diff --git a/.gitattributes b/.gitattributes index d45620912..77332e539 100644 --- a/.gitattributes +++ b/.gitattributes @@ -16,3 +16,5 @@ #Appveyor /appveyor.yml -crlf -whitespace # Other +*.c text=auto +*.h text=auto diff --git a/libs/libopenmpt/bin/x86/libopenmpt.dll b/libs/libopenmpt/bin/x86/libopenmpt.dll index 7fec7d99e..479114bcd 100644 Binary files a/libs/libopenmpt/bin/x86/libopenmpt.dll and b/libs/libopenmpt/bin/x86/libopenmpt.dll differ diff --git a/libs/libopenmpt/bin/x86/mingw/libopenmpt.dll b/libs/libopenmpt/bin/x86/mingw/libopenmpt.dll deleted file mode 100644 index 945b475e6..000000000 Binary files a/libs/libopenmpt/bin/x86/mingw/libopenmpt.dll and /dev/null differ diff --git a/libs/libopenmpt/bin/x86/openmpt-mpg123.dll b/libs/libopenmpt/bin/x86/openmpt-mpg123.dll index 54c4b9fce..60bc3b958 100644 Binary files a/libs/libopenmpt/bin/x86/openmpt-mpg123.dll and b/libs/libopenmpt/bin/x86/openmpt-mpg123.dll differ diff --git a/libs/libopenmpt/bin/x86/openmpt-ogg.dll b/libs/libopenmpt/bin/x86/openmpt-ogg.dll index f5e087421..32df3461a 100644 Binary files a/libs/libopenmpt/bin/x86/openmpt-ogg.dll and b/libs/libopenmpt/bin/x86/openmpt-ogg.dll differ diff --git a/libs/libopenmpt/bin/x86/openmpt-vorbis.dll b/libs/libopenmpt/bin/x86/openmpt-vorbis.dll index 0653f6f81..bb154d167 100644 Binary files a/libs/libopenmpt/bin/x86/openmpt-vorbis.dll and b/libs/libopenmpt/bin/x86/openmpt-vorbis.dll differ diff --git a/libs/libopenmpt/bin/x86/openmpt-zlib.dll b/libs/libopenmpt/bin/x86/openmpt-zlib.dll index 01ba3ec89..948bc80f5 100644 Binary files a/libs/libopenmpt/bin/x86/openmpt-zlib.dll and b/libs/libopenmpt/bin/x86/openmpt-zlib.dll differ diff --git a/libs/libopenmpt/bin/x86_64/libopenmpt.dll b/libs/libopenmpt/bin/x86_64/libopenmpt.dll index 1cdb0c567..05c4237a7 100644 Binary files a/libs/libopenmpt/bin/x86_64/libopenmpt.dll and b/libs/libopenmpt/bin/x86_64/libopenmpt.dll differ diff --git a/libs/libopenmpt/bin/x86_64/openmpt-mpg123.dll b/libs/libopenmpt/bin/x86_64/openmpt-mpg123.dll index 3ef350e0e..c917604df 100644 Binary files a/libs/libopenmpt/bin/x86_64/openmpt-mpg123.dll and b/libs/libopenmpt/bin/x86_64/openmpt-mpg123.dll differ diff --git a/libs/libopenmpt/bin/x86_64/openmpt-ogg.dll b/libs/libopenmpt/bin/x86_64/openmpt-ogg.dll index bc1f42cf3..de503b03f 100644 Binary files a/libs/libopenmpt/bin/x86_64/openmpt-ogg.dll and b/libs/libopenmpt/bin/x86_64/openmpt-ogg.dll differ diff --git a/libs/libopenmpt/bin/x86_64/openmpt-vorbis.dll b/libs/libopenmpt/bin/x86_64/openmpt-vorbis.dll index 66b7be774..5f21dee26 100644 Binary files a/libs/libopenmpt/bin/x86_64/openmpt-vorbis.dll and b/libs/libopenmpt/bin/x86_64/openmpt-vorbis.dll differ diff --git a/libs/libopenmpt/bin/x86_64/openmpt-zlib.dll b/libs/libopenmpt/bin/x86_64/openmpt-zlib.dll index cd738be6b..1ae938ff7 100644 Binary files a/libs/libopenmpt/bin/x86_64/openmpt-zlib.dll and b/libs/libopenmpt/bin/x86_64/openmpt-zlib.dll differ diff --git a/libs/libopenmpt/inc/libopenmpt/libopenmpt.hpp b/libs/libopenmpt/inc/libopenmpt/libopenmpt.hpp index b35f42066..69784e8ea 100644 --- a/libs/libopenmpt/inc/libopenmpt/libopenmpt.hpp +++ b/libs/libopenmpt/inc/libopenmpt/libopenmpt.hpp @@ -1,1195 +1,1195 @@ -/* - * libopenmpt.hpp - * -------------- - * Purpose: libopenmpt public c++ interface - * Notes : (currently none) - * Authors: OpenMPT Devs - * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. - */ - -#ifndef LIBOPENMPT_HPP -#define LIBOPENMPT_HPP - -#include "libopenmpt_config.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -/*! - * \page libopenmpt_cpp_overview C++ API - * - * \section libopenmpt_cpp_error Error Handling - * - * libopenmpt C++ uses C++ exception handling for errror reporting. - * - * Unless otherwise noted, any libopenmpt function may throw exceptions and - * all exceptions thrown by libopenmpt itself are derived from - * openmpt::exception. - * In addition, any libopenmpt function may also throw any exception specified - * by the C++ language and C++ standard library. These are all derived from - * std::exception. - * - * \section libopenmpt_cpp_strings Strings - * - * - All strings returned from libopenmpt are encoded in UTF-8. - * - All strings passed to libopenmpt should also be encoded in UTF-8. - * Behaviour in case of invalid UTF-8 is unspecified. - * - libopenmpt does not enforce or expect any particular Unicode - * normalization form. - * - * \section libopenmpt_cpp_fileio File I/O - * - * libopenmpt can use 3 different strategies for file I/O. - * - * - openmpt::module::module() with any kind of memory buffer as parameter will - * load the module from the provided memory buffer, which will require loading - * all data upfront by the library - * caller. - * - openmpt::module::module() with a seekable std::istream as parameter will - * load the module via the stream interface. libopenmpt will not implement an - * additional buffering layer in this case whih means the callbacks are assumed - * to be performant even with small i/o sizes. - * - openmpt::module::module() with an unseekable std::istream as parameter - * will load the module via the stream interface. libopempt will make an - * internal copy as it goes along, and sometimes have to pre-cache the whole - * file in case it needs to know the complete file size. This strategy is - * intended to be used if the file is located on a high latency network. - * - * | constructor | speed | memory consumption | - * | ----------------: | :----: | :----------------: | - * | memory buffer |

fast

|

medium

| - * | seekable stream |

slow

|

low

| - * | unseekable stream |

medium

|

high

| - * - * In all cases, the data or stream passed to the constructor is no longer - * needed after the openmpt::module has been constructed and can be destroyed - * by the caller. - * - * \section libopenmpt_cpp_outputformat Output Format - * - * libopenmpt supports a wide range of PCM output formats: - * [8000..192000]/[mono|stereo|quad]/[f32|i16]. - * - * Unless you have some very specific requirements demanding a particular aspect - * of the output format, you should always prefer 48000/stereo/f32 as the - * libopenmpt PCM format. - * - * - Please prefer 48000Hz unless the user explicitly demands something else. - * Practically all audio equipment and file formats use 48000Hz nowadays. - * - Practically all module formats are made for stereo output. Mono will not - * give you any measurable speed improvements and can trivially be obtained from - * the stereo output anyway. Quad is not expected by almost all modules and even - * if they do use surround effects, they expect the effects to be mixed to - * stereo. - * - Floating point output provides headroom instead of hard clipping if the - * module is louder than 0dBFs, will give you a better signal-to-noise ratio - * than int16 output, and avoid the need to apply an additional dithering to the - * output by libopenmpt. Unless your platform has no floating point unit at all, - * floating point will thus also be slightly faster. - * - * \section libopenmpt_cpp_threads libopenmpt in multi-threaded environments - * - * - libopenmpt is thread-aware. - * - Individual libopenmpt objects are not thread-safe. - * - libopenmpt itself does not spawn any user-visible threads but may spawn - * threads for internal use. - * - You must ensure to only ever access a particular libopenmpt object via - * non-const member functions from a single thread at a time. - * - You may access a particular libopenmpt object concurrently from different - * threads when using only const member functions from all threads. - * - Consecutive accesses can happen from different threads. - * - Different objects can be accessed concurrently from different threads. - * - * \section libopenmpt-cpp-windows Windows support - * - * Using the libopenmpt C++ API when libopenmpt is compiled as a DLL on Windows - * requires `#define LIBOPENMPT_USE_DLL` (or some equivalent build system - * configuration) before `#include ` in order to - * correctly import the symbols from the DLL. - * - * \section libopenmpt-cpp-detailed Detailed documentation - * - * \ref libopenmpt_cpp - * - * \section libopenmpt_cpp_examples Example - * - * \include libopenmpt_example_cxx.cpp - * - */ - -/*! \defgroup libopenmpt_cpp libopenmpt C++ */ - -namespace openmpt { - -/*! \addtogroup libopenmpt_cpp - @{ -*/ - -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable:4275) -#endif -//! libopenmpt exception base class -/*! - Base class used for all exceptions that are thrown by libopenmpt itself. Libopenmpt may additionally throw any exception thrown by the standard library which are all derived from std::exception. - \sa \ref libopenmpt_cpp_error -*/ -class LIBOPENMPT_CXX_API_CLASS exception : public std::exception { -private: - char * text; -public: - LIBOPENMPT_CXX_API_MEMBER exception( const std::string & text ) noexcept; - LIBOPENMPT_CXX_API_MEMBER exception( const exception & other ) noexcept; - LIBOPENMPT_CXX_API_MEMBER exception( exception && other ) noexcept; - LIBOPENMPT_CXX_API_MEMBER exception & operator = ( const exception & other ) noexcept; - LIBOPENMPT_CXX_API_MEMBER exception & operator = ( exception && other ) noexcept; - LIBOPENMPT_CXX_API_MEMBER virtual ~exception() noexcept; - LIBOPENMPT_CXX_API_MEMBER const char * what() const noexcept override; -}; // class exception -#if defined(_MSC_VER) -#pragma warning(pop) -#endif - -//! Get the libopenmpt version number -/*! - Returns the libopenmpt version number. - \return The value represents (major << 24 + minor << 16 + patch << 0). - \remarks libopenmpt < 0.3.0-pre used the following scheme: (major << 24 + minor << 16 + revision). -*/ -LIBOPENMPT_CXX_API std::uint32_t get_library_version(); - -//! Get the core version number -/*! - Return the OpenMPT core version number. - \return The value represents (majormajor << 24 + major << 16 + minor << 8 + minorminor). -*/ -LIBOPENMPT_CXX_API std::uint32_t get_core_version(); - -namespace string { - -//! Return a verbose library version string from openmpt::string::get(). \deprecated Please use `"library_version"` directly. -static const char library_version LIBOPENMPT_ATTR_DEPRECATED [] = "library_version"; -//! Return a verbose library features string from openmpt::string::get(). \deprecated Please use `"library_features"` directly. -static const char library_features LIBOPENMPT_ATTR_DEPRECATED [] = "library_features"; -//! Return a verbose OpenMPT core version string from openmpt::string::get(). \deprecated Please use `"core_version"` directly. -static const char core_version LIBOPENMPT_ATTR_DEPRECATED [] = "core_version"; -//! Return information about the current build (e.g. the build date or compiler used) from openmpt::string::get(). \deprecated Please use `"build"` directly. -static const char build LIBOPENMPT_ATTR_DEPRECATED [] = "build"; -//! Return all contributors from openmpt::string::get(). \deprecated Please use `"credits"` directly. -static const char credits LIBOPENMPT_ATTR_DEPRECATED [] = "credits"; -//! Return contact information about libopenmpt from openmpt::string::get(). \deprecated Please use `"contact"` directly. -static const char contact LIBOPENMPT_ATTR_DEPRECATED [] = "contact"; -//! Return the libopenmpt license from openmpt::string::get(). \deprecated Please use `"license"` directly. -static const char license LIBOPENMPT_ATTR_DEPRECATED [] = "license"; - -//! Get library related metadata. -/*! - \param key Key to query. - Possible keys are: - - "library_version": verbose library version string - - "library_version_major": libopenmpt major version number - - "library_version_minor": libopenmpt minor version number - - "library_version_patch": libopenmpt patch version number - - "library_version_prerel": libopenmpt pre-release version string - - "library_version_is_release": "1" if the version is an officially released version - - "library_features": verbose library features string - - "core_version": verbose OpenMPT core version string - - "source_url": original source code URL - - "source_date": original source code date - - "source_revision": original source code revision - - "source_is_modified": "1" if the original source has been modified - - "source_has_mixed_revisions": "1" if the original source has been compiled from different various revision - - "source_is_package": "1" if the original source has been obtained from a source pacakge instead of source code version control - - "build": information about the current build (e.g. the build date or compiler used) - - "build_compiler": information about the compiler used to build libopenmpt - - "credits": all contributors - - "contact": contact information about libopenmpt - - "license": the libopenmpt license - - "url": libopenmpt website URL - - "support_forum_url": libopenmpt support and discussions forum URL - - "bugtracker_url": libopenmpt bug and issue tracker URL - - \return A (possibly multi-line) string containing the queried information. If no information is available, the string is empty. -*/ -LIBOPENMPT_CXX_API std::string get( const std::string & key ); - -} // namespace string - -//! Get a list of supported file extensions -/*! - \return The list of extensions supported by this libopenmpt build. The extensions are returned lower-case without a leading dot. -*/ -LIBOPENMPT_CXX_API std::vector get_supported_extensions(); - -//! Query whether a file extension is supported -/*! - \param extension file extension to query without a leading dot. The case is ignored. - \return true if the extension is supported by libopenmpt, false otherwise. - \deprecated Please use openmpt::is_extension_supported2(). -*/ -LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API bool is_extension_supported( const std::string & extension ); -//! Query whether a file extension is supported -/*! - \param extension file extension to query without a leading dot. The case is ignored. - \return true if the extension is supported by libopenmpt, false otherwise. - \since 0.5.0 -*/ -LIBOPENMPT_CXX_API bool is_extension_supported2( std::string_view extension ); - -//! Roughly scan the input stream to find out whether libopenmpt might be able to open it -/*! - \param stream Input stream to scan. - \param effort Effort to make when validating stream. Effort 0.0 does not even look at stream at all and effort 1.0 completely loads the file from stream. A lower effort requires less data to be loaded but only gives a rough estimate answer. Use an effort of 0.25 to only verify the header data of the module file. - \param log Log where warning and errors are written. - \return Probability between 0.0 and 1.0. - \remarks openmpt::probe_file_header() provides a simpler and faster interface that fits almost all use cases better. It is recommended to use openmpt::probe_file_header() instead of openmpt::could_open_probability(). - \remarks openmpt::could_open_probability() can return any value between 0.0 and 1.0. Only 0.0 and 1.0 are definitive answers, all values in between are just estimates. In general, any return value >0.0 means that you should try loading the file, and any value below 1.0 means that loading may fail. If you want a threshold above which you can be reasonably sure that libopenmpt will be able to load the file, use >=0.5. If you see the need for a threshold below which you could reasonably outright reject a file, use <0.25 (Note: Such a threshold for rejecting on the lower end is not recommended, but may be required for better integration into some other framework's probe scoring.). - \remarks openmpt::could_open_probability() expects the complete file data to be eventually available to it, even if it is asked to just parse the header. Verification will be unreliable (both false positives and false negatives), if you pretend that the file is just some few bytes of initial data threshold in size. In order to really just access the first bytes of a file, check in your std::istream implementation whether data or seeking is requested beyond your initial data threshold, and in that case, return an error. openmpt::could_open_probability() will treat this as any other I/O error and return 0.0. You must not expect the correct result in this case. You instead must remember that it asked for more data than you currently want to provide to it and treat this situation as if openmpt::could_open_probability() returned 0.5. - \sa \ref libopenmpt_c_fileio - \sa openmpt::probe_file_header() - \since 0.3.0 -*/ -LIBOPENMPT_CXX_API double could_open_probability( std::istream & stream, double effort = 1.0, std::ostream & log = std::clog ); - -//! Roughly scan the input stream to find out whether libopenmpt might be able to open it -/*! - \deprecated Please use openmpt::could_open_probability(). -*/ -LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API double could_open_propability( std::istream & stream, double effort = 1.0, std::ostream & log = std::clog ); - -//! Get recommended header size for successfull format probing -/*! - \sa openmpt::probe_file_header() - \since 0.3.0 -*/ -LIBOPENMPT_CXX_API std::size_t probe_file_header_get_recommended_size(); - -//! Probe for module formats in openmpt::probe_file_header(). \since 0.3.0 \deprecated Please use openmpt::probe_file_header_flags_modules2. -static const std::uint64_t probe_file_header_flags_modules LIBOPENMPT_ATTR_DEPRECATED = 0x1ull; - -//! Probe for module-specific container formats in openmpt::probe_file_header(). \since 0.3.0 \deprecated Please use openmpt::probe_file_header_flags_containers2. -static const std::uint64_t probe_file_header_flags_containers LIBOPENMPT_ATTR_DEPRECATED = 0x2ull; - -//! Probe for the default set of formats in openmpt::probe_file_header(). \since 0.3.0 \deprecated Please use openmpt::probe_file_header_flags_default2. -static const std::uint64_t probe_file_header_flags_default LIBOPENMPT_ATTR_DEPRECATED = 0x1ull | 0x2ull; - -//! Probe for no formats in openmpt::probe_file_header(). \since 0.3.0 \deprecated Please use openmpt::probe_file_header_flags_none2. -static const std::uint64_t probe_file_header_flags_none LIBOPENMPT_ATTR_DEPRECATED = 0x0ull; - -//! Possible values for openmpt::probe_file_header() flags parameter. \since 0.6.0 -enum probe_file_header_flags : std::uint64_t { - //! Probe for module formats in openmpt::probe_file_header(). \since 0.6.0 - probe_file_header_flags_modules2 = 0x1ull, - //! Probe for module-specific container formats in openmpt::probe_file_header(). \since 0.6.0 - probe_file_header_flags_containers2 = 0x2ull, - //! Probe for the default set of formats in openmpt::probe_file_header(). \since 0.6.0 - probe_file_header_flags_default2 = probe_file_header_flags_modules2 | probe_file_header_flags_containers2, - //! Probe for no formats in openmpt::probe_file_header(). \since 0.6.0 - probe_file_header_flags_none2 = 0x0ull -}; - -//! Possible return values for openmpt::probe_file_header(). \since 0.3.0 -enum probe_file_header_result { - //! The file will most likely be supported by libopenmpt. \since 0.3.0 - probe_file_header_result_success = 1, - //! The file is not supported by libopenmpt. \since 0.3.0 - probe_file_header_result_failure = 0, - //! An answer could not be determined with the amount of data provided. \since 0.3.0 - probe_file_header_result_wantmoredata = -1 -}; - -//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it -/*! - \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. - \param data Beginning of the file data. - \param size Size of the beginning of the file data. - \param filesize Full size of the file data on disk. - \remarks It is recommended to provide openmpt::probe_file_header_get_recommended_size() bytes of data for data and size. If the file is smaller, only provide the filesize amount and set size and filesize to the file's size. - \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. - \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. - \retval probe_file_header_result_failure The file is not supported by libopenmpt. - \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. - \sa openmpt::probe_file_header_get_recommended_size() - \sa openmpt::could_open_probability() - \since 0.5.0 -*/ -LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, const std::byte * data, std::size_t size, std::uint64_t filesize ); -//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it -/*! - \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. - \param data Beginning of the file data. - \param size Size of the beginning of the file data. - \param filesize Full size of the file data on disk. - \remarks It is recommended to provide openmpt::probe_file_header_get_recommended_size() bytes of data for data and size. If the file is smaller, only provide the filesize amount and set size and filesize to the file's size. - \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. - \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. - \retval probe_file_header_result_failure The file is not supported by libopenmpt. - \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. - \sa openmpt::probe_file_header_get_recommended_size() - \sa openmpt::could_open_probability() - \since 0.3.0 -*/ -LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, const std::uint8_t * data, std::size_t size, std::uint64_t filesize ); - -//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it -/*! - \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. - \param data Beginning of the file data. - \param size Size of the beginning of the file data. - \remarks It is recommended to use the overload of this function that also takes the filesize as parameter if at all possile. libopenmpt can provide more accurate answers if the filesize is known. - \remarks It is recommended to provide openmpt::probe_file_header_get_recommended_size() bytes of data for data and size. If the file is smaller, only provide the filesize amount and set size to the file's size. - \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. - \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. - \retval probe_file_header_result_failure The file is not supported by libopenmpt. - \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. - \sa openmpt::probe_file_header_get_recommended_size() - \sa openmpt::could_open_probability() - \since 0.5.0 -*/ -LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, const std::byte * data, std::size_t size ); -//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it -/*! - \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. - \param data Beginning of the file data. - \param size Size of the beginning of the file data. - \remarks It is recommended to use the overload of this function that also takes the filesize as parameter if at all possile. libopenmpt can provide more accurate answers if the filesize is known. - \remarks It is recommended to provide openmpt::probe_file_header_get_recommended_size() bytes of data for data and size. If the file is smaller, only provide the filesize amount and set size to the file's size. - \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. - \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. - \retval probe_file_header_result_failure The file is not supported by libopenmpt. - \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. - \sa openmpt::probe_file_header_get_recommended_size() - \sa openmpt::could_open_probability() - \since 0.3.0 -*/ -LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, const std::uint8_t * data, std::size_t size ); - -//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it -/*! - \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. - \param stream Input stream to scan. - \remarks stream is left in an unspecified state when this function returns. - \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. - \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. - \retval probe_file_header_result_failure The file is not supported by libopenmpt. - \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. - \sa openmpt::probe_file_header_get_recommended_size() - \sa openmpt::could_open_probability() - \since 0.3.0 -*/ -LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, std::istream & stream ); - -class module_impl; - -class module_ext; - -namespace detail { - -typedef std::map< std::string, std::string > initial_ctls_map; - -} // namespace detail - -class LIBOPENMPT_CXX_API_CLASS module { - - friend class module_ext; - -public: - - //! Parameter index to use with openmpt::module::get_render_param and openmpt::module::set_render_param - enum render_param { - //! Master Gain - /*! - The related value represents a relative gain in milliBel.\n - The default value is 0.\n - The supported value range is unlimited.\n - */ - RENDER_MASTERGAIN_MILLIBEL = 1, - //! Stereo Separation - /*! - The related value represents the stereo separation generated by the libopenmpt mixer in percent.\n - The default value is 100.\n - The supported value range is [0,200].\n - */ - RENDER_STEREOSEPARATION_PERCENT = 2, - //! Interpolation Filter - /*! - The related value represents the interpolation filter length used by the libopenmpt mixer.\n - The default value is 0, which indicates a recommended default value.\n - The supported value range is [0,inf). Values greater than the implementation limit are clamped to the maximum supported value.\n - Currently supported values: - - 0: internal default - - 1: no interpolation (zero order hold) - - 2: linear interpolation - - 4: cubic interpolation - - 8: windowed sinc with 8 taps - */ - RENDER_INTERPOLATIONFILTER_LENGTH = 3, - //! Volume Ramping Strength - /*! - The related value represents the amount of volume ramping done by the libopenmpt mixer.\n - The default value is -1, which indicates a recommended default value.\n - The meaningful value range is [-1..10].\n - A value of 0 completely disables volume ramping. This might cause clicks in sound output.\n - Higher values imply slower/softer volume ramps. - */ - RENDER_VOLUMERAMPING_STRENGTH = 4 - }; - - //! Parameter index to use with openmpt::module::get_pattern_row_channel_command, openmpt::module::format_pattern_row_channel_command and openmpt::module::highlight_pattern_row_channel_command - enum command_index { - command_note = 0, - command_instrument = 1, - command_volumeffect = 2, - command_effect = 3, - command_volume = 4, - command_parameter = 5 - }; - -private: - module_impl * impl; -private: - // non-copyable - module( const module & ); - void operator = ( const module & ); -private: - // for module_ext - module(); - void set_impl( module_impl * i ); -public: - //! Construct an openmpt::module - /*! - \param stream Input stream from which the module is loaded. After the constructor has finished successfully, the input position of stream is set to the byte after the last byte that has been read. If the constructor fails, the state of the input position of stream is undefined. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see \ref openmpt::module::get_ctls and openmpt::module::ctl_set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - */ - LIBOPENMPT_CXX_API_MEMBER module( std::istream & stream, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param data Data to load the module from. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see \ref openmpt::module::get_ctls and openmpt::module::ctl_set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER module( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param beg Begin of data to load the module from. - \param end End of data to load the module from. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see \ref openmpt::module::get_ctls and openmpt::module::ctl_set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER module( const std::byte * beg, const std::byte * end, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param data Data to load the module from. - \param size Amount of data available. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see openmpt::module::get_ctls. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER module( const std::byte * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param data Data to load the module from. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see \ref openmpt::module::get_ctls and openmpt::module::ctl_set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - */ - LIBOPENMPT_CXX_API_MEMBER module( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param beg Begin of data to load the module from. - \param end End of data to load the module from. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see openmpt::module::get_ctls. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - */ - LIBOPENMPT_CXX_API_MEMBER module( const std::uint8_t * beg, const std::uint8_t * end, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param data Data to load the module from. - \param size Amount of data available. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see openmpt::module::get_ctls. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - */ - LIBOPENMPT_CXX_API_MEMBER module( const std::uint8_t * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param data Data to load the module from. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see openmpt::module::get_ctls. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - */ - LIBOPENMPT_CXX_API_MEMBER module( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param beg Begin of data to load the module from. - \param end End of data to load the module from. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see openmpt::module::get_ctls. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - */ - LIBOPENMPT_CXX_API_MEMBER module( const char * beg, const char * end, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param data Data to load the module from. - \param size Amount of data available. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see openmpt::module::get_ctls. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - */ - LIBOPENMPT_CXX_API_MEMBER module( const char * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - /*! - \param data Data to load the module from. - \param size Amount of data available. - \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. - \param ctls A map of initial ctl values, see openmpt::module::get_ctls. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. - \remarks The input data can be discarded after an openmpt::module has been constructed successfully. - \sa \ref libopenmpt_cpp_fileio - */ - LIBOPENMPT_CXX_API_MEMBER module( const void * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER virtual ~module(); -public: - - //! Select a sub-song from a multi-song module - /*! - \param subsong Index of the sub-song. -1 plays all sub-songs consecutively. - \throws openmpt::exception Throws an exception derived from openmpt::exception if sub-song is not in range [-1,openmpt::module::get_num_subsongs()[ - \sa openmpt::module::get_num_subsongs, openmpt::module::get_selected_subsong, openmpt::module::get_subsong_names - \remarks Whether subsong -1 (all subsongs consecutively), subsong 0 or some other subsong is selected by default, is an implementation detail and subject to change. If you do not want to care about subsongs, it is recommended to just not call openmpt::module::select_subsong() at all. - */ - LIBOPENMPT_CXX_API_MEMBER void select_subsong( std::int32_t subsong ); - //! Get currently selected sub-song from a multi-song module - /*! - \return Currently selected sub-song. -1 for all subsongs consecutively, 0 or greater for the current sub-song index. - \sa openmpt::module::get_num_subsongs, openmpt::module::select_subsong, openmpt::module::get_subsong_names - \since 0.3.0 - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_selected_subsong() const; - //! Set Repeat Count - /*! - \param repeat_count Repeat Count - - -1: repeat forever - - 0: play once, repeat zero times (the default) - - n>0: play once and repeat n times after that - \sa openmpt::module::get_repeat_count - */ - LIBOPENMPT_CXX_API_MEMBER void set_repeat_count( std::int32_t repeat_count ); - //! Get Repeat Count - /*! - \return Repeat Count - - -1: repeat forever - - 0: play once, repeat zero times (the default) - - n>0: play once and repeat n times after that - \sa openmpt::module::set_repeat_count - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_repeat_count() const; - - //! Get approximate song duration - /*! - \return Approximate duration of current sub-song in seconds. - \remarks The function may return infinity if the pattern data is too complex to evaluate. - */ - LIBOPENMPT_CXX_API_MEMBER double get_duration_seconds() const; - - //! Set approximate current song position - /*! - \param seconds Seconds to seek to. If seconds is out of range, the position gets set to song start or end respectively. - \return Approximate new song position in seconds. - \sa openmpt::module::get_position_seconds - */ - LIBOPENMPT_CXX_API_MEMBER double set_position_seconds( double seconds ); - //! Get current song position - /*! - \return Current song position in seconds. - \sa openmpt::module::set_position_seconds - */ - LIBOPENMPT_CXX_API_MEMBER double get_position_seconds() const; - - //! Set approximate current song position - /*! - If order or row are out of range, to position is not modified and the current position is returned. - \param order Pattern order number to seek to. - \param row Pattern row number to seek to. - \return Approximate new song position in seconds. - \sa openmpt::module::set_position_seconds - \sa openmpt::module::get_position_seconds - */ - LIBOPENMPT_CXX_API_MEMBER double set_position_order_row( std::int32_t order, std::int32_t row ); - - //! Get render parameter - /*! - \param param Parameter to query. See openmpt::module::render_param. - \return The current value of the parameter. - \throws openmpt::exception Throws an exception derived from openmpt::exception if param is invalid. - \sa openmpt::module::render_param - \sa openmpt::module::set_render_param - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_render_param( int param ) const; - //! Set render parameter - /*! - \param param Parameter to set. See openmpt::module::render_param. - \param value The value to set param to. - \throws openmpt::exception Throws an exception derived from openmpt::exception if param is invalid or value is out of range. - \sa openmpt::module::render_param - \sa openmpt::module::get_render_param - */ - LIBOPENMPT_CXX_API_MEMBER void set_render_param( int param, std::int32_t value ); - - /*@{*/ - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param mono Pointer to a buffer of at least count elements that receives the mono/center output. - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, std::int16_t * mono ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param left Pointer to a buffer of at least count elements that receives the left output. - \param right Pointer to a buffer of at least count elements that receives the right output. - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, std::int16_t * left, std::int16_t * right ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param left Pointer to a buffer of at least count elements that receives the left output. - \param right Pointer to a buffer of at least count elements that receives the right output. - \param rear_left Pointer to a buffer of at least count elements that receives the rear left output. - \param rear_right Pointer to a buffer of at least count elements that receives the rear right output. - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, std::int16_t * left, std::int16_t * right, std::int16_t * rear_left, std::int16_t * rear_right ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param mono Pointer to a buffer of at least count elements that receives the mono/center output. - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, float * mono ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param left Pointer to a buffer of at least count elements that receives the left output. - \param right Pointer to a buffer of at least count elements that receives the right output. - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, float * left, float * right ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param left Pointer to a buffer of at least count elements that receives the left output. - \param right Pointer to a buffer of at least count elements that receives the right output. - \param rear_left Pointer to a buffer of at least count elements that receives the rear left output. - \param rear_right Pointer to a buffer of at least count elements that receives the rear right output. - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, float * left, float * right, float * rear_left, float * rear_right ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param interleaved_stereo Pointer to a buffer of at least count*2 elements that receives the interleaved stereo output in the order (L,R). - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read_interleaved_stereo( std::int32_t samplerate, std::size_t count, std::int16_t * interleaved_stereo ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param interleaved_quad Pointer to a buffer of at least count*4 elements that receives the interleaved quad surround output in the order (L,R,RL,RR). - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read_interleaved_quad( std::int32_t samplerate, std::size_t count, std::int16_t * interleaved_quad ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param interleaved_stereo Pointer to a buffer of at least count*2 elements that receives the interleaved stereo output in the order (L,R). - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read_interleaved_stereo( std::int32_t samplerate, std::size_t count, float * interleaved_stereo ); - //! Render audio data - /*! - \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. - \param count Number of audio frames to render per channel. - \param interleaved_quad Pointer to a buffer of at least count*4 elements that receives the interleaved quad surround output in the order (L,R,RL,RR). - \return The number of frames actually rendered. - \retval 0 The end of song has been reached. - \remarks The output buffers are only written to up to the returned number of elements. - \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. - \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. - \sa \ref libopenmpt_cpp_outputformat - */ - LIBOPENMPT_CXX_API_MEMBER std::size_t read_interleaved_quad( std::int32_t samplerate, std::size_t count, float * interleaved_quad ); - /*@}*/ - - //! Get the list of supported metadata item keys - /*! - \return Metadata item keys supported by openmpt::module::get_metadata - \sa openmpt::module::get_metadata - */ - LIBOPENMPT_CXX_API_MEMBER std::vector get_metadata_keys() const; - //! Get a metadata item value - /*! - \param key Metadata item key to query. Use openmpt::module::get_metadata_keys to check for available keys. - Possible keys are: - - type: Module format extension (e.g. it) or another similar identifier for modules formats that typically do not use a file extension - - type_long: Format name associated with the module format (e.g. Impulse Tracker) - - originaltype: Module format extension (e.g. it) of the original module in case the actual type is a converted format (e.g. mo3 or gdm) - - originaltype_long: Format name associated with the module format (e.g. Impulse Tracker) of the original module in case the actual type is a converted format (e.g. mo3 or gdm) - - container: Container format the module file is embedded in, if any (e.g. umx) - - container_long: Full container name if the module is embedded in a container (e.g. Unreal Music) - - tracker: Tracker that was (most likely) used to save the module file, if known - - artist: Author of the module - - title: Module title - - date: Date the module was last saved, in ISO-8601 format. - - message: Song message. If the song message is empty or the module format does not support song messages, a list of instrument and sample names is returned instead. - - message_raw: Song message. If the song message is empty or the module format does not support song messages, an empty string is returned. - - warnings: A list of warnings that were generated while loading the module. - \return The associated value for key. - \sa openmpt::module::get_metadata_keys - */ - LIBOPENMPT_CXX_API_MEMBER std::string get_metadata( const std::string & key ) const; - - //! Get the current estimated beats per minute (BPM). - /*! - \remarks Many module formats lack time signature metadata. It is common that this estimate is off by a factor of two, but other multipliers are also possible. - \remarks Due to the nature of how module tempo works, the estimate may change slightly after switching libopenmpt's output to a different sample rate. - \return The current estimated BPM. - */ - LIBOPENMPT_CXX_API_MEMBER double get_current_estimated_bpm() const; - //! Get the current speed - /*! - \return The current speed in ticks per row. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_speed() const; - //! Get the current tempo - /*! - \return The current tempo in tracker units. The exact meaning of this value depends on the tempo mode being used. - \deprecated Please use openmpt::module::get_current_tempo2(). - */ - LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_tempo() const; - //! Get the current tempo - /*! - \return The current tempo in tracker units. The exact meaning of this value depends on the tempo mode being used. - \since 0.7.0 - */ - LIBOPENMPT_CXX_API_MEMBER double get_current_tempo2() const; - //! Get the current order - /*! - \return The current order at which the module is being played back. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_order() const; - //! Get the current pattern - /*! - \return The current pattern that is being played. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_pattern() const; - //! Get the current row - /*! - \return The current row at which the current pattern is being played. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_row() const; - //! Get the current amount of playing channels. - /*! - \return The amount of sample channels that are currently being rendered. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_playing_channels() const; - - //! Get an approximate indication of the channel volume. - /*! - \param channel The channel whose volume should be retrieved. - \return The approximate channel volume. - \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. - */ - LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_mono( std::int32_t channel ) const; - //! Get an approximate indication of the channel volume on the front-left speaker. - /*! - \param channel The channel whose volume should be retrieved. - \return The approximate channel volume. - \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. - */ - LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_left( std::int32_t channel ) const; - //! Get an approximate indication of the channel volume on the front-right speaker. - /*! - \param channel The channel whose volume should be retrieved. - \return The approximate channel volume. - \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. - */ - LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_right( std::int32_t channel ) const; - //! Get an approximate indication of the channel volume on the rear-left speaker. - /*! - \param channel The channel whose volume should be retrieved. - \return The approximate channel volume. - \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. - */ - LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_rear_left( std::int32_t channel ) const; - //! Get an approximate indication of the channel volume on the rear-right speaker. - /*! - \param channel The channel whose volume should be retrieved. - \return The approximate channel volume. - \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. - */ - LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_rear_right( std::int32_t channel ) const; - - //! Get the number of sub-songs - /*! - \return The number of sub-songs in the module. This includes any "hidden" songs (songs that share the same sequence, but start at different order indices) and "normal" sub-songs or "sequences" (if the format supports them). - \sa openmpt::module::get_subsong_names, openmpt::module::select_subsong, openmpt::module::get_selected_subsong - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_subsongs() const; - //! Get the number of pattern channels - /*! - \return The number of pattern channels in the module. Not all channels do necessarily contain data. - \remarks The number of pattern channels is completely independent of the number of output channels. libopenmpt can render modules in mono, stereo or quad surround, but the choice of which of the three modes to use must not be made based on the return value of this function, which may be any positive integer amount. Only use this function for informational purposes. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_channels() const; - //! Get the number of orders - /*! - \return The number of orders in the current sequence of the module. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_orders() const; - //! Get the number of patterns - /*! - \return The number of distinct patterns in the module. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_patterns() const; - //! Get the number of instruments - /*! - \return The number of instrument slots in the module. Instruments are a layer on top of samples, and are not supported by all module formats. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_instruments() const; - //! Get the number of samples - /*! - \return The number of sample slots in the module. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_samples() const; - - //! Get a list of sub-song names - /*! - \return All sub-song names. - \sa openmpt::module::get_num_subsongs, openmpt::module::select_subsong, openmpt::module::get_selected_subsong - */ - LIBOPENMPT_CXX_API_MEMBER std::vector get_subsong_names() const; - //! Get a list of channel names - /*! - \return All channel names. - \sa openmpt::module::get_num_channels - */ - LIBOPENMPT_CXX_API_MEMBER std::vector get_channel_names() const; - //! Get a list of order names - /*! - \return All order names. - \sa openmpt::module::get_num_orders - */ - LIBOPENMPT_CXX_API_MEMBER std::vector get_order_names() const; - //! Get a list of pattern names - /*! - \return All pattern names. - \sa openmpt::module::get_num_patterns - */ - LIBOPENMPT_CXX_API_MEMBER std::vector get_pattern_names() const; - //! Get a list of instrument names - /*! - \return All instrument names. - \sa openmpt::module::get_num_instruments - */ - LIBOPENMPT_CXX_API_MEMBER std::vector get_instrument_names() const; - //! Get a list of sample names - /*! - \return All sample names. - \sa openmpt::module::get_num_samples - */ - LIBOPENMPT_CXX_API_MEMBER std::vector get_sample_names() const; - - //! Get pattern at order position - /*! - \param order The order item whose pattern index should be retrieved. - \return The pattern index found at the given order position of the current sequence. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_order_pattern( std::int32_t order ) const; - - //! Get the number of rows in a pattern - /*! - \param pattern The pattern whose row count should be retrieved. - \return The number of rows in the given pattern. If the pattern does not exist, 0 is returned. - */ - LIBOPENMPT_CXX_API_MEMBER std::int32_t get_pattern_num_rows( std::int32_t pattern ) const; - - //! Get raw pattern content - /*! - \param pattern The pattern whose data should be retrieved. - \param row The row from which the data should be retrieved. - \param channel The channel from which the data should be retrieved. - \param command The cell index at which the data should be retrieved. See openmpt::module::command_index - \return The internal, raw pattern data at the given pattern position. - */ - LIBOPENMPT_CXX_API_MEMBER std::uint8_t get_pattern_row_channel_command( std::int32_t pattern, std::int32_t row, std::int32_t channel, int command ) const; - - //! Get formatted (human-readable) pattern content - /*! - \param pattern The pattern whose data should be retrieved. - \param row The row from which the data should be retrieved. - \param channel The channel from which the data should be retrieved. - \param command The cell index at which the data should be retrieved. - \return The formatted pattern data at the given pattern position. See openmpt::module::command_index - \sa openmpt::module::highlight_pattern_row_channel_command - */ - LIBOPENMPT_CXX_API_MEMBER std::string format_pattern_row_channel_command( std::int32_t pattern, std::int32_t row, std::int32_t channel, int command ) const; - - //! Get highlighting information for formatted pattern content - /*! - \param pattern The pattern whose data should be retrieved. - \param row The row from which the data should be retrieved. - \param channel The channel from which the data should be retrieved. - \param command The cell index at which the data should be retrieved. See openmpt::module::command_index - \return The highlighting string for the formatted pattern data as retrieved by openmpt::module::get_pattern_row_channel_command at the given pattern position. - \remarks The returned string will map each character position of the string returned by openmpt::module::get_pattern_row_channel_command to a highlighting instruction. - Possible highlighting characters are: - - " " : empty/space - - "." : empty/dot - - "n" : generic note - - "m" : special note - - "i" : generic instrument - - "u" : generic volume column effect - - "v" : generic volume column parameter - - "e" : generic effect column effect - - "f" : generic effect column parameter - \sa openmpt::module::get_pattern_row_channel_command - */ - LIBOPENMPT_CXX_API_MEMBER std::string highlight_pattern_row_channel_command( std::int32_t pattern, std::int32_t row, std::int32_t channel, int command ) const; - - //! Get formatted (human-readable) pattern content - /*! - \param pattern The pattern whose data should be retrieved. - \param row The row from which the data should be retrieved. - \param channel The channel from which the data should be retrieved. - \param width The maximum number of characters the string should contain. 0 means no limit. - \param pad If true, the string will be resized to the exact length provided in the width parameter. - \return The formatted pattern data at the given pattern position. - \sa openmpt::module::highlight_pattern_row_channel - */ - LIBOPENMPT_CXX_API_MEMBER std::string format_pattern_row_channel( std::int32_t pattern, std::int32_t row, std::int32_t channel, std::size_t width = 0, bool pad = true ) const; - //! Get highlighting information for formatted pattern content - /*! - \param pattern The pattern whose data should be retrieved. - \param row The row from which the data should be retrieved. - \param channel The channel from which the data should be retrieved. - \param width The maximum number of characters the string should contain. 0 means no limit. - \param pad If true, the string will be resized to the exact length provided in the width parameter. - \return The highlighting string for the formatted pattern data as retrieved by openmpt::module::format_pattern_row_channel at the given pattern position. - \sa openmpt::module::format_pattern_row_channel - */ - LIBOPENMPT_CXX_API_MEMBER std::string highlight_pattern_row_channel( std::int32_t pattern, std::int32_t row, std::int32_t channel, std::size_t width = 0, bool pad = true ) const; - - //! Retrieve supported ctl keys - /*! - \return A vector containing all supported ctl keys. - \remarks Currently supported ctl values are: - - load.skip_samples (boolean): Set to "1" to avoid loading samples into memory - - load.skip_patterns (boolean): Set to "1" to avoid loading patterns into memory - - load.skip_plugins (boolean): Set to "1" to avoid loading plugins - - load.skip_subsongs_init (boolean): Set to "1" to avoid pre-initializing sub-songs. Skipping results in faster module loading but slower seeking. - - seek.sync_samples (boolean): Set to "0" to not sync sample playback when using openmpt::module::set_position_seconds or openmpt::module::set_position_order_row. - - subsong (integer): The current subsong. Setting it has identical semantics as openmpt::module::select_subsong(), getting it returns the currently selected subsong. - - play.at_end (text): Chooses the behaviour when the end of song is reached. The song end is considered to be reached after the number of reptitions set by openmpt::module::set_repeat_count was played, so if the song is set to repeat infinitely, its end is never considered to be reached. - - "fadeout": Fades the module out for a short while. Subsequent reads after the fadeout will return 0 rendered frames. - - "continue": Returns 0 rendered frames when the song end is reached. Subsequent reads will continue playing from the loop start (if the song is not programmed to loop, playback resumsed from the song start). - - "stop": Returns 0 rendered frames when the song end is reached. Subsequent reads will return 0 rendered frames. - - play.tempo_factor (floatingpoint): Set a floating point tempo factor. "1.0" is the default tempo. - - play.pitch_factor (floatingpoint): Set a floating point pitch factor. "1.0" is the default pitch. - - render.resampler.emulate_amiga (boolean): Set to "1" to enable the Amiga resampler for Amiga modules. This emulates the sound characteristics of the Paula chip and overrides the selected interpolation filter. Non-Amiga module formats are not affected by this setting. - - render.resampler.emulate_amiga_type (string): Configures the filter type to use for the Amiga resampler. Supported values are: - - "auto": Filter type is chosen by the library and might change. This is the default. - - "a500": Amiga A500 filter. - - "a1200": Amiga A1200 filter. - - "unfiltered": BLEP synthesis without model-specific filters. The LED filter is ignored by this setting. This filter mode is considered to be experimental and might change in the future. - - render.opl.volume_factor (floatingpoint): Set volume factor applied to synthesized OPL sounds, relative to the default OPL volume. - - dither (integer): Set the dither algorithm that is used for the 16 bit versions of openmpt::module::read. Supported values are: - - 0: No dithering. - - 1: Default mode. Chosen by OpenMPT code, might change. - - 2: Rectangular, 0.5 bit depth, no noise shaping (original ModPlug Tracker). - - 3: Rectangular, 1 bit depth, simple 1st order noise shaping - - An exclamation mark ("!") or a question mark ("?") can be appended to any ctl key in order to influence the behaviour in case of an unknown ctl key. "!" causes an exception to be thrown; "?" causes the ctl to be silently ignored. In case neither is appended to the key name, unknown init_ctls are ignored by default and other ctls throw an exception by default. - */ - LIBOPENMPT_CXX_API_MEMBER std::vector get_ctls() const; - - //! Get current ctl value - /*! - \param ctl The ctl key whose value should be retrieved. - \return The associated ctl value. - \sa openmpt::module::get_ctls - \deprecated Please use openmpt::module::ctl_get_boolean(), openmpt::module::ctl_get_integer(), openmpt::module::ctl_get_floatingpoint(), or openmpt::module::ctl_get_text(). - */ - LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API_MEMBER std::string ctl_get( const std::string & ctl ) const; - //! Get current ctl boolean value - /*! - \param ctl The ctl key whose value should be retrieved. - \return The associated ctl value. - \sa openmpt::module::get_ctls - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER bool ctl_get_boolean( std::string_view ctl ) const; - //! Get current ctl integer value - /*! - \param ctl The ctl key whose value should be retrieved. - \return The associated ctl value. - \sa openmpt::module::get_ctls - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER std::int64_t ctl_get_integer( std::string_view ctl ) const; - //! Get current ctl floatingpoint value - /*! - \param ctl The ctl key whose value should be retrieved. - \return The associated ctl value. - \sa openmpt::module::get_ctls - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER double ctl_get_floatingpoint( std::string_view ctl ) const; - //! Get current ctl text value - /*! - \param ctl The ctl key whose value should be retrieved. - \return The associated ctl value. - \sa openmpt::module::get_ctls - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER std::string ctl_get_text( std::string_view ctl ) const; - - //! Set ctl value - /*! - \param ctl The ctl key whose value should be set. - \param value The value that should be set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. - \sa openmpt::module::get_ctls - \deprecated Please use openmpt::module::ctl_set_boolean(), openmpt::module::ctl_set_integer(), openmpt::module::ctl_set_floatingpoint(), or openmpt::module::ctl_set_text(). - */ - LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API_MEMBER void ctl_set( const std::string & ctl, const std::string & value ); - //! Set ctl boolean value - /*! - \param ctl The ctl key whose value should be set. - \param value The value that should be set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. - \sa openmpt::module::get_ctls - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER void ctl_set_boolean( std::string_view ctl, bool value ); - //! Set ctl integer value - /*! - \param ctl The ctl key whose value should be set. - \param value The value that should be set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. - \sa openmpt::module::get_ctls - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER void ctl_set_integer( std::string_view ctl, std::int64_t value ); - //! Set ctl floatingpoint value - /*! - \param ctl The ctl key whose value should be set. - \param value The value that should be set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. - \sa openmpt::module::get_ctls - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER void ctl_set_floatingpoint( std::string_view ctl, double value ); - //! Set ctl text value - /*! - \param ctl The ctl key whose value should be set. - \param value The value that should be set. - \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. - \sa openmpt::module::get_ctls - \since 0.5.0 - */ - LIBOPENMPT_CXX_API_MEMBER void ctl_set_text( std::string_view ctl, std::string_view value ); - - // remember to add new functions to both C and C++ interfaces and to increase OPENMPT_API_VERSION_MINOR - -}; // class module - -/*! - @} -*/ - -} // namespace openmpt - -#endif // LIBOPENMPT_HPP +/* + * libopenmpt.hpp + * -------------- + * Purpose: libopenmpt public c++ interface + * Notes : (currently none) + * Authors: OpenMPT Devs + * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. + */ + +#ifndef LIBOPENMPT_HPP +#define LIBOPENMPT_HPP + +#include "libopenmpt_config.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +/*! + * \page libopenmpt_cpp_overview C++ API + * + * \section libopenmpt_cpp_error Error Handling + * + * libopenmpt C++ uses C++ exception handling for errror reporting. + * + * Unless otherwise noted, any libopenmpt function may throw exceptions and + * all exceptions thrown by libopenmpt itself are derived from + * openmpt::exception. + * In addition, any libopenmpt function may also throw any exception specified + * by the C++ language and C++ standard library. These are all derived from + * std::exception. + * + * \section libopenmpt_cpp_strings Strings + * + * - All strings returned from libopenmpt are encoded in UTF-8. + * - All strings passed to libopenmpt should also be encoded in UTF-8. + * Behaviour in case of invalid UTF-8 is unspecified. + * - libopenmpt does not enforce or expect any particular Unicode + * normalization form. + * + * \section libopenmpt_cpp_fileio File I/O + * + * libopenmpt can use 3 different strategies for file I/O. + * + * - openmpt::module::module() with any kind of memory buffer as parameter will + * load the module from the provided memory buffer, which will require loading + * all data upfront by the library + * caller. + * - openmpt::module::module() with a seekable std::istream as parameter will + * load the module via the stream interface. libopenmpt will not implement an + * additional buffering layer in this case whih means the callbacks are assumed + * to be performant even with small i/o sizes. + * - openmpt::module::module() with an unseekable std::istream as parameter + * will load the module via the stream interface. libopempt will make an + * internal copy as it goes along, and sometimes have to pre-cache the whole + * file in case it needs to know the complete file size. This strategy is + * intended to be used if the file is located on a high latency network. + * + * | constructor | speed | memory consumption | + * | ----------------: | :----: | :----------------: | + * | memory buffer |

fast

|

medium

| + * | seekable stream |

slow

|

low

| + * | unseekable stream |

medium

|

high

| + * + * In all cases, the data or stream passed to the constructor is no longer + * needed after the openmpt::module has been constructed and can be destroyed + * by the caller. + * + * \section libopenmpt_cpp_outputformat Output Format + * + * libopenmpt supports a wide range of PCM output formats: + * [8000..192000]/[mono|stereo|quad]/[f32|i16]. + * + * Unless you have some very specific requirements demanding a particular aspect + * of the output format, you should always prefer 48000/stereo/f32 as the + * libopenmpt PCM format. + * + * - Please prefer 48000Hz unless the user explicitly demands something else. + * Practically all audio equipment and file formats use 48000Hz nowadays. + * - Practically all module formats are made for stereo output. Mono will not + * give you any measurable speed improvements and can trivially be obtained from + * the stereo output anyway. Quad is not expected by almost all modules and even + * if they do use surround effects, they expect the effects to be mixed to + * stereo. + * - Floating point output provides headroom instead of hard clipping if the + * module is louder than 0dBFs, will give you a better signal-to-noise ratio + * than int16 output, and avoid the need to apply an additional dithering to the + * output by libopenmpt. Unless your platform has no floating point unit at all, + * floating point will thus also be slightly faster. + * + * \section libopenmpt_cpp_threads libopenmpt in multi-threaded environments + * + * - libopenmpt is thread-aware. + * - Individual libopenmpt objects are not thread-safe. + * - libopenmpt itself does not spawn any user-visible threads but may spawn + * threads for internal use. + * - You must ensure to only ever access a particular libopenmpt object via + * non-const member functions from a single thread at a time. + * - You may access a particular libopenmpt object concurrently from different + * threads when using only const member functions from all threads. + * - Consecutive accesses can happen from different threads. + * - Different objects can be accessed concurrently from different threads. + * + * \section libopenmpt-cpp-windows Windows support + * + * Using the libopenmpt C++ API when libopenmpt is compiled as a DLL on Windows + * requires `#define LIBOPENMPT_USE_DLL` (or some equivalent build system + * configuration) before `#include ` in order to + * correctly import the symbols from the DLL. + * + * \section libopenmpt-cpp-detailed Detailed documentation + * + * \ref libopenmpt_cpp + * + * \section libopenmpt_cpp_examples Example + * + * \include libopenmpt_example_cxx.cpp + * + */ + +/*! \defgroup libopenmpt_cpp libopenmpt C++ */ + +namespace openmpt { + +/*! \addtogroup libopenmpt_cpp + @{ +*/ + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable:4275) +#endif +//! libopenmpt exception base class +/*! + Base class used for all exceptions that are thrown by libopenmpt itself. Libopenmpt may additionally throw any exception thrown by the standard library which are all derived from std::exception. + \sa \ref libopenmpt_cpp_error +*/ +class LIBOPENMPT_CXX_API_CLASS exception : public std::exception { +private: + char * text; +public: + LIBOPENMPT_CXX_API_MEMBER exception( const std::string & text ) noexcept; + LIBOPENMPT_CXX_API_MEMBER exception( const exception & other ) noexcept; + LIBOPENMPT_CXX_API_MEMBER exception( exception && other ) noexcept; + LIBOPENMPT_CXX_API_MEMBER exception & operator = ( const exception & other ) noexcept; + LIBOPENMPT_CXX_API_MEMBER exception & operator = ( exception && other ) noexcept; + LIBOPENMPT_CXX_API_MEMBER virtual ~exception() noexcept; + LIBOPENMPT_CXX_API_MEMBER const char * what() const noexcept override; +}; // class exception +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +//! Get the libopenmpt version number +/*! + Returns the libopenmpt version number. + \return The value represents (major << 24 + minor << 16 + patch << 0). + \remarks libopenmpt < 0.3.0-pre used the following scheme: (major << 24 + minor << 16 + revision). +*/ +LIBOPENMPT_CXX_API std::uint32_t get_library_version(); + +//! Get the core version number +/*! + Return the OpenMPT core version number. + \return The value represents (majormajor << 24 + major << 16 + minor << 8 + minorminor). +*/ +LIBOPENMPT_CXX_API std::uint32_t get_core_version(); + +namespace string { + +//! Return a verbose library version string from openmpt::string::get(). \deprecated Please use `"library_version"` directly. +static const char library_version LIBOPENMPT_ATTR_DEPRECATED [] = "library_version"; +//! Return a verbose library features string from openmpt::string::get(). \deprecated Please use `"library_features"` directly. +static const char library_features LIBOPENMPT_ATTR_DEPRECATED [] = "library_features"; +//! Return a verbose OpenMPT core version string from openmpt::string::get(). \deprecated Please use `"core_version"` directly. +static const char core_version LIBOPENMPT_ATTR_DEPRECATED [] = "core_version"; +//! Return information about the current build (e.g. the build date or compiler used) from openmpt::string::get(). \deprecated Please use `"build"` directly. +static const char build LIBOPENMPT_ATTR_DEPRECATED [] = "build"; +//! Return all contributors from openmpt::string::get(). \deprecated Please use `"credits"` directly. +static const char credits LIBOPENMPT_ATTR_DEPRECATED [] = "credits"; +//! Return contact information about libopenmpt from openmpt::string::get(). \deprecated Please use `"contact"` directly. +static const char contact LIBOPENMPT_ATTR_DEPRECATED [] = "contact"; +//! Return the libopenmpt license from openmpt::string::get(). \deprecated Please use `"license"` directly. +static const char license LIBOPENMPT_ATTR_DEPRECATED [] = "license"; + +//! Get library related metadata. +/*! + \param key Key to query. + Possible keys are: + - "library_version": verbose library version string + - "library_version_major": libopenmpt major version number + - "library_version_minor": libopenmpt minor version number + - "library_version_patch": libopenmpt patch version number + - "library_version_prerel": libopenmpt pre-release version string + - "library_version_is_release": "1" if the version is an officially released version + - "library_features": verbose library features string + - "core_version": verbose OpenMPT core version string + - "source_url": original source code URL + - "source_date": original source code date + - "source_revision": original source code revision + - "source_is_modified": "1" if the original source has been modified + - "source_has_mixed_revisions": "1" if the original source has been compiled from different various revision + - "source_is_package": "1" if the original source has been obtained from a source pacakge instead of source code version control + - "build": information about the current build (e.g. the build date or compiler used) + - "build_compiler": information about the compiler used to build libopenmpt + - "credits": all contributors + - "contact": contact information about libopenmpt + - "license": the libopenmpt license + - "url": libopenmpt website URL + - "support_forum_url": libopenmpt support and discussions forum URL + - "bugtracker_url": libopenmpt bug and issue tracker URL + + \return A (possibly multi-line) string containing the queried information. If no information is available, the string is empty. +*/ +LIBOPENMPT_CXX_API std::string get( const std::string & key ); + +} // namespace string + +//! Get a list of supported file extensions +/*! + \return The list of extensions supported by this libopenmpt build. The extensions are returned lower-case without a leading dot. +*/ +LIBOPENMPT_CXX_API std::vector get_supported_extensions(); + +//! Query whether a file extension is supported +/*! + \param extension file extension to query without a leading dot. The case is ignored. + \return true if the extension is supported by libopenmpt, false otherwise. + \deprecated Please use openmpt::is_extension_supported2(). +*/ +LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API bool is_extension_supported( const std::string & extension ); +//! Query whether a file extension is supported +/*! + \param extension file extension to query without a leading dot. The case is ignored. + \return true if the extension is supported by libopenmpt, false otherwise. + \since 0.5.0 +*/ +LIBOPENMPT_CXX_API bool is_extension_supported2( std::string_view extension ); + +//! Roughly scan the input stream to find out whether libopenmpt might be able to open it +/*! + \param stream Input stream to scan. + \param effort Effort to make when validating stream. Effort 0.0 does not even look at stream at all and effort 1.0 completely loads the file from stream. A lower effort requires less data to be loaded but only gives a rough estimate answer. Use an effort of 0.25 to only verify the header data of the module file. + \param log Log where warning and errors are written. + \return Probability between 0.0 and 1.0. + \remarks openmpt::probe_file_header() provides a simpler and faster interface that fits almost all use cases better. It is recommended to use openmpt::probe_file_header() instead of openmpt::could_open_probability(). + \remarks openmpt::could_open_probability() can return any value between 0.0 and 1.0. Only 0.0 and 1.0 are definitive answers, all values in between are just estimates. In general, any return value >0.0 means that you should try loading the file, and any value below 1.0 means that loading may fail. If you want a threshold above which you can be reasonably sure that libopenmpt will be able to load the file, use >=0.5. If you see the need for a threshold below which you could reasonably outright reject a file, use <0.25 (Note: Such a threshold for rejecting on the lower end is not recommended, but may be required for better integration into some other framework's probe scoring.). + \remarks openmpt::could_open_probability() expects the complete file data to be eventually available to it, even if it is asked to just parse the header. Verification will be unreliable (both false positives and false negatives), if you pretend that the file is just some few bytes of initial data threshold in size. In order to really just access the first bytes of a file, check in your std::istream implementation whether data or seeking is requested beyond your initial data threshold, and in that case, return an error. openmpt::could_open_probability() will treat this as any other I/O error and return 0.0. You must not expect the correct result in this case. You instead must remember that it asked for more data than you currently want to provide to it and treat this situation as if openmpt::could_open_probability() returned 0.5. + \sa \ref libopenmpt_c_fileio + \sa openmpt::probe_file_header() + \since 0.3.0 +*/ +LIBOPENMPT_CXX_API double could_open_probability( std::istream & stream, double effort = 1.0, std::ostream & log = std::clog ); + +//! Roughly scan the input stream to find out whether libopenmpt might be able to open it +/*! + \deprecated Please use openmpt::could_open_probability(). +*/ +LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API double could_open_propability( std::istream & stream, double effort = 1.0, std::ostream & log = std::clog ); + +//! Get recommended header size for successfull format probing +/*! + \sa openmpt::probe_file_header() + \since 0.3.0 +*/ +LIBOPENMPT_CXX_API std::size_t probe_file_header_get_recommended_size(); + +//! Probe for module formats in openmpt::probe_file_header(). \since 0.3.0 \deprecated Please use openmpt::probe_file_header_flags_modules2. +static const std::uint64_t probe_file_header_flags_modules LIBOPENMPT_ATTR_DEPRECATED = 0x1ull; + +//! Probe for module-specific container formats in openmpt::probe_file_header(). \since 0.3.0 \deprecated Please use openmpt::probe_file_header_flags_containers2. +static const std::uint64_t probe_file_header_flags_containers LIBOPENMPT_ATTR_DEPRECATED = 0x2ull; + +//! Probe for the default set of formats in openmpt::probe_file_header(). \since 0.3.0 \deprecated Please use openmpt::probe_file_header_flags_default2. +static const std::uint64_t probe_file_header_flags_default LIBOPENMPT_ATTR_DEPRECATED = 0x1ull | 0x2ull; + +//! Probe for no formats in openmpt::probe_file_header(). \since 0.3.0 \deprecated Please use openmpt::probe_file_header_flags_none2. +static const std::uint64_t probe_file_header_flags_none LIBOPENMPT_ATTR_DEPRECATED = 0x0ull; + +//! Possible values for openmpt::probe_file_header() flags parameter. \since 0.6.0 +enum probe_file_header_flags : std::uint64_t { + //! Probe for module formats in openmpt::probe_file_header(). \since 0.6.0 + probe_file_header_flags_modules2 = 0x1ull, + //! Probe for module-specific container formats in openmpt::probe_file_header(). \since 0.6.0 + probe_file_header_flags_containers2 = 0x2ull, + //! Probe for the default set of formats in openmpt::probe_file_header(). \since 0.6.0 + probe_file_header_flags_default2 = probe_file_header_flags_modules2 | probe_file_header_flags_containers2, + //! Probe for no formats in openmpt::probe_file_header(). \since 0.6.0 + probe_file_header_flags_none2 = 0x0ull +}; + +//! Possible return values for openmpt::probe_file_header(). \since 0.3.0 +enum probe_file_header_result { + //! The file will most likely be supported by libopenmpt. \since 0.3.0 + probe_file_header_result_success = 1, + //! The file is not supported by libopenmpt. \since 0.3.0 + probe_file_header_result_failure = 0, + //! An answer could not be determined with the amount of data provided. \since 0.3.0 + probe_file_header_result_wantmoredata = -1 +}; + +//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it +/*! + \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. + \param data Beginning of the file data. + \param size Size of the beginning of the file data. + \param filesize Full size of the file data on disk. + \remarks It is recommended to provide openmpt::probe_file_header_get_recommended_size() bytes of data for data and size. If the file is smaller, only provide the filesize amount and set size and filesize to the file's size. + \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. + \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. + \retval probe_file_header_result_failure The file is not supported by libopenmpt. + \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. + \sa openmpt::probe_file_header_get_recommended_size() + \sa openmpt::could_open_probability() + \since 0.5.0 +*/ +LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, const std::byte * data, std::size_t size, std::uint64_t filesize ); +//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it +/*! + \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. + \param data Beginning of the file data. + \param size Size of the beginning of the file data. + \param filesize Full size of the file data on disk. + \remarks It is recommended to provide openmpt::probe_file_header_get_recommended_size() bytes of data for data and size. If the file is smaller, only provide the filesize amount and set size and filesize to the file's size. + \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. + \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. + \retval probe_file_header_result_failure The file is not supported by libopenmpt. + \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. + \sa openmpt::probe_file_header_get_recommended_size() + \sa openmpt::could_open_probability() + \since 0.3.0 +*/ +LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, const std::uint8_t * data, std::size_t size, std::uint64_t filesize ); + +//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it +/*! + \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. + \param data Beginning of the file data. + \param size Size of the beginning of the file data. + \remarks It is recommended to use the overload of this function that also takes the filesize as parameter if at all possile. libopenmpt can provide more accurate answers if the filesize is known. + \remarks It is recommended to provide openmpt::probe_file_header_get_recommended_size() bytes of data for data and size. If the file is smaller, only provide the filesize amount and set size to the file's size. + \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. + \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. + \retval probe_file_header_result_failure The file is not supported by libopenmpt. + \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. + \sa openmpt::probe_file_header_get_recommended_size() + \sa openmpt::could_open_probability() + \since 0.5.0 +*/ +LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, const std::byte * data, std::size_t size ); +//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it +/*! + \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. + \param data Beginning of the file data. + \param size Size of the beginning of the file data. + \remarks It is recommended to use the overload of this function that also takes the filesize as parameter if at all possile. libopenmpt can provide more accurate answers if the filesize is known. + \remarks It is recommended to provide openmpt::probe_file_header_get_recommended_size() bytes of data for data and size. If the file is smaller, only provide the filesize amount and set size to the file's size. + \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. + \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. + \retval probe_file_header_result_failure The file is not supported by libopenmpt. + \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. + \sa openmpt::probe_file_header_get_recommended_size() + \sa openmpt::could_open_probability() + \since 0.3.0 +*/ +LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, const std::uint8_t * data, std::size_t size ); + +//! Probe the provided bytes from the beginning of a file for supported file format headers to find out whether libopenmpt might be able to open it +/*! + \param flags Bit mask of openmpt::probe_file_header_flags_modules2 and openmpt::probe_file_header_flags_containers2, or openmpt::probe_file_header_flags_default2. + \param stream Input stream to scan. + \remarks stream is left in an unspecified state when this function returns. + \remarks openmpt::could_open_probability() provides a more elaborate interface that might be required for special use cases. It is recommended to use openmpt::probe_file_header() though, if possible. + \retval probe_file_header_result_success The file will most likely be supported by libopenmpt. + \retval probe_file_header_result_failure The file is not supported by libopenmpt. + \retval probe_file_header_result_wantmoredata An answer could not be determined with the amount of data provided. + \sa openmpt::probe_file_header_get_recommended_size() + \sa openmpt::could_open_probability() + \since 0.3.0 +*/ +LIBOPENMPT_CXX_API int probe_file_header( std::uint64_t flags, std::istream & stream ); + +class module_impl; + +class module_ext; + +namespace detail { + +typedef std::map< std::string, std::string > initial_ctls_map; + +} // namespace detail + +class LIBOPENMPT_CXX_API_CLASS module { + + friend class module_ext; + +public: + + //! Parameter index to use with openmpt::module::get_render_param and openmpt::module::set_render_param + enum render_param { + //! Master Gain + /*! + The related value represents a relative gain in milliBel.\n + The default value is 0.\n + The supported value range is unlimited.\n + */ + RENDER_MASTERGAIN_MILLIBEL = 1, + //! Stereo Separation + /*! + The related value represents the stereo separation generated by the libopenmpt mixer in percent.\n + The default value is 100.\n + The supported value range is [0,200].\n + */ + RENDER_STEREOSEPARATION_PERCENT = 2, + //! Interpolation Filter + /*! + The related value represents the interpolation filter length used by the libopenmpt mixer.\n + The default value is 0, which indicates a recommended default value.\n + The supported value range is [0,inf). Values greater than the implementation limit are clamped to the maximum supported value.\n + Currently supported values: + - 0: internal default + - 1: no interpolation (zero order hold) + - 2: linear interpolation + - 4: cubic interpolation + - 8: windowed sinc with 8 taps + */ + RENDER_INTERPOLATIONFILTER_LENGTH = 3, + //! Volume Ramping Strength + /*! + The related value represents the amount of volume ramping done by the libopenmpt mixer.\n + The default value is -1, which indicates a recommended default value.\n + The meaningful value range is [-1..10].\n + A value of 0 completely disables volume ramping. This might cause clicks in sound output.\n + Higher values imply slower/softer volume ramps. + */ + RENDER_VOLUMERAMPING_STRENGTH = 4 + }; + + //! Parameter index to use with openmpt::module::get_pattern_row_channel_command, openmpt::module::format_pattern_row_channel_command and openmpt::module::highlight_pattern_row_channel_command + enum command_index { + command_note = 0, + command_instrument = 1, + command_volumeffect = 2, + command_effect = 3, + command_volume = 4, + command_parameter = 5 + }; + +private: + module_impl * impl; +private: + // non-copyable + module( const module & ); + void operator = ( const module & ); +private: + // for module_ext + module(); + void set_impl( module_impl * i ); +public: + //! Construct an openmpt::module + /*! + \param stream Input stream from which the module is loaded. After the constructor has finished successfully, the input position of stream is set to the byte after the last byte that has been read. If the constructor fails, the state of the input position of stream is undefined. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see \ref openmpt::module::get_ctls and openmpt::module::ctl_set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + */ + LIBOPENMPT_CXX_API_MEMBER module( std::istream & stream, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param data Data to load the module from. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see \ref openmpt::module::get_ctls and openmpt::module::ctl_set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER module( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param beg Begin of data to load the module from. + \param end End of data to load the module from. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see \ref openmpt::module::get_ctls and openmpt::module::ctl_set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER module( const std::byte * beg, const std::byte * end, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param data Data to load the module from. + \param size Amount of data available. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see openmpt::module::get_ctls. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER module( const std::byte * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param data Data to load the module from. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see \ref openmpt::module::get_ctls and openmpt::module::ctl_set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + */ + LIBOPENMPT_CXX_API_MEMBER module( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param beg Begin of data to load the module from. + \param end End of data to load the module from. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see openmpt::module::get_ctls. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + */ + LIBOPENMPT_CXX_API_MEMBER module( const std::uint8_t * beg, const std::uint8_t * end, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param data Data to load the module from. + \param size Amount of data available. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see openmpt::module::get_ctls. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + */ + LIBOPENMPT_CXX_API_MEMBER module( const std::uint8_t * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param data Data to load the module from. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see openmpt::module::get_ctls. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + */ + LIBOPENMPT_CXX_API_MEMBER module( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param beg Begin of data to load the module from. + \param end End of data to load the module from. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see openmpt::module::get_ctls. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + */ + LIBOPENMPT_CXX_API_MEMBER module( const char * beg, const char * end, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param data Data to load the module from. + \param size Amount of data available. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see openmpt::module::get_ctls. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + */ + LIBOPENMPT_CXX_API_MEMBER module( const char * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + /*! + \param data Data to load the module from. + \param size Amount of data available. + \param log Log where any warnings or errors are printed to. The lifetime of the reference has to be as long as the lifetime of the module instance. + \param ctls A map of initial ctl values, see openmpt::module::get_ctls. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the provided file cannot be opened. + \remarks The input data can be discarded after an openmpt::module has been constructed successfully. + \sa \ref libopenmpt_cpp_fileio + */ + LIBOPENMPT_CXX_API_MEMBER module( const void * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER virtual ~module(); +public: + + //! Select a sub-song from a multi-song module + /*! + \param subsong Index of the sub-song. -1 plays all sub-songs consecutively. + \throws openmpt::exception Throws an exception derived from openmpt::exception if sub-song is not in range [-1,openmpt::module::get_num_subsongs()[ + \sa openmpt::module::get_num_subsongs, openmpt::module::get_selected_subsong, openmpt::module::get_subsong_names + \remarks Whether subsong -1 (all subsongs consecutively), subsong 0 or some other subsong is selected by default, is an implementation detail and subject to change. If you do not want to care about subsongs, it is recommended to just not call openmpt::module::select_subsong() at all. + */ + LIBOPENMPT_CXX_API_MEMBER void select_subsong( std::int32_t subsong ); + //! Get currently selected sub-song from a multi-song module + /*! + \return Currently selected sub-song. -1 for all subsongs consecutively, 0 or greater for the current sub-song index. + \sa openmpt::module::get_num_subsongs, openmpt::module::select_subsong, openmpt::module::get_subsong_names + \since 0.3.0 + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_selected_subsong() const; + //! Set Repeat Count + /*! + \param repeat_count Repeat Count + - -1: repeat forever + - 0: play once, repeat zero times (the default) + - n>0: play once and repeat n times after that + \sa openmpt::module::get_repeat_count + */ + LIBOPENMPT_CXX_API_MEMBER void set_repeat_count( std::int32_t repeat_count ); + //! Get Repeat Count + /*! + \return Repeat Count + - -1: repeat forever + - 0: play once, repeat zero times (the default) + - n>0: play once and repeat n times after that + \sa openmpt::module::set_repeat_count + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_repeat_count() const; + + //! Get approximate song duration + /*! + \return Approximate duration of current sub-song in seconds. + \remarks The function may return infinity if the pattern data is too complex to evaluate. + */ + LIBOPENMPT_CXX_API_MEMBER double get_duration_seconds() const; + + //! Set approximate current song position + /*! + \param seconds Seconds to seek to. If seconds is out of range, the position gets set to song start or end respectively. + \return Approximate new song position in seconds. + \sa openmpt::module::get_position_seconds + */ + LIBOPENMPT_CXX_API_MEMBER double set_position_seconds( double seconds ); + //! Get current song position + /*! + \return Current song position in seconds. + \sa openmpt::module::set_position_seconds + */ + LIBOPENMPT_CXX_API_MEMBER double get_position_seconds() const; + + //! Set approximate current song position + /*! + If order or row are out of range, to position is not modified and the current position is returned. + \param order Pattern order number to seek to. + \param row Pattern row number to seek to. + \return Approximate new song position in seconds. + \sa openmpt::module::set_position_seconds + \sa openmpt::module::get_position_seconds + */ + LIBOPENMPT_CXX_API_MEMBER double set_position_order_row( std::int32_t order, std::int32_t row ); + + //! Get render parameter + /*! + \param param Parameter to query. See openmpt::module::render_param. + \return The current value of the parameter. + \throws openmpt::exception Throws an exception derived from openmpt::exception if param is invalid. + \sa openmpt::module::render_param + \sa openmpt::module::set_render_param + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_render_param( int param ) const; + //! Set render parameter + /*! + \param param Parameter to set. See openmpt::module::render_param. + \param value The value to set param to. + \throws openmpt::exception Throws an exception derived from openmpt::exception if param is invalid or value is out of range. + \sa openmpt::module::render_param + \sa openmpt::module::get_render_param + */ + LIBOPENMPT_CXX_API_MEMBER void set_render_param( int param, std::int32_t value ); + + /*@{*/ + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param mono Pointer to a buffer of at least count elements that receives the mono/center output. + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, std::int16_t * mono ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param left Pointer to a buffer of at least count elements that receives the left output. + \param right Pointer to a buffer of at least count elements that receives the right output. + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, std::int16_t * left, std::int16_t * right ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param left Pointer to a buffer of at least count elements that receives the left output. + \param right Pointer to a buffer of at least count elements that receives the right output. + \param rear_left Pointer to a buffer of at least count elements that receives the rear left output. + \param rear_right Pointer to a buffer of at least count elements that receives the rear right output. + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, std::int16_t * left, std::int16_t * right, std::int16_t * rear_left, std::int16_t * rear_right ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param mono Pointer to a buffer of at least count elements that receives the mono/center output. + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, float * mono ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param left Pointer to a buffer of at least count elements that receives the left output. + \param right Pointer to a buffer of at least count elements that receives the right output. + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, float * left, float * right ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param left Pointer to a buffer of at least count elements that receives the left output. + \param right Pointer to a buffer of at least count elements that receives the right output. + \param rear_left Pointer to a buffer of at least count elements that receives the rear left output. + \param rear_right Pointer to a buffer of at least count elements that receives the rear right output. + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read( std::int32_t samplerate, std::size_t count, float * left, float * right, float * rear_left, float * rear_right ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param interleaved_stereo Pointer to a buffer of at least count*2 elements that receives the interleaved stereo output in the order (L,R). + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read_interleaved_stereo( std::int32_t samplerate, std::size_t count, std::int16_t * interleaved_stereo ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param interleaved_quad Pointer to a buffer of at least count*4 elements that receives the interleaved quad surround output in the order (L,R,RL,RR). + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks It is recommended to use the floating point API because of the greater dynamic range and no implied clipping. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read_interleaved_quad( std::int32_t samplerate, std::size_t count, std::int16_t * interleaved_quad ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param interleaved_stereo Pointer to a buffer of at least count*2 elements that receives the interleaved stereo output in the order (L,R). + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read_interleaved_stereo( std::int32_t samplerate, std::size_t count, float * interleaved_stereo ); + //! Render audio data + /*! + \param samplerate Sample rate to render output. Should be in [8000,192000], but this is not enforced. + \param count Number of audio frames to render per channel. + \param interleaved_quad Pointer to a buffer of at least count*4 elements that receives the interleaved quad surround output in the order (L,R,RL,RR). + \return The number of frames actually rendered. + \retval 0 The end of song has been reached. + \remarks The output buffers are only written to up to the returned number of elements. + \remarks You can freely switch between any of the "read*" variants if you see a need to do so. libopenmpt tries to introduce as little switching annoyances as possible. Normally, you would only use a single one of these functions for rendering a particular module. + \remarks Floating point samples are in the [-1.0..1.0] nominal range. They are not clipped to that range though and thus might overshoot. + \sa \ref libopenmpt_cpp_outputformat + */ + LIBOPENMPT_CXX_API_MEMBER std::size_t read_interleaved_quad( std::int32_t samplerate, std::size_t count, float * interleaved_quad ); + /*@}*/ + + //! Get the list of supported metadata item keys + /*! + \return Metadata item keys supported by openmpt::module::get_metadata + \sa openmpt::module::get_metadata + */ + LIBOPENMPT_CXX_API_MEMBER std::vector get_metadata_keys() const; + //! Get a metadata item value + /*! + \param key Metadata item key to query. Use openmpt::module::get_metadata_keys to check for available keys. + Possible keys are: + - type: Module format extension (e.g. it) or another similar identifier for modules formats that typically do not use a file extension + - type_long: Format name associated with the module format (e.g. Impulse Tracker) + - originaltype: Module format extension (e.g. it) of the original module in case the actual type is a converted format (e.g. mo3 or gdm) + - originaltype_long: Format name associated with the module format (e.g. Impulse Tracker) of the original module in case the actual type is a converted format (e.g. mo3 or gdm) + - container: Container format the module file is embedded in, if any (e.g. umx) + - container_long: Full container name if the module is embedded in a container (e.g. Unreal Music) + - tracker: Tracker that was (most likely) used to save the module file, if known + - artist: Author of the module + - title: Module title + - date: Date the module was last saved, in ISO-8601 format. + - message: Song message. If the song message is empty or the module format does not support song messages, a list of instrument and sample names is returned instead. + - message_raw: Song message. If the song message is empty or the module format does not support song messages, an empty string is returned. + - warnings: A list of warnings that were generated while loading the module. + \return The associated value for key. + \sa openmpt::module::get_metadata_keys + */ + LIBOPENMPT_CXX_API_MEMBER std::string get_metadata( const std::string & key ) const; + + //! Get the current estimated beats per minute (BPM). + /*! + \remarks Many module formats lack time signature metadata. It is common that this estimate is off by a factor of two, but other multipliers are also possible. + \remarks Due to the nature of how module tempo works, the estimate may change slightly after switching libopenmpt's output to a different sample rate. + \return The current estimated BPM. + */ + LIBOPENMPT_CXX_API_MEMBER double get_current_estimated_bpm() const; + //! Get the current speed + /*! + \return The current speed in ticks per row. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_speed() const; + //! Get the current tempo + /*! + \return The current tempo in tracker units. The exact meaning of this value depends on the tempo mode being used. + \deprecated Please use openmpt::module::get_current_tempo2(). + */ + LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_tempo() const; + //! Get the current tempo + /*! + \return The current tempo in tracker units. The exact meaning of this value depends on the tempo mode being used. + \since 0.7.0 + */ + LIBOPENMPT_CXX_API_MEMBER double get_current_tempo2() const; + //! Get the current order + /*! + \return The current order at which the module is being played back. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_order() const; + //! Get the current pattern + /*! + \return The current pattern that is being played. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_pattern() const; + //! Get the current row + /*! + \return The current row at which the current pattern is being played. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_row() const; + //! Get the current amount of playing channels. + /*! + \return The amount of sample channels that are currently being rendered. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_current_playing_channels() const; + + //! Get an approximate indication of the channel volume. + /*! + \param channel The channel whose volume should be retrieved. + \return The approximate channel volume. + \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. + */ + LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_mono( std::int32_t channel ) const; + //! Get an approximate indication of the channel volume on the front-left speaker. + /*! + \param channel The channel whose volume should be retrieved. + \return The approximate channel volume. + \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. + */ + LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_left( std::int32_t channel ) const; + //! Get an approximate indication of the channel volume on the front-right speaker. + /*! + \param channel The channel whose volume should be retrieved. + \return The approximate channel volume. + \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. + */ + LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_right( std::int32_t channel ) const; + //! Get an approximate indication of the channel volume on the rear-left speaker. + /*! + \param channel The channel whose volume should be retrieved. + \return The approximate channel volume. + \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. + */ + LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_rear_left( std::int32_t channel ) const; + //! Get an approximate indication of the channel volume on the rear-right speaker. + /*! + \param channel The channel whose volume should be retrieved. + \return The approximate channel volume. + \remarks The returned value is solely based on the note velocity and does not take the actual waveform of the playing sample into account. + */ + LIBOPENMPT_CXX_API_MEMBER float get_current_channel_vu_rear_right( std::int32_t channel ) const; + + //! Get the number of sub-songs + /*! + \return The number of sub-songs in the module. This includes any "hidden" songs (songs that share the same sequence, but start at different order indices) and "normal" sub-songs or "sequences" (if the format supports them). + \sa openmpt::module::get_subsong_names, openmpt::module::select_subsong, openmpt::module::get_selected_subsong + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_subsongs() const; + //! Get the number of pattern channels + /*! + \return The number of pattern channels in the module. Not all channels do necessarily contain data. + \remarks The number of pattern channels is completely independent of the number of output channels. libopenmpt can render modules in mono, stereo or quad surround, but the choice of which of the three modes to use must not be made based on the return value of this function, which may be any positive integer amount. Only use this function for informational purposes. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_channels() const; + //! Get the number of orders + /*! + \return The number of orders in the current sequence of the module. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_orders() const; + //! Get the number of patterns + /*! + \return The number of distinct patterns in the module. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_patterns() const; + //! Get the number of instruments + /*! + \return The number of instrument slots in the module. Instruments are a layer on top of samples, and are not supported by all module formats. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_instruments() const; + //! Get the number of samples + /*! + \return The number of sample slots in the module. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_num_samples() const; + + //! Get a list of sub-song names + /*! + \return All sub-song names. + \sa openmpt::module::get_num_subsongs, openmpt::module::select_subsong, openmpt::module::get_selected_subsong + */ + LIBOPENMPT_CXX_API_MEMBER std::vector get_subsong_names() const; + //! Get a list of channel names + /*! + \return All channel names. + \sa openmpt::module::get_num_channels + */ + LIBOPENMPT_CXX_API_MEMBER std::vector get_channel_names() const; + //! Get a list of order names + /*! + \return All order names. + \sa openmpt::module::get_num_orders + */ + LIBOPENMPT_CXX_API_MEMBER std::vector get_order_names() const; + //! Get a list of pattern names + /*! + \return All pattern names. + \sa openmpt::module::get_num_patterns + */ + LIBOPENMPT_CXX_API_MEMBER std::vector get_pattern_names() const; + //! Get a list of instrument names + /*! + \return All instrument names. + \sa openmpt::module::get_num_instruments + */ + LIBOPENMPT_CXX_API_MEMBER std::vector get_instrument_names() const; + //! Get a list of sample names + /*! + \return All sample names. + \sa openmpt::module::get_num_samples + */ + LIBOPENMPT_CXX_API_MEMBER std::vector get_sample_names() const; + + //! Get pattern at order position + /*! + \param order The order item whose pattern index should be retrieved. + \return The pattern index found at the given order position of the current sequence. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_order_pattern( std::int32_t order ) const; + + //! Get the number of rows in a pattern + /*! + \param pattern The pattern whose row count should be retrieved. + \return The number of rows in the given pattern. If the pattern does not exist, 0 is returned. + */ + LIBOPENMPT_CXX_API_MEMBER std::int32_t get_pattern_num_rows( std::int32_t pattern ) const; + + //! Get raw pattern content + /*! + \param pattern The pattern whose data should be retrieved. + \param row The row from which the data should be retrieved. + \param channel The channel from which the data should be retrieved. + \param command The cell index at which the data should be retrieved. See openmpt::module::command_index + \return The internal, raw pattern data at the given pattern position. + */ + LIBOPENMPT_CXX_API_MEMBER std::uint8_t get_pattern_row_channel_command( std::int32_t pattern, std::int32_t row, std::int32_t channel, int command ) const; + + //! Get formatted (human-readable) pattern content + /*! + \param pattern The pattern whose data should be retrieved. + \param row The row from which the data should be retrieved. + \param channel The channel from which the data should be retrieved. + \param command The cell index at which the data should be retrieved. + \return The formatted pattern data at the given pattern position. See openmpt::module::command_index + \sa openmpt::module::highlight_pattern_row_channel_command + */ + LIBOPENMPT_CXX_API_MEMBER std::string format_pattern_row_channel_command( std::int32_t pattern, std::int32_t row, std::int32_t channel, int command ) const; + + //! Get highlighting information for formatted pattern content + /*! + \param pattern The pattern whose data should be retrieved. + \param row The row from which the data should be retrieved. + \param channel The channel from which the data should be retrieved. + \param command The cell index at which the data should be retrieved. See openmpt::module::command_index + \return The highlighting string for the formatted pattern data as retrieved by openmpt::module::get_pattern_row_channel_command at the given pattern position. + \remarks The returned string will map each character position of the string returned by openmpt::module::get_pattern_row_channel_command to a highlighting instruction. + Possible highlighting characters are: + - " " : empty/space + - "." : empty/dot + - "n" : generic note + - "m" : special note + - "i" : generic instrument + - "u" : generic volume column effect + - "v" : generic volume column parameter + - "e" : generic effect column effect + - "f" : generic effect column parameter + \sa openmpt::module::get_pattern_row_channel_command + */ + LIBOPENMPT_CXX_API_MEMBER std::string highlight_pattern_row_channel_command( std::int32_t pattern, std::int32_t row, std::int32_t channel, int command ) const; + + //! Get formatted (human-readable) pattern content + /*! + \param pattern The pattern whose data should be retrieved. + \param row The row from which the data should be retrieved. + \param channel The channel from which the data should be retrieved. + \param width The maximum number of characters the string should contain. 0 means no limit. + \param pad If true, the string will be resized to the exact length provided in the width parameter. + \return The formatted pattern data at the given pattern position. + \sa openmpt::module::highlight_pattern_row_channel + */ + LIBOPENMPT_CXX_API_MEMBER std::string format_pattern_row_channel( std::int32_t pattern, std::int32_t row, std::int32_t channel, std::size_t width = 0, bool pad = true ) const; + //! Get highlighting information for formatted pattern content + /*! + \param pattern The pattern whose data should be retrieved. + \param row The row from which the data should be retrieved. + \param channel The channel from which the data should be retrieved. + \param width The maximum number of characters the string should contain. 0 means no limit. + \param pad If true, the string will be resized to the exact length provided in the width parameter. + \return The highlighting string for the formatted pattern data as retrieved by openmpt::module::format_pattern_row_channel at the given pattern position. + \sa openmpt::module::format_pattern_row_channel + */ + LIBOPENMPT_CXX_API_MEMBER std::string highlight_pattern_row_channel( std::int32_t pattern, std::int32_t row, std::int32_t channel, std::size_t width = 0, bool pad = true ) const; + + //! Retrieve supported ctl keys + /*! + \return A vector containing all supported ctl keys. + \remarks Currently supported ctl values are: + - load.skip_samples (boolean): Set to "1" to avoid loading samples into memory + - load.skip_patterns (boolean): Set to "1" to avoid loading patterns into memory + - load.skip_plugins (boolean): Set to "1" to avoid loading plugins + - load.skip_subsongs_init (boolean): Set to "1" to avoid pre-initializing sub-songs. Skipping results in faster module loading but slower seeking. + - seek.sync_samples (boolean): Set to "0" to not sync sample playback when using openmpt::module::set_position_seconds or openmpt::module::set_position_order_row. + - subsong (integer): The current subsong. Setting it has identical semantics as openmpt::module::select_subsong(), getting it returns the currently selected subsong. + - play.at_end (text): Chooses the behaviour when the end of song is reached. The song end is considered to be reached after the number of reptitions set by openmpt::module::set_repeat_count was played, so if the song is set to repeat infinitely, its end is never considered to be reached. + - "fadeout": Fades the module out for a short while. Subsequent reads after the fadeout will return 0 rendered frames. + - "continue": Returns 0 rendered frames when the song end is reached. Subsequent reads will continue playing from the loop start (if the song is not programmed to loop, playback resumsed from the song start). + - "stop": Returns 0 rendered frames when the song end is reached. Subsequent reads will return 0 rendered frames. + - play.tempo_factor (floatingpoint): Set a floating point tempo factor. "1.0" is the default tempo. + - play.pitch_factor (floatingpoint): Set a floating point pitch factor. "1.0" is the default pitch. + - render.resampler.emulate_amiga (boolean): Set to "1" to enable the Amiga resampler for Amiga modules. This emulates the sound characteristics of the Paula chip and overrides the selected interpolation filter. Non-Amiga module formats are not affected by this setting. + - render.resampler.emulate_amiga_type (string): Configures the filter type to use for the Amiga resampler. Supported values are: + - "auto": Filter type is chosen by the library and might change. This is the default. + - "a500": Amiga A500 filter. + - "a1200": Amiga A1200 filter. + - "unfiltered": BLEP synthesis without model-specific filters. The LED filter is ignored by this setting. This filter mode is considered to be experimental and might change in the future. + - render.opl.volume_factor (floatingpoint): Set volume factor applied to synthesized OPL sounds, relative to the default OPL volume. + - dither (integer): Set the dither algorithm that is used for the 16 bit versions of openmpt::module::read. Supported values are: + - 0: No dithering. + - 1: Default mode. Chosen by OpenMPT code, might change. + - 2: Rectangular, 0.5 bit depth, no noise shaping (original ModPlug Tracker). + - 3: Rectangular, 1 bit depth, simple 1st order noise shaping + + An exclamation mark ("!") or a question mark ("?") can be appended to any ctl key in order to influence the behaviour in case of an unknown ctl key. "!" causes an exception to be thrown; "?" causes the ctl to be silently ignored. In case neither is appended to the key name, unknown init_ctls are ignored by default and other ctls throw an exception by default. + */ + LIBOPENMPT_CXX_API_MEMBER std::vector get_ctls() const; + + //! Get current ctl value + /*! + \param ctl The ctl key whose value should be retrieved. + \return The associated ctl value. + \sa openmpt::module::get_ctls + \deprecated Please use openmpt::module::ctl_get_boolean(), openmpt::module::ctl_get_integer(), openmpt::module::ctl_get_floatingpoint(), or openmpt::module::ctl_get_text(). + */ + LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API_MEMBER std::string ctl_get( const std::string & ctl ) const; + //! Get current ctl boolean value + /*! + \param ctl The ctl key whose value should be retrieved. + \return The associated ctl value. + \sa openmpt::module::get_ctls + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER bool ctl_get_boolean( std::string_view ctl ) const; + //! Get current ctl integer value + /*! + \param ctl The ctl key whose value should be retrieved. + \return The associated ctl value. + \sa openmpt::module::get_ctls + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER std::int64_t ctl_get_integer( std::string_view ctl ) const; + //! Get current ctl floatingpoint value + /*! + \param ctl The ctl key whose value should be retrieved. + \return The associated ctl value. + \sa openmpt::module::get_ctls + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER double ctl_get_floatingpoint( std::string_view ctl ) const; + //! Get current ctl text value + /*! + \param ctl The ctl key whose value should be retrieved. + \return The associated ctl value. + \sa openmpt::module::get_ctls + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER std::string ctl_get_text( std::string_view ctl ) const; + + //! Set ctl value + /*! + \param ctl The ctl key whose value should be set. + \param value The value that should be set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. + \sa openmpt::module::get_ctls + \deprecated Please use openmpt::module::ctl_set_boolean(), openmpt::module::ctl_set_integer(), openmpt::module::ctl_set_floatingpoint(), or openmpt::module::ctl_set_text(). + */ + LIBOPENMPT_ATTR_DEPRECATED LIBOPENMPT_CXX_API_MEMBER void ctl_set( const std::string & ctl, const std::string & value ); + //! Set ctl boolean value + /*! + \param ctl The ctl key whose value should be set. + \param value The value that should be set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. + \sa openmpt::module::get_ctls + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER void ctl_set_boolean( std::string_view ctl, bool value ); + //! Set ctl integer value + /*! + \param ctl The ctl key whose value should be set. + \param value The value that should be set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. + \sa openmpt::module::get_ctls + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER void ctl_set_integer( std::string_view ctl, std::int64_t value ); + //! Set ctl floatingpoint value + /*! + \param ctl The ctl key whose value should be set. + \param value The value that should be set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. + \sa openmpt::module::get_ctls + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER void ctl_set_floatingpoint( std::string_view ctl, double value ); + //! Set ctl text value + /*! + \param ctl The ctl key whose value should be set. + \param value The value that should be set. + \throws openmpt::exception Throws an exception derived from openmpt::exception in case the value is not sensible (e.g. negative tempo factor) or under the circumstances outlined in openmpt::module::get_ctls. + \sa openmpt::module::get_ctls + \since 0.5.0 + */ + LIBOPENMPT_CXX_API_MEMBER void ctl_set_text( std::string_view ctl, std::string_view value ); + + // remember to add new functions to both C and C++ interfaces and to increase OPENMPT_API_VERSION_MINOR + +}; // class module + +/*! + @} +*/ + +} // namespace openmpt + +#endif // LIBOPENMPT_HPP diff --git a/libs/libopenmpt/inc/libopenmpt/libopenmpt_ext.hpp b/libs/libopenmpt/inc/libopenmpt/libopenmpt_ext.hpp index 71524d2b6..c84d927be 100644 --- a/libs/libopenmpt/inc/libopenmpt/libopenmpt_ext.hpp +++ b/libs/libopenmpt/inc/libopenmpt/libopenmpt_ext.hpp @@ -1,429 +1,429 @@ -/* - * libopenmpt_ext.hpp - * ------------------ - * Purpose: libopenmpt public c++ interface for libopenmpt extensions - * Notes : - * Authors: OpenMPT Devs - * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. - */ - -#ifndef LIBOPENMPT_EXT_HPP -#define LIBOPENMPT_EXT_HPP - -#include "libopenmpt_config.h" -#include "libopenmpt.hpp" - -/*! - * \page libopenmpt_ext_cpp_overview libopenmpt_ext C++ API - * - * libopenmpt_ext is now included in all builds by default. - * - * \section libopenmpt-ext-cpp-detailed Detailed documentation - * - * \ref libopenmpt_ext_cpp - * - */ - -/*! \defgroup libopenmpt_ext_cpp libopenmpt_ext C++ */ - -namespace openmpt { - -/*! \addtogroup libopenmpt_ext_cpp - @{ -*/ - -class module_ext_impl; - -class LIBOPENMPT_CXX_API_CLASS module_ext : public module { - -private: - module_ext_impl * ext_impl; -private: - // non-copyable - LIBOPENMPT_CXX_API_MEMBER module_ext( const module_ext & ); - LIBOPENMPT_CXX_API_MEMBER void operator = ( const module_ext & ); -public: - LIBOPENMPT_CXX_API_MEMBER module_ext( std::istream & stream, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER module_ext( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER module_ext( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER module_ext( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER module_ext( const std::byte * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER module_ext( const std::uint8_t * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER module_ext( const char * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER module_ext( const void * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); - LIBOPENMPT_CXX_API_MEMBER virtual ~module_ext(); - -public: - - //! Retrieve a libopenmpt extension. - /*! Example: Retrieving the interactive extension to change the tempo of a module: - \code{.cpp} - openmpt::module_ext *mod = new openmpt::module_ext( stream ); - #ifdef LIBOPENMPT_EXT_INTERFACE_INTERACTIVE - openmpt::ext::interactive *interactive = static_cast( self->mod->get_interface( openmpt::ext::interactive_id ) ); - if ( interactive ) { - interactive->set_tempo_factor( 2.0 ); // play module at double speed - } else { - // interface not available - } - #else - // interfae not available - #endif - \endcode - \param interface_id The name of the extension interface to retrieve. - \return The interface object. This may be a nullptr if the extension was not found. - */ - LIBOPENMPT_CXX_API_MEMBER void * get_interface( const std::string & interface_id ); - -}; // class module_ext - -/*! - @} -*/ - -namespace ext { - -/*! \addtogroup libopenmpt_ext_cpp - @{ -*/ - -#define LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(name) \ - static const char name ## _id [] = # name ; \ - class name; \ -/**/ - -#define LIBOPENMPT_EXT_CXX_INTERFACE(name) \ - protected: \ - name () {} \ - virtual ~ name () {} \ - public: \ -/**/ - - -#ifndef LIBOPENMPT_EXT_INTERFACE_PATTERN_VIS -#define LIBOPENMPT_EXT_INTERFACE_PATTERN_VIS -#endif - -LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(pattern_vis) - -class pattern_vis { - - LIBOPENMPT_EXT_CXX_INTERFACE(pattern_vis) - - //! Pattern command type - enum effect_type { - - effect_unknown = 0, - effect_general = 1, - effect_global = 2, - effect_volume = 3, - effect_panning = 4, - effect_pitch = 5 - - }; // enum effect_type - - //! Get pattern command type for pattern highlighting - /*! - \param pattern The pattern whose data should be retrieved. - \param row The row from which the data should be retrieved. - \param channel The channel from which the data should be retrieved. - \return The command type in the effect column at the given pattern position (see openmpt::ext::pattern_vis::effect_type) - \sa openmpt::ext::pattern_vis::get_pattern_row_channel_effect_type - */ - virtual effect_type get_pattern_row_channel_volume_effect_type( std::int32_t pattern, std::int32_t row, std::int32_t channel ) const = 0; - - //! Get pattern command type for pattern highlighting - /*! - \param pattern The pattern whose data should be retrieved. - \param row The row from which the data should be retrieved. - \param channel The channel from which the data should be retrieved. - \return The command type in the volume column at the given pattern position (see openmpt::ext::pattern_vis::effect_type) - \sa openmpt::ext::pattern_vis::get_pattern_row_channel_volume_effect_type - */ - virtual effect_type get_pattern_row_channel_effect_type( std::int32_t pattern, std::int32_t row, std::int32_t channel ) const = 0; - -}; // class pattern_vis - - -#ifndef LIBOPENMPT_EXT_INTERFACE_INTERACTIVE -#define LIBOPENMPT_EXT_INTERFACE_INTERACTIVE -#endif - -LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(interactive) - -class interactive { - - LIBOPENMPT_EXT_CXX_INTERFACE(interactive) - - //! Set the current ticks per row (speed) - /*! - \param speed The new tick count in range [1, 65535]. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the speed is outside the specified range. - \remarks The tick count may be reset by pattern commands at any time. - \sa openmpt::module::get_current_speed - */ - virtual void set_current_speed( std::int32_t speed ) = 0; - - //! Set the current module tempo - /*! - \param tempo The new tempo in range [32, 512]. The exact meaning of the value depends on the tempo mode used by the module. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the tempo is outside the specified range. - \remarks The tempo may be reset by pattern commands at any time. Use openmpt::ext:interactive::set_tempo_factor to apply a tempo factor that is independent of pattern commands. - \sa openmpt::module::get_current_tempo - \deprecated Please use openmpt::ext::interactive3::set_current_tempo2(). - */ - LIBOPENMPT_ATTR_DEPRECATED virtual void set_current_tempo( std::int32_t tempo ) = 0; - - //! Set the current module tempo factor without affecting playback pitch - /*! - \param factor The new tempo factor in range ]0.0, 4.0] - 1.0 means unmodified tempo. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the factor is outside the specified range. - \remarks Modifying the tempo without applying the same pitch factor using openmpt::ext::interactive::set_pitch_factor may cause rhythmic samples (e.g. drum loops) to go out of sync. - \sa openmpt::ext::interactive::get_tempo_factor - */ - virtual void set_tempo_factor( double factor ) = 0; - - //! Gets the current module tempo factor - /*! - \return The current tempo factor. - \sa openmpt::ext::interactive::set_tempo_factor - */ - virtual double get_tempo_factor( ) const = 0; - - //! Set the current module pitch factor without affecting playback speed - /*! - \param factor The new pitch factor in range ]0.0, 4.0] - 1.0 means unmodified pitch. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the factor is outside the specified range. - \remarks Modifying the pitch without applying the the same tempo factor using openmpt::ext::interactive::set_tempo_factor may cause rhythmic samples (e.g. drum loops) to go out of sync. - \remarks To shift the pich by `n` semitones, the parameter can be calculated as follows: `pow( 2.0, n / 12.0 )` - \sa openmpt::ext::interactive::get_pitch_factor - */ - virtual void set_pitch_factor( double factor ) = 0; - - //! Gets the current module pitch factor - /*! - \return The current pitch factor. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the pitch is outside the specified range. - \sa openmpt::ext::interactive::set_pitch_factor - */ - virtual double get_pitch_factor( ) const = 0; - - //! Set the current global volume - /*! - \param volume The new global volume in range [0.0, 1.0] - \throws openmpt::exception Throws an exception derived from openmpt::exception if the volume is outside the specified range. - \remarks The global volume may be reset by pattern commands at any time. Use openmpt::module::set_render_param to apply a global overall volume factor that is independent of pattern commands. - \sa openmpt::ext::interactive::get_global_volume - */ - virtual void set_global_volume( double volume ) = 0; - - //! Get the current global volume - /*! - \return The current global volume in range [0.0, 1.0] - \sa openmpt::ext::interactive::set_global_volume - */ - virtual double get_global_volume( ) const = 0; - - //! Set the current channel volume for a channel - /*! - \param channel The channel whose volume should be set, in range [0, openmpt::module::get_num_channels()[ - \param volume The new channel volume in range [0.0, 1.0] - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel or volume is outside the specified range. - \remarks The channel volume may be reset by pattern commands at any time. - \sa openmpt::ext::interactive::get_channel_volume - */ - virtual void set_channel_volume( std::int32_t channel, double volume ) = 0; - - //! Get the current channel volume for a channel - /*! - \param channel The channel whose volume should be retrieved, in range [0, openmpt::module::get_num_channels()[ - \return The current channel volume in range [0.0, 1.0] - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. - \sa openmpt::ext::interactive::set_channel_volume - */ - virtual double get_channel_volume( std::int32_t channel ) const = 0; - - //! Set the current mute status for a channel - /*! - \param channel The channel whose mute status should be set, in range [0, openmpt::module::get_num_channels()[ - \param mute The new mute status. true is muted, false is unmuted. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. - \sa openmpt::ext::interactive::get_channel_mute_status - */ - virtual void set_channel_mute_status( std::int32_t channel, bool mute ) = 0; - - //! Get the current mute status for a channel - /*! - \param channel The channel whose mute status should be retrieved, in range [0, openmpt::module::get_num_channels()[ - \return The current channel mute status. true is muted, false is unmuted. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. - \sa openmpt::ext::interactive::set_channel_mute_status - */ - virtual bool get_channel_mute_status( std::int32_t channel ) const = 0; - - //! Set the current mute status for an instrument - /*! - \param instrument The instrument whose mute status should be set, in range [0, openmpt::module::get_num_instruments()[ if openmpt::module::get_num_instruments is not 0, otherwise in [0, openmpt::module::get_num_samples()[ - \param mute The new mute status. true is muted, false is unmuted. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the instrument is outside the specified range. - \sa openmpt::ext::interactive::get_instrument_mute_status - */ - virtual void set_instrument_mute_status( std::int32_t instrument, bool mute ) = 0; - - //! Get the current mute status for an instrument - /*! - \param instrument The instrument whose mute status should be retrieved, in range [0, openmpt::module::get_num_instruments()[ if openmpt::module::get_num_instruments is not 0, otherwise in [0, openmpt::module::get_num_samples()[ - \return The current instrument mute status. true is muted, false is unmuted. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the instrument is outside the specified range. - \sa openmpt::ext::interactive::set_instrument_mute_status - */ - virtual bool get_instrument_mute_status( std::int32_t instrument ) const = 0; - - //! Play a note using the specified instrument - /*! - \param instrument The instrument that should be played, in range [0, openmpt::module::get_num_instruments()[ if openmpt::module::get_num_instruments is not 0, otherwise in [0, openmpt::module::get_num_samples()[ - \param note The note to play, in rage [0, 119]. 60 is the middle C. - \param volume The volume at which the note should be triggered, in range [0.0, 1.0] - \param panning The panning position at which the note should be triggered, in range [-1.0, 1.0], 0.0 is center. - \return The channel on which the note is played. This can pe be passed to openmpt::ext::interactive::stop_note to stop the note. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the instrument or note is outside the specified range. - \sa openmpt::ext::interactive::stop_note - \sa openmpt::ext::interactive2::note_off - \sa openmpt::ext::interactive2::note_fade - */ - virtual std::int32_t play_note( std::int32_t instrument, std::int32_t note, double volume, double panning ) = 0; - - //! Stop the note playing on the specified channel - /*! - \param channel The channel on which the note should be stopped. This is the value returned by a previous play_note call. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. - \sa openmpt::ext::interactive::play_note - \sa openmpt::ext::interactive2::note_off - \sa openmpt::ext::interactive2::note_fade - */ - virtual void stop_note( std::int32_t channel ) = 0; - -}; // class interactive - - -#ifndef LIBOPENMPT_EXT_INTERFACE_INTERACTIVE2 -#define LIBOPENMPT_EXT_INTERFACE_INTERACTIVE2 -#endif - -LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(interactive2) - -class interactive2 { - - LIBOPENMPT_EXT_CXX_INTERFACE(interactive2) - - //! Sends a key-off command for the note playing on the specified channel - /*! - \param channel The channel on which the key-off event should be triggered. This is the value returned by a previous play_note call. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. - \remarks This method releases envelopes and sample sustain loops. If the sample has no sustain loop, or if the module does not use instruments, it does nothing. - \sa openmpt::ext::interactive::play_note - \sa openmpt::ext::interactive::stop_note - \sa openmpt::ext::interactive2::note_fade - \since 0.6.0 - */ - virtual void note_off(int32_t channel ) = 0; - - //! Sends a note fade command for the note playing on the specified channel - /*! - \param channel The channel on which the note should be faded. This is the value returned by a previous play_note call. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. - \remarks This method uses the instrument's fade-out value. If the module does not use instruments, or the instrument's fade-out value is 0, it does nothing. - \sa openmpt::ext::interactive::play_note - \sa openmpt::ext::interactive::stop_note - \sa openmpt::ext::interactive2::note_off - \since 0.6.0 - */ - virtual void note_fade(int32_t channel) = 0; - - //! Set the current panning position for a channel - /*! - \param channel The channel whose panning will be changed, in range [0, openmpt::module::get_num_channels()[ - \param panning The panning position to set on the channel, in range [-1.0, 1.0], 0.0 is center. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. - \remarks This command affects subsequent notes played on the same channel, and may itself be overridden by subsequent panning commands encountered in the module itself. - \sa openmpt::ext::interactive2::get_channel_panning - \since 0.6.0 - */ - virtual void set_channel_panning(int32_t channel, double panning ) = 0; - - //! Get the current panning position for a channel - /*! - \param channel The channel whose panning should be retrieved, in range [0, openmpt::module::get_num_channels()[ - \return The current channel panning, in range [-1.0, 1.0], 0.0 is center. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. - \sa openmpt::ext::interactive2::set_channel_panning - \since 0.6.0 - */ - virtual double get_channel_panning( int32_t channel ) = 0; - - //! Set the finetune for the currently playing note on a channel - /*! - \param channel The channel whose finetune will be changed, in range [0, openmpt::module::get_num_channels()[ - \param finetune The finetune to set on the channel, in range [-1.0, 1.0], 0.0 is center. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. - \remarks The finetune range depends on the pitch wheel depth of the instrument playing on the current channel; for sample-based modules, the depth of this command is fixed to +/-1 semitone. - \remarks This command does not affect subsequent notes played on the same channel, but may itself be overridden by subsequent finetune commands encountered in the module itself. - \sa openmpt::ext::interactive2::get_note_finetune - \since 0.6.0 - */ - virtual void set_note_finetune(int32_t channel, double finetune ) = 0; - - //! Get the finetune for the currently playing note on a channel - /*! - \param channel The channel whose finetune should be retrieved, in range [0, openmpt::module::get_num_channels()[ - \return The current channel finetune, in range [-1.0, 1.0], 0.0 is center. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. - \remarks The finetune range depends on the pitch wheel depth of the instrument playing on the current channel; for sample-based modules, the depth of this command is fixed to +/-1 semitone. - \sa openmpt::ext::interactive2::set_note_finetune - \since 0.6.0 - */ - virtual double get_note_finetune( int32_t channel ) = 0; - -}; // class interactive2 - - -#ifndef LIBOPENMPT_EXT_INTERFACE_INTERACTIVE3 -#define LIBOPENMPT_EXT_INTERFACE_INTERACTIVE3 -#endif - -LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(interactive3) - -class interactive3 { - - LIBOPENMPT_EXT_CXX_INTERFACE(interactive3) - - //! Set the current module tempo - /*! - \param tempo The new tempo in range [32, 512]. The exact meaning of the value depends on the tempo mode used by the module. - \throws openmpt::exception Throws an exception derived from openmpt::exception if the tempo is outside the specified range. - \remarks The tempo may be reset by pattern commands at any time. Use openmpt::ext:interactive::set_tempo_factor to apply a tempo factor that is independent of pattern commands. - \sa openmpt::module::get_current_tempo2 - \since 0.7.0 - */ - virtual void set_current_tempo2( double tempo ) = 0; - -}; // class interactive3 - - - -/* add stuff here */ - - - -#undef LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE -#undef LIBOPENMPT_EXT_CXX_INTERFACE - -/*! - @} -*/ - -} // namespace ext - -} // namespace openmpt - -#endif // LIBOPENMPT_EXT_HPP +/* + * libopenmpt_ext.hpp + * ------------------ + * Purpose: libopenmpt public c++ interface for libopenmpt extensions + * Notes : + * Authors: OpenMPT Devs + * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. + */ + +#ifndef LIBOPENMPT_EXT_HPP +#define LIBOPENMPT_EXT_HPP + +#include "libopenmpt_config.h" +#include "libopenmpt.hpp" + +/*! + * \page libopenmpt_ext_cpp_overview libopenmpt_ext C++ API + * + * libopenmpt_ext is now included in all builds by default. + * + * \section libopenmpt-ext-cpp-detailed Detailed documentation + * + * \ref libopenmpt_ext_cpp + * + */ + +/*! \defgroup libopenmpt_ext_cpp libopenmpt_ext C++ */ + +namespace openmpt { + +/*! \addtogroup libopenmpt_ext_cpp + @{ +*/ + +class module_ext_impl; + +class LIBOPENMPT_CXX_API_CLASS module_ext : public module { + +private: + module_ext_impl * ext_impl; +private: + // non-copyable + LIBOPENMPT_CXX_API_MEMBER module_ext( const module_ext & ); + LIBOPENMPT_CXX_API_MEMBER void operator = ( const module_ext & ); +public: + LIBOPENMPT_CXX_API_MEMBER module_ext( std::istream & stream, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER module_ext( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER module_ext( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER module_ext( const std::vector & data, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER module_ext( const std::byte * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER module_ext( const std::uint8_t * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER module_ext( const char * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER module_ext( const void * data, std::size_t size, std::ostream & log = std::clog, const std::map< std::string, std::string > & ctls = detail::initial_ctls_map() ); + LIBOPENMPT_CXX_API_MEMBER virtual ~module_ext(); + +public: + + //! Retrieve a libopenmpt extension. + /*! Example: Retrieving the interactive extension to change the tempo of a module: + \code{.cpp} + openmpt::module_ext *mod = new openmpt::module_ext( stream ); + #ifdef LIBOPENMPT_EXT_INTERFACE_INTERACTIVE + openmpt::ext::interactive *interactive = static_cast( self->mod->get_interface( openmpt::ext::interactive_id ) ); + if ( interactive ) { + interactive->set_tempo_factor( 2.0 ); // play module at double speed + } else { + // interface not available + } + #else + // interfae not available + #endif + \endcode + \param interface_id The name of the extension interface to retrieve. + \return The interface object. This may be a nullptr if the extension was not found. + */ + LIBOPENMPT_CXX_API_MEMBER void * get_interface( const std::string & interface_id ); + +}; // class module_ext + +/*! + @} +*/ + +namespace ext { + +/*! \addtogroup libopenmpt_ext_cpp + @{ +*/ + +#define LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(name) \ + static const char name ## _id [] = # name ; \ + class name; \ +/**/ + +#define LIBOPENMPT_EXT_CXX_INTERFACE(name) \ + protected: \ + name () {} \ + virtual ~ name () {} \ + public: \ +/**/ + + +#ifndef LIBOPENMPT_EXT_INTERFACE_PATTERN_VIS +#define LIBOPENMPT_EXT_INTERFACE_PATTERN_VIS +#endif + +LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(pattern_vis) + +class pattern_vis { + + LIBOPENMPT_EXT_CXX_INTERFACE(pattern_vis) + + //! Pattern command type + enum effect_type { + + effect_unknown = 0, + effect_general = 1, + effect_global = 2, + effect_volume = 3, + effect_panning = 4, + effect_pitch = 5 + + }; // enum effect_type + + //! Get pattern command type for pattern highlighting + /*! + \param pattern The pattern whose data should be retrieved. + \param row The row from which the data should be retrieved. + \param channel The channel from which the data should be retrieved. + \return The command type in the effect column at the given pattern position (see openmpt::ext::pattern_vis::effect_type) + \sa openmpt::ext::pattern_vis::get_pattern_row_channel_effect_type + */ + virtual effect_type get_pattern_row_channel_volume_effect_type( std::int32_t pattern, std::int32_t row, std::int32_t channel ) const = 0; + + //! Get pattern command type for pattern highlighting + /*! + \param pattern The pattern whose data should be retrieved. + \param row The row from which the data should be retrieved. + \param channel The channel from which the data should be retrieved. + \return The command type in the volume column at the given pattern position (see openmpt::ext::pattern_vis::effect_type) + \sa openmpt::ext::pattern_vis::get_pattern_row_channel_volume_effect_type + */ + virtual effect_type get_pattern_row_channel_effect_type( std::int32_t pattern, std::int32_t row, std::int32_t channel ) const = 0; + +}; // class pattern_vis + + +#ifndef LIBOPENMPT_EXT_INTERFACE_INTERACTIVE +#define LIBOPENMPT_EXT_INTERFACE_INTERACTIVE +#endif + +LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(interactive) + +class interactive { + + LIBOPENMPT_EXT_CXX_INTERFACE(interactive) + + //! Set the current ticks per row (speed) + /*! + \param speed The new tick count in range [1, 65535]. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the speed is outside the specified range. + \remarks The tick count may be reset by pattern commands at any time. + \sa openmpt::module::get_current_speed + */ + virtual void set_current_speed( std::int32_t speed ) = 0; + + //! Set the current module tempo + /*! + \param tempo The new tempo in range [32, 512]. The exact meaning of the value depends on the tempo mode used by the module. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the tempo is outside the specified range. + \remarks The tempo may be reset by pattern commands at any time. Use openmpt::ext:interactive::set_tempo_factor to apply a tempo factor that is independent of pattern commands. + \sa openmpt::module::get_current_tempo + \deprecated Please use openmpt::ext::interactive3::set_current_tempo2(). + */ + LIBOPENMPT_ATTR_DEPRECATED virtual void set_current_tempo( std::int32_t tempo ) = 0; + + //! Set the current module tempo factor without affecting playback pitch + /*! + \param factor The new tempo factor in range ]0.0, 4.0] - 1.0 means unmodified tempo. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the factor is outside the specified range. + \remarks Modifying the tempo without applying the same pitch factor using openmpt::ext::interactive::set_pitch_factor may cause rhythmic samples (e.g. drum loops) to go out of sync. + \sa openmpt::ext::interactive::get_tempo_factor + */ + virtual void set_tempo_factor( double factor ) = 0; + + //! Gets the current module tempo factor + /*! + \return The current tempo factor. + \sa openmpt::ext::interactive::set_tempo_factor + */ + virtual double get_tempo_factor( ) const = 0; + + //! Set the current module pitch factor without affecting playback speed + /*! + \param factor The new pitch factor in range ]0.0, 4.0] - 1.0 means unmodified pitch. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the factor is outside the specified range. + \remarks Modifying the pitch without applying the the same tempo factor using openmpt::ext::interactive::set_tempo_factor may cause rhythmic samples (e.g. drum loops) to go out of sync. + \remarks To shift the pich by `n` semitones, the parameter can be calculated as follows: `pow( 2.0, n / 12.0 )` + \sa openmpt::ext::interactive::get_pitch_factor + */ + virtual void set_pitch_factor( double factor ) = 0; + + //! Gets the current module pitch factor + /*! + \return The current pitch factor. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the pitch is outside the specified range. + \sa openmpt::ext::interactive::set_pitch_factor + */ + virtual double get_pitch_factor( ) const = 0; + + //! Set the current global volume + /*! + \param volume The new global volume in range [0.0, 1.0] + \throws openmpt::exception Throws an exception derived from openmpt::exception if the volume is outside the specified range. + \remarks The global volume may be reset by pattern commands at any time. Use openmpt::module::set_render_param to apply a global overall volume factor that is independent of pattern commands. + \sa openmpt::ext::interactive::get_global_volume + */ + virtual void set_global_volume( double volume ) = 0; + + //! Get the current global volume + /*! + \return The current global volume in range [0.0, 1.0] + \sa openmpt::ext::interactive::set_global_volume + */ + virtual double get_global_volume( ) const = 0; + + //! Set the current channel volume for a channel + /*! + \param channel The channel whose volume should be set, in range [0, openmpt::module::get_num_channels()[ + \param volume The new channel volume in range [0.0, 1.0] + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel or volume is outside the specified range. + \remarks The channel volume may be reset by pattern commands at any time. + \sa openmpt::ext::interactive::get_channel_volume + */ + virtual void set_channel_volume( std::int32_t channel, double volume ) = 0; + + //! Get the current channel volume for a channel + /*! + \param channel The channel whose volume should be retrieved, in range [0, openmpt::module::get_num_channels()[ + \return The current channel volume in range [0.0, 1.0] + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. + \sa openmpt::ext::interactive::set_channel_volume + */ + virtual double get_channel_volume( std::int32_t channel ) const = 0; + + //! Set the current mute status for a channel + /*! + \param channel The channel whose mute status should be set, in range [0, openmpt::module::get_num_channels()[ + \param mute The new mute status. true is muted, false is unmuted. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. + \sa openmpt::ext::interactive::get_channel_mute_status + */ + virtual void set_channel_mute_status( std::int32_t channel, bool mute ) = 0; + + //! Get the current mute status for a channel + /*! + \param channel The channel whose mute status should be retrieved, in range [0, openmpt::module::get_num_channels()[ + \return The current channel mute status. true is muted, false is unmuted. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. + \sa openmpt::ext::interactive::set_channel_mute_status + */ + virtual bool get_channel_mute_status( std::int32_t channel ) const = 0; + + //! Set the current mute status for an instrument + /*! + \param instrument The instrument whose mute status should be set, in range [0, openmpt::module::get_num_instruments()[ if openmpt::module::get_num_instruments is not 0, otherwise in [0, openmpt::module::get_num_samples()[ + \param mute The new mute status. true is muted, false is unmuted. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the instrument is outside the specified range. + \sa openmpt::ext::interactive::get_instrument_mute_status + */ + virtual void set_instrument_mute_status( std::int32_t instrument, bool mute ) = 0; + + //! Get the current mute status for an instrument + /*! + \param instrument The instrument whose mute status should be retrieved, in range [0, openmpt::module::get_num_instruments()[ if openmpt::module::get_num_instruments is not 0, otherwise in [0, openmpt::module::get_num_samples()[ + \return The current instrument mute status. true is muted, false is unmuted. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the instrument is outside the specified range. + \sa openmpt::ext::interactive::set_instrument_mute_status + */ + virtual bool get_instrument_mute_status( std::int32_t instrument ) const = 0; + + //! Play a note using the specified instrument + /*! + \param instrument The instrument that should be played, in range [0, openmpt::module::get_num_instruments()[ if openmpt::module::get_num_instruments is not 0, otherwise in [0, openmpt::module::get_num_samples()[ + \param note The note to play, in rage [0, 119]. 60 is the middle C. + \param volume The volume at which the note should be triggered, in range [0.0, 1.0] + \param panning The panning position at which the note should be triggered, in range [-1.0, 1.0], 0.0 is center. + \return The channel on which the note is played. This can pe be passed to openmpt::ext::interactive::stop_note to stop the note. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the instrument or note is outside the specified range. + \sa openmpt::ext::interactive::stop_note + \sa openmpt::ext::interactive2::note_off + \sa openmpt::ext::interactive2::note_fade + */ + virtual std::int32_t play_note( std::int32_t instrument, std::int32_t note, double volume, double panning ) = 0; + + //! Stop the note playing on the specified channel + /*! + \param channel The channel on which the note should be stopped. This is the value returned by a previous play_note call. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. + \sa openmpt::ext::interactive::play_note + \sa openmpt::ext::interactive2::note_off + \sa openmpt::ext::interactive2::note_fade + */ + virtual void stop_note( std::int32_t channel ) = 0; + +}; // class interactive + + +#ifndef LIBOPENMPT_EXT_INTERFACE_INTERACTIVE2 +#define LIBOPENMPT_EXT_INTERFACE_INTERACTIVE2 +#endif + +LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(interactive2) + +class interactive2 { + + LIBOPENMPT_EXT_CXX_INTERFACE(interactive2) + + //! Sends a key-off command for the note playing on the specified channel + /*! + \param channel The channel on which the key-off event should be triggered. This is the value returned by a previous play_note call. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. + \remarks This method releases envelopes and sample sustain loops. If the sample has no sustain loop, or if the module does not use instruments, it does nothing. + \sa openmpt::ext::interactive::play_note + \sa openmpt::ext::interactive::stop_note + \sa openmpt::ext::interactive2::note_fade + \since 0.6.0 + */ + virtual void note_off(int32_t channel ) = 0; + + //! Sends a note fade command for the note playing on the specified channel + /*! + \param channel The channel on which the note should be faded. This is the value returned by a previous play_note call. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. + \remarks This method uses the instrument's fade-out value. If the module does not use instruments, or the instrument's fade-out value is 0, it does nothing. + \sa openmpt::ext::interactive::play_note + \sa openmpt::ext::interactive::stop_note + \sa openmpt::ext::interactive2::note_off + \since 0.6.0 + */ + virtual void note_fade(int32_t channel) = 0; + + //! Set the current panning position for a channel + /*! + \param channel The channel whose panning will be changed, in range [0, openmpt::module::get_num_channels()[ + \param panning The panning position to set on the channel, in range [-1.0, 1.0], 0.0 is center. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. + \remarks This command affects subsequent notes played on the same channel, and may itself be overridden by subsequent panning commands encountered in the module itself. + \sa openmpt::ext::interactive2::get_channel_panning + \since 0.6.0 + */ + virtual void set_channel_panning(int32_t channel, double panning ) = 0; + + //! Get the current panning position for a channel + /*! + \param channel The channel whose panning should be retrieved, in range [0, openmpt::module::get_num_channels()[ + \return The current channel panning, in range [-1.0, 1.0], 0.0 is center. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. + \sa openmpt::ext::interactive2::set_channel_panning + \since 0.6.0 + */ + virtual double get_channel_panning( int32_t channel ) = 0; + + //! Set the finetune for the currently playing note on a channel + /*! + \param channel The channel whose finetune will be changed, in range [0, openmpt::module::get_num_channels()[ + \param finetune The finetune to set on the channel, in range [-1.0, 1.0], 0.0 is center. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel index is invalid. + \remarks The finetune range depends on the pitch wheel depth of the instrument playing on the current channel; for sample-based modules, the depth of this command is fixed to +/-1 semitone. + \remarks This command does not affect subsequent notes played on the same channel, but may itself be overridden by subsequent finetune commands encountered in the module itself. + \sa openmpt::ext::interactive2::get_note_finetune + \since 0.6.0 + */ + virtual void set_note_finetune(int32_t channel, double finetune ) = 0; + + //! Get the finetune for the currently playing note on a channel + /*! + \param channel The channel whose finetune should be retrieved, in range [0, openmpt::module::get_num_channels()[ + \return The current channel finetune, in range [-1.0, 1.0], 0.0 is center. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the channel is outside the specified range. + \remarks The finetune range depends on the pitch wheel depth of the instrument playing on the current channel; for sample-based modules, the depth of this command is fixed to +/-1 semitone. + \sa openmpt::ext::interactive2::set_note_finetune + \since 0.6.0 + */ + virtual double get_note_finetune( int32_t channel ) = 0; + +}; // class interactive2 + + +#ifndef LIBOPENMPT_EXT_INTERFACE_INTERACTIVE3 +#define LIBOPENMPT_EXT_INTERFACE_INTERACTIVE3 +#endif + +LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE(interactive3) + +class interactive3 { + + LIBOPENMPT_EXT_CXX_INTERFACE(interactive3) + + //! Set the current module tempo + /*! + \param tempo The new tempo in range [32, 512]. The exact meaning of the value depends on the tempo mode used by the module. + \throws openmpt::exception Throws an exception derived from openmpt::exception if the tempo is outside the specified range. + \remarks The tempo may be reset by pattern commands at any time. Use openmpt::ext:interactive::set_tempo_factor to apply a tempo factor that is independent of pattern commands. + \sa openmpt::module::get_current_tempo2 + \since 0.7.0 + */ + virtual void set_current_tempo2( double tempo ) = 0; + +}; // class interactive3 + + + +/* add stuff here */ + + + +#undef LIBOPENMPT_DECLARE_EXT_CXX_INTERFACE +#undef LIBOPENMPT_EXT_CXX_INTERFACE + +/*! + @} +*/ + +} // namespace ext + +} // namespace openmpt + +#endif // LIBOPENMPT_EXT_HPP diff --git a/libs/libopenmpt/inc/libopenmpt/libopenmpt_version.h b/libs/libopenmpt/inc/libopenmpt/libopenmpt_version.h index 6191fb5a1..d006c9ed3 100644 --- a/libs/libopenmpt/inc/libopenmpt/libopenmpt_version.h +++ b/libs/libopenmpt/inc/libopenmpt/libopenmpt_version.h @@ -21,7 +21,7 @@ /*! \brief libopenmpt minor version number */ #define OPENMPT_API_VERSION_MINOR 7 /*! \brief libopenmpt patch version number */ -#define OPENMPT_API_VERSION_PATCH 2 +#define OPENMPT_API_VERSION_PATCH 3 /*! \brief libopenmpt pre-release tag */ #define OPENMPT_API_VERSION_PREREL "" /*! \brief libopenmpt pre-release flag */ diff --git a/libs/libopenmpt/lib/x86/libopenmpt.lib b/libs/libopenmpt/lib/x86/libopenmpt.lib index 4ae31a98e..6f42fb2b0 100644 Binary files a/libs/libopenmpt/lib/x86/libopenmpt.lib and b/libs/libopenmpt/lib/x86/libopenmpt.lib differ diff --git a/libs/libopenmpt/lib/x86/mingw/libopenmpt.dll.a b/libs/libopenmpt/lib/x86/mingw/libopenmpt.dll.a deleted file mode 100644 index 1d7637253..000000000 Binary files a/libs/libopenmpt/lib/x86/mingw/libopenmpt.dll.a and /dev/null differ diff --git a/libs/libopenmpt/lib/x86_64/libopenmpt.lib b/libs/libopenmpt/lib/x86_64/libopenmpt.lib index 2b62077c9..e2d30a94d 100644 Binary files a/libs/libopenmpt/lib/x86_64/libopenmpt.lib and b/libs/libopenmpt/lib/x86_64/libopenmpt.lib differ diff --git a/org.srb2.SRB2Kart-Saturn.desktop b/org.srb2.SRB2Kart-Saturn.desktop new file mode 100644 index 000000000..e0282b90f --- /dev/null +++ b/org.srb2.SRB2Kart-Saturn.desktop @@ -0,0 +1,20 @@ +[Desktop Entry] +Version=1.0 +Type=Application +Name=Sonic Robo Blast 2 Kart Saturn +Comment=A kart racing mod based on the 3D Sonic the Hedgehog fangame Sonic Robo Blast 2 +TryExec=srb2kart.sh +Exec=srb2kart.sh +Icon=org.srb2.SRB2Kart-Saturn +Terminal=false +Categories=Game;SportsGame; +Keywords=kart;sonic;racer;multiplayer;doom; +Actions=OpenGL;Software; + +[Desktop Action OpenGL] +Name=OpenGL renderer +Exec=srb2kart.sh -opengl + +[Desktop Action Software] +Name=Software renderer +Exec=srb2kart.sh -software diff --git a/org.srb2.SRB2Kart-Saturn.metainfo.xml b/org.srb2.SRB2Kart-Saturn.metainfo.xml new file mode 100644 index 000000000..54c1de8b2 --- /dev/null +++ b/org.srb2.SRB2Kart-Saturn.metainfo.xml @@ -0,0 +1,80 @@ + + + + org.srb2.SRB2Kart-Saturn + FSFAP + GPL-2.0+ + Sonic Robo Blast 2 Kart Saturn + Modded SRB2Kart adding many custom features + +

+ A modded net-compatible version of SRB2Kart v1.6 that offers multiple code optimizations, palette rendering, player sprite rotation, base Kart HUD customization, and many more. +

+
+ org.srb2.SRB2Kart-Saturn.desktop + + + https://wiki.srb2.org/w/images/a/ac/Srb2kart_title.png + Title screen + + + https://user-images.githubusercontent.com/15758649/227740700-26e0962b-5572-486c-b633-7d4990d86f89.png + Game modes + + + https://user-images.githubusercontent.com/1964655/82821921-3d180c00-9ea5-11ea-937b-e1f53fe6c686.png + Game play as Sonic + + + https://user-images.githubusercontent.com/1964655/82821933-41442980-9ea5-11ea-9146-38998161edae.png + Game play as Tails + + + https://user-images.githubusercontent.com/1964655/82821966-502adc00-9ea5-11ea-9cbd-274d7adb479e.png + Game play as Eggman + + + https://user-images.githubusercontent.com/1964655/82821980-5620bd00-9ea5-11ea-9eec-2835ebb2a262.png + Game play as Metal Sonic + + + https://github.com/Indev450/SRB2Kart-Saturn + https://github.com/Indev450/SRB2Kart-Saturn/issues + Indev450 + + srb2kart + + + + +

The complete changelog can be found on the build's GitHub repository.

+
+ https://github.com/Indev450/SRB2Kart-Saturn/releases/tag/v5.1 +
+ + +

The complete changelog can be found on the build's GitHub repository.

+
+ https://github.com/Indev450/SRB2Kart-Saturn/releases/tag/v5 +
+
+ + Game + SportsGame + + + keyboard + gamepad + + + moderate + mild + intense + mild + + + doom + multiplayer + racing + +
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 50f3f813a..3743118c8 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -3,7 +3,6 @@ # Core sources set(SRB2_CORE_SOURCES am_map.c - args.c b_bot.c command.c comptime.c @@ -53,7 +52,6 @@ set(SRB2_CORE_SOURCES set(SRB2_CORE_HEADERS am_map.h - args.h b_bot.h byteptr.h command.h @@ -107,7 +105,6 @@ set(SRB2_CORE_HEADERS m_swap.h md5.h mserv.h - p5prof.h s_sound.h screen.h sounds.h @@ -457,6 +454,8 @@ endif() if(${SRB2_CONFIG_HWRENDER}) add_definitions(-DHWRENDER) set(SRB2_HWRENDER_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_batching.c + ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_shaders.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_bsp.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_cache.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_clip.c @@ -472,6 +471,8 @@ if(${SRB2_CONFIG_HWRENDER}) ) set (SRB2_HWRENDER_HEADERS + ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_batching.h + ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_shaders.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_clip.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_data.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_defs.h diff --git a/src/Makefile b/src/Makefile index 717f881a0..cf1cfb006 100644 --- a/src/Makefile +++ b/src/Makefile @@ -275,7 +275,7 @@ else OPTS+=-DHWRENDER OBJS+=$(OBJDIR)/hw_bsp.o $(OBJDIR)/hw_draw.o $(OBJDIR)/hw_light.o \ $(OBJDIR)/hw_main.o $(OBJDIR)/hw_clip.o $(OBJDIR)/hw_md2.o $(OBJDIR)/hw_cache.o $(OBJDIR)/hw_trick.o \ - $(OBJDIR)/hw_md2load.o $(OBJDIR)/hw_md3load.o $(OBJDIR)/hw_model.o $(OBJDIR)/u_list.o + $(OBJDIR)/hw_md2load.o $(OBJDIR)/hw_md3load.o $(OBJDIR)/hw_model.o $(OBJDIR)/u_list.o $(OBJDIR)/hw_batching.o $(OBJDIR)/hw_shaders.o endif OPTS += -DCOMPVERSION @@ -538,7 +538,6 @@ OBJS:=$(i_main_o) \ $(OBJDIR)/i_time.o \ $(OBJDIR)/lzf.o \ $(OBJDIR)/b_bot.o \ - $(OBJDIR)/args.o \ $(i_net_o) \ $(i_system_o) \ $(i_sound_o) \ diff --git a/src/android/i_cdmus.c b/src/android/i_cdmus.c deleted file mode 100644 index 426bc5dc9..000000000 --- a/src/android/i_cdmus.c +++ /dev/null @@ -1,37 +0,0 @@ -#include "../command.h" -#include "../s_sound.h" -#include "../i_sound.h" - -// -// CD MUSIC I/O -// - -UINT8 cdaudio_started = 0; - -consvar_t cd_volume = {"cd_volume","18",CV_SAVE,soundvolume_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cdUpdate = {"cd_update","1",CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; - - -void I_InitCD(void){} - -void I_StopCD(void){} - -void I_PauseCD(void){} - -void I_ResumeCD(void){} - -void I_ShutdownCD(void){} - -void I_UpdateCD(void){} - -void I_PlayCD(UINT8 track, UINT8 looping) -{ - (void)track; - (void)looping; -} - -boolean I_SetVolumeCD(INT32 volume) -{ - (void)volume; - return false; -} diff --git a/src/apng.h b/src/apng.h index aa7fac3df..0f22dca6d 100644 --- a/src/apng.h +++ b/src/apng.h @@ -24,12 +24,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define APNG_H #ifndef _MSC_VER -#ifndef _WII #ifndef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE #endif #endif -#endif #ifndef _LFS64_LARGEFILE #define _LFS64_LARGEFILE diff --git a/src/args.c b/src/args.c deleted file mode 100644 index 88eec9092..000000000 --- a/src/args.c +++ /dev/null @@ -1,1309 +0,0 @@ -#include "doomtype.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "args.h" -#include "command.h" -#include "m_misc.h" - - -/* ------------------ */ -/* Utility functions. */ -/* ------------------ */ - - -// Prints a message to the console marking it as an error. -static void err(const char* msg) { - CONS_Alert(CONS_ERROR, "%s\n", msg); -} - -// Duplicates a string, automatically allocating memory for the copy. -// Returns NULL if memory cannot be allocated for the copy. -static char* str_dup(const char* string) { - size_t len = strlen(string) + 1; - char *copy = malloc(len); - return copy ? memcpy(copy, string, len) : NULL; -} - - -// Hashes a string using the FNV-1a algorithm. -static uint32_t str_hash(const char* string) { - uint32_t hash = 2166136261u; - size_t length = strlen(string); - for (size_t i = 0; i < length; i++) { - hash ^= (uint8_t)string[i]; - hash *= 16777619; - } - return hash; -} - - -// Attempts to parse a string as an integer value, exiting on failure. -static int try_str_to_int(const char* string) { - char *endptr; - errno = 0; - long result = strtol(string, &endptr, 0); - if (errno == ERANGE || result > INT_MAX || result < INT_MIN) { - err(va("'%s' is out of range", string)); - } - if (*endptr != '\0') { - err(va("cannot parse '%s' as an integer", string)); - } - return (int) result; -} - - -// Attempts to parse a string as a double value, exiting on failure. -static double try_str_to_double(const char* string) { - char *endptr; - errno = 0; - double result = strtod(string, &endptr); - if (errno == ERANGE) { - err(va("'%s' is out of range", string)); - } - if (*endptr != '\0') { - err(va("cannot parse '%s' as a floating-point value", string)); - } - return result; -} - - -/* --------------------------------- */ -/* Vec: a dynamic array of pointers. */ -/* --------------------------------- */ - - -typedef struct { - int count; - int capacity; - void** entries; -} Vec; - - -static Vec* vec_new() { - Vec* vec = malloc(sizeof(Vec)); - if (!vec) { - return NULL; - } - vec->count = 0; - vec->capacity = 0; - vec->entries = NULL; - return vec; -} - - -static void vec_free(Vec* vec) { - if (vec) { - free(vec->entries); - free(vec); - } -} - - -static boolean vec_add(Vec* vec, void* entry) { - if (vec->count + 1 > vec->capacity) { - int new_capacity = vec->capacity < 8 ? 8 : vec->capacity * 2; - void** new_array = realloc(vec->entries, sizeof(void*) * new_capacity); - if (!new_array) { - return false; - } - vec->entries = new_array; - vec->capacity = new_capacity; - } - vec->entries[vec->count] = entry; - vec->count++; - return true; -} - - -/* ------------------------------------------------------------------- */ -/* Map: a linear-probing hash map with string-keys and pointer-values. */ -/* ------------------------------------------------------------------- */ - - -// The map automatically grows to keep count/capacity < MAP_MAX_LOAD. -// This data structure performs optimally when it's less than half-full. -#define MAP_MAX_LOAD 0.5 - - -typedef struct { - char* key; - void* value; - uint32_t key_hash; -} MapEntry; - - -typedef struct { - int count; - int capacity; - int max_load_threshold; - MapEntry* entries; -} Map; - - -static Map* map_new() { - Map* map = malloc(sizeof(Map)); - if (!map) { - return NULL; - } - map->count = 0; - map->capacity = 0; - map->max_load_threshold = 0; - map->entries = NULL; - return map; -} - - -static void map_free(Map* map) { - if (map) { - for (int i = 0; i < map->capacity; i++) { - MapEntry* entry = &map->entries[i]; - if (entry->key != NULL) { - free(entry->key); - } - } - free(map->entries); - free(map); - } -} - - -static MapEntry* map_find(Map* map, const char* key, uint32_t key_hash) { - // Capacity is always a power of 2 so we can use bitwise-AND as a fast - // modulo operator, i.e. this is equivalent to: index = key_hash % capacity. - size_t index = key_hash & (map->capacity - 1); - - for (;;) { - MapEntry* entry = &map->entries[index]; - if (entry->key == NULL) { - return entry; - } else if (key_hash == entry->key_hash && strcmp(key, entry->key) == 0) { - return entry; - } - index = (index + 1) & (map->capacity - 1); - } -} - - -static boolean map_grow(Map* map) { - MapEntry* old_entries = map->entries; - int old_capacity = map->capacity; - int new_capacity = old_capacity < 8 ? 8 : old_capacity * 2; - - MapEntry* new_entries = malloc(sizeof(MapEntry) * new_capacity); - if (!new_entries) { - return false; - } - - for (int i = 0; i < new_capacity; i++) { - new_entries[i].key = NULL; - } - - map->count = 0; - map->capacity = new_capacity; - map->max_load_threshold = new_capacity * MAP_MAX_LOAD; - map->entries = new_entries; - - for (int i = 0; i < old_capacity; i++) { - MapEntry* src = &old_entries[i]; - if (src->key == NULL) continue; - - MapEntry* dst = map_find(map, src->key, src->key_hash); - dst->key = src->key; - dst->value = src->value; - dst->key_hash = src->key_hash; - map->count++; - } - - free(old_entries); - return true; -} - - -// Returns true if the key was found. -static boolean map_get(Map* map, const char* key, void** value) { - if (map->count == 0) return false; - - uint32_t key_hash = str_hash(key); - MapEntry* entry = map_find(map, key, key_hash); - if (entry->key == NULL) return false; - - *value = entry->value; - return true; -} - - -// Adds a new entry to the map or updates the value of an existing entry. -// (Note that the map stores its own internal copy of the key string.) -static boolean map_set(Map* map, const char* key, void* value) { - if (map->count == map->max_load_threshold) { - if (!map_grow(map)) { - return false; - } - } - - uint32_t key_hash = str_hash(key); - MapEntry* entry = map_find(map, key, key_hash); - if (entry->key == NULL) { - char* key_copy = str_dup(key); - if (!key_copy) { - return false; - } - map->count++; - entry->key = key_copy; - entry->value = value; - entry->key_hash = key_hash; - } else { - entry->value = value; - } - - return true; -} - - -// Convenience wrapper for map_set(). This splits the key string into space- -// separated words and adds a separate entry to the map for each word. -static boolean map_set_splitkey(Map* map, const char* key_string, void* value) { - char *copy_of_key_string = str_dup(key_string); - if (!copy_of_key_string) { - return false; - } - - char* word_start = copy_of_key_string; - char* string_end = word_start + strlen(copy_of_key_string); - - while (word_start < string_end) { - if (*word_start == ' ') { - word_start++; - continue; - } - - char* word_end = word_start; - while (true) { - if (*word_end == ' ' || *word_end == '\0') { - break; - } - word_end++; - } - *word_end = '\0'; - - if (!map_set(map, word_start, value)) { - free(copy_of_key_string); - return false; - } - - word_start = word_end + 1; - } - - free(copy_of_key_string); - return true; -} - - -/* -------- */ -/* Options. */ -/* -------- */ - - -typedef enum { - OPT_FLAG, - OPT_STR, - OPT_INT, - OPT_DBL, -} OptionType; - - -typedef union { - char* str_val; - int int_val; - double dbl_val; -} OptionValue; - - -typedef struct { - OptionType type; - int count; - int capacity; - OptionValue* values; - OptionValue fallback; -} Option; - - -static void option_free(Option* opt) { - if (opt) { - free(opt->values); - free(opt); - } -} - - -static boolean option_append_value(Option* opt, OptionValue value) { - if (opt->count + 1 > opt->capacity) { - int new_capacity = opt->capacity < 4 ? 4 : opt->capacity * 2; - OptionValue* new_array = realloc(opt->values, sizeof(OptionValue) * new_capacity); - if (!new_array) { - return false; - } - opt->capacity = new_capacity; - opt->values = new_array; - } - opt->values[opt->count] = value; - opt->count++; - return true; -} - - -static boolean option_try_set(Option* opt, char* arg) { - if (opt->type == OPT_STR) { - return option_append_value(opt, (OptionValue){.str_val = arg}); - } - else if (opt->type == OPT_INT) { - int value = try_str_to_int(arg); - return option_append_value(opt, (OptionValue){.int_val = value}); - } - else if (opt->type == OPT_DBL) { - double value = try_str_to_double(arg); - return option_append_value(opt, (OptionValue){.dbl_val = value}); - } - assert(false); - return false; -} - - -static Option* option_new() { - Option *option = malloc(sizeof(Option)); - if (!option) { - return NULL; - } - option->count = 0; - option->capacity = 0; - option->values = NULL; - return option; -} - - -static Option* option_new_flag() { - Option *opt = option_new(); - if (!opt) { - return NULL; - } - opt->type = OPT_FLAG; - return opt; -} - - -static Option* option_new_str(char* fallback) { - Option *opt = option_new(); - if (!opt) { - return NULL; - } - opt->type = OPT_STR; - opt->fallback = (OptionValue){.str_val = fallback}; - return opt; -} - - -static Option* option_new_int(int fallback) { - Option *opt = option_new(); - if (!opt) { - return NULL; - } - opt->type = OPT_INT; - opt->fallback = (OptionValue){.int_val = fallback}; - return opt; -} - - -static Option* option_new_double(double fallback) { - Option *opt = option_new(); - if (!opt) { - return NULL; - } - opt->type = OPT_DBL; - opt->fallback = (OptionValue){.dbl_val = fallback}; - return opt; -} - - -static char* option_get_str(Option* opt) { - if (opt->count > 0) { - return opt->values[opt->count - 1].str_val; - } - return opt->fallback.str_val; -} - - -static int option_get_int(Option* opt) { - if (opt->count > 0) { - return opt->values[opt->count - 1].int_val; - } - return opt->fallback.int_val; -} - - -static double option_get_double(Option* opt) { - if (opt->count > 0) { - return opt->values[opt->count - 1].dbl_val; - } - return opt->fallback.dbl_val; -} - - -// Returns the option's values as a freshly-allocated array of string pointers. -static char** option_get_str_list(Option* opt) { - if (opt->count == 0) { - return NULL; - } - char** list = malloc(sizeof(char*) * opt->count); - if (!list) { - return NULL; - } - for (int i = 0; i < opt->count; i++) { - list[i] = opt->values[i].str_val; - } - return list; -} - - -// Returns the option's values as a freshly-allocated array of integers. -static int* option_get_int_list(Option* opt) { - if (opt->count == 0) { - return NULL; - } - int* list = malloc(sizeof(int) * opt->count ); - if (!list) { - return NULL; - } - for (int i = 0; i < opt->count ; i++) { - list[i] = opt->values[i].int_val; - } - return list; -} - - -// Returns the option's values as a freshly-allocated array of doubles. -static double* option_get_double_list(Option* opt) { - if (opt->count == 0) { - return NULL; - } - double* list = malloc(sizeof(double) * opt->count ); - if (!list) { - return NULL; - } - for (int i = 0; i < opt->count ; i++) { - list[i] = opt->values[i].dbl_val; - } - return list; -} - - -// Returns a freshly-allocated state-string for debugging. -static char* option_to_str(Option* opt) { - if (opt->type == OPT_FLAG) { - return va("%i", opt->count); - } - - char *fallback = NULL; - if (opt->type == OPT_STR) { - fallback = str_dup(opt->fallback.str_val); - } else if (opt->type == OPT_INT) { - fallback = va("%i", opt->fallback.int_val); - } else if (opt->type == OPT_DBL) { - fallback = va("%f", opt->fallback.dbl_val); - } - - char *values = str_dup(""); - for (int i = 0; i < opt->count; i++) { - char *value = NULL; - if (opt->type == OPT_STR) { - value = str_dup(opt->values[i].str_val); - } else if (opt->type == OPT_INT) { - value = va("%i", opt->values[i].int_val); - } else if (opt->type == OPT_DBL) { - value = va("%f", opt->values[i].dbl_val); - } - char *old_values = values; - if (i == 0) { - values = str_dup(value); - } else { - values = va("%s, %s", old_values, value); - } - free(old_values); - free(value); - } - - char *output = va("(%s) [%s]", fallback, values); - free(fallback); - free(values); - return output; -} - - -/* ----------------------------------------------------- */ -/* ArgStream: a wrapper for an array of string pointers. */ -/* ----------------------------------------------------- */ - - -typedef struct ArgStream { - int count; - int index; - char** args; -} ArgStream; - - -static ArgStream* argstream_new(int count, char** args) { - ArgStream* stream = malloc(sizeof(ArgStream)); - if (!stream) { - return NULL; - } - stream->count = count; - stream->index = 0; - stream->args = args; - return stream; -} - - -static void argstream_free(ArgStream* stream) { - free(stream); -} - - -static char* argstream_next(ArgStream* stream) { - return stream->args[stream->index++]; -} - - -static boolean argstream_has_next(ArgStream* stream) { - return stream->index < stream->count; -} - - -/* ----------------- */ -/* ArgParser: setup. */ -/* ----------------- */ - - -struct ArgParser { - char* helptext; - char* version; - Vec* option_vec; - Map* option_map; - Vec* command_vec; - Map* command_map; - Vec* positional_args; - ap_callback_t callback; - char* cmd_name; - struct ArgParser* cmd_parser; - boolean enable_help_command; - boolean had_memory_error; - struct ArgParser* parent; - boolean first_positional_arg_ends_options; -}; - - -ArgParser* ap_new() { - ArgParser *parser = malloc(sizeof(ArgParser)); - if (!parser) { - return NULL; - } - - parser->helptext = NULL; - parser->version = NULL; - parser->callback = NULL; - parser->cmd_name = NULL; - parser->cmd_parser = NULL; - parser->enable_help_command = false; - parser->had_memory_error = false; - parser->parent = NULL; - parser->first_positional_arg_ends_options = false; - - parser->option_vec = NULL; - parser->option_map = NULL; - parser->command_vec = NULL; - parser->command_map = NULL; - parser->positional_args = NULL; - - parser->option_vec = vec_new(); - if (!parser->option_vec) { - ap_free(parser); - return NULL; - } - - parser->option_map = map_new(); - if (!parser->option_map) { - ap_free(parser); - return NULL; - } - - parser->command_vec = vec_new(); - if (!parser->command_vec) { - ap_free(parser); - return NULL; - } - - parser->command_map = map_new(); - if (!parser->command_map) { - ap_free(parser); - return NULL; - } - - parser->positional_args = vec_new(); - if (!parser->positional_args) { - ap_free(parser); - return NULL; - } - - return parser; -} - - -void ap_free(ArgParser* parser) { - if (!parser) { - return; - } - - free(parser->helptext); - free(parser->version); - - if (parser->option_map) { - map_free(parser->option_map); - } - - if (parser->option_vec) { - for (int i = 0; i < parser->option_vec->count; i++) { - option_free(parser->option_vec->entries[i]); - } - vec_free(parser->option_vec); - } - - if (parser->command_map) { - map_free(parser->command_map); - } - - if (parser->command_vec) { - for (int i = 0; i < parser->command_vec->count; i++) { - ap_free(parser->command_vec->entries[i]); - } - vec_free(parser->command_vec); - } - - if (parser->positional_args) { - vec_free(parser->positional_args); - } - - free(parser); -} - - -static void ap_set_memory_error_flag(ArgParser* parser) { - parser->had_memory_error = true; - - ArgParser* parent = parser->parent; - while (parent) { - parent->had_memory_error = true; - parent = parent->parent; - } -} - - -void ap_set_helptext(ArgParser* parser, const char* helptext) { - free(parser->helptext); - parser->helptext = NULL; - - if (helptext) { - parser->helptext = str_dup(helptext); - if (!parser->helptext) { - ap_set_memory_error_flag(parser); - } - } -} - - -char* ap_get_helptext(ArgParser* parser) { - return parser->helptext; -} - - -void ap_set_version(ArgParser* parser, const char* version) { - free(parser->version); - parser->version = NULL; - - if (version) { - parser->version = str_dup(version); - if (!parser->version) { - ap_set_memory_error_flag(parser); - } - } -} - - -char* ap_get_version(ArgParser* parser) { - return parser->version; -} - - -void ap_first_pos_arg_ends_options(ArgParser* parser, boolean enable) { - parser->first_positional_arg_ends_options = enable; -} - - -/* -------------------------------------- */ -/* ArgParser: register flags and options. */ -/* -------------------------------------- */ - - -static void ap_register_option(ArgParser* parser, const char* name, Option* opt) { - if (!opt) { - ap_set_memory_error_flag(parser); - return; - } - - if (vec_add(parser->option_vec, opt)) { - if (map_set_splitkey(parser->option_map, name, opt)) { - return; - } else { - ap_set_memory_error_flag(parser); - parser->option_vec->count--; - option_free(opt); - return; - } - } else { - ap_set_memory_error_flag(parser); - option_free(opt); - return; - } -} - - -// Register a new flag. -void ap_flag(ArgParser *parser, const char* name) { - Option* opt = option_new_flag(); - ap_register_option(parser, name, opt); -} - - -// Register a new string-valued option. -void ap_str_opt(ArgParser* parser, const char* name, const char* fallback) { - Option* opt = option_new_str((char*)fallback); - ap_register_option(parser, name, opt); -} - - -// Register a new integer-valued option. -void ap_int_opt(ArgParser* parser, const char* name, int fallback) { - Option* opt = option_new_int(fallback); - ap_register_option(parser, name, opt); -} - - -// Register a new double-valued option. -void ap_dbl_opt(ArgParser* parser, const char* name, double fallback) { - Option* opt = option_new_double(fallback); - ap_register_option(parser, name, opt); -} - - -/* ---------------------------------- */ -/* ArgParser: flag and option values. */ -/* ---------------------------------- */ - - -// Retrieve an Option instance by name. -static Option* ap_get_opt(ArgParser* parser, const char* name) { - void* opt; - if (!map_get(parser->option_map, name, &opt)) { - err(va("'%s' is not a registered flag or option name", name)); - } - return (Option*)opt; -} - - -// Returns the number of times the specified flag or option was found. -int ap_count(ArgParser* parser, const char* name) { - Option* opt = ap_get_opt(parser, name); - return opt->count; -} - - -// Returns true if the specified flag or option was found. -boolean ap_found(ArgParser* parser, const char* name) { - Option* opt = ap_get_opt(parser, name); - return opt->count > 0; -} - - -// Returns the value of the specified string option. -char* ap_str_value(ArgParser* parser, const char* name) { - Option* opt = ap_get_opt(parser, name); - return (char*)option_get_str(opt); -} - - -// Returns the string value at the specified index. -char* ap_str_value_at_index(ArgParser* parser, const char* name, int index) { - Option* opt = ap_get_opt(parser, name); - return opt->values[index].str_val; -} - - -// Returns the value of the specified integer option. -int ap_int_value(ArgParser* parser, const char* name) { - Option* opt = ap_get_opt(parser, name); - return option_get_int(opt); -} - - -// Returns the integer value at the specified index. -int ap_int_value_at_index(ArgParser* parser, const char* name, int index) { - Option* opt = ap_get_opt(parser, name); - return opt->values[index].int_val; -} - - -// Returns the value of the specified floating-point option. -double ap_dbl_value(ArgParser* parser, const char* name) { - Option* opt = ap_get_opt(parser, name); - return option_get_double(opt); -} - - -// Returns the floating-point value at the specified index. -double ap_dbl_value_at_index(ArgParser* parser, const char* name, int index) { - Option* opt = ap_get_opt(parser, name); - return opt->values[index].dbl_val; -} - - -// Returns an option's values as a freshly-allocated array of string pointers. -// The array's memory is not affected by calls to ap_free(). -// Returns NULL if memory cannot be allocated for the array. -char** ap_str_values(ArgParser* parser, const char* name) { - Option* opt = ap_get_opt(parser, name); - return (char**)option_get_str_list(opt); -} - - -// Returns an option's values as a freshly-allocated array of integers. The -// array's memory is not affected by calls to ap_free(). -// Returns NULL if memory cannot be allocated for the array. -int* ap_int_values(ArgParser* parser, const char* name) { - Option* opt = ap_get_opt(parser, name); - return option_get_int_list(opt); -} - - -// Returns an option's values as a freshly-allocated array of doubles. The -// array's memory is not affected by calls to ap_free(). -// Returns NULL if memory cannot be allocated for the array. -double* ap_dbl_values(ArgParser* parser, const char* name) { - Option* opt = ap_get_opt(parser, name); - return option_get_double_list(opt); -} - - -/* -------------------------------- */ -/* ArgParser: positional arguments. */ -/* -------------------------------- */ - - -// Returns true if the parser has found one or more positional arguments. -boolean ap_has_args(ArgParser* parser) { - return parser->positional_args->count > 0; -} - - -// Returns the number of positional arguments. -int ap_count_args(ArgParser* parser) { - return parser->positional_args->count; -} - - -// Returns the positional argument at the specified index. -char* ap_arg(ArgParser* parser, int index) { - return (char*)parser->positional_args->entries[index]; -} - - -// Returns the positional arguments as a freshly-allocated array of string -// pointers. The memory occupied by the returned array is not affected by -// calls to ap_free(). -// Returns NULL if memory cannot be allocated for the array. -char** ap_args(ArgParser* parser) { - int count = ap_count_args(parser); - char** args = malloc(sizeof(char*) * count); - if (!args) { - return NULL; - } - memcpy(args, parser->positional_args->entries, sizeof(char*) * count); - return args; -} - - -// Attempts to parse and return the positional arguments as a freshly -// allocated array of integers. Exits with an error message on failure. The -// memory occupied by the returned array is not affected by calls to -// ap_free(). -// Returns NULL if memory cannot be allocated for the array. -int* ap_args_as_ints(ArgParser* parser) { - int count = ap_count_args(parser); - int* args = malloc(sizeof(int) * count); - if (!args) { - return NULL; - } - for (int i = 0; i < count; i++) { - *(args + i) = try_str_to_int(parser->positional_args->entries[i]); - } - return args; -} - - -// Attempts to parse and return the positional arguments as a freshly -// allocated array of doubles. Exits with an error message on failure. The -// memory occupied by the returned array is not affected by calls to -// ap_free(). -// Returns NULL if memory cannot be allocated for the array. -double* ap_args_as_doubles(ArgParser* parser) { - int count = ap_count_args(parser); - double *args = malloc(sizeof(double) * count); - if (!args) { - return NULL; - } - for (int i = 0; i < count; i++) { - *(args + i) = try_str_to_double(parser->positional_args->entries[i]); - } - return args; -} - - -/* -------------------- */ -/* ArgParser: commands. */ -/* -------------------- */ - - -// Register a new command. -ArgParser* ap_cmd(ArgParser* parser, const char* name) { - ArgParser* cmd_parser = ap_new(); - if (!cmd_parser) { - return NULL; - } - - if (vec_add(parser->command_vec, cmd_parser)) { - if (map_set_splitkey(parser->command_map, name, cmd_parser)) { - parser->enable_help_command = true; - return cmd_parser; - } else { - parser->command_vec--; - ap_free(cmd_parser); - return NULL; - } - } else { - ap_free(cmd_parser); - return NULL; - } -} - - -// Register a callback function for a command. -void ap_callback(ArgParser* parser, ap_callback_t function) { - parser->callback = function; -} - - -// Returns true if the parser has found a command. -boolean ap_has_cmd(ArgParser* parser) { - return parser->cmd_name != NULL; -} - - -// Returns the command name, if the parser has found a command. -char* ap_cmd_name(ArgParser* parser) { - return parser->cmd_name; -} - - -// Returns the command's parser instance, if the parser has found a command. -ArgParser* ap_cmd_parser(ArgParser* parser) { - return parser->cmd_parser; -} - - -// Toggles support for the automatic 'help' command. -void ap_enable_help_command(ArgParser* parser, boolean enable) { - parser->enable_help_command = enable; -} - - -/* --------------------------- */ -/* ArgParser: parse arguments. */ -/* --------------------------- */ - - -// Parse an option of the form --name=value or -n=value. -static void ap_handle_equals_opt(ArgParser* parser, const char* prefix, const char* arg) { - char* name = str_dup(arg); - if (!name) { - ap_set_memory_error_flag(parser); - return; - } - - *strchr(name, '=') = '\0'; - char *value = strchr(arg, '=') + 1; - - Option* option; - boolean found = map_get(parser->option_map, name, (void**)&option); - - if (!found || option->type == OPT_FLAG) { - err(va("%s%s is not a recognised option name", prefix, name)); - } - - if (strlen(value) == 0) { - err(va("missing argument for %s%s", prefix, name)); - } - - if (!option_try_set(option, value)) { - ap_set_memory_error_flag(parser); - } - - free(name); -} - -// Parse a long-form option, i.e. an option beginning with a double dash. -static void ap_handle_long_opt(ArgParser* parser, const char* arg, ArgStream* stream) { - Option* option; - if (map_get(parser->option_map, arg, (void**)&option)) { - if (option->type == OPT_FLAG) { - option->count++; - } else if (argstream_has_next(stream)) { - if (!option_try_set(option, argstream_next(stream))) { - ap_set_memory_error_flag(parser); - } - } else { - err(va("missing argument for --%s", arg)); - } - } else if (strcmp(arg, "help") == 0 && parser->helptext != NULL) { - CONS_Printf("%s\n", parser->helptext); - } else if (strcmp(arg, "version") == 0 && parser->version != NULL) { - CONS_Printf("%s\n", parser->version); - } else { - err(va("--%s is not a recognised flag or option name", arg)); - } -} - - -// Parse a short-form option, i.e. an option beginning with a single dash. -static void ap_handle_short_opt(ArgParser* parser, const char* arg, ArgStream* stream) { - for (size_t i = 0; i < strlen(arg); i++) { - char keystr[] = {arg[i], 0}; - Option* option; - boolean found = map_get(parser->option_map, keystr, (void**)&option); - if (!found) { - if (arg[i] == 'h' && parser->helptext != NULL) { - CONS_Printf("%s\n", parser->helptext); - } else if (arg[i] == 'v' && parser->version != NULL) { - CONS_Printf("%s\n", parser->version); - } else if (strlen(arg) > 1) { - err(va("'%c' in -%s is not a recognised flag or option name", arg[i], arg)); - } else { - err(va("-%s is not a recognised flag or option name", arg)); - } - } else if (option->type == OPT_FLAG) { - option->count++; - } else if (argstream_has_next(stream)) { - if (!option_try_set(option, argstream_next(stream))) { - ap_set_memory_error_flag(parser); - } - } else if (strlen(arg) > 1) { - err(va("missing argument for '%c' in -%s", arg[i], arg)); - } else { - err(va("missing argument for -%s", arg)); - } - } -} - - -// Parse a stream of string arguments. -static void ap_parse_stream(ArgParser* parser, ArgStream* stream) { - if (parser->had_memory_error) { - return; - } - - ArgParser* cmd_parser; - boolean is_first_arg = true; - - while (argstream_has_next(stream)) { - char* arg = argstream_next(stream); - - // If we encounter a '--' argument, turn off option-parsing. - if (strcmp(arg, "--") == 0) { - while (argstream_has_next(stream)) { - if (!vec_add(parser->positional_args, argstream_next(stream))) { - ap_set_memory_error_flag(parser); - } - } - } - - // Is the argument a long-form option or flag? - else if (strncmp(arg, "--", 2) == 0) { - if (strstr(arg, "=") != NULL) { - ap_handle_equals_opt(parser, "--", arg + 2); - } else { - ap_handle_long_opt(parser, arg + 2, stream); - } - } - - // Is the argument a short-form option or flag? - else if (arg[0] == '-') { - if (strlen(arg) == 1 || isdigit(arg[1])) { - if (!vec_add(parser->positional_args, arg)) { - ap_set_memory_error_flag(parser); - } - } else if (strstr(arg, "=") != NULL) { - ap_handle_equals_opt(parser, "-", arg + 1); - } else { - ap_handle_short_opt(parser, arg + 1, stream); - } - } - - // Is the argument a registered command? - else if (is_first_arg && map_get(parser->command_map, arg, (void**)&cmd_parser)) { - parser->cmd_name = arg; - parser->cmd_parser = cmd_parser; - ap_parse_stream(cmd_parser, stream); - if (cmd_parser->callback && !parser->had_memory_error) { - cmd_parser->callback(arg, cmd_parser); - } - } - - // Is the argument the automatic 'help' command? - else if (is_first_arg && parser->enable_help_command && strcmp(arg, "help") == 0) { - if (argstream_has_next(stream)) { - char* name = argstream_next(stream); - if (map_get(parser->command_map, name, (void**)&cmd_parser)) { - if (cmd_parser->helptext) { - CONS_Printf("%s\n", cmd_parser->helptext); - } - } else { - err(va("'%s' is not a recognised command", name)); - } - } else { - err(va("the help command requires an argument")); - } - } - - // Otherwise add the argument to our list of positionals. - else { - if (!vec_add(parser->positional_args, arg)) { - ap_set_memory_error_flag(parser); - } - if (parser->first_positional_arg_ends_options) { - while (argstream_has_next(stream)) { - if (!vec_add(parser->positional_args, argstream_next(stream))) { - ap_set_memory_error_flag(parser); - } - } - } - } - - is_first_arg = false; - } -} - - -// Parse an array of string arguments. -static boolean ap_parse_array(ArgParser* parser, int count, char* args[]) { - if (parser->had_memory_error) { - return false; - } - - ArgStream *stream = argstream_new(count, args); - if (!stream) { - return false; - } - - ap_parse_stream(parser, stream); - argstream_free(stream); - - return !parser->had_memory_error; -} - - -// This function parses the application's command line arguments. It assumes that [argc] and [argv] -// are the arguments passed to main(), i.e. that the first element in [argv] is the program's name -// and should be ignored when parsing the actual *arguments*. In some situations [argv] can be -// empty, i.e. [argc == 0], which can lead to security vulnerabilities if not explicitly handled. -boolean ap_parse(ArgParser* parser, int argc, char* argv[]) { - if (argc > 1) { - return ap_parse_array(parser, argc - 1, argv + 1); - } - return !parser->had_memory_error; -} - - -/* --------------------- */ -/* ArgParser: utilities. */ -/* --------------------- */ - - -boolean ap_had_memory_error(ArgParser* parser) { - return parser->had_memory_error; -} - - -void ap_print(ArgParser* parser) { - CONS_Printf("%s\n", "Flags/Options:"); - if (parser->option_map->count > 0) { - for (int i = 0; i < parser->option_map->capacity; i++) { - MapEntry* entry = &parser->option_map->entries[i]; - if (entry->key != NULL) { - Option* opt = entry->value; - char* opt_str = option_to_str(opt); - CONS_Printf("%s\n", entry->key, opt_str); - free(opt_str); - } - } - } else { - CONS_Printf("%s\n", " [none]"); - } - - CONS_Printf("%s\n", "\nArguments:"); - if (parser->positional_args->count > 0) { - for (int i = 0; i < parser->positional_args->count; i++) { - CONS_Printf("%s\n", ap_arg(parser, i)); - } - } else { - CONS_Printf("%s\n", " [none]"); - } - - CONS_Printf("%s\n", "\nCommand:"); - if (ap_has_cmd(parser)) { - CONS_Printf("%s\n", ap_cmd_name(parser)); - } else { - CONS_Printf("%s\n", " [none]"); - } -} - - -/* --------------------- */ -/* Deprecated functions. */ -/* --------------------- */ - - -void ap_cmd_help(ArgParser* parser, boolean enable) { - ap_enable_help_command(parser, enable); -} - - -void ap_helptext(ArgParser* parser, const char* helptext) { - ap_set_helptext(parser, helptext); -} - - -void ap_version(ArgParser* parser, const char* version) { - ap_set_version(parser, version); -} diff --git a/src/args.h b/src/args.h deleted file mode 100644 index e2db1e501..000000000 --- a/src/args.h +++ /dev/null @@ -1,206 +0,0 @@ -// ----------------------------------------------------------------------------- -// Args: a C99 library for parsing command line arguments. -// Version: 2.8.0 -// Notes: This has been edited to work properly within SRB2. -// Licensed under the 0BSD license. -// ----------------------------------------------------------------------------- - -#ifndef args_h -#define args_h - -#include "doomtype.h" - -// ----------------------------------------------------------------------------- -// Types. -// ----------------------------------------------------------------------------- - -// An ArgParser instance stores registered flags, options and commands. -typedef struct ArgParser ArgParser; - -// A command callback function should accept two arguments: the command's name -// and the command's ArgParser instance. -typedef void (*ap_callback_t)(char* cmd_name, ArgParser* cmd_parser); - -// ----------------------------------------------------------------------------- -// Initialization, parsing, teardown. -// ----------------------------------------------------------------------------- - -// Initializes a new ArgParser instance. Returns NULL if sufficient memory -// cannot be allocated for the new parser. -ArgParser* ap_new(); - -// Specifies a helptext string for the parser. If [helptext] is not NULL, this -// activates an automatic --help/-h flag. (Either --help or -h can be overridden -// by explicitly registered flags.) The parser stores and manages its own copy -// of the [helptext] string so [helptext] can be freed immediately after this -// call if it was dynamically constructed. -void ap_set_helptext(ArgParser* parser, const char* helptext); - -// Returns a pointer to the parser's helptext string. -char* ap_get_helptext(ArgParser* parser); - -// Specifies a version string for the parser. If [version] is not NULL, this -// activates an automatic --version/-v flag. (Either --version or -v can be -// overridden by explicitly registered flags.) The parser stores and manages its -// own copy of the [version] string so [version] can be freed immediately after -// this call if it was dynamically constructed. -void ap_set_version(ArgParser* parser, const char* version); - -// Returns a pointer to the parser's version string. -char* ap_get_version(ArgParser* parser); - -// If toggled to true, the first positional argument ends option parsing; all -// subsequent arguments will be treated as positionals. Defaults to false. -void ap_first_pos_arg_ends_options(ArgParser* parser, boolean enable); - -// Parses the application's command line arguments. The parameters are assumed -// to be [argc] and [argv] as supplied to main(), i.e. the first element of the -// array is assumed to be the binary name and is therefore ignored. Returns true -// if the arguments were successfully parsed. Returns false if parsing failed -// due to a memory allocation error. (This memory allocation error may have -// occured during set-up rather than during parsing.) -boolean ap_parse(ArgParser* parser, int argc, char** argv); - -// Frees the memory associated with the parser and any subparsers. -void ap_free(ArgParser* parser); - -// ----------------------------------------------------------------------------- -// Register flags and options. -// ----------------------------------------------------------------------------- - -// Registers a new flag. -void ap_flag(ArgParser* parser, const char* name); - -// Registers a new string-valued option. -void ap_str_opt(ArgParser* parser, const char* name, const char* fallback); - -// Registers a new integer-valued option. -void ap_int_opt(ArgParser* parser, const char* name, int fallback); - -// Registers a new double-valued option. -void ap_dbl_opt(ArgParser* parser, const char* name, double fallback); - -// ----------------------------------------------------------------------------- -// Inspect flags and options. -// ----------------------------------------------------------------------------- - -// Returns the number of times the specified flag or option was found. -int ap_count(ArgParser* parser, const char* name); - -// Returns true if the specified flag or option was found. -boolean ap_found(ArgParser* parser, const char* name); - -// Returns the value of a string option. -char* ap_str_value(ArgParser* parser, const char* name); - -// Returns the string value at the specified index. -char* ap_str_value_at_index(ArgParser* parser, const char* name, int index); - -// Returns the value of an integer option. -int ap_int_value(ArgParser* parser, const char* name); - -// Returns the integer value at the specified index. -int ap_int_value_at_index(ArgParser* parser, const char* name, int index); - -// Returns the value of a floating-point option. -double ap_dbl_value(ArgParser* parser, const char* name); - -// Returns the floating-point value at the specified index. -double ap_dbl_value_at_index(ArgParser* parser, const char* name, int index); - -// Returns an option's values as a freshly-allocated array of string -// pointers. The array's memory is not affected by calls to ap_free(). -// Returns NULL if memory allocation fails. -char** ap_str_values(ArgParser* parser, const char* name); - -// Returns an option's values as a freshly-allocated array of integers. -// The array's memory is not affected by calls to ap_free(). -// Returns NULL if memory allocation fails. -int* ap_int_values(ArgParser* parser, const char* name); - -// Returns an option's values as a freshly-allocated array of doubles. -// The array's memory is not affected by calls to ap_free(). -// Returns NULL if memory allocation fails. -double* ap_dbl_values(ArgParser* parser, const char* name); - -// ----------------------------------------------------------------------------- -// Positional arguments. -// ----------------------------------------------------------------------------- - -// Returns true if the parser has found one or more positional arguments. -boolean ap_has_args(ArgParser* parser); - -// Returns the number of positional arguments. -int ap_count_args(ArgParser* parser); - -// Returns the positional argument at the specified index. -char* ap_arg(ArgParser* parser, int index); - -// Returns the positional arguments as a freshly-allocated array of string -// pointers. The memory occupied by the returned array is not affected by -// calls to ap_free(). Returns NULL if memory allocation fails. -char** ap_args(ArgParser* parser); - -// Attempts to parse and return the positional arguments as a freshly allocated -// array of integers. Exits with an error message on failure. The memory -// occupied by the returned array is not affected by calls to ap_free(). -// Returns NULL if memory allocation fails. -int* ap_args_as_ints(ArgParser* parser); - -// Attempts to parse and return the positional arguments as a freshly allocated -// array of doubles. Exits with an error message on failure. The memory -// occupied by the returned array is not affected by calls to ap_free(). -// Returns NULL if memory allocation fails. -double* ap_args_as_doubles(ArgParser* parser); - -// ----------------------------------------------------------------------------- -// Commands. -// ----------------------------------------------------------------------------- - -// Registers a new command. Returns the ArgParser instance for the command. -// Returns NULL if sufficient memory cannot be allocated for the new parser. -ArgParser* ap_cmd(ArgParser* parser, const char* name); - -// Registers a callback function on a command parser. The function will be -// called if the command is found. -void ap_callback(ArgParser* parser, ap_callback_t function); - -// Returns true if the parser has found a command. -boolean ap_has_cmd(ArgParser* parser); - -// Returns the command name, if the parser has found a command. -char* ap_cmd_name(ArgParser* parser); - -// Returns the command's parser instance, if the parser has found a command. -ArgParser* ap_cmd_parser(ArgParser* parser); - -// This booleanean switch toggles support for an automatic 'help' command that -// prints subcommand helptext. The value defaults to false but gets toggled -// automatically to true whenever a command is registered. You can use this -// function to disable the feature if required. -void ap_enable_help_command(ArgParser* parser, boolean enable); - -// ----------------------------------------------------------------------------- -// Debugging utilities. -// ----------------------------------------------------------------------------- - -// Dump a parser instance for debugging. -void ap_print(ArgParser* parser); - -// True if an attempt to allocate memory failed. -boolean ap_had_memory_error(ArgParser* parser); - -// ----------------------------------------------------------------------------- -// Deprecated. -// ----------------------------------------------------------------------------- - -// Replaced by ap_enable_help_command(). -void ap_cmd_help(ArgParser* parser, boolean enable); - -// Replaced by ap_set_helptext(). -void ap_helptext(ArgParser* parser, const char* helptext); - -// Replaced by ap_set_version(). -void ap_version(ArgParser* parser, const char* version); - -#endif diff --git a/src/command.c b/src/command.c index 2a9c40227..165cbb584 100644 --- a/src/command.c +++ b/src/command.c @@ -49,6 +49,7 @@ static void COM_CEchoDuration_f(void); static void COM_Exec_f(void); static void COM_Wait_f(void); static void COM_Help_f(void); +static void COM_Find_f(void); static void COM_Toggle_f(void); static void COM_Add_f(void); @@ -299,6 +300,7 @@ void COM_Init(void) COM_AddCommand("exec", COM_Exec_f); COM_AddCommand("wait", COM_Wait_f); COM_AddCommand("help", COM_Help_f); + COM_AddCommand("find", COM_Find_f); COM_AddCommand("toggle", COM_Toggle_f); COM_AddCommand("add", COM_Add_f); RegisterNetXCmd(XD_NETVAR, Got_NetVar); @@ -820,7 +822,7 @@ static void COM_Help_f(void) if (cvar) { CONS_Printf("\x82""Variable %s:\n", cvar->name); - CONS_Printf(M_GetText(" flags :")); + CONS_Printf(M_GetText(" flags: ")); if (cvar->flags & CV_SAVE) CONS_Printf("AUTOSAVE "); if (cvar->flags & CV_FLOAT) @@ -874,30 +876,9 @@ static void COM_Help_f(void) return; } - CONS_Printf("No exact match, searching...\n"); - // commands - CONS_Printf("\x82""Commands:\n"); - for (cmd = com_commands; cmd; cmd = cmd->next) - { - if (!strstr(cmd->name, help)) - continue; - CONS_Printf("%s ",cmd->name); - i++; - } + CONS_Printf("No variable or command named %s", help); + CONS_Printf("\x82""\nCheck wiki.srb2.org for more or try typing help without arguments\n"); - // variables - CONS_Printf("\x82""\nVariables:\n"); - for (cvar = consvar_vars; cvar; cvar = cvar->next) - { - if ((cvar->flags & CV_NOSHOWHELP) || (!strstr(cvar->name, help))) - continue; - CONS_Printf("%s ", cvar->name); - i++; - } - - CONS_Printf("\x82""\nCheck wiki.srb2.org for more or type help \n"); - - CONS_Debug(DBG_GAMELOGIC, "\x87Total : %d\n", i); } return; } @@ -927,6 +908,78 @@ static void COM_Help_f(void) } } + +static void COM_Find_f(void) +{ + static char prefix[80]; + xcommand_t *cmd; + consvar_t *cvar; + cmdalias_t *alias; + const char *match; + const char *help; + size_t helplen; + boolean matchesany; + + if (COM_Argc() != 2) + { + CONS_Printf(M_GetText("find : Search for variables, commands and aliases containing \n")); + return; + } + + help = COM_Argv(1); + helplen = strlen(help); + CONS_Printf("\x82""Variables:\n"); + matchesany = false; + for (cvar = consvar_vars; cvar; cvar = cvar->next) + { + if (cvar->flags & CV_NOSHOWHELP) + continue; + match = strstr(cvar->name, help); + if (match != NULL) + { + memcpy(prefix, cvar->name, match - cvar->name); + prefix[match - cvar->name] = '\0'; + CONS_Printf(" %s\x83%s\x80%s\n", prefix, help, &match[helplen]); + matchesany = true; + } + } + if (!matchesany) + CONS_Printf(" (none)\n"); + + CONS_Printf("\x82""Commands:\n"); + matchesany = false; + for (cmd = com_commands; cmd; cmd = cmd->next) + { + match = strstr(cmd->name, help); + if (match != NULL) + { + memcpy(prefix, cmd->name, match - cmd->name); + prefix[match - cmd->name] = '\0'; + CONS_Printf(" %s\x83%s\x80%s\n", prefix, help, &match[helplen]); + matchesany = true; + } + } + if (!matchesany) + CONS_Printf(" (none)\n"); + + CONS_Printf("\x82""Aliases:\n"); + matchesany = false; + for (alias = com_alias; alias; alias = alias->next) + { + match = strstr(alias->name, help); + if (match != NULL) + { + memcpy(prefix, alias->name, match - alias->name); + prefix[match - alias->name] = '\0'; + CONS_Printf(" %s\x83%s\x80%s\n", prefix, help, &match[helplen]); + matchesany = true; + } + } + if (!matchesany) + CONS_Printf(" (none)\n"); +} + + /** Toggles a console variable. Useful for on/off values. * * This works on on/off, yes/no values only diff --git a/src/console.c b/src/console.c index 21c9eb695..73eac9ff9 100644 --- a/src/console.c +++ b/src/console.c @@ -869,7 +869,9 @@ boolean CON_Responder(event_t *ev) static UINT8 consdown = false; // console is treated differently due to rare usage // sequential completions a la 4dos - static char completion[80]; + static char completioncmd[80 + sizeof("find ")] = "find "; + static char *completion = &completioncmd[sizeof("find ")-1]; + static INT32 comskips, varskips; const char *cmd = ""; @@ -948,7 +950,6 @@ boolean CON_Responder(event_t *ev) // show all cvars/commands that match what we have inputted if (key == KEY_TAB) { - size_t i, len; if (!completion[0]) { @@ -957,19 +958,8 @@ boolean CON_Responder(event_t *ev) strcpy(completion, inputlines[inputline]); comskips = varskips = 0; } - len = strlen(completion); - //first check commands - CONS_Printf("\nCommands:\n"); - for (i = 0, cmd = COM_CompleteCommand(completion, i); cmd; cmd = COM_CompleteCommand(completion, ++i)) - CONS_Printf(" \x83" "%s" "\x80" "%s\n", completion, cmd+len); - if (i == 0) CONS_Printf(" (none)\n"); - - //now we move on to CVARs - CONS_Printf("Variables:\n"); - for (i = 0, cmd = CV_CompleteVar(completion, i); cmd; cmd = CV_CompleteVar(completion, ++i)) - CONS_Printf(" \x83" "%s" "\x80" "%s\n", completion, cmd+len); - if (i == 0) CONS_Printf(" (none)\n"); + COM_BufInsertText(completioncmd); return true; } diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 6e56d3ac4..248afd2f9 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -47,6 +47,7 @@ #include "k_kart.h" #include "s_sound.h" // sfx_syfail #include "m_perfstats.h" +#include "d_main.h" #ifdef CLIENT_LOADINGSCREEN // cl loading screen @@ -171,6 +172,8 @@ static textcmdtic_t *textcmds[TEXTCMD_HASH_SIZE] = {NULL}; consvar_t cv_showjoinaddress = {"showjoinaddress", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_shownodeip = {"showipinnodelist", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + static CV_PossibleValue_t playbackspeed_cons_t[] = {{1, "MIN"}, {10, "MAX"}, {0, NULL}}; consvar_t cv_playbackspeed = {"playbackspeed", "1", 0, playbackspeed_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -1899,6 +1902,15 @@ static void CL_LoadReceivedSavegame(void) demo.title = false; automapactive = false; + if (!postautoloaded) + { + CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n"); + if (W_AddAutoloadedLocalFiles(autoloadwadfilespost) == 0) + CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); + D_CleanFile(autoloadwadfilespost); + postautoloaded = true; + } + // load a base level if (P_LoadNetGame()) { @@ -1939,12 +1951,13 @@ static void CL_LoadReceivedSavegame(void) static void SendAskInfo(INT32 node) { tic_t asktime; - + #ifdef HOLEPUNCH if (node != 0 && node != BROADCASTADDR && cv_rendezvousserver.string[0]) { I_NetRequestHolePunch(node); } + #endif asktime = I_GetTime(); @@ -3345,7 +3358,7 @@ static void Command_Nodes(void) { CONS_Printf("%.2u: %*s", i, (int)maxlen, player_names[i]); CONS_Printf(" - %.2d", playernode[i]); - if (I_GetNodeAddress && (address = I_GetNodeAddress(playernode[i])) != NULL) + if ((I_GetNodeAddress && (address = I_GetNodeAddress(playernode[i])) != NULL) && (cv_shownodeip.value)) CONS_Printf(" - %s", address); if (IsPlayerAdmin(i)) @@ -3359,6 +3372,94 @@ static void Command_Nodes(void) } } +//Screw the base game nodes lets replace with listplayers instead. +static void Command_Listplayers(void) +{ + const char *address; + int width = 0; + + boolean admin; + boolean spectator; + + /* + Mode of player status for an individual player (admin, spectator). + 1 for admin + 2 for spectator + 4 for both + */ + int mode = 0; + + INT32 totalplayers = 0; + + const char *cc; + const char *pcc; + + INT32 i; + int n; + + for (i = 0; i < MAXPLAYERS; ++i) + if (playeringame[i]) + { + n = strlen(player_names[i]); + if (n > width) + width = n; + + if (mode != 7) + { + admin = IsPlayerAdmin(i); + spectator = players[i].spectator; + + if (admin) + mode |= 1; + if (spectator) + mode |= 2; + if (admin && spectator) + mode |= 4; + } + } + + for (i = 0; i < MAXPLAYERS; ++i) + if (playeringame[i]) + { + admin = IsPlayerAdmin(i); + spectator = players[i].spectator; + + if (admin) + cc = "\x85";/* red */ + else if (spectator) + cc = "\x86";/* gray */ + else + cc = ""; + + pcc = HU_SkinColorToConsoleColor(players[i].skincolor); + + CONS_Printf("%.2d: ""%s""%-*s""\x80", i, pcc,width, player_names[i]); + + if ((I_GetNodeAddress && (address = I_GetNodeAddress(playernode[i])) != NULL) && (cv_shownodeip.value)) + CONS_Printf(" -- %s", address); + else/* print spacer */ + { + /* ...but not if there's a crammed status and were admin */ + if (mode != 7 || !admin) + CONS_Printf(" -- ");/* -- self */ + } + + if (admin) + CONS_Printf(M_GetText("%s"" (admin)"),cc); + if (spectator) + CONS_Printf(M_GetText("%s"" (spectator)"),cc); + + CONS_Printf("\n"); + + totalplayers++; + } + + if (totalplayers == 1) + CONS_Printf("\nThere is 1 player in the game.\n"); + else + CONS_Printf("\nThere are %d players in the game.\n", totalplayers); +} + static void Command_Ban(void) { if (COM_Argc() < 2) @@ -3924,6 +4025,7 @@ void D_ClientServerInit(void) COM_AddCommand("reloadbans", Command_ReloadBan); COM_AddCommand("connect", Command_connect); COM_AddCommand("nodes", Command_Nodes); + COM_AddCommand("listplayers", Command_Listplayers); #ifdef HAVE_CURL COM_AddCommand("set_http_login", Command_set_http_login); COM_AddCommand("list_http_logins", Command_list_http_logins); @@ -4215,6 +4317,13 @@ static void Got_RemovePlayer(UINT8 **p, INT32 playernum) pnum = READUINT8(*p); reason = READUINT8(*p); + if (pnum == serverplayer) + { + CONS_Alert(CONS_WARNING, "Attempt to remove server player\n"); + + return; + } + CL_RemovePlayer(pnum, reason); #ifdef HAVE_DISCORDRPC @@ -4981,36 +5090,26 @@ static void HandlePacketFromPlayer(SINT8 node) /// \todo Use a separate cvar for that kind of timeout? freezetimeout[node] = I_GetTime() + connectiontimeout; - //Ported this from 2.2 Prevent dropped ticcmds due to interp timing jutter - // If we've alredy received a ticcmd for this tic, just submit it for the next one. - tic_t faketic = maketic; - if ((!!(netcmds[maketic % TICQUEUE][netconsole].angleturn & TICCMD_RECEIVED)) - && (maketic - firstticstosend < TICQUEUE - 1)) - faketic++; - - - // Don't do anything for packets of type NODEKEEPALIVE? // Sryder 2018/07/01: Update the freezetimeout still! if (netbuffer->packettype == PT_NODEKEEPALIVE || netbuffer->packettype == PT_NODEKEEPALIVEMIS) break; - // Copy ticcmd Prevent dropped ticcmds due to interp timing jutter - G_MoveTiccmd(&netcmds[faketic%TICQUEUE][netconsole], &netbuffer->u.clientpak.cmd, 1); - + // Copy ticcmd + G_MoveTiccmd(&netcmds[maketic%TICQUEUE][netconsole], &netbuffer->u.clientpak.cmd, 1); // Check ticcmd for "speed hacks" if (CheckForSpeedHacks((UINT8)netconsole)) break; - // Splitscreen cmd Prevent dropped ticcmds due to interp timing jutter + // Splitscreen cmd if (((netbuffer->packettype == PT_CLIENT2CMD || netbuffer->packettype == PT_CLIENT2MIS) || (netbuffer->packettype == PT_CLIENT3CMD || netbuffer->packettype == PT_CLIENT3MIS) || (netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS)) && (nodetoplayer2[node] >= 0)) { - G_MoveTiccmd(&netcmds[faketic%TICQUEUE][(UINT8)nodetoplayer2[node]], + G_MoveTiccmd(&netcmds[maketic%TICQUEUE][(UINT8)nodetoplayer2[node]], &netbuffer->u.client2pak.cmd2, 1); if (CheckForSpeedHacks((UINT8)nodetoplayer2[node])) @@ -5021,7 +5120,7 @@ static void HandlePacketFromPlayer(SINT8 node) || (netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS)) && (nodetoplayer3[node] >= 0)) { - G_MoveTiccmd(&netcmds[faketic%TICQUEUE][(UINT8)nodetoplayer3[node]], + G_MoveTiccmd(&netcmds[maketic%TICQUEUE][(UINT8)nodetoplayer3[node]], &netbuffer->u.client3pak.cmd3, 1); if (CheckForSpeedHacks((UINT8)nodetoplayer3[node])) @@ -5031,7 +5130,7 @@ static void HandlePacketFromPlayer(SINT8 node) if ((netbuffer->packettype == PT_CLIENT4CMD || netbuffer->packettype == PT_CLIENT4MIS) && (nodetoplayer4[node] >= 0)) { - G_MoveTiccmd(&netcmds[faketic%TICQUEUE][(UINT8)nodetoplayer4[node]], + G_MoveTiccmd(&netcmds[maketic%TICQUEUE][(UINT8)nodetoplayer4[node]], &netbuffer->u.client4pak.cmd4, 1); if (CheckForSpeedHacks((UINT8)nodetoplayer4[node])) @@ -5299,7 +5398,7 @@ static void HandlePacketFromPlayer(SINT8 node) } else { - DEBFILE(va("frame not in bound: %u\n", neededtic)); + DEBFILE(va("frame not in bound: %u (bounds are from %u to %u)\n", neededtic, realstart, realend)); /*if (realend < neededtic - 2 * TICRATE || neededtic + 2 * TICRATE < realstart) I_Error("Received an out of order PT_SERVERTICS packet!\n" "Got tics %d-%d, needed tic %d\n\n" @@ -6153,6 +6252,7 @@ static void UpdatePingTable(void) } } +#ifdef HOLEPUNCH static void RenewHolePunch(void) { if (cv_rendezvousserver.string[0]) @@ -6168,6 +6268,7 @@ static void RenewHolePunch(void) } } } +#endif // Handle timeouts to prevent definitive freezes from happenning static void HandleNodeTimeouts(void) @@ -6201,11 +6302,14 @@ void NetKeepAlive(void) #ifdef MASTERSERVER MasterClient_Ticker(); #endif - + + #ifdef HOLEPUNCH if (netgame && serverrunning) { RenewHolePunch(); } + #endif + if (client) { @@ -6318,10 +6422,12 @@ void NetUpdate(void) MasterClient_Ticker(); // Acking the Master Server #endif + #ifdef HOLEPUNCH if (netgame && serverrunning) { RenewHolePunch(); } + #endif if (client) { diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 65fd3c9a9..b1bc9ffcc 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -515,6 +515,8 @@ extern consvar_t cv_kicktime; extern consvar_t cv_showjoinaddress; extern consvar_t cv_playbackspeed; +extern consvar_t cv_shownodeip; + #define BASEPACKETSIZE offsetof(doomdata_t, u) #define FILETXHEADER offsetof(filetx_pak, data) #define BASESERVERTICSSIZE offsetof(doomdata_t, u.serverpak.cmds[0]) diff --git a/src/d_main.c b/src/d_main.c index 3d946dd85..885a0be26 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -66,7 +66,7 @@ #include "fastcmp.h" #include "r_fps.h" // Frame interpolation/uncapped #include "keys.h" -#include "filesrch.h" // refreshdirmenu +#include "filesrch.h" // refreshdirmenu, pathisdirectory #include "d_protocol.h" #include "m_perfstats.h" @@ -94,8 +94,6 @@ // platform independant focus loss UINT8 window_notinfocus = false; -INT32 window_x; -INT32 window_y; // // DEMO LOOP @@ -105,6 +103,13 @@ static const char *pagename = "MAP1PIC"; static char *startupwadfiles[MAX_WADFILES]; static char *startuppwads[MAX_WADFILES]; +// autoloading +static char *autoloadwadfiles[MAX_WADFILES]; +char *autoloadwadfilespost[MAX_WADFILES]; +boolean autoloading; +boolean autoloaded; +boolean postautoloaded; + boolean devparm = false; // started game with -devparm boolean singletics = false; // timedemo @@ -885,7 +890,162 @@ static void D_AddFile(const char *file, char **filearray) filearray[pnumwadfiles] = newfile; } -static inline void D_CleanFile(char **filearray) +// Taken from TSoURDt3rd +// https://github.com/StarManiaKG/The-Story-of-Uncapped-Revengence-Discord-the-3rd/blob/main/src/STAR/star_functions.c +static INT32 D_DetectFileType(const char* filename) +{ + if (pathisdirectory(filename) == 1) + return 1; + else + { + if (!stricmp(&filename[strlen(filename) - 4], ".wad")) + return 2; + else if (!stricmp(&filename[strlen(filename) - 4], ".pk3")) + return 3; + else if (!stricmp(&filename[strlen(filename) - 5], ".kart")) + return 4; + + else if (!stricmp(&filename[strlen(filename) - 4], ".lua")) + return 5; + else if (!stricmp(&filename[strlen(filename) - 4], ".soc")) + return 6; + + else if (!stricmp(&filename[strlen(filename) - 4], ".cfg")) + return 7; + else if (!stricmp(&filename[strlen(filename) - 4], ".txt")) + return 8; + } + + return 0; +} + +// autoload that shit +static void D_AutoloadFile(const char *file, char **filearray) +{ + size_t pnumwadfiles; + char *newfile; + INT32 fileType = D_DetectFileType(file); + + for (pnumwadfiles = 0; filearray[pnumwadfiles]; pnumwadfiles++) + ; + + newfile = malloc(strlen(file) + 1); + if (!newfile) + I_Error("No more free memory to AutoloadFile %s",file); + + if (!fileType) + { + CONS_Printf("D_AutoloadFile: File %s is unknown or invalid\n", file); + return; + } + + strcpy(newfile, file); + + if (fileType <= 6) + filearray[pnumwadfiles] = newfile; + else + COM_BufAddText(va("exec %s\n", newfile)); +} + +static char *strremove(char *str, const char *sub) { + char *p, *q, *r; + if (*sub && (q = r = strstr(str, sub)) != NULL) { + size_t len = strlen(sub); + while ((r = strstr(p = r + len, sub)) != NULL) { + while (p < r) + *q++ = *p++; + } + while ((*q++ = *p++) != '\0') + continue; + } + return str; +} + +// FIND THEM +static void D_FindAddonsToAutoload(void) +{ + FILE *autoloadconfigfile; + const char *autoloadpath; + boolean postload; + + INT32 i, len; + boolean hasprefix = false; + char wadsToAutoload[256] = "", renameAutoloadStrings[256] = ""; + + // does it exist tho + autoloadpath = va("%s"PATHSEP"%s",srb2home,AUTOLOADCONFIGFILENAME); + autoloadconfigfile = fopen(autoloadpath, "r"); + + // If the file is found, run our shit + if (!autoloadconfigfile) // nope outta here + return; + + while (fgets(wadsToAutoload, sizeof wadsToAutoload, autoloadconfigfile) != NULL) + { + postload = false; + // skip if commented or empty + if ((wadsToAutoload[1] == '\0' || wadsToAutoload[1] == '\n') + || (wadsToAutoload[0] == '#')) + continue; + // this marks it so that it loads after loading server addons + else if (fastncmp(wadsToAutoload, "postload ", 9)) { + strremove(wadsToAutoload, "postload "); + postload = true; + } + + // Remove Any Empty or Skipped Lines + for (i = 0; wadsToAutoload[i] != '\0'; i++) + { + if (wadsToAutoload[i] == '\n') + wadsToAutoload[i] = '\0'; + } + + len = strlen(wadsToAutoload); + hasprefix = false; + + for (i = 0; i < len; ++i) + { + if (wadsToAutoload[i] == '_') + { + hasprefix = true; + break; + } + } + + // Lets just hope no one adds bonuschars in autoload + if (hasprefix) + { + // We searching for c in prefix, which stands for "character" and doesn't work well with + // autoload atm, only fine for postload + for (i = 0; i < len; ++i) + { + if (wadsToAutoload[i] == '_') break; // Prefix end + + if (wadsToAutoload[i] == 'c' || wadsToAutoload[i] == 'C') + { + CONS_Alert(CONS_WARNING, "forcing postload for %s as local skin\n", wadsToAutoload); + postload = true; + break; // Found it + } + } + } + + // LOAD IT + if (!postload) + D_AutoloadFile(wadsToAutoload, autoloadwadfiles); + else + D_AutoloadFile(wadsToAutoload, autoloadwadfilespost); + + // end it here + for (i = 0; wadsToAutoload[i] != '\0'; i++) + wadsToAutoload[i] = '\0'; + } + + // we dont want memory leaks around here do we? + fclose(autoloadconfigfile); +} + +void D_CleanFile(char **filearray) { size_t pnumwadfiles; for (pnumwadfiles = 0; filearray[pnumwadfiles]; pnumwadfiles++) @@ -921,6 +1081,8 @@ boolean snw_speedo; // snowy speedometer check boolean clr_hud; // colour hud check boolean big_lap; // bigger lap counter boolean big_lap_color; // bigger lap counter but colour +boolean kartzspeedo; // kartZ speedometer +boolean statdp; // New stat static void IdentifyVersion(void) { @@ -1186,6 +1348,9 @@ void D_SRB2Main(void) if (M_CheckParm("-password") && M_IsNextParm()) D_SetPassword(M_GetNextParm()); + // FIND THEM + D_FindAddonsToAutoload(); + // add any files specified on the command line with -file wadfile // to the wad list if (!(M_CheckParm("-connect") && !M_CheckParm("-server"))) @@ -1278,23 +1443,35 @@ void D_SRB2Main(void) mainwads++; if (found_extra2_kart) mainwads++; - + // now check for speedometer stuff if (W_CheckMultipleLumps("SP_SMSTC", "K_TRNULL", "SP_MKMH", "SP_MMPH", "SP_MFRAC", "SP_MPERC", NULL)) snw_speedo = true; - + // check for bigger lap count if (W_CheckMultipleLumps("K_STLAPB", "K_STLA2B", NULL)) big_lap = true; - + // now check for colour hud stuff if (W_CheckMultipleLumps("K_SCTIME", "K_SCTIMW", "K_SCLAPS", "K_SCLAPW", \ "K_SCBALN", "K_SCBALW", "K_SCKARM", "K_SCTOUT", "K_ISMULC", "K_ITMULC", "K_ITBC","K_ITBCD", "K_ISBC", "K_ISBCD", NULL)) clr_hud = true; - + // check for bigger lap count but color** its color bitch if (W_CheckMultipleLumps("K_SCLAPB", "K_SCLA2B", NULL)) big_lap_color = true; + + // kartzspeedo + if (W_CheckMultipleLumps("K_KZSP1", "K_KZSP2", "K_KZSP3", "K_KZSP4", "K_KZSP5", \ + "K_KZSP6", "K_KZSP7", "K_KZSP8", "K_KZSP9", "K_KZSP10", "K_KZSP11", "K_KZSP12", \ + "K_KZSP13", "K_KZSP14", "K_KZSP15", "K_KZSP16", "K_KZSP17", "K_KZSP18", "K_KZSP19", \ + "K_KZSP20", "K_KZSP21", "K_KZSP22", "K_KZSP23", "K_KZSP24", "K_KZSP25", NULL)) + kartzspeedo = true; + + // stat display for extended player setup + if (W_CheckMultipleLumps("K_STATNB", "K_STATN1", "K_STATN2", "K_STATN3", "K_STATN4", \ + "K_STATN5", "K_STATN6", NULL)) + statdp = true; } // @@ -1372,14 +1549,6 @@ void D_SRB2Main(void) HWR_AddCommands(); #endif -#ifdef HWRENDER - if (rendermode == render_opengl) - { - for (i = 0; i < numwadfiles; i++) - HWR_LoadShaders(i, (wadfiles[i]->type == RET_PK3)); - } -#endif - //--------------------------------------------------------- CONSOLE // setup loading screen SCR_Startup(); @@ -1490,12 +1659,19 @@ void D_SRB2Main(void) I_StartupSound(); I_InitMusic(); S_InitSfxChannels(cv_soundvolume.value); - S_InitMusicDefs(); } + S_InitMusicDefs(); + S_InitMTDefs(); + CONS_Printf("ST_Init(): Init status bar.\n"); ST_Init(); + CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n"); + if (W_AddAutoloadedLocalFiles(autoloadwadfiles) == 0) + CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); + D_CleanFile(autoloadwadfiles); + // Set up splitscreen players before joining! if (!dedicated && (M_CheckParm("-splitscreen") && M_IsNextParm())) { diff --git a/src/d_main.h b/src/d_main.h index 8c91be487..4214e06a4 100644 --- a/src/d_main.h +++ b/src/d_main.h @@ -32,6 +32,14 @@ extern boolean snw_speedo; // snowy speedometer check extern boolean clr_hud; // colour hud check extern boolean big_lap; // bigger lap counter extern boolean big_lap_color; //bigger lap counter but colour +extern boolean kartzspeedo; //kartZ speedo +extern boolean statdp; //stat display for extended player setup + +extern boolean autoloading; +extern boolean autoloaded; +extern boolean postautoloaded; + +extern char *autoloadwadfilespost[MAX_WADFILES]; // the infinite loop of D_SRB2Loop() called from win_main for windows version void D_SRB2Loop(void) FUNCNORETURN; @@ -48,6 +56,8 @@ void D_PostEvent(const event_t *ev); void D_ProcessEvents(void); +void D_CleanFile(char **filearray); + const char *D_Home(void); // diff --git a/src/d_net.c b/src/d_net.c index a4cc3a3be..b0bb637c4 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -51,7 +51,9 @@ doomcom_t *doomcom = NULL; /// \brief network packet data, points inside doomcom doomdata_t *netbuffer = NULL; /// \brief hole punching packet, also points inside doomcom +#ifdef HOLEPUNCH holepunch_t *holepunchpacket = NULL; +#endif #ifdef DEBUGFILE FILE *debugfile = NULL; // put some net info in a file during the game @@ -75,8 +77,10 @@ boolean (*I_NetCanGet)(void) = NULL; void (*I_NetCloseSocket)(void) = NULL; void (*I_NetFreeNodenum)(INT32 nodenum) = NULL; SINT8 (*I_NetMakeNodewPort)(const char *address, const char* port) = NULL; +#ifdef HOLEPUNCH void (*I_NetRequestHolePunch)(INT32 node) = NULL; void (*I_NetRegisterHolePunch)(void) = NULL; +#endif boolean (*I_NetOpenSocket)(void) = NULL; boolean (*I_Ban) (INT32 node) = NULL; void (*I_ClearBans)(void) = NULL; @@ -827,6 +831,10 @@ static const char *packettypename[NUMPACKETTYPE] = "CLIENTJOIN", "NODETIMEOUT", "RESYNCHING", + + "TELLFILESNEEDED", + "MOREFILESNEEDED", + "PING" }; @@ -1349,7 +1357,9 @@ boolean D_CheckNetGame(void) I_Error("Too many nodes (%d), max:%d", doomcom->numnodes, MAXNETNODES); netbuffer = (doomdata_t *)(void *)&doomcom->data; + #ifdef HOLEPUNCH holepunchpacket = (holepunch_t *)(void *)&doomcom->data; + #endif #ifdef DEBUGFILE if (M_CheckParm("-debugfile")) diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 7c1f4bbed..c64804fef 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -35,7 +35,6 @@ #include "p_spec.h" #include "m_cheat.h" #include "d_clisrv.h" -#include "v_video.h" #include "d_main.h" #include "m_random.h" #include "f_finale.h" @@ -195,6 +194,8 @@ static void Command_Isgamemodified_f(void); static void Command_Cheats_f(void); static void Command_ListSkins(void); +static void Command_SkinSearch(void); + #ifdef _DEBUG static void Command_Togglemodified_f(void); @@ -295,12 +296,16 @@ consvar_t cv_skin4 = {"skin4", DEFAULTSKIN4, CV_SAVE|CV_CALL|CV_NOINIT, NULL, Sk // haha I've beaten you now, ONLINE consvar_t cv_localskin = {"internal___localskin", "none", CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showlocalskinmenus = {"showlocalskinmenus", "Yes", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; + consvar_t cv_skipmapcheck = {"skipmapcheck", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; INT32 cv_debug; consvar_t cv_usemouse = {"use_mouse", "Off", CV_SAVE|CV_CALL,usemouse_cons_t, I_StartupMouse, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_usemouse2 = {"use_mouse2", "Off", CV_SAVE|CV_CALL,usemouse_cons_t, I_StartupMouse2, 0, NULL, NULL, 0, 0, NULL}; +//WTF +consvar_t cv_mouseturn = {"mouseturn", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; #if defined(HAVE_SDL) || defined(_WINDOWS) //joystick 1 and 2 consvar_t cv_usejoystick = {"use_joystick", "1", CV_SAVE|CV_CALL, usejoystick_cons_t, @@ -412,7 +417,7 @@ consvar_t cv_kartdebugcheckpoint = {"kartdebugcheckpoint", "Off", CV_NOSHOWHELP, consvar_t cv_kartdebugnodes = {"kartdebugnodes", "Off", CV_NOSHOWHELP, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_kartdebugcolorize = {"kartdebugcolorize", "Off", CV_NOSHOWHELP, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -static CV_PossibleValue_t votetime_cons_t[] = {{10, "MIN"}, {3600, "MAX"}, {0, NULL}}; +static CV_PossibleValue_t votetime_cons_t[] = {{1, "MIN"}, {3600, "MAX"}, {0, NULL}}; consvar_t cv_votetime = {"votetime", "20", CV_NETVAR, votetime_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_ringslinger = {"ringslinger", "No", CV_NETVAR|CV_NOSHOWHELP|CV_CALL|CV_CHEAT, CV_YesNo, @@ -478,6 +483,10 @@ consvar_t cv_showping = {"showping", "Always", CV_SAVE, showping_cons_t, NULL, 0 static CV_PossibleValue_t pingmeasurement_cons_t[] = {{0, "Frames"}, {1, "Milliseconds"}, {0, NULL}}; consvar_t cv_pingmeasurement = {"pingmeasurement", "Frames", CV_SAVE, pingmeasurement_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_pingicon = {"pingicon", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; + +static CV_PossibleValue_t cv_pingstyle_cons_t[] = {{0, "New"}, {1, "Old"}, {0, NULL}}; +consvar_t cv_pingstyle = {"pingstyle", "New", CV_SAVE, cv_pingstyle_cons_t, 0, 0, NULL, NULL, 0, 0, NULL}; + consvar_t cv_luaimmersion = {"luaimmersion", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_minihead = {"smallminimapplayers", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -509,7 +518,7 @@ static CV_PossibleValue_t skinselectspin_cons_t[] = { consvar_t cv_skinselectspin = {"skinselectspin", "5", CV_SAVE, skinselectspin_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t perfstats_cons_t[] = { - {0, "Off"}, {1, "Rendering"}, {2, "Logic"}, {3, "ThinkFrame"}, {0, NULL}}; + {0, "Off"}, {1, "Rendering"}, {2, "Logic"}, {3, "ThinkFrame"}, {4, "PreThinkFrame"}, {5, "PostThinkFrame"}, {0, NULL}}; consvar_t cv_perfstats = {"perfstats", "Off", CV_CALL, perfstats_cons_t, PS_PerfStats_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_ps_thinkframe_page = {"ps_thinkframe_page", "1", CV_CALL, CV_Natural, PS_ThinkFrame_Page_OnChange, 0, NULL, NULL, 0, 0, NULL}; @@ -523,8 +532,8 @@ consvar_t cv_ps_descriptor = {"ps_descriptor", "Average", 0, ps_descriptor_cons_ consvar_t cv_showtrackaddon = {"showtrackaddon", "Yes", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; -static CV_PossibleValue_t skinselectmenu_t[] = {{SKINMENUTYPE_SCROLL, "Scroll"}, {SKINMENUTYPE_2D, "2d"}, {SKINMENUTYPE_GRID, "Grid"}, {0, NULL}}; -consvar_t cv_skinselectmenu = {"skinselectmenu", "Grid", CV_SAVE, skinselectmenu_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t skinselectmenu_t[] = {{SKINMENUTYPE_SCROLL, "Scroll"}, {SKINMENUTYPE_2D, "2d"}, {SKINMENUTYPE_GRID, "Grid"}, {SKINMENUTYPE_EXTENDED, "Extended"}, {0, NULL}}; +consvar_t cv_skinselectmenu = {"skinselectmenu", "Extended", CV_SAVE, skinselectmenu_t, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t skinselectgridsort_t[] ={ { SKINMENUSORT_REALNAME, "Real name" }, @@ -774,6 +783,7 @@ void D_RegisterServerCommands(void) CV_RegisterVar(&cv_joinnextround); #endif CV_RegisterVar(&cv_showjoinaddress); + CV_RegisterVar(&cv_shownodeip); CV_RegisterVar(&cv_blamecfail); #endif @@ -788,6 +798,7 @@ void D_RegisterServerCommands(void) CV_RegisterVar(&cv_showping); CV_RegisterVar(&cv_pingmeasurement); CV_RegisterVar(&cv_pingicon); + CV_RegisterVar(&cv_pingstyle); #ifdef SEENAMES CV_RegisterVar(&cv_allowseenames); @@ -944,9 +955,6 @@ void D_RegisterClientCommands(void) #endif #endif - // FIXME: not to be here.. but needs be done for config loading - CV_RegisterVar(&cv_usegamma); - // m_menu.c //CV_RegisterVar(&cv_compactscoreboard); CV_RegisterVar(&cv_chatheight); @@ -967,6 +975,8 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_luaimmersion); CV_RegisterVar(&cv_fakelocalskin); + + CV_RegisterVar(&cv_showlocalskinmenus); //CV_RegisterVar(&cv_crosshair); //CV_RegisterVar(&cv_crosshair2); @@ -1097,22 +1107,12 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_ps_thinkframe_page); CV_RegisterVar(&cv_ps_samplesize); CV_RegisterVar(&cv_ps_descriptor); - - CV_RegisterVar(&cv_invincmusicfade); - CV_RegisterVar(&cv_growmusicfade); - - CV_RegisterVar(&cv_respawnfademusicout); - CV_RegisterVar(&cv_respawnfademusicback); - - CV_RegisterVar(&cv_resetspecialmusic); - - CV_RegisterVar(&cv_resume); - CV_RegisterVar(&cv_fading); //Value used to store last server player has joined CV_RegisterVar(&cv_lastserver); CV_RegisterVar(&cv_showallmaps); + CV_RegisterVar(&cv_showmusicfilename); // ingame object placing COM_AddCommand("objectplace", Command_ObjectPlace_f); @@ -1158,6 +1158,7 @@ void D_RegisterClientCommands(void) #endif COM_AddCommand("listskins", Command_ListSkins); + COM_AddCommand("skinsearch", Command_SkinSearch); } /** @@ -3082,7 +3083,7 @@ static void Got_Pause(UINT8 **cp, INT32 playernum) if (paused) { - if (!menuactive || netgame) + if ((!menuactive || netgame) && (!cv_pausemusic.value)) S_PauseAudio(); } else @@ -4605,14 +4606,6 @@ static void Command_Addfile(void) SendNetXCmd(XD_ADDFILE, buf, buf_p - buf); } -// i hate myself -static boolean DumbStartsWith(const char *pre, const char *str) -{ - size_t lenpre = strlen(pre), - lenstr = strlen(str); - return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0; -} - /** Adds something at runtime. */ static void @@ -4649,16 +4642,13 @@ Command_Addskins (void) */ } -// args n stuff -#include "args.h" - -static void Command_GLocalSkin (void) +static void Command_GLocalSkin (void) { size_t first_option; size_t option_display; size_t option_all; size_t option_player; - + option_player = COM_CheckPartialParm("-p"); option_display = COM_CheckPartialParm("-d"); option_all = COM_CheckPartialParm("-a"); @@ -4686,31 +4676,27 @@ static void Command_GLocalSkin (void) fuck = ConcatCommandArgv(1, first_option); - char* player_name = player_names[consoleplayer]; - char* display_num = "0"; + const char* player_name = player_names[consoleplayer]; + const char* display_num = "0"; size_t dnum = 0; if (option_display) // -display { // handle default: 0 - if (COM_Argv(option_display + 1)[0] == "" || COM_Argv(option_display + 1)[0] != "-") + if (COM_Argc() >= option_display) display_num = COM_Argv(option_display + 1); - if (isdigit(display_num[0]) || display_num == "0") - { - dnum = atoi(display_num); - if (dnum > 3 || dnum < 0) // nuh uh - dnum = 0; - SetLocalPlayerSkin(displayplayers[dnum], fuck, NULL); + dnum = atoi(display_num); + if (dnum > 3) // nuh uh + dnum = 0; - CONS_Printf("Successfully applied localskin to displayed player.\n"); - return; - } - - CONS_Printf("Could not apply localskin.\n"); - + SetLocalPlayerSkin(displayplayers[dnum], fuck, NULL); + + CONS_Printf("Successfully applied localskin to displayed player.\n"); + + Z_Free(fuck); return; - } + } else if (option_all) // -all { int i; @@ -4723,34 +4709,38 @@ static void Command_GLocalSkin (void) } CONS_Printf("Successfully applied localskin to all players.\n"); + Z_Free(fuck); return; - } + } else // -player or no other arguments { - if (option_player) + if (option_player) { int i; player_name = COM_Argv(option_player + 1); - for (i = 0; i < MAXPLAYERS; ++i) + for (i = 0; i < MAXPLAYERS; ++i) { if (fasticmp(player_names[i], player_name)) SetLocalPlayerSkin(i, fuck, NULL); } CONS_Printf("Successfully applied localskin to specified player.\n"); + Z_Free(fuck); return; - } - else + } + else { SetLocalPlayerSkin(consoleplayer, fuck, &cv_localskin); CONS_Printf("Successfully applied localskin.\n"); + Z_Free(fuck); return; } CONS_Printf("Could not apply localskin.\n"); + Z_Free(fuck); return; } } @@ -6060,6 +6050,26 @@ static void Command_ListSkins(void) } } +static void Command_SkinSearch(void) +{ + size_t i; + UINT16 s; + UINT16 ic = 0; + //skin_t *skininput = &skins[s]; + for (i = 1; i < COM_Argc(); i++){ + for( s = 0 ; s < numallskins ; s++ ) + { + skin_t *skininput = &skins[s]; + if (strcasestr(skininput->realname,COM_Argv(i))) + { + ic++; + CONS_Printf("%d. %s%s:\x80 %s\n", ic,HU_SkinColorToConsoleColor(skininput->prefcolor),skininput->realname,skininput->name); + } + } + } + CONS_Printf("Total %d skins.\n", ic); +} + /** Sends a color change for the console player, unless that player is moving. * \sa cv_playercolor, Color2_OnChange, Skin_OnChange * \author Graue diff --git a/src/d_netcmd.h b/src/d_netcmd.h index 9b6d99b25..8fbdf1d5f 100644 --- a/src/d_netcmd.h +++ b/src/d_netcmd.h @@ -41,6 +41,8 @@ extern consvar_t cv_splitplayers; extern consvar_t cv_seenames, cv_allowseenames; #endif extern consvar_t cv_usemouse; +//WTF +extern consvar_t cv_mouseturn; extern consvar_t cv_usejoystick; extern consvar_t cv_usejoystick2; extern consvar_t cv_usejoystick3; @@ -154,6 +156,7 @@ extern consvar_t cv_pingtimeout; extern consvar_t cv_showping; extern consvar_t cv_pingmeasurement; extern consvar_t cv_pingicon; +extern consvar_t cv_pingstyle; //extern consvar_t cv_smallpos; extern consvar_t cv_showminimapnames; @@ -164,6 +167,7 @@ extern consvar_t cv_showlapemblem; extern consvar_t cv_showviewpointtext; extern consvar_t cv_luaimmersion; extern consvar_t cv_fakelocalskin; +extern consvar_t cv_showlocalskinmenus; extern consvar_t cv_skipmapcheck; @@ -183,7 +187,8 @@ typedef enum { SKINMENUTYPE_SCROLL = 0, SKINMENUTYPE_2D, // 1 - SKINMENUTYPE_GRID // 2 + SKINMENUTYPE_GRID, // 2 + SKINMENUTYPE_EXTENDED // 3 } skinmenutype_t; typedef enum diff --git a/src/d_netfil.c b/src/d_netfil.c index 0f835ddd2..a51d44f80 100644 --- a/src/d_netfil.c +++ b/src/d_netfil.c @@ -1342,7 +1342,7 @@ void CURLGetFile(void) if (easyres == CURLE_HTTP_RETURNED_ERROR) curl_easy_getinfo(e, CURLINFO_RESPONSE_CODE, &response_code); - easy_handle_error = (response_code) ? va("HTTP reponse code %ld", response_code) : curl_easy_strerror(easyres); + easy_handle_error = (response_code) ? va("HTTP response code %ld", response_code) : curl_easy_strerror(easyres); curl_curfile->status = FS_FALLBACK; curl_curfile->currentsize = curl_origfilesize; curl_curfile->totalsize = curl_origtotalfilesize; diff --git a/src/d_player.h b/src/d_player.h index c9329fe9c..4d61474fb 100644 --- a/src/d_player.h +++ b/src/d_player.h @@ -416,8 +416,8 @@ typedef struct player_s UINT8 skincolor; INT32 skin; - INT32 localskin; - boolean skinlocal; + INT32 localskin; // current localskin number + boolean skinlocal; // determines if localskin is a skin already loaded in the server UINT32 score; // player score fixed_t dashspeed; // dashing speed diff --git a/src/dehacked.c b/src/dehacked.c index b34303c20..9326b526b 100644 --- a/src/dehacked.c +++ b/src/dehacked.c @@ -8289,6 +8289,7 @@ struct { // Frame settings {"FF_FRAMEMASK",FF_FRAMEMASK}, + {"FF_HORIZONTALFLIP",FF_HORIZONTALFLIP}, {"FF_PAPERSPRITE",FF_PAPERSPRITE}, {"FF_ANIMATE",FF_ANIMATE}, {"FF_FULLBRIGHT",FF_FULLBRIGHT}, diff --git a/src/discord.c b/src/discord.c index ea9bc66b9..4e574f05e 100644 --- a/src/discord.c +++ b/src/discord.c @@ -101,7 +101,7 @@ static void DRPC_HandleReady(const DiscordUser *user) { if (cv_discordstreamer.value) { - CONS_Printf("Discord: connected to %s\n", user->username); + CONS_Printf("Discord: connection successful\n"); } else { @@ -480,14 +480,18 @@ void DRPC_UpdatePresence(void) // Server info if (netgame) { +#ifdef MASTERSERVER if (cv_advertise.value) { discordPresence.state = "Public"; } else { +#endif discordPresence.state = "Private"; +#ifdef MASTERSERVER } +#endif discordPresence.partyId = server_context; // Thanks, whoever gave us Mumble support, for implementing the EXACT thing Discord wanted for this field! discordPresence.partySize = D_NumPlayers(); // Players in server diff --git a/src/doomdef.h b/src/doomdef.h index f41a02782..60035995e 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -127,8 +127,8 @@ extern char logfilename[1024]; #else #define VERSION 1 // Game version #define SUBVERSION 6 // more precise version number -#define VERSIONSTRING "Saturn v4 " -#define VERSIONSTRINGW L"Saturn v4" +#define VERSIONSTRING "Saturn v5.1 " +#define VERSIONSTRINGW L"Saturn v5.1" // Hey! If you change this, add 1 to the MODVERSION below! Otherwise we can't force updates! // And change CMakeLists.txt (not src/, but in root), for CMake users! // AND appveyor.yml, for the build bots! @@ -639,6 +639,7 @@ extern const char *compdate, *comptime, *comprevision, *compbranch; #if defined (HAVE_CURL) && ! defined (NONET) #define MASTERSERVER +#define HOLEPUNCH #else #undef UPDATE_ALERT #endif diff --git a/src/doomstat.h b/src/doomstat.h index fc4c38733..3f90eb531 100644 --- a/src/doomstat.h +++ b/src/doomstat.h @@ -108,8 +108,6 @@ extern boolean digital_disabled; extern boolean menuactive; // Menu overlaid? extern UINT8 paused; // Game paused? extern UINT8 window_notinfocus; // are we in focus? (backend independant -- handles auto pausing and display of "focus lost" message) -extern INT32 window_x; -extern INT32 window_y; extern boolean nodrawers; extern boolean noblit; diff --git a/src/dummy/i_cdmus.c b/src/dummy/i_cdmus.c deleted file mode 100644 index fc35eb9cf..000000000 --- a/src/dummy/i_cdmus.c +++ /dev/null @@ -1,38 +0,0 @@ -#include "../command.h" -#include "../s_sound.h" -#include "../i_sound.h" - -// -// CD MUSIC I/O -// - -UINT8 cdaudio_started = 0; - -consvar_t cd_volume = {"cd_volume","31",CV_SAVE,soundvolume_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cdUpdate = {"cd_update","1",CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; - - -void I_InitCD(void){} - -void I_StopCD(void){} - -void I_PauseCD(void){} - -void I_ResumeCD(void){} - -void I_ShutdownCD(void){} - -void I_UpdateCD(void){} - -void I_PlayCD(UINT8 track, UINT8 looping) -{ - (void)track; - (void)looping; -} - -boolean I_SetVolumeCD(int volume) -{ - (void)volume; - return false; -} - diff --git a/src/dummy/i_sound.c b/src/dummy/i_sound.c index f09158e01..ff01bdff0 100644 --- a/src/dummy/i_sound.c +++ b/src/dummy/i_sound.c @@ -169,7 +169,7 @@ void I_SetMusicVolume(UINT8 volume) (void)volume; } -boolean I_SetSongTrack(int track) +boolean I_SetSongTrack(INT32 track) { (void)track; return false; diff --git a/src/f_finale.c b/src/f_finale.c index 1b5310e01..2d9a45e8c 100644 --- a/src/f_finale.c +++ b/src/f_finale.c @@ -520,6 +520,19 @@ static const char *credits[] = { "Karol \"Fooruman\" D""\x1E""browski", // DÄ…browski, accents in srb2 :ytho: "\"Virt\"", "", + "\1Saturn", + "\"Alufolie91\" aka \"Alug\"", + "\"Indev\"", + "\"Haya\"", + "\"NepDisk\"", + "\"Xyzzy\"", + " ", + "\"Sunflower\" aka \"AnimeSonic\"", + "\"Yuz\" aka \"Yuzler\"", + "\"Democrab\"", + "\"Expand\" aka \"Maver\"", + "\"Nexit\"", + "", "\1Special Thanks", "SEGA", "Sonic Team", @@ -559,10 +572,11 @@ static struct { {224, 80+(216*13), "K_ITMINE", SKINCOLOR_BRONZE}, {224, 80+(216*14), "K_ITTHNS", SKINCOLOR_RASPBERRY}, {224, 80+(216*15), "K_ITINV1", SKINCOLOR_GREY}, + {224, 80+(216*16), "K_ITSINK", SKINCOLOR_PINETREE}, // This Tyler52 gag is troublesome // Alignment should be ((spaces+1 * 100) + (headers+1 * 38) + (lines * 15)) // Current max image spacing: (216*17) - {112, (16*100)+(19*38)+(103*15), "TYLER52", SKINCOLOR_NONE}, + {112, (17*100)+(20*38)+(114*15), "TYLER52", SKINCOLOR_NONE}, {0, 0, NULL, SKINCOLOR_NONE} }; @@ -596,6 +610,7 @@ void F_StartCredits(void) timetonext = 2*TICRATE; } + void F_CreditDrawer(void) { UINT16 i; @@ -925,7 +940,6 @@ void F_GameEndTicker(void) D_StartTitle(); } - // ============== // TITLE SCREEN // ============== @@ -988,7 +1002,7 @@ void F_TitleScreenDrawer(void) else { INT32 transval = 0; - + if (finalecount <= (50+(9<<1))) transval = (finalecount - 50)>>1; diff --git a/src/filesrch.c b/src/filesrch.c index d51ef9516..e2acdf324 100644 --- a/src/filesrch.c +++ b/src/filesrch.c @@ -337,6 +337,23 @@ size_t dir_on[menudepth]; UINT8 refreshdirmenu = 0; char *refreshdirname = NULL; +// Checks if the specified path is a directory. +// Returns 1 if so, 0 if not, and -1 if an error occurred. +// direrror is set if there was an error. +INT32 pathisdirectory(const char *path) +{ + struct stat fsstat; + + if (stat(path, &fsstat) < 0) + { + return -1; + } + else if (S_ISDIR(fsstat.st_mode)) + return 1; + + return 0; +} + filestatus_t filesearch(char *filename, const char *startpath, const UINT8 *wantedmd5sum, boolean completepath, int maxsearchdepth) { filestatus_t retval = FS_NOTFOUND; @@ -396,9 +413,28 @@ filestatus_t filesearch(char *filename, const char *startpath, const UINT8 *want // okay, now we actually want searchpath to incorporate d_name strcpy(&searchpath[searchpathindex[depthleft]],dent->d_name); +#if defined(__linux__) || defined(__FreeBSD__) + if (dent->d_type == DT_UNKNOWN) + if (lstat(searchpath,&fsstat) == 0 && S_ISDIR(fsstat.st_mode)) + dent->d_type = DT_DIR; + else if (lstat(searchpath,&fsstat) == 0 && S_ISLNK(fsstat.st_mode)) + dent->d_type = DT_LNK; + + // Symlinks aren't always directory symlinks. Dunno if this would resolve recursive + // symlinks, but i think stat already does that + if (dent->d_type == DT_LNK && stat(searchpath,&fsstat) == 0 && !S_ISDIR(fsstat.st_mode)) + { + dent->d_type = DT_UNKNOWN; + } + + // Linux and FreeBSD has a special field for file type on dirent, so use that to speed up lookups. + // FIXME: should we also follow symlinks? + if ((dent->d_type == DT_DIR && depthleft) || (dent->d_type == DT_LNK && depthleft)) +#else if (stat(searchpath,&fsstat) < 0) // do we want to follow symlinks? if not: change it to lstat ; // was the file (re)moved? can't stat it else if (S_ISDIR(fsstat.st_mode) && depthleft) +#endif { searchpathindex[--depthleft] = strlen(searchpath) + 1; dirhandle[depthleft] = opendir(searchpath); diff --git a/src/filesrch.h b/src/filesrch.h index 4cb92b238..b991e8b16 100644 --- a/src/filesrch.h +++ b/src/filesrch.h @@ -89,6 +89,7 @@ typedef enum REFRESHDIR_GAMEDATA = 64 } refreshdir_enum; +INT32 pathisdirectory(const char *path); void closefilemenu(boolean validsize); void searchfilemenu(char *tempname); boolean preparefilemenu(boolean samedepth, boolean replayhut); diff --git a/src/g_game.c b/src/g_game.c index 0e31ab4f5..38f063f62 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -496,12 +496,11 @@ consvar_t cv_ydeadzone4 = {"joy4_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_c static CV_PossibleValue_t driftsparkpulse_t[] = {{0, "MIN"}, {FRACUNIT*3, "MAX"}, {0, NULL}}; consvar_t cv_driftsparkpulse = {"driftsparkpulse", "1.4", CV_FLOAT | CV_SAVE, driftsparkpulse_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -static CV_PossibleValue_t stretchfactor_t[] = {{0, "MIN"}, {FRACUNIT, "MAX"}, {0, NULL}}; -consvar_t cv_gravstretch = {"gravstretch", "0", CV_FLOAT | CV_SAVE, stretchfactor_t, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_sloperoll = {"sloperoll", "Off", CV_SAVE|CV_CALL, CV_OnOff, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_sliptideroll = {"sliptideroll", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t stretchfactor_t[] = { + {0, "Off"}, {FRACUNIT/8, "0.125"}, {FRACUNIT/4, "0.250"}, + {3*FRACUNIT/8, "0.375"}, {FRACUNIT/2, "0.500"}, {5*FRACUNIT/8, "0.625"}, + {3*FRACUNIT/4, "0.750"}, {7*FRACUNIT/8, "0.875"}, {FRACUNIT, "Max"}, {0, NULL}}; +consvar_t cv_gravstretch = {"gravstretch", "0", CV_SAVE, stretchfactor_t, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t slamsound_t[] = {{0, "Off"}, {1, "On"}, {0, NULL}}; consvar_t cv_slamsound = {"slamsound", "1", CV_SAVE, slamsound_t, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -512,17 +511,14 @@ static CV_PossibleValue_t sloperolldist_cons_t[] = { {3072, "3072"}, {4096, "4096"}, {6144, "6144"}, {8192, "8192"}, {0, "Infinite"}, {0, NULL}}; consvar_t cv_sloperolldist = {"sloperolldist", "Infinite", CV_SAVE, sloperolldist_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t sloperoll_cons_t[] = {{0, "Off"}, {1, "Players"}, {2, "Everything"}, {0, NULL}}; +consvar_t cv_spriteroll = {"spriteroll", "Off", CV_SAVE|CV_CALL, CV_OnOff, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_sloperoll = {"sloperoll", "Off", CV_SAVE|CV_CALL, sloperoll_cons_t, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_sparkroll = {"sparkroll", "Off", CV_SAVE|CV_CALL, CV_OnOff, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_sliptideroll = {"sliptideroll", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_cechotoggle = {"show_cecho", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_invincmusicfade = {"invincmusicfade", "300", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_growmusicfade = {"growmusicfade", "500", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_respawnfademusicout = {"respawnfademusicout", "1000", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_respawnfademusicback = {"respawnfademusicback", "500", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_resetspecialmusic = {"resetspecialmusic", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_resume = {"resume", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_fading = {"fading", "Off", CV_SAVE|CV_CALL, CV_OnOff, Bird_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; - #if MAXPLAYERS > 16 #error "please update player_name table using the new value for MAXPLAYERS" #endif @@ -1423,9 +1419,9 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) side += ((axis * sidemove[0]) >> 10); } - // Specator mouse turning - if (player->spectator) + if (player->spectator || cv_mouseturn.value) { + //THIS WORKS WTF???????? cmd->angleturn = (INT16)(cmd->angleturn - ((mousex*(encoremode ? -1 : 1)*8))); cmd->driftturn = (INT16)(cmd->driftturn - ((mousex*(encoremode ? -1 : 1)*8))); } @@ -1961,7 +1957,7 @@ boolean G_Responder(event_t *ev) paused = true; S_PauseAudio(); } - else if (paused) + else if ((paused) && (!cv_pausemusic.value)) S_PauseAudio(); else S_ResumeAudio(); @@ -2828,7 +2824,7 @@ void G_PlayerReborn(INT32 player) /* I'm putting this here because lol */ - fade = ( cv_fading.value && P_IsLocalPlayer(p) ); + fade = (cv_fading.value && cv_birdmusic.value && P_IsLocalPlayer(p)); if (fade) { @@ -5036,16 +5032,29 @@ void G_FreeMapSearch(mapsearchfreq_t *freq, INT32 freqc) INT32 G_FindMapByNameOrCode(const char *mapname, char **realmapnamep) { boolean usemapcode = false; - INT32 newmapnum; - size_t mapnamelen; + size_t mapnamelen = strlen(mapname); char *p; - - mapnamelen = strlen(mapname); - - if (mapnamelen == 2)/* maybe two digit code */ + + if (mapnamelen == 1) + { + if (mapname[0] == '*') // current map + return gamemap; + else if (mapname[0] == '+' && mapheaderinfo[gamemap-1]) // next map + { + newmapnum = mapheaderinfo[gamemap-1]->nextlevel; + if (newmapnum < 1 || newmapnum > NUMMAPS) + { + CONS_Alert(CONS_ERROR, M_GetText("NextLevel (%d) is not a valid map.\n"), newmapnum); + return 0; + } + else + return newmapnum; + } + } + else if (mapnamelen == 2)/* maybe two digit code */ { if (( newmapnum = M_MapNumber(mapname[0], mapname[1]) )) usemapcode = true; @@ -8189,7 +8198,7 @@ void G_AddGhost(char *defdemoname) count = READUINT16(p); while (count--) { - SKIPSTRING(p); + p += 2; SKIPSTRING(p); p++; } diff --git a/src/g_game.h b/src/g_game.h index 8cebc088a..a57468a2e 100644 --- a/src/g_game.h +++ b/src/g_game.h @@ -127,25 +127,33 @@ extern consvar_t cv_turnaxis4,cv_moveaxis4,cv_brakeaxis4,cv_aimaxis4,cv_lookaxis extern consvar_t cv_ghost_besttime, cv_ghost_bestlap, cv_ghost_last, cv_ghost_guest, cv_ghost_staff; // Hud offsets -extern consvar_t cv_item_xoffset; -extern consvar_t cv_item_yoffset; -extern consvar_t cv_time_xoffset; -extern consvar_t cv_time_yoffset; -extern consvar_t cv_laps_xoffset; -extern consvar_t cv_laps_yoffset; -extern consvar_t cv_spdm_xoffset; -extern consvar_t cv_spdm_yoffset; -extern consvar_t cv_posi_xoffset; -extern consvar_t cv_posi_yoffset; -extern consvar_t cv_face_xoffset; -extern consvar_t cv_face_yoffset; -extern consvar_t cv_stcd_xoffset; -extern consvar_t cv_stcd_yoffset; -extern consvar_t cv_chek_yoffset; -extern consvar_t cv_mini_xoffset; -extern consvar_t cv_mini_yoffset; -extern consvar_t cv_want_xoffset; -extern consvar_t cv_want_yoffset; +#define DECL_HUD_OFFSET_X(name)\ +extern consvar_t cv_##name##_xoffset; + +#define DECL_HUD_OFFSET_Y(name)\ +extern consvar_t cv_##name##_yoffset; + +#define DECL_HUD_OFFSET(name)\ +DECL_HUD_OFFSET_X(name)\ +DECL_HUD_OFFSET_Y(name) + +DECL_HUD_OFFSET(item); // Item box +DECL_HUD_OFFSET(time); // Time +DECL_HUD_OFFSET(laps); // Number of laps +DECL_HUD_OFFSET(dnft); // Countdown (did not finish timer) +DECL_HUD_OFFSET(speed); // Speedometer +DECL_HUD_OFFSET(posi); // Position in race +DECL_HUD_OFFSET(face); // Mini rankings +DECL_HUD_OFFSET(stcd); // Starting countdown +DECL_HUD_OFFSET_Y(chek); // Check gfx +DECL_HUD_OFFSET(mini); // Minimap +DECL_HUD_OFFSET(want); // Wanted +DECL_HUD_OFFSET(stat); // Stats + +#undef DECL_HUD_OFFSET +#undef DECL_HUD_OFFSET_X +#undef DECL_HUD_OFFSET_Y + extern consvar_t cv_showinput; extern consvar_t cv_newspeedometer; @@ -156,23 +164,14 @@ extern consvar_t cv_saltysquish; extern consvar_t cv_driftsparkpulse; extern consvar_t cv_gravstretch; extern consvar_t cv_sloperoll; +extern consvar_t cv_spriteroll; extern consvar_t cv_sliptideroll; extern consvar_t cv_slamsound; extern consvar_t cv_sloperolldist; - -extern consvar_t cv_invincmusicfade; -extern consvar_t cv_growmusicfade; - -extern consvar_t cv_respawnfademusicout; -extern consvar_t cv_respawnfademusicback; - -extern consvar_t cv_resetspecialmusic; +extern consvar_t cv_sparkroll; extern consvar_t cv_cechotoggle; -extern consvar_t cv_resume; -extern consvar_t cv_fading; - #ifndef NONET extern consvar_t cv_chatlogsize; #endif diff --git a/src/hardware/hw_batching.c b/src/hardware/hw_batching.c new file mode 100644 index 000000000..388bb2023 --- /dev/null +++ b/src/hardware/hw_batching.c @@ -0,0 +1,462 @@ +// SONIC ROBO BLAST 2 +//----------------------------------------------------------------------------- +// Copyright (C) 2020-2023 by Sonic Team Junior. +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- +/// \file hw_batching.c +/// \brief Draw call batching and related things. + +#ifdef HWRENDER +#include "hw_glob.h" +#include "hw_batching.h" +#include "hw_main.h" +#include "../i_system.h" + +typedef struct +{ + FSurfaceInfo surf; // surf also has its own polyflags for some reason, but it seems unused + unsigned int vertsIndex; // location of verts in unsortedVertices + FUINT numVerts; + FBITFIELD polyFlags; + GLMipmap_t *texture; + int shader; + // this tells batching that the plane belongs to a horizon line and must be drawn in correct order with the skywalls + boolean horizonSpecial; +} DrawCallInfo; + +// The texture for the next polygon given to HWR_ProcessPolygon. +// Set with HWR_SetCurrentTexture. +GLMipmap_t *current_texture = NULL; + +boolean currently_batching = false; + +// Dynamic arrays for: +// - unsorted draw calls +// - sorted order of draw calls +// - unsorted vertices +// - final (sorted) vertices +// - vertex indices for sorted vertices + +// contains the draw calls from DrawPolygon, waiting to be processed +DrawCallInfo* drawCalls = NULL; +int drawCallsSize = 0; +int drawCallsCapacity = 65536; + +// contains sorted order (array indices) for drawCalls +// (therefore size and capacity shared with it) +UINT32* drawCallOrder = NULL; + +// contains unsorted vertices and texture coordinates from DrawPolygon +FOutVector* unsortedVertices = NULL; +int unsortedVerticesSize = 0; +int unsortedVerticesCapacity = 65536; + +// contains subset of sorted vertices and texture coordinates to be sent to gpu +FOutVector* finalVertices = NULL; +int finalVerticesSize = 0; +int finalVerticesCapacity = 65536; + +// contains vertex indices into finalVertices for glDrawElements, +// taking into account fan->triangles conversion +UINT32* finalIndices = NULL; // this is alloced with 3x finalVertices size +int finalIndicesSize = 0; + +// Enables batching mode. HWR_ProcessPolygon will collect polygons instead of passing them directly to the rendering backend. +// Call HWR_RenderBatches to render all the collected geometry. +void HWR_StartBatching(void) +{ + if (currently_batching) + I_Error("Repeat call to HWR_StartBatching without HWR_RenderBatches"); + + // init arrays if that has not been done yet + if (!finalVertices) + { + finalVertices = malloc(finalVerticesCapacity * sizeof(FOutVector)); + finalIndices = malloc(finalVerticesCapacity * 3 * sizeof(UINT32)); + drawCalls = malloc(drawCallsCapacity * sizeof(DrawCallInfo)); + drawCallOrder = malloc(drawCallsCapacity * sizeof(UINT32)); + unsortedVertices = malloc(unsortedVerticesCapacity * sizeof(FOutVector)); + } + + currently_batching = true; +} + +// This replaces the direct calls to pfnSetTexture in cases where batching is available. +// The texture selection is saved for the next HWR_ProcessPolygon call. +// Doing this was easier than getting a texture pointer to HWR_ProcessPolygon. +void HWR_SetCurrentTexture(GLMipmap_t *texture) +{ + if (currently_batching) + current_texture = texture; + else + HWD.pfnSetTexture(texture); +} + +static void HWR_CollectDrawCallInfo(FSurfaceInfo *pSurf, FUINT iNumPts, FBITFIELD PolyFlags, int shader_target, boolean horizonSpecial) +{ + // make sure dynamic array has capacity + if (drawCallsSize == drawCallsCapacity) + { + DrawCallInfo* new_array; + // ran out of space, make new array double the size + drawCallsCapacity *= 2; + new_array = malloc(drawCallsCapacity * sizeof(DrawCallInfo)); + memcpy(new_array, drawCalls, drawCallsSize * sizeof(DrawCallInfo)); + free(drawCalls); + drawCalls = new_array; + // also need to redo the index array, dont need to copy it though + free(drawCallOrder); + drawCallOrder = malloc(drawCallsCapacity * sizeof(UINT32)); + } + // add entry to array + drawCalls[drawCallsSize].surf = *pSurf; + drawCalls[drawCallsSize].vertsIndex = unsortedVerticesSize; + drawCalls[drawCallsSize].numVerts = iNumPts; + drawCalls[drawCallsSize].polyFlags = PolyFlags; + drawCalls[drawCallsSize].texture = current_texture; + drawCalls[drawCallsSize].shader = (shader_target != -1) ? HWR_GetShaderFromTarget(shader_target) : shader_target; + drawCalls[drawCallsSize].horizonSpecial = horizonSpecial; + drawCallsSize++; +} + +static void HWR_CollectDrawCallVertices(FOutVector *pOutVerts, FUINT iNumPts) +{ + // make sure dynamic array has capacity + while (unsortedVerticesSize + (int)iNumPts > unsortedVerticesCapacity) + { + FOutVector* new_array; + // need more space for vertices in unsortedVertices + unsortedVerticesCapacity *= 2; + new_array = malloc(unsortedVerticesCapacity * sizeof(FOutVector)); + memcpy(new_array, unsortedVertices, unsortedVerticesSize * sizeof(FOutVector)); + free(unsortedVertices); + unsortedVertices = new_array; + } + // add vertices to array + memcpy(&unsortedVertices[unsortedVerticesSize], pOutVerts, iNumPts * sizeof(FOutVector)); + unsortedVerticesSize += iNumPts; +} + +// If batching is enabled, this function collects the polygon data and the chosen texture +// for later use in HWR_RenderBatches. Otherwise the rendering backend is used to +// render the polygon immediately. +void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, int shader_target, boolean horizonSpecial) +{ + if (currently_batching) + { + if (!pSurf) + { + // handling null FSurfaceInfo is not implemented + I_Error("Got a null FSurfaceInfo in batching"); + } + + HWR_CollectDrawCallInfo(pSurf, iNumPts, PolyFlags, shader_target, horizonSpecial); + HWR_CollectDrawCallVertices(pOutVerts, iNumPts); + } + else + { + HWD.pfnSetShader((shader_target != SHADER_NONE) ? HWR_GetShaderFromTarget(shader_target) : shader_target); + HWD.pfnDrawPolygon(pSurf, pOutVerts, iNumPts, PolyFlags); + } +} + +static int compareDrawCalls(const void *p1, const void *p2) +{ + UINT32 index1 = *(const UINT32*)p1; + UINT32 index2 = *(const UINT32*)p2; + DrawCallInfo* poly1 = &drawCalls[index1]; + DrawCallInfo* poly2 = &drawCalls[index2]; + int diff; + INT64 diff64; + UINT32 downloaded1 = 0; + UINT32 downloaded2 = 0; + + int shader1 = poly1->shader; + int shader2 = poly2->shader; + // make skywalls and horizon lines first in order + if (poly1->polyFlags & PF_NoTexture || poly1->horizonSpecial) + shader1 = -1; + if (poly2->polyFlags & PF_NoTexture || poly2->horizonSpecial) + shader2 = -1; + diff = shader1 - shader2; + if (diff != 0) return diff; + + // skywalls and horizon lines must retain their order for horizon lines to work + if (shader1 == -1 && shader2 == -1) + return index1 - index2; + + if (poly1->texture) + downloaded1 = poly1->texture->downloaded; // there should be a opengl texture name here, usable for comparisons + if (poly2->texture) + downloaded2 = poly2->texture->downloaded; + diff64 = downloaded1 - downloaded2; + if (diff64 != 0) return diff64; + + diff = poly1->polyFlags - poly2->polyFlags; + if (diff != 0) return diff; + + diff64 = poly1->surf.PolyColor.rgba - poly2->surf.PolyColor.rgba; + if (diff64 < 0) return -1; else if (diff64 > 0) return 1; + diff64 = poly1->surf.TintColor.rgba - poly2->surf.TintColor.rgba; + if (diff64 < 0) return -1; else if (diff64 > 0) return 1; + diff64 = poly1->surf.FadeColor.rgba - poly2->surf.FadeColor.rgba; + if (diff64 < 0) return -1; else if (diff64 > 0) return 1; + + diff = poly1->surf.LightInfo.light_level - poly2->surf.LightInfo.light_level; + if (diff != 0) return diff; + diff = poly1->surf.LightInfo.fade_start - poly2->surf.LightInfo.fade_start; + if (diff != 0) return diff; + diff = poly1->surf.LightInfo.fade_end - poly2->surf.LightInfo.fade_end; + return diff; +} + +static int compareDrawCallsNoShaders(const void *p1, const void *p2) +{ + UINT32 index1 = *(const UINT32*)p1; + UINT32 index2 = *(const UINT32*)p2; + DrawCallInfo* poly1 = &drawCalls[index1]; + DrawCallInfo* poly2 = &drawCalls[index2]; + int diff; + INT64 diff64; + + GLMipmap_t *texture1 = poly1->texture; + GLMipmap_t *texture2 = poly2->texture; + UINT32 downloaded1 = 0; + UINT32 downloaded2 = 0; + if (poly1->polyFlags & PF_NoTexture || poly1->horizonSpecial) + texture1 = NULL; + if (poly2->polyFlags & PF_NoTexture || poly2->horizonSpecial) + texture2 = NULL; + if (texture1) + downloaded1 = texture1->downloaded; // there should be a opengl texture name here, usable for comparisons + if (texture2) + downloaded2 = texture2->downloaded; + // skywalls and horizon lines must retain their order for horizon lines to work + if (!texture1 && !texture2) + return index1 - index2; + diff64 = downloaded1 - downloaded2; + if (diff64 != 0) return diff64; + + diff = poly1->polyFlags - poly2->polyFlags; + if (diff != 0) return diff; + + diff64 = poly1->surf.PolyColor.rgba - poly2->surf.PolyColor.rgba; + if (diff64 < 0) return -1; else if (diff64 > 0) return 1; + + return 0; +} + +static void HWR_CollectVerticesIntoBatch(DrawCallInfo *drawCall) +{ + int firstVIndex; + int lastVIndex; + int numVerts = drawCall->numVerts; + // before writing, check if there is enough room + // using 'while' instead of 'if' here makes sure that there will *always* be enough room. + // probably never will this loop run more than once though + while (finalVerticesSize + numVerts > finalVerticesCapacity) + { + FOutVector* new_array; + UINT32* new_index_array; + finalVerticesCapacity *= 2; + new_array = malloc(finalVerticesCapacity * sizeof(FOutVector)); + memcpy(new_array, finalVertices, finalVerticesSize * sizeof(FOutVector)); + free(finalVertices); + finalVertices = new_array; + // also increase size of index array, 3x of vertex array since + // going from fans to triangles increases vertex count to 3x + new_index_array = malloc(finalVerticesCapacity * 3 * sizeof(UINT32)); + memcpy(new_index_array, finalIndices, finalIndicesSize * sizeof(UINT32)); + free(finalIndices); + finalIndices = new_index_array; + } + // write the vertices of the polygon + memcpy(&finalVertices[finalVerticesSize], &unsortedVertices[drawCall->vertsIndex], + numVerts * sizeof(FOutVector)); + // write the indexes, pointing to the fan vertexes but in triangles format + firstVIndex = finalVerticesSize; + lastVIndex = finalVerticesSize + numVerts; + finalVerticesSize += 2; + while (finalVerticesSize < lastVIndex) + { + finalIndices[finalIndicesSize++] = firstVIndex; + finalIndices[finalIndicesSize++] = finalVerticesSize - 1; + finalIndices[finalIndicesSize++] = finalVerticesSize++; + } +} + +static GLMipmap_t *HWR_GetDrawCallTexture(DrawCallInfo *dc) +{ + return (dc->polyFlags & PF_NoTexture) ? NULL : dc->texture; +} + +// flags returned by HWR_MarkStateChanges +#define SHADER_CHANGED 1 +#define TEXTURE_CHANGED 2 +#define POLYFLAGS_CHANGED 4 +#define SURFACEINFO_CHANGED 8 + +static unsigned int HWR_MarkStateChanges(DrawCallInfo *current, DrawCallInfo *next) +{ + unsigned int stateChanges = 0; + FSurfaceInfo *currentSI = ¤t->surf; + FSurfaceInfo *nextSI = &next->surf; + + // check if a state change is required and flag it to stateChanges + + if (current->shader != next->shader && cv_grshaders.value && gr_shadersavailable) + stateChanges |= SHADER_CHANGED; + if (HWR_GetDrawCallTexture(current) != HWR_GetDrawCallTexture(next)) + stateChanges |= TEXTURE_CHANGED; + if (current->polyFlags != next->polyFlags) + stateChanges |= POLYFLAGS_CHANGED; + if (cv_grshaders.value && gr_shadersavailable) + { + if (currentSI->PolyColor.rgba != nextSI->PolyColor.rgba || + currentSI->TintColor.rgba != nextSI->TintColor.rgba || + currentSI->FadeColor.rgba != nextSI->FadeColor.rgba || + currentSI->LightInfo.light_level != nextSI->LightInfo.light_level || + currentSI->LightInfo.fade_start != nextSI->LightInfo.fade_start || + currentSI->LightInfo.fade_end != nextSI->LightInfo.fade_end) + { + stateChanges |= SURFACEINFO_CHANGED; + } + } + else + { + if (currentSI->PolyColor.rgba != nextSI->PolyColor.rgba) + stateChanges |= SURFACEINFO_CHANGED; + } + + return stateChanges; +} + +static void HWR_ExecuteStateChanges(unsigned int stateChanges, DrawCallInfo *dc) +{ + if ((stateChanges & SHADER_CHANGED) && cv_grshaders.value && gr_shadersavailable) + { + HWD.pfnSetShader(dc->shader); + ps_hw_numshaders.value.i++; + } + if (stateChanges & TEXTURE_CHANGED) + { + // for PF_NoTexture the texture is set in DrawIndexedTriangles + if (!(dc->polyFlags & PF_NoTexture)) + { + // texture should be already ready for use from calls to + // SetTexture during batch collection + HWD.pfnSetTexture(dc->texture); + } + ps_hw_numtextures.value.i++; + } + // these two are just parameters to DrawIndexedTriangles + // (changes to polyflags states are tracked in r_opengl.c though) + if (stateChanges & POLYFLAGS_CHANGED) + ps_hw_numpolyflags.value.i++; + if (stateChanges & SURFACEINFO_CHANGED) + ps_hw_numcolors.value.i++; +} + + +static void HWR_InitBatchingStats(void) +{ + ps_hw_numpolys.value.i = drawCallsSize; + ps_hw_numcalls.value.i = ps_hw_numverts.value.i + = ps_hw_numshaders.value.i = ps_hw_numtextures.value.i + = ps_hw_numpolyflags.value.i = ps_hw_numcolors.value.i = 0; +} + +// This function organizes the geometry and draw calls collected by HWR_ProcessPolygon +// calls into batches and uses the rendering backend to draw them. +void HWR_RenderBatches(void) +{ + int drawCallReadPos = 0; // position in drawCallOrder + int i; + + if (!currently_batching) + I_Error("HWR_RenderBatches called without starting batching"); + + currently_batching = false; // no longer collecting batches + + HWR_InitBatchingStats(); + + if (!drawCallsSize) + return; // nothing to draw + + // init drawCallOrder + for (i = 0; i < drawCallsSize; i++) + drawCallOrder[i] = i; + + // sort the draw calls + PS_START_TIMING(ps_hw_batchsorttime); + if (cv_grshaders.value && gr_shadersavailable) + qsort(drawCallOrder, drawCallsSize, sizeof(UINT32), compareDrawCalls); + else + qsort(drawCallOrder, drawCallsSize, sizeof(UINT32), compareDrawCallsNoShaders); + PS_STOP_TIMING(ps_hw_batchsorttime); + // sort grouping order + // 1. shader + // 2. texture + // 3. polyflags + // 4. colors + light level + // not sure about what order of the last 2 should be, or if it even matters + + PS_START_TIMING(ps_hw_batchdrawtime); + + // set state for first batch + HWR_ExecuteStateChanges(0xFFFF, &drawCalls[drawCallOrder[0]]); + + // - iterate through draw calls + // - accumulate converted vertices and indices into finalVertices and finalIndices + // and send them as a combined draw call when a state change occurs + while (1) + { + boolean stopFlag = false; + unsigned int stateChanges = 0; // flags defined above HWR_MarkStateChanges + DrawCallInfo *currentDrawCall = &drawCalls[drawCallOrder[drawCallReadPos++]]; + DrawCallInfo *nextDrawCall = NULL; + + HWR_CollectVerticesIntoBatch(currentDrawCall); + + if (drawCallReadPos >= drawCallsSize) // was that the last draw call? + { + stopFlag = true; + } + else + { + nextDrawCall = &drawCalls[drawCallOrder[drawCallReadPos]]; + stateChanges = HWR_MarkStateChanges(currentDrawCall, nextDrawCall); + } + + if (stateChanges || stopFlag) + { + // execute combined draw call + HWD.pfnDrawIndexedTriangles(¤tDrawCall->surf, finalVertices, + finalIndicesSize, currentDrawCall->polyFlags, finalIndices); + // update stats + ps_hw_numcalls.value.i++; + ps_hw_numverts.value.i += finalIndicesSize; + // reset final geometry collection arrays + finalVerticesSize = 0; + finalIndicesSize = 0; + } + else + continue; + + // if we're here then either its time to stop or time to change state + if (stopFlag) + break; + else + HWR_ExecuteStateChanges(stateChanges, nextDrawCall); + } + // reset the arrays (set sizes to 0) + drawCallsSize = 0; + unsortedVerticesSize = 0; + + PS_STOP_TIMING(ps_hw_batchdrawtime); +} + +#endif // HWRENDER diff --git a/src/hardware/hw_batching.h b/src/hardware/hw_batching.h new file mode 100644 index 000000000..b4e4bd9e3 --- /dev/null +++ b/src/hardware/hw_batching.h @@ -0,0 +1,27 @@ +// SONIC ROBO BLAST 2 +//----------------------------------------------------------------------------- +// Copyright (C) 1998-2000 by DooM Legacy Team. +// Copyright (C) 1999-2020 by Sonic Team Junior. +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- +/// \file hw_batching.h +/// \brief Draw call batching and related things. + +#ifndef __HWR_BATCHING_H__ +#define __HWR_BATCHING_H__ + +#include "hw_defs.h" +#include "hw_data.h" +#include "hw_drv.h" + +void HWR_StartBatching(void); +void HWR_SetCurrentTexture(GLMipmap_t *texture); +void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, int shader, boolean horizonSpecial); +void HWR_RenderBatches(void); + +extern boolean currently_batching; + +#endif diff --git a/src/hardware/hw_bsp.c b/src/hardware/hw_bsp.c index 7015bf9f9..ff7e035f8 100644 --- a/src/hardware/hw_bsp.c +++ b/src/hardware/hw_bsp.c @@ -894,11 +894,11 @@ void HWR_CreatePlanePolygons(INT32 bspnum) ls_count = ls_percent = 0; // reset the loading status CON_Drawer(); //let the user know what we are doing I_FinishUpdate(); // page flip or blit buffer +#endif + // reset the portal flag gr_maphasportals = 0; -#endif - // find min/max boundaries of map //CONS_Debug(DBG_RENDER, "Looking for boundaries of map...\n"); M_ClearBox(rootbbox); diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index bfd5fa26d..593da1058 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -17,6 +17,7 @@ #include "hw_main.h" #include "hw_glob.h" #include "hw_drv.h" +#include "hw_batching.h" #include "../doomstat.h" //gamemode #include "../i_video.h" //rendermode @@ -33,12 +34,20 @@ static INT32 blocksize, blockwidth, blockheight; INT32 patchformat = GR_TEXFMT_AP_88; // use alpha for holes INT32 textureformat = GR_TEXFMT_P_8; // use chromakey for hole +RGBA_t mapPalette[256] = {0}; // the palette for the currently loaded level or menu etc. + +// Returns a pointer to the palette which should be used for caching textures. +RGBA_t *HWR_GetTexturePalette(void) +{ + return HWR_ShouldUsePaletteRendering() ? mapPalette : pLocalPalette; +} + // sprite, use alpha and chroma key for hole static void HWR_DrawPatchInCache(GLMipmap_t *mipmap, INT32 pblockwidth, INT32 pblockheight, INT32 blockmodulo, INT32 ptexturewidth, INT32 ptextureheight, INT32 originx, INT32 originy, // where to draw patch in surface block - const patch_t *realpatch, INT32 bpp) + const patch_t *realpatch, INT32 bpp, RGBA_t *palette) { INT32 x, x1, x2; INT32 col, ncols; @@ -67,6 +76,8 @@ static void HWR_DrawPatchInCache(GLMipmap_t *mipmap, if (!ptexturewidth) return; + + palette = HWR_GetTexturePalette(); col = x * pblockwidth / ptexturewidth; ncols = ((x2 - x) * pblockwidth) / ptexturewidth; @@ -152,10 +163,10 @@ static void HWR_DrawPatchInCache(GLMipmap_t *mipmap, case 2 : texelu16 = (UINT16)((alpha<<8) | texel); memcpy(dest, &texelu16, sizeof(UINT16)); break; - case 3 : colortemp = V_GetColor(texel); + case 3 : colortemp = palette[texel]; memcpy(dest, &colortemp, sizeof(RGBA_t)-sizeof(UINT8)); break; - case 4 : colortemp = V_GetColor(texel); + case 4 : colortemp = palette[texel]; colortemp.s.alpha = alpha; memcpy(dest, &colortemp, sizeof(RGBA_t)); break; @@ -329,6 +340,9 @@ static void HWR_GenerateTexture(INT32 texnum, GLTexture_t *grtex) INT32 i; boolean skyspecial = false; //poor hack for Legacy large skies.. + + RGBA_t *palette; + palette = HWR_GetTexturePalette(); texture = textures[texnum]; @@ -349,7 +363,12 @@ static void HWR_GenerateTexture(INT32 texnum, GLTexture_t *grtex) HWR_ResizeBlock (texture->width, texture->height, &grtex->mipmap.grInfo); grtex->mipmap.width = (UINT16)blockwidth; grtex->mipmap.height = (UINT16)blockheight; - grtex->mipmap.grInfo.format = textureformat; + //grtex->mipmap.grInfo.format = textureformat; + + if (skyspecial) + grtex->mipmap.grInfo.format = GR_RGBA; // that skyspecial code below assumes this format ... + else + grtex->mipmap.grInfo.format = textureformat; grtex->mipmap.colormap = colormaps; @@ -365,7 +384,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLTexture_t *grtex) INT32 j; RGBA_t col; - col = V_GetColor(HWR_CHROMAKEY_EQUIVALENTCOLORINDEX); + col = palette[HWR_CHROMAKEY_EQUIVALENTCOLORINDEX]; for (j = 0; j < blockheight; j++) { for (i = 0; i < blockwidth; i++) @@ -388,7 +407,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLTexture_t *grtex) texture->width, texture->height, patch->originx, patch->originy, realpatch, - format2bpp[grtex->mipmap.grInfo.format]); + format2bpp[grtex->mipmap.grInfo.format], palette); Z_Unlock(realpatch); } //Hurdler: not efficient at all but I don't remember exactly how HWR_DrawPatchInCache works :( @@ -412,6 +431,8 @@ static void HWR_GenerateTexture(INT32 texnum, GLTexture_t *grtex) void HWR_MakePatch (patch_t *patch, GLPatch_t *grPatch, GLMipmap_t *grMipmap, boolean makebitmap) { INT32 newwidth, newheight; + + RGBA_t *palette = HWR_GetTexturePalette(); // don't do it twice (like a cache) if (grMipmap->width == 0) @@ -456,7 +477,7 @@ void HWR_MakePatch (patch_t *patch, GLPatch_t *grPatch, GLMipmap_t *grMipmap, bo grPatch->width, grPatch->height, 0, 0, patch, - format2bpp[grMipmap->grInfo.format]); + format2bpp[grMipmap->grInfo.format], palette); } grPatch->max_s = (float)newwidth / (float)blockwidth; @@ -557,25 +578,6 @@ void HWR_PrepLevelCache(size_t pnumtextures) I_Error("HWR_PrepLevelCache: can't alloc gr_textures"); } -void HWR_SetPalette(RGBA_t *palette) -{ - //Hudler: 16/10/99: added for OpenGL gamma correction - RGBA_t gamma_correction = {0x7F7F7F7F}; - - //Hurdler 16/10/99: added for OpenGL gamma correction - gamma_correction.s.red = (UINT8)cv_grgammared.value; - gamma_correction.s.green = (UINT8)cv_grgammagreen.value; - gamma_correction.s.blue = (UINT8)cv_grgammablue.value; - HWD.pfnSetPalette(palette, &gamma_correction); - - // hardware driver will flush there own cache if cache is non paletized - // now flush data texture cache so 32 bit texture are recomputed - if (patchformat == GR_RGBA || textureformat == GR_RGBA) - { - Z_FreeTags(PU_HWRCACHE, PU_HWRCACHE); - Z_FreeTags(PU_HWRCACHE_UNLOCKED, PU_HWRCACHE_UNLOCKED); - } -} // -------------------------------------------------------------------------- // Make sure texture is downloaded and set it as the source // -------------------------------------------------------------------------- @@ -591,7 +593,11 @@ GLTexture_t *HWR_GetTexture(INT32 tex) if (!grtex->mipmap.grInfo.data && !grtex->mipmap.downloaded) HWR_GenerateTexture(tex, grtex); - HWD.pfnSetTexture(&grtex->mipmap); + // If hardware does not have the texture, then call pfnSetTexture to upload it + if (!grtex->mipmap.downloaded) + HWD.pfnSetTexture(&grtex->mipmap); + + HWR_SetCurrentTexture(&grtex->mipmap); // The system-memory data can be purged now. Z_ChangeTag(grtex->mipmap.grInfo.data, PU_HWRCACHE_UNLOCKED); @@ -672,18 +678,14 @@ void HWR_GetFlat(lumpnum_t flatlumpnum, boolean noencoremap) grmip->colormap += (256*32); #endif - grmip->colormap = colormaps; - -#ifdef GLENCORE - if (!noencoremap && encoremap) - grmip->colormap += (256*32); -#endif - - if (!grmip->downloaded && !grmip->grInfo.data) HWR_CacheFlat(grmip, flatlumpnum); - HWD.pfnSetTexture(grmip); + // If hardware does not have the texture, then call pfnSetTexture to upload it + if (!grmip->downloaded) + HWD.pfnSetTexture(grmip); + + HWR_SetCurrentTexture(grmip); // The system-memory data can be purged now. Z_ChangeTag(grmip->grInfo.data, PU_HWRCACHE_UNLOCKED); @@ -709,8 +711,11 @@ static void HWR_LoadMappedPatch(GLMipmap_t *grmip, GLPatch_t *gpatch) Z_Free(patch); } - - HWD.pfnSetTexture(grmip); + // If hardware does not have the texture, then call pfnSetTexture to upload it + if (!grmip->downloaded) + HWD.pfnSetTexture(grmip); + + HWR_SetCurrentTexture(grmip); // The system-memory data can be purged now. Z_ChangeTag(grmip->grInfo.data, PU_HWRCACHE_UNLOCKED); @@ -740,7 +745,11 @@ void HWR_GetPatch(GLPatch_t *gpatch) Z_Free(ptr); } - HWD.pfnSetTexture(gpatch->mipmap); + // If hardware does not have the texture, then call pfnSetTexture to upload it + if (!gpatch->mipmap->downloaded) + HWD.pfnSetTexture(gpatch->mipmap); + + HWR_SetCurrentTexture(gpatch->mipmap); // The system-memory patch data can be purged now. Z_ChangeTag(gpatch->mipmap->grInfo.data, PU_HWRCACHE_UNLOCKED); @@ -829,6 +838,7 @@ static void HWR_DrawFadeMaskInCache(GLMipmap_t *mipmap, INT32 pblockwidth, INT32 UINT8 *flat; UINT8 *dest, *src, texel; RGBA_t col; + RGBA_t *palette = HWR_GetTexturePalette(); // Place the flats data into flat W_ReadLump(fademasklumpnum, Z_Malloc(W_LumpLength(fademasklumpnum), @@ -846,7 +856,7 @@ static void HWR_DrawFadeMaskInCache(GLMipmap_t *mipmap, INT32 pblockwidth, INT32 { // fademask bpp is always 1, and is used just for alpha texel = src[(posx)>>FRACBITS]; - col = V_GetColor(texel); + col = palette[texel]; *dest = col.s.red; // take the red level of the colour and use it for alpha, as fademasks do dest++; @@ -922,4 +932,192 @@ void HWR_GetFadeMask(lumpnum_t fademasklumpnum) Z_ChangeTag(grmip->grInfo.data, PU_HWRCACHE_UNLOCKED); } +// ================================================= +// PALETTE HANDLING +// ================================================= + +void HWR_SetPalette(RGBA_t *palette) +{ + if (HWR_ShouldUsePaletteRendering()) + { + // set the palette for palette postprocessing + if (cv_grpalettedepth.value == 16) + { + // crush to 16-bit rgb565, like software currently does in the standard configuration + // Note: Software's screenshots have the 24-bit palette, but the screen gets + // the 16-bit version! For making comparison screenshots either use an external screenshot + // tool or set the palette depth to 24 bits. + RGBA_t crushed_palette[256]; + int i; + for (i = 0; i < 256; i++) + { + float fred = (float)(palette[i].s.red >> 3); + float fgreen = (float)(palette[i].s.green >> 2); + float fblue = (float)(palette[i].s.blue >> 3); + crushed_palette[i].s.red = (UINT8)(fred / 31.0f * 255.0f); + crushed_palette[i].s.green = (UINT8)(fgreen / 63.0f * 255.0f); + crushed_palette[i].s.blue = (UINT8)(fblue / 31.0f * 255.0f); + crushed_palette[i].s.alpha = 255; + } + HWD.pfnSetScreenPalette(crushed_palette); + } + else + { + HWD.pfnSetScreenPalette(palette); + } + + // this part is responsible for keeping track of the palette OUTSIDE of a level. + if ((!(gamestate == GS_LEVEL)) || (gamestate == GS_TITLESCREEN)) + HWR_SetMapPalette(); + } + else + { + // set the palette for the textures + HWD.pfnSetTexturePalette(palette); + // reset mapPalette so next call to HWR_SetMapPalette will update everything correctly + memset(mapPalette, 0, sizeof(mapPalette)); + // hardware driver will flush there own cache if cache is non paletized + // now flush data texture cache so 32 bit texture are recomputed + + //if (patchformat == GL_TEXFMT_RGBA || textureformat == GL_TEXFMT_RGBA) + if (patchformat == GR_RGBA || textureformat == GR_RGBA) + { + Z_FreeTag(PU_HWRCACHE); + Z_FreeTag(PU_HWRCACHE_UNLOCKED); + } + } +} + +static void HWR_SetPaletteLookup(RGBA_t *palette) +{ + int r, g, b; + UINT8 *lut = Z_Malloc( + HWR_PALETTE_LUT_SIZE*HWR_PALETTE_LUT_SIZE*HWR_PALETTE_LUT_SIZE*sizeof(UINT8), + PU_STATIC, NULL); +#define STEP_SIZE (256/HWR_PALETTE_LUT_SIZE) + for (b = 0; b < HWR_PALETTE_LUT_SIZE; b++) + { + for (g = 0; g < HWR_PALETTE_LUT_SIZE; g++) + { + for (r = 0; r < HWR_PALETTE_LUT_SIZE; r++) + { + lut[b*HWR_PALETTE_LUT_SIZE*HWR_PALETTE_LUT_SIZE+g*HWR_PALETTE_LUT_SIZE+r] = + NearestPaletteColor(r*STEP_SIZE, g*STEP_SIZE, b*STEP_SIZE, palette); + } + } + } +#undef STEP_SIZE + HWD.pfnSetPaletteLookup(lut); + Z_Free(lut); +} + +// Updates mapPalette to reflect the loaded level or other game state. +// Textures are flushed if needed. +// Call this function only in palette rendering mode. +void HWR_SetMapPalette(void) +{ + RGBA_t RGBA_converted[256]; + RGBA_t *palette; + int i; + + if ((!(gamestate == GS_LEVEL)) || (gamestate == GS_TITLESCREEN)) + { + // outside of a level, pMasterPalette should have PLAYPAL ready for us + //palette = pMasterPalette; // we dont have this in kart so just use pLocalPalette as before + + palette = pLocalPalette; + } + else + { + // in a level pLocalPalette might have a flash palette, but we + // want the map's original palette. + lumpnum_t lumpnum = W_GetNumForName(GetPalette()); + size_t palsize = W_LumpLength(lumpnum); + UINT8 *RGB_data; + if (palsize < 768) // 256 * 3 + I_Error("HWR_SetMapPalette: A programmer assumed palette lumps are at least 768 bytes long, but apparently this was a wrong assumption!\n"); + RGB_data = W_CacheLumpNum(lumpnum, PU_CACHE); + // we got the RGB palette now, but we need it in RGBA format. + for (i = 0; i < 256; i++) + { + RGBA_converted[i].s.red = *(RGB_data++); + RGBA_converted[i].s.green = *(RGB_data++); + RGBA_converted[i].s.blue = *(RGB_data++); + RGBA_converted[i].s.alpha = 255; + } + palette = RGBA_converted; + } + + // check if the palette has changed from the previous one + if (memcmp(mapPalette, palette, sizeof(mapPalette))) + { + memcpy(mapPalette, palette, sizeof(mapPalette)); + // in palette rendering mode, this means that all rgba textures now have wrong colors + // and the lookup table is outdated + HWR_SetPaletteLookup(mapPalette); + HWD.pfnSetTexturePalette(mapPalette); + + //if (patchformat == GL_TEXFMT_RGBA || textureformat == GL_TEXFMT_RGBA) + if (patchformat == GR_RGBA || textureformat == GR_RGBA) + { + Z_FreeTag(PU_HWRCACHE); + Z_FreeTag(PU_HWRCACHE_UNLOCKED); + } + } +} + +// Creates a hardware lighttable from the supplied lighttable. +// Returns the id of the hw lighttable, usable in FSurfaceInfo. +UINT32 HWR_CreateLightTable(UINT8 *lighttable) +{ + UINT32 i, id; + RGBA_t *palette = HWR_GetTexturePalette(); + RGBA_t *hw_lighttable = Z_Malloc(256 * 32 * sizeof(RGBA_t), PU_STATIC, NULL); + + // To make the palette index -> RGBA mapping easier for the shader, + // the hardware lighttable is composed of RGBA colors instead of palette indices. + for (i = 0; i < 256 * 32; i++) + hw_lighttable[i] = palette[lighttable[i]]; + + id = HWD.pfnCreateLightTable(hw_lighttable); + Z_Free(hw_lighttable); + return id; +} + + +// get hwr lighttable id for colormap, create it if it doesn't already exist +UINT32 HWR_GetLightTableID(extracolormap_t *colormap) +{ + boolean default_colormap = false; + if (!colormap) + { + colormap = &extra_colormaps[num_extra_colormaps]; // a place to store the hw lighttable id + // alternatively could just store the id in a global variable if there are issues + default_colormap = true; + } + + // create hw lighttable if there isn't one + if (!colormap->gl_lighttable_id) + { + UINT8 *colormap_pointer; + + if (default_colormap) + colormap_pointer = colormaps; // don't actually use the data from the "default colormap" + else + colormap_pointer = colormap->colormap; + colormap->gl_lighttable_id = HWR_CreateLightTable(colormap_pointer); + } + + return colormap->gl_lighttable_id; +} + +// Note: all hardware lighttable ids assigned before this +// call become invalid and must not be used. +void HWR_ClearLightTables(void) +{ + //if (vid.glstate == VID_GL_LIBRARY_LOADED) // we have pfnInit which is essentially the same, but it doesent work here for whatever reason, since this should not be done in software renderer ever! + if (rendermode == render_opengl) + HWD.pfnClearLightTables(); +} + #endif //HWRENDER diff --git a/src/hardware/hw_defs.h b/src/hardware/hw_defs.h index 674ae876a..f5d0c9a18 100644 --- a/src/hardware/hw_defs.h +++ b/src/hardware/hw_defs.h @@ -25,6 +25,12 @@ #define NZCLIP_PLANE 0.9f // Seems to be only used for the HUD and screen textures #define FAR_ZCLIP_DEFAULT 32768.0f +// The width/height/depth of the palette lookup table used by palette rendering. +// Changing this also requires changing the shader code! +// Also assumed to be a power of two in some parts of the code. +// 64 seems to work perfectly for the vanilla palette. +#define HWR_PALETTE_LUT_SIZE 64 + // ========================================================================== // SIMPLE TYPES // ========================================================================== @@ -129,8 +135,10 @@ typedef struct FLOAT x,y,z; // position #ifdef USE_FTRANSFORM_ANGLEZ FLOAT anglex,angley,anglez; // aimingangle / viewangle + FLOAT anglex2,anglez2; // secondaries #else FLOAT anglex,angley; // aimingangle / viewangle + FLOAT anglex2; // secondaries #endif FLOAT scalex,scaley,scalez; FLOAT spritexscale,spriteyscale; @@ -157,6 +165,46 @@ typedef struct FLOAT s,t; } FOutVector; +#ifdef GL_SHADERS +// Shader targets used to render specific types of geometry. +// A shader target is resolved to an actual shader with HWR_GetShaderFromTarget. +// The shader returned may be a base shader or a custom shader. +enum +{ + SHADER_NONE = -1, + SHADER_FLOOR = 0, + SHADER_WALL, + SHADER_MODEL, + SHADER_SPRITE, + SHADER_WATER, + SHADER_FOG, + SHADER_SKY, + SHADER_PALETTE_POSTPROCESS, + SHADER_UI_COLORMAP_FADE, + + NUMSHADERTARGETS +}; + +// Must be at least NUMSHADERTARGETS*2 to fit base and custom shaders for each shader target. +#define HWR_MAXSHADERS NUMSHADERTARGETS*2 + +// Custom shader reference table +typedef struct +{ + const char *type; + INT32 id; +} customshaderxlat_t; + +enum hwdshaderstage +{ + HWD_SHADERSTAGE_VERTEX, + HWD_SHADERSTAGE_FRAGMENT, +}; + +typedef enum hwdshaderstage hwdshaderstage_t; + +#endif + // ========================================================================== // RENDER MODES // ========================================================================== @@ -183,14 +231,15 @@ enum EPolyFlags PF_NoDepthTest = 0x00000200, // Disable the depth test mode PF_Invisible = 0x00000400, // Disable write to color buffer PF_Decal = 0x00000800, // Enable polygon offset - PF_Modulated = 0x00001000, // Modulation (multiply output with constant ARGB) + PF_Modulated = 0x00001000, // Modulation (multiply output with constant RGBA) // When set, pass the color constant into the FSurfaceInfo -> FlatColor PF_NoTexture = 0x00002000, // Disable texture - PF_Ripple = 0x00004000, // Water shader effect + PF_ColorMapped = 0x00008000, // Surface has "tint" and "fade" colors, which are sent as uniforms to a shader. // 0x00008000 PF_RemoveYWrap = 0x00010000, // Force clamp texture on Y PF_ForceWrapX = 0x00020000, // Force repeat texture on X - PF_ForceWrapY = 0x00040000, // Force repeat texture on Y + PF_ForceWrapY = 0x00040000, // Forces repeat texture on Y + PF_Ripple = 0x00100000 // Water ripple effect. The current backend doesn't use it for anything. // 0x20000000 // 0x40000000 // 0x80000000 @@ -208,7 +257,6 @@ enum ETextureFlags typedef struct GLMipmap_s FTextureInfo; -// jimita 14032019 struct FLightInfo { FUINT light_level; @@ -225,14 +273,13 @@ struct FSurfaceInfo RGBA_t TintColor; RGBA_t FadeColor; UINT32 LightTableId; - FLightInfo LightInfo; // jimita 14032019 + FLightInfo LightInfo; }; typedef struct FSurfaceInfo FSurfaceInfo; enum hwdsetspecialstate { HWD_SET_SHADERS, - HWD_SET_PALETTE_SHADER_ENABLED, HWD_SET_TEXTUREFILTERMODE, HWD_SET_TEXTUREANISOTROPICMODE, @@ -240,8 +287,6 @@ enum hwdsetspecialstate HWD_SET_MSAA, HWD_SET_SCREEN_TEXTURES, - - HWD_SET_DEPTH_ONLY_MODE,// for portals HWD_SET_PORTAL_MODE,// new portal thing HWD_SET_STENCIL_LEVEL, @@ -281,4 +326,15 @@ enum hwdfiltermode HWD_SET_TEXTUREFILTER_MIXED3, }; +// Screen texture slots +enum hwdscreentexture +{ + HWD_SCREENTEXTURE_WIPE_START, // source image for the wipe/fade effect + HWD_SCREENTEXTURE_WIPE_END, // destination image for the wipe/fade effect + HWD_SCREENTEXTURE_GENERIC1, // underwater/heat effect, intermission background + HWD_SCREENTEXTURE_GENERIC2, // palette-based colormap fade, final screen texture + NUMSCREENTEXTURES, // (generic3 is unused if palette rendering is disabled) +}; +typedef enum hwdscreentexture hwdscreentexture_t; + #endif //_HWR_DEFS_ diff --git a/src/hardware/hw_draw.c b/src/hardware/hw_draw.c index 8f94abbba..bd09b69d2 100644 --- a/src/hardware/hw_draw.c +++ b/src/hardware/hw_draw.c @@ -122,7 +122,7 @@ void HWR_DrawPatch(GLPatch_t *gpatch, INT32 x, INT32 y, INT32 option) flags |= PF_ForceWrapY; // clip it since it is used for bunny scroll in doom I - HWD.pfnDrawPolygon(NULL, v, 4, flags, false); + HWD.pfnDrawPolygon(NULL, v, 4, flags); } void HWR_DrawStretchyFixedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, fixed_t vscale, INT32 option, const UINT8 *colormap) @@ -300,10 +300,10 @@ void HWR_DrawStretchyFixedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t else if (alphalevel == 15) Surf.PolyColor.s.alpha = softwaretranstogl_hi[hudtrans]; else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; flags |= PF_Modulated; - HWD.pfnDrawPolygon(&Surf, v, 4, flags, false); + HWD.pfnDrawPolygon(&Surf, v, 4, flags); } else - HWD.pfnDrawPolygon(NULL, v, 4, flags, false); + HWD.pfnDrawPolygon(NULL, v, 4, flags); } void HWR_DrawCroppedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, INT32 option, fixed_t sx, fixed_t sy, fixed_t w, fixed_t h) @@ -454,10 +454,10 @@ void HWR_DrawCroppedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscal else if (alphalevel == 15) Surf.PolyColor.s.alpha = softwaretranstogl_hi[cv_translucenthud.value]; else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; flags |= PF_Modulated; - HWD.pfnDrawPolygon(&Surf, v, 4, flags, false); + HWD.pfnDrawPolygon(&Surf, v, 4, flags); } else - HWD.pfnDrawPolygon(NULL, v, 4, flags, false); + HWD.pfnDrawPolygon(NULL, v, 4, flags); } // ========================================================================== @@ -533,7 +533,7 @@ void HWR_DrawFlatFill (INT32 x, INT32 y, INT32 w, INT32 h, lumpnum_t flatlumpnum // BTW, I see we put 0 for PFs, and If I'm right, that // means we take the previous PFs as default // how can we be sure they are ok? - HWD.pfnDrawPolygon(NULL, v, 4, PF_NoDepthTest, false); //PF_Translucent); + HWD.pfnDrawPolygon(NULL, v, 4, PF_NoDepthTest); //PF_Translucent); } @@ -548,6 +548,7 @@ void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength) { FOutVector v[4]; FSurfaceInfo Surf; + FBITFIELD poly_flags = PF_NoTexture|PF_Modulated|PF_NoDepthTest; v[0].x = v[3].x = -1.0f; v[2].x = v[1].x = 1.0f; @@ -562,15 +563,40 @@ void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength) if (color & 0xFF00) // Do COLORMAP fade. { - Surf.PolyColor.rgba = UINT2RGBA(0x01010160); - Surf.PolyColor.s.alpha = (strength*8); + if (HWR_ShouldUsePaletteRendering() && cv_grscreentextures.value) + { + const hwdscreentexture_t scr_tex = HWD_SCREENTEXTURE_GENERIC2; + + Surf.LightTableId = HWR_GetLightTableID(NULL); + Surf.LightInfo.light_level = strength; + HWD.pfnMakeScreenTexture(scr_tex); + HWD.pfnSetShader(HWR_GetShaderFromTarget(SHADER_UI_COLORMAP_FADE)); + HWD.pfnDrawScreenTexture(scr_tex, &Surf, PF_ColorMapped|PF_NoDepthTest); + HWD.pfnUnSetShader(); + + return; + } + else + { + Surf.PolyColor.rgba = UINT2RGBA(0x01010160); + Surf.PolyColor.s.alpha = (strength*8); + poly_flags |= PF_Translucent; + } } else // Do TRANSMAP** fade. { - Surf.PolyColor.rgba = pLocalPalette[color].rgba; - Surf.PolyColor.s.alpha = (UINT8)(strength*25.5f); + RGBA_t *palette = HWR_GetTexturePalette(); + Surf.PolyColor.rgba = palette[color&0xFF].rgba; + + if (HWR_ShouldUsePaletteRendering()) + Surf.PolyColor.s.alpha = softwaretranstogl[strength]; + else + Surf.PolyColor.s.alpha = (UINT8)(strength*25.5f); + + poly_flags |= PF_Translucent; } - HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest, false); + + HWD.pfnDrawPolygon(&Surf, v, 4, poly_flags); } // Draw the console background with translucency support @@ -597,7 +623,7 @@ void HWR_DrawConsoleBack(UINT32 color, INT32 height) Surf.PolyColor.rgba = UINT2RGBA(color); Surf.PolyColor.s.alpha = 0x80; - HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest, false); + HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); } @@ -743,9 +769,10 @@ void HWR_drawAMline(const fline_t *fl, INT32 color) { F2DCoord v1, v2; RGBA_t color_rgba; - - color_rgba = V_GetColor(color); - + RGBA_t *palette = HWR_GetTexturePalette(); + + color_rgba = palette[color&0xFF]; + v1.x = ((float)fl->a.x-(vid.width/2.0f))*(2.0f/vid.width); v1.y = ((float)fl->a.y-(vid.height/2.0f))*(2.0f/vid.height); @@ -763,6 +790,7 @@ void HWR_DrawDiag(INT32 x, INT32 y, INT32 wh, INT32 color) FOutVector v[4]; FSurfaceInfo Surf; float fx, fy, fw, fh, fwait = 0; + RGBA_t *palette = HWR_GetTexturePalette(); if (wh < 0) return; // consistency w/ software @@ -843,10 +871,10 @@ void HWR_DrawDiag(INT32 x, INT32 y, INT32 wh, INT32 color) v[0].t = v[1].t = 0.0f; v[2].t = v[3].t = 1.0f; - Surf.PolyColor = V_GetColor(color); + Surf.PolyColor = palette[color&0xFF]; HWD.pfnDrawPolygon(&Surf, v, 4, - PF_Modulated|PF_NoTexture|PF_NoDepthTest, false); + PF_Modulated|PF_NoTexture|PF_NoDepthTest); } // -------------------+ @@ -857,6 +885,7 @@ void HWR_DrawConsoleFill(INT32 x, INT32 y, INT32 w, INT32 h, UINT32 color, INT32 FOutVector v[4]; FSurfaceInfo Surf; float fx, fy, fw, fh; + RGBA_t *palette = HWR_GetTexturePalette(); if (w < 0 || h < 0) return; // consistency w/ software @@ -877,7 +906,7 @@ void HWR_DrawConsoleFill(INT32 x, INT32 y, INT32 w, INT32 h, UINT32 color, INT32 if (x == 0 && y == 0 && w == BASEVIDWIDTH && h == BASEVIDHEIGHT) { - RGBA_t rgbaColour = V_GetColor(color); + RGBA_t rgbaColour = palette[color&0xFF]; FRGBAFloat clearColour; clearColour.red = (float)rgbaColour.s.red / 255; clearColour.green = (float)rgbaColour.s.green / 255; @@ -954,17 +983,20 @@ void HWR_DrawConsoleFill(INT32 x, INT32 y, INT32 w, INT32 h, UINT32 color, INT32 Surf.PolyColor.rgba = UINT2RGBA(color); Surf.PolyColor.s.alpha = 0x80; - HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest, false); + HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); } // -----------------+ // HWR_DrawFill : draw flat coloured rectangle, with no texture // -----------------+ +// alug: now with translucency support X) void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) { FOutVector v[4]; FSurfaceInfo Surf; float fx, fy, fw, fh; + UINT8 alphalevel = ((color & V_ALPHAMASK) >> V_ALPHASHIFT); + RGBA_t *palette = HWR_GetTexturePalette(); if (w < 0 || h < 0) return; // consistency w/ software @@ -985,7 +1017,7 @@ void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) if (x == 0 && y == 0 && w == BASEVIDWIDTH && h == BASEVIDHEIGHT) { - RGBA_t rgbaColour = V_GetColor(color); + RGBA_t rgbaColour = palette[color&0xFF]; FRGBAFloat clearColour; clearColour.red = (float)rgbaColour.s.red / 255; clearColour.green = (float)rgbaColour.s.green / 255; @@ -1059,10 +1091,17 @@ void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) v[0].t = v[1].t = 0.0f; v[2].t = v[3].t = 1.0f; - Surf.PolyColor = V_GetColor(color); + Surf.PolyColor = palette[color&0xFF]; - HWD.pfnDrawPolygon(&Surf, v, 4, - PF_Modulated|PF_NoTexture|PF_NoDepthTest, false); + if (alphalevel) + { + if (alphalevel == 13) Surf.PolyColor.s.alpha = softwaretranstogl_lo[hudtrans]; + else if (alphalevel == 14) Surf.PolyColor.s.alpha = softwaretranstogl[hudtrans]; + else if (alphalevel == 15) Surf.PolyColor.s.alpha = softwaretranstogl_hi[hudtrans]; + else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; + } + + HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); } #ifdef HAVE_PNG @@ -1138,12 +1177,15 @@ static inline boolean saveTGA(const char *file_name, void *buffer, UINT8 *HWR_GetScreenshot(void) { - UINT8 *buf = malloc(vid.width * vid.height * 3 * sizeof (*buf)); + static UINT8 *buf = NULL; + + buf = realloc(buf, vid.width * vid.height * 3); if (!buf) return NULL; + // returns 24bit 888 RGB - HWD.pfnReadRect(0, 0, vid.width, vid.height, vid.width * 3, (void *)buf); + HWD.pfnReadScreenTexture(HWD_SCREENTEXTURE_GENERIC2, (void *)buf); return buf; } @@ -1159,7 +1201,7 @@ boolean HWR_Screenshot(const char *pathname) } // returns 24bit 888 RGB - HWD.pfnReadRect(0, 0, vid.width, vid.height, vid.width * 3, (void *)buf); + HWD.pfnReadScreenTexture(HWD_SCREENTEXTURE_GENERIC2, (void *)buf); #ifdef USE_PNG ret = M_SavePNG(pathname, buf, vid.width, vid.height, NULL); diff --git a/src/hardware/hw_drv.h b/src/hardware/hw_drv.h index bcf627236..df4d431f9 100644 --- a/src/hardware/hw_drv.h +++ b/src/hardware/hw_drv.h @@ -28,19 +28,17 @@ // ========================================================================== EXPORT boolean HWRAPI(Init) (void); -#if defined (PURESDL) || defined (macintosh) -EXPORT void HWRAPI(SetPalette) (INT32 *, RGBA_t *gamma); -#else -EXPORT void HWRAPI(SetPalette) (RGBA_t *ppal, RGBA_t *pgamma); -#endif +EXPORT void HWRAPI(SetupGLInfo) (void); +EXPORT void HWRAPI(SetTexturePalette) (RGBA_t *ppal); EXPORT void HWRAPI(FinishUpdate) (INT32 waitvbl); EXPORT void HWRAPI(Draw2DLine) (F2DCoord *v1, F2DCoord *v2, RGBA_t Color); -EXPORT void HWRAPI(DrawPolygon) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, boolean horizonSpecial); +EXPORT void HWRAPI(DrawPolygon) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags); +EXPORT void HWRAPI(DrawIndexedTriangles) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, unsigned int *IndexArray); EXPORT void HWRAPI(SetBlend) (FBITFIELD PolyFlags); EXPORT void HWRAPI(ClearBuffer) (FBOOLEAN ColorMask, FBOOLEAN DepthMask, FBOOLEAN StencilMask, FRGBAFloat *ClearColor); EXPORT void HWRAPI(SetTexture) (FTextureInfo *TexInfo); EXPORT void HWRAPI(UpdateTexture) (FTextureInfo *TexInfo); -EXPORT void HWRAPI(ReadRect) (INT32 x, INT32 y, INT32 width, INT32 height, INT32 dst_stride, UINT16 *dst_data); +EXPORT void HWRAPI(ReadScreenTexture) (int tex, UINT16 *dst_data); EXPORT void HWRAPI(GClipRect) (INT32 minx, INT32 miny, INT32 maxx, INT32 maxy, float nearclip, float farclip); EXPORT void HWRAPI(ClearMipMapCache) (void); @@ -49,7 +47,7 @@ EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value); //Hurdler: added for new development -EXPORT void HWRAPI(DrawModel) (model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, FSurfaceInfo *Surface); +EXPORT void HWRAPI(DrawModel) (model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface); EXPORT void HWRAPI(CreateModelVBOs) (model_t *model); EXPORT void HWRAPI(SetTransform) (FTransform *stransform); @@ -58,32 +56,29 @@ EXPORT INT32 HWRAPI(GetTextureUsed) (void); EXPORT void HWRAPI(RenderSkyDome) (INT32 tex, INT32 texture_width, INT32 texture_height, FTransform transform); EXPORT void HWRAPI(FlushScreenTextures) (void); -EXPORT void HWRAPI(StartScreenWipe) (void); -EXPORT void HWRAPI(EndScreenWipe) (void); -EXPORT void HWRAPI(DoScreenWipe) (void); -EXPORT void HWRAPI(DrawIntermissionBG) (void); -EXPORT void HWRAPI(MakeScreenTexture) (void); -EXPORT void HWRAPI(MakeScreenFinalTexture) (void); -EXPORT void HWRAPI(DrawScreenFinalTexture) (int width, int height); +EXPORT void HWRAPI(DoScreenWipe) (int wipeStart, int wipeEnd); +EXPORT void HWRAPI(DrawScreenTexture) (int tex, FSurfaceInfo *surf, FBITFIELD polyflags); +EXPORT void HWRAPI(MakeScreenTexture) (int tex); +EXPORT void HWRAPI(DrawScreenFinalTexture) (int tex, int width, int height); + +EXPORT void HWRAPI(RenderVhsEffect) (fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize); #define SCREENVERTS 10 EXPORT void HWRAPI(PostImgRedraw) (float points[SCREENVERTS][SCREENVERTS][2]); // jimita -EXPORT boolean HWRAPI(LoadShaders) (void); -EXPORT void HWRAPI(KillShaders) (void); -EXPORT void HWRAPI(SetShader) (int shader); +EXPORT boolean HWRAPI(InitShaders) (void); +EXPORT void HWRAPI(LoadShader) (int slot, char *code, hwdshaderstage_t stage); +EXPORT boolean HWRAPI(CompileShader) (int slot); +EXPORT void HWRAPI(SetShader) (int slot); EXPORT void HWRAPI(UnSetShader) (void); EXPORT void HWRAPI(SetShaderInfo) (hwdshaderinfo_t info, INT32 value); -EXPORT void HWRAPI(LoadCustomShader) (int number, char *shader, size_t size, boolean fragment); -EXPORT boolean HWRAPI(InitCustomShaders) (void); -EXPORT void HWRAPI(StartBatching) (void); -EXPORT void HWRAPI(RenderBatches) (precise_t *sSortTime, precise_t *sDrawTime, int *sNumPolys, int *sNumVerts, int *sNumCalls, int *sNumShaders, int *sNumTextures, int *sNumPolyFlags, int *sNumColors); - -EXPORT UINT32 HWRAPI(AddLightTable) (UINT8 *lighttable); -EXPORT void HWRAPI(ClearLightTableCache) (void); +EXPORT void HWRAPI(SetPaletteLookup)(UINT8 *lut); +EXPORT UINT32 HWRAPI(CreateLightTable)(RGBA_t *hw_lighttable); +EXPORT void HWRAPI(ClearLightTables)(void); +EXPORT void HWRAPI(SetScreenPalette)(RGBA_t *palette); // ========================================================================== // HWR DRIVER OBJECT, FOR CLIENT PROGRAM @@ -94,15 +89,17 @@ EXPORT void HWRAPI(ClearLightTableCache) (void); struct hwdriver_s { Init pfnInit; - SetPalette pfnSetPalette; + SetupGLInfo pfnSetupGLInfo; + SetTexturePalette pfnSetTexturePalette; FinishUpdate pfnFinishUpdate; Draw2DLine pfnDraw2DLine; DrawPolygon pfnDrawPolygon; + DrawIndexedTriangles pfnDrawIndexedTriangles; SetBlend pfnSetBlend; ClearBuffer pfnClearBuffer; SetTexture pfnSetTexture; UpdateTexture pfnUpdateTexture; - ReadRect pfnReadRect; + ReadScreenTexture pfnReadScreenTexture; GClipRect pfnGClipRect; ClearMipMapCache pfnClearMipMapCache; SetSpecialState pfnSetSpecialState; @@ -112,30 +109,26 @@ struct hwdriver_s GetTextureUsed pfnGetTextureUsed; PostImgRedraw pfnPostImgRedraw; FlushScreenTextures pfnFlushScreenTextures; - StartScreenWipe pfnStartScreenWipe; - EndScreenWipe pfnEndScreenWipe; DoScreenWipe pfnDoScreenWipe; - DrawIntermissionBG pfnDrawIntermissionBG; + DrawScreenTexture pfnDrawScreenTexture; MakeScreenTexture pfnMakeScreenTexture; - MakeScreenFinalTexture pfnMakeScreenFinalTexture; + RenderVhsEffect pfnRenderVhsEffect; DrawScreenFinalTexture pfnDrawScreenFinalTexture; RenderSkyDome pfnRenderSkyDome; - LoadShaders pfnLoadShaders; - KillShaders pfnKillShaders; + InitShaders pfnInitShaders; + LoadShader pfnLoadShader; + CompileShader pfnCompileShader; SetShader pfnSetShader; UnSetShader pfnUnSetShader; SetShaderInfo pfnSetShaderInfo; - LoadCustomShader pfnLoadCustomShader; - InitCustomShaders pfnInitCustomShaders; - StartBatching pfnStartBatching; - RenderBatches pfnRenderBatches; - - AddLightTable pfnAddLightTable; - ClearLightTableCache pfnClearLightTableCache; + SetPaletteLookup pfnSetPaletteLookup; + CreateLightTable pfnCreateLightTable; + ClearLightTables pfnClearLightTables; + SetScreenPalette pfnSetScreenPalette; }; extern struct hwdriver_s hwdriver; @@ -144,4 +137,4 @@ extern struct hwdriver_s hwdriver; #endif //not defined _CREATE_DLL_ -#endif //__HWR_DRV_H__ \ No newline at end of file +#endif //__HWR_DRV_H__ diff --git a/src/hardware/hw_glob.h b/src/hardware/hw_glob.h index 1950a10da..9e565a8aa 100644 --- a/src/hardware/hw_glob.h +++ b/src/hardware/hw_glob.h @@ -68,6 +68,11 @@ void HWR_GetMappedPatch(GLPatch_t *gpatch, const UINT8 *colormap); void HWR_MakePatch(patch_t *patch, GLPatch_t *grPatch, GLMipmap_t *grMipmap, boolean makebitmap); void HWR_UnlockCachedPatch(GLPatch_t *gpatch); void HWR_SetPalette(RGBA_t *palette); + +void HWR_SetMapPalette(void); +UINT32 HWR_CreateLightTable(UINT8 *lighttable); +UINT32 HWR_GetLightTableID(extracolormap_t *colormap); +void HWR_ClearLightTables(void); GLPatch_t *HWR_GetCachedGLPatchPwad(UINT16 wad, UINT16 lump); GLPatch_t *HWR_GetCachedGLPatch(lumpnum_t lumpnum); void HWR_GetFadeMask(lumpnum_t fademasklumpnum); @@ -90,4 +95,18 @@ void HWR_AddTransparentPolyobjectFloor(lumpnum_t lumpnum, polyobj_t *polysector, void HWR_RenderDrawNodes(void); +// -------- +// hw_shaders.c +// -------- +boolean HWR_InitShaders(void); +void HWR_CompileShaders(void); + +int HWR_GetShaderFromTarget(int shader_target); + +void HWR_LoadAllCustomShaders(void); +void HWR_LoadCustomShadersFromFile(UINT16 wadnum, boolean PK3); +const char *HWR_GetShaderName(INT32 shader); + +extern customshaderxlat_t shaderxlat[]; + #endif //_HW_GLOB_ \ No newline at end of file diff --git a/src/hardware/hw_main.c b/src/hardware/hw_main.c index c444f8e12..79d9e5085 100644 --- a/src/hardware/hw_main.c +++ b/src/hardware/hw_main.c @@ -19,6 +19,7 @@ #include "hw_main.h" #include "hw_glob.h" #include "hw_drv.h" +#include "hw_batching.h" #include "hw_md2.h" #include "hw_clip.h" #include "hw_light.h" @@ -57,27 +58,22 @@ // ========================================================================== struct hwdriver_s hwdriver; +// false if shaders have not been initialized yet, or if shaders are not available +boolean gr_shadersavailable = false; + +// Whether the internal state is set to palette rendering or not. +static boolean gr_palette_rendering_state = false; + // ========================================================================== // Commands and console variables // ========================================================================== -// keep the state here instead of in the cv var, so it always matches the state in r_opengl.c -int gr_use_palette_shader = 0; - static void CV_filtermode_ONChange(void); static void CV_anisotropic_ONChange(void); static void CV_screentextures_ONChange(void); -static void CV_useCustomShaders_ONChange(void); -static void CV_grpaletteshader_OnChange(void); -static void CV_Gammaxxx_ONChange(void); - -static CV_PossibleValue_t grgamma_cons_t[] = {{1, "MIN"}, {255, "MAX"}, {0, NULL}}; -consvar_t cv_grgammared = {"gr_gammared", "127", CV_SAVE|CV_CALL, grgamma_cons_t, - CV_Gammaxxx_ONChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grgammagreen = {"gr_gammagreen", "127", CV_SAVE|CV_CALL, grgamma_cons_t, - CV_Gammaxxx_ONChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grgammablue = {"gr_gammablue", "127", CV_SAVE|CV_CALL, grgamma_cons_t, - CV_Gammaxxx_ONChange, 0, NULL, NULL, 0, 0, NULL}; +static void CV_grshaders_OnChange(void); +static void CV_grpaletterendering_OnChange(void); +static void CV_grpalettedepth_OnChange(void); static CV_PossibleValue_t grfakecontrast_cons_t[] = {{0, "Off"}, {1, "Standard"}, {2, "Smooth"}, {0, NULL}}; @@ -93,21 +89,29 @@ consvar_t cv_grrounddown = {"gr_rounddown", "Off", 0, CV_OnOff, NULL, 0, NULL, N consvar_t cv_grfiltermode = {"gr_filtermode", "Nearest", CV_CALL|CV_SAVE, grfiltermode_cons_t, CV_filtermode_ONChange, 0, NULL, NULL, 0, 0, NULL}; - + consvar_t cv_granisotropicmode = {"gr_anisotropicmode", "1", CV_CALL|CV_SAVE, granisotropicmode_cons_t, CV_anisotropic_ONChange, 0, NULL, NULL, 0, 0, NULL}; - + consvar_t cv_grcorrecttricks = {"gr_correcttricks", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_grsolvetjoin = {"gr_solvetjoin", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_grbatching = {"gr_batching", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_grfofcut = {"gr_fofcut", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_fofzfightfix = {"fofzfightfix", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_splitwallfix = {"splitwallfix", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_slopepegfix = {"slopepegfix", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + static CV_PossibleValue_t grrenderdistance_cons_t[] = { {0, "Max"}, {1, "1024"}, {2, "2048"}, {3, "4096"}, {4, "6144"}, {5, "8192"}, {6, "12288"}, {7, "16384"}, {0, NULL}}; consvar_t cv_grrenderdistance = {"gr_renderdistance", "Max", CV_SAVE, grrenderdistance_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; - + consvar_t cv_grportals = {"gr_portals", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_nostencil = {"nostencil", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_portalline = {"portalline", "0", 0, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -116,16 +120,17 @@ CV_PossibleValue_t secbright_cons_t[] = {{0, "MIN"}, {255, "MAX"}, {0, NULL}}; consvar_t cv_secbright = {"secbright", "0", CV_SAVE, secbright_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; - + consvar_t cv_grfovchange = {"gr_fovchange", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - + + // values for the far clipping plane static float clipping_distances[] = {1024.0f, 2048.0f, 4096.0f, 6144.0f, 8192.0f, 12288.0f, 16384.0f}; // values for bsp culling // slightly higher than the far clipping plane to compensate for impreciseness static INT32 bsp_culling_distances[] = {(1024+512)*FRACUNIT, (2048+512)*FRACUNIT, (4096+512)*FRACUNIT, (6144+512)*FRACUNIT, (8192+512)*FRACUNIT, (12288+512)*FRACUNIT, (16384+512)*FRACUNIT}; - + static INT32 current_bsp_culling_distance = 0; // The current screen texture implementation is inefficient and disabling it can result in significant @@ -134,15 +139,18 @@ static INT32 current_bsp_culling_distance = 0; // - water and heat wave effects // - intermission background // - full screen scaling (use native resolution or windowed mode to avoid this) -consvar_t cv_grscreentextures = {"gr_screentextures", "On", CV_CALL, CV_OnOff, +consvar_t cv_grscreentextures = {"gr_screentextures", "On", CV_CALL|CV_SAVE, CV_OnOff, CV_screentextures_ONChange, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grshaders = {"gr_shaders", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grusecustomshaders = {"gr_usecustomshaders", "Yes", CV_CALL|CV_SAVE, CV_OnOff, CV_useCustomShaders_ONChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grpaletteshader = {"gr_paletteshader", "Off", CV_CALL|CV_SAVE, CV_OnOff, CV_grpaletteshader_OnChange, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t grshaders_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Ignore custom shaders"}, {0, NULL}}; +consvar_t cv_grshaders = {"gr_shaders", "On", CV_CALL|CV_SAVE, grshaders_cons_t, CV_grshaders_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grflashpal = {"gr_flashpal", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_grpaletterendering = {"gr_paletteshader", "Off", CV_CALL|CV_SAVE, CV_OnOff, CV_grpaletterendering_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +static CV_PossibleValue_t glpalettedepth_cons_t[] = {{16, "16 bits"}, {24, "24 bits"}, {0, NULL}}; +consvar_t cv_grpalettedepth = {"gr_palettedepth", "16 bits", CV_SAVE|CV_CALL, glpalettedepth_cons_t, CV_grpalettedepth_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_grflashpal = {"gr_flashpal", "On", CV_CALL|CV_SAVE, CV_OnOff, CV_grpaletterendering_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_grmdls = {"gr_mdls", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_grfallbackplayermodel = {"gr_fallbackplayermodel", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -152,51 +160,63 @@ consvar_t cv_grspritebillboarding = {"gr_spritebillboarding", "On", CV_SAVE, CV_ consvar_t cv_grfakecontrast = {"gr_fakecontrast", "Standard", CV_SAVE, grfakecontrast_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_grslopecontrast = {"gr_slopecontrast", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_grhorizonlines = {"gr_horizonlines", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + + +#define ONLY_IF_GL_LOADED if (vid.glstate != VID_GL_LIBRARY_LOADED) return; + static void CV_filtermode_ONChange(void) { - if (rendermode == render_opengl) + ONLY_IF_GL_LOADED HWD.pfnSetSpecialState(HWD_SET_TEXTUREFILTERMODE, cv_grfiltermode.value); } static void CV_anisotropic_ONChange(void) { - if (rendermode == render_opengl) + ONLY_IF_GL_LOADED HWD.pfnSetSpecialState(HWD_SET_TEXTUREANISOTROPICMODE, cv_granisotropicmode.value); } static void CV_screentextures_ONChange(void) { - if (rendermode == render_opengl) + ONLY_IF_GL_LOADED HWD.pfnSetSpecialState(HWD_SET_SCREEN_TEXTURES, cv_grscreentextures.value); } -static void CV_useCustomShaders_ONChange(void) +static void CV_grshaders_OnChange(void) { - if (rendermode == render_opengl) + ONLY_IF_GL_LOADED + HWR_SetShaderState(); + if ((cv_grpaletterendering.value)) { - if (cv_grshaders.value) - HWD.pfnInitCustomShaders(); + // can't do palette rendering without shaders, so update the state if needed + HWR_TogglePaletteRendering(); } } -static void CV_grpaletteshader_OnChange(void) +static void CV_grpaletterendering_OnChange(void) { - if (rendermode == render_opengl) + ONLY_IF_GL_LOADED + if (gr_shadersavailable) { - if (cv_grshaders.value) - { - HWD.pfnSetSpecialState(HWD_SET_PALETTE_SHADER_ENABLED, cv_grpaletteshader.value); - gr_use_palette_shader = cv_grpaletteshader.value; - V_SetPalette(0); - } + HWR_CompileShaders(); + HWR_TogglePaletteRendering(); } } -// change the palette directly to see the change -static void CV_Gammaxxx_ONChange(void) +static void CV_grpalettedepth_OnChange(void) { - if (rendermode == render_opengl) - V_SetPalette(0); + ONLY_IF_GL_LOADED + if (HWR_ShouldUsePaletteRendering()) + HWR_SetPalette(pLocalPalette); +} + +// +// Sets the shader state. +// +void HWR_SetShaderState(void) +{ + HWD.pfnSetSpecialState(HWD_SET_SHADERS, (INT32)HWR_UseShader()); } // ========================================================================== @@ -228,7 +248,7 @@ static line_t *gr_linedef; static sector_t *gr_frontsector; static sector_t *gr_backsector; -boolean gr_shadersavailable = true; +static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfaceInfo* Surf, INT32 cutflag, ffloor_t *pfloor, FBITFIELD polyflags); // Performance stats ps_metric_t ps_hw_nodesorttime = {0}; @@ -262,20 +282,24 @@ static fixed_t dup_viewx, dup_viewy, dup_viewz; static angle_t gr_aimingangle; static float gr_viewludsin, gr_viewludcos; -// -// PORTALS -// +// ========================================================================== +// Visual portals (attr. Hannu Hanhi) +// ========================================================================== -#define MAX_GRPORTALS 13 -// Note: portal sorting has not been ported to this -//#define PORTALSORTING // Breaks recursive portals :[ - - -// for porting gonna add stuff from r_portal here with adjustments - -typedef struct portal_s +enum { - struct portal_s *next; + GRPORTAL_OFF, + GRPORTAL_SEARCH, + GRPORTAL_STENCIL, + GRPORTAL_DEPTH, + GRPORTAL_INSIDE, +}; + +static int gr_portal = GRPORTAL_OFF; +static boolean gl_drawing_stencil = false; +typedef struct gl_portal_s +{ + struct gl_portal_s *next; // Viewport. fixed_t viewx; @@ -289,36 +313,38 @@ typedef struct portal_s INT32 drawcount; /**< For OpenGL. */ seg_t *seg; -} portal_t; +} gl_portal_t; -typedef struct portallist_s +typedef struct gl_portallist_s { - portal_t *base; - portal_t *cap; -} portallist_t; + gl_portal_t *base; + gl_portal_t *cap; +} gl_portallist_t; // new thing -portallist_t *currentportallist; +gl_portallist_t *currentportallist; INT32 portalviewside; // Linked list for portals. -portal_t *portal_base_gl, *portal_cap_gl; +gl_portal_t *portal_base_gl, *portal_cap_gl; +/* For now, these aren't used. // maybe at some point these could be organized better -void HWR_Portal_InitList (void) +static void HWR_Portal_InitList (void) { portalrender = 0; portal_base_gl = portal_cap_gl = NULL; } -void HWR_Portal_Remove (portal_t* portal) +static void HWR_Portal_Remove(gl_portal_t* portal) { portal_base_gl = portal->next; Z_Free(portal); } +*/ -void HWR_Portal_Add2Lines (const INT32 line1, const INT32 line2, seg_t *seg) +static void HWR_Portal_Add2Lines(const INT32 line1, const INT32 line2, seg_t *seg) { line_t *start, *dest; @@ -329,17 +355,9 @@ void HWR_Portal_Add2Lines (const INT32 line1, const INT32 line2, seg_t *seg) vertex_t dest_c, start_c; - portal_t *portal; + gl_portal_t *portal; - // check for duplicate - /*if (currentportallist->base && currentportallist->cap->startline == line1 && currentportallist->cap->clipline == line2) - { - if (printportals) - CONS_Printf("Duplicate portal skipped\n"); - return; - }*/ - - portal = Z_Malloc(sizeof(portal_t), PU_STATIC, NULL); + portal = Z_Malloc(sizeof(gl_portal_t), PU_STATIC, NULL); // Linked list. if (!currentportallist->base) @@ -393,7 +411,7 @@ void HWR_Portal_Add2Lines (const INT32 line1, const INT32 line2, seg_t *seg) portal->clipline = line2; } -void HWR_PortalFrame(portal_t* portal) +static void HWR_PortalFrame(gl_portal_t* portal) { viewx = portal->viewx; viewy = portal->viewy; @@ -418,57 +436,35 @@ void HWR_PortalFrame(portal_t* portal) } } -enum -{ - GRPORTAL_OFF, - GRPORTAL_SEARCH, - GRPORTAL_STENCIL, - GRPORTAL_DEPTH, - GRPORTAL_INSIDE, -}; - -void HWR_RenderSinglePortal(portal_t *portal, size_t portalnum, float fpov, player_t *player); - -#ifdef PORTALSORTING -static portal_t gr_portals[MAX_GRPORTALS]; -static size_t gr_numportals = 0; - -static void HWR_AddPortal(portal_t *portal); -static void HWR_SortPortals(player_t *player, float fpov, INT32 viewnumber, postimg_t *ptype); -#endif - -static int gr_portal = GRPORTAL_OFF; -static boolean gl_drawing_stencil = false; - -// Culling -typedef struct -{ - seg_t *seg; - sector_t *frontsector; - sector_t *backsector; -} gr_portalcullinfo_t; - -static gr_portalcullinfo_t gr_portalsegs[MAX_GRPORTALS]; -static size_t gr_numportalsegs = 0; - -static sector_t *gr_portalcullsectors[MAX_GRPORTALS]; -static size_t gr_numportalcullsectors = 0; - // ========================================================================== // Lighting // ========================================================================== +boolean HWR_UseShader(void) +{ + return (cv_grshaders.value && gr_shadersavailable); +} + +boolean HWR_ShouldUsePaletteRendering(void) +{ + return (cv_grpaletterendering.value && HWR_UseShader()); +} + +boolean HWR_PalRenderFlashpal(void) +{ + return (HWR_ShouldUsePaletteRendering() && cv_grflashpal.value); +} + void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *colormap) { RGBA_t poly_color, tint_color, fade_color; - boolean default_colormap = false; poly_color.rgba = 0xFFFFFFFF; tint_color.rgba = (colormap != NULL) ? (UINT32)colormap->rgba : GL_DEFAULTMIX; fade_color.rgba = (colormap != NULL) ? (UINT32)colormap->fadergba : GL_DEFAULTFOG; // Crappy backup coloring if you can't do shaders - if (!cv_grshaders.value || !gr_shadersavailable) + if (!HWR_UseShader()) { // be careful, this may get negative for high lightlevel values. float tint_alpha, fade_alpha; @@ -514,36 +510,10 @@ void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *col Surface->LightInfo.fade_start = (colormap != NULL) ? colormap->fadestart : 0; Surface->LightInfo.fade_end = (colormap != NULL) ? colormap->fadeend : 31; - if (gr_use_palette_shader) - { - if (!colormap) - { - colormap = &extra_colormaps[num_extra_colormaps]; - default_colormap = true; - } - if (!colormap->gl_lighttable_id) - { - UINT8 *colormap_pointer; - - if (default_colormap) - { - colormap_pointer = colormaps; - } - else - { - colormap_pointer = colormap->colormap; - } - colormap->gl_lighttable_id = HWD.pfnAddLightTable(colormap_pointer); - } - - Surface->LightTableId = colormap->gl_lighttable_id; - } -} - -void HWR_ClearLightTableCache() -{ - if (rendermode == render_opengl) - HWD.pfnClearLightTableCache(); + if (HWR_ShouldUsePaletteRendering()) + Surface->LightTableId = HWR_GetLightTableID(colormap); + else + Surface->LightTableId = 0; } UINT8 HWR_FogBlockAlpha(INT32 light, extracolormap_t *colormap) // Let's see if this can work @@ -553,7 +523,7 @@ UINT8 HWR_FogBlockAlpha(INT32 light, extracolormap_t *colormap) // Let's see if realcolor.rgba = (colormap != NULL) ? colormap->rgba : GL_DEFAULTMIX; - if (cv_grshaders.value && gr_shadersavailable) + if (HWR_UseShader()) { surfcolor.s.alpha = (255 - light); } @@ -576,7 +546,6 @@ UINT8 HWR_FogBlockAlpha(INT32 light, extracolormap_t *colormap) // Let's see if return surfcolor.s.alpha; } - static FUINT HWR_CalcWallLight(FUINT lightnum, fixed_t v1x, fixed_t v1y, fixed_t v2x, fixed_t v2y) { INT16 finallight = lightnum; @@ -666,7 +635,7 @@ static FUINT HWR_CalcSlopeLight(FUINT lightnum, angle_t dir, fixed_t delta) // HWR_RenderPlane // Render a floor or ceiling convex polygon -void HWR_RenderPlane(extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, FBITFIELD PolyFlags, INT32 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap, subsector_t *subsector) +void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, FBITFIELD PolyFlags, INT32 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap) { polyvertex_t * pv; float height; //constant y for all points on the convex flat polygon @@ -687,6 +656,8 @@ void HWR_RenderPlane(extrasubsector_t *xsub, boolean isceiling, fixed_t fixedhei static FOutVector *planeVerts = NULL; static UINT16 numAllocedPlaneVerts = 0; + + INT32 shader = SHADER_NONE; // no convex poly were generated for this subsector if (!xsub->planepoly) @@ -821,8 +792,8 @@ void HWR_RenderPlane(extrasubsector_t *xsub, boolean isceiling, fixed_t fixedhei #define SETUP3DVERT(vert, vx, vy) {\ /* Hurdler: add scrolling texture on floor/ceiling */\ - vert->s = (float)(((vx) / fflatsize) - flatxref + scrollx);\ - vert->t = (float)(flatyref - ((vy) / fflatsize) + scrolly);\ + vert->s = (float)(((vx) / fflatsize) - flatxref + scrollx);\ + vert->t = (float)(flatyref - ((vy) / fflatsize) + scrolly);\ \ /* Need to rotate before translate */\ if (angle) /* Only needs to be done if there's an altered angle */\ @@ -861,16 +832,21 @@ void HWR_RenderPlane(extrasubsector_t *xsub, boolean isceiling, fixed_t fixedhei else PolyFlags |= PF_Masked|PF_Modulated; - if (PolyFlags & PF_Fog) - HWD.pfnSetShader(6); // fog shader - else if (PolyFlags & PF_Ripple) - HWD.pfnSetShader(5); // water shader - else - HWD.pfnSetShader(gr_use_palette_shader ? 9 : 1); // floor shader + if (HWR_UseShader()) + { + if (PolyFlags & PF_Fog) + shader = SHADER_FOG; // fog shader + else if (PolyFlags & PF_Ripple) + shader = SHADER_WATER; // water shader + else + shader = SHADER_FLOOR; // floor shader + + PolyFlags |= PF_ColorMapped; + } - HWD.pfnDrawPolygon(&Surf, planeVerts, nrPlaneVerts, PolyFlags, false); + HWR_ProcessPolygon(&Surf, planeVerts, nrPlaneVerts, PolyFlags, shader, false); - if (subsector) + if (subsector && cv_grhorizonlines.value) { // Horizon lines FOutVector horizonpts[6]; @@ -886,7 +862,7 @@ void HWR_RenderPlane(extrasubsector_t *xsub, boolean isceiling, fixed_t fixedhei for (i = 0; i < subsector->numlines; i++, line++) { - if (line->linedef->special == 41 && R_PointOnSegSide(dup_viewx, dup_viewy, line) == 0) + if (line->linedef->special == HORIZONSPECIAL && R_PointOnSegSide(dup_viewx, dup_viewy, line) == 0) { P_ClosestPointOnLine(viewx, viewy, line->linedef, &v); dist = FIXED_TO_FLOAT(R_PointToDist(v.x, v.y)); @@ -953,7 +929,7 @@ void HWR_RenderPlane(extrasubsector_t *xsub, boolean isceiling, fixed_t fixedhei horizonpts[4].y = gr_viewz; // Draw - HWD.pfnDrawPolygon(&Surf, horizonpts, 6, PolyFlags, true); + HWR_ProcessPolygon(&Surf, horizonpts, 6, PolyFlags, shader, true); } } } @@ -969,6 +945,8 @@ static void HWR_DrawSegsSplats(FSurfaceInfo * pSurf) fixed_t i; // seg bbox fixed_t segbbox[4]; + + INT32 shader = SHADER_NONE; M_ClearBox(segbbox); M_AddToBox(segbbox, @@ -1020,8 +998,10 @@ static void HWR_DrawSegsSplats(FSurfaceInfo * pSurf) break; } - HWD.pfnSetShader(gr_use_palette_shader ? 10 : 2); // wall shader - HWD.pfnDrawPolygon(&pSurf, wallVerts, 4, i|PF_Modulated|PF_Decal, false); + if (HWR_UseShader()) + shader = SHADER_WALL; // wall shader + + HWR_ProcessPolygon(&pSurf, wallVerts, 4, i|PF_Modulated|PF_Decal, shader, false); } } #endif @@ -1052,9 +1032,15 @@ FBITFIELD HWR_TranstableToAlpha(INT32 transtablenum, FSurfaceInfo *pSurf) // void HWR_ProjectWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blendmode, INT32 lightlevel, extracolormap_t *wallcolormap) { + INT32 shader = SHADER_NONE; + HWR_Lighting(pSurf, lightlevel, wallcolormap); - HWD.pfnSetShader(gr_use_palette_shader ? 10 : 2); // wall shader + if (HWR_UseShader()) + { + shader = SHADER_WALL; // wall shader + blendmode |= PF_ColorMapped; + } // don't draw to color buffer when drawing to stencil if (gl_drawing_stencil) @@ -1063,7 +1049,7 @@ void HWR_ProjectWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend blendmode &= ~PF_Masked; } - HWD.pfnDrawPolygon(pSurf, wallVerts, 4, blendmode|PF_Modulated|PF_Occlude, false); + HWR_ProcessPolygon(pSurf, wallVerts, 4, blendmode|PF_Modulated|PF_Occlude, shader, false); // wall shader #ifdef WALLSPLATS if (gr_curline->linedef->splats && cv_splats.value) @@ -1074,12 +1060,10 @@ void HWR_ProjectWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend // // HWR_SplitWall // -void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfaceInfo* Surf, INT32 cutflag, ffloor_t *pfloor, FBITFIELD polyflags) +// SoM: split up and light walls according to the lightlist. +// This may also include leaving out parts of the wall that can't be seen +static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfaceInfo* Surf, INT32 cutflag, ffloor_t *pfloor, FBITFIELD polyflags) { - /* SoM: split up and light walls according to the - lightlist. This may also include leaving out parts - of the wall that can't be seen */ - float realtop, realbot, top, bot; float pegt, pegb, pegmul; float height = 0.0f, bheight = 0.0f; @@ -1088,67 +1072,82 @@ void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfa float endrealtop, endrealbot, endtop, endbot; float endpegt, endpegb, endpegmul; float endheight = 0.0f, endbheight = 0.0f; + + float diff; - fixed_t v1x = FLOAT_TO_FIXED(wallVerts[0].x); - fixed_t v1y = FLOAT_TO_FIXED(wallVerts[0].z); // not a typo - fixed_t v2x = FLOAT_TO_FIXED(wallVerts[1].x); - fixed_t v2y = FLOAT_TO_FIXED(wallVerts[1].z); // not a typo - // compiler complains when P_GetZAt is used in FLOAT_TO_FIXED directly - // use this as a temp var to store P_GetZAt's return value each time - fixed_t temp; + fixed_t v1x = FloatToFixed(wallVerts[0].x); + fixed_t v1y = FloatToFixed(wallVerts[0].z); + fixed_t v2x = FloatToFixed(wallVerts[1].x); + fixed_t v2y = FloatToFixed(wallVerts[1].z); #endif - INT32 solid, i; - lightlist_t * list = sector->lightlist; const UINT8 alpha = Surf->PolyColor.s.alpha; FUINT lightnum = HWR_CalcWallLight(sector->lightlevel, v1x, v1y, v2x, v2y); extracolormap_t *colormap = NULL; realtop = top = wallVerts[3].y; realbot = bot = wallVerts[0].y; + + diff = top - bot; + pegt = wallVerts[3].t; pegb = wallVerts[0].t; - pegmul = (pegb - pegt) / (top - bot); - if (fpclassify(pegmul) == FP_NAN) + // Lactozilla: If both heights of a side lay on the same position, then this wall is a triangle. + // To avoid division by zero, which would result in a NaN, we check if the vertical difference + // between the two vertices is not zero. + if (fpclassify(diff) == FP_ZERO) pegmul = 0.0; + else + pegmul = (pegb - pegt) / diff; #ifdef ESLOPE endrealtop = endtop = wallVerts[2].y; - endrealbot = endbot = wallVerts[1].y; + endrealbot = endbot = wallVerts[1].y; endpegt = wallVerts[2].t; endpegb = wallVerts[1].t; endpegmul = (endpegb - endpegt) / (endtop - endbot); #endif - if (fpclassify(endpegmul) == FP_NAN) - endpegmul = 0.0; - - for (i = 0; i < sector->numlights; i++) + for (INT32 i = 0; i < sector->numlights; i++) { #ifdef ESLOPE if (endtop < endrealbot) #endif if (top < realbot) return; + + lightlist_t *list = sector->lightlist; if (!(list[i].flags & FF_NOSHADE)) { if (pfloor && (pfloor->flags & FF_FOG)) { - colormap = pfloor->master->frontsector->extra_colormap; - lightnum = pfloor->master->frontsector->lightlevel; - lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, v1x, v1y, v2x, v2y); + if (HWR_ShouldUsePaletteRendering()) + { + lightnum = pfloor->master->frontsector->lightlevel; + colormap = pfloor->master->frontsector->extra_colormap; + lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, v1x, v1y, v2x, v2y); + }else{ + lightnum = HWR_CalcWallLight(pfloor->master->frontsector->lightlevel, v1x, v1y, v2x, v2y); + colormap = pfloor->master->frontsector->extra_colormap; + } } else { - colormap = list[i].extra_colormap; - lightnum = *list[i].lightlevel; - lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, v1x, v1y, v2x, v2y); + if (HWR_ShouldUsePaletteRendering()) + { + lightnum = *list[i].lightlevel; + colormap = list[i].extra_colormap; + lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, v1x, v1y, v2x, v2y); + }else{ + lightnum = HWR_CalcWallLight(*list[i].lightlevel, v1x, v1y, v2x, v2y); + colormap = list[i].extra_colormap; + } } } - solid = false; + boolean solid = false; if ((sector->lightlist[i].flags & FF_CUTSOLIDS) && !(cutflag & FF_EXTRA)) solid = true; @@ -1168,21 +1167,18 @@ void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfa #ifdef ESLOPE if (list[i].slope) { - temp = P_GetZAt(list[i].slope, v1x, v1y); - height = FIXED_TO_FLOAT(temp); - temp = P_GetZAt(list[i].slope, v2x, v2y); - endheight = FIXED_TO_FLOAT(temp); + height = FixedToFloat(P_GetZAt(list[i].slope, v1x, v1y)); + endheight = FixedToFloat(P_GetZAt(list[i].slope, v2x, v2y)); } else height = endheight = FIXED_TO_FLOAT(list[i].height); + if (solid) { if (*list[i].caster->b_slope) { - temp = P_GetZAt(*list[i].caster->b_slope, v1x, v1y); - bheight = FIXED_TO_FLOAT(temp); - temp = P_GetZAt(*list[i].caster->b_slope, v2x, v2y); - endbheight = FIXED_TO_FLOAT(temp); + bheight = FixedToFloat(P_GetZAt(*list[i].caster->b_slope, v1x, v1y)); + endbheight = FixedToFloat(P_GetZAt(*list[i].caster->b_slope, v2x, v2y)); } else bheight = endbheight = FIXED_TO_FLOAT(*list[i].caster->bottomheight); @@ -1211,10 +1207,8 @@ void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfa { if (list[i+1].slope) { - temp = P_GetZAt(list[i+1].slope, v1x, v1y); - bheight = FIXED_TO_FLOAT(temp); - temp = P_GetZAt(list[i+1].slope, v2x, v2y); - endbheight = FIXED_TO_FLOAT(temp); + bheight = FixedToFloat(P_GetZAt(list[i+1].slope, v1x, v1y)); + endbheight = FixedToFloat(P_GetZAt(list[i+1].slope, v2x, v2y)); } else bheight = endbheight = FIXED_TO_FLOAT(list[i+1].height); @@ -1235,6 +1229,8 @@ void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfa } #endif + if (cv_splitwallfix.value) + { #ifdef ESLOPE if (endbheight > endtop) endbot = endtop; @@ -1251,6 +1247,27 @@ void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfa #ifdef ESLOPE endbot = min(max(endbheight, endrealbot), endtop); #endif + }else{ +#ifdef ESLOPE + if (endbheight >= endtop) +#endif + if (bheight >= top) + continue; + + //Found a break; + bot = bheight; + + if (bot < realbot) + bot = realbot; + +#ifdef ESLOPE + endbot = endbheight; + + if (endbot < endrealbot) + endbot = endrealbot; +#endif + } + Surf->PolyColor.s.alpha = alpha; @@ -1273,13 +1290,23 @@ void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfa wallVerts[2].y = wallVerts[3].y = top; wallVerts[0].y = wallVerts[1].y = bot; #endif - - if (cutflag & FF_FOG) - HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Fog|PF_NoTexture|polyflags, true, lightnum, colormap); - else if (cutflag & FF_TRANSLUCENT) - HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Translucent|polyflags, false, lightnum, colormap); - else - HWR_ProjectWall(wallVerts, Surf, PF_Masked|polyflags, lightnum, colormap); + if (cv_fofzfightfix.value) + { + if (cutflag & FF_FOG) + HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Fog|PF_NoTexture|polyflags, true, lightnum, colormap); + else if (cutflag & FF_TRANSLUCENT) + HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Translucent|polyflags, false, lightnum, colormap); + else + HWR_ProjectWall(wallVerts, Surf, PF_Masked|polyflags, lightnum, colormap); + }else{ + if (cutflag & FF_FOG) + HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Fog|PF_NoTexture, true, lightnum, colormap); + else if (cutflag & FF_TRANSLUCENT) + HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Translucent, false, lightnum, colormap); + else + HWR_ProjectWall(wallVerts, Surf, PF_Masked, lightnum, colormap); + } + top = bot; #ifdef ESLOPE @@ -1317,12 +1344,22 @@ void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfa wallVerts[0].y = wallVerts[1].y = bot; #endif - if (cutflag & FF_FOG) - HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Fog|PF_NoTexture|polyflags, true, lightnum, colormap); - else if (cutflag & FF_TRANSLUCENT) - HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Translucent|polyflags, false, lightnum, colormap); - else - HWR_ProjectWall(wallVerts, Surf, PF_Masked|polyflags, lightnum, colormap); + if (cv_fofzfightfix.value) + { + if (cutflag & FF_FOG) + HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Fog|PF_NoTexture|polyflags, true, lightnum, colormap); + else if (cutflag & FF_TRANSLUCENT) + HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Translucent|polyflags, false, lightnum, colormap); + else + HWR_ProjectWall(wallVerts, Surf, PF_Masked|polyflags, lightnum, colormap); + }else{ + if (cutflag & FF_FOG) + HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Fog|PF_NoTexture, true, lightnum, colormap); + else if (cutflag & FF_TRANSLUCENT) + HWR_AddTransparentWall(wallVerts, Surf, texnum, PF_Translucent, false, lightnum, colormap); + else + HWR_ProjectWall(wallVerts, Surf, PF_Masked, lightnum, colormap); + } } // skywall list system for fixing portal issues by postponing skywall rendering (and using stencil buffer for them) @@ -1337,12 +1374,12 @@ int skyWallVertexArrayAllocSize = 65536;// what a mouthful boolean gr_collect_skywalls = false; -void HWR_SkyWallList_Clear() +static void HWR_SkyWallList_Clear(void) { skyWallVertexArraySize = 0; } -void HWR_SkyWallList_Add(FOutVector *wallVerts) +static void HWR_SkyWallList_Add(FOutVector *wallVerts) { if (!skyWallVertexArray) { @@ -1361,18 +1398,18 @@ void HWR_SkyWallList_Add(FOutVector *wallVerts) skyWallVertexArraySize++; } -void HWR_DrawSkyWallList() +static void HWR_DrawSkyWallList(void) { int i; FSurfaceInfo surf; surf.PolyColor.rgba = 0xFFFFFFFF; - HWD.pfnSetTexture(NULL); + HWR_SetCurrentTexture(NULL); HWD.pfnUnSetShader(); for (i = 0; i < skyWallVertexArraySize; i++) { - HWD.pfnDrawPolygon(&surf, skyWallVertexArray + i * 4, 4, PF_Occlude|PF_Invisible|PF_NoTexture, false); + HWD.pfnDrawPolygon(&surf, skyWallVertexArray + i * 4, 4, PF_Occlude|PF_Invisible|PF_NoTexture); } } @@ -1393,7 +1430,7 @@ void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) } else { - HWD.pfnSetTexture(NULL); + HWR_SetCurrentTexture(NULL); HWR_ProjectWall(wallVerts, Surf, PF_Invisible|PF_NoTexture, 255, NULL); } // PF_Invisible so it's not drawn into the colour buffer @@ -1401,68 +1438,6 @@ void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) // PF_Occlude is set in HWR_ProjectWall to draw into the depth buffer } -// HWR_DrawPortalClipWall -// Draws an invisible wall that extends to nowhere, -// so that portals can be clipped correctly. -static void HWR_DrawPortalClipWall(line_t *line) -{ - FOutVector wallVerts[4]; - FSurfaceInfo Surf; - v2d_t vs, ve; - fixed_t length = 1000*FRACUNIT; - fixed_t temp = 0; - - angle_t angle = R_PointToAngle2(line->v1->x, line->v1->y, line->v2->x, line->v2->y); - angle_t lineangle = 0; - - // no texture - HWD.pfnSetTexture(NULL); - wallVerts[3].t = wallVerts[2].t = 0; - wallVerts[0].t = wallVerts[1].t = 0; - wallVerts[0].s = wallVerts[3].s = 0; - wallVerts[2].s = wallVerts[1].s = 0; - - //wallVerts[0].w = wallVerts[1].w = wallVerts[2].w = wallVerts[3].w = 1.0f; whatever this is i guess it cant be here - wallVerts[0].y = wallVerts[1].y = FIXED_TO_FLOAT(INT32_MIN); - wallVerts[2].y = wallVerts[3].y = FIXED_TO_FLOAT(INT32_MAX); - - // first - vs.x = FIXED_TO_FLOAT(line->v1->x); - vs.y = FIXED_TO_FLOAT(line->v1->y); - - angle -= ANGLE_180; - lineangle = (angle >> ANGLETOFINESHIFT); - temp = FixedMul(length, FINECOSINE(lineangle)); - ve.x = vs.x + FIXED_TO_FLOAT(temp); - temp = FixedMul(length, FINESINE(lineangle)); - ve.y = vs.y + FIXED_TO_FLOAT(temp); - - wallVerts[0].x = wallVerts[3].x = ve.x; - wallVerts[0].z = wallVerts[3].z = ve.y; - wallVerts[2].x = wallVerts[1].x = vs.x; - wallVerts[2].z = wallVerts[1].z = vs.y; - - HWR_ProjectWall(wallVerts, &Surf, PF_NoTexture, 255, NULL); - - // second - vs.x = FIXED_TO_FLOAT(line->v2->x); - vs.y = FIXED_TO_FLOAT(line->v2->y); - - angle += ANGLE_180; - lineangle = (angle >> ANGLETOFINESHIFT); - temp = FixedMul(length, FINECOSINE(lineangle)); - ve.x = vs.x + FIXED_TO_FLOAT(temp); - temp = FixedMul(length, FINESINE(lineangle)); - ve.y = vs.y + FIXED_TO_FLOAT(temp); - - wallVerts[0].x = wallVerts[3].x = ve.x; - wallVerts[0].z = wallVerts[3].z = ve.y; - wallVerts[2].x = wallVerts[1].x = vs.x; - wallVerts[2].z = wallVerts[1].z = vs.y; - - HWR_ProjectWall(wallVerts, &Surf, PF_NoTexture, 255, NULL); -} - // // HWR_ProcessSeg // A portion or all of a wall segment will be drawn, from startfrac to endfrac, @@ -1560,10 +1535,16 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom cliphigh = (float)(texturehpeg + (gr_curline->flength*FRACUNIT)); } - colormap = gr_frontsector->extra_colormap; - lightnum = gr_frontsector->lightlevel; - lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, vs.x, vs.y, ve.x, ve.y); - + if (HWR_ShouldUsePaletteRendering()) + { + lightnum = gr_frontsector->lightlevel; + colormap = gr_frontsector->extra_colormap; + lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, vs.x, vs.y, ve.x, ve.y); + }else{ + lightnum = HWR_CalcWallLight(gr_frontsector->lightlevel, vs.x, vs.y, ve.x, ve.y); + colormap = gr_frontsector->extra_colormap; + } + if (gr_frontsector) Surf.PolyColor.s.alpha = 255; @@ -1927,6 +1908,10 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom popentopslope = min(worldtopslope, worldhighslope); popenbottomslope = max(worldbottomslope, worldlowslope); +#else + popentop = min(front->ceilingheight, back->ceilingheight); + popenbottom = max(front->floorheight, back->floorheight); +#endif } #ifdef ESLOPE @@ -1991,38 +1976,108 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom l = max(polybottom, lowcut); hS = min(highcutslope, polytopslope); lS = max(polybottomslope, lowcutslope); - + // PEGGING fixed_t texturevpeg, texturevpegslope; + + grTex = HWR_GetTexture(gr_midtexture); + + if (cv_slopepegfix.value) + { + if (!!(gr_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gr_linedef->flags & ML_EFFECT3)) + { + texturevpeg = midtexheight - h + polybottom; + texturevpegslope = midtexheight - hS + polybottomslope; + } + else + { + texturevpeg = polytop - h; + texturevpegslope = polytopslope - hS; + } + + wallVerts[3].t = texturevpeg * grTex->scaleY; + wallVerts[0].t = (h - l + texturevpeg) * grTex->scaleY; + wallVerts[2].t = texturevpegslope * grTex->scaleY; + wallVerts[1].t = (hS - lS + texturevpegslope) * grTex->scaleY; + wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; + wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; - if (!!(gr_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gr_linedef->flags & ML_EFFECT3)) - { - texturevpeg = midtexheight - h + polybottom; - texturevpegslope = midtexheight - hS + polybottomslope; + // set top/bottom coords + // Take the texture peg into account, rather than changing the offsets past + // where the polygon might not be. + wallVerts[3].y = FIXED_TO_FLOAT(h); + wallVerts[0].y = FIXED_TO_FLOAT(l); + wallVerts[2].y = FIXED_TO_FLOAT(hS); + wallVerts[1].y = FIXED_TO_FLOAT(lS); } else { - texturevpeg = polytop - h; - texturevpegslope = polytopslope - hS; - } - - grTex = HWR_GetTexture(gr_midtexture); - - wallVerts[3].t = texturevpeg * grTex->scaleY; - wallVerts[0].t = (h - l + texturevpeg) * grTex->scaleY; - wallVerts[2].t = texturevpegslope * grTex->scaleY; - wallVerts[1].t = (hS - lS + texturevpegslope) * grTex->scaleY; - wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; - wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; - - // set top/bottom coords - // Take the texture peg into account, rather than changing the offsets past - // where the polygon might not be. - wallVerts[3].y = FIXED_TO_FLOAT(h); - wallVerts[0].y = FIXED_TO_FLOAT(l); - wallVerts[2].y = FIXED_TO_FLOAT(hS); - wallVerts[1].y = FIXED_TO_FLOAT(lS); + // PEGGING +#ifdef ESLOPE + if (!!(gr_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gr_linedef->flags & ML_EFFECT3)) +#else + if (gr_linedef->flags & ML_DONTPEGBOTTOM) #endif + texturevpeg = textureheight[gr_sidedef->midtexture]*repeats - h + polybottom; + else + texturevpeg = polytop - h; + + wallVerts[3].t = wallVerts[2].t = texturevpeg * grTex->scaleY; + wallVerts[0].t = wallVerts[1].t = (h - l + texturevpeg) * grTex->scaleY; + wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; + wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; + + // set top/bottom coords + // Take the texture peg into account, rather than changing the offsets past + // where the polygon might not be. + wallVerts[2].y = wallVerts[3].y = FIXED_TO_FLOAT(h); + wallVerts[0].y = wallVerts[1].y = FIXED_TO_FLOAT(l); + +#ifdef ESLOPE + // Correct to account for slopes + { + fixed_t midtextureslant; + + if (gr_linedef->flags & ML_EFFECT2) + midtextureslant = 0; + else if (!!(gr_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gr_linedef->flags & ML_EFFECT3)) + midtextureslant = worldlow < worldbottom + ? worldbottomslope-worldbottom + : worldlowslope-worldlow; + else + midtextureslant = worldtop < worldhigh + ? worldtopslope-worldtop + : worldhighslope-worldhigh; + + polytop += midtextureslant; + polybottom += midtextureslant; + + highcut += worldtop < worldhigh + ? worldtopslope-worldtop + : worldhighslope-worldhigh; + lowcut += worldlow < worldbottom + ? worldbottomslope-worldbottom + : worldlowslope-worldlow; + + // Texture stuff + h = min(highcut, polytop); + l = max(polybottom, lowcut); + + { + // PEGGING + if (!!(gr_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gr_linedef->flags & ML_EFFECT3)) + texturevpeg = textureheight[gr_sidedef->midtexture]*repeats - h + polybottom; + else + texturevpeg = polytop - h; + wallVerts[2].t = texturevpeg * grTex->scaleY; + wallVerts[1].t = (h - l + texturevpeg) * grTex->scaleY; + } + + wallVerts[2].y = FIXED_TO_FLOAT(h); + wallVerts[1].y = FIXED_TO_FLOAT(l); + } +#endif + } // set alpha for transparent walls (new boom and legacy linedef types) FBITFIELD blendmode; @@ -2095,16 +2150,27 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom // Render midtextures on two-sided lines with a z-buffer offset. // This will cause the midtexture appear on top, if a FOF overlaps with it. - blendmode |= PF_Decal; + if (cv_fofzfightfix.value) + blendmode |= PF_Decal; if (!gl_drawing_stencil && gr_frontsector->numlights) { - if (!(blendmode & PF_Masked)) - HWR_SplitWall(gr_frontsector, wallVerts, gr_midtexture, &Surf, FF_TRANSLUCENT, NULL, PF_Decal); - else + if (cv_fofzfightfix.value) { - HWR_SplitWall(gr_frontsector, wallVerts, gr_midtexture, &Surf, FF_CUTLEVEL, NULL, PF_Decal); - } + if (!(blendmode & PF_Masked)) + HWR_SplitWall(gr_frontsector, wallVerts, gr_midtexture, &Surf, FF_TRANSLUCENT, NULL, PF_Decal); + else + { + HWR_SplitWall(gr_frontsector, wallVerts, gr_midtexture, &Surf, FF_CUTLEVEL, NULL, PF_Decal); + } + }else{ + if (!(blendmode & PF_Masked)) + HWR_SplitWall(gr_frontsector, wallVerts, gr_midtexture, &Surf, FF_TRANSLUCENT, NULL, 0); + else + { + HWR_SplitWall(gr_frontsector, wallVerts, gr_midtexture, &Surf, FF_CUTLEVEL, NULL, 0); + } + } } else if (!gl_drawing_stencil && !(blendmode & PF_Masked)) HWR_AddTransparentWall(wallVerts, &Surf, gr_midtexture, blendmode, false, lightnum, colormap); @@ -2116,7 +2182,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom { // Single sided line... Deal only with the middletexture (if one exists) gr_midtexture = R_GetTextureNum(gr_sidedef->midtexture); - if (gr_midtexture && gr_linedef->special != 41) // (Ignore horizon line for OGL) + if (gr_midtexture && gr_linedef->special != HORIZONSPECIAL) // Ignore horizon line for OGL { { fixed_t texturevpeg; @@ -2233,7 +2299,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom { ffloor_t * rover; fixed_t highcut = 0, lowcut = 0; - fixed_t lowcutslope, highcutslope; + fixed_t lowcutslope = 0, highcutslope = 0; // Used for height comparisons and etc across FOFs and slopes fixed_t high1, highslope1, low1, lowslope1; @@ -2241,10 +2307,21 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom INT32 texnum; line_t * newline = NULL; // Multi-Property FOF - lowcut = max(worldbottom, worldlow); - highcut = min(worldtop, worldhigh); - lowcutslope = max(worldbottomslope, worldlowslope); - highcutslope = min(worldtopslope, worldhighslope); + if (!cv_grfofcut.value) + { + ///TODO add slope support (fixing cutoffs, proper wall clipping) - maybe just disable highcut/lowcut if either sector or FOF has a slope + /// to allow fun plane intersecting in OGL? But then people would abuse that and make software look bad. :C + highcut = gr_frontsector->ceilingheight < gr_backsector->ceilingheight ? gr_frontsector->ceilingheight : gr_backsector->ceilingheight; + lowcut = gr_frontsector->floorheight > gr_backsector->floorheight ? gr_frontsector->floorheight : gr_backsector->floorheight; + } + else + { + lowcut = max(worldbottom, worldlow); + highcut = min(worldtop, worldhigh); + lowcutslope = max(worldbottomslope, worldlowslope); + highcutslope = min(worldtopslope, worldhighslope); + } + if (gr_backsector->ffloors) { @@ -2253,17 +2330,26 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERSIDES) || (rover->flags & FF_INVERTSIDES)) continue; - SLOPEPARAMS(*rover->t_slope, high1, highslope1, *rover->topheight) - SLOPEPARAMS(*rover->b_slope, low1, lowslope1, *rover->bottomheight) + if (!cv_grfofcut.value) + { + if (*rover->topheight < lowcut || *rover->bottomheight > highcut) + continue; + } + else + { + SLOPEPARAMS(*rover->t_slope, high1, highslope1, *rover->topheight) + SLOPEPARAMS(*rover->b_slope, low1, lowslope1, *rover->bottomheight) + + if ((high1 < lowcut && highslope1 < lowcutslope) || (low1 > highcut && lowslope1 > highcutslope)) + continue; + } - if ((high1 < lowcut && highslope1 < lowcutslope) || (low1 > highcut && lowslope1 > highcutslope)) - continue; texnum = R_GetTextureNum(sides[rover->master->sidenum[0]].midtexture); if (rover->master->flags & ML_TFERLINE) { - size_t linenum = gr_curline->linedef-gr_backsector->lines[0]; + size_t linenum = min(gr_curline->linedef-gr_backsector->lines[0], rover->master->frontsector->linecount); newline = rover->master->frontsector->lines[0] + linenum; texnum = R_GetTextureNum(sides[newline->sidenum[0]].midtexture); } @@ -2273,17 +2359,31 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom hS = *rover->t_slope ? P_GetZAt(*rover->t_slope, v2x, v2y) : *rover->topheight; l = *rover->b_slope ? P_GetZAt(*rover->b_slope, v1x, v1y) : *rover->bottomheight; lS = *rover->b_slope ? P_GetZAt(*rover->b_slope, v2x, v2y) : *rover->bottomheight; - // Adjust the heights so the FOF does not overlap with top and bottom textures. - if (h >= highcut && hS >= highcutslope) + + + if (!cv_grfofcut.value) { - h = highcut; - hS = highcutslope; + if (!(*rover->t_slope) && !gr_frontsector->c_slope && !gr_backsector->c_slope && h > highcut) + h = hS = highcut; + if (!(*rover->b_slope) && !gr_frontsector->f_slope && !gr_backsector->f_slope && l < lowcut) + l = lS = lowcut; } - if (l <= lowcut && lS <= lowcutslope) + else { - l = lowcut; - lS = lowcutslope; + // Adjust the heights so the FOF does not overlap with top and bottom textures. + if (h >= highcut && hS >= highcutslope) + { + h = highcut; + hS = highcutslope; + } + if (l <= lowcut && lS <= lowcutslope) + { + l = lowcut; + lS = lowcutslope; + } } + + //Hurdler: HW code starts here //FIXME: check if peging is correct // set top/bottom coords @@ -2383,11 +2483,16 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom blendmode = PF_Fog|PF_NoTexture; - colormap = rover->master->frontsector->extra_colormap; - lightnum = rover->master->frontsector->lightlevel; - lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, vs.x, vs.y, ve.x, ve.y); - - + if (HWR_ShouldUsePaletteRendering()) + { + lightnum = rover->master->frontsector->lightlevel; + colormap = rover->master->frontsector->extra_colormap; + lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, vs.x, vs.y, ve.x, ve.y); + }else{ + lightnum = HWR_CalcWallLight(rover->master->frontsector->lightlevel, vs.x, vs.y, ve.x, ve.y); + colormap = rover->master->frontsector->extra_colormap; + } + Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(rover->master->frontsector->lightlevel, rover->master->frontsector->extra_colormap); if (gr_frontsector->numlights) @@ -2425,17 +2530,26 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERSIDES) || !(rover->flags & FF_ALLSIDES)) continue; - SLOPEPARAMS(*rover->t_slope, high1, highslope1, *rover->topheight) - SLOPEPARAMS(*rover->b_slope, low1, lowslope1, *rover->bottomheight) + if (!cv_grfofcut.value) + { + if (*rover->topheight < lowcut || *rover->bottomheight > highcut) + continue; + } + else + { + SLOPEPARAMS(*rover->t_slope, high1, highslope1, *rover->topheight) + SLOPEPARAMS(*rover->b_slope, low1, lowslope1, *rover->bottomheight) + + if ((high1 < lowcut && highslope1 < lowcutslope) || (low1 > highcut && lowslope1 > highcutslope)) + continue; + } - if ((high1 < lowcut && highslope1 < lowcutslope) || (low1 > highcut && lowslope1 > highcutslope)) - continue; texnum = R_GetTextureNum(sides[rover->master->sidenum[0]].midtexture); if (rover->master->flags & ML_TFERLINE) { - size_t linenum = gr_curline->linedef-gr_backsector->lines[0]; + size_t linenum = min(gr_curline->linedef-gr_backsector->lines[0], rover->master->frontsector->linecount); newline = rover->master->frontsector->lines[0] + linenum; texnum = R_GetTextureNum(sides[newline->sidenum[0]].midtexture); } @@ -2444,17 +2558,29 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom hS = *rover->t_slope ? P_GetZAt(*rover->t_slope, v2x, v2y) : *rover->topheight; l = *rover->b_slope ? P_GetZAt(*rover->b_slope, v1x, v1y) : *rover->bottomheight; lS = *rover->b_slope ? P_GetZAt(*rover->b_slope, v2x, v2y) : *rover->bottomheight; - // Adjust the heights so the FOF does not overlap with top and bottom textures. - if (h >= highcut && hS >= highcutslope) + + if (!cv_grfofcut.value) { - h = highcut; - hS = highcutslope; + if (!(*rover->t_slope) && !gr_frontsector->c_slope && !gr_backsector->c_slope && h > highcut) + h = hS = highcut; + if (!(*rover->b_slope) && !gr_frontsector->f_slope && !gr_backsector->f_slope && l < lowcut) + l = lS = lowcut; } - if (l <= lowcut && lS <= lowcutslope) + else { - l = lowcut; - lS = lowcutslope; + // Adjust the heights so the FOF does not overlap with top and bottom textures. + if (h >= highcut && hS >= highcutslope) + { + h = highcut; + hS = highcutslope; + } + if (l <= lowcut && lS <= lowcutslope) + { + l = lowcut; + lS = lowcutslope; + } } + //Hurdler: HW code starts here //FIXME: check if peging is correct // set top/bottom coords @@ -2508,9 +2634,15 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom blendmode = PF_Fog|PF_NoTexture; - colormap = rover->master->frontsector->extra_colormap; - lightnum = rover->master->frontsector->lightlevel; - lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, vs.x, vs.y, ve.x, ve.y); + if (HWR_ShouldUsePaletteRendering()) + { + lightnum = rover->master->frontsector->lightlevel; + colormap = rover->master->frontsector->extra_colormap; + lightnum = colormap ? lightnum : HWR_CalcWallLight(lightnum, vs.x, vs.y, ve.x, ve.y); + }else{ + lightnum = HWR_CalcWallLight(rover->master->frontsector->lightlevel, vs.x, vs.y, ve.x, ve.y); + colormap = rover->master->frontsector->extra_colormap; + } Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(rover->master->frontsector->lightlevel, rover->master->frontsector->extra_colormap); @@ -2632,15 +2764,7 @@ static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector) viewc1 = backc1; viewc2 = backc2; } -/* - // dont clip viewsector when rendering portal contents - if (portalclipline) - { - if (printportals) - CONS_Printf("Clipping skipped on portal viewsector\n"); - return false; - } -*/ + // check if camera is outside the bounds of the floor and the ceiling (noclipping) // either above the ceiling or below the floor if ((viewz > viewc1 && viewz > viewc2) || (viewz < viewf1 && viewz < viewf2)) @@ -2755,20 +2879,7 @@ void HWR_AddLine(seg_t *line) { vertex_t closest_point; boolean pass = false; - /* - if (P_PointOnLineSide(line->v1->x, line->v1->y, portalclipline) != portalviewside) - { - P_ClosestPointOnLine(line->v1->x, line->v1->y, portalclipline, &closest_point); - if (closest_point.x != line->v1->x || closest_point.y != line->v1->y) - pass = true; - } - if (!pass && P_PointOnLineSide(line->v2->x, line->v2->y, portalclipline) != portalviewside) - { - P_ClosestPointOnLine(line->v2->x, line->v2->y, portalclipline, &closest_point); - if (closest_point.x != line->v2->x || closest_point.y != line->v2->y) - pass = true; - } - */ + // similar idea than in PortalCheckBBox, but checking the line vertices instead // TODO could make the check more efficient and not check anything if pass==true from earlier or something P_ClosestPointOnLine(line->v1->x, line->v1->y, portalclipline, &closest_point); @@ -2782,19 +2893,7 @@ void HWR_AddLine(seg_t *line) { if (P_PointOnLineSide(line->v2->x, line->v2->y, portalclipline) != portalviewside) pass = true; - }/* - P_ClosestPointOnLine(v1x, v1y, portalclipline, &closest_point); - if (closest_point.x != v1x || closest_point.y != v1y) - { - if (P_PointOnLineSide(v1x, v1y, portalclipline) != portalviewside) - pass = true; } - P_ClosestPointOnLine(v2x, v2y, portalclipline, &closest_point); - if (closest_point.x != v2x || closest_point.y != v2y) - { - if (P_PointOnLineSide(v2x, v2y, portalclipline) != portalviewside) - pass = true; - }*/ if (!pass) return; } @@ -2817,83 +2916,6 @@ void HWR_AddLine(seg_t *line) gr_backsector = line->backsector; - // Portal line -/* - if (cv_grportals.value && line->linedef->special == 40 && line->side == 0) - { - if (portalrender < cv_maxportals.value) - { - // Find the other side! - INT32 line2 = P_FindSpecialLineFromTag(40, line->linedef->tag, -1); - if (line->linedef == &lines[line2]) - line2 = P_FindSpecialLineFromTag(40, line->linedef->tag, line2); - if (line2 >= 0) // found it! - { - // oh no :DD - if (gr_portal == GRPORTAL_PROCESS) - { - gr_portal = GRPORTAL_FOUND; - return; - } - - // Portal processing - if ((gr_portal == GRPORTAL_MASKING) || (gr_portal == GRPORTAL_INSIDE)) - { - // masking the view 1 - if (gr_portal == GRPORTAL_MASKING) - { - size_t numportal = gr_numportalsegs; - if (numportal < MAX_GRPORTALS) - { - gr_portalsegs[numportal].seg = line; - gr_portalsegs[numportal].frontsector = gr_frontsector; - gr_portalsegs[numportal].backsector = gr_backsector; - gr_numportalsegs++; - } - } - - // Add the portal - HWR_Portal_Add2Lines(line->linedef-lines, line2); - - // masking the view 2 - if (gr_portal == GRPORTAL_MASKING) - { - // portal_cap_gl = last added portal - portal_t *lastportal = portal_cap_gl; - lastportal->drawcount = drawcount++; - - // extend clipping - HWR_DrawPortalClipWall(line->linedef); - - // add cull sector - if (gr_numportalcullsectors < MAX_GRPORTALS) - { - sector_t *cullsec = NULL; - if (lastportal->clipline != -1) - { - line_t *grclipline = &lines[lastportal->clipline]; - cullsec = grclipline->frontsector; - } - gr_portalcullsectors[gr_numportalcullsectors] = cullsec; - gr_numportalcullsectors++; - } - } - } - - gld_clipper_SafeAddClipRange(angle2, angle1); - - if (gr_portal != GRPORTAL_OUTSIDE) - return; - } - } - // Recursed TOO FAR (viewing a portal within a portal) - // So uhhh, render it as a normal wall instead or something ??? - } -#ifndef PORTALSORTING - else if (gr_portal == GRPORTAL_MASKING) - return; -#endif -*/ if (line->linedef->special == 40) { if (line->side == 0) @@ -2910,6 +2932,8 @@ void HWR_AddLine(seg_t *line) dont_draw = true; } } + else + return;// dont do anything with the other side i guess? } doaddline: @@ -3058,9 +3082,9 @@ boolean HWR_CheckBBox(fixed_t *bspcoord) void HWR_AddPolyObjectSegs(void) { size_t i, j; - seg_t *gr_fakeline = Z_Calloc(sizeof(seg_t), PU_STATIC, NULL); - polyvertex_t *pv1 = Z_Calloc(sizeof(polyvertex_t), PU_STATIC, NULL); - polyvertex_t *pv2 = Z_Calloc(sizeof(polyvertex_t), PU_STATIC, NULL); + seg_t gr_fakeline; + polyvertex_t pv1; + polyvertex_t pv2; // Sort through all the polyobjects for (i = 0; i < numpolys; ++i) @@ -3069,25 +3093,20 @@ void HWR_AddPolyObjectSegs(void) for (j = 0; j < po_ptrs[i]->segCount; ++j) { // Copy the info of a polyobject's seg, then convert it to OpenGL floating point - M_Memcpy(gr_fakeline, po_ptrs[i]->segs[j], sizeof(seg_t)); + M_Memcpy(&gr_fakeline, po_ptrs[i]->segs[j], sizeof(seg_t)); // Now convert the line to float and add it to be rendered - pv1->x = FIXED_TO_FLOAT(gr_fakeline->v1->x); - pv1->y = FIXED_TO_FLOAT(gr_fakeline->v1->y); - pv2->x = FIXED_TO_FLOAT(gr_fakeline->v2->x); - pv2->y = FIXED_TO_FLOAT(gr_fakeline->v2->y); + pv1.x = FIXED_TO_FLOAT(gr_fakeline.v1->x); + pv1.y = FIXED_TO_FLOAT(gr_fakeline.v1->y); + pv2.x = FIXED_TO_FLOAT(gr_fakeline.v2->x); + pv2.y = FIXED_TO_FLOAT(gr_fakeline.v2->y); - gr_fakeline->pv1 = pv1; - gr_fakeline->pv2 = pv2; + gr_fakeline.pv1 = &pv1; + gr_fakeline.pv2 = &pv2; - HWR_AddLine(gr_fakeline); + HWR_AddLine(&gr_fakeline); } } - - // Free temporary data no longer needed - Z_Free(pv2); - Z_Free(pv1); - Z_Free(gr_fakeline); } #ifdef POLYOBJECTS_PLANES @@ -3108,6 +3127,8 @@ void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, fixed_t static FOutVector *planeVerts = NULL; static UINT16 numAllocedPlaneVerts = 0; + + INT32 shader = SHADER_NONE; nrPlaneVerts = polysector->numVertices; @@ -3251,8 +3272,13 @@ void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, fixed_t else blendmode |= PF_Masked|PF_Modulated; - HWD.pfnSetShader(gr_use_palette_shader ? 9 : 1); // floor shader - HWD.pfnDrawPolygon(&Surf, planeVerts, nrPlaneVerts, blendmode, false); + if (HWR_UseShader()) + { + shader = SHADER_FLOOR; // floor shader + blendmode |= PF_ColorMapped; + } + + HWR_ProcessPolygon(&Surf, planeVerts, nrPlaneVerts, blendmode, shader, false); // floor shader } void HWR_AddPolyObjectPlanes(void) @@ -3469,11 +3495,11 @@ void HWR_Subsector(size_t num) if (sub->validcount != validcount) { HWR_GetFlat(levelflats[gr_frontsector->floorpic].lumpnum, R_NoEncore(gr_frontsector, false)); - HWR_RenderPlane(&extrasubsectors[num], false, + HWR_RenderPlane(sub, &extrasubsectors[num], false, // Hack to make things continue to work around slopes. locFloorHeight == cullFloorHeight ? locFloorHeight : gr_frontsector->floorheight, // We now return you to your regularly scheduled rendering. - PF_Occlude, floorlightlevel, levelflats[gr_frontsector->floorpic].lumpnum, NULL, 255, floorcolormap, sub); + PF_Occlude, floorlightlevel, levelflats[gr_frontsector->floorpic].lumpnum, NULL, 255, floorcolormap); } } } @@ -3485,11 +3511,11 @@ void HWR_Subsector(size_t num) if (sub->validcount != validcount) { HWR_GetFlat(levelflats[gr_frontsector->ceilingpic].lumpnum, R_NoEncore(gr_frontsector, true)); - HWR_RenderPlane(&extrasubsectors[num], true, + HWR_RenderPlane(sub, &extrasubsectors[num], true, // Hack to make things continue to work around slopes. locCeilingHeight == cullCeilingHeight ? locCeilingHeight : gr_frontsector->ceilingheight, // We now return you to your regularly scheduled rendering. - PF_Occlude, ceilinglightlevel, levelflats[gr_frontsector->ceilingpic].lumpnum,NULL, 255, ceilingcolormap, sub); + PF_Occlude, ceilinglightlevel, levelflats[gr_frontsector->ceilingpic].lumpnum,NULL, 255, ceilingcolormap); } } } @@ -3554,8 +3580,8 @@ void HWR_Subsector(size_t num) { HWR_GetFlat(levelflats[*rover->bottompic].lumpnum, R_NoEncore(gr_frontsector, false)); light = R_GetPlaneLight(gr_frontsector, centerHeight, viewz < cullHeight ? true : false); - HWR_RenderPlane(&extrasubsectors[num], false, *rover->bottomheight, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Occlude, *gr_frontsector->lightlist[light].lightlevel, levelflats[*rover->bottompic].lumpnum, - rover->master->frontsector, 255, gr_frontsector->lightlist[light].extra_colormap, sub); + HWR_RenderPlane(sub, &extrasubsectors[num], false, *rover->bottomheight, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Occlude, *gr_frontsector->lightlist[light].lightlevel, levelflats[*rover->bottompic].lumpnum, + rover->master->frontsector, 255, gr_frontsector->lightlist[light].extra_colormap); } } @@ -3606,8 +3632,8 @@ void HWR_Subsector(size_t num) { HWR_GetFlat(levelflats[*rover->toppic].lumpnum, R_NoEncore(gr_frontsector, true)); light = R_GetPlaneLight(gr_frontsector, centerHeight, viewz < cullHeight ? true : false); - HWR_RenderPlane(&extrasubsectors[num], true, *rover->topheight, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Occlude, *gr_frontsector->lightlist[light].lightlevel, levelflats[*rover->toppic].lumpnum, - rover->master->frontsector, 255, gr_frontsector->lightlist[light].extra_colormap, sub); + HWR_RenderPlane(sub, &extrasubsectors[num], true, *rover->topheight, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Occlude, *gr_frontsector->lightlist[light].lightlevel, levelflats[*rover->toppic].lumpnum, + rover->master->frontsector, 255, gr_frontsector->lightlist[light].extra_colormap); } } } @@ -3700,7 +3726,7 @@ skip_stuff_for_portals: // use returned value as multiplier for the added values from p_thrust thing // P_InterceptVector needs divlines which need dx and dy, dx=x2-x1 dy=y2-y1 -boolean HWR_PortalCheckBBox(fixed_t *bspcoord) +static boolean HWR_PortalCheckBBox(fixed_t *bspcoord) { vertex_t closest_point; if (!portalclipline) @@ -3773,10 +3799,6 @@ void HWR_RenderBSPNode(INT32 bspnum) return; } - // in portal checking phase we can stop after one is found - //if (gr_portal == GRPORTAL_FOUND) - // return; - // Decide which side the view point is on. side = R_PointOnSide(viewx, viewy, bsp); @@ -3784,10 +3806,6 @@ void HWR_RenderBSPNode(INT32 bspnum) if (HWR_PortalCheckBBox(bsp->bbox[side])) HWR_RenderBSPNode(bsp->children[side]); - // in portal checking phase we can stop after one is found - //if (gr_portal == GRPORTAL_FOUND) - // return; - // Possibly divide back space. if (HWR_CheckBBox(bsp->bbox[side^1]) && HWR_PortalCheckBBox(bsp->bbox[side^1])) HWR_RenderBSPNode(bsp->children[side^1]); @@ -3916,11 +3934,14 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch, float t fixed_t slopez; float offset = 0; + INT32 shader = SHADER_NONE; + R_GetShadowZ(spr->mobj, &floorslope); mobjfloor = HWR_OpaqueFloorAtPos( spr->mobj->x, spr->mobj->y, spr->mobj->z, spr->mobj->height); + if (cv_shadowoffs.value) { angle_t shadowdir; @@ -4042,9 +4063,9 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch, float t swallVerts[0].t = swallVerts[1].t = gpatch->max_t; } - sSurf.PolyColor.s.red = 0x00; - sSurf.PolyColor.s.blue = 0x00; - sSurf.PolyColor.s.green = 0x00; + sSurf.PolyColor.s.red = 0x01; + sSurf.PolyColor.s.blue = 0x01; + sSurf.PolyColor.s.green = 0x01; // shadow is always half as translucent as the sprite itself if (!cv_translucency.value) // use default translucency (main sprite won't have any translucency) @@ -4062,8 +4083,13 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch, float t if (sSurf.PolyColor.s.alpha > floorheight/4) { sSurf.PolyColor.s.alpha = (UINT8)(sSurf.PolyColor.s.alpha - floorheight/4); - HWD.pfnSetShader(gr_use_palette_shader ? 9 : 1); // floor shader - HWD.pfnDrawPolygon(&sSurf, swallVerts, 4, PF_Translucent|PF_Modulated, false); + + if (HWR_UseShader()) + { + shader = SHADER_FLOOR; // floor shader + } + + HWR_ProcessPolygon(&sSurf, swallVerts, 4, PF_Translucent|PF_Modulated, shader, false); } } @@ -4079,7 +4105,7 @@ static void HWR_RotateSpritePolyToAim(gr_vissprite_t *spr, FOutVector *wallVerts // do interpolation if (R_UsingFrameInterpolation() && !paused) { - if (spr->precip) + if (precip) { R_InterpolatePrecipMobjState((precipmobj_t *)spr->mobj, rendertimefrac, &interp); } @@ -4090,7 +4116,7 @@ static void HWR_RotateSpritePolyToAim(gr_vissprite_t *spr, FOutVector *wallVerts } else { - if (spr->precip) + if (precip) { R_InterpolatePrecipMobjState((precipmobj_t *)spr->mobj, FRACUNIT, &interp); } @@ -4159,6 +4185,8 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) fixed_t v1x, v1y, v2x, v2y; #endif + INT32 shader = SHADER_NONE; + this_scale = FIXED_TO_FLOAT(spr->mobj->scale); if (hires) @@ -4273,6 +4301,7 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) } alpha = Surf.PolyColor.s.alpha; + // Start with the lightlevel and colormap from the top of the sprite lightlevel = *list[sector->numlights - 1].lightlevel; @@ -4428,9 +4457,14 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) HWR_Lighting(&Surf, lightlevel, colormap); Surf.PolyColor.s.alpha = alpha; - - HWD.pfnSetShader(gr_use_palette_shader ? 10 : 3); // sprite shader - HWD.pfnDrawPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, false); + + if (HWR_UseShader()) + { + shader = SHADER_SPRITE; // sprite shader + blend |= PF_ColorMapped; + } + + HWR_ProcessPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, shader, false); // sprite shader top = bot; #ifdef ESLOPE @@ -4469,8 +4503,13 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) Surf.PolyColor.s.alpha = alpha; - HWD.pfnSetShader(gr_use_palette_shader ? 10 : 3); // sprite shader - HWD.pfnDrawPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, false); + if (HWR_UseShader()) + { + shader = SHADER_SPRITE; // sprite shader + blend |= PF_ColorMapped; + } + + HWR_ProcessPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, shader, false); // sprite shader } // -----------------+ @@ -4484,6 +4523,9 @@ static void HWR_DrawSprite(gr_vissprite_t *spr) FOutVector wallVerts[4]; GLPatch_t *gpatch; // sprite patch converted to hardware FSurfaceInfo Surf; + + INT32 shader = SHADER_NONE; + const boolean hires = (spr->mobj && spr->mobj->skin && ((skin_t *)( (spr->mobj->localskin) ? spr->mobj->localskin : spr->mobj->skin ))->flags & SF_HIRES); if (spr->mobj) this_scale = FIXED_TO_FLOAT(spr->mobj->scale); @@ -4622,8 +4664,13 @@ static void HWR_DrawSprite(gr_vissprite_t *spr) blend = PF_Translucent|PF_Occlude; } - HWD.pfnSetShader(gr_use_palette_shader ? 10 : 3); // sprite shader - HWD.pfnDrawPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, false); + if (HWR_UseShader()) + { + shader = SHADER_SPRITE; // sprite shader + blend |= PF_ColorMapped; + } + + HWR_ProcessPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, shader, false); } } @@ -4634,6 +4681,8 @@ static inline void HWR_DrawPrecipitationSprite(gr_vissprite_t *spr) FOutVector wallVerts[4]; GLPatch_t *gpatch; // sprite patch converted to hardware FSurfaceInfo Surf; + + INT32 shader = SHADER_NONE; if (!spr->mobj) return; @@ -4716,8 +4765,13 @@ static inline void HWR_DrawPrecipitationSprite(gr_vissprite_t *spr) blend = PF_Translucent|PF_Occlude; } - HWD.pfnSetShader(gr_use_palette_shader ? 10 : 3); // sprite shader - HWD.pfnDrawPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, false); + if (HWR_UseShader()) + { + shader = SHADER_SPRITE; // sprite shader + blend |= PF_ColorMapped; + } + + HWR_ProcessPolygon(&Surf, wallVerts, 4, blend|PF_Modulated, shader, false); } // -------------------------------------------------------------------------- @@ -4877,7 +4931,12 @@ void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean planeinfo->isceiling = isceiling; planeinfo->fixedheight = fixedheight; - planeinfo->lightlevel = lightlevel; + + if (HWR_ShouldUsePaletteRendering()) + planeinfo->lightlevel = (planecolormap && (planecolormap->fog & 1)) ? 255 : lightlevel; + else + planeinfo->lightlevel = lightlevel; + planeinfo->lumpnum = lumpnum; planeinfo->xsub = xsub; planeinfo->alpha = alpha; @@ -4895,7 +4954,12 @@ void HWR_AddTransparentPolyobjectFloor(lumpnum_t lumpnum, polyobj_t *polysector, polyplaneinfo->isceiling = isceiling; polyplaneinfo->fixedheight = fixedheight; - polyplaneinfo->lightlevel = lightlevel; + + if (HWR_ShouldUsePaletteRendering()) + polyplaneinfo->lightlevel = (planecolormap && (planecolormap->fog & 1)) ? 255 : lightlevel; + else + polyplaneinfo->lightlevel = lightlevel; + polyplaneinfo->lumpnum = lumpnum; polyplaneinfo->polysector = polysector; polyplaneinfo->alpha = alpha; @@ -4982,19 +5046,19 @@ void HWR_RenderDrawNodes(void) { planeinfo_t *plane = &drawnode->u.plane; - // We aren't traversing the BSP tree, so make gl_frontsector null to avoid crashes. + // We aren't traversing the BSP tree, so make gr_frontsector null to avoid crashes. gr_frontsector = NULL; if (!(plane->blend & PF_NoTexture)) HWR_GetFlat(plane->lumpnum, R_NoEncore(plane->FOFSector, plane->isceiling)); - HWR_RenderPlane(plane->xsub, plane->isceiling, plane->fixedheight, plane->blend, plane->lightlevel, - plane->lumpnum, plane->FOFSector, plane->alpha, plane->planecolormap, NULL); + HWR_RenderPlane(NULL, plane->xsub, plane->isceiling, plane->fixedheight, plane->blend, plane->lightlevel, + plane->lumpnum, plane->FOFSector, plane->alpha, plane->planecolormap); } else if (drawnode->type == DRAWNODE_POLYOBJECT_PLANE) { polyplaneinfo_t *polyplane = &drawnode->u.polyplane; - // We aren't traversing the BSP tree, so make gl_frontsector null to avoid crashes. + // We aren't traversing the BSP tree, so make gr_frontsector null to avoid crashes. gr_frontsector = NULL; if (!(polyplane->blend & PF_NoTexture)) @@ -5229,10 +5293,12 @@ void HWR_ProjectSprite(mobj_t *thing) size_t lumpoff; unsigned rot; UINT8 flip; - angle_t ang; + boolean mirrored = thing->mirrored; + boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); + + angle_t ang, camang; const boolean papersprite = (thing->frame & FF_PAPERSPRITE); INT32 heightsec, phs; - vector3_t pos; fixed_t spr_width, spr_height; fixed_t spr_offset, spr_topoffset; @@ -5243,8 +5309,6 @@ void HWR_ProjectSprite(mobj_t *thing) angle_t sliptiderollangle = 0; #endif - - // uncapped/interpolation interpmobjstate_t interp = {0}; @@ -5292,11 +5356,11 @@ void HWR_ProjectSprite(mobj_t *thing) rot = thing->frame&FF_FRAMEMASK; //Fab : 02-08-98: 'skin' override spritedef currently used for skin - if (thing->skin && thing->sprite == SPR_PLAY) + if ((thing->skin || thing->localskin) && thing->sprite == SPR_PLAY) { sprdef = &((skin_t *)( (thing->localskin) ? thing->localskin : thing->skin ))->spritedef; #ifdef ROTSPRITE - sprinfo = &spriteinfo[thing->sprite]; + sprinfo = &((skin_t *)( (thing->localskin) ? thing->localskin : thing->skin ))->sprinfo; #endif } else @@ -5330,6 +5394,10 @@ void HWR_ProjectSprite(mobj_t *thing) #endif ang = R_PointToAngle (interp.x, interp.y) - interp.angle; + camang = R_PointToAngle (interp.x, interp.y); + + if (mirrored) + ang = InvAngle(ang); if (sprframe->rotate == SRF_SINGLE) { @@ -5378,29 +5446,38 @@ void HWR_ProjectSprite(mobj_t *thing) spr_topoffset = spritecachedinfo[lumpoff].topoffset; #ifdef ROTSPRITE - if ((thing->rollangle)||(thing->sloperoll)||(thing->player && thing->player->sliproll)) + if (cv_spriteroll.value) { - if (thing->player) - { - sliptiderollangle = cv_sliptideroll.value ? thing->player->sliproll*(thing->player->sliptidemem) : 0; - rollsum = (thing->rollangle)+(thing->sloperoll)+FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), sliptiderollangle); - } - else - rollsum = (thing->rollangle)+(thing->sloperoll); + rollangle = FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), interp.roll) + + FixedMul(FINESINE((ang) >> ANGLETOFINESHIFT), interp.pitch) + + FixedMul(FINECOSINE((camang) >> ANGLETOFINESHIFT), interp.sloperoll) + + FixedMul(FINESINE((camang) >> ANGLETOFINESHIFT), interp.slopepitch) + + thing->rollangle; - rollangle = R_GetRollAngle(rollsum); - rotsprite = Patch_GetRotatedSprite(sprframe, (thing->frame & FF_FRAMEMASK), rot, flip, false, sprinfo, rollangle); - - if (rotsprite != NULL) + if ((rollangle)||(thing->player && thing->player->sliproll)) { - spr_width = rotsprite->width << FRACBITS; - spr_height = rotsprite->height << FRACBITS; - spr_offset = rotsprite->leftoffset << FRACBITS; - spr_topoffset = rotsprite->topoffset << FRACBITS; - spr_topoffset += FEETADJUST; - - // flip -> rotate, not rotate -> flip - flip = 0; + if (thing->player) + { + sliptiderollangle = cv_sliptideroll.value ? thing->player->sliproll*(thing->player->sliptidemem) : 0; + rollsum = rollangle+FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), sliptiderollangle); + } + else + rollsum = rollangle; + + rollangle = R_GetRollAngle(rollsum); + rotsprite = Patch_GetRotatedSprite(sprframe, (thing->frame & FF_FRAMEMASK), rot, flip, false, sprinfo, rollangle); + + if (rotsprite != NULL) + { + spr_width = rotsprite->width << FRACBITS; + spr_height = rotsprite->height << FRACBITS; + spr_offset = rotsprite->leftoffset << FRACBITS; + spr_topoffset = rotsprite->topoffset << FRACBITS; + spr_topoffset += FEETADJUST; + + // flip -> rotate, not rotate -> flip + flip = 0; + } } } #endif @@ -5434,6 +5511,8 @@ void HWR_ProjectSprite(mobj_t *thing) this_xscale = spritexscale * this_scale; this_yscale = spriteyscale * this_scale; + + flip = !flip != !hflip; if (flip) { @@ -5504,7 +5583,7 @@ void HWR_ProjectSprite(mobj_t *thing) vis->spriteyoffset = FIXED_TO_FLOAT(spr_topoffset); #ifdef ROTSPRITE - if (rotsprite) + if ((rotsprite) && (cv_spriteroll.value)) vis->gpatch = (GLPatch_t *)rotsprite; else #endif @@ -5719,9 +5798,9 @@ void HWR_DrawSkyBackground(float fpov) dometransform.splitscreen = splitscreen; HWR_GetTexture(texturetranslation[skytexture]); - HWD.pfnSetShader(7); // sky shader + if (HWR_UseShader()) + HWD.pfnSetShader(HWR_GetShaderFromTarget(SHADER_SKY));// sky shader HWD.pfnRenderSkyDome(skytexture, textures[skytexture]->width, textures[skytexture]->height, dometransform); - HWD.pfnSetShader(0); } @@ -5852,7 +5931,7 @@ void HWR_ClearClipper(void) } // Adds an entry to the clipper for portal rendering -void HWR_PortalClipping(portal_t *portal) +static void HWR_PortalClipping(gl_portal_t *portal) { angle_t angle1, angle2; @@ -5865,14 +5944,84 @@ void HWR_PortalClipping(portal_t *portal) gld_clipper_SafeAddClipRange(angle2, angle1); } -// -// Render portals recursively depth first. With portals disabled only current scene is rendered. -// -void RecursivePortalRendering(portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals) +enum { - portallist_t portallist; - portal_t *portal; - portal_t *portal_temp; + HWR_STENCIL_NORMAL, + HWR_STENCIL_BEGIN, + HWR_STENCIL_REVERSE, + HWR_STENCIL_DEPTH, + HWR_STENCIL_SKY +}; + +// Changes the current stencil state. +static void HWR_SetStencilState(int state, int level) +{ + if (!cv_nostencil.value && level > -1) + HWD.pfnSetSpecialState(HWD_SET_STENCIL_LEVEL, level); + HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, state); +} + +// Renders a portal segment. +static void HWR_RenderPortalSeg(gl_portal_t* portal, int state) +{ + gl_drawing_stencil = true; // do not draw outside of the stencil buffer, idiot. + // set our portal state and prepare to render the seg + gr_portal = state; + gr_curline = portal->seg; + gr_frontsector = portal->seg->frontsector; + gr_backsector = portal->seg->backsector; + HWR_ProcessSeg(); + gl_drawing_stencil = false; + // need to work around the r_opengl PF_Invisible bug with this call + // similarly as in the linkdraw hack in HWR_DrawSprites + HWD.pfnSetBlend(PF_Translucent|PF_Occlude|PF_Masked); +} + +// Renders the current viewpoint, though takes portal arguments for recursive portals. +static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals); + +// Renders a single portal from the current viewpoint. +static void HWR_RenderPortal(gl_portal_t* portal, gl_portal_t* rootportal, const float fpov, player_t *player, int stencil_level) +{ + // draw portal seg to stencil buffer with increment + HWR_SetTransform(fpov, player); + HWR_ClearClipper(); + + HWR_SetStencilState(HWR_STENCIL_BEGIN, stencil_level); + HWR_RenderPortalSeg(portal, GRPORTAL_STENCIL); + + // go to portal frame lmao + HWR_PortalFrame(portal); + // call HWR_RenderViewpoint + HWR_RenderViewpoint(portal, fpov, player, stencil_level + 1, true); + // return to current frame + if (rootportal) + HWR_PortalFrame(rootportal); + else // current frame is not a portal frame but the main view! + { + R_SetupFrame(player, false); + portalclipline = NULL; + } + + // remove portal seg from stencil buffer + HWR_SetTransform(fpov, player); + HWR_ClearClipper(); + + HWR_SetStencilState(HWR_STENCIL_REVERSE, stencil_level); + HWR_RenderPortalSeg(portal, GRPORTAL_STENCIL); + + // draw portal seg to depth buffer + HWR_ClearClipper(); + HWR_SetStencilState(HWR_STENCIL_DEPTH, stencil_level); + HWR_RenderPortalSeg(portal, GRPORTAL_DEPTH); +} + +// Renders the current viewpoint, though takes portal arguments for recursive portals. +static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals) +{ + gl_portallist_t portallist; + gl_portal_t *portal; + gl_portal_t *gl_portal_temp; portallist.base = portallist.cap = NULL; const boolean skybox = (skyboxmo[0] && cv_skybox.value); @@ -5896,75 +6045,14 @@ void RecursivePortalRendering(portal_t *rootportal, const float fpov, player_t * { if (cv_portalline.value && cv_portalline.value != portal->startline) continue; - if (!cv_nostencil.value) - { - // draw portal seg to stencil buffer with increment - HWR_SetTransform(fpov, player); - HWR_ClearClipper(); - gl_drawing_stencil = true; - HWD.pfnSetSpecialState(HWD_SET_STENCIL_LEVEL, stencil_level); - HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, HWD_PORTAL_STENCIL_SEGS); - gr_portal = GRPORTAL_STENCIL; - gr_frontsector = portal->seg->frontsector; - validcount++; - HWR_AddLine(portal->seg); - gl_drawing_stencil = false; - // need to work around the r_opengl PF_Invisible bug with this call - // similarly as in the linkdraw hack in HWR_DrawSprites - HWD.pfnSetBlend(PF_Translucent|PF_Occlude|PF_Masked); - } - // go to portal frame - HWR_PortalFrame(portal); - // call RecursivePortalRendering - RecursivePortalRendering(portal, fpov, player, stencil_level + 1, true); - // return to current frame - if (rootportal) - HWR_PortalFrame(rootportal); - else// current frame is not a portal frame but the main view! - { - R_SetupFrame(player, false); - portalclipline = NULL; - } - if (!cv_nostencil.value) - { - // remove portal seg from stencil buffer - HWR_SetTransform(fpov, player); - HWR_ClearClipper(); - gl_drawing_stencil = true; - HWD.pfnSetSpecialState(HWD_SET_STENCIL_LEVEL, stencil_level); - HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, HWD_PORTAL_STENCIL_REVERSE_SEGS); - gr_portal = GRPORTAL_STENCIL; - gr_frontsector = portal->seg->frontsector; - validcount++; - HWR_AddLine(portal->seg); - gl_drawing_stencil = false; - // need to work around the r_opengl PF_Invisible bug with this call - // similarly as in the linkdraw hack in HWR_DrawSprites - HWD.pfnSetBlend(PF_Translucent|PF_Occlude|PF_Masked); - } - // draw portal seg to depth buffer - HWR_ClearClipper(); - gl_drawing_stencil = true; - if (!cv_nostencil.value) - HWD.pfnSetSpecialState(HWD_SET_STENCIL_LEVEL, stencil_level); - HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, HWD_PORTAL_DEPTH_SEGS); - gr_portal = GRPORTAL_DEPTH; - gr_frontsector = portal->seg->frontsector; - validcount++; - HWR_AddLine(portal->seg); - gl_drawing_stencil = false; - // need to work around the r_opengl PF_Invisible bug with this call - // similarly as in the linkdraw hack in HWR_DrawSprites - HWD.pfnSetBlend(PF_Translucent|PF_Occlude|PF_Masked); + HWR_RenderPortal(portal, rootportal, fpov, player, stencil_level); } gr_portal = GRPORTAL_INSIDE;// when portal walls are encountered in following bsp traversal, nothing should be drawn } else gr_portal = GRPORTAL_OFF;// there may be portals and they need to be drawn as regural walls // draw normal things in current frame in current incremented stencil buffer area - if (!cv_nostencil.value) - HWD.pfnSetSpecialState(HWD_SET_STENCIL_LEVEL, stencil_level); - HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, HWD_PORTAL_NORMAL); + HWR_SetStencilState(HWR_STENCIL_NORMAL, stencil_level); if (!cv_portalonly.value || rootportal) { HWR_ClearClipper(); @@ -5980,8 +6068,9 @@ void RecursivePortalRendering(portal_t *rootportal, const float fpov, player_t * } //drawcount = 0; validcount++; + if (cv_grbatching.value) - HWD.pfnStartBatching(); + HWR_StartBatching(); ps_numbspcalls.value.i = 0; ps_numpolyobjects.value.i = 0; @@ -5990,29 +6079,31 @@ void RecursivePortalRendering(portal_t *rootportal, const float fpov, player_t * if (!rootportal && portallist.base && !skybox)// if portals have been drawn in the main view, then render skywalls differently gr_collect_skywalls = true; + // HAYA: Save the old portal state, and turn portals off while normally rendering the BSP tree. + // This fixes specific effects not working, such as horizon lines. + int oldgl_portal_state = gr_portal; + + if (gr_portal != GRPORTAL_OFF) // if we already haven't hit the recursion limit or we already ended our portal shenanigans + gr_portal = GRPORTAL_INSIDE; // TURN IT OFF // Recursively "render" the BSP tree. HWR_RenderBSPNode((INT32)numnodes-1); + // woo we back + gr_portal = oldgl_portal_state; PS_STOP_TIMING(ps_bsptime); - + if (cv_grbatching.value) - { - HWD.pfnRenderBatches(&ps_hw_batchsorttime.value.p, &ps_hw_batchdrawtime.value.p, - &ps_hw_numpolys.value.i, &ps_hw_numverts.value.i, &ps_hw_numcalls.value.i, - &ps_hw_numshaders.value.i, &ps_hw_numtextures.value.i, &ps_hw_numpolyflags.value.i, - &ps_hw_numcolors.value.i); - } + HWR_RenderBatches(); + if (skyWallVertexArraySize)// if there are skywalls to draw using the alternate method { - HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, HWD_PORTAL_SKY_STENCIL_SEGS); + HWR_SetStencilState(HWR_STENCIL_SKY, -1); HWR_DrawSkyWallList(); HWR_SkyWallList_Clear(); - HWD.pfnSetSpecialState(HWD_SET_STENCIL_LEVEL, 1); - HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, HWD_PORTAL_NORMAL); + HWR_SetStencilState(HWR_STENCIL_NORMAL, 1); drewsky = false; HWR_DrawSkyBackground(fpov); - HWD.pfnSetSpecialState(HWD_SET_STENCIL_LEVEL, 0); - HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, HWD_PORTAL_NORMAL); + HWR_SetStencilState(HWR_STENCIL_NORMAL, 0); HWD.pfnClearBuffer(false, false, true, 0);// clear skywall markings from the stencil buffer HWR_SetTransform(fpov, player);// restore transform } @@ -6032,12 +6123,12 @@ void RecursivePortalRendering(portal_t *rootportal, const float fpov, player_t * HWR_RenderDrawNodes(); } // free memory from portal list allocated by calls to Add2Lines - portal_temp = portallist.base; - while (portal_temp) + gl_portal_temp = portallist.base; + while (gl_portal_temp) { - portal_t *nextportal = portal_temp->next; - Z_Free(portal_temp); - portal_temp = nextportal; + gl_portal_t *nextportal = gl_portal_temp->next; + Z_Free(gl_portal_temp); + gl_portal_temp = nextportal; } // TODO: batching at some point @@ -6050,7 +6141,6 @@ void RecursivePortalRendering(portal_t *rootportal, const float fpov, player_t * // ========================================================================== void HWR_RenderFrame(INT32 viewnumber, player_t *player, boolean skybox) { - angle_t a1; const float fpov = FIXED_TO_FLOAT(cv_fov.value+player->fovadd); postimg_t *postprocessor = &postimgtype[0]; INT32 i; @@ -6075,6 +6165,20 @@ void HWR_RenderFrame(INT32 viewnumber, player_t *player, boolean skybox) gr_windowcenterx += gr_viewwidth; } + if (splitscreen == 2 && player == &players[displayplayers[2]]) + { + // V_DrawPatchFill, but for the fourth screen only + GLPatch_t *gpatch = W_CachePatchName("SRB2BACK", PU_CACHE); + INT32 dupz = (vid.dupx < vid.dupy ? vid.dupx : vid.dupy); + INT32 x, y, pw = SHORT(gpatch->width) * dupz, ph = SHORT(gpatch->height) * dupz; + + for (x = vid.width>>1; x < vid.width; x += pw) + { + for (y = vid.height>>1; y < vid.height; y += ph) + HWR_DrawStretchyFixedPatch(gpatch, (x)<pass; // Recursiveness depth. - - // Apply the viewpoint stored for the portal. - HWR_PortalFrame(portal); - HWR_ClearClipper(); - HWR_ClearSprites(); - HWR_SetTransform(fpov, player); - validcount++; - - // Render the BSP from the new viewpoint. - portalcullsector = gr_portalcullsectors[portalnum]; - HWR_RenderBSPNode((INT32)numnodes - 1); - - HWR_SortVisSprites(); - HWR_DrawSprites(); - HWR_RenderDrawNodes(); -} - // ========================================================================== // Render the player view. // ========================================================================== @@ -6247,8 +6330,48 @@ void HWR_RenderPlayerView(INT32 viewnumber, player_t *player) HWR_RenderFrame(viewnumber, player, false); } +// enable or disable palette rendering state depending on settings and availability +// called when relevant settings change +// shader recompilation is done in the cvar callback +void HWR_TogglePaletteRendering(void) +{ + // which state should we go to? + if (HWR_ShouldUsePaletteRendering()) + { + // are we not in that state already? + if (!gr_palette_rendering_state) + { + gr_palette_rendering_state = true; + // The textures will still be converted to RGBA by r_opengl. + // This however makes hw_cache use paletted blending for composite textures! + // (patchformat is not touched) + textureformat = GR_TEXFMT_P_8; + HWR_SetMapPalette(); + HWR_SetPalette(pLocalPalette); + + // If the r_opengl "texture palette" stays the same during this switch, these textures + // will not be cleared out. However they are still out of date since the + // composite texture blending method has changed. Therefore they need to be cleared. + HWD.pfnClearMipMapCache(); + } + } + else + { + // are we not in that state already? + if (gr_palette_rendering_state) + { + gr_palette_rendering_state = false; + textureformat = GR_RGBA; + HWR_SetPalette(pLocalPalette); + // If the r_opengl "texture palette" stays the same during this switch, these textures + // will not be cleared out. However they are still out of date since the + // composite texture blending method has changed. Therefore they need to be cleared. + HWD.pfnClearMipMapCache(); + } + } +} //added by Hurdler: console varibale that are saved void HWR_AddCommands(void) @@ -6258,16 +6381,20 @@ void HWR_AddCommands(void) CV_RegisterVar(&cv_granisotropicmode); CV_RegisterVar(&cv_grcorrecttricks); CV_RegisterVar(&cv_grsolvetjoin); - - CV_RegisterVar(&cv_grbatching); - CV_RegisterVar(&cv_grscreentextures); - CV_RegisterVar(&cv_grrenderdistance); - CV_RegisterVar(&cv_grgammablue); - CV_RegisterVar(&cv_grgammagreen); - CV_RegisterVar(&cv_grgammared); + CV_RegisterVar(&cv_grbatching); + CV_RegisterVar(&cv_grfofcut); + CV_RegisterVar(&cv_fofzfightfix); + CV_RegisterVar(&cv_splitwallfix); + CV_RegisterVar(&cv_slopepegfix); + + CV_RegisterVar(&cv_grscreentextures); + + CV_RegisterVar(&cv_grrenderdistance); + CV_RegisterVar(&cv_grfakecontrast); CV_RegisterVar(&cv_grslopecontrast); + CV_RegisterVar(&cv_grhorizonlines); CV_RegisterVar(&cv_grfovchange); @@ -6279,7 +6406,6 @@ void HWR_AddCommands(void) CV_RegisterVar(&cv_grshearing); CV_RegisterVar(&cv_grshaders); - CV_RegisterVar(&cv_grusecustomshaders); CV_RegisterVar(&cv_grportals); CV_RegisterVar(&cv_nostencil); @@ -6288,8 +6414,9 @@ void HWR_AddCommands(void) CV_RegisterVar(&cv_secbright); - CV_RegisterVar(&cv_grpaletteshader); - CV_RegisterVar(&cv_grflashpal); + CV_RegisterVar(&cv_grpaletterendering); + CV_RegisterVar(&cv_grpalettedepth); + CV_RegisterVar(&cv_grflashpal); } // -------------------------------------------------------------------------- @@ -6303,27 +6430,26 @@ void HWR_Startup(void) if (!startupdone) { CONS_Printf("HWR_Startup()...\n"); - HWR_InitTextureCache(); - HWR_InitMD2(); - } - - if (rendermode == render_opengl) textureformat = patchformat = GR_RGBA; - startupdone = true; + HWR_InitTextureCache(); + HWR_InitMD2(); - // jimita - HWD.pfnKillShaders(); - if (!HWD.pfnLoadShaders()) - gr_shadersavailable = false; + gr_shadersavailable = HWR_InitShaders(); + HWR_SetShaderState(); + HWR_LoadAllCustomShaders(); - if (msaa) - { - if (a2c) - HWD.pfnSetSpecialState(HWD_SET_MSAA, 2); - else - HWD.pfnSetSpecialState(HWD_SET_MSAA, 1); + HWR_TogglePaletteRendering(); + + if (msaa) + { + if (a2c) + HWD.pfnSetSpecialState(HWD_SET_MSAA, 2); + else + HWD.pfnSetSpecialState(HWD_SET_MSAA, 1); + } } + startupdone = true; } // -------------------------------------------------------------------------- @@ -6341,6 +6467,8 @@ void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, { FBITFIELD blendmode = blend; UINT8 alpha = pSurf->PolyColor.s.alpha; // retain the alpha + + INT32 shader = SHADER_NONE; // Lighting is done here instead so that fog isn't drawn incorrectly on transparent walls after sorting HWR_Lighting(pSurf, lightlevel, wallcolormap); @@ -6350,17 +6478,21 @@ void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, if (blend & PF_Environment) blendmode |= PF_Occlude; // PF_Occlude must be used for solid objects - if (fogwall) + if (HWR_UseShader()) { - blendmode |= PF_Fog; - HWD.pfnSetShader(6); // fog shader + if (fogwall) + shader = SHADER_FOG; + else + shader = SHADER_WALL; + + blendmode |= PF_ColorMapped; } - + + if (fogwall) + blendmode |= PF_Fog; + blendmode |= PF_Modulated; // No PF_Occlude means overlapping (incorrect) transparency - - if (!fogwall) - HWD.pfnSetShader(gr_use_palette_shader ? 10 : 2); // wall shader - HWD.pfnDrawPolygon(pSurf, wallVerts, 4, blendmode, false); + HWR_ProcessPolygon(pSurf, wallVerts, 4, blendmode, shader, false); #ifdef WALLSPLATS if (gr_curline->linedef->splats && cv_splats.value) @@ -6391,7 +6523,7 @@ void HWR_DoPostProcessor(player_t *player) // Armageddon Blast Flash! // Could this even be considered postprocessor? - if ((player->flashcount && !cv_grpaletteshader.value) || (player->flashcount && cv_grpaletteshader.value && !cv_grflashpal.value)) + if ((player->flashcount) && (!HWR_PalRenderFlashpal())) { FOutVector v[4]; FSurfaceInfo Surf; @@ -6411,7 +6543,7 @@ void HWR_DoPostProcessor(player_t *player) Surf.PolyColor.s.alpha = 0xc0; // match software mode - HWD.pfnDrawPolygon(&Surf, v, 4, PF_Modulated|PF_Translucent|PF_NoTexture|PF_NoDepthTest, false); + HWD.pfnDrawPolygon(&Surf, v, 4, PF_Modulated|PF_Translucent|PF_NoTexture|PF_NoDepthTest); } if (!cv_grscreentextures.value) // screen textures are needed for the rest of the effects @@ -6419,7 +6551,7 @@ void HWR_DoPostProcessor(player_t *player) // Capture the screen for intermission and screen waving if(gamestate != GS_INTERMISSION) - HWD.pfnMakeScreenTexture(); + HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); if (splitscreen) // Not supported in splitscreen - someone want to add support? return; @@ -6463,24 +6595,24 @@ void HWR_DoPostProcessor(player_t *player) // Capture the screen again for screen waving on the intermission if(gamestate != GS_INTERMISSION) - HWD.pfnMakeScreenTexture(); + HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); } // Flipping of the screen isn't done here anymore } void HWR_StartScreenWipe(void) { - HWD.pfnStartScreenWipe(); + HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_WIPE_START); } void HWR_EndScreenWipe(void) { - HWD.pfnEndScreenWipe(); + HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_WIPE_END); } void HWR_DrawIntermissionBG(void) { - HWD.pfnDrawIntermissionBG(); + HWD.pfnDrawScreenTexture(HWD_SCREENTEXTURE_GENERIC1, NULL, 0); } void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum) @@ -6508,176 +6640,21 @@ void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum) } HWR_GetFadeMask(lumpnum); - HWD.pfnDoScreenWipe(); + HWD.pfnDoScreenWipe(HWD_SCREENTEXTURE_WIPE_START, HWD_SCREENTEXTURE_WIPE_END); +} + +void HWR_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize) +{ + HWD.pfnRenderVhsEffect(upbary, downbary, updistort, downdistort, barsize); } void HWR_MakeScreenFinalTexture(void) { - HWD.pfnMakeScreenFinalTexture(); + HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_GENERIC2); } void HWR_DrawScreenFinalTexture(int width, int height) { - if (gr_use_palette_shader) - HWD.pfnSetShader(11); //post processing - HWD.pfnDrawScreenFinalTexture(width, height); + HWD.pfnDrawScreenFinalTexture(HWD_SCREENTEXTURE_GENERIC2, width, height); } - -// jimita 18032019 -typedef struct -{ - char type[16]; - INT32 id; -} shaderxlat_t; - -static inline UINT16 HWR_CheckShader(UINT16 wadnum) -{ - UINT16 i; - lumpinfo_t *lump_p; - - lump_p = wadfiles[wadnum]->lumpinfo; - for (i = 0; i < wadfiles[wadnum]->numlumps; i++, lump_p++) - if (memcmp(lump_p->name, "SHADERS", 7) == 0) - return i; - - return INT16_MAX; -} - -void HWR_LoadShaders(UINT16 wadnum, boolean PK3) -{ - UINT16 lump; - char *shaderdef, *line; - char *stoken; - char *value; - size_t size; - int linenum = 1; - int shadertype = 0; - int i; - - #define SHADER_TYPES 7 - shaderxlat_t shaderxlat[SHADER_TYPES] = - { - {"Flat", 1}, - {"WallTexture", 2}, - {"Sprite", 3}, - {"Model", 4}, - {"WaterRipple", 5}, - {"Fog", 6}, - {"Sky", 7}, - }; - - lump = HWR_CheckShader(wadnum); - if (lump == INT16_MAX) - return; - - shaderdef = W_CacheLumpNumPwad(wadnum, lump, PU_CACHE); - size = W_LumpLengthPwad(wadnum, lump); - - line = Z_Malloc(size+1, PU_STATIC, NULL); - if (!line) - I_Error("HWR_LoadShaders: No more free memory\n"); - - M_Memcpy(line, shaderdef, size); - line[size] = '\0'; - - stoken = strtok(line, "\r\n "); - while (stoken) - { - if ((stoken[0] == '/' && stoken[1] == '/') - || (stoken[0] == '#'))// skip comments - { - stoken = strtok(NULL, "\r\n"); - goto skip_field; - } - - if (!stricmp(stoken, "GLSL")) - { - value = strtok(NULL, "\r\n "); - if (!value) - { - CONS_Alert(CONS_WARNING, "HWR_LoadShaders: Missing shader type (file %s, line %d)\n", wadfiles[wadnum]->filename, linenum); - stoken = strtok(NULL, "\r\n"); // skip end of line - goto skip_lump; - } - - if (!stricmp(value, "VERTEX")) - shadertype = 1; - else if (!stricmp(value, "FRAGMENT")) - shadertype = 2; - -skip_lump: - stoken = strtok(NULL, "\r\n "); - linenum++; - } - else - { - value = strtok(NULL, "\r\n= "); - if (!value) - { - CONS_Alert(CONS_WARNING, "HWR_LoadShaders: Missing shader target (file %s, line %d)\n", wadfiles[wadnum]->filename, linenum); - stoken = strtok(NULL, "\r\n"); // skip end of line - goto skip_field; - } - - if (!shadertype) - { - CONS_Alert(CONS_ERROR, "HWR_LoadShaders: Missing shader type (file %s, line %d)\n", wadfiles[wadnum]->filename, linenum); - Z_Free(line); - return; - } - - for (i = 0; i < SHADER_TYPES; i++) - { - if (!stricmp(shaderxlat[i].type, stoken)) - { - size_t shader_size; - char *shader_source; - char *shader_lumpname; - UINT16 shader_lumpnum; - - if (PK3) - { - shader_lumpname = Z_Malloc(strlen(value) + 12, PU_STATIC, NULL); - strcpy(shader_lumpname, "Shaders/sh_"); - strcat(shader_lumpname, value); - shader_lumpnum = W_CheckNumForFullNamePK3(shader_lumpname, wadnum, 0); - } - else - { - shader_lumpname = Z_Malloc(strlen(value) + 4, PU_STATIC, NULL); - strcpy(shader_lumpname, "SH_"); - strcat(shader_lumpname, value); - shader_lumpnum = W_CheckNumForNamePwad(shader_lumpname, wadnum, 0); - } - - if (shader_lumpnum == INT16_MAX) - { - CONS_Alert(CONS_ERROR, "HWR_LoadShaders: Missing shader source %s (file %s, line %d)\n", shader_lumpname, wadfiles[wadnum]->filename, linenum); - Z_Free(shader_lumpname); - continue; - } - - shader_size = W_LumpLengthPwad(wadnum, shader_lumpnum); - shader_source = Z_Malloc(shader_size, PU_STATIC, NULL); - W_ReadLumpPwad(wadnum, shader_lumpnum, shader_source); - - HWD.pfnLoadCustomShader(shaderxlat[i].id, shader_source, shader_size, (shadertype == 2)); - - Z_Free(shader_source); - Z_Free(shader_lumpname); - } - } - -skip_field: - stoken = strtok(NULL, "\r\n= "); - linenum++; - } - } - - HWD.pfnInitCustomShaders(); - - Z_Free(line); - return; -} - #endif // HWRENDER diff --git a/src/hardware/hw_main.h b/src/hardware/hw_main.h index b5761e202..0d63732e3 100644 --- a/src/hardware/hw_main.h +++ b/src/hardware/hw_main.h @@ -64,6 +64,8 @@ extern ps_metric_t ps_hw_numcolors; extern ps_metric_t ps_hw_batchsorttime; extern ps_metric_t ps_hw_batchdrawtime; +extern boolean gr_shadersavailable; + // hw_draw.c void HWR_DrawPatch(GLPatch_t *gpatch, INT32 x, INT32 y, INT32 option); void HWR_DrawStretchyFixedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, fixed_t vscale, INT32 option, const UINT8 *colormap); @@ -83,12 +85,16 @@ boolean HWR_Screenshot(const char *lbmname); // hw_main.c void HWR_RenderFrame(INT32 viewnumber, player_t *player, boolean skybox); void HWR_RenderPlayerView(INT32 viewnumber, player_t *player); -void HWR_LoadShaders(UINT16 wadnum, boolean PK3); void HWR_SetViewSize(void); void HWR_AddCommands(void); void HWR_SetTransform(float fpov, player_t *player); void HWR_ClearClipper(void); +boolean HWR_UseShader(void); +boolean HWR_ShouldUsePaletteRendering(void); +boolean HWR_PalRenderFlashpal(void); +void HWR_TogglePaletteRendering(void); + // My original intention was to split hw_main.c // into files like hw_bsp.c, hw_sprites.c... @@ -107,11 +113,12 @@ void HWR_StartScreenWipe(void); void HWR_EndScreenWipe(void); void HWR_DrawIntermissionBG(void); void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum); +void HWR_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize); void HWR_MakeScreenFinalTexture(void); void HWR_DrawScreenFinalTexture(int width, int height); // hw_main.c: Planes -void HWR_RenderPlane(extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, FBITFIELD PolyFlags, INT32 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap, subsector_t *subsector); +void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, FBITFIELD PolyFlags, INT32 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap); void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, boolean fogplane, extracolormap_t *planecolormap); #ifdef POLYOBJECTS @@ -127,7 +134,7 @@ void HWR_ProcessSeg(void); // Sort of like GLWall::Process in GZDoom void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap); void HWR_ProjectWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blendmode, INT32 lightlevel, extracolormap_t *wallcolormap); void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo * pSurf, INT32 texnum, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap); -void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, FSurfaceInfo* Surf, INT32 cutflag, ffloor_t *pfloor, FBITFIELD polyflags); +// moved HWR_SplitWall to hw_main.c void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf); void HWR_DrawSkyBackground(float fpov); @@ -142,8 +149,6 @@ void HWR_AddLine(seg_t *line); boolean HWR_CheckBBox(fixed_t *bspcoord); void HWR_RenderDrawNodes(void); -void HWR_ClearLightTableCache(void); - // hw_main.c: Sprites void HWR_AddSprites(sector_t *sec); void HWR_ProjectSprite(mobj_t *thing); @@ -156,20 +161,24 @@ extern boolean gr_maphasportals; // hw_cache.c void HWR_PrepLevelCache(size_t pnumtextures); +RGBA_t *HWR_GetTexturePalette(void); // hw_trick.c void HWR_CorrectSWTricks(void); +void HWR_SetShaderState(void); + // Console variables extern consvar_t cv_grshaders; +extern consvar_t cv_grfofcut; +extern consvar_t cv_fofzfightfix; +extern consvar_t cv_splitwallfix; +extern consvar_t cv_slopepegfix; extern consvar_t cv_grshearing; extern consvar_t cv_grfov; extern consvar_t cv_grmdls; extern consvar_t cv_grfog; extern consvar_t cv_grfogdensity; -extern consvar_t cv_grgammared; -extern consvar_t cv_grgammagreen; -extern consvar_t cv_grgammablue; extern consvar_t cv_grfiltermode; extern consvar_t cv_granisotropicmode; extern consvar_t cv_grcorrecttricks; @@ -178,12 +187,14 @@ extern consvar_t cv_grsolvetjoin; extern consvar_t cv_grspritebillboarding; extern consvar_t cv_grfakecontrast; extern consvar_t cv_grslopecontrast; +extern consvar_t cv_grhorizonlines; extern consvar_t cv_grfallbackplayermodel; extern consvar_t cv_grbatching; extern consvar_t cv_grrenderdistance; -extern consvar_t cv_grusecustomshaders; -extern consvar_t cv_grpaletteshader; +extern consvar_t cv_grpaletterendering; +extern consvar_t cv_grpalettedepth; extern consvar_t cv_grflashpal; +extern consvar_t cv_grscreentextures; extern consvar_t cv_grportals; extern consvar_t cv_nostencil; extern consvar_t cv_secbright; diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index 140c42c1f..c64d77639 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -1149,6 +1149,7 @@ void HWR_DrawMD2(gr_vissprite_t *spr) INT32 tics = spr->mobj->tics; //mdlframe_t *next = NULL; const UINT8 flip = (UINT8)((spr->mobj->eflags & MFE_VERTICALFLIP) == MFE_VERTICALFLIP); + const UINT8 hflip = (UINT8)(!(spr->mobj->mirrored) != !(spr->mobj->frame & FF_HORIZONTALFLIP)); spritedef_t *sprdef; spriteframe_t *sprframe; spriteinfo_t *sprinfo; @@ -1366,17 +1367,16 @@ void HWR_DrawMD2(gr_vissprite_t *spr) angle_t sliptideroll = 0; if (spr->mobj->player) - sliptideroll = ((cv_sloperoll.value) ? spr->mobj->player->sliproll : 0); + sliptideroll = ((cv_sloperoll.value && cv_sliptideroll.value) ? spr->mobj->player->sliproll : 0); - if ((spr->mobj->rollangle)||sliptideroll) + if ((spr->mobj->rollangle)||(sliptideroll && cv_sliptideroll.value)) { angle_t rollang = 0; rollfactor = ((spr->mobj->rollmodel == true) ? 1 : 0); - if (spr->mobj->player) - rollang = (spr->mobj->rollangle*rollfactor) + (sliptideroll*spr->mobj->player->sliptidemem); - else - rollang = (spr->mobj->rollangle*rollfactor); + rollang = (spr->mobj->player && sliptideroll && cv_sliptideroll.value) + ? (spr->mobj->rollangle * rollfactor) + (sliptideroll * spr->mobj->player->sliptidemem) + : (spr->mobj->rollangle * rollfactor); fixed_t anglef = AngleFixed(rollang); p.rollangle = FIXED_TO_FLOAT(anglef); @@ -1401,18 +1401,55 @@ void HWR_DrawMD2(gr_vissprite_t *spr) p.anglex = 0.0f; + p.anglex2 = 0.0f; #ifdef USE_FTRANSFORM_ANGLEZ // Slope rotation from Kart p.anglez = 0.0f; + p.anglez2 = 0.0f; + + // use secondary angles for the slope rotation if (spr->mobj->standingslope) { fixed_t tempz = spr->mobj->standingslope->normal.z; fixed_t tempy = spr->mobj->standingslope->normal.y; fixed_t tempx = spr->mobj->standingslope->normal.x; fixed_t tempangle = AngleFixed(R_PointToAngle2(0, 0, FixedSqrt(FixedMul(tempy, tempy) + FixedMul(tempz, tempz)), tempx)); - p.anglez = FIXED_TO_FLOAT(tempangle); + p.anglez2 = FIXED_TO_FLOAT(tempangle); tempangle = -AngleFixed(R_PointToAngle2(0, 0, tempz, tempy)); - p.anglex = FIXED_TO_FLOAT(tempangle); + p.anglex2 = FIXED_TO_FLOAT(tempangle); + } + else if ((spr->mobj->sloperoll || spr->mobj->slopepitch) && (!P_IsObjectOnGround(spr->mobj)) && (!paused)) + { + SINT8 flipfactor = flip ? -1 : 1; + + angle_t camang = R_PointToAngle(interp.x, interp.y); + angle_t mobjang; + + if (spr->mobj->flags & (MF_NOTHINK|MF_SCENERY)) + mobjang = spr->mobj->angle; + else + mobjang = interp.angle; + + angle_t fmoang; + fmoang = camang - mobjang; + + // slopepitch + p.anglex += flipfactor*FIXED_TO_FLOAT( AngleFixed(FixedMul(FINESINE((camang-fmoang) >> ANGLETOFINESHIFT), interp.slopepitch)) ); + p.anglez -= flipfactor*FIXED_TO_FLOAT( AngleFixed(FixedMul(FINECOSINE((camang-fmoang) >> ANGLETOFINESHIFT), interp.slopepitch)) ); + + // sloperoll + p.anglex += flipfactor*FIXED_TO_FLOAT( AngleFixed(FixedMul(FINECOSINE((camang-fmoang) >> ANGLETOFINESHIFT), interp.sloperoll)) ); + p.anglez += flipfactor*FIXED_TO_FLOAT( AngleFixed(FixedMul(FINESINE((camang-fmoang) >> ANGLETOFINESHIFT), interp.sloperoll)) ); + p.roll = true; + } + + // pitch and roll + if (interp.roll || interp.pitch) + { + SINT8 flipfactor = flip ? -1 : 1; + p.anglex += flipfactor*FIXED_TO_FLOAT(AngleFixed(interp.roll)); + p.anglez -= flipfactor*FIXED_TO_FLOAT(AngleFixed(interp.pitch)); + p.roll = true; } #endif @@ -1421,22 +1458,24 @@ void HWR_DrawMD2(gr_vissprite_t *spr) p.mirror = atransform.mirror; // from Kart #endif - HWD.pfnSetShader(4); // model shader + HWD.pfnSetShader(SHADER_MODEL); // model shader { - float this_scale = FIXED_TO_FLOAT(interp.scale); + SINT8 flipfactor = flip ? -1 : 1; + + float this_scale = FIXED_TO_FLOAT(interp.scale); float xs = this_scale * FIXED_TO_FLOAT(interp.spritexscale); float ys = this_scale * FIXED_TO_FLOAT(interp.spriteyscale); - float ox = xs * FIXED_TO_FLOAT(interp.spritexoffset); - float oy = ys * FIXED_TO_FLOAT(interp.spriteyoffset); + float ox = xs * flipfactor*FIXED_TO_FLOAT(interp.spritexoffset); + float oy = ys * flipfactor*FIXED_TO_FLOAT(interp.spriteyoffset); // offset perpendicular to the camera angle p.x -= ox * gr_viewsin; p.y += ox * gr_viewcos; p.z += oy; - HWD.pfnDrawModel(md2->model, frame, durs, tics, nextFrame, &p, md2->scale * xs, md2->scale * ys, flip, &Surf); + HWD.pfnDrawModel(md2->model, frame, durs, tics, nextFrame, &p, md2->scale * xs, md2->scale * ys, flip, hflip, &Surf); } } } diff --git a/src/hardware/hw_shaders.c b/src/hardware/hw_shaders.c new file mode 100644 index 000000000..f9c755b0d --- /dev/null +++ b/src/hardware/hw_shaders.c @@ -0,0 +1,630 @@ +// SONIC ROBO BLAST 2 +//----------------------------------------------------------------------------- +// Copyright (C) 2021 by Sonic Team Junior. +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- +/// \file hw_shaders.c +/// \brief Handles the shaders used by the game. + +#ifdef HWRENDER + +#include "hw_main.h" +#include "hw_glob.h" +#include "hw_drv.h" +#include "hw_shaders.h" +#include "../z_zone.h" + +// ================ +// Shader sources +// ================ + +static struct { + const char *vertex; + const char *fragment; +} const gl_shadersources[] = { + + // Floor shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_FLOOR_FRAGMENT_SHADER}, + + // Wall shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_WALL_FRAGMENT_SHADER}, + + // Sprite shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_WALL_FRAGMENT_SHADER}, + + // Model shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_WALL_FRAGMENT_SHADER}, + + // Water shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_WATER_FRAGMENT_SHADER}, + + // Fog shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_FOG_FRAGMENT_SHADER}, + + // Sky shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_SKY_FRAGMENT_SHADER}, + + // Palette postprocess shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_PALETTE_POSTPROCESS_FRAGMENT_SHADER}, + + // UI colormap fade shader + {GLSL_DEFAULT_VERTEX_SHADER, GLSL_UI_COLORMAP_FADE_FRAGMENT_SHADER}, + + {NULL, NULL}, +}; + +typedef struct +{ + int base_shader; // index of base shader_t + int custom_shader; // index of custom shader_t +} shadertarget_t; + +typedef struct +{ + char *vertex; + char *fragment; + boolean compiled; +} shader_t; // these are in an array and accessed by indices + +// the array has NUMSHADERTARGETS entries for base shaders and for custom shaders +// the array could be expanded in the future to fit "dynamic" custom shaders that +// aren't fixed to shader targets +static shader_t gl_shaders[NUMSHADERTARGETS*2]; + +static shadertarget_t gl_shadertargets[NUMSHADERTARGETS]; + +#define WHITESPACE_CHARS " \t" + +#define PALETTE_RENDERING_DEFINE "#define SRB2_PALETTE_RENDERING" + +// Initialize shader variables and the backend's shader system. Load the base shaders. +// Returns false if shaders cannot be used. +boolean HWR_InitShaders(void) +{ + int i; + + if (!HWD.pfnInitShaders()) + return false; + + for (i = 0; i < NUMSHADERTARGETS; i++) + { + // set up string pointers for base shaders + gl_shaders[i].vertex = Z_StrDup(gl_shadersources[i].vertex); + gl_shaders[i].fragment = Z_StrDup(gl_shadersources[i].fragment); + // set shader target indices to correct values + gl_shadertargets[i].base_shader = i; + gl_shadertargets[i].custom_shader = -1; + } + + HWR_CompileShaders(); + + return true; +} + +// helper function: strstr but returns an int with the substring position +// returns INT32_MAX if not found +static INT32 strstr_int(const char *str1, const char *str2) +{ + char *location = strstr(str1, str2); + if (location) + return location - str1; + else + return INT32_MAX; +} + +// Creates a preprocessed copy of the shader according to the current graphics settings +// Returns a pointer to the results on success and NULL on failure. +// Remember memory management of the returned string. +static char *HWR_PreprocessShader(char *original) +{ + const char *line_ending = "\n"; + int line_ending_len; + char *read_pos = original; + int original_len = strlen(original); + int distance_to_end = original_len; + int new_len; + char *new_shader; + char *write_pos; + char shader_glsl_version[3]; + int version_pos = -1; + int version_len = 0; + + if (strstr(original, "\r\n")) + { + line_ending = "\r\n"; + // check if all line endings are same + while ((read_pos = strchr(read_pos, '\n'))) + { + read_pos--; + if (*read_pos != '\r') + { + // this file contains mixed CRLF and LF line endings. + // treating it as a LF file during parsing should keep + // the results sane enough as long as the gpu driver is fine + // with these kinds of weirdly formatted shader sources. + line_ending = "\n"; + break; + } + read_pos += 2; + } + read_pos = original; + } + + line_ending_len = strlen(line_ending); + + // Find the #version directive, if it exists. Also don't get fooled if it's + // inside a comment. Copy the version digits so they can be used in the preamble. + // Time for some string parsing :D + +#define STARTSWITH(str, with_what) !strncmp(str, with_what, sizeof(with_what)-1) +#define ADVANCE(amount) read_pos += (amount); distance_to_end -= (amount); + while (true) + { + // we're at the start of a line or at the end of a block comment. + // first get any possible whitespace out of the way + int whitespace_len = strspn(read_pos, WHITESPACE_CHARS); + if (whitespace_len == distance_to_end) + break; // we got to the end + ADVANCE(whitespace_len) + + if (STARTSWITH(read_pos, "#version")) + { + // found a version directive (and it's not inside a comment) + // now locate, verify and read the version number + int version_number_len; + version_pos = read_pos - original; + ADVANCE(sizeof("#version") - 1) + whitespace_len = strspn(read_pos, WHITESPACE_CHARS); + if (!whitespace_len) + { + CONS_Alert(CONS_ERROR, "HWR_PreprocessShader: Syntax error in #version. Expected space after #version, but got other text.\n"); + return NULL; + } + else if (whitespace_len == distance_to_end) + { + CONS_Alert(CONS_ERROR, "HWR_PreprocessShader: Syntax error in #version. Expected version number, but got end of file.\n"); + return NULL; + } + ADVANCE(whitespace_len) + version_number_len = strspn(read_pos, "0123456789"); + if (!version_number_len) + { + CONS_Alert(CONS_ERROR, "HWR_PreprocessShader: Syntax error in #version. Expected version number, but got other text.\n"); + return NULL; + } + else if (version_number_len != 3) + { + CONS_Alert(CONS_ERROR, "HWR_PreprocessShader: Syntax error in #version. Expected version with 3 digits, but got %d digits.\n", version_number_len); + return NULL; + } + M_Memcpy(shader_glsl_version, read_pos, 3); + ADVANCE(version_number_len) + version_len = (read_pos - original) - version_pos; + whitespace_len = strspn(read_pos, WHITESPACE_CHARS); + ADVANCE(whitespace_len) + if (STARTSWITH(read_pos, "es")) + { + CONS_Alert(CONS_ERROR, "HWR_PreprocessShader: Support for ES shaders is not implemented.\n"); + return NULL; + } + break; + } + else + { + // go to next newline or end of next block comment if it starts before the newline + // and is not inside a line comment + INT32 newline_pos = strstr_int(read_pos, line_ending); + INT32 line_comment_pos; + INT32 block_comment_pos; + // optimization: temporarily put a null at the line ending, so strstr does not needlessly + // look past it since we're only interested in the current line + if (newline_pos != INT32_MAX) + read_pos[newline_pos] = '\0'; + line_comment_pos = strstr_int(read_pos, "//"); + block_comment_pos = strstr_int(read_pos, "/*"); + // restore the line ending, remove the null we just put there + if (newline_pos != INT32_MAX) + read_pos[newline_pos] = line_ending[0]; + if (line_comment_pos < block_comment_pos) + { + // line comment found, skip rest of the line + if (newline_pos != INT32_MAX) + { + ADVANCE(newline_pos + line_ending_len) + } + else + { + // we got to the end + break; + } + } + else if (block_comment_pos < line_comment_pos) + { + // block comment found, skip past it + INT32 block_comment_end; + ADVANCE(block_comment_pos + 2) + block_comment_end = strstr_int(read_pos, "*/"); + if (block_comment_end == INT32_MAX) + { + // could also leave insertion_pos at 0 and let the GLSL compiler + // output an error message for this broken comment + CONS_Alert(CONS_ERROR, "HWR_PreprocessShader: Encountered unclosed block comment in shader.\n"); + return NULL; + } + ADVANCE(block_comment_end + 2) + } + else if (newline_pos == INT32_MAX) + { + // we got to the end + break; + } + else + { + // nothing special on this line, move to the next one + ADVANCE(newline_pos + line_ending_len) + } + } + } +#undef STARTSWITH +#undef ADVANCE + +#define ADD_TO_LEN(def) new_len += sizeof(def) - 1 + line_ending_len; + + // Calculate length of modified shader. + new_len = original_len; + + if (cv_grpaletterendering.value) + ADD_TO_LEN(PALETTE_RENDERING_DEFINE) + +#undef ADD_TO_LEN + +#define VERSION_PART "#version " + + if (new_len != original_len) + { + if (version_pos != -1) + new_len += sizeof(VERSION_PART) - 1 + 3 + line_ending_len; + new_len += sizeof("#line 0") - 1 + line_ending_len; + } + + // Allocate memory for modified shader. + new_shader = Z_Malloc(new_len + 1, PU_STATIC, NULL); + + read_pos = original; + write_pos = new_shader; + + if (new_len != original_len && version_pos != -1) + { + strcpy(write_pos, VERSION_PART); + write_pos += sizeof(VERSION_PART) - 1; + M_Memcpy(write_pos, shader_glsl_version, 3); + write_pos += 3; + strcpy(write_pos, line_ending); + write_pos += line_ending_len; + } + +#undef VERSION_PART + +#define WRITE_DEFINE(define) \ + { \ + strcpy(write_pos, define); \ + write_pos += sizeof(define) - 1; \ + strcpy(write_pos, line_ending); \ + write_pos += line_ending_len; \ + } + + // Write the defines. + if (cv_grpaletterendering.value) + WRITE_DEFINE(PALETTE_RENDERING_DEFINE) + +#undef WRITE_DEFINE + + // Write a #line directive, so compiler errors will report line numbers from the + // original shader without our preamble lines. + if (new_len != original_len) + { + // line numbering in the #line directive is different for versions 110-150 + if (version_pos == -1 || shader_glsl_version[0] == '1') + strcpy(write_pos, "#line 0"); + else + strcpy(write_pos, "#line 1"); + write_pos += sizeof("#line 0") - 1; + strcpy(write_pos, line_ending); + write_pos += line_ending_len; + } + + // Copy the original shader. + M_Memcpy(write_pos, read_pos, original_len); + + // Erase the original #version directive, if it exists and was copied. + if (new_len != original_len && version_pos != -1) + memset(write_pos + version_pos, ' ', version_len); + + // Terminate the new string. + new_shader[new_len] = '\0'; + + return new_shader; +} + +// preprocess and compile shader at gl_shaders[index] +static void HWR_CompileShader(int index) +{ + char *vertex_source = gl_shaders[index].vertex; + char *fragment_source = gl_shaders[index].fragment; + + if (vertex_source) + { + char *preprocessed = HWR_PreprocessShader(vertex_source); + if (!preprocessed) return; + HWD.pfnLoadShader(index, preprocessed, HWD_SHADERSTAGE_VERTEX); + } + if (fragment_source) + { + char *preprocessed = HWR_PreprocessShader(fragment_source); + if (!preprocessed) return; + HWD.pfnLoadShader(index, preprocessed, HWD_SHADERSTAGE_FRAGMENT); + } + + gl_shaders[index].compiled = HWD.pfnCompileShader(index); +} + +// compile or recompile shaders +void HWR_CompileShaders(void) +{ + int i; + + for (i = 0; i < NUMSHADERTARGETS; i++) + { + int custom_index = gl_shadertargets[i].custom_shader; + HWR_CompileShader(i); + if (!gl_shaders[i].compiled) + CONS_Alert(CONS_ERROR, "HWR_CompileShaders: Compilation failed for base %s shader!\n", shaderxlat[i].type); + if (custom_index != -1) + { + HWR_CompileShader(custom_index); + if (!gl_shaders[custom_index].compiled) + CONS_Alert(CONS_ERROR, "HWR_CompileShaders: Recompilation failed for the custom %s shader! See the console messages above for more information.\n", shaderxlat[i].type); + } + } +} + +int HWR_GetShaderFromTarget(int shader_target) +{ + int custom_shader = gl_shadertargets[shader_target].custom_shader; + // use custom shader if following are true + // - custom shader exists + // - custom shader has been compiled successfully + // - custom shaders are enabled + // - custom shaders are allowed by the server + if (custom_shader != -1 && gl_shaders[custom_shader].compiled && + cv_grshaders.value == 1) + return custom_shader; + else + return gl_shadertargets[shader_target].base_shader; +} + +static inline UINT16 HWR_FindShaderDefs(UINT16 wadnum) +{ + UINT16 i; + lumpinfo_t *lump_p; + + lump_p = wadfiles[wadnum]->lumpinfo; + for (i = 0; i < wadfiles[wadnum]->numlumps; i++, lump_p++) + if (memcmp(lump_p->name, "SHADERS", 7) == 0) + return i; + + return INT16_MAX; +} + +customshaderxlat_t shaderxlat[] = +{ + {"Flat", SHADER_FLOOR}, + {"WallTexture", SHADER_WALL}, + {"Sprite", SHADER_SPRITE}, + {"Model", SHADER_MODEL}, + {"WaterRipple", SHADER_WATER}, + {"Fog", SHADER_FOG}, + {"Sky", SHADER_SKY}, + {"PalettePostprocess", SHADER_PALETTE_POSTPROCESS}, + {"UIColormapFade", SHADER_UI_COLORMAP_FADE}, + {NULL, 0}, +}; + +void HWR_LoadAllCustomShaders(void) +{ + INT32 i; + + // read every custom shader + for (i = 0; i < numwadfiles; i++) + HWR_LoadCustomShadersFromFile(i, (wadfiles[i]->type == RET_PK3)); +} + +void HWR_LoadCustomShadersFromFile(UINT16 wadnum, boolean PK3) +{ + UINT16 lump; + char *shaderdef, *line; + char *stoken; + char *value; + size_t size; + int linenum = 1; + int shadertype = 0; + int i; + boolean modified_shaders[NUMSHADERTARGETS] = {0}; + + if (!HWR_UseShader()) + return; + + lump = HWR_FindShaderDefs(wadnum); + if (lump == INT16_MAX) + return; + + shaderdef = W_CacheLumpNumPwad(wadnum, lump, PU_CACHE); + size = W_LumpLengthPwad(wadnum, lump); + + line = Z_Malloc(size+1, PU_STATIC, NULL); + M_Memcpy(line, shaderdef, size); + line[size] = '\0'; + + stoken = strtok(line, "\r\n "); + while (stoken) + { + if ((stoken[0] == '/' && stoken[1] == '/') + || (stoken[0] == '#'))// skip comments + { + stoken = strtok(NULL, "\r\n"); + goto skip_field; + } + + if (!stricmp(stoken, "GLSL")) + { + value = strtok(NULL, "\r\n "); + if (!value) + { + CONS_Alert(CONS_WARNING, "HWR_LoadCustomShadersFromFile: Missing shader type (file %s, line %d)\n", wadfiles[wadnum]->filename, linenum); + stoken = strtok(NULL, "\r\n"); // skip end of line + goto skip_lump; + } + + if (!stricmp(value, "VERTEX")) + shadertype = 1; + else if (!stricmp(value, "FRAGMENT")) + shadertype = 2; + +skip_lump: + stoken = strtok(NULL, "\r\n "); + linenum++; + } + else + { + value = strtok(NULL, "\r\n= "); + if (!value) + { + CONS_Alert(CONS_WARNING, "HWR_LoadCustomShadersFromFile: Missing shader target (file %s, line %d)\n", wadfiles[wadnum]->filename, linenum); + stoken = strtok(NULL, "\r\n"); // skip end of line + goto skip_field; + } + + if (!shadertype) + { + CONS_Alert(CONS_ERROR, "HWR_LoadCustomShadersFromFile: Missing shader type (file %s, line %d)\n", wadfiles[wadnum]->filename, linenum); + Z_Free(line); + return; + } + + for (i = 0; shaderxlat[i].type; i++) + { + if (!stricmp(shaderxlat[i].type, stoken)) + { + size_t shader_string_length; + char *shader_source; + char *shader_lumpname; + UINT16 shader_lumpnum; + int shader_index; // index in gl_shaders + + if (PK3) + { + shader_lumpname = Z_Malloc(strlen(value) + 12, PU_STATIC, NULL); + strcpy(shader_lumpname, "Shaders/sh_"); + strcat(shader_lumpname, value); + shader_lumpnum = W_CheckNumForFullNamePK3(shader_lumpname, wadnum, 0); + } + else + { + shader_lumpname = Z_Malloc(strlen(value) + 4, PU_STATIC, NULL); + strcpy(shader_lumpname, "SH_"); + strcat(shader_lumpname, value); + shader_lumpnum = W_CheckNumForNamePwad(shader_lumpname, wadnum, 0); + } + + if (shader_lumpnum == INT16_MAX) + { + CONS_Alert(CONS_ERROR, "HWR_LoadCustomShadersFromFile: Missing shader source %s (file %s, line %d)\n", shader_lumpname, wadfiles[wadnum]->filename, linenum); + Z_Free(shader_lumpname); + continue; + } + + shader_string_length = W_LumpLengthPwad(wadnum, shader_lumpnum) + 1; + shader_source = Z_Malloc(shader_string_length, PU_STATIC, NULL); + W_ReadLumpPwad(wadnum, shader_lumpnum, shader_source); + shader_source[shader_string_length-1] = '\0'; + + shader_index = shaderxlat[i].id + NUMSHADERTARGETS; + if (!modified_shaders[shaderxlat[i].id]) + { + // this will clear any old custom shaders from previously loaded files + // Z_Free checks if the pointer is NULL! + Z_Free(gl_shaders[shader_index].vertex); + gl_shaders[shader_index].vertex = NULL; + Z_Free(gl_shaders[shader_index].fragment); + gl_shaders[shader_index].fragment = NULL; + } + modified_shaders[shaderxlat[i].id] = true; + + if (shadertype == 1) + { + if (gl_shaders[shader_index].vertex) + { + CONS_Alert(CONS_WARNING, "HWR_LoadCustomShadersFromFile: %s is overwriting another %s vertex shader from the same addon! (file %s, line %d)\n", shader_lumpname, shaderxlat[i].type, wadfiles[wadnum]->filename, linenum); + Z_Free(gl_shaders[shader_index].vertex); + } + gl_shaders[shader_index].vertex = shader_source; + } + else + { + if (gl_shaders[shader_index].fragment) + { + CONS_Alert(CONS_WARNING, "HWR_LoadCustomShadersFromFile: %s is overwriting another %s fragment shader from the same addon! (file %s, line %d)\n", shader_lumpname, shaderxlat[i].type, wadfiles[wadnum]->filename, linenum); + Z_Free(gl_shaders[shader_index].fragment); + } + gl_shaders[shader_index].fragment = shader_source; + } + + Z_Free(shader_lumpname); + } + } + +skip_field: + stoken = strtok(NULL, "\r\n= "); + linenum++; + } + } + + for (i = 0; i < NUMSHADERTARGETS; i++) + { + if (modified_shaders[i]) + { + int shader_index = i + NUMSHADERTARGETS; // index to gl_shaders + gl_shadertargets[i].custom_shader = shader_index; + // if only one stage (vertex/fragment) is defined, the other one + // is copied from the base shaders. + if (!gl_shaders[shader_index].fragment) + gl_shaders[shader_index].fragment = Z_StrDup(gl_shadersources[i].fragment); + if (!gl_shaders[shader_index].vertex) + gl_shaders[shader_index].vertex = Z_StrDup(gl_shadersources[i].vertex); + HWR_CompileShader(shader_index); + if (!gl_shaders[shader_index].compiled) + CONS_Alert(CONS_ERROR, "HWR_LoadCustomShadersFromFile: A compilation error occured for the %s shader in file %s. See the console messages above for more information.\n", shaderxlat[i].type, wadfiles[wadnum]->filename); + } + } + + Z_Free(line); + return; +} + +const char *HWR_GetShaderName(INT32 shader) +{ + INT32 i; + + for (i = 0; shaderxlat[i].type; i++) + { + if (shaderxlat[i].id == shader) + return shaderxlat[i].type; + } + + return "Unknown"; +} + +#endif // HWRENDER diff --git a/src/hardware/hw_shaders.h b/src/hardware/hw_shaders.h new file mode 100644 index 000000000..eb705c34c --- /dev/null +++ b/src/hardware/hw_shaders.h @@ -0,0 +1,298 @@ +// SONIC ROBO BLAST 2 +//----------------------------------------------------------------------------- +// Copyright (C) 2021 by Sonic Team Junior. +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- +/// \file hw_shaders.h +/// \brief Handles the shaders used by the game. + +#ifndef _HW_SHADERS_H_ +#define _HW_SHADERS_H_ + +#include "../doomtype.h" + +// ================ +// Vertex shaders +// ================ + +// +// Generic vertex shader +// + +#define GLSL_DEFAULT_VERTEX_SHADER \ + "void main()\n" \ + "{\n" \ + "gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;\n" \ + "gl_FrontColor = gl_Color;\n" \ + "gl_TexCoord[0].xy = gl_MultiTexCoord0.xy;\n" \ + "gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;\n" \ + "}\0" + +// ================== +// Fragment shaders +// ================== + +// +// Generic fragment shader +// + +#define GLSL_DEFAULT_FRAGMENT_SHADER \ + "uniform sampler2D tex;\n" \ + "uniform vec4 poly_color;\n" \ + "void main(void) {\n" \ + "gl_FragColor = texture2D(tex, gl_TexCoord[0].st) * poly_color;\n" \ + "}\0" + +// +// Software fragment shader +// + +// Include GLSL_FLOOR_FUDGES or GLSL_WALL_FUDGES or define the fudges in shaders that use this macro. +#define GLSL_DOOM_COLORMAP \ + "float R_DoomColormap(float light, float z)\n" \ + "{\n" \ + "float lightnum = clamp(light / 17.0, 0.0, 15.0);\n" \ + "float lightz = clamp(z / 16.0, 0.0, 127.0);\n" \ + "float startmap = (15.0 - lightnum) * 4.0;\n" \ + "float scale = 160.0 / (lightz + 1.0);\n" \ + "float cap = (155.0 - light) * 0.26;\n" \ + "return max(startmap * STARTMAP_FUDGE - scale * 0.5 * SCALE_FUDGE, cap);\n" \ + "}\n" +// lighting cap adjustment: +// first num (155.0), increase to make it start to go dark sooner +// second num (0.26), increase to make it go dark faster + +#define GLSL_DOOM_LIGHT_EQUATION \ + "float R_DoomLightingEquation(float light)\n" \ + "{\n" \ + "float z = gl_FragCoord.z / gl_FragCoord.w;\n" \ + "float colormap = floor(R_DoomColormap(light, z)) + 0.5;\n" \ + "return clamp(colormap, 0.0, 31.0) / 32.0;\n" \ + "}\n" + +#define GLSL_SOFTWARE_TINT_EQUATION \ + "if (tint_color.a > 0.0) {\n" \ + "float color_bright = sqrt((base_color.r * base_color.r) + (base_color.g * base_color.g) + (base_color.b * base_color.b));\n" \ + "float strength = sqrt(9.0 * tint_color.a);\n" \ + "final_color.r = clamp((color_bright * (tint_color.r * strength)) + (base_color.r * (1.0 - strength)), 0.0, 1.0);\n" \ + "final_color.g = clamp((color_bright * (tint_color.g * strength)) + (base_color.g * (1.0 - strength)), 0.0, 1.0);\n" \ + "final_color.b = clamp((color_bright * (tint_color.b * strength)) + (base_color.b * (1.0 - strength)), 0.0, 1.0);\n" \ + "}\n" + +#define GLSL_SOFTWARE_FADE_EQUATION \ + "float darkness = R_DoomLightingEquation(lighting);\n" \ + "if (fade_start != 0.0 || fade_end != 31.0) {\n" \ + "float fs = fade_start / 31.0;\n" \ + "float fe = fade_end / 31.0;\n" \ + "float fd = fe - fs;\n" \ + "darkness = clamp((darkness - fs) * (1.0 / fd), 0.0, 1.0);\n" \ + "}\n" \ + "final_color = mix(final_color, fade_color, darkness);\n" + +#define GLSL_PALETTE_RENDERING \ + "float tex_pal_idx = texture3D(palette_lookup_tex, vec3((texel * 63.0 + 0.5) / 64.0))[0] * 255.0;\n" \ + "float z = gl_FragCoord.z / gl_FragCoord.w;\n" \ + "float light_y = clamp(floor(R_DoomColormap(lighting, z)), 0.0, 31.0);\n" \ + "vec2 lighttable_coord = vec2((tex_pal_idx + 0.5) / 256.0, (light_y + 0.5) / 32.0);\n" \ + "vec4 final_color = texture2D(lighttable_tex, lighttable_coord);\n" \ + "final_color.a = texel.a * poly_color.a;\n" \ + "gl_FragColor = final_color;\n" \ + +#define GLSL_SOFTWARE_FRAGMENT_SHADER \ + "#ifdef SRB2_PALETTE_RENDERING\n" \ + "uniform sampler2D tex;\n" \ + "uniform sampler3D palette_lookup_tex;\n" \ + "uniform sampler2D lighttable_tex;\n" \ + "uniform vec4 poly_color;\n" \ + "uniform float lighting;\n" \ + GLSL_DOOM_COLORMAP \ + "void main(void) {\n" \ + "vec4 texel = texture2D(tex, gl_TexCoord[0].st);\n" \ + GLSL_PALETTE_RENDERING \ + "}\n" \ + "#else\n" \ + "uniform sampler2D tex;\n" \ + "uniform vec4 poly_color;\n" \ + "uniform vec4 tint_color;\n" \ + "uniform vec4 fade_color;\n" \ + "uniform float lighting;\n" \ + "uniform float fade_start;\n" \ + "uniform float fade_end;\n" \ + GLSL_DOOM_COLORMAP \ + GLSL_DOOM_LIGHT_EQUATION \ + "void main(void) {\n" \ + "vec4 texel = texture2D(tex, gl_TexCoord[0].st);\n" \ + "vec4 base_color = texel * poly_color;\n" \ + "vec4 final_color = base_color;\n" \ + GLSL_SOFTWARE_TINT_EQUATION \ + GLSL_SOFTWARE_FADE_EQUATION \ + "final_color.a = texel.a * poly_color.a;\n" \ + "gl_FragColor = final_color;\n" \ + "}\n" \ + "#endif\0" + +// hand tuned adjustments for light level calculation +#define GLSL_FLOOR_FUDGES \ + "#define STARTMAP_FUDGE 1.06\n" \ + "#define SCALE_FUDGE 1.15\n" + +#define GLSL_WALL_FUDGES \ + "#define STARTMAP_FUDGE 1.05\n" \ + "#define SCALE_FUDGE 2.2\n" + +#define GLSL_FLOOR_FRAGMENT_SHADER \ + GLSL_FLOOR_FUDGES \ + GLSL_SOFTWARE_FRAGMENT_SHADER + +#define GLSL_WALL_FRAGMENT_SHADER \ + GLSL_WALL_FUDGES \ + GLSL_SOFTWARE_FRAGMENT_SHADER + +// +// Water surface shader +// +// Mostly guesstimated, rather than the rest being built off Software science. +// Still needs to distort things underneath/around the water... +// + +#define GLSL_WATER_TEXEL \ + "float water_z = (gl_FragCoord.z / gl_FragCoord.w) / 2.0;\n" \ + "float a = -pi * (water_z * freq) + (leveltime * speed);\n" \ + "float sdistort = sin(a) * amp;\n" \ + "float cdistort = cos(a) * amp;\n" \ + "vec4 texel = texture2D(tex, vec2(gl_TexCoord[0].s - sdistort, gl_TexCoord[0].t - cdistort));\n" + +#define GLSL_WATER_FRAGMENT_SHADER \ + GLSL_FLOOR_FUDGES \ + "const float freq = 0.025;\n" \ + "const float amp = 0.025;\n" \ + "const float speed = 2.0;\n" \ + "const float pi = 3.14159;\n" \ + "#ifdef SRB2_PALETTE_RENDERING\n" \ + "uniform sampler2D tex;\n" \ + "uniform sampler3D palette_lookup_tex;\n" \ + "uniform sampler2D lighttable_tex;\n" \ + "uniform vec4 poly_color;\n" \ + "uniform float lighting;\n" \ + "uniform float leveltime;\n" \ + GLSL_DOOM_COLORMAP \ + "void main(void) {\n" \ + GLSL_WATER_TEXEL \ + GLSL_PALETTE_RENDERING \ + "}\n" \ + "#else\n" \ + "uniform sampler2D tex;\n" \ + "uniform vec4 poly_color;\n" \ + "uniform vec4 tint_color;\n" \ + "uniform vec4 fade_color;\n" \ + "uniform float lighting;\n" \ + "uniform float fade_start;\n" \ + "uniform float fade_end;\n" \ + "uniform float leveltime;\n" \ + GLSL_DOOM_COLORMAP \ + GLSL_DOOM_LIGHT_EQUATION \ + "void main(void) {\n" \ + GLSL_WATER_TEXEL \ + "vec4 base_color = texel * poly_color;\n" \ + "vec4 final_color = base_color;\n" \ + GLSL_SOFTWARE_TINT_EQUATION \ + GLSL_SOFTWARE_FADE_EQUATION \ + "final_color.a = texel.a * poly_color.a;\n" \ + "gl_FragColor = final_color;\n" \ + "}\n" \ + "#endif\0" + +// +// Fog block shader +// +// Alpha of the planes themselves are still slightly off -- see HWR_FogBlockAlpha +// + +// The floor fudges are used, but should the wall fudges be used instead? or something inbetween? +// or separate values for floors and walls? (need to change more than this shader for that) +#define GLSL_FOG_FRAGMENT_SHADER \ + GLSL_FLOOR_FUDGES \ + "uniform vec4 tint_color;\n" \ + "uniform vec4 fade_color;\n" \ + "uniform float lighting;\n" \ + "uniform float fade_start;\n" \ + "uniform float fade_end;\n" \ + GLSL_DOOM_COLORMAP \ + GLSL_DOOM_LIGHT_EQUATION \ + "void main(void) {\n" \ + "vec4 base_color = gl_Color;\n" \ + "vec4 final_color = base_color;\n" \ + GLSL_SOFTWARE_TINT_EQUATION \ + GLSL_SOFTWARE_FADE_EQUATION \ + "gl_FragColor = final_color;\n" \ + "}\0" + +// +// Sky fragment shader +// Modulates poly_color with gl_Color +// +#define GLSL_SKY_FRAGMENT_SHADER \ + "uniform sampler2D tex;\n" \ + "uniform vec4 poly_color;\n" \ + "void main(void) {\n" \ + "gl_FragColor = texture2D(tex, gl_TexCoord[0].st) * gl_Color * poly_color;\n" \ + "}\0" + +// Shader for the palette rendering postprocess step +#define GLSL_PALETTE_POSTPROCESS_FRAGMENT_SHADER \ + "uniform sampler2D tex;\n" \ + "uniform sampler3D palette_lookup_tex;\n" \ + "uniform sampler1D palette_tex;\n" \ + "void main(void) {\n" \ + "vec4 texel = texture2D(tex, gl_TexCoord[0].st);\n" \ + "float tex_pal_idx = texture3D(palette_lookup_tex, vec3((texel * 63.0 + 0.5) / 64.0))[0] * 255.0;\n" \ + "float palette_coord = (tex_pal_idx + 0.5) / 256.0;\n" \ + "vec4 final_color = texture1D(palette_tex, palette_coord);\n" \ + "gl_FragColor = final_color;\n" \ + "}\0" + +// Applies a palettized colormap fade to tex +#define GLSL_UI_COLORMAP_FADE_FRAGMENT_SHADER \ + "uniform sampler2D tex;\n" \ + "uniform float lighting;\n" \ + "uniform sampler3D palette_lookup_tex;\n" \ + "uniform sampler2D lighttable_tex;\n" \ + "void main(void) {\n" \ + "vec4 texel = texture2D(tex, gl_TexCoord[0].st);\n" \ + "float tex_pal_idx = texture3D(palette_lookup_tex, vec3((texel * 63.0 + 0.5) / 64.0))[0] * 255.0;\n" \ + "vec2 lighttable_coord = vec2((tex_pal_idx + 0.5) / 256.0, (lighting + 0.5) / 32.0);\n" \ + "gl_FragColor = texture2D(lighttable_tex, lighttable_coord);\n" \ + "}\0" \ + +// ================ +// Fallback shaders +// ================ + +// +// Generic vertex shader +// + +#define GLSL_FALLBACK_VERTEX_SHADER \ + "void main()\n" \ + "{\n" \ + "gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;\n" \ + "gl_FrontColor = gl_Color;\n" \ + "gl_TexCoord[0].xy = gl_MultiTexCoord0.xy;\n" \ + "gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;\n" \ + "}\0" + +// +// Generic fragment shader +// + +#define GLSL_FALLBACK_FRAGMENT_SHADER \ + "uniform sampler2D tex;\n" \ + "uniform vec4 poly_color;\n" \ + "void main(void) {\n" \ + "gl_FragColor = texture2D(tex, gl_TexCoord[0].st) * poly_color;\n" \ + "}\0" + +#endif diff --git a/src/hardware/r_opengl/ogl_win.c b/src/hardware/r_opengl/ogl_win.c index 562afe998..095f2e230 100644 --- a/src/hardware/r_opengl/ogl_win.c +++ b/src/hardware/r_opengl/ogl_win.c @@ -117,7 +117,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, // handle to DLL module #define pwglDeleteContext wglDeleteContext; #define pwglMakeCurrent wglMakeCurrent; #else -static HMODULE OGL32, GLU32; +static HMODULE OGL32; typedef void *(WINAPI *PFNwglGetProcAddress) (const char *); static PFNwglGetProcAddress pwglGetProcAddress; typedef HGLRC (WINAPI *PFNwglCreateContext) (HDC hdc); @@ -132,13 +132,6 @@ static PFNwglMakeCurrent pwglMakeCurrent; void *GetGLFunc(const char *proc) { void *func = NULL; - if (strncmp(proc, "glu", 3) == 0) - { - if (GLU32) - func = GetProcAddress(GLU32, proc); - else - return NULL; - } if (pwglGetProcAddress) func = pwglGetProcAddress(proc); if (!func) @@ -155,8 +148,6 @@ boolean LoadGL(void) if (!OGL32) return 0; - GLU32 = LoadLibrary("GLU32.DLL"); - pwglGetProcAddress = GetGLFunc("wglGetProcAddress"); pwglCreateContext = GetGLFunc("wglCreateContext"); pwglDeleteContext = GetGLFunc("wglDeleteContext"); @@ -528,7 +519,6 @@ EXPORT void HWRAPI(Shutdown) (void) ReleaseDC(hWnd, hDC); hDC = NULL; } - FreeLibrary(GLU32); FreeLibrary(OGL32); DBG_Printf ("HWRAPI Shutdown(DONE)\n"); } @@ -564,15 +554,15 @@ EXPORT void HWRAPI(FinishUpdate) (INT32 waitvbl) // : in OpenGL, we store values for conversion of paletted graphics when // : they are downloaded to the 3D card. // -----------------+ -EXPORT void HWRAPI(SetPalette) (RGBA_t *pal, RGBA_t *gamma) +EXPORT void HWRAPI(SetPalette) (RGBA_t *pal) { INT32 i; for (i = 0; i < 256; i++) { - myPaletteData[i].s.red = (UINT8)MIN((pal[i].s.red*gamma->s.red)/127, 255); - myPaletteData[i].s.green = (UINT8)MIN((pal[i].s.green*gamma->s.green)/127, 255); - myPaletteData[i].s.blue = (UINT8)MIN((pal[i].s.blue*gamma->s.blue)/127, 255); + myPaletteData[i].s.red = pal[i].s.red; + myPaletteData[i].s.green = pal[i].s.green; + myPaletteData[i].s.blue = pal[i].s.blue; myPaletteData[i].s.alpha = pal[i].s.alpha; } diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index c0592539d..59a119ee5 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -27,16 +27,9 @@ #include "r_opengl.h" #include "r_vbo.h" -#include "../../v_video.h" // pLocalPalette -#include "../../r_data.h" // NearestColor - -//#include "../../p_tick.h" // for leveltime (NOTE: THIS IS BAD, FIGURE OUT HOW TO PROPERLY IMPLEMENT gl_leveltime) -#include "../../i_system.h" // for I_GetPreciseTime (batching time measurements) - #include "../hw_main.h" -// Eeeeh not sure is this right way, but it works < sry :c -extern consvar_t cv_grusecustomshaders; +// Eeeeh not sure is this right way, but it works < sry :c < sry again it had to go :c extern fixed_t fovtan; // also extremely bad, I'm just too lazy!!! @@ -51,16 +44,22 @@ struct GLRGBAFloat }; typedef struct GLRGBAFloat GLRGBAFloat; -static const GLubyte white[4] = { 255, 255, 255, 255 }; +// lighttable list item +struct LTListItem +{ + UINT32 id; + struct LTListItem *next; +}; +typedef struct LTListItem LTListItem; // ========================================================================== // CONSTANTS // ========================================================================== - +static const GLubyte white[4] = { 255, 255, 255, 255 }; // With OpenGL 1.1+, the first texture should be 1 -#define NOTEXTURE_NUM 0 +static GLuint NOTEXTURE_NUM = 0; #define N_PI_DEMI (M_PIl/2.0f) //(1.5707963268f) @@ -74,24 +73,23 @@ static float NEAR_CLIPPING_PLANE = NZCLIP_PLANE; // GLOBALS // ************************************************************************** - static GLuint tex_downloaded = 0; +static GLuint lt_downloaded = 0; // currently bound lighttable texture static GLfloat fov = 90.0f; static FBITFIELD CurrentPolyFlags; static FTextureInfo *gr_cachetail = NULL; static FTextureInfo *gr_cachehead = NULL; -typedef struct LightTableCacheEntry_s -{ - GLuint id; - struct LightTableCacheEntry_s *next; -} LightTableCacheEntry_t; +// Linked list of all lighttables. +static LTListItem *LightTablesTail = NULL; +static LTListItem *LightTablesHead = NULL; -LightTableCacheEntry_t *ltcachehead = NULL; -LightTableCacheEntry_t *ltcachetail = NULL; +static RGBA_t screenPalette[256] = {0}; // the palette for the postprocessing step in palette rendering +static GLuint screenPaletteTex = 0; // 1D texture containing the screen palette +static GLuint paletteLookupTex = 0; // 3D texture containing RGB -> palette index lookup table +RGBA_t myPaletteData[256]; // the palette for converting textures to RGBA -RGBA_t myPaletteData[256]; GLint screen_width = 0; // used by Draw2DLine() GLint screen_height = 0; GLbyte screen_depth = 0; @@ -112,23 +110,12 @@ static GLfloat modelMatrix[16]; static GLfloat projMatrix[16]; static GLint viewport[4]; -#ifdef USE_PALETTED_TEXTURE - PFNGLCOLORTABLEEXTPROC glColorTableEXT = NULL; - GLubyte palette_tex[256*3]; -#endif // Sryder: NextTexAvail is broken for these because palette changes or changes to the texture filter or antialiasing // flush all of the stored textures, leaving them unavailable at times such as between levels // These need to start at 0 and be set to their number, and be reset to 0 when deleted so that Intel GPUs // can know when the textures aren't there, as textures are always considered resident in their virtual memory -static GLuint screentexture = 0; -static GLuint startScreenWipe = 0; -static GLuint endScreenWipe = 0; -static GLuint finalScreenTexture = 0; - -// Lactozilla: Set shader programs and uniforms -static void *Shader_Load(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade); -static void Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade); +static GLuint screenTextures[NUMSCREENTEXTURES] = {0}; // shortcut for ((float)1/i) static const GLfloat byte2float[256] = { @@ -166,6 +153,8 @@ static const GLfloat byte2float[256] = { 0.972549f, 0.976471f, 0.980392f, 0.984314f, 0.988235f, 0.992157f, 0.996078f, 1.000000f }; +// Loaded OpenGL version +static int majorGL = 0, minorGL = 0; // -----------------+ // GL_DBG_Printf : Output debug messages to debug log if DEBUG_TO_FILE is defined, @@ -196,7 +185,6 @@ FUNCPRINTF void GL_DBG_Printf(const char *format, ...) #endif } - // -----------------+ // GL_MSG_Warning : Raises a warning. // : @@ -248,7 +236,6 @@ static void GL_MSG_Error(const char *format, ...) #endif } - #ifdef STATIC_OPENGL /* 1.0 functions */ /* Miscellaneous */ @@ -290,11 +277,6 @@ static void GL_MSG_Error(const char *format, ...) #define pglDrawElements glDrawElements #define pglEnableClientState glEnableClientState #define pglDisableClientState glDisableClientState -#define pglClientActiveTexture glClientActiveTexture -#define pglGenBuffers glGenBuffers -#define pglBindBuffer glBindBuffer -#define pglBufferData glBufferData -#define pglDeleteBuffers glDeleteBuffers /* Lighting */ #define pglShadeModel glShadeModel @@ -395,14 +377,6 @@ typedef void (APIENTRY * PFNglEnableClientState) (GLenum cap); static PFNglEnableClientState pglEnableClientState; typedef void (APIENTRY * PFNglDisableClientState) (GLenum cap); static PFNglDisableClientState pglDisableClientState; -typedef void (APIENTRY * PFNglGenBuffers) (GLsizei n, GLuint *buffers); -static PFNglGenBuffers pglGenBuffers; -typedef void (APIENTRY * PFNglBindBuffer) (GLenum target, GLuint buffer); -static PFNglBindBuffer pglBindBuffer; -typedef void (APIENTRY * PFNglBufferData) (GLenum target, GLsizei size, const GLvoid *data, GLenum usage); -static PFNglBufferData pglBufferData; -typedef void (APIENTRY * PFNglDeleteBuffers) (GLsizei n, const GLuint *buffers); -static PFNglDeleteBuffers pglDeleteBuffers; /* Lighting */ typedef void (APIENTRY * PFNglShadeModel) (GLenum mode); @@ -427,10 +401,10 @@ typedef void (APIENTRY * PFNglTexEnvi) (GLenum target, GLenum pname, GLint param static PFNglTexEnvi pglTexEnvi; typedef void (APIENTRY * PFNglTexParameteri) (GLenum target, GLenum pname, GLint param); static PFNglTexParameteri pglTexParameteri; +typedef void (APIENTRY * PFNglTexImage1D) (GLenum target, GLint level, GLint internalFormat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +static PFNglTexImage1D pglTexImage1D; typedef void (APIENTRY * PFNglTexImage2D) (GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); static PFNglTexImage2D pglTexImage2D; -typedef void (APIENTRY * PFNglTexImage3D) (GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); -static PFNglTexImage3D pglTexImage3D; typedef void (APIENTRY * PFNglTexSubImage2D) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); static PFNglTexSubImage2D pglTexSubImage2D; @@ -449,9 +423,16 @@ static PFNglCopyTexImage2D pglCopyTexImage2D; typedef void (APIENTRY * PFNglCopyTexSubImage2D) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); static PFNglCopyTexSubImage2D pglCopyTexSubImage2D; #endif -/* GLU functions */ -typedef GLint (APIENTRY * PFNgluBuild2DMipmaps) (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *data); -static PFNgluBuild2DMipmaps pgluBuild2DMipmaps; + +/* 3.0 functions */ +#ifdef GL_VERSION_3_0 +typedef void (APIENTRY * PFNglGenerateMipmap) (GLenum target); +static PFNglGenerateMipmap pglGenerateMipmap; +#endif + +/* 1.2 functions for 3D textures */ +typedef void (APIENTRY * PFNglTexImage3D) (GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +static PFNglTexImage3D pglTexImage3D; /* 1.3 functions for multitexturing */ typedef void (APIENTRY *PFNglActiveTexture) (GLenum); @@ -463,6 +444,16 @@ static PFNglMultiTexCoord2fv pglMultiTexCoord2fv; typedef void (APIENTRY *PFNglClientActiveTexture) (GLenum); static PFNglClientActiveTexture pglClientActiveTexture; +/* 1.5 functions for buffers */ +typedef void (APIENTRY * PFNglGenBuffers) (GLsizei n, GLuint *buffers); +static PFNglGenBuffers pglGenBuffers; +typedef void (APIENTRY * PFNglBindBuffer) (GLenum target, GLuint buffer); +static PFNglBindBuffer pglBindBuffer; +typedef void (APIENTRY * PFNglBufferData) (GLenum target, GLsizei size, const GLvoid *data, GLenum usage); +static PFNglBufferData pglBufferData; +typedef void (APIENTRY * PFNglDeleteBuffers) (GLsizei n, const GLuint *buffers); +static PFNglDeleteBuffers pglDeleteBuffers; + // sky dome needs this typedef void (APIENTRY *PFNglColorPointer) (GLint, GLenum, GLsizei, const GLvoid*); static PFNglColorPointer pglColorPointer; @@ -486,6 +477,9 @@ static PFNglColorPointer pglColorPointer; #ifndef GL_TEXTURE1 #define GL_TEXTURE1 0x84C1 #endif +#ifndef GL_TEXTURE2 +#define GL_TEXTURE2 0x84C2 +#endif boolean SetupGLfunc(void) { @@ -548,8 +542,9 @@ boolean SetupGLfunc(void) GETOPENGLFUNC(pglTexEnvi, glTexEnvi) GETOPENGLFUNC(pglTexParameteri, glTexParameteri) + GETOPENGLFUNC(pglTexImage1D, glTexImage1D) GETOPENGLFUNC(pglTexImage2D, glTexImage2D) - GETOPENGLFUNC(pglTexSubImage2D , glTexSubImage2D) + GETOPENGLFUNC(pglTexSubImage2D, glTexSubImage2D) GETOPENGLFUNC(pglGenTextures, glGenTextures) GETOPENGLFUNC(pglDeleteTextures, glDeleteTextures) @@ -577,12 +572,12 @@ typedef void (APIENTRY *PFNglGetShaderiv) (GLuint, GLenum, GLint*); typedef void (APIENTRY *PFNglGetShaderInfoLog) (GLuint, GLsizei, GLsizei*, GLchar*); typedef void (APIENTRY *PFNglDeleteShader) (GLuint); typedef GLuint (APIENTRY *PFNglCreateProgram) (void); +typedef void (APIENTRY *PFNglDeleteProgram) (GLuint); typedef void (APIENTRY *PFNglAttachShader) (GLuint, GLuint); typedef void (APIENTRY *PFNglLinkProgram) (GLuint); typedef void (APIENTRY *PFNglGetProgramiv) (GLuint, GLenum, GLint*); typedef void (APIENTRY *PFNglUseProgram) (GLuint); typedef void (APIENTRY *PFNglUniform1i) (GLint, GLint); -typedef void (APIENTRY *PFNglUniform1iv) (GLint, GLsizei, const GLint*); typedef void (APIENTRY *PFNglUniform1f) (GLint, GLfloat); typedef void (APIENTRY *PFNglUniform2f) (GLint, GLfloat, GLfloat); typedef void (APIENTRY *PFNglUniform3f) (GLint, GLfloat, GLfloat, GLfloat); @@ -599,12 +594,12 @@ static PFNglGetShaderiv pglGetShaderiv; static PFNglGetShaderInfoLog pglGetShaderInfoLog; static PFNglDeleteShader pglDeleteShader; static PFNglCreateProgram pglCreateProgram; +static PFNglDeleteProgram pglDeleteProgram; static PFNglAttachShader pglAttachShader; static PFNglLinkProgram pglLinkProgram; static PFNglGetProgramiv pglGetProgramiv; static PFNglUseProgram pglUseProgram; static PFNglUniform1i pglUniform1i; -static PFNglUniform1iv pglUniform1iv; static PFNglUniform1f pglUniform1f; static PFNglUniform2f pglUniform2f; static PFNglUniform3f pglUniform3f; @@ -614,23 +609,9 @@ static PFNglUniform2fv pglUniform2fv; static PFNglUniform3fv pglUniform3fv; static PFNglGetUniformLocation pglGetUniformLocation; -#define MAXSHADERS 16 -#define MAXSHADERPROGRAMS 16 - // 18032019 -static char *gl_customvertexshaders[MAXSHADERS]; -static char *gl_customfragmentshaders[MAXSHADERS]; - -static boolean gl_allowshaders = false; static boolean gl_shadersenabled = false; -static GLuint gl_currentshaderprogram = 0; -static boolean gl_shaderprogramchanged = true; - -static boolean gl_batching = false;// are we currently collecting batches? - -static GLint gl_palette[768]; -static INT32 gl_use_palette_shader = 0; -boolean gl_palette_initialized = false; +static INT32 gl_allowshaders = 0; static INT32 gl_enable_screen_textures = 1; @@ -650,298 +631,51 @@ typedef enum gluniform_fade_end, // palette rendering - gluniform_palette, - gluniform_color_lookup, - gluniform_lighttable_tex, - + gluniform_palette_tex, // 1d texture containing a palette + gluniform_palette_lookup_tex, // 3d texture containing the rgb->index lookup table + gluniform_lighttable_tex, // 2d texture containing a light table + // misc. gluniform_leveltime, gluniform_max, } gluniform_t; -typedef struct gl_shaderprogram_s +typedef struct gl_shader_s { + char *vertex_shader; + char *fragment_shader; GLuint program; - boolean custom; GLint uniforms[gluniform_max+1]; -} gl_shaderprogram_t; -static gl_shaderprogram_t gl_shaderprograms[MAXSHADERPROGRAMS]; +} gl_shader_t; + +static gl_shader_t gl_shaders[HWR_MAXSHADERS]; +static gl_shader_t gl_fallback_shader; + +// 09102020 +typedef struct gl_shaderstate_s +{ + gl_shader_t *current; + GLuint type; + GLuint program; + boolean changed; +} gl_shaderstate_t; +static gl_shaderstate_t gl_shaderstate; // Shader info static float shader_leveltime = 0; -// ======================== -// Fragment shader macros -// ======================== +// Lactozilla: Shader functions +static boolean Shader_CompileProgram(gl_shader_t *shader, GLint i); +static void Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade); + +static GLRGBAFloat shader_defaultcolor = {1.0f, 1.0f, 1.0f, 1.0f}; // -// GLSL Software fragment shader +// Generic vertex shader // -#define GLSL_DOOM_COLORMAP_floors \ - "float R_DoomColormap(float light, float z)\n" \ - "{\n" \ - "float lightnum = clamp(light / 17.0, 0.0, 15.0);\n" \ - "float lightz = clamp(z / 16.0, 0.0, 127.0);\n" \ - "float startmap = (15.0 - lightnum) * 4.0;\n" \ - "float scale = 160.0 / (lightz + 1.0);\n" \ - "return startmap * 1.06 - scale * 0.5 * 1.15;\n" \ - "}\n" - -// 1.06 and 1.15 were chosen when trying to match software lighting in a test map - -#define GLSL_DOOM_COLORMAP \ - "float R_DoomColormap(float light, float z)\n" \ - "{\n" \ - "float lightnum = clamp(light / 17.0, 0.0, 15.0);\n" \ - "float lightz = clamp(z / 16.0, 0.0, 127.0);\n" \ - "float startmap = (15.0 - lightnum) * 4.0;\n" \ - "float scale = 160.0 / (lightz + 1.0);\n" \ - "return startmap - scale * 0.5;\n" \ - "}\n" - -#define GLSL_DOOM_COLORMAP_walls \ - "float R_DoomColormap(float light, float z)\n" \ - "{\n" \ - "float lightnum = clamp(light / 17.0, 0.0, 15.0);\n" \ - "float lightz = clamp(z / 16.0, 0.0, 127.0);\n" \ - "float startmap = (15.0 - lightnum) * 4.0;\n" \ - "float scale = 160.0 / (lightz + 1.0);\n" \ - "return startmap * 1.05 - scale * 1.0 * 1.1;\n" \ - "}\n" - -#define GLSL_DOOM_LIGHT_EQUATION \ - "float R_DoomLightingEquation(float light)\n" \ - "{\n" \ - "float z = gl_FragCoord.z / gl_FragCoord.w;\n" \ - "float colormap = floor(R_DoomColormap(light, z)) + 0.5;\n" \ - "return clamp(colormap, 0.0, 31.0) / 32.0;\n" \ - "}\n" - -#define GLSL_SOFTWARE_TINT_EQUATION \ - "if (tint_color.a > 0.0) {\n" \ - "float color_bright = sqrt((base_color.r * base_color.r) + (base_color.g * base_color.g) + (base_color.b * base_color.b));\n" \ - "float strength = sqrt(9.0 * tint_color.a);\n" \ - "final_color.r = clamp((color_bright * (tint_color.r * strength)) + (base_color.r * (1.0 - strength)), 0.0, 1.0);\n" \ - "final_color.g = clamp((color_bright * (tint_color.g * strength)) + (base_color.g * (1.0 - strength)), 0.0, 1.0);\n" \ - "final_color.b = clamp((color_bright * (tint_color.b * strength)) + (base_color.b * (1.0 - strength)), 0.0, 1.0);\n" \ - "}\n" - -#define GLSL_SOFTWARE_FADE_EQUATION \ - "float darkness = R_DoomLightingEquation(lighting);\n" \ - "if (fade_start != 0.0 || fade_end != 31.0) {\n" \ - "float fs = fade_start / 31.0;\n" \ - "float fe = fade_end / 31.0;\n" \ - "float fd = fe - fs;\n" \ - "darkness = clamp((darkness - fs) * (1.0 / fd), 0.0, 1.0);\n" \ - "}\n" \ - "final_color = mix(final_color, fade_color, darkness);\n" - -#define GLSL_SOFTWARE_UNIFORMS \ - "uniform sampler2D tex;\n" \ - "uniform vec4 poly_color;\n" \ - "uniform vec4 tint_color;\n" \ - "uniform vec4 fade_color;\n" \ - "uniform float lighting;\n" \ - "uniform float fade_start;\n" \ - "uniform float fade_end;\n" - -#define GLSL_SOFTWARE_MAIN \ - "void main(void) {\n" \ - "vec4 texel = texture2D(tex, gl_TexCoord[0].st);\n" \ - "vec4 base_color = texel * poly_color;\n" \ - "vec4 final_color = base_color;\n" \ - GLSL_SOFTWARE_TINT_EQUATION \ - GLSL_SOFTWARE_FADE_EQUATION \ - "final_color.a = texel.a * poly_color.a;\n" \ - "gl_FragColor = final_color;\n" \ - "}\n" - -#define GLSL_SOFTWARE_FRAGMENT_SHADER_FLOORS \ - GLSL_SOFTWARE_UNIFORMS \ - GLSL_DOOM_COLORMAP_floors \ - GLSL_DOOM_LIGHT_EQUATION \ - GLSL_SOFTWARE_MAIN \ - "\0" - -#define GLSL_SOFTWARE_FRAGMENT_SHADER_WALLS \ - GLSL_SOFTWARE_UNIFORMS \ - GLSL_DOOM_COLORMAP_walls \ - GLSL_DOOM_LIGHT_EQUATION \ - GLSL_SOFTWARE_MAIN \ - "\0" - -#define GLSL_SOFTWARE_PAL_UNIFORMS \ - "uniform sampler2D tex;\n" \ - "uniform sampler2D lighttable_tex;\n" \ - "uniform sampler3D lookup_tex;\n" \ - "uniform int palette[768];\n" \ - "uniform vec4 poly_color;\n" \ - "uniform float lighting;\n" \ - -#define GLSL_SOFTWARE_PAL_MAIN \ - "void main(void) {\n" \ - "vec4 texel = texture2D(tex, gl_TexCoord[0].st);\n" \ - "int tex_pal_idx = int(texture3D(lookup_tex, vec3((texel * 63.0 + 0.5) / 64.0))[0] * 255.0);\n" \ - "float z = gl_FragCoord.z / gl_FragCoord.w;\n" \ - "int light_y = int(clamp(floor(R_DoomColormap(lighting, z)), 0.0, 31.0));\n" \ - "vec2 lighttable_coord = vec2((float(tex_pal_idx) + 0.5) / 256.0, (float(light_y) + 0.5) / 32.0);\n" \ - "int final_idx = int(texture2D(lighttable_tex, lighttable_coord)[0] * 255.0);\n" \ - "vec4 final_color = vec4(float(palette[final_idx*3])/255.0, float(palette[final_idx*3+1])/255.0, float(palette[final_idx*3+2])/255.0, 1.0);\n" \ - "final_color.a = texel.a * poly_color.a;\n" \ - "gl_FragColor = final_color;\n" \ - "}\n" - -#define GLSL_SOFTWARE_PAL_FRAGMENT_SHADER_FLOORS \ - GLSL_SOFTWARE_PAL_UNIFORMS \ - GLSL_DOOM_COLORMAP_floors \ - GLSL_SOFTWARE_PAL_MAIN \ - "\0" - -#define GLSL_SOFTWARE_PAL_FRAGMENT_SHADER_WALLS \ - GLSL_SOFTWARE_PAL_UNIFORMS \ - GLSL_DOOM_COLORMAP_walls \ - GLSL_SOFTWARE_PAL_MAIN \ - "\0" - -#define GLSL_SOFTWARE_PAL_FRAGMENT_SHADER_POSTPROCESS \ - GLSL_SOFTWARE_PAL_UNIFORMS \ - GLSL_SOFTWARE_PAL_MAIN \ - "\0" - -// -// Water surface shader -// -// Mostly guesstimated, rather than the rest being built off Software science. -// Still needs to distort things underneath/around the water... -// - -#define GLSL_WATER_FRAGMENT_SHADER \ - "uniform sampler2D tex;\n" \ - "uniform vec4 poly_color;\n" \ - "uniform vec4 tint_color;\n" \ - "uniform vec4 fade_color;\n" \ - "uniform float lighting;\n" \ - "uniform float fade_start;\n" \ - "uniform float fade_end;\n" \ - "uniform float leveltime;\n" \ - "const float freq = 0.025;\n" \ - "const float amp = 0.025;\n" \ - "const float speed = 2.0;\n" \ - "const float pi = 3.14159;\n" \ - GLSL_DOOM_COLORMAP \ - GLSL_DOOM_LIGHT_EQUATION \ - "void main(void) {\n" \ - "float z = (gl_FragCoord.z / gl_FragCoord.w) / 2.0;\n" \ - "float a = -pi * (z * freq) + (leveltime * speed);\n" \ - "float sdistort = sin(a) * amp;\n" \ - "float cdistort = cos(a) * amp;\n" \ - "vec4 texel = texture2D(tex, vec2(gl_TexCoord[0].s - sdistort, gl_TexCoord[0].t - cdistort));\n" \ - "vec4 base_color = texel * poly_color;\n" \ - "vec4 final_color = base_color;\n" \ - GLSL_SOFTWARE_TINT_EQUATION \ - GLSL_SOFTWARE_FADE_EQUATION \ - "final_color.a = texel.a * poly_color.a;\n" \ - "gl_FragColor = final_color;\n" \ - "}\0" - -// -// Fog block shader -// -// Alpha of the planes themselves are still slightly off -- see HWR_FogBlockAlpha -// - -#define GLSL_FOG_FRAGMENT_SHADER \ - "uniform vec4 tint_color;\n" \ - "uniform vec4 fade_color;\n" \ - "uniform float lighting;\n" \ - "uniform float fade_start;\n" \ - "uniform float fade_end;\n" \ - GLSL_DOOM_COLORMAP \ - GLSL_DOOM_LIGHT_EQUATION \ - "void main(void) {\n" \ - "vec4 base_color = gl_Color;\n" \ - "vec4 final_color = base_color;\n" \ - GLSL_SOFTWARE_TINT_EQUATION \ - GLSL_SOFTWARE_FADE_EQUATION \ - "gl_FragColor = final_color;\n" \ - "}\0" - -// -// Palette color quantization shader -// - -#define GLSL_PALETTE_FRAGMENT_SHADER \ - "uniform sampler2D tex;\n" \ - "uniform sampler3D lookup_tex;\n" \ - "uniform int palette[768];\n" \ - "void main(void) {\n" \ - "vec3 texel = vec3(texture2D(tex, gl_TexCoord[0].st));\n" \ - "int pal_idx = int(texture3D(lookup_tex, vec3((63.0/64.0) * texel + 1.0 / 128.0))[0] * 255.0);\n" \ - "gl_FragColor = vec4(float(palette[pal_idx*3])/255.0, float(palette[pal_idx*3+1])/255.0, float(palette[pal_idx*3+2])/255.0, 1.0);\n" \ - "}\0" - -// -// GLSL generic fragment shader -// - -#define GLSL_DEFAULT_FRAGMENT_SHADER \ - "uniform sampler2D tex;\n" \ - "uniform vec4 poly_color;\n" \ - "void main(void) {\n" \ - "gl_FragColor = texture2D(tex, gl_TexCoord[0].st) * poly_color;\n" \ - "}\0" - -static const char *fragment_shaders[] = { - // Default fragment shader - GLSL_DEFAULT_FRAGMENT_SHADER, - - // Floor fragment shader - GLSL_SOFTWARE_FRAGMENT_SHADER_FLOORS, - - // Wall fragment shader - GLSL_SOFTWARE_FRAGMENT_SHADER_WALLS, - - // Sprite fragment shader - GLSL_SOFTWARE_FRAGMENT_SHADER_WALLS, - - // Model fragment shader - GLSL_SOFTWARE_FRAGMENT_SHADER_WALLS, - - // Water fragment shader - GLSL_WATER_FRAGMENT_SHADER, - - // Fog fragment shader - GLSL_FOG_FRAGMENT_SHADER, - - // Sky fragment shader - "uniform sampler2D tex;\n" - "void main(void) {\n" - "gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n" - "}\0", - - // Palette fragment shader - GLSL_PALETTE_FRAGMENT_SHADER, - - GLSL_SOFTWARE_PAL_FRAGMENT_SHADER_FLOORS, - - GLSL_SOFTWARE_PAL_FRAGMENT_SHADER_WALLS, - - GLSL_SOFTWARE_PAL_FRAGMENT_SHADER_POSTPROCESS, - - NULL, -}; - -// ====================== -// Vertex shader macros -// ====================== - -// -// GLSL generic vertex shader -// - -#define GLSL_DEFAULT_VERTEX_SHADER \ +#define GLSL_FALLBACK_VERTEX_SHADER \ "void main()\n" \ "{\n" \ "gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;\n" \ @@ -950,50 +684,30 @@ static const char *fragment_shaders[] = { "gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;\n" \ "}\0" -static const char *vertex_shaders[] = { - // Default vertex shader - GLSL_DEFAULT_VERTEX_SHADER, +// +// Generic fragment shader +// - // Floor vertex shader - GLSL_DEFAULT_VERTEX_SHADER, - - // Wall vertex shader - GLSL_DEFAULT_VERTEX_SHADER, - - // Sprite vertex shader - GLSL_DEFAULT_VERTEX_SHADER, - - // Model vertex shader - GLSL_DEFAULT_VERTEX_SHADER, - - // Water vertex shader - GLSL_DEFAULT_VERTEX_SHADER, - - // Fog vertex shader - GLSL_DEFAULT_VERTEX_SHADER, - - // Sky vertex shader - GLSL_DEFAULT_VERTEX_SHADER, - - // Palette vertex shader - GLSL_DEFAULT_VERTEX_SHADER, - - GLSL_DEFAULT_VERTEX_SHADER, - - GLSL_DEFAULT_VERTEX_SHADER, - - NULL, -}; +#define GLSL_FALLBACK_FRAGMENT_SHADER \ + "uniform sampler2D tex;\n" \ + "uniform vec4 poly_color;\n" \ + "void main(void) {\n" \ + "gl_FragColor = texture2D(tex, gl_TexCoord[0].st) * poly_color;\n" \ + "}\0" #endif // GL_SHADERS void SetupGLFunc4(void) { + /* 1.2 funcs */ pglTexImage3D = GetGLFunc("glTexImage3D"); + /* 1.3 funcs */ pglActiveTexture = GetGLFunc("glActiveTexture"); pglMultiTexCoord2f = GetGLFunc("glMultiTexCoord2f"); pglClientActiveTexture = GetGLFunc("glClientActiveTexture"); pglMultiTexCoord2fv = GetGLFunc("glMultiTexCoord2fv"); + + /* 1.5 funcs */ pglGenBuffers = GetGLFunc("glGenBuffers"); pglBindBuffer = GetGLFunc("glBindBuffer"); pglBufferData = GetGLFunc("glBufferData"); @@ -1011,12 +725,12 @@ void SetupGLFunc4(void) pglGetShaderInfoLog = GetGLFunc("glGetShaderInfoLog"); pglDeleteShader = GetGLFunc("glDeleteShader"); pglCreateProgram = GetGLFunc("glCreateProgram"); + pglDeleteProgram = GetGLFunc("glDeleteProgram"); pglAttachShader = GetGLFunc("glAttachShader"); pglLinkProgram = GetGLFunc("glLinkProgram"); pglGetProgramiv = GetGLFunc("glGetProgramiv"); pglUseProgram = GetGLFunc("glUseProgram"); pglUniform1i = GetGLFunc("glUniform1i"); - pglUniform1iv = GetGLFunc("glUniform1iv"); pglUniform1f = GetGLFunc("glUniform1f"); pglUniform2f = GetGLFunc("glUniform2f"); pglUniform3f = GetGLFunc("glUniform3f"); @@ -1027,169 +741,83 @@ void SetupGLFunc4(void) pglGetUniformLocation = GetGLFunc("glGetUniformLocation"); #endif - // GLU - pgluBuild2DMipmaps = GetGLFunc("gluBuild2DMipmaps"); +#ifdef GL_VERSION_3_0 + pglGenerateMipmap = GetGLFunc("glGenerateMipmap"); +#endif } -// jimita -EXPORT boolean HWRAPI(LoadShaders) (void) +EXPORT boolean HWRAPI(InitShaders) (void) { #ifdef GL_SHADERS - GLuint gl_vertShader, gl_fragShader; - GLint i, result; + if (!pglUseProgram) + return false; - if (!pglUseProgram) return false; + gl_fallback_shader.vertex_shader = Z_StrDup(GLSL_FALLBACK_VERTEX_SHADER); + gl_fallback_shader.fragment_shader = Z_StrDup(GLSL_FALLBACK_FRAGMENT_SHADER); - gl_customvertexshaders[0] = NULL; - gl_customfragmentshaders[0] = NULL; - - for (i = 0; vertex_shaders[i] && fragment_shaders[i]; i++) + if (!Shader_CompileProgram(&gl_fallback_shader, -1)) { - gl_shaderprogram_t *shader; - const GLchar* vert_shader = vertex_shaders[i]; - const GLchar* frag_shader = fragment_shaders[i]; - boolean custom = cv_grusecustomshaders.value && ((gl_customvertexshaders[i] || gl_customfragmentshaders[i]) && (i > 0)); - - // 18032019 - if (cv_grusecustomshaders.value && gl_customvertexshaders[i]) - vert_shader = gl_customvertexshaders[i]; - if (cv_grusecustomshaders.value && gl_customfragmentshaders[i]) - frag_shader = gl_customfragmentshaders[i]; - - - if (i >= MAXSHADERS) - break; - if (i >= MAXSHADERPROGRAMS) - break; - - // - // Load and compile vertex shader - // - gl_vertShader = pglCreateShader(GL_VERTEX_SHADER); - if (!gl_vertShader) - { - GL_MSG_Error("LoadShaders: Error creating vertex shader %d\n", i); - continue; - } - - pglShaderSource(gl_vertShader, 1, &vert_shader, NULL); - pglCompileShader(gl_vertShader); - - // check for compile errors - pglGetShaderiv(gl_vertShader, GL_COMPILE_STATUS, &result); - if (result == GL_FALSE) - { - GLchar* infoLog; - GLint logLength; - - pglGetShaderiv(gl_vertShader, GL_INFO_LOG_LENGTH, &logLength); - - infoLog = malloc(logLength); - pglGetShaderInfoLog(gl_vertShader, logLength, NULL, infoLog); - - GL_MSG_Error("LoadShaders: Error compiling vertex shader %d\n%s", i, infoLog); - continue; - } - - // - // Load and compile fragment shader - // - gl_fragShader = pglCreateShader(GL_FRAGMENT_SHADER); - if (!gl_fragShader) - { - GL_MSG_Error("LoadShaders: Error creating fragment shader %d\n", i); - continue; - } - - pglShaderSource(gl_fragShader, 1, &frag_shader, NULL); - pglCompileShader(gl_fragShader); - - // check for compile errors - pglGetShaderiv(gl_fragShader, GL_COMPILE_STATUS, &result); - if (result == GL_FALSE) - { - GLchar* infoLog; - GLint logLength; - - pglGetShaderiv(gl_fragShader, GL_INFO_LOG_LENGTH, &logLength); - - infoLog = malloc(logLength); - pglGetShaderInfoLog(gl_fragShader, logLength, NULL, infoLog); - - GL_MSG_Error("LoadShaders: Error compiling fragment shader %d\n%s", i, infoLog); - continue; - } - - shader = &gl_shaderprograms[i]; - shader->program = pglCreateProgram(); - shader->custom = custom; - pglAttachShader(shader->program, gl_vertShader); - pglAttachShader(shader->program, gl_fragShader); - pglLinkProgram(shader->program); - - // check link status - pglGetProgramiv(shader->program, GL_LINK_STATUS, &result); - - // delete the shader objects - pglDeleteShader(gl_vertShader); - pglDeleteShader(gl_fragShader); - - // couldn't link? - if (result != GL_TRUE) - { - shader->program = 0; - shader->custom = false; - GL_MSG_Error("LoadShaders: Error linking shader program %d\n", i); - continue; - } - - // 13062019 -#define GETUNI(uniform) pglGetUniformLocation(shader->program, uniform); - - // lighting - shader->uniforms[gluniform_poly_color] = GETUNI("poly_color"); - shader->uniforms[gluniform_tint_color] = GETUNI("tint_color"); - shader->uniforms[gluniform_fade_color] = GETUNI("fade_color"); - shader->uniforms[gluniform_lighting] = GETUNI("lighting"); - shader->uniforms[gluniform_fade_start] = GETUNI("fade_start"); - shader->uniforms[gluniform_fade_end] = GETUNI("fade_end"); - - // misc. (custom shaders) - shader->uniforms[gluniform_leveltime] = GETUNI("leveltime"); - - // palette rendering - shader->uniforms[gluniform_palette] = GETUNI("palette"); - shader->uniforms[gluniform_color_lookup] = GETUNI("lookup_tex"); - shader->uniforms[gluniform_lighttable_tex] = GETUNI("lighttable_tex"); - -#undef GETUNI - -// set permanent uniform values -#define UNIFORM_1(uniform, a, function) \ - if (uniform != -1) \ - function (uniform, a); - -#define UNIFORM_2(uniform, a, b, function) \ - if (uniform != -1) \ - function (uniform, a, b); - - pglUseProgram(shader->program); - - // texture unit numbers for the samplers used for palette rendering - UNIFORM_2(shader->uniforms[gluniform_palette], 768, gl_palette, pglUniform1iv); - UNIFORM_1(shader->uniforms[gluniform_color_lookup], 1, pglUniform1i); - UNIFORM_1(shader->uniforms[gluniform_lighttable_tex], 2, pglUniform1i); - - pglUseProgram(0); - -#undef UNIFORM_1 -#undef UNIFORM_2 - + GL_MSG_Error("Failed to compile the fallback shader program!\n"); + return false; } -#endif + return true; +#else + return false; +#endif } +EXPORT void HWRAPI(LoadShader) (int slot, char *code, hwdshaderstage_t stage) +{ +#ifdef GL_SHADERS + gl_shader_t *shader; + + if (slot < 0 || slot >= HWR_MAXSHADERS) + I_Error("LoadShader: Invalid slot %d", slot); + + shader = &gl_shaders[slot]; + +#define LOADSHADER(source) { \ + if (shader->source) \ + Z_Free(shader->source); \ + shader->source = code; \ + } + + if (stage == HWD_SHADERSTAGE_VERTEX) + LOADSHADER(vertex_shader) + else if (stage == HWD_SHADERSTAGE_FRAGMENT) + LOADSHADER(fragment_shader) + else + I_Error("LoadShader: invalid shader stage"); + +#undef LOADSHADER +#else + (void)slot; + (void)code; + (void)stage; +#endif +} + +EXPORT boolean HWRAPI(CompileShader) (int slot) +{ +#ifdef GL_SHADERS + if (slot < 0 || slot >= HWR_MAXSHADERS) + I_Error("CompileShader: Invalid slot %d", slot); + + if (Shader_CompileProgram(&gl_shaders[slot], slot)) + { + return true; + } + else + { + gl_shaders[slot].program = 0; + return false; + } +#else + (void)slot; + return false; +#endif +} // // Shader info @@ -1202,7 +830,7 @@ EXPORT void HWRAPI(SetShaderInfo) (hwdshaderinfo_t info, INT32 value) switch (info) { case HWD_SHADERINFO_LEVELTIME: - shader_leveltime = (((float)(value-1)) + FIXED_TO_FLOAT(rendertimefrac)) / TICRATE; + shader_leveltime = value; break; default: break; @@ -1213,67 +841,31 @@ EXPORT void HWRAPI(SetShaderInfo) (hwdshaderinfo_t info, INT32 value) #endif } -// -// Custom shader loading -// -EXPORT void HWRAPI(LoadCustomShader) (int number, char *shader, size_t size, boolean fragment) -{ -#ifdef GL_SHADERS - if (!pglUseProgram) - return; - - if (number < 1 || number > MAXSHADERS) - I_Error("LoadCustomShader(): cannot load shader %d (max %d)", number, MAXSHADERS); - - if (fragment) - { - gl_customfragmentshaders[number] = malloc(size+1); - strncpy(gl_customfragmentshaders[number], shader, size); - gl_customfragmentshaders[number][size] = 0; - } - else - { - gl_customvertexshaders[number] = malloc(size+1); - strncpy(gl_customvertexshaders[number], shader, size); - gl_customvertexshaders[number][size] = 0; - } -#else - (void)number; - (void)shader; - (void)size; - (void)fragment; -#endif -} - -EXPORT boolean HWRAPI(InitCustomShaders) (void) -{ -#ifdef GL_SHADERS - KillShaders(); - return LoadShaders(); - - if (gl_use_palette_shader) - { - InitPalette(0, false); - } -#endif -} - - -EXPORT void HWRAPI(SetShader) (int shader) +EXPORT void HWRAPI(SetShader) (int slot) { #ifdef GL_SHADERS if (gl_allowshaders) { - if ((GLuint)shader != gl_currentshaderprogram) + gl_shader_t *next_shader = &gl_shaders[slot]; // the gl_shader_t we are going to switch to + + if (!next_shader->program) + next_shader = &gl_fallback_shader; // unusable shader, use fallback instead + + // update gl_shaderstate if an actual shader switch is needed + if (gl_shaderstate.current != next_shader) { - gl_currentshaderprogram = shader; - gl_shaderprogramchanged = true; + gl_shaderstate.current = next_shader; + gl_shaderstate.program = next_shader->program; + gl_shaderstate.type = slot; + gl_shaderstate.changed = true; } + gl_shadersenabled = true; + return; } #else - (void)shader; + (void)slot; #endif gl_shadersenabled = false; } @@ -1281,130 +873,15 @@ EXPORT void HWRAPI(SetShader) (int shader) EXPORT void HWRAPI(UnSetShader) (void) { #ifdef GL_SHADERS - gl_shadersenabled = false; - gl_currentshaderprogram = 0; - gl_shaderprogramchanged = true;// not sure if this is needed - if (!pglUseProgram) return; - pglUseProgram(0); + gl_shaderstate.current = NULL; + gl_shaderstate.type = 0; + gl_shaderstate.program = 0; + + if (pglUseProgram) + pglUseProgram(0); #endif -} -EXPORT void HWRAPI(KillShaders) (void) -{ - // unused......................... -} - -GLuint palette_tex_num; -// length of one side of lookup texture -// smallest separation between all the colors in the srb2 palette is 6, so -// possibly a 64x64x64 lookup texture might be enough for 100% correct colors -// (min separation for 64^3 size is 4) -#define LUT_SIZE 64 -#define STEP_SIZE (256/LUT_SIZE) -// the +2 in the NearestColor call also needs to be adjusted if LUT_SIZE is changed! -// the hardcoded values in the shader also need to be adjusted if LUT_SIZE is changed! - -void InitPalette(int flashnum, boolean skiplut) -{ - int i, r, g, b; - - //Hudler: 16/10/99: added for OpenGL gamma correction - RGBA_t gamma_correction = {0x7F7F7F7F}; - - //Hurdler 16/10/99: added for OpenGL gamma correction - gamma_correction.s.red = (UINT8)cv_grgammared.value; - gamma_correction.s.green = (UINT8)cv_grgammagreen.value; - gamma_correction.s.blue = (UINT8)cv_grgammablue.value; - - // init the palette - int flashoffset = flashnum*256; - for (i = 0+flashoffset; i < 256+flashoffset; i++) - { - int fi = i-flashoffset; - - // gamma correction - int pr, pg, pb; - pr = (UINT8)MIN((pLocalPalette[i].s.red*gamma_correction.s.red)/127, 255); - pg = (UINT8)MIN((pLocalPalette[i].s.green*gamma_correction.s.green)/127, 255); - pb = (UINT8)MIN((pLocalPalette[i].s.blue*gamma_correction.s.blue)/127, 255); - - // crush to 16-bit rgb565, like software currently does - float fred = (float)(pr >> 3); - float fgreen = (float)(pg >> 2); - float fblue = (float)(pb >> 3); - // restore to rgb888 - gl_palette[fi*3] = (GLint)(fred / 31.0f * 255.0f); - gl_palette[fi*3+1] = (GLint)(fgreen / 63.0f * 255.0f); - gl_palette[fi*3+2] = (GLint)(fblue / 31.0f * 255.0f); - } - - if (!skiplut) - { - GLenum internalFormat; - if (gl_version[0] == '1' || gl_version[0] == '2') - { - // if the OpenGL version is below 3.0, then the GL_R8 format may not be available. - // so use GL_LUMINANCE8 instead to get a single component 8-bit format - // (it is possible to have access to shaders even in some OpenGL 1.x systems, - // so palette rendering can still possibly be achieved there) - internalFormat = GL_LUMINANCE8; - } - else - { - internalFormat = GL_R8; - } - - // init the palette conversion lookup texture - GLubyte *pal_lookup_tex = malloc(LUT_SIZE*LUT_SIZE*LUT_SIZE*sizeof(GLubyte)); - - if (!pal_lookup_tex) - I_Error("Failed to allocate memory for generating palette lookup texture."); - - for (b = 0; b < LUT_SIZE; b++) - { - for (g = 0; g < LUT_SIZE; g++) - { - for (r = 0; r < LUT_SIZE; r++) - { - pal_lookup_tex[b*LUT_SIZE*LUT_SIZE+g*LUT_SIZE+r] = NearestColor(r*STEP_SIZE+0, g*STEP_SIZE+0, b*STEP_SIZE+0); - } - } - } - - pglGenTextures(1, &palette_tex_num); - pglBindTexture(GL_TEXTURE_3D, palette_tex_num); - pglTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - pglTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - if (!pglTexImage3D) - I_Error("pglTexImage3D is NULL!"); - pglTexImage3D(GL_TEXTURE_3D, 0, internalFormat, LUT_SIZE, LUT_SIZE, LUT_SIZE, 0, GL_RED, GL_UNSIGNED_BYTE, pal_lookup_tex); - free(pal_lookup_tex); - } -#undef STEP_SIZE - - pglUseProgram(gl_shaderprograms[8].program); - pglUniform1i(gl_shaderprograms[8].uniforms[gluniform_color_lookup], 1); // bind sampler to second texture unit - pglUniform1iv(gl_shaderprograms[8].uniforms[gluniform_palette], 768, gl_palette); - // bind the palette to the fancy shader here - pglUseProgram(gl_shaderprograms[9].program); - pglUniform1iv(gl_shaderprograms[9].uniforms[gluniform_palette], 768, gl_palette); - // bind tex unit 2 to lighttable tex - pglUniform1i(gl_shaderprograms[9].uniforms[gluniform_lighttable_tex], 2); - pglUniform1i(gl_shaderprograms[9].uniforms[gluniform_color_lookup], 1); - // bind the palette to the fancy shader here - pglUseProgram(gl_shaderprograms[10].program); - pglUniform1iv(gl_shaderprograms[10].uniforms[gluniform_palette], 768, gl_palette); - // bind tex unit 2 to lighttable tex - pglUniform1i(gl_shaderprograms[10].uniforms[gluniform_lighttable_tex], 2); - pglUniform1i(gl_shaderprograms[10].uniforms[gluniform_color_lookup], 1); - pglUseProgram(0); - pglBindTexture(GL_TEXTURE_3D, 0); - - // bind 3d lookup to unit 1, maybe it can stay there - pglActiveTexture(GL_TEXTURE1); - pglBindTexture(GL_TEXTURE_3D, palette_tex_num); - pglActiveTexture(GL_TEXTURE0); - gl_palette_initialized = true; + gl_shadersenabled = false; } // -----------------+ @@ -1413,8 +890,10 @@ void InitPalette(int flashnum, boolean skiplut) static void SetNoTexture(void) { // Disable texture. - if (tex_downloaded != NOTEXTURE_NUM && !gl_batching) + if (tex_downloaded != NOTEXTURE_NUM) { + if (NOTEXTURE_NUM == 0) + pglGenTextures(1, &NOTEXTURE_NUM); pglBindTexture(GL_TEXTURE_2D, NOTEXTURE_NUM); tex_downloaded = NOTEXTURE_NUM; } @@ -1486,11 +965,13 @@ void SetStates(void) pglEnable(GL_TEXTURE_2D); // two-dimensional texturing pglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + pglEnable(GL_ALPHA_TEST); pglAlphaFunc(GL_NOTEQUAL, 0.0f); pglEnable(GL_BLEND); // enable color blending pglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + pglEnable(GL_STENCIL_TEST); pglEnable(GL_DEPTH_TEST); // check the depth buffer pglDepthMask(GL_TRUE); // enable writing to depth buffer pglClearDepth(1.0f); @@ -1501,7 +982,7 @@ void SetStates(void) CurrentPolyFlags = 0xffffffff; SetBlend(0); - //tex_downloaded = (GLuint)-1; + tex_downloaded = 0; SetNoTexture(); pglPolygonOffset(-1.0f, -1.0f); @@ -1510,8 +991,6 @@ void SetStates(void) pglLoadIdentity(); pglScalef(1.0f, 1.0f, -1.0f); pglGetFloatv(GL_MODELVIEW_MATRIX, modelMatrix); // added for new coronas' code (without depth buffer) - - pglEnable(GL_STENCIL_TEST); } // -----------------+ @@ -1575,6 +1054,17 @@ EXPORT boolean HWRAPI(Init) (void) } +// -----------------+ +// SetupGLInfo : Retreive and store currently loaded OpenGL version +// -----------------+ +EXPORT void HWRAPI(SetupGLInfo) (void) +{ + const GLubyte *versionGL = pglGetString(GL_VERSION); + CONS_Printf("Loaded OpenGL version %s\n", (const char*)versionGL); + sscanf((const char*)versionGL, "%d.%d", &majorGL, &minorGL); +} + + // -----------------+ // ClearMipMapCache : Flush OpenGL textures from memory // -----------------+ @@ -1583,99 +1073,40 @@ EXPORT void HWRAPI(ClearMipMapCache) (void) Flush(); } -EXPORT UINT32 HWRAPI(AddLightTable) (UINT8 *lighttable) -{ - LightTableCacheEntry_t *cache_entry = malloc(sizeof(LightTableCacheEntry_t)); - if (!ltcachetail) - { - ltcachehead = ltcachetail = cache_entry; - } - else - { - ltcachetail->next = cache_entry; - ltcachetail = cache_entry; - } - ltcachetail->next = NULL; - pglGenTextures(1, <cachetail->id); - if (!ltcachetail->id) - I_Error("hwr lighttable cache entry id is zero"); - pglBindTexture(GL_TEXTURE_2D, ltcachetail->id); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - pglTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 256, 32, 0, GL_RED, GL_UNSIGNED_BYTE, lighttable); - - // restore previously bound texture - if (!gl_batching) - pglBindTexture(GL_TEXTURE_2D, tex_downloaded); - - return ltcachetail->id; -} - -// Delete light table textures, ids given before become invalid and must not be used. -EXPORT void HWRAPI(ClearLightTableCache) (void) -{ - while (ltcachehead) - { - pglDeleteTextures(1, <cachehead->id); - LightTableCacheEntry_t *next = ltcachehead->next; - free(ltcachehead); - ltcachehead = next; - } - ltcachetail = NULL; -} - -// -----------------+ -// ReadRect : Read a rectangle region of the truecolor framebuffer -// : store pixels as 16bit 565 RGB -// Returns : 16bit 565 RGB pixel array stored in dst_data -// -----------------+ -EXPORT void HWRAPI(ReadRect) (INT32 x, INT32 y, INT32 width, INT32 height, - INT32 dst_stride, UINT16 * dst_data) +// Writes screen texture tex into dst_data. +// Pixel format is 24-bit RGB. Row order is top to bottom. +// Dimensions are screen_width * screen_height. +EXPORT void HWRAPI(ReadScreenTexture) (int tex, UINT16 *dst_data) { INT32 i; - //GL_DBG_Printf("ReadRect()\n"); - if (dst_stride == width*3) + int dst_stride = screen_width * 3; // stride between rows of image data + GLubyte*top = (GLvoid*)dst_data, *bottom = top + dst_stride * (screen_height - 1); + GLubyte *row; + row = malloc(dst_stride); + if (!row) return; + // at the time this function is called, generic2 can be found drawn on the framebuffer + // if some other screen texture is needed, draw it to the framebuffer + // and draw generic2 back after reading the framebuffer. + // this hack is for some reason **much** faster than the simple solution of using glGetTexImage. + if (tex != HWD_SCREENTEXTURE_GENERIC2) + DrawScreenTexture(tex, NULL, 0); + pglPixelStorei(GL_PACK_ALIGNMENT, 1); + pglReadPixels(0, 0, screen_width, screen_height, GL_RGB, GL_UNSIGNED_BYTE, dst_data); + if (tex != HWD_SCREENTEXTURE_GENERIC2) + DrawScreenTexture(HWD_SCREENTEXTURE_GENERIC2, NULL, 0); + // Flip image upside down. + // In other words, convert OpenGL's "bottom->top" row order into "top->bottom". + for(i = 0; i < screen_height/2; i++) { - GLubyte*top = (GLvoid*)dst_data, *bottom = top + dst_stride * (height - 1); - GLubyte *row = malloc(dst_stride); - if (!row) return; - pglPixelStorei(GL_PACK_ALIGNMENT, 1); - pglReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, dst_data); - pglPixelStorei(GL_UNPACK_ALIGNMENT, 1); - for(i = 0; i < height/2; i++) - { - memcpy(row, top, dst_stride); - memcpy(top, bottom, dst_stride); - memcpy(bottom, row, dst_stride); - top += dst_stride; - bottom -= dst_stride; - } - free(row); - } - else - { - INT32 j; - GLubyte *image = malloc(width*height*3*sizeof (*image)); - if (!image) return; - pglPixelStorei(GL_PACK_ALIGNMENT, 1); - pglReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, image); - pglPixelStorei(GL_UNPACK_ALIGNMENT, 1); - for (i = height-1; i >= 0; i--) - { - for (j = 0; j < width; j++) - { - dst_data[(height-1-i)*width+j] = - (UINT16)( - ((image[(i*width+j)*3]>>3)<<11) | - ((image[(i*width+j)*3+1]>>2)<<5) | - ((image[(i*width+j)*3+2]>>3))); - } - } - free(image); + memcpy(row, top, dst_stride); + memcpy(top, bottom, dst_stride); + memcpy(bottom, row, dst_stride); + top += dst_stride; + bottom -= dst_stride; } + free(row); } - // -----------------+ // GClipRect : Defines the 2D hardware clipping window // -----------------+ @@ -1704,7 +1135,7 @@ EXPORT void HWRAPI(GClipRect) (INT32 minx, INT32 miny, INT32 maxx, INT32 maxy, f // -----------------+ EXPORT void HWRAPI(ClearBuffer) (FBOOLEAN ColorMask, FBOOLEAN DepthMask, - FBOOLEAN StencilMask, + FBOOLEAN StencilMask, FRGBAFloat * ClearColor) { //GL_DBG_Printf("ClearBuffer(%d)\n", alpha); @@ -1734,9 +1165,6 @@ EXPORT void HWRAPI(ClearBuffer) (FBOOLEAN ColorMask, pglClear(ClearMask); pglEnableClientState(GL_VERTEX_ARRAY); // We always use this one pglEnableClientState(GL_TEXTURE_COORD_ARRAY); // And mostly this one, too - - if (!gl_palette_initialized) - InitPalette(0, false); // just gonna put this here for now } @@ -1937,6 +1365,7 @@ EXPORT void HWRAPI(UpdateTexture) (FTextureInfo *pTexInfo) const GLvoid *ptex = tex; INT32 w, h; GLuint texnum = 0; + if (!pTexInfo->downloaded) { @@ -1952,6 +1381,8 @@ EXPORT void HWRAPI(UpdateTexture) (FTextureInfo *pTexInfo) w = pTexInfo->width; h = pTexInfo->height; + if (w*h > 2048*2048 && pTexInfo->grInfo.format != GL_RGBA) + I_Error("Tried to convert too big texture: %dx%d", w, h); if ((pTexInfo->grInfo.format == GR_TEXFMT_P_8) || (pTexInfo->grInfo.format == GR_TEXFMT_AP_88)) @@ -2058,12 +1489,23 @@ EXPORT void HWRAPI(UpdateTexture) (FTextureInfo *pTexInfo) //pglTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); if (MipMap) { - pgluBuild2DMipmaps(GL_TEXTURE_2D, GL_LUMINANCE_ALPHA, w, h, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + if ((majorGL == 1 && minorGL >= 4) || (majorGL == 2)) + { + pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); + pglTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + } +#ifdef GL_VERSION_3_0 + else if (majorGL >= 3) + { + pglTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + pglGenerateMipmap(GL_TEXTURE_2D); + } +#endif pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); if (pTexInfo->flags & TF_TRANSPARENT) pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 0); // No mippmaps on transparent stuff else - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 16); //pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_LINEAR_MIPMAP_LINEAR); } else @@ -2079,12 +1521,23 @@ EXPORT void HWRAPI(UpdateTexture) (FTextureInfo *pTexInfo) //pglTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); if (MipMap) { - pgluBuild2DMipmaps(GL_TEXTURE_2D, GL_ALPHA, w, h, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + if ((majorGL == 1 && minorGL >= 4) || (majorGL == 2)) + { + pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); + pglTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + } +#ifdef GL_VERSION_3_0 + else if (majorGL >= 3) + { + pglTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + pglGenerateMipmap(GL_TEXTURE_2D); + } +#endif pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); if (pTexInfo->flags & TF_TRANSPARENT) pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 0); // No mippmaps on transparent stuff else - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 16); //pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_LINEAR_MIPMAP_LINEAR); } else @@ -2099,13 +1552,24 @@ EXPORT void HWRAPI(UpdateTexture) (FTextureInfo *pTexInfo) { if (MipMap) { - pgluBuild2DMipmaps(GL_TEXTURE_2D, textureformatGL, w, h, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + if ((majorGL == 1 && minorGL >= 4) || (majorGL == 2)) + { + pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); + pglTexImage2D(GL_TEXTURE_2D, 0, textureformatGL, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + } +#ifdef GL_VERSION_3_0 + else if (majorGL >= 3) + { + pglTexImage2D(GL_TEXTURE_2D, 0, textureformatGL, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + pglGenerateMipmap(GL_TEXTURE_2D); + } +#endif // Control the mipmap level of detail pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); // the lower the number, the higer the detail if (pTexInfo->flags & TF_TRANSPARENT) pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 0); // No mippmaps on transparent stuff else - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 5); + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 16); } else { @@ -2163,43 +1627,32 @@ EXPORT void HWRAPI(SetTexture) (FTextureInfo *pTexInfo) } } - -static void *Shader_Load(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade) -{ -#ifdef GL_SHADERS - if (gl_shadersenabled && pglUseProgram) - { - gl_shaderprogram_t *shader = &gl_shaderprograms[gl_currentshaderprogram]; - if (shader->program) - { - if (gl_shaderprogramchanged) - { - pglUseProgram(gl_shaderprograms[gl_currentshaderprogram].program); - gl_shaderprogramchanged = false; - } - Shader_SetUniforms(Surface, poly, tint, fade); - return shader; - } - else - pglUseProgram(0); - } -#else - (void)Surface; - (void)poly; - (void)tint; - (void)fade; -#endif - return NULL; -} - static void Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade) { #ifdef GL_SHADERS - if (gl_shadersenabled) + gl_shader_t *shader = gl_shaderstate.current; + + if (gl_shadersenabled && (shader != NULL) && pglUseProgram) { - gl_shaderprogram_t *shader = &gl_shaderprograms[gl_currentshaderprogram]; if (!shader->program) + { + pglUseProgram(0); return; + } + + if (gl_shaderstate.changed) + { + pglUseProgram(shader->program); + gl_shaderstate.changed = false; + } + + // Color uniforms can be left NULL and will be set to white (1.0f, 1.0f, 1.0f, 1.0f) + if (poly == NULL) + poly = &shader_defaultcolor; + if (tint == NULL) + tint = &shader_defaultcolor; + if (fade == NULL) + fade = &shader_defaultcolor; #define UNIFORM_1(uniform, a, function) \ if (uniform != -1) \ @@ -2221,13 +1674,15 @@ static void Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAF UNIFORM_4(shader->uniforms[gluniform_poly_color], poly->red, poly->green, poly->blue, poly->alpha, pglUniform4f); UNIFORM_4(shader->uniforms[gluniform_tint_color], tint->red, tint->green, tint->blue, tint->alpha, pglUniform4f); UNIFORM_4(shader->uniforms[gluniform_fade_color], fade->red, fade->green, fade->blue, fade->alpha, pglUniform4f); + if (Surface != NULL) { UNIFORM_1(shader->uniforms[gluniform_lighting], Surface->LightInfo.light_level, pglUniform1f); UNIFORM_1(shader->uniforms[gluniform_fade_start], Surface->LightInfo.fade_start, pglUniform1f); UNIFORM_1(shader->uniforms[gluniform_fade_end], Surface->LightInfo.fade_end, pglUniform1f); } - UNIFORM_1(shader->uniforms[gluniform_leveltime], shader_leveltime, pglUniform1f); + + UNIFORM_1(shader->uniforms[gluniform_leveltime], ((float)shader_leveltime) / TICRATE, pglUniform1f); #undef UNIFORM_1 #undef UNIFORM_2 @@ -2242,621 +1697,219 @@ static void Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAF #endif } - -// unfinished draw call batching - -// Note: could use realloc in the array reallocation code - -typedef struct +static boolean Shader_CompileProgram(gl_shader_t *shader, GLint i) { - FSurfaceInfo surf;// surf also has its own polyflags for some reason, but it seems unused - unsigned int vertsIndex;// location of verts in unsortedVertexArray - FUINT numVerts; - FBITFIELD polyFlags; - GLuint texNum; - GLuint shader; - // this tells batching that the plane belongs to a horizon line and must be drawn in correct order with the skywalls - boolean horizonSpecial; -} PolygonArrayEntry; + GLuint gl_vertShader = 0; + GLuint gl_fragShader = 0; + GLint result; + const GLchar *vert_shader = shader->vertex_shader; + const GLchar *frag_shader = shader->fragment_shader; -FOutVector* finalVertexArray = NULL;// contains subset of sorted vertices and texture coordinates to be sent to gpu -UINT32* finalVertexIndexArray = NULL;// contains indexes for glDrawElements, taking into account fan->triangles conversion -// NOTE have this alloced as 3x finalVertexArray size -int finalVertexArrayAllocSize = 65536; -//GLubyte* colorArray = NULL;// contains color data to be sent to gpu, if needed -//int colorArrayAllocSize = 65536; -// not gonna use this for now, just sort by color and change state when it changes -// later maybe when using vertex attributes if it's needed + if (shader->program) + pglDeleteProgram(shader->program); -PolygonArrayEntry* polygonArray = NULL;// contains the polygon data from DrawPolygon, waiting to be processed -int polygonArraySize = 0; -PolygonArrayEntry **polygonArraySorted = NULL;// contains sorted pointers to polygonArray -int polygonArrayAllocSize = 65536; - -FOutVector* unsortedVertexArray = NULL;// contains unsorted vertices and texture coordinates from DrawPolygon -int unsortedVertexArraySize = 0; -int unsortedVertexArrayAllocSize = 65536; - -EXPORT void HWRAPI(StartBatching) (void) -{ - //CONS_Printf("StartBatching begin\n"); - // init arrays if that has not been done yet - if (!finalVertexArray) + if (!vert_shader && !frag_shader) { - finalVertexArray = malloc(finalVertexArrayAllocSize * sizeof(FOutVector)); - finalVertexIndexArray = malloc(finalVertexArrayAllocSize * 3 * sizeof(UINT32)); - polygonArray = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry)); - polygonArraySorted = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry *)); - unsortedVertexArray = malloc(unsortedVertexArrayAllocSize * sizeof(FOutVector)); + GL_MSG_Error("Shader_CompileProgram: Missing shaders for shader program %s\n", HWR_GetShaderName(i)); + return false; } - // drawing functions will now collect the drawing data instead of passing it to opengl - gl_batching = true; - //CONS_Printf("StartBatching end\n"); -} -static int comparePolygons(const void *p1, const void *p2) -{ - PolygonArrayEntry *poly1 = *(PolygonArrayEntry *const *)p1; - PolygonArrayEntry *poly2 = *(PolygonArrayEntry *const *)p2; - int diff; - INT64 diff64; + if (vert_shader) + { + // + // Load and compile vertex shader + // + gl_vertShader = pglCreateShader(GL_VERTEX_SHADER); + if (!gl_vertShader) + { + GL_MSG_Error("Shader_CompileProgram: Error creating vertex shader %s\n", HWR_GetShaderName(i)); + return false; + } - int shader1 = poly1->shader; - int shader2 = poly2->shader; - // make skywalls and horizon lines first in order - if (poly1->polyFlags & PF_NoTexture || poly1->horizonSpecial) - shader1 = -1; - if (poly2->polyFlags & PF_NoTexture || poly2->horizonSpecial) - shader2 = -1; - diff = shader1 - shader2; - if (diff != 0) return diff; + pglShaderSource(gl_vertShader, 1, &vert_shader, NULL); + pglCompileShader(gl_vertShader); - // skywalls and horizon lines must retain their order for horizon lines to work - if (shader1 == -1 && shader2 == -1) - return poly1 - poly2; + // check for compile errors + pglGetShaderiv(gl_vertShader, GL_COMPILE_STATUS, &result); + if (result == GL_FALSE) + { + GL_MSG_Error("Error compiling vertex shader", gl_vertShader, i); + pglDeleteShader(gl_vertShader); + return false; + } + } - diff = poly1->texNum - poly2->texNum; - if (diff != 0) return diff; + if (frag_shader) + { + // + // Load and compile fragment shader + // + gl_fragShader = pglCreateShader(GL_FRAGMENT_SHADER); + if (!gl_fragShader) + { + GL_MSG_Error("Shader_CompileProgram: Error creating fragment shader %s\n", HWR_GetShaderName(i)); + pglDeleteShader(gl_vertShader); + pglDeleteShader(gl_fragShader); + return false; + } + + pglShaderSource(gl_fragShader, 1, &frag_shader, NULL); + pglCompileShader(gl_fragShader); + + // check for compile errors + pglGetShaderiv(gl_fragShader, GL_COMPILE_STATUS, &result); + if (result == GL_FALSE) + { + GL_MSG_Error("Error compiling fragment shader", gl_fragShader, i); + pglDeleteShader(gl_vertShader); + pglDeleteShader(gl_fragShader); + return false; + } + } + + shader->program = pglCreateProgram(); + if (vert_shader) + pglAttachShader(shader->program, gl_vertShader); + if (frag_shader) + pglAttachShader(shader->program, gl_fragShader); + pglLinkProgram(shader->program); + + // check link status + pglGetProgramiv(shader->program, GL_LINK_STATUS, &result); + + // delete the shader objects + if (vert_shader) + pglDeleteShader(gl_vertShader); + if (frag_shader) + pglDeleteShader(gl_fragShader); - if (gl_use_palette_shader) + // couldn't link? + if (result != GL_TRUE) { - diff = poly1->surf.LightTableId - poly2->surf.LightTableId; - if (diff != 0) return diff; + GL_MSG_Error("Shader_CompileProgram: Error linking shader program %s\n", HWR_GetShaderName(i)); + pglDeleteProgram(shader->program); + return false; } - diff = poly1->polyFlags - poly2->polyFlags; - if (diff != 0) return diff; + // 13062019 +#define GETUNI(uniform) pglGetUniformLocation(shader->program, uniform); - diff64 = poly1->surf.PolyColor.rgba - poly2->surf.PolyColor.rgba; - if (diff64 < 0) return -1; else if (diff64 > 0) return 1; - diff64 = poly1->surf.TintColor.rgba - poly2->surf.TintColor.rgba; - if (diff64 < 0) return -1; else if (diff64 > 0) return 1; - diff64 = poly1->surf.FadeColor.rgba - poly2->surf.FadeColor.rgba; - if (diff64 < 0) return -1; else if (diff64 > 0) return 1; + // lighting + shader->uniforms[gluniform_poly_color] = GETUNI("poly_color"); + shader->uniforms[gluniform_tint_color] = GETUNI("tint_color"); + shader->uniforms[gluniform_fade_color] = GETUNI("fade_color"); + shader->uniforms[gluniform_lighting] = GETUNI("lighting"); + shader->uniforms[gluniform_fade_start] = GETUNI("fade_start"); + shader->uniforms[gluniform_fade_end] = GETUNI("fade_end"); - diff = poly1->surf.LightInfo.light_level - poly2->surf.LightInfo.light_level; - if (diff != 0) return diff; - diff = poly1->surf.LightInfo.fade_start - poly2->surf.LightInfo.fade_start; - if (diff != 0) return diff; - diff = poly1->surf.LightInfo.fade_end - poly2->surf.LightInfo.fade_end; - return diff; + // palette rendering + shader->uniforms[gluniform_palette_tex] = GETUNI("palette_tex"); + shader->uniforms[gluniform_palette_lookup_tex] = GETUNI("palette_lookup_tex"); + shader->uniforms[gluniform_lighttable_tex] = GETUNI("lighttable_tex"); + + // misc. + shader->uniforms[gluniform_leveltime] = GETUNI("leveltime"); +#undef GETUNI + + // set permanent uniform values +#define UNIFORM_1(uniform, a, function) \ + if (uniform != -1) \ + function (uniform, a); + + pglUseProgram(shader->program); + + // texture unit numbers for the samplers used for palette rendering + UNIFORM_1(shader->uniforms[gluniform_palette_tex], 2, pglUniform1i); + UNIFORM_1(shader->uniforms[gluniform_palette_lookup_tex], 1, pglUniform1i); + UNIFORM_1(shader->uniforms[gluniform_lighttable_tex], 2, pglUniform1i); + + // restore gl shader state + pglUseProgram(gl_shaderstate.program); +#undef UNIFORM_1 + + return true; } -static int comparePolygonsNoShaders(const void *p1, const void *p2) +// code that is common between DrawPolygon and DrawIndexedTriangles +// DrawScreenTexture also can use this function for fancier screen texture drawing +// the corona thing is there too, i have no idea if that stuff works with DrawIndexedTriangles and batching +static void PreparePolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FBITFIELD PolyFlags) { - PolygonArrayEntry *poly1 = *(PolygonArrayEntry *const *)p1; - PolygonArrayEntry *poly2 = *(PolygonArrayEntry *const *)p2; - int diff; - INT64 diff64; + static GLRGBAFloat poly = {0,0,0,0}; + static GLRGBAFloat tint = {0,0,0,0}; + static GLRGBAFloat fade = {0,0,0,0}; - GLuint texNum1 = poly1->texNum; - GLuint texNum2 = poly2->texNum; - if (poly1->polyFlags & PF_NoTexture || poly1->horizonSpecial) - texNum1 = 0; - if (poly2->polyFlags & PF_NoTexture || poly2->horizonSpecial) - texNum2 = 0; - diff = texNum1 - texNum2; - if (diff != 0) return diff; + SetBlend(PolyFlags); //TODO: inline (#pragma..) - // skywalls and horizon lines must retain their order for horizon lines to work - if (texNum1 == 0 && texNum2 == 0) - return poly1 - poly2; - - diff = poly1->polyFlags - poly2->polyFlags; - if (diff != 0) return diff; - - diff64 = poly1->surf.PolyColor.rgba - poly2->surf.PolyColor.rgba; - if (diff64 < 0) return -1; else if (diff64 > 0) return 1; - - return 0; -} - -// the parameters for this functions (numPolys etc.) are used to return rendering stats -EXPORT void HWRAPI(RenderBatches) (precise_t *sSortTime, precise_t *sDrawTime, int *sNumPolys, int *sNumVerts, int *sNumCalls, int *sNumShaders, int *sNumTextures, int *sNumPolyFlags, int *sNumColors) -{ - int finalVertexWritePos = 0;// position in finalVertexArray - int finalIndexWritePos = 0;// position in finalVertexIndexArray - - int polygonReadPos = 0;// position in polygonArraySorted - - GLuint currentShader; - GLuint currentTexture; - FBITFIELD currentPolyFlags; - FSurfaceInfo currentSurfaceInfo; - - GLRGBAFloat firstPoly = {0,0,0,0}; // may be misleading but this means first PolyColor - GLRGBAFloat firstTint = {0,0,0,0}; - GLRGBAFloat firstFade = {0,0,0,0}; - - boolean needRebind = false; - - int i; - - //CONS_Printf("RenderBatches\n"); - gl_batching = false;// no longer collecting batches - if (!polygonArraySize) + // PolyColor + if (pSurf) { - *sSortTime = *sDrawTime = *sNumPolys = *sNumCalls = *sNumShaders = *sNumTextures = *sNumPolyFlags = *sNumColors = 0; - return;// nothing to draw - } - // init stats vars - *sNumPolys = polygonArraySize; - *sNumCalls = *sNumVerts = 0; - *sNumShaders = *sNumTextures = *sNumPolyFlags = *sNumColors = 1; - // init polygonArraySorted - for (i = 0; i < polygonArraySize; i++) - { - polygonArraySorted[i] = &polygonArray[i]; - } - - // sort polygons - //CONS_Printf("qsort polys\n"); - *sSortTime = I_GetPreciseTime(); - if (gl_allowshaders) - qsort(polygonArraySorted, polygonArraySize, sizeof(PolygonArrayEntry *), comparePolygons); - else - qsort(polygonArraySorted, polygonArraySize, sizeof(PolygonArrayEntry *), comparePolygonsNoShaders); - *sSortTime = I_GetPreciseTime() - *sSortTime; - //CONS_Printf("sort done\n"); - // sort order - // 1. shader - // 2. texture - // 3. polyflags - // 4. colors + light level - // not sure about order of last 2, or if it even matters - - *sDrawTime = I_GetPreciseTime(); - - currentShader = polygonArraySorted[0]->shader; - currentTexture = polygonArraySorted[0]->texNum; - currentPolyFlags = polygonArraySorted[0]->polyFlags; - currentSurfaceInfo = polygonArraySorted[0]->surf; - // For now, will sort and track the colors. Vertex attributes could be used instead of uniforms - // and a color array could replace the color calls. - - // set state for first batch - //CONS_Printf("set first state\n"); - gl_currentshaderprogram = currentShader; - gl_shaderprogramchanged = true; - if (currentPolyFlags & PF_Modulated) - { - // Poly color - firstPoly.red = byte2float[currentSurfaceInfo.PolyColor.s.red]; - firstPoly.green = byte2float[currentSurfaceInfo.PolyColor.s.green]; - firstPoly.blue = byte2float[currentSurfaceInfo.PolyColor.s.blue]; - firstPoly.alpha = byte2float[currentSurfaceInfo.PolyColor.s.alpha]; - pglColor4ubv((GLubyte*)¤tSurfaceInfo.PolyColor.s); - } - // Tint color - firstTint.red = byte2float[currentSurfaceInfo.TintColor.s.red]; - firstTint.green = byte2float[currentSurfaceInfo.TintColor.s.green]; - firstTint.blue = byte2float[currentSurfaceInfo.TintColor.s.blue]; - firstTint.alpha = byte2float[currentSurfaceInfo.TintColor.s.alpha]; - // Fade color - firstFade.red = byte2float[currentSurfaceInfo.FadeColor.s.red]; - firstFade.green = byte2float[currentSurfaceInfo.FadeColor.s.green]; - firstFade.blue = byte2float[currentSurfaceInfo.FadeColor.s.blue]; - firstFade.alpha = byte2float[currentSurfaceInfo.FadeColor.s.alpha]; - - if (gl_allowshaders) - { - Shader_Load(¤tSurfaceInfo, &firstPoly, &firstTint, &firstFade); - if (gl_use_palette_shader) + // If Modulated, mix the surface colour to the texture + if (CurrentPolyFlags & PF_Modulated) { - pglActiveTexture(GL_TEXTURE2);// this stuff could be done better but gonna do it quick like this for now - pglBindTexture(GL_TEXTURE_2D, currentSurfaceInfo.LightTableId); + // Poly color + poly.red = byte2float[pSurf->PolyColor.s.red]; + poly.green = byte2float[pSurf->PolyColor.s.green]; + poly.blue = byte2float[pSurf->PolyColor.s.blue]; + poly.alpha = byte2float[pSurf->PolyColor.s.alpha]; + + pglColor4ubv((GLubyte*)&pSurf->PolyColor.s); + } + + // Tint color + tint.red = byte2float[pSurf->TintColor.s.red]; + tint.green = byte2float[pSurf->TintColor.s.green]; + tint.blue = byte2float[pSurf->TintColor.s.blue]; + tint.alpha = byte2float[pSurf->TintColor.s.alpha]; + + // Fade color + fade.red = byte2float[pSurf->FadeColor.s.red]; + fade.green = byte2float[pSurf->FadeColor.s.green]; + fade.blue = byte2float[pSurf->FadeColor.s.blue]; + fade.alpha = byte2float[pSurf->FadeColor.s.alpha]; + + if (pSurf->LightTableId && pSurf->LightTableId != lt_downloaded) + { + pglActiveTexture(GL_TEXTURE2); + pglBindTexture(GL_TEXTURE_2D, pSurf->LightTableId); pglActiveTexture(GL_TEXTURE0); + lt_downloaded = pSurf->LightTableId; } } - if (currentPolyFlags & PF_NoTexture) - currentTexture = 0; - pglBindTexture(GL_TEXTURE_2D, currentTexture); - tex_downloaded = currentTexture; - - SetBlend(currentPolyFlags); - - //CONS_Printf("first pointers to ogl\n"); - pglVertexPointer(3, GL_FLOAT, sizeof(FOutVector), &finalVertexArray[0].x); - pglTexCoordPointer(2, GL_FLOAT, sizeof(FOutVector), &finalVertexArray[0].s); - - while (1)// note: remember handling notexture polyflag as having texture number 0 (also in comparePolygons) - { - int firstIndex; - int lastIndex; - - boolean stopFlag = false; - boolean changeState = false; - boolean changeShader = false; - GLuint nextShader = 0U; - boolean changeTexture = false; - GLuint nextTexture = 0U; - boolean changePolyFlags = false; - FBITFIELD nextPolyFlags = 0U; - boolean changeSurfaceInfo = false; - FSurfaceInfo nextSurfaceInfo; - - //CONS_Printf("loop iter start\n"); - // new try: - // write vertices - // check for changes or end, otherwise go back to writing - // changes will affect the next vars and the change bools - // end could set flag for stopping - // execute draw call - // could check ending flag here - // change states according to next vars and change bools, updating the current vars and reseting the bools - // reset write pos - // repeat loop - - PolygonArrayEntry *entry = polygonArraySorted[polygonReadPos++]; - int numVerts = entry->numVerts; - // before writing, check if there is enough room - // using 'while' instead of 'if' here makes sure that there will *always* be enough room. - // probably never will this loop run more than once though - while (finalVertexWritePos + numVerts > finalVertexArrayAllocSize) - { - FOutVector* new_array; - unsigned int* new_index_array; - //CONS_Printf("final vert realloc\n"); - finalVertexArrayAllocSize *= 2; - new_array = malloc(finalVertexArrayAllocSize * sizeof(FOutVector)); - memcpy(new_array, finalVertexArray, finalVertexWritePos * sizeof(FOutVector)); - free(finalVertexArray); - finalVertexArray = new_array; - // also increase size of index array, 3x of vertex array since - // going from fans to triangles increases vertex count to 3x - new_index_array = malloc(finalVertexArrayAllocSize * 3 * sizeof(UINT32)); - memcpy(new_index_array, finalVertexIndexArray, finalIndexWritePos * sizeof(UINT32)); - free(finalVertexIndexArray); - finalVertexIndexArray = new_index_array; - // if vertex buffers are reallocated then opengl needs to know too - needRebind = true; - } - //CONS_Printf("write verts to final\n"); - // write the vertices of the polygon - memcpy(&finalVertexArray[finalVertexWritePos], &unsortedVertexArray[entry->vertsIndex], - numVerts * sizeof(FOutVector)); - // write the indexes, pointing to the fan vertexes but in triangles format - firstIndex = finalVertexWritePos; - lastIndex = finalVertexWritePos + numVerts; - finalVertexWritePos += 2; - //CONS_Printf("write final vert indices\n"); - while (finalVertexWritePos < lastIndex) - { - finalVertexIndexArray[finalIndexWritePos++] = firstIndex; - finalVertexIndexArray[finalIndexWritePos++] = finalVertexWritePos - 1; - finalVertexIndexArray[finalIndexWritePos++] = finalVertexWritePos++; - } - - if (polygonReadPos >= polygonArraySize) - { - stopFlag = true; - } - else - { - //CONS_Printf("state change check\n"); - // check if a state change is required, set the change bools and next vars - PolygonArrayEntry *nextEntry = polygonArraySorted[polygonReadPos]; - nextShader = nextEntry->shader; - nextTexture = nextEntry->texNum; - nextPolyFlags = nextEntry->polyFlags; - nextSurfaceInfo = nextEntry->surf; - if (nextPolyFlags & PF_NoTexture) - nextTexture = 0; - if (currentShader != nextShader) - { - changeState = true; - changeShader = true; - } - if (currentTexture != nextTexture) - { - changeState = true; - changeTexture = true; - } - if (currentPolyFlags != nextPolyFlags) - { - changeState = true; - changePolyFlags = true; - } - if ((gl_allowshaders) && (gl_use_palette_shader)) - { - if (currentSurfaceInfo.PolyColor.rgba != nextSurfaceInfo.PolyColor.rgba || - currentSurfaceInfo.TintColor.rgba != nextSurfaceInfo.TintColor.rgba || - currentSurfaceInfo.FadeColor.rgba != nextSurfaceInfo.FadeColor.rgba || - currentSurfaceInfo.LightInfo.light_level != nextSurfaceInfo.LightInfo.light_level || - currentSurfaceInfo.LightInfo.fade_start != nextSurfaceInfo.LightInfo.fade_start || - currentSurfaceInfo.LightInfo.fade_end != nextSurfaceInfo.LightInfo.fade_end || - currentSurfaceInfo.LightTableId != nextSurfaceInfo.LightTableId) - { - changeState = true; - changeSurfaceInfo = true; - } - } - else if ((gl_allowshaders) && (!gl_use_palette_shader)) - { - if (currentSurfaceInfo.PolyColor.rgba != nextSurfaceInfo.PolyColor.rgba || - currentSurfaceInfo.TintColor.rgba != nextSurfaceInfo.TintColor.rgba || - currentSurfaceInfo.FadeColor.rgba != nextSurfaceInfo.FadeColor.rgba || - currentSurfaceInfo.LightInfo.light_level != nextSurfaceInfo.LightInfo.light_level || - currentSurfaceInfo.LightInfo.fade_start != nextSurfaceInfo.LightInfo.fade_start || - currentSurfaceInfo.LightInfo.fade_end != nextSurfaceInfo.LightInfo.fade_end) - { - changeState = true; - changeSurfaceInfo = true; - } - } - else - { - if (currentSurfaceInfo.PolyColor.rgba != nextSurfaceInfo.PolyColor.rgba) - { - changeState = true; - changeSurfaceInfo = true; - } - } - } - - if (changeState || stopFlag) - { - if (needRebind) - { - //CONS_Printf("rebind\n"); - pglVertexPointer(3, GL_FLOAT, sizeof(FOutVector), &finalVertexArray[0].x); - pglTexCoordPointer(2, GL_FLOAT, sizeof(FOutVector), &finalVertexArray[0].s); - needRebind = false; - } - //CONS_Printf("exec draw call\n"); - // execute draw call - pglDrawElements(GL_TRIANGLES, finalIndexWritePos, GL_UNSIGNED_INT, finalVertexIndexArray); - //CONS_Printf("draw call done\n"); - // update stats - (*sNumCalls)++; - *sNumVerts += finalIndexWritePos; - // reset write positions - finalVertexWritePos = 0; - finalIndexWritePos = 0; - } - else continue; - - // if we're here then either its time to stop or time to change state - if (stopFlag) break; - - //CONS_Printf("state change\n"); - - // change state according to change bools and next vars, update current vars and reset bools - if (changeShader) - { - GLRGBAFloat poly = {0,0,0,0}; - GLRGBAFloat tint = {0,0,0,0}; - GLRGBAFloat fade = {0,0,0,0}; - gl_currentshaderprogram = nextShader; - gl_shaderprogramchanged = true; - if (nextPolyFlags & PF_Modulated) - { - // Poly color - poly.red = byte2float[nextSurfaceInfo.PolyColor.s.red]; - poly.green = byte2float[nextSurfaceInfo.PolyColor.s.green]; - poly.blue = byte2float[nextSurfaceInfo.PolyColor.s.blue]; - poly.alpha = byte2float[nextSurfaceInfo.PolyColor.s.alpha]; - } - // Tint color - tint.red = byte2float[nextSurfaceInfo.TintColor.s.red]; - tint.green = byte2float[nextSurfaceInfo.TintColor.s.green]; - tint.blue = byte2float[nextSurfaceInfo.TintColor.s.blue]; - tint.alpha = byte2float[nextSurfaceInfo.TintColor.s.alpha]; - // Fade color - fade.red = byte2float[nextSurfaceInfo.FadeColor.s.red]; - fade.green = byte2float[nextSurfaceInfo.FadeColor.s.green]; - fade.blue = byte2float[nextSurfaceInfo.FadeColor.s.blue]; - fade.alpha = byte2float[nextSurfaceInfo.FadeColor.s.alpha]; - - Shader_Load(&nextSurfaceInfo, &poly, &tint, &fade); - currentShader = nextShader; - changeShader = false; - - (*sNumShaders)++; - } - if (changeTexture) - { - // texture should be already ready for use from calls to SetTexture during batch collection - pglBindTexture(GL_TEXTURE_2D, nextTexture); - tex_downloaded = nextTexture; - currentTexture = nextTexture; - changeTexture = false; - - (*sNumTextures)++; - } - if (changePolyFlags) - { - SetBlend(nextPolyFlags); - currentPolyFlags = nextPolyFlags; - changePolyFlags = false; - - (*sNumPolyFlags)++; - } - if (changeSurfaceInfo) - { - GLRGBAFloat poly = {0,0,0,0}; - GLRGBAFloat tint = {0,0,0,0}; - GLRGBAFloat fade = {0,0,0,0}; - gl_shaderprogramchanged = false; - if (nextPolyFlags & PF_Modulated) - { - // Poly color - poly.red = byte2float[nextSurfaceInfo.PolyColor.s.red]; - poly.green = byte2float[nextSurfaceInfo.PolyColor.s.green]; - poly.blue = byte2float[nextSurfaceInfo.PolyColor.s.blue]; - poly.alpha = byte2float[nextSurfaceInfo.PolyColor.s.alpha]; - pglColor4ubv((GLubyte*)&nextSurfaceInfo.PolyColor.s); - } - if (gl_allowshaders) - { - // Tint color - tint.red = byte2float[nextSurfaceInfo.TintColor.s.red]; - tint.green = byte2float[nextSurfaceInfo.TintColor.s.green]; - tint.blue = byte2float[nextSurfaceInfo.TintColor.s.blue]; - tint.alpha = byte2float[nextSurfaceInfo.TintColor.s.alpha]; - // Fade color - fade.red = byte2float[nextSurfaceInfo.FadeColor.s.red]; - fade.green = byte2float[nextSurfaceInfo.FadeColor.s.green]; - fade.blue = byte2float[nextSurfaceInfo.FadeColor.s.blue]; - fade.alpha = byte2float[nextSurfaceInfo.FadeColor.s.alpha]; - - Shader_Load(&nextSurfaceInfo, &poly, &tint, &fade); - - if (gl_use_palette_shader) - { - pglActiveTexture(GL_TEXTURE2);// this stuff could be done better but gonna do it quick like this for now - pglBindTexture(GL_TEXTURE_2D, nextSurfaceInfo.LightTableId); - pglActiveTexture(GL_TEXTURE0); - } - } - - currentSurfaceInfo = nextSurfaceInfo; - changeSurfaceInfo = false; - - (*sNumColors)++; - } - // and that should be it? - } - // reset the arrays (set sizes to 0) - polygonArraySize = 0; - unsortedVertexArraySize = 0; - - *sDrawTime = I_GetPreciseTime() - *sDrawTime; + Shader_SetUniforms(pSurf, &poly, &tint, &fade); } // -----------------+ // DrawPolygon : Render a polygon, set the texture, set render mode // -----------------+ -EXPORT void HWRAPI(DrawPolygon) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, boolean horizonSpecial) +EXPORT void HWRAPI(DrawPolygon) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags) { - if (gl_batching) - { - //CONS_Printf("Batched DrawPolygon\n"); - if (!pSurf) - I_Error("Got a null FSurfaceInfo in batching");// nulls should only come in sky background pic drawing - if (polygonArraySize == polygonArrayAllocSize) - { - PolygonArrayEntry* new_array; - // ran out of space, make new array double the size - polygonArrayAllocSize *= 2; - new_array = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry)); - memcpy(new_array, polygonArray, polygonArraySize * sizeof(PolygonArrayEntry)); - free(polygonArray); - polygonArray = new_array; - // also need to redo the index array, dont need to copy it though - free(polygonArraySorted); - polygonArraySorted = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry *)); - } + PreparePolygon(pSurf, pOutVerts, PolyFlags); - while (unsortedVertexArraySize + (int)iNumPts > unsortedVertexArrayAllocSize) - { - FOutVector* new_array; - // need more space for vertices in unsortedVertexArray - unsortedVertexArrayAllocSize *= 2; - new_array = malloc(unsortedVertexArrayAllocSize * sizeof(FOutVector)); - memcpy(new_array, unsortedVertexArray, unsortedVertexArraySize * sizeof(FOutVector)); - free(unsortedVertexArray); - unsortedVertexArray = new_array; - } + pglVertexPointer(3, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].x); + pglTexCoordPointer(2, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].s); + pglDrawArrays(GL_TRIANGLE_FAN, 0, iNumPts); - // add the polygon data to the arrays + if (PolyFlags & PF_RemoveYWrap) + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - polygonArray[polygonArraySize].surf = *pSurf; - polygonArray[polygonArraySize].vertsIndex = unsortedVertexArraySize; - polygonArray[polygonArraySize].numVerts = iNumPts; - polygonArray[polygonArraySize].polyFlags = PolyFlags; - polygonArray[polygonArraySize].texNum = tex_downloaded; - polygonArray[polygonArraySize].shader = gl_currentshaderprogram; - polygonArray[polygonArraySize].horizonSpecial = horizonSpecial; - polygonArraySize++; + if (PolyFlags & PF_ForceWrapX) + Clamp2D(GL_TEXTURE_WRAP_S); - memcpy(&unsortedVertexArray[unsortedVertexArraySize], pOutVerts, iNumPts * sizeof(FOutVector)); - unsortedVertexArraySize += iNumPts; - } - else - { - static GLRGBAFloat poly = {0,0,0,0}; - static GLRGBAFloat tint = {0,0,0,0}; - static GLRGBAFloat fade = {0,0,0,0}; + if (PolyFlags & PF_ForceWrapY) + Clamp2D(GL_TEXTURE_WRAP_T); +} - SetBlend(PolyFlags); //TODO: inline (#pragma..) +EXPORT void HWRAPI(DrawIndexedTriangles) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, unsigned int *IndexArray) +{ + PreparePolygon(pSurf, pOutVerts, PolyFlags); - if (gl_portal_mode == HWD_PORTAL_NORMAL) - { - // PolyColor - if (pSurf) - { - // If Modulated, mix the surface colour to the texture - if (CurrentPolyFlags & PF_Modulated) - { - // Poly color - poly.red = byte2float[pSurf->PolyColor.s.red]; - poly.green = byte2float[pSurf->PolyColor.s.green]; - poly.blue = byte2float[pSurf->PolyColor.s.blue]; - poly.alpha = byte2float[pSurf->PolyColor.s.alpha]; + pglVertexPointer(3, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].x); + pglTexCoordPointer(2, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].s); + pglDrawElements(GL_TRIANGLES, iNumPts, GL_UNSIGNED_INT, IndexArray); - pglColor4ubv((GLubyte*)&pSurf->PolyColor.s); - } - - // Tint color - tint.red = byte2float[pSurf->TintColor.s.red]; - tint.green = byte2float[pSurf->TintColor.s.green]; - tint.blue = byte2float[pSurf->TintColor.s.blue]; - tint.alpha = byte2float[pSurf->TintColor.s.alpha]; - - // Fade color - fade.red = byte2float[pSurf->FadeColor.s.red]; - fade.green = byte2float[pSurf->FadeColor.s.green]; - fade.blue = byte2float[pSurf->FadeColor.s.blue]; - fade.alpha = byte2float[pSurf->FadeColor.s.alpha]; - - if (gl_use_palette_shader && gl_allowshaders) - { - pglActiveTexture(GL_TEXTURE2); - pglBindTexture(GL_TEXTURE_2D, pSurf->LightTableId); - pglActiveTexture(GL_TEXTURE0); - } - } - - Shader_Load(pSurf, &poly, &tint, &fade); - } - else - UnSetShader(); - - pglVertexPointer(3, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].x); - pglTexCoordPointer(2, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].s); - pglDrawArrays(GL_TRIANGLE_FAN, 0, iNumPts); - - if (PolyFlags & PF_RemoveYWrap) - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - - if (PolyFlags & PF_ForceWrapX) - Clamp2D(GL_TEXTURE_WRAP_S); - - if (PolyFlags & PF_ForceWrapY) - Clamp2D(GL_TEXTURE_WRAP_T); - } + // the DrawPolygon variant of this has some code about polyflags and wrapping here but havent noticed any problems from omitting it? } // Sky dome code, taken/backported from SRB2 @@ -2949,54 +2002,6 @@ static void SkyVertex(vbo_vertex_t *vbo, int r, int c) vbo->z = z; } -void RevertStencilBuffer()// TODO need to add OpenGL stencil functions to function importing -{ - /*const float screenVerts[12] = - { - -1.0f, -1.0f, 1.0f, - -1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, - 1.0f, -1.0f, 1.0f - };*/ - - const float screenVerts[12] = - { - -1.0f, -1.0f, 1.0f, - 1.0f, -1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, - -1.0f, 1.0f, 1.0f - }; - - pglDisableClientState(GL_TEXTURE_COORD_ARRAY); - pglDisable(GL_TEXTURE_2D); - pglDisable(GL_DEPTH_TEST); - pglDisable(GL_BLEND); - //pglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); - pglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);// TEST - - //pglStencilFuncSeparate(GL_FRONT_AND_BACK, GL_EQUAL, gl_portal_stencil_level + 1, 0xFF); - //pglStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, gl_portal_stencil_level + 1, 0xFF);// TEST - //pglStencilOpSeparate(GL_FRONT_AND_BACK, GL_KEEP, GL_DECR, GL_DECR); - //pglStencilOpSeparate(GL_FRONT_AND_BACK, GL_KEEP, GL_KEEP, GL_KEEP);// TEST - - pglPushMatrix(); - pglLoadIdentity(); - pglScalef(1.0f, 1.0f, -1.0f); -// glMatrixMode(GL_PROJECTION - - pglColor4ubv(white); - pglVertexPointer(3, GL_FLOAT, 0, screenVerts); - pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - pglPopMatrix(); - - pglEnableClientState(GL_TEXTURE_COORD_ARRAY); - pglEnable(GL_TEXTURE_2D); - pglEnable(GL_DEPTH_TEST); - pglEnable(GL_BLEND); - pglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); -} - static GLSkyVBO sky_vbo; static void gld_BuildSky(int row_count, int col_count) @@ -3169,19 +2174,7 @@ EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value) switch (IdState) { case HWD_SET_SHADERS: - switch (Value) - { - case 1: - gl_allowshaders = true; - break; - default: - gl_allowshaders = false; - break; - } - break; - - case HWD_SET_PALETTE_SHADER_ENABLED: - gl_use_palette_shader = Value; + gl_allowshaders = Value; break; case HWD_SET_TEXTUREFILTERMODE: @@ -3219,11 +2212,22 @@ EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value) mag_filter = GL_LINEAR; min_filter = GL_NEAREST; } - if (!pgluBuild2DMipmaps) + if (majorGL == 1 && minorGL <= 3) { MipMap = GL_FALSE; min_filter = GL_LINEAR; } +#ifdef GL_VERSION_3_0 + else + { + if (!pglGenerateMipmap) + { + MipMap = GL_FALSE; + min_filter = GL_LINEAR; + } + } +#endif + Flush(); //??? if we want to change filter mode by texture, remove this break; @@ -3245,18 +2249,6 @@ EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value) case HWD_SET_SCREEN_TEXTURES: gl_enable_screen_textures = Value; break; - - case HWD_SET_DEPTH_ONLY_MODE:// for portals - if (Value) - { - pglClear(GL_DEPTH_BUFFER_BIT); - pglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); - } - else - { - pglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - } - break; case HWD_SET_PORTAL_MODE: gl_portal_mode = Value; @@ -3269,7 +2261,6 @@ EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value) pglEnable(GL_BLEND); pglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); pglStencilFuncSeparate(GL_FRONT_AND_BACK, GL_EQUAL, gl_portal_stencil_level, 0xFF); - //pglStencilFuncSeparate(GL_FRONT_AND_BACK, GL_GEQUAL, 0, 0xFF); pglStencilOpSeparate(GL_FRONT_AND_BACK, GL_KEEP, GL_KEEP, GL_KEEP); pglDepthMask(GL_TRUE); break; @@ -3295,8 +2286,6 @@ EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value) break; case HWD_PORTAL_DEPTH_SEGS: // draw only to depth, only to current level of stencil - // also revert last stencil buffer write at this point - //RevertStencilBuffer(); pglDisable(GL_TEXTURE_2D); pglEnable(GL_DEPTH_TEST); pglDisable(GL_BLEND); @@ -3531,7 +2520,7 @@ EXPORT void HWRAPI(CreateModelVBOs) (model_t *model) #define BUFFER_OFFSET(i) ((char*)(i)) -static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, FSurfaceInfo *Surface) +static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface) { static GLRGBAFloat poly = {0,0,0,0}; static GLRGBAFloat tint = {0,0,0,0}; @@ -3585,19 +2574,28 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float fade.green = byte2float[Surface->FadeColor.s.green]; fade.blue = byte2float[Surface->FadeColor.s.blue]; fade.alpha = byte2float[Surface->FadeColor.s.alpha]; + + if (Surface->LightTableId && Surface->LightTableId != lt_downloaded) + { + pglActiveTexture(GL_TEXTURE2); + pglBindTexture(GL_TEXTURE_2D, Surface->LightTableId); + pglActiveTexture(GL_TEXTURE0); + lt_downloaded = Surface->LightTableId; + } - Shader_Load(Surface, &poly, &tint, &fade); + Shader_SetUniforms(Surface, &poly, &tint, &fade); pglEnable(GL_CULL_FACE); pglEnable(GL_NORMALIZE); #ifdef USE_FTRANSFORM_MIRROR - // flipped is if the object is flipped + // flipped is if the object is vertically flipped + // hflipped is if the object is horizontally flipped // pos->flip is if the screen is flipped vertically // pos->mirror is if the screen is flipped horizontally // XOR all the flips together to figure out what culling to use! { - boolean reversecull = (flipped ^ pos->flip ^ pos->mirror); + boolean reversecull = (flipped ^ hflipped ^ pos->flip ^ pos->mirror); if (reversecull) pglCullFace(GL_FRONT); else @@ -3605,7 +2603,7 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float } #else // pos->flip is if the screen is flipped too - if (flipped != pos->flip) // If either are active, but not both, invert the model's culling + if (flipped ^ hflipped ^ pos->flip) // If one or three of these are active, but not two, invert the model's culling pglCullFace(GL_FRONT); else pglCullFace(GL_BACK); @@ -3615,22 +2613,32 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float pglTranslatef(pos->x, pos->z, pos->y); if (flipped) scaley = -scaley; + if (hflipped) + scalez = -scalez; #ifdef USE_FTRANSFORM_ANGLEZ - pglRotatef(pos->anglez, 0.0f, 0.0f, -1.0f); // rotate by slope from Kart + pglRotatef(pos->anglez2, 0.0f, 0.0f, -1.0f); // rotate by slope from Kart #endif - pglRotatef(pos->anglex, -1.0f, 0.0f, 0.0f); + pglRotatef(pos->anglex2, -1.0f, 0.0f, 0.0f); pglRotatef(pos->angley, 0.0f, -1.0f, 0.0f); if (pos->roll) { float roll = (1.0f * pos->rollflip); pglTranslatef(pos->centerx, pos->centery, 0); + + // rotate model for pitch and roll + pglRotatef(pos->anglex, 1.0f, 0.0f, 0.0f); +#ifdef USE_FTRANSFORM_ANGLEZ + pglRotatef(pos->anglez, 0.0f, 0.0f, -1.0f); +#endif + if (pos->rotaxis == 2) // Z pglRotatef(pos->rollangle, 0.0f, 0.0f, roll); else if (pos->rotaxis == 1) // Y pglRotatef(pos->rollangle, 0.0f, roll, 0.0f); else // X pglRotatef(pos->rollangle, roll, 0.0f, 0.0f); + pglTranslatef(-pos->centerx, -pos->centery, 0); } @@ -3743,9 +2751,9 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float // -----------------+ // HWRAPI DrawModel : Draw a model // -----------------+ -EXPORT void HWRAPI(DrawModel) (model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, FSurfaceInfo *Surface) +EXPORT void HWRAPI(DrawModel) (model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface) { - DrawModelEx(model, frameIndex, duration, tics, nextFrameIndex, pos, hscale, vscale, flipped, Surface); + DrawModelEx(model, frameIndex, duration, tics, nextFrameIndex, pos, hscale, vscale, flipped, hflipped, Surface); } // -----------------+ @@ -3799,6 +2807,8 @@ EXPORT void HWRAPI(SetTransform) (FTransform *stransform) if (shearing) { float dy = FIXED_TO_FLOAT(AIMINGTODY(stransform->viewaiming)) * 2; //screen_width/BASEVIDWIDTH; + if (stransform->flip) + dy *= -1.0f; pglTranslatef(0.0f, -dy/BASEVIDHEIGHT, 0.0f); } @@ -3858,7 +2868,7 @@ EXPORT void HWRAPI(PostImgRedraw) (float points[SCREENVERTS][SCREENVERTS][2]) 16.0f, 16.0f, 6.0f, 16.0f, -16.0f, 6.0f }; - + if (!gl_enable_screen_textures) return; // look for power of two that is large enough for the screen @@ -3933,77 +2943,13 @@ EXPORT void HWRAPI(PostImgRedraw) (float points[SCREENVERTS][SCREENVERTS][2]) // a new size EXPORT void HWRAPI(FlushScreenTextures) (void) { - pglDeleteTextures(1, &screentexture); - pglDeleteTextures(1, &startScreenWipe); - pglDeleteTextures(1, &endScreenWipe); - pglDeleteTextures(1, &finalScreenTexture); - - screentexture = 0; - startScreenWipe = 0; - endScreenWipe = 0; - finalScreenTexture = 0; + int i; + pglDeleteTextures(NUMSCREENTEXTURES, screenTextures); + for (i = 0; i < NUMSCREENTEXTURES; i++) + screenTextures[i] = 0; } -// Create Screen to fade from -EXPORT void HWRAPI(StartScreenWipe) (void) -{ - INT32 texsize = 512; - boolean firstTime = (startScreenWipe == 0); - - // look for power of two that is large enough for the screen - while (texsize < screen_width || texsize < screen_height) - texsize <<= 1; - - // Create screen texture - if (firstTime) - pglGenTextures(1, &startScreenWipe); - pglBindTexture(GL_TEXTURE_2D, startScreenWipe); - - if (firstTime) - { - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - Clamp2D(GL_TEXTURE_WRAP_S); - Clamp2D(GL_TEXTURE_WRAP_T); - pglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, texsize, texsize, 0); - } - else - pglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, texsize, texsize); - - tex_downloaded = startScreenWipe; -} - -// Create Screen to fade to -EXPORT void HWRAPI(EndScreenWipe)(void) -{ - INT32 texsize = 512; - boolean firstTime = (endScreenWipe == 0); - - // look for power of two that is large enough for the screen - while (texsize < screen_width || texsize < screen_height) - texsize <<= 1; - - // Create screen texture - if (firstTime) - pglGenTextures(1, &endScreenWipe); - pglBindTexture(GL_TEXTURE_2D, endScreenWipe); - - if (firstTime) - { - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - Clamp2D(GL_TEXTURE_WRAP_S); - Clamp2D(GL_TEXTURE_WRAP_T); - pglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, texsize, texsize, 0); - } - else - pglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, texsize, texsize); - - tex_downloaded = endScreenWipe; -} - -// Draw the last scene under the intermission -EXPORT void HWRAPI(DrawIntermissionBG)(void) +EXPORT void HWRAPI(DrawScreenTexture)(int tex, FSurfaceInfo *surf, FBITFIELD polyflags) { float xfix, yfix; INT32 texsize = 512; @@ -4017,6 +2963,8 @@ EXPORT void HWRAPI(DrawIntermissionBG)(void) }; float fix[8]; + + if (!gl_enable_screen_textures) return; // look for power of two that is large enough for the screen while (texsize < screen_width || texsize < screen_height) @@ -4025,6 +2973,9 @@ EXPORT void HWRAPI(DrawIntermissionBG)(void) xfix = 1/((float)(texsize)/((float)((screen_width)))); yfix = 1/((float)(texsize)/((float)((screen_height)))); + // const float screenVerts[12] + + // float fix[8]; fix[0] = 0.0f; fix[1] = 0.0f; fix[2] = 0.0f; @@ -4035,17 +2986,23 @@ EXPORT void HWRAPI(DrawIntermissionBG)(void) fix[7] = 0.0f; pglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); - pglBindTexture(GL_TEXTURE_2D, screentexture); - pglColor4ubv(white); + + pglBindTexture(GL_TEXTURE_2D, screenTextures[tex]); + + PreparePolygon(surf, NULL, surf ? polyflags : (PF_NoDepthTest)); + if (!surf) + pglColor4ubv(white); + pglTexCoordPointer(2, GL_FLOAT, 0, fix); pglVertexPointer(3, GL_FLOAT, 0, screenVerts); pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); - tex_downloaded = screentexture; + tex_downloaded = screenTextures[tex]; } + // Do screen fades! -EXPORT void HWRAPI(DoScreenWipe)(void) +EXPORT void HWRAPI(DoScreenWipe)(int wipeStart, int wipeEnd) { INT32 texsize = 512; float xfix, yfix; @@ -4077,6 +3034,9 @@ EXPORT void HWRAPI(DoScreenWipe)(void) xfix = 1/((float)(texsize)/((float)((screen_width)))); yfix = 1/((float)(texsize)/((float)((screen_height)))); + // const float screenVerts[12] + + // float fix[8]; fix[0] = 0.0f; fix[1] = 0.0f; fix[2] = 0.0f; @@ -4092,7 +3052,7 @@ EXPORT void HWRAPI(DoScreenWipe)(void) pglEnable(GL_TEXTURE_2D); // Draw the original screen - pglBindTexture(GL_TEXTURE_2D, startScreenWipe); + pglBindTexture(GL_TEXTURE_2D, screenTextures[wipeStart]); pglColor4ubv(white); pglTexCoordPointer(2, GL_FLOAT, 0, fix); pglVertexPointer(3, GL_FLOAT, 0, screenVerts); @@ -4103,7 +3063,7 @@ EXPORT void HWRAPI(DoScreenWipe)(void) // Draw the end screen that fades in pglActiveTexture(GL_TEXTURE0); pglEnable(GL_TEXTURE_2D); - pglBindTexture(GL_TEXTURE_2D, endScreenWipe); + pglBindTexture(GL_TEXTURE_2D, screenTextures[wipeEnd]); pglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); pglActiveTexture(GL_TEXTURE1); @@ -4112,6 +3072,8 @@ EXPORT void HWRAPI(DoScreenWipe)(void) pglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + // const float defaultST[8] + pglClientActiveTexture(GL_TEXTURE0); pglTexCoordPointer(2, GL_FLOAT, 0, fix); pglVertexPointer(3, GL_FLOAT, 0, screenVerts); @@ -4125,15 +3087,116 @@ EXPORT void HWRAPI(DoScreenWipe)(void) pglActiveTexture(GL_TEXTURE0); pglClientActiveTexture(GL_TEXTURE0); - tex_downloaded = endScreenWipe; + tex_downloaded = screenTextures[wipeEnd]; +} + +EXPORT void HWRAPI(RenderVhsEffect) (fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize) +{ + INT32 texsize = 512; + float xfix, yfix; + float fix[8]; + GLubyte color[4] = {255, 255, 255, 255}; + float i; + + float screenVerts[12] = + { + -1.0f, -1.0f, 1.0f, + -1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, + 1.0f, -1.0f, 1.0f + }; + + // look for power of two that is large enough for the screen + while (texsize < screen_width || texsize < screen_height) + texsize <<= 1; + + xfix = 1/((float)(texsize)/((float)((screen_width)))); + yfix = 1/((float)(texsize)/((float)((screen_height)))); + + // Slight fuzziness + MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); + SetBlend(PF_Modulated|PF_Translucent|PF_NoDepthTest); + //pglBindTexture(GL_TEXTURE_2D, screentexture); + + for (i = 0; i < 1; i += 2.f/vid.height) + { + fix[2] = (float)(rand() % 128) / -22000 * xfix; + fix[0] = fix[2]; + fix[6] = fix[0] + xfix; + fix[4] = fix[2] + xfix; + fix[1] = fix[7] = i*yfix; + fix[3] = fix[5] = (i+0.015)*yfix; + + screenVerts[1] = screenVerts[10] = 2*i - 1.0f; + screenVerts[4] = screenVerts[7] = screenVerts[1] + 0.03; + + pglColor4ubv(color); + + pglTexCoordPointer(2, GL_FLOAT, 0, fix); + pglVertexPointer(3, GL_FLOAT, 0, screenVerts); + pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); + } + + // Upward bar + MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); + //pglBindTexture(GL_TEXTURE_2D, screentexture); + color[0] = color[1] = color[2] = 190; + color[3] = 250; + pglColor4ubv(color); + + fix[0] = 0.0f; + fix[6] = xfix; + fix[2] = (float)updistort / screen_width * xfix; + fix[4] = fix[2] + fix[6]; + + screenVerts[1] = screenVerts[10] = 2.0f*upbary/screen_height - 1.0f; + screenVerts[4] = screenVerts[7] = screenVerts[1] + (float)barsize/screen_height; + + fix[1] = fix[7] = (float)upbary/screen_height * yfix; + fix[3] = fix[5] = fix[1] + (float)barsize/2/screen_height * yfix; + + pglTexCoordPointer(2, GL_FLOAT, 0, fix); + pglVertexPointer(3, GL_FLOAT, 0, screenVerts); + pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); + + fix[1] = fix[7] += (fix[3] - fix[7])*2; + screenVerts[1] = screenVerts[10] += (screenVerts[4] - screenVerts[1])*2; + pglTexCoordPointer(2, GL_FLOAT, 0, fix); + pglVertexPointer(3, GL_FLOAT, 0, screenVerts); + pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); + + // Downward bar + MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); + //pglBindTexture(GL_TEXTURE_2D, screentexture); + + fix[0] = 0.0f; + fix[6] = xfix; + fix[2] = (float)downdistort / screen_width * -xfix; + fix[4] = fix[2] + fix[6]; + + screenVerts[1] = screenVerts[10] = 2.0f*downbary/screen_height - 1.0f; + screenVerts[4] = screenVerts[7] = screenVerts[1] + (float)barsize/screen_height; + + fix[1] = fix[7] = (float)downbary/screen_height * yfix; + fix[3] = fix[5] = fix[1] + (float)barsize/2/screen_height * yfix; + + pglTexCoordPointer(2, GL_FLOAT, 0, fix); + pglVertexPointer(3, GL_FLOAT, 0, screenVerts); + pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); + + fix[1] = fix[7] += (fix[3] - fix[7])*2; + screenVerts[1] = screenVerts[10] += (screenVerts[4] - screenVerts[1])*2; + pglTexCoordPointer(2, GL_FLOAT, 0, fix); + pglVertexPointer(3, GL_FLOAT, 0, screenVerts); + pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); } // Create a texture from the screen. -EXPORT void HWRAPI(MakeScreenTexture) (void) +EXPORT void HWRAPI(MakeScreenTexture) (int tex) { INT32 texsize = 512; - boolean firstTime = (screentexture == 0); - + boolean firstTime = (screenTextures[tex] == 0); + if (!gl_enable_screen_textures) return; // look for power of two that is large enough for the screen @@ -4142,8 +3205,8 @@ EXPORT void HWRAPI(MakeScreenTexture) (void) // Create screen texture if (firstTime) - pglGenTextures(1, &screentexture); - pglBindTexture(GL_TEXTURE_2D, screentexture); + pglGenTextures(1, &screenTextures[tex]); + pglBindTexture(GL_TEXTURE_2D, screenTextures[tex]); if (firstTime) { @@ -4156,40 +3219,10 @@ EXPORT void HWRAPI(MakeScreenTexture) (void) else pglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, texsize, texsize); - tex_downloaded = screentexture; + tex_downloaded = screenTextures[tex]; } -EXPORT void HWRAPI(MakeScreenFinalTexture) (void) -{ - INT32 texsize = 512; - boolean firstTime = (finalScreenTexture == 0); - - if (!gl_enable_screen_textures) return; - - // look for power of two that is large enough for the screen - while (texsize < screen_width || texsize < screen_height) - texsize <<= 1; - - // Create screen texture - if (firstTime) - pglGenTextures(1, &finalScreenTexture); - pglBindTexture(GL_TEXTURE_2D, finalScreenTexture); - - if (firstTime) - { - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - Clamp2D(GL_TEXTURE_WRAP_S); - Clamp2D(GL_TEXTURE_WRAP_T); - pglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, texsize, texsize, 0); - } - else - pglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, texsize, texsize); - - tex_downloaded = finalScreenTexture; -} - -EXPORT void HWRAPI(DrawScreenFinalTexture)(int width, int height) +EXPORT void HWRAPI(DrawScreenFinalTexture)(int tex, int width, int height) { float xfix, yfix; float origaspect, newaspect; @@ -4199,7 +3232,7 @@ EXPORT void HWRAPI(DrawScreenFinalTexture)(int width, int height) float off[12]; float fix[8]; - + if (!gl_enable_screen_textures) return; // look for power of two that is large enough for the screen @@ -4222,6 +3255,7 @@ EXPORT void HWRAPI(DrawScreenFinalTexture)(int width, int height) yoff = newaspect / origaspect; } + // float off[12]; off[0] = -xoff; off[1] = -yoff; off[2] = 1.0f; @@ -4235,7 +3269,7 @@ EXPORT void HWRAPI(DrawScreenFinalTexture)(int width, int height) off[10] = -yoff; off[11] = 1.0f; - + // float fix[8]; fix[0] = 0.0f; fix[1] = 0.0f; fix[2] = 0.0f; @@ -4250,28 +3284,108 @@ EXPORT void HWRAPI(DrawScreenFinalTexture)(int width, int height) clearColour.red = clearColour.green = clearColour.blue = 0; clearColour.alpha = 1; ClearBuffer(true, false, false, &clearColour); - pglBindTexture(GL_TEXTURE_2D, finalScreenTexture); + SetBlend(PF_NoDepthTest); + + pglBindTexture(GL_TEXTURE_2D, screenTextures[tex]); - // prepare shader, if it is enabled - Shader_SetUniforms(NULL, NULL, NULL, NULL); - - if (gl_use_palette_shader && cv_grshaders.value) - { - pglUseProgram(gl_shaderprograms[8].program); // palette shader - pglActiveTexture(GL_TEXTURE1); - } + if (HWR_ShouldUsePaletteRendering()) + pglUseProgram(gl_shaders[SHADER_PALETTE_POSTPROCESS].program); // palette postprocess shader pglColor4ubv(white); + pglTexCoordPointer(2, GL_FLOAT, 0, fix); pglVertexPointer(3, GL_FLOAT, 0, off); pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - tex_downloaded = finalScreenTexture; - if (gl_use_palette_shader && cv_grshaders.value) + if (HWR_ShouldUsePaletteRendering()) + UnSetShader(); + + tex_downloaded = screenTextures[tex]; +} + +EXPORT void HWRAPI(SetPaletteLookup)(UINT8 *lut) +{ + GLenum internalFormat; + if (gl_version[0] == '1' || gl_version[0] == '2') { - pglUseProgram(0); + // if the OpenGL version is below 3.0, then the GL_R8 format may not be available. + // so use GL_LUMINANCE8 instead to get a single component 8-bit format + // (it is possible to have access to shaders even in some OpenGL 1.x systems, + // so palette rendering can still possibly be achieved there) + internalFormat = GL_LUMINANCE8; + } + else + { + internalFormat = GL_R8; + } + + if (!paletteLookupTex) + pglGenTextures(1, &paletteLookupTex); + pglActiveTexture(GL_TEXTURE1); + pglBindTexture(GL_TEXTURE_3D, paletteLookupTex); + pglTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + pglTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + pglTexImage3D(GL_TEXTURE_3D, 0, internalFormat, HWR_PALETTE_LUT_SIZE, HWR_PALETTE_LUT_SIZE, HWR_PALETTE_LUT_SIZE, + 0, GL_RED, GL_UNSIGNED_BYTE, lut); // should there be a safety guard here aswell as the old one had? cant really test since i dont have hardware which doesent support 3D textures + pglActiveTexture(GL_TEXTURE0); +} + +EXPORT UINT32 HWRAPI(CreateLightTable)(RGBA_t *hw_lighttable) +{ + LTListItem *item = malloc(sizeof(LTListItem)); + if (!LightTablesTail) + { + LightTablesHead = LightTablesTail = item; + } + else + { + LightTablesTail->next = item; + LightTablesTail = item; + } + item->next = NULL; + pglGenTextures(1, &item->id); + pglBindTexture(GL_TEXTURE_2D, item->id); + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + pglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, hw_lighttable); + + // restore previously bound texture + pglBindTexture(GL_TEXTURE_2D, tex_downloaded); + + return item->id; +} + +// Delete light table textures, ids given before become invalid and must not be used. +EXPORT void HWRAPI(ClearLightTables)(void) +{ + while (LightTablesHead) + { + LTListItem *item = LightTablesHead; + pglDeleteTextures(1, (GLuint *)&item->id); + LightTablesHead = item->next; + free(item); + } + + LightTablesTail = NULL; + + // we no longer have a bound light table (if we had one), we just deleted it! + lt_downloaded = 0; +} + +// This palette is used for the palette rendering postprocessing step. +EXPORT void HWRAPI(SetScreenPalette)(RGBA_t *palette) +{ + if (memcmp(screenPalette, palette, sizeof(screenPalette))) + { + memcpy(screenPalette, palette, sizeof(screenPalette)); + if (!screenPaletteTex) + pglGenTextures(1, &screenPaletteTex); + pglActiveTexture(GL_TEXTURE2); + pglBindTexture(GL_TEXTURE_1D, screenPaletteTex); + pglTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + pglTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + pglTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, palette); pglActiveTexture(GL_TEXTURE0); } } diff --git a/src/hardware/r_opengl/r_opengl.h b/src/hardware/r_opengl/r_opengl.h index 8bce7d15b..ba3cccbce 100644 --- a/src/hardware/r_opengl/r_opengl.h +++ b/src/hardware/r_opengl/r_opengl.h @@ -35,7 +35,6 @@ #else #include -#include #ifdef STATIC_OPENGL // Because of the 1.3 functions, you'll need GLext to compile it if static #define GL_GLEXT_PROTOTYPES @@ -46,6 +45,7 @@ #define _CREATE_DLL_ // necessary for Unix AND Windows #include "../../doomdef.h" #include "../hw_drv.h" +#include "../../z_zone.h" // ========================================================================== // DEFINITIONS @@ -73,10 +73,6 @@ void Flush(void); INT32 isExtAvailable(const char *extension, const GLubyte *start); void SetModelView(GLint w, GLint h); void SetStates(void); -#ifdef USE_PALETTED_TEXTURE -extern PFNGLCOLORTABLEEXTPROC glColorTableEXT; -extern GLubyte palette_tex[256*3]; -#endif #ifndef GL_EXT_texture_filter_anisotropic #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE @@ -133,8 +129,4 @@ typedef enum GLF_NOTEXENV = 0x02, } oglflags_t; -// in order for custom playpals n shit to work properly -extern boolean gl_palette_initialized; -void InitPalette(int flashnum, boolean skiplut); - #endif diff --git a/src/hardware/s_fmod/s_fmod.c b/src/hardware/s_fmod/s_fmod.c index 9dd1cacbb..5d4422bb1 100644 --- a/src/hardware/s_fmod/s_fmod.c +++ b/src/hardware/s_fmod/s_fmod.c @@ -534,9 +534,6 @@ EXPORT INT32 HWRAPI(Startup) (I_Error_t FatalErrorFunction, snddev_t *snd_dev) case FSOUND_OUTPUT_A3D: DBG_Printf("FMOD driver: A3D driver.\n"); break; - case FSOUND_OUTPUT_XBOX: - DBG_Printf("FMOD driver: Xbox driver\n"); - break; case FSOUND_OUTPUT_OSS: DBG_Printf("FMOD driver: Linux/Unix OSS (Open Sound System) driver, i.e. the kernel sound drivers.\n"); break; @@ -549,12 +546,6 @@ EXPORT INT32 HWRAPI(Startup) (I_Error_t FatalErrorFunction, snddev_t *snd_dev) case FSOUND_OUTPUT_MAC: DBG_Printf("FMOD driver: Mac SoundManager driver\n"); break; - case FSOUND_OUTPUT_PS2: - DBG_Printf("FMOD driver: PlayStation 2 driver\n"); - break; - case FSOUND_OUTPUT_GC: - DBG_Printf("FMOD driver: Gamecube driver\n"); - break; case FSOUND_OUTPUT_NOSOUND_NONREALTIME: DBG_Printf("FMOD driver: This is the same as nosound, but the sound generation is driven by FSOUND_Update\n"); break; diff --git a/src/http-mserv.c b/src/http-mserv.c index 8358a2454..08b8821d4 100644 --- a/src/http-mserv.c +++ b/src/http-mserv.c @@ -87,9 +87,13 @@ Printf_url (const char *url) { boolean startup; +#ifdef HAVE_THREADS I_lock_mutex(&con_mutex); startup = con_startup; I_unlock_mutex(con_mutex); +#else + startup = con_startup; +#endif if (cv_masterserver_debug.value) (startup ? I_OutputMsg : CONS_Printf)( @@ -540,6 +544,8 @@ HMS_fetch_rules (char *buffer, size_t buffer_size) else buffer = NULL; } + else + buffer = NULL; HMS_end(hms); diff --git a/src/hu_stuff.c b/src/hu_stuff.c index c8399407b..08c2d7c33 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -1142,6 +1142,10 @@ void HU_Ticker(void) } if (cechotimer > 0) --cechotimer; + + // Animate the desynch dots + if (hu_resynching) + resynch_ticker++; //tic tic tic tic tic HU_TickSongCredits(); } @@ -2575,54 +2579,92 @@ void HU_drawPing(INT32 x, INT32 y, UINT32 lag, INT32 flags) UINT8 *colormap = NULL; INT32 measureid = cv_pingmeasurement.value ? 1 : 0; INT32 gfxnum; // gfx to draw + + //SRB2/Kart v1.0 style + UINT8 numbars = 0; // how many ping bars do we draw? + UINT8 barcolor = 31; // color we use for the bars (green, yellow, red or black) + SINT8 i = 0; + SINT8 yoffset = 6; + INT32 dx; gfxnum = Ping_gfx_num(lag); - - if (measureid == 1) + + if (!cv_pingstyle.value) { - if (cv_ticrate.value == 2){ - V_DrawScaledPatch(x+12 - pingmeasure[measureid]->width, y+22, flags, pingmeasure[measureid]); - }else{ + if (measureid == 1) V_DrawScaledPatch(x+11 - pingmeasure[measureid]->width, y+9, flags, pingmeasure[measureid]); - } - } - - - if (cv_pingicon.value) - { - if (cv_ticrate.value == 2){ - V_DrawScaledPatch(x+2, y+13, flags, pinggfx[gfxnum]); - }else{ - V_DrawScaledPatch(x+2, y, flags, pinggfx[gfxnum]); - } - } - - - if (servermaxping && lag > servermaxping && hu_tick < 4) - { - // flash ping red if too high - colormap = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_RASPBERRY, GTC_CACHE); - } - - if (cv_pingmeasurement.value) - { - lag = (INT32)(lag * (1000.00f / TICRATE)); - } - - if (cv_ticrate.value == 2){ - x = V_DrawPingNum(x + (measureid == 1 ? 11 - pingmeasure[measureid]->width : 10), y+22, flags, lag, colormap); - }else{ - x = V_DrawPingNum(x + (measureid == 1 ? 11 - pingmeasure[measureid]->width : 10), y+9, flags, lag, colormap); - } - - if (measureid == 0){ - if (cv_ticrate.value == 2){ - V_DrawScaledPatch(x+1 - pingmeasure[measureid]->width, y+22, flags, pingmeasure[measureid]); - }else{ - V_DrawScaledPatch(x+1 - pingmeasure[measureid]->width, y+9, flags, pingmeasure[measureid]); - } - } + if (cv_pingicon.value) + V_DrawScaledPatch(x+2, y, flags, pinggfx[gfxnum]); + + if (servermaxping && lag > servermaxping && hu_tick < 4) + colormap = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_RASPBERRY, GTC_CACHE); // flash ping red if too high + + if (cv_pingmeasurement.value) + lag = (INT32)(lag * (1000.00f / TICRATE)); + + x = V_DrawPingNum(x + (measureid == 1 ? 11 - pingmeasure[measureid]->width : 10), y+9, flags, lag, colormap); + + if (measureid == 0) + V_DrawScaledPatch(x+1 - pingmeasure[measureid]->width, y+9, flags, pingmeasure[measureid]); + } + else if (cv_pingstyle.value) // old style ping + { + if (cv_pingicon.value) + { + if (lag < 4) + { + numbars = 3; + barcolor = 184; + } + else if (lag < 7) + { + numbars = 2; // Apparently ternaries w/ multiple statements don't look good in C so I decided against it. + barcolor = 103; + } + else if (lag < 10) + { + numbars = 1; + barcolor = 155; // need a better red + } + else // brazil + { + numbars = 0; + barcolor = 31; + } + } + + if (cv_pingmeasurement.value) + lag = (INT32)(lag * (1000.00f / TICRATE)); + + if (vid.width >= 640) // how sad, we're using a shit resolution. + { + if (measureid == 1) + { + //dx = x+1 - (V_SmallStringWidth(va("%dms", lag), V_ALLOWLOWERCASE|flags)/2); + //V_DrawSmallString(dx, y+4, V_ALLOWLOWERCASE|flags, va("%dms", lag)); + V_DrawRightAlignedSmallString(x+12, y+13, V_ALLOWLOWERCASE|flags, va("%dms", lag)); + } + else if (measureid == 0) + { + //dx = x+1 - (V_SmallStringWidth(va("d%d", lag), flags)/2); + //V_DrawSmallString(dx, y+4, flags, va("d%d", lag)); + V_DrawRightAlignedSmallString(x+12, y+13, flags, va("d%d", lag)); + } + } + + if (cv_pingicon.value) + { + for (i=0; (i<3); i++) // Draw the ping bar + { + V_DrawFill(x+2 *(i-1)+7, y+8+yoffset-4, 2, 8-yoffset, 31|flags); + if (i < numbars) + V_DrawFill(x+2 *(i-1)+7, y+8+yoffset-3, 1, 8-yoffset-1, barcolor|flags); + + yoffset -= 2; + } + } + } } // @@ -2715,8 +2757,11 @@ static void HU_DrawRankings(void) //else //V_DrawString(4, 188, hilicol|V_SNAPTOBOTTOM|V_SNAPTOLEFT, gametype_cons_t[gametype].strvalue); - // draw the current map in the lower right - V_DrawString(4, 188, hilicol|V_SNAPTOBOTTOM|V_SNAPTOLEFT, G_BuildMapTitle(gamemap)); + // draw the current map in the lower right if theres none just say its unknown + if (!G_BuildMapTitle(gamemap)) + V_DrawString(4, 188, hilicol|V_SNAPTOBOTTOM|V_SNAPTOLEFT, "UNKNOWN"); + else + V_DrawString(4, 188, hilicol|V_SNAPTOBOTTOM|V_SNAPTOLEFT, G_BuildMapTitle(gamemap)); if (G_GametypeHasTeams()) { diff --git a/src/i_net.h b/src/i_net.h index b9da94ec4..c3391a1ed 100644 --- a/src/i_net.h +++ b/src/i_net.h @@ -79,19 +79,24 @@ typedef struct char data[MAXPACKETLENGTH]; } ATTRPACK doomcom_t; +#ifdef HOLEPUNCH typedef struct { INT32 magic; INT32 addr; INT16 port; } ATTRPACK holepunch_t; +#endif #if defined(_MSC_VER) #pragma pack() #endif extern doomcom_t *doomcom; + +#ifdef HOLEPUNCH extern holepunch_t *holepunchpacket; +#endif /** \brief return packet in doomcom struct */ @@ -152,12 +157,14 @@ extern void (*I_NetCloseSocket)(void); /** \brief send a hole punching request */ +#ifdef HOLEPUNCH extern void (*I_NetRequestHolePunch)(INT32 node); - +#endif /** \brief register this machine on the hole punching server */ +#ifdef HOLEPUNCH extern void (*I_NetRegisterHolePunch)(void); - +#endif extern boolean (*I_Ban) (INT32 node); extern void (*I_ClearBans)(void); diff --git a/src/i_system.h b/src/i_system.h index 05826c79e..87198c923 100644 --- a/src/i_system.h +++ b/src/i_system.h @@ -369,6 +369,4 @@ const char *I_ClipboardPaste(void); void I_RegisterSysCommands(void); -void I_CursedWindowMovement(int xd, int yd); - #endif diff --git a/src/i_tcp.c b/src/i_tcp.c index 9162d61ae..81c221d27 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -201,8 +201,10 @@ static size_t broadcastaddresses = 0; static boolean nodeconnected[MAXNETNODES+1]; static banned_t *banned; /* See ../doc/Holepunch-Protocol.txt */ +#ifdef HOLEPUNCH static const INT32 hole_punch_magic = MSBF_LONG (0x52eb11); #endif +#endif static size_t numbans = 0; static size_t banned_size = 0; @@ -609,8 +611,10 @@ is_external_address (UINT32 p) } } +#ifdef HOLEPUNCH static boolean hole_punch(ssize_t c) { + /* See ../doc/Holepunch-Protocol.txt */ if (cv_rendezvousserver.string[0] && c == 10 && holepunchpacket->magic == hole_punch_magic && @@ -631,7 +635,9 @@ static boolean hole_punch(ssize_t c) { return false; } + } +#endif // Returns true if a packet was received from a new node, false in all other cases static boolean SOCK_Get(void) @@ -655,11 +661,12 @@ static boolean SOCK_Get(void) break; } #endif - +#ifdef HOLEPUNCH if (hole_punch(c)) { break; } +#endif // find remote node number for (j = 1; j <= MAXNETNODES; j++) //include LAN @@ -1363,7 +1370,7 @@ static SINT8 SOCK_NetMakeNodewPort(const char *address, const char *port) } /* See ../doc/Holepunch-Protocol.txt */ - +#ifdef HOLEPUNCH static void rendezvous(int size) { char *addrs = strdup(cv_rendezvousserver.string); @@ -1391,7 +1398,9 @@ static void rendezvous(int size) if (tic == refreshtic) { + #ifdef HOLEPUNCH holepunchpacket->magic = hole_punch_magic; + #endif sendto(mysockets[0], doomcom->data, size, 0, &rzv.any, sizeof rzv.ip4); } @@ -1417,6 +1426,8 @@ static void SOCK_RegisterHolePunch(void) } #endif +#endif + static boolean SOCK_OpenSocket(void) { #ifndef NONET @@ -1439,9 +1450,11 @@ static boolean SOCK_OpenSocket(void) I_NetCanSend = SOCK_CanSend; I_NetCanGet = SOCK_CanGet; #endif +#ifdef HOLEPUNCH I_NetRequestHolePunch = SOCK_RequestHolePunch; I_NetRegisterHolePunch = SOCK_RegisterHolePunch; +#endif // build the socket but close it first SOCK_CloseSocket(); @@ -1709,6 +1722,7 @@ boolean I_InitTcpNetwork(void) // server address only in ip if (serverhostname[0]) { + CV_Set(&cv_lastserver, serverhostname); COM_BufAddText("connect \""); COM_BufAddText(serverhostname); COM_BufAddText("\"\n"); @@ -1718,6 +1732,9 @@ boolean I_InitTcpNetwork(void) } else { + // Not quite sure if we want to save that but i'll do that for now + CV_Set(&cv_lastserver, "any"); + // so we're on a LAN COM_BufAddText("connect any\n"); diff --git a/src/k_kart.c b/src/k_kart.c index 1181acd18..3170bc143 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -8,6 +8,7 @@ #include "hu_stuff.h" #include "g_game.h" #include "m_random.h" +#include "m_menu.h" // ffdhidshfuisduifigergho9igj89dgodhfih AAAAAAAAAA #include "p_local.h" #include "p_slopes.h" #include "r_draw.h" @@ -25,54 +26,57 @@ #include "d_main.h" // found_extra_kart // Hud offset cvars -consvar_t cv_item_xoffset = {"hud_item_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_item_yoffset = {"hud_item_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +#define IMPL_HUD_OFFSET_X(name)\ +consvar_t cv_##name##_xoffset = {"hud_" #name "_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_time_xoffset = {"hud_time_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_time_yoffset = {"hud_time_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +#define IMPL_HUD_OFFSET_Y(name)\ +consvar_t cv_##name##_yoffset = {"hud_" #name "_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_laps_xoffset = {"hud_laps_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_laps_yoffset = {"hud_laps_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +#define IMPL_HUD_OFFSET(name)\ +IMPL_HUD_OFFSET_X(name)\ +IMPL_HUD_OFFSET_Y(name) -consvar_t cv_spdm_xoffset = {"hud_speed_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_spdm_yoffset = {"hud_speed_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +IMPL_HUD_OFFSET(item); // Item box +IMPL_HUD_OFFSET(time); // Time +IMPL_HUD_OFFSET(laps); // Number of laps +IMPL_HUD_OFFSET(dnft); // Countdown (did not finish timer) +IMPL_HUD_OFFSET(speed); // Speedometer +IMPL_HUD_OFFSET(posi); // Position in race +IMPL_HUD_OFFSET(face); // Mini rankings +IMPL_HUD_OFFSET(stcd); // Starting countdown +IMPL_HUD_OFFSET_Y(chek); // Check gfx +IMPL_HUD_OFFSET(mini); // Minimap +IMPL_HUD_OFFSET(want); // Wanted +IMPL_HUD_OFFSET(stat); // Stats -consvar_t cv_posi_xoffset = {"hud_position_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_posi_yoffset = {"hud_position_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_face_xoffset = {"hud_face_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_face_yoffset = {"hud_face_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_stcd_xoffset = {"hud_startcountdown_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_stcd_yoffset = {"hud_startcountdown_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_chek_yoffset = {"hud_check_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_mini_xoffset = {"hud_minimap_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_mini_yoffset = {"hud_minimap_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_want_xoffset = {"hud_wanted_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_want_yoffset = {"hud_wanted_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +#undef IMPL_HUD_OFFSET +#undef IMPL_HUD_OFFSET_X +#undef IMPL_HUD_OFFSET_Y +//extra hud things +consvar_t cv_showstats = {"showstats", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_showinput = {"showinput", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_newspeedometer = {"newspeedometer", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t speedo_cons_t[] = {{1, "Default"}, {2, "Small"}, {3, "P-Meter"}, {0, NULL}}; +consvar_t cv_newspeedometer = {"newspeedometer", "Default", CV_SAVE, speedo_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; + +//hardcode saltyhop mhhm consvar_t cv_saltyhop = {"hardcodehop", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_saltyhopsfx = {"hardcodehopsfx", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_saltysquish = {"hardcodehopsquish", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; //Colourized HUD -consvar_t cv_colorizedhud = {"colorizedhud", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_colorizedhud = {"colorizedhud", "Off", CV_SAVE|CV_CALL, CV_OnOff, Saturn_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_colorizeditembox = {"colorizeditembox", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - static CV_PossibleValue_t HudColor_cons_t[MAXSKINCOLORS+1]; consvar_t cv_colorizedhudcolor = {"colorizedhudcolor", "Skin Color", CV_SAVE, HudColor_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_darkitembox = {"darkitembox", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_highresportrait = {"highresportrait", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; //make char potraits use their high-res version instead -consvar_t cv_biglaps = {"biglaphud", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // here for ppl who dont want to make 2 more patches for their custom hud +consvar_t cv_darkitembox = {"darkitembox", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; //itembox gets a dark box with specific items +consvar_t cv_biglaps = {"biglaphud", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; //here for ppl who dont want to make 2 more patches for their custom hud // SOME IMPORTANT VARIABLES DEFINED IN DOOMDEF.H: // gamespeed is cc (0 for easy, 1 for normal, 2 for hard) @@ -553,7 +557,7 @@ void K_GenerateKartColormap(UINT8 *dest_colormap, INT32 skinnum, UINT8 color, bo return; } - starttranscolor = (skinnum != TC_DEFAULT) ? ( (local) ? localskins : skins )[skinnum].starttranscolor : DEFAULT_STARTTRANSCOLOR; + starttranscolor = (skinnum != TC_DEFAULT) ? ((local) ? localskins : skins)[skinnum].starttranscolor : DEFAULT_STARTTRANSCOLOR; // Fill in the entries of the palette that are fixed for (i = 0; i < starttranscolor; i++) @@ -587,11 +591,18 @@ UINT8 K_GetKartColorByName(const char *name) return 0; } -UINT8 K_GetHudColor() +UINT8 K_GetHudColor(void) +{ + if (cv_colorizedhud.value){ + if (cv_colorizedhudcolor.value) return cv_colorizedhudcolor.value; + } + if (stplyr && P_IsLocalPlayer(stplyr) && gamestate == GS_LEVEL) return stplyr->skincolor; + return ((stplyr && gamestate == GS_LEVEL) ? stplyr->skincolor : cv_playercolor.value); +} + +boolean K_UseColorHud(void) { - if (stplyr && players - stplyr != consoleplayer) return stplyr->skincolor; - if (cv_colorizedhudcolor.value) return cv_colorizedhudcolor.value; - return cv_playercolor.value; + return (cv_colorizedhud.value && clr_hud); } //} @@ -659,30 +670,39 @@ void K_RegisterKartStuff(void) CV_RegisterVar(&cv_kartdebugcheckpoint); CV_RegisterVar(&cv_kartdebugnodes); CV_RegisterVar(&cv_kartdebugcolorize); - - CV_RegisterVar(&cv_item_xoffset); - CV_RegisterVar(&cv_item_yoffset); - CV_RegisterVar(&cv_time_xoffset); - CV_RegisterVar(&cv_time_yoffset); - CV_RegisterVar(&cv_laps_xoffset); - CV_RegisterVar(&cv_laps_yoffset); - CV_RegisterVar(&cv_spdm_xoffset); - CV_RegisterVar(&cv_spdm_yoffset); - CV_RegisterVar(&cv_posi_xoffset); - CV_RegisterVar(&cv_posi_yoffset); - CV_RegisterVar(&cv_face_xoffset); - CV_RegisterVar(&cv_face_yoffset); - CV_RegisterVar(&cv_stcd_xoffset); - CV_RegisterVar(&cv_stcd_yoffset); - CV_RegisterVar(&cv_chek_yoffset); - CV_RegisterVar(&cv_mini_xoffset); - CV_RegisterVar(&cv_mini_yoffset); - CV_RegisterVar(&cv_want_xoffset); - CV_RegisterVar(&cv_want_yoffset); - + +#define REG_HUD_OFFSET_X(name)\ + CV_RegisterVar(&cv_##name##_xoffset); + +#define REG_HUD_OFFSET_Y(name)\ + CV_RegisterVar(&cv_##name##_yoffset); + +#define REG_HUD_OFFSET(name)\ + REG_HUD_OFFSET_X(name)\ + REG_HUD_OFFSET_Y(name) + + REG_HUD_OFFSET(item); // Item box + REG_HUD_OFFSET(time); // Time + REG_HUD_OFFSET(laps); // Number of laps + REG_HUD_OFFSET(dnft); // Countdown (did not finish timer) + REG_HUD_OFFSET(speed); // Speedometer + REG_HUD_OFFSET(posi); // Position in race + REG_HUD_OFFSET(face); // Mini rankings + REG_HUD_OFFSET(stcd); // Starting countdown + REG_HUD_OFFSET_Y(chek); // Check gfx + REG_HUD_OFFSET(mini); // Minimap + REG_HUD_OFFSET(want); // Wanted + REG_HUD_OFFSET(stat); // Stats + +#undef REG_HUD_OFFSET +#undef REG_HUD_OFFSET_X +#undef REG_HUD_OFFSET_Y + + CV_RegisterVar(&cv_showstats); CV_RegisterVar(&cv_showinput); CV_RegisterVar(&cv_newspeedometer); + CV_RegisterVar(&cv_saltyhop); CV_RegisterVar(&cv_saltyhopsfx); CV_RegisterVar(&cv_saltysquish); @@ -696,6 +716,8 @@ void K_RegisterKartStuff(void) CV_RegisterVar(&cv_biglaps); + CV_RegisterVar(&cv_highresportrait); + CV_RegisterVar(&cv_slamsound); CV_RegisterVar(&cv_minihead); @@ -705,6 +727,9 @@ void K_RegisterKartStuff(void) CV_RegisterVar(&cv_stagetitle); CV_RegisterVar(&cv_lessflicker); + + CV_RegisterVar(&cv_mouseturn); + } //} @@ -2980,6 +3005,13 @@ static void K_SpawnDriftSparks(player_t *player) spark->momy = player->mo->momy/2; //spark->momz = player->mo->momz/2; + // rotate the sparks based on pitch and roll; it just looks neat + if (cv_sparkroll.value == 1) + { + spark->slopepitch = player->mo->slopepitch; + spark->sloperoll = player->mo->sloperoll; + } + if (player->kartstuff[k_driftcharge] >= K_GetKartDriftSparkValue(player)*4) { spark->color = (UINT8)(1 + (leveltime % (MAXSKINCOLORS-1))); @@ -3087,7 +3119,7 @@ static void K_StretchPlayerGravity(player_t *p) if (p->mo->slamsoundtimer) p->mo->slamsoundtimer--; - if (cv_slamsound.value == 1 && (p->mo->eflags & MFE_JUSTHITFLOOR) && p->mo->stretchslam > 4*mos && !p->mo->slamsoundtimer) + if (cv_slamsound.value && (p->mo->eflags & MFE_JUSTHITFLOOR) && p->mo->stretchslam > 4*mos && !p->mo->slamsoundtimer) { S_StartSound(p->mo, sfx_s3k4c); p->mo->slamsoundtimer = TICRATE; @@ -3120,12 +3152,11 @@ static void K_StretchPlayerGravity(player_t *p) else slamDiv = FixedDiv(p->mo->stretchslam, stretchScaleFactor); p->mo->spritexscale = (dxs+(((slamDiv*2)/3)*2)); - p->mo->spriteyscale = ((dys-(slamDiv))); + p->mo->spriteyscale = (dys-(slamDiv)); if (p->mo->stretchslam > 0) p->mo->stretchslam -= (4*mos); else p->mo->stretchslam = 0; - } } @@ -3190,110 +3221,72 @@ static void K_QuiteSaltyHop(player_t *p) } } -static INT32 K_FindPlayerNum(player_t *plyr) +/*static INT32 K_FindPlayerNum(player_t *plyr) { INT32 i; + for(i = 0; i < 4; i++) { if (plyr == &players[displayplayers[i]]) return i; } return 0; // technically defaulting to player 1 but fuck it -} +}*/ -static angle_t K_GetSlopeRollAngle(player_t *p, boolean dontflip, boolean useReserves) +#define SLOPEROLL_DIV 3 + +void K_RollMobjBySlopes(mobj_t* mo, boolean usedistance) { - angle_t lookAngle = 0; - angle_t zangle = 0; - angle_t xydirection = 0; - angle_t an; - angle_t final_slope; - INT32 pNum = K_FindPlayerNum(p); + I_Assert(mo->subsector != NULL); + I_Assert(mo->subsector->sector != NULL); - I_Assert(p != NULL); - I_Assert(p->mo != NULL); - I_Assert(!P_MobjWasRemoved(p->mo)); + angle_t an; + boolean flip = mo->eflags & MFE_VERTICALFLIP; + fixed_t m_dist = R_PointToDist(mo->x, mo->y); + fixed_t rolldist = cv_sloperolldist.value * mapobjectscale; - if (useReserves) - { - I_Assert(p->mo->reservezangle != NULL); - I_Assert(p->mo->reservexydir != NULL); - } + // lifted from hw_md2 + if (mo->standingslope) + { + fixed_t tempz = mo->standingslope->normal.z; + fixed_t tempy = mo->standingslope->normal.y; + fixed_t tempx = mo->standingslope->normal.x; + fixed_t tempangle = -(R_PointToAngle2( + 0, 0, FixedSqrt(FixedMul(tempy, tempy) + FixedMul(tempz, tempz)), tempx)); - lookAngle = R_PointToAngle2(camera[pNum].x, camera[pNum].y, p->mo->x, p->mo->y); + // admittedly this is a very hacky way to do the pitch and roll easing + // pitch + if ((!usedistance) || (m_dist <= (rolldist))) + { + an = (INT32)((angle_t)tempangle - mo->pitch_sprite) / SLOPEROLL_DIV; - if (!R_PointToDist(p->mo->x, p->mo->y)) - lookAngle = p->mo->angle; + mo->pitch_sprite = an ? mo->pitch_sprite + an : (angle_t)tempangle; + } + else + mo->pitch_sprite = FixedAngle(0); - if (!useReserves) - { - zangle = p->mo->standingslope->zangle; - xydirection = p->mo->standingslope->xydirection; + mo->slopepitch = flip ? InvAngle(mo->pitch_sprite) : mo->pitch_sprite; - p->mo->reservezangle = zangle; - p->mo->reservexydir = xydirection; - } - else - { - if (p->mo->reservezangle) - { - zangle = p->mo->reservezangle; - xydirection = p->mo->reservexydir; - } - } + // roll + tempangle = (R_PointToAngle2(0, 0, tempz, tempy)); - if ((p->mo->eflags & MFE_VERTICALFLIP) && (!dontflip)) - zangle = InvAngle(zangle); + if ((!usedistance) || (m_dist <= (rolldist))) + { + an = (INT32)((angle_t)tempangle - mo->roll_sprite) / SLOPEROLL_DIV; - an = (lookAngle - xydirection); - final_slope = -(FixedMul(FINESINE(an>>ANGLETOFINESHIFT), zangle)); - an = (INT32)(final_slope - p->tilt_sprite) / 3; // instead of just a direct snap + mo->roll_sprite = an ? mo->roll_sprite + an : (angle_t)tempangle; + } + else + mo->roll_sprite = FixedAngle(0); - if (an) - p->tilt_sprite += an; - else - p->tilt_sprite = final_slope; - return -p->tilt_sprite; -} - -static void K_RollPlayerBySlopes(player_t *p, boolean usedistance) -{ - I_Assert(p->mo->subsector != NULL); - I_Assert(p->mo->subsector->sector != NULL); - - INT32 pNum = K_FindPlayerNum(p); - - fixed_t p_dist = R_PointToDist2(p->mo->x, p->mo->y, camera[pNum].x, camera[pNum].y); - fixed_t mos = mapobjectscale; - fixed_t rolldist = cv_sloperolldist.value*mos; - - if (!P_IsObjectOnGround(p->mo)) - { - if (!usedistance) - p->mo->sloperoll = K_GetSlopeRollAngle(p, false, true); - else if (p_dist <= (rolldist)) - p->mo->sloperoll = K_GetSlopeRollAngle(p, false, true); - else - p->mo->sloperoll = FixedAngle(0); - - return; - } - - if (!p->mo->standingslope) - { - p->mo->sloperoll = FixedAngle(0); - p->mo->reservezangle = FixedAngle(0); - p->mo->reservexydir = FixedAngle(0); - return; - } - - if (!usedistance) - p->mo->sloperoll = K_GetSlopeRollAngle(p, false, false); - else if (p_dist <= (rolldist)) - p->mo->sloperoll = K_GetSlopeRollAngle(p, false, false); - else - p->mo->sloperoll = FixedAngle(0); + mo->sloperoll = flip ? InvAngle(mo->roll_sprite) : mo->roll_sprite; + } + else if (P_IsObjectOnGround(mo)) + { + mo->sloperoll = FixedAngle(0); + mo->slopepitch = FixedAngle(0); + } } void K_SpawnBoostTrail(player_t *player) @@ -3345,6 +3338,14 @@ void K_SpawnBoostTrail(player_t *player) K_FlipFromObject(flame, player->mo); flame->momx = 8; + + // since you have to be on the ground for sneaker trails, this should be fine(?) + if (cv_sparkroll.value == 1) + { + flame->slopepitch = player->mo->slopepitch; + flame->sloperoll = player->mo->sloperoll; + } + P_XYMovement(flame); if (P_MobjWasRemoved(flame)) continue; @@ -6007,7 +6008,7 @@ void K_MoveKartPlayer(player_t *player, boolean onground) P_SetScale(overlay, player->mo->scale); } player->kartstuff[k_invincibilitytimer] = itemtime+(2*TICRATE); // 10 seconds - if (P_IsLocalPlayer(player)) + if (P_IsLocalPlayer(player) && cv_supermusic.value && cv_birdmusic.value) S_ChangeMusicSpecial("kinvnc"); else S_StartSound(player->mo, (cv_kartinvinsfx.value ? sfx_alarmi : sfx_kinvnc)); @@ -6212,7 +6213,7 @@ void K_MoveKartPlayer(player_t *player, boolean onground) if (cv_kartdebugshrink.value && !modeattacking && !player->bot) player->mo->destscale = (6*player->mo->destscale)/8; player->kartstuff[k_growshrinktimer] = itemtime+(4*TICRATE); // 12 seconds - if (P_IsLocalPlayer(player)) + if (P_IsLocalPlayer(player) && cv_growmusic.value && cv_birdmusic.value ) S_ChangeMusicSpecial("kgrow"); else S_StartSound(player->mo, (cv_kartinvinsfx.value ? sfx_alarmg : sfx_kgrow)); @@ -6440,13 +6441,21 @@ void K_MoveKartPlayer(player_t *player, boolean onground) player->mo->spritexscale = player->mo->realxscale; player->mo->spriteyscale = player->mo->realyscale; } + boolean usedist = false; + if (cv_sloperolldist.value > 0) usedist = true; - if (cv_sloperoll.value == 1) - K_RollPlayerBySlopes(player, usedist); + if ((cv_spriteroll.value) && (cv_sloperoll.value)) + { + if ((!player->mo->salty_jump)) // seeing a character rotate mid-hop looks really janky + K_RollMobjBySlopes(player->mo, usedist); + } else + { player->mo->sloperoll = FixedAngle(0); + player->mo->slopepitch = FixedAngle(0); + } // Quick Turning @@ -6881,21 +6890,15 @@ void K_UpdateSpectateGrief(void) INT32 i; if (nospectategrief) - { return; - } if (leveltime <= (starttime + 20*TICRATE)) - { return; - } for (i = 0; i < MAXPLAYERS; i++) { if (!playeringame[i] || players[i].spectator) - { continue; - } numingame++; } @@ -6944,6 +6947,10 @@ static patch_t *skp_smallstickerclr; static patch_t *kp_itemmulstickerclr[2]; static patch_t *kp_itembgclr[4]; + +//Kartz speedo +static patch_t *kp_kartzspeedo[25]; + static patch_t *kp_startcountdown[16]; static patch_t *kp_racefinish[6]; @@ -7029,12 +7036,12 @@ void K_LoadKartHUDGraphics(void) kp_karmasticker = W_CachePatchName("K_STKARM", PU_HUDGFX); kp_splitkarmabomb = W_CachePatchName("K_SPTKRM", PU_HUDGFX); kp_timeoutsticker = W_CachePatchName("K_STTOUT", PU_HUDGFX); - + if (big_lap){ kp_lapstickerbig = W_CachePatchName("K_STLAPB", PU_HUDGFX); kp_lapstickerbig2 = W_CachePatchName("K_STLA2B", PU_HUDGFX); - } - + } + //Colourized hud if (clr_hud) { @@ -7056,12 +7063,41 @@ void K_LoadKartHUDGraphics(void) kp_lapstickerbigclr = W_CachePatchName("K_SCLAPB", PU_HUDGFX); kp_lapstickerbig2clr = W_CachePatchName("K_SCLA2B", PU_HUDGFX); } - - if (snw_speedo){ + + if (snw_speedo) skp_smallstickerclr = W_CachePatchName("SC_SMSTC", PU_HUDGFX); - } } + //KartZ speedo + if (kartzspeedo) + { + kp_kartzspeedo[0] = W_CachePatchName("K_KZSP1", PU_HUDGFX); + kp_kartzspeedo[1] = W_CachePatchName("K_KZSP2", PU_HUDGFX); + kp_kartzspeedo[2] = W_CachePatchName("K_KZSP3", PU_HUDGFX); + kp_kartzspeedo[3] = W_CachePatchName("K_KZSP4", PU_HUDGFX); + kp_kartzspeedo[4] = W_CachePatchName("K_KZSP5", PU_HUDGFX); + kp_kartzspeedo[5] = W_CachePatchName("K_KZSP6", PU_HUDGFX); + kp_kartzspeedo[6] = W_CachePatchName("K_KZSP7", PU_HUDGFX); + kp_kartzspeedo[7] = W_CachePatchName("K_KZSP8", PU_HUDGFX); + kp_kartzspeedo[8] = W_CachePatchName("K_KZSP9", PU_HUDGFX); + kp_kartzspeedo[9] = W_CachePatchName("K_KZSP10", PU_HUDGFX); + kp_kartzspeedo[10] = W_CachePatchName("K_KZSP11", PU_HUDGFX); + kp_kartzspeedo[11] = W_CachePatchName("K_KZSP12", PU_HUDGFX); + kp_kartzspeedo[12] = W_CachePatchName("K_KZSP13", PU_HUDGFX); + kp_kartzspeedo[13] = W_CachePatchName("K_KZSP14", PU_HUDGFX); + kp_kartzspeedo[14] = W_CachePatchName("K_KZSP15", PU_HUDGFX); + kp_kartzspeedo[15] = W_CachePatchName("K_KZSP16", PU_HUDGFX); + kp_kartzspeedo[16] = W_CachePatchName("K_KZSP17", PU_HUDGFX); + kp_kartzspeedo[17] = W_CachePatchName("K_KZSP18", PU_HUDGFX); + kp_kartzspeedo[18] = W_CachePatchName("K_KZSP19", PU_HUDGFX); + kp_kartzspeedo[19] = W_CachePatchName("K_KZSP20", PU_HUDGFX); + kp_kartzspeedo[20] = W_CachePatchName("K_KZSP21", PU_HUDGFX); + kp_kartzspeedo[21] = W_CachePatchName("K_KZSP22", PU_HUDGFX); + kp_kartzspeedo[22] = W_CachePatchName("K_KZSP23", PU_HUDGFX); + kp_kartzspeedo[23] = W_CachePatchName("K_KZSP24", PU_HUDGFX); + kp_kartzspeedo[24] = W_CachePatchName("K_KZSP25", PU_HUDGFX); + } + // Starting countdown kp_startcountdown[0] = W_CachePatchName("K_CNT3A", PU_HUDGFX); kp_startcountdown[1] = W_CachePatchName("K_CNT2A", PU_HUDGFX); @@ -7415,8 +7451,8 @@ static void K_initKartHUD(void) LAPS_X = 9 + cv_laps_xoffset.value; // 9 LAPS_Y = BASEVIDHEIGHT - 29 + cv_laps_yoffset.value; // 171 // Speedometer - SPDM_X = 9 + cv_spdm_xoffset.value; // 9 - SPDM_Y = BASEVIDHEIGHT - 45 + cv_spdm_yoffset.value; // 155 + SPDM_X = 9 + cv_speed_xoffset.value; // 9 + SPDM_Y = BASEVIDHEIGHT - 45 + cv_speed_yoffset.value; // 155 // Position Number POSI_X = BASEVIDWIDTH - 9 + cv_posi_xoffset.value; // 268 POSI_Y = BASEVIDHEIGHT - 9 + cv_posi_yoffset.value; // 138 @@ -7531,6 +7567,121 @@ INT32 K_calcSplitFlags(INT32 snapflags) return (splitflags|snapflags); } +static void K_drawKartStats(void) +{ + INT32 x, y, spdoffset, flags; + + // For 1-player display + x = 15; + y = 150; + spdoffset = 0; + flags = V_SNAPTOBOTTOM|V_SNAPTOLEFT; + + UINT8 splitnum = 0; + + for (; splitnum < MAXSPLITSCREENPLAYERS; ++splitnum) + { + if (stplyr == &players[displayplayers[splitnum]]) + break; + } + +#ifdef HAVE_BLUA + if (!LUA_HudEnabled(hud_statdisplay)) + return; +#endif + + + // I tried my best, but this is still mess :/ + if (splitscreen) + { + if (splitscreen == 1) + { + // If we are in 2-player splitscreen, for player 1 we move hud to up and remove snapping + // to bottom + if (splitnum == 0) + { + y /= 2; + flags = V_SNAPTOLEFT; + } + else + { + // Can move it down a bit + y += 20; + } + } + else + { + // In 4-player splitscreen... + flags = 0; + + // ...For players 2 and 4, which are at right side, we move x coordinate... + if (splitnum == 1 || splitnum == 3) + x += BASEVIDWIDTH/2; + // ...Else, for players on left side we can snap position to left... + else + flags |= V_SNAPTOLEFT; + + // ...For players 1 and 2, which are at top side, we move y coordinate... + if (splitnum == 0 || splitnum == 1) + y /= 2; + // ...Else, for players on bottom side we can snap position to bottom + else + { + flags |= V_SNAPTOBOTTOM; + // Can move it down a bit + y += 20; + } + } + } + + //Internal offset for speedometer + if (cv_kartspeedometer.value) + { + if (cv_newspeedometer.value == 2 && snw_speedo) + spdoffset = -10; + else + spdoffset = -14; + } + else + spdoffset = 0; + + // Customizations c: + x += 18 + cv_stat_xoffset.value; + y += cv_stat_yoffset.value + (G_BattleGametype() ? (stplyr->kartstuff[k_bumper] ? -5 : -8) : 0) + spdoffset; + flags |= V_HUDTRANS; + + skin_t *fakeskin; + fakeskin = &skins[stplyr->skin]; + + // local skinner + if (stplyr->localskin) + { + if (stplyr->skinlocal) + fakeskin = &localskins[stplyr->localskin - 1]; + else + fakeskin = &skins[stplyr->localskin - 1]; + } + + if (!splitscreen) + { + // Skin name + V_DrawSmallString(x+20, y+12, flags|V_ALLOWLOWERCASE, va("%c%s", V_GetSkincolorChar(stplyr->skincolor), fakeskin->realname)); + + // Icon and stats + if (cv_highresportrait.value) + V_DrawSmallMappedPatch(x, y, flags, R_GetSkinFaceWant(stplyr), R_GetLocalTranslationColormap(fakeskin, fakeskin, stplyr->skincolor, GTC_CACHE, stplyr->skinlocal)); + else + V_DrawMappedPatch(x, y, flags, R_GetSkinFaceRank(stplyr), R_GetLocalTranslationColormap(fakeskin, fakeskin, stplyr->skincolor, GTC_CACHE, stplyr->skinlocal)); + V_DrawMappedPatch(x-3, y-2, flags, kp_facenum[min(9, max(1, stplyr->kartspeed))], R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_BLUEBERRY, GTC_CACHE)); + V_DrawMappedPatch(x+10, y+10, flags, kp_facenum[min(9, max(1, stplyr->kartweight))], R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_BURGUNDY, GTC_CACHE)); + } + else + { + // In splitscreen, just draw a string with stats + V_DrawString(x, y+10, flags, va("\x84%dS \x87%dW", stplyr->kartspeed, stplyr->kartweight)); + } +} + static void K_drawKartItem(void) { // ITEM_X = BASEVIDWIDTH-50; // 270 @@ -7542,7 +7693,7 @@ static void K_drawKartItem(void) patch_t *localpatch = kp_nodraw; patch_t *localbg; - if (cv_colorizeditembox.value && cv_colorizedhud.value && clr_hud) + if (cv_colorizeditembox.value && K_UseColorHud()) localbg = ((offset) ? kp_itembgclr[2] : kp_itembgclr[0]); else localbg = ((offset) ? kp_itembg[2] : kp_itembg[0]); @@ -7706,12 +7857,8 @@ static void K_drawKartItem(void) break; case KITEM_INVINCIBILITY: localpatch = localinv; - if (cv_darkitembox.value){ - if (cv_colorizeditembox.value && cv_colorizedhud.value && clr_hud) - localbg = kp_itembgclr[offset+1]; - else - localbg = kp_itembg[offset+1]; - } + if (cv_darkitembox.value) + localbg = (cv_colorizeditembox.value && K_UseColorHud()) ? kp_itembgclr[offset + 1] : kp_itembg[offset + 1]; break; case KITEM_BANANA: localpatch = kp_banana[offset]; @@ -7733,12 +7880,8 @@ static void K_drawKartItem(void) break; case KITEM_SPB: localpatch = kp_selfpropelledbomb[offset]; - if (cv_darkitembox.value){ - if (cv_colorizeditembox.value && cv_colorizedhud.value && clr_hud) - localbg = kp_itembgclr[offset+1]; - else - localbg = kp_itembg[offset+1]; - } + if (cv_darkitembox.value) + localbg = (cv_colorizeditembox.value && K_UseColorHud()) ? kp_itembgclr[offset + 1] : kp_itembg[offset + 1]; break; case KITEM_GROW: localpatch = kp_grow[offset]; @@ -7748,12 +7891,8 @@ static void K_drawKartItem(void) break; case KITEM_THUNDERSHIELD: localpatch = kp_thundershield[offset]; - if (cv_darkitembox.value){ - if (cv_colorizeditembox.value && cv_colorizedhud.value && clr_hud) - localbg = kp_itembgclr[offset+1]; - else - localbg = kp_itembg[offset+1]; - } + if (cv_darkitembox.value) + localbg = (cv_colorizeditembox.value && K_UseColorHud()) ? kp_itembgclr[offset + 1] : kp_itembg[offset + 1]; break; case KITEM_HYUDORO: localpatch = kp_hyudoro[offset]; @@ -7822,31 +7961,18 @@ static void K_drawKartItem(void) colmap = R_GetTranslationColormap(colormode, localcolor, GTC_CACHE); - if (cv_colorizeditembox.value && cv_colorizedhud.value && clr_hud) - { + if (cv_colorizeditembox.value && K_UseColorHud()) V_DrawMappedPatch(fx, fy, V_HUDTRANS|fflags, localbg,colormap); - } else - { V_DrawScaledPatch(fx, fy, V_HUDTRANS|fflags, localbg); - } - - - - // Then, the numbers: if (stplyr->kartstuff[k_itemamount] >= numberdisplaymin && !stplyr->kartstuff[k_itemroulette]) { - //Colourized hud - if (cv_colorizedhud.value && clr_hud) - { - V_DrawMappedPatch(fx + (flipamount ? 48 : 0), fy, V_HUDTRANS|fflags|(flipamount ? V_FLIP : 0), kp_itemmulstickerclr[offset],colormap); // flip this graphic for p2 and p4 in split and shift it. - } - else - { - V_DrawScaledPatch(fx + (flipamount ? 48 : 0), fy, V_HUDTRANS|fflags|(flipamount ? V_FLIP : 0), kp_itemmulsticker[offset]); // flip this graphic for p2 and p4 in split and shift it. - } + if (!K_UseColorHud()) + V_DrawScaledPatch(fx + (flipamount ? 48 : 0), fy, V_HUDTRANS|fflags|(flipamount ? V_FLIP : 0), kp_itemmulsticker[offset]); + else //Colourized hud + V_DrawMappedPatch(fx + (flipamount ? 48 : 0), fy, V_HUDTRANS|fflags|(flipamount ? V_FLIP : 0), kp_itemmulstickerclr[offset], colormap); // flip this graphic for p2 and p4 in split and shift it. V_DrawFixedPatch(fx<kartstuff[k_itemamount])); else { - V_DrawScaledPatch(fy+28, fy+41, V_HUDTRANS|fflags, kp_itemx); + V_DrawScaledPatch(fx+28, fy+41, V_HUDTRANS|fflags, kp_itemx); V_DrawKartString(fx+38, fy+36, V_HUDTRANS|fflags, va("%d", stplyr->kartstuff[k_itemamount])); } } @@ -7910,14 +8036,11 @@ void K_drawKartTimestamp(tic_t drawtime, INT32 TX, INT32 TY, INT16 emblemmap, UI } } - - if (!cv_colorizedhud.value || !clr_hud) + if (!K_UseColorHud()) V_DrawScaledPatch(TX, TY, splitflags, ((mode == 2) ? kp_lapstickerwide : kp_timestickerwide)); - else + else //Colourized hud { - //Colourized hud UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - V_DrawMappedPatch(TX, TY, splitflags, ((mode == 2) ? kp_lapstickerwideclr : kp_timestickerwideclr), colormap); } @@ -8078,9 +8201,8 @@ static void K_DrawKartPositionNum(INT32 num) scale *= 2; overtake = true; // this is used for splitscreen stuff in conjunction with flipdraw. } - if (splitscreen) - scale /= 2; - if (cv_showinput.value && !splitscreen) // anuther one. + + if (splitscreen || (cv_showinput.value && !splitscreen)) scale /= 2; W = FixedMul(W<>FRACBITS; @@ -8089,7 +8211,7 @@ static void K_DrawKartPositionNum(INT32 num) if (!splitscreen) { fx = POSI_X + xoffs; - fy = BASEVIDHEIGHT - 8; + fy = BASEVIDHEIGHT - 8 + cv_posi_yoffset.value; fflags = V_SNAPTOBOTTOM|V_SNAPTORIGHT; } else if (splitscreen == 1) // for this splitscreen, we'll use case by case because it's a bit different. @@ -8097,14 +8219,14 @@ static void K_DrawKartPositionNum(INT32 num) fx = POSI_X; if (stplyr == &players[displayplayers[0]]) // for player 1: display this at the top right, above the minimap. { - fy = 30; + fy = 30 + cv_posi_yoffset.value; fflags = V_SNAPTOTOP|V_SNAPTORIGHT; if (overtake) flipvdraw = true; // make sure overtaking doesn't explode us } else // if we're not p1, that means we're p2. display this at the bottom right, below the minimap. { - fy = BASEVIDHEIGHT - 8; + fy = BASEVIDHEIGHT - 8 + cv_posi_yoffset.value; fflags = V_SNAPTOBOTTOM|V_SNAPTORIGHT; } } @@ -8285,7 +8407,10 @@ static boolean K_drawKartPositionFaces(void) { player_t *p; p = &players[rankplayer[i]]; - V_DrawMappedPatch(FACE_X, Y, V_HUDTRANS|V_SNAPTOLEFT, ( (p->skinlocal) ? localfacerankprefix : facerankprefix )[( (p->localskin) ? p->localskin-1 : p->skin )], colormap); + if (cv_highresportrait.value) + V_DrawSmallMappedPatch(FACE_X, Y, V_HUDTRANS|V_SNAPTOLEFT, R_GetSkinFaceWant(p), colormap); + else + V_DrawMappedPatch(FACE_X, Y, V_HUDTRANS|V_SNAPTOLEFT, R_GetSkinFaceRank(p), colormap); } #ifdef HAVE_BLUA @@ -8375,7 +8500,10 @@ void HU_DrawTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, I { player_t *p; p = &players[tab[i].num]; - V_DrawMappedPatch(x, y-4, 0, ( (p->skinlocal) ? localfacerankprefix : facerankprefix )[( (p->localskin) ? p->localskin-1 : p->skin )], colormap); + if (cv_highresportrait.value) + V_DrawSmallMappedPatch(x, y-4, 0, R_GetSkinFaceWant(p), colormap); + else + V_DrawMappedPatch(x, y-4, 0, R_GetSkinFaceRank(p), colormap); } /*if (G_BattleGametype() && players[tab[i].num].kartstuff[k_bumper] > 0) -- not enough space for this { @@ -8438,6 +8566,14 @@ void HU_DrawTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, I } } +static boolean K_BigLapSticker(void) +{ + if (K_UseColorHud()) + return ((cv_numlaps.value > 9) && (big_lap_color) && (cv_biglaps.value) && (!stplyr->exiting)); + else + return ((cv_numlaps.value > 9) && (big_lap) && (cv_biglaps.value) && (!stplyr->exiting)); +} + static void K_drawKartLaps(void) { INT32 splitflags = K_calcSplitFlags(V_SNAPTOBOTTOM|V_SNAPTOLEFT); @@ -8447,7 +8583,6 @@ static void K_drawKartLaps(void) if (splitscreen > 1) { - // pain and suffering defined below if (splitscreen < 2) // don't change shit for THIS splitscreen. { @@ -8472,8 +8607,6 @@ static void K_drawKartLaps(void) } } - - if (stplyr->exiting) // draw stuff as god intended. { V_DrawScaledPatch(fx, fy, V_HUDTRANS|fflags, kp_splitlapflag); @@ -8495,31 +8628,22 @@ static void K_drawKartLaps(void) } else { - - if (!cv_colorizedhud.value || !clr_hud){ - if ((cv_numlaps.value > 9) && (big_lap) && (cv_biglaps.value)){ - if (stplyr->laps+1 > 9) - V_DrawScaledPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_lapstickerbig2); - else - V_DrawScaledPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_lapstickerbig); - } + if (!K_UseColorHud()) + { + if (K_BigLapSticker()) + V_DrawScaledPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, ((stplyr->laps + 1 > 9) ? kp_lapstickerbig2 : kp_lapstickerbig)); else V_DrawScaledPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_lapsticker); } - else + else //Colourized hud { - //Colourized hud UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - if ((cv_numlaps.value > 9) && (big_lap_color) && (cv_biglaps.value)){ - if (stplyr->laps+1 > 9) - V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_lapstickerbig2clr, colormap); - else - V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_lapstickerbigclr, colormap); - } + if (K_BigLapSticker()) + V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, ((stplyr->laps + 1 > 9) ? kp_lapstickerbig2clr : kp_lapstickerbigclr), colormap); else V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_lapstickerclr, colormap); } - + if (stplyr->exiting) V_DrawKartString(LAPS_X+33, LAPS_Y+3, V_HUDTRANS|splitflags, "FIN"); else @@ -8534,6 +8658,11 @@ static void K_drawKartSpeedometer(void) return; fixed_t convSpeed = 0; + + //KartZ speedo + fixed_t fuspeed = 0; + INT32 spdpatch = 0; + INT32 speedtype = 0; INT32 splitflags = K_calcSplitFlags(V_SNAPTOBOTTOM|V_SNAPTOLEFT); @@ -8562,7 +8691,7 @@ static void K_drawKartSpeedometer(void) } // man. - if ((!cv_newspeedometer.value) || (cv_newspeedometer.value && !snw_speedo)) + if ((cv_newspeedometer.value == 1) || (cv_newspeedometer.value == 2 && !snw_speedo) || (cv_newspeedometer.value == 3 && !kartzspeedo)) { switch (speedtype) { case 1: @@ -8579,23 +8708,91 @@ static void K_drawKartSpeedometer(void) V_DrawKartString(SPDM_X, SPDM_Y, V_HUDTRANS|splitflags, va("%4d P", convSpeed)); else V_DrawKartString(SPDM_X, SPDM_Y, V_HUDTRANS|splitflags, va("%4d %%", convSpeed)); + break; + default: + break; } } - else if (cv_newspeedometer.value && snw_speedo) { // why bother if we dont? - if (!cv_colorizedhud.value || !clr_hud) + else if (cv_newspeedometer.value == 2 && snw_speedo) // why bother if we dont? + { + if (!K_UseColorHud()) V_DrawScaledPatch(SPDM_X + 1, SPDM_Y + 4, (V_HUDTRANS|splitflags), (skp_smallsticker)); - else + else //Colourized hud { - //Colourized hud UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - V_DrawMappedPatch(SPDM_X + 1, SPDM_Y + 4, (V_HUDTRANS|splitflags), (skp_smallstickerclr), colormap); } V_DrawRankNum(SPDM_X + 26, SPDM_Y + 4, V_HUDTRANS|splitflags, convSpeed, 3, NULL); V_DrawScaledPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_speedpatches[cv_kartspeedometer.value]); + } + + // Kart Z speedo bullshit... + // Draw the Speed counter. + // Warning large if statement below... + else if (cv_newspeedometer.value == 3 && kartzspeedo) + { + fuspeed = FixedDiv(stplyr->speed, mapobjectscale)/FRACUNIT; + + if (fuspeed < 2 && fuspeed > 0) + spdpatch = 0; + else if (fuspeed < 5 && fuspeed > 1) + spdpatch = 1; + else if (fuspeed < 7 && fuspeed > 4) + spdpatch = 2; + else if (fuspeed < 10 && fuspeed > 6) + spdpatch = 3; + else if (fuspeed < 12 && fuspeed > 9) + spdpatch = 4; + else if (fuspeed < 15 && fuspeed > 11) + spdpatch = 5; + else if (fuspeed < 17 && fuspeed > 14) + spdpatch = 6; + else if (fuspeed < 20 && fuspeed > 16) + spdpatch = 7; + else if (fuspeed < 22 && fuspeed > 19) + spdpatch = 8; + else if (fuspeed < 25 && fuspeed > 21) + spdpatch = 9; + else if (fuspeed < 27 && fuspeed > 24) + spdpatch = 10; + else if (fuspeed < 30 && fuspeed > 26) + spdpatch = 11; + else if (fuspeed < 32 && fuspeed > 29) + spdpatch = 12; + else if (fuspeed < 35 && fuspeed > 31) + spdpatch = 13; + else if (fuspeed < 37 && fuspeed > 34) + spdpatch = 14; + else if (fuspeed < 40 && fuspeed > 36) + spdpatch = 15; + else if (fuspeed < 42 && fuspeed > 39) + spdpatch = 16; + else if (fuspeed < 45 && fuspeed > 41) + spdpatch = 17; + else if (fuspeed < 47 && fuspeed > 44) + spdpatch = 18; + else if (fuspeed < 50 && fuspeed > 46) + spdpatch = 19; + else if (fuspeed < 52 && fuspeed > 49) + spdpatch = 20; + else if (fuspeed < 55 && fuspeed > 51) + spdpatch = 21; + else if (fuspeed < 57 && fuspeed > 54 && (leveltime&4)) + spdpatch = 24; + else if (fuspeed < 57 && fuspeed > 54 && !(leveltime&4)) + spdpatch = 23; + else if (fuspeed < 60 && fuspeed > 56 && (leveltime&4)) + spdpatch = 24; + else if (fuspeed < 60 && fuspeed > 56 && !(leveltime&4)) + spdpatch = 23; + else if (fuspeed > 59 && (leveltime&4)) + spdpatch = 24; + else if (fuspeed > 59 && !(leveltime&4)) + spdpatch = 23; + V_DrawScaledPatch(SPDM_X, SPDM_Y, V_HUDTRANS|splitflags, kp_kartzspeedo[spdpatch]); } } @@ -8609,7 +8806,6 @@ static void K_drawKartBumpersOrKarma(void) if (splitscreen > 1) { - // we will reuse lap coords here since it's essentially the same shit. if (stplyr == &players[displayplayers[0]] || stplyr == &players[displayplayers[2]]) // If we are P1 or P3... @@ -8631,7 +8827,7 @@ static void K_drawKartBumpersOrKarma(void) V_DrawMappedPatch(fx, fy-1, V_HUDTRANS|fflags, kp_splitkarmabomb, colormap); V_DrawString(fx+13, fy+1, V_HUDTRANS|fflags, va("%d/2", stplyr->kartstuff[k_comebackpoints])); } - else // the above doesn't need to account for weird stuff since the max amount of karma necessary is always 2 ^^^^ + else // the above doesn't need to account for weird stuff since the max amount of karma necessary is always 2 ^^^^ { if (flipstring) // for p2 and p4, assume we can have more than 10 bumpers. It's retarded but who knows. { @@ -8640,7 +8836,7 @@ static void K_drawKartBumpersOrKarma(void) V_DrawMappedPatch(BASEVIDWIDTH-stringw-16, fy-1, V_HUDTRANS|fflags, kp_rankbumper, colormap); V_DrawRightAlignedString(BASEVIDWIDTH-3, fy+1, V_HUDTRANS|fflags, va("%d/%d", stplyr->kartstuff[k_bumper], cv_kartbumpers.value)); } - else // draw bumpers normally. + else // draw bumpers normally. { V_DrawMappedPatch(fx, fy-1, V_HUDTRANS|fflags, kp_rankbumper, colormap); V_DrawString(fx+13, fy+1, V_HUDTRANS|fflags, va("%d/%d", stplyr->kartstuff[k_bumper], cv_kartbumpers.value)); @@ -8651,39 +8847,15 @@ static void K_drawKartBumpersOrKarma(void) { if (stplyr->kartstuff[k_bumper] <= 0) { - //Colourized hud - if (cv_colorizedhud.value && clr_hud) - { - V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_karmastickerclr, colormap); - } - else - { - V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_karmasticker, colormap); - } + V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, (K_UseColorHud() ? kp_karmastickerclr : kp_karmasticker), colormap); V_DrawKartString(LAPS_X+47, LAPS_Y+3, V_HUDTRANS|splitflags, va("%d/2", stplyr->kartstuff[k_comebackpoints])); } else { if (stplyr->kartstuff[k_bumper] > 9 && cv_kartbumpers.value > 9) - //Colourized hud - if (cv_colorizedhud.value && clr_hud) - { - V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_bumperstickerwideclr, colormap); - } - else - { - V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_bumperstickerwide, colormap); - } + V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, (K_UseColorHud() ? kp_bumperstickerwideclr : kp_bumperstickerwide), colormap); else - //Colourized hud - if (cv_colorizedhud.value && clr_hud) - { - V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_bumperstickerclr, colormap); - } - else - { - V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, kp_bumpersticker, colormap); - } + V_DrawMappedPatch(LAPS_X, LAPS_Y, V_HUDTRANS|splitflags, (K_UseColorHud() ? kp_bumperstickerclr : kp_bumpersticker), colormap); V_DrawKartString(LAPS_X+47, LAPS_Y+3, V_HUDTRANS|splitflags, va("%d/%d", stplyr->kartstuff[k_bumper], cv_kartbumpers.value)); } @@ -8783,7 +8955,7 @@ static void K_drawKartWanted(void) if (players[battlewanted[i]].skincolor) { colormap = R_GetTranslationColormap(TC_RAINBOW, p->skincolor, GTC_CACHE); - V_DrawFixedPatch(x<skinlocal) ? localfacewantprefix : facewantprefix )[( (p->localskin) ? p->localskin-1 : p->skin )] : ( (p->skinlocal) ? localfacerankprefix : facerankprefix )[( (p->localskin) ? p->localskin-1 : p->skin )]), colormap); + V_DrawFixedPatch(x<skin] : facerankprefix[p->skin]), colormap);*/ } @@ -8863,7 +9035,7 @@ static void K_drawKartMinimapHead(mobj_t *mo, INT32 x, INT32 y, INT32 flags, pat fixed_t xscale, yscale, zoom; if (mo->skin) - skin = ((skin_t*)( (mo->localskin) ? mo->localskin : mo->skin ))-( (skinlocal) ? localskins : skins ); + skin = ((skin_t*)((mo->localskin) ? mo->localskin : mo->skin))-((skinlocal) ? localskins : skins); maxx = maxy = INT32_MAX; minx = miny = INT32_MIN; @@ -8907,39 +9079,37 @@ static void K_drawKartMinimapHead(mobj_t *mo, INT32 x, INT32 y, INT32 flags, pat if (encoremode) amnumxpos = -amnumxpos; - amxpos = amnumxpos + ((x + AutomapPic->width/2 - (( (skinlocal) ? localfacemmapprefix : facemmapprefix )[skin]->width/2))<height/2 - (( (skinlocal) ? localfacemmapprefix : facemmapprefix )[skin]->height/2))<width/2 - (((skinlocal) ? localfacemmapprefix : facemmapprefix)[skin]->width/2))<height/2 - (((skinlocal) ? localfacemmapprefix : facemmapprefix)[skin]->height/2))<color) // 'default' color V_DrawSciencePatch(amxpos, amypos, flags, ( (skinlocal) ? localfacemmapprefix : facemmapprefix )[skin], FRACUNIT); else { - UINT8 *colormap = R_GetTranslationColormap((mo->colorized) ? TC_RAINBOW : skin, mo->color, GTC_CACHE); + UINT8 *colormap; + if (mo->colorized) + colormap = R_GetTranslationColormap(TC_RAINBOW, mo->color, GTC_CACHE); + else + colormap = R_GetLocalTranslationColormap(mo->skin, mo->localskin, mo->color, GTC_CACHE, skinlocal); - if (cv_minihead.value == 1) - { - colormap = R_GetLocalTranslationColormap(mo->skin, mo->localskin, mo->color, GTC_CACHE, skinlocal); - V_DrawFixedPatch(amxpos + (2 * FRACUNIT), amypos + (2 * FRACUNIT), FRACUNIT/2, flags, ( (skinlocal) ? localfacemmapprefix : facemmapprefix )[skin], colormap); - } - else if (cv_minihead.value == 0) - { - colormap = R_GetLocalTranslationColormap(mo->skin, mo->localskin, mo->color, GTC_CACHE, skinlocal); - V_DrawFixedPatch(amxpos, amypos, FRACUNIT, flags, ( (skinlocal) ? localfacemmapprefix : facemmapprefix )[skin], colormap); - } + if (cv_minihead.value) + V_DrawFixedPatch(amxpos + (2*FRACUNIT), amypos + (2*FRACUNIT), FRACUNIT/2, flags, ((skinlocal) ? localfacemmapprefix : facemmapprefix)[skin], colormap); + else + V_DrawFixedPatch(amxpos, amypos, FRACUNIT, flags, ((skinlocal) ? localfacemmapprefix : facemmapprefix)[skin], colormap); if (cv_showminimapnames.value && !(modeattacking || gamestate == GS_TIMEATTACK)) { const char *player_name = va("%c%s", V_GetSkincolorChar(mo->color), player_names[mo->player - players]); - V_DrawCenteredSmallStringAtFixed(amxpos + (4 * FRACUNIT), amypos - (3 * FRACUNIT), V_ALLOWLOWERCASE|flags, player_name); + V_DrawCenteredSmallStringAtFixed(amxpos + (4*FRACUNIT), amypos - (3*FRACUNIT), V_ALLOWLOWERCASE|flags, player_name); } if (mo->player && ((G_RaceGametype() && mo->player->kartstuff[k_position] == spbplace) || (G_BattleGametype() && K_IsPlayerWanted(mo->player)))) { - if (cv_minihead.value == 1) - V_DrawFixedPatch(amxpos, amypos, FRACUNIT / 2, flags, kp_wantedreticle, NULL); - else if (cv_minihead.value == 0) - V_DrawFixedPatch(amxpos - (4<kartstuff[k_comebacktimer]/TICRATE)); else { - if (!cv_colorizedhud.value || !clr_hud) - V_DrawFixedPatch(x<kartstuff[k_lapanimation]; UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); @@ -9809,6 +9974,12 @@ void K_drawKartHUD(void) #endif K_drawInput(); + if (!demo.title && cv_showstats.value) +#ifdef HAVE_BLUA + if (LUA_HudEnabled(hud_statdisplay)) +#endif + K_drawKartStats(); + if (demo.title) // Draw title logo instead in demo.titles { INT32 x = BASEVIDWIDTH - 32, y = 128, offs; @@ -9886,12 +10057,16 @@ void K_drawKartHUD(void) { char *countstr = va("%d", racecountdown/TICRATE); + // Eeeh dunno if would be better to add another variable instead of LAPS_Y but this works too + int yoff = cv_dnft_yoffset.value - cv_laps_yoffset.value; + int xoff = cv_dnft_xoffset.value; + if (splitscreen > 1) - V_DrawCenteredString(BASEVIDWIDTH/4, LAPS_Y+1, K_calcSplitFlags(0), countstr); + V_DrawCenteredString(BASEVIDWIDTH/4+xoff, LAPS_Y+1+yoff, K_calcSplitFlags(0), countstr); else { INT32 karlen = strlen(countstr)*6; // half of 12 - V_DrawKartString((BASEVIDWIDTH/2)-karlen, LAPS_Y+3, K_calcSplitFlags(0), countstr); + V_DrawKartString((BASEVIDWIDTH/2)-karlen+xoff, LAPS_Y+3+yoff, K_calcSplitFlags(0), countstr); } } @@ -9900,7 +10075,7 @@ void K_drawKartHUD(void) { if (stplyr->exiting) K_drawKartFinish(); - else if (stplyr->kartstuff[k_lapanimation] && !splitscreen) + else if (stplyr->kartstuff[k_lapanimation] && !splitscreen && cv_showlapemblem.value) K_drawLapStartAnim(); } diff --git a/src/k_kart.h b/src/k_kart.h index 1b8e9c7ab..803594790 100644 --- a/src/k_kart.h +++ b/src/k_kart.h @@ -17,7 +17,7 @@ extern const UINT8 KartColor_Opposite[MAXSKINCOLORS*2]; void K_RainbowColormap(UINT8 *dest_colormap, UINT8 skincolor); void K_GenerateKartColormap(UINT8 *dest_colormap, INT32 skinnum, UINT8 color, boolean local); UINT8 K_GetKartColorByName(const char *name); -UINT8 K_GetHudColor(); +UINT8 K_GetHudColor(void); void K_RegisterKartStuff(void); @@ -26,6 +26,10 @@ extern consvar_t cv_colorizeditembox; extern consvar_t cv_colorizedhudcolor; extern consvar_t cv_darkitembox; extern consvar_t cv_biglaps; +extern consvar_t cv_highresportrait; +extern consvar_t cv_stat_xoffset; +extern consvar_t cv_stat_yoffset; +extern consvar_t cv_showstats; boolean K_IsPlayerLosing(player_t *player); boolean K_IsPlayerWanted(player_t *player); @@ -45,6 +49,7 @@ void K_ExplodePlayer(player_t *player, mobj_t *source, mobj_t *inflictor); void K_StealBumper(player_t *player, player_t *victim, boolean force); void K_SpawnKartExplosion(fixed_t x, fixed_t y, fixed_t z, fixed_t radius, INT32 number, mobjtype_t type, angle_t rotangle, boolean spawncenter, boolean ghostit, mobj_t *source); void K_SpawnMineExplosion(mobj_t *source, UINT8 color); +void K_RollMobjBySlopes(mobj_t *mo, boolean usedistance); void K_SpawnBoostTrail(player_t *player); void K_SpawnSparkleTrail(mobj_t *mo); void K_SpawnWipeoutTrail(mobj_t *mo, boolean translucent); diff --git a/src/lua_baselib.c b/src/lua_baselib.c index 5fd813dc5..9e42e7e9f 100644 --- a/src/lua_baselib.c +++ b/src/lua_baselib.c @@ -538,6 +538,18 @@ static int lib_pFlashPal(lua_State *L) return 0; } + +// not sure if this is netsafe... +static int lib_pRollPitchMobj(lua_State *L) +{ + mobj_t *source = *((mobj_t **)luaL_checkudata(L, 1, META_MOBJ)); + NOHUD + if (!source) + return LUA_ErrInvalid(L, "mobj_t"); + P_RollPitchMobj(source); + return 0; +} + static int lib_pGetClosestAxis(lua_State *L) { mobj_t *source = *((mobj_t **)luaL_checkudata(L, 1, META_MOBJ)); @@ -3033,6 +3045,7 @@ static luaL_Reg lib[] = { {"P_GetMobjGravity",lib_pGetMobjGravity}, {"P_WeaponOrPanel",lib_pWeaponOrPanel}, {"P_FlashPal",lib_pFlashPal}, + {"P_RollPitchMobj",lib_pRollPitchMobj}, {"P_GetClosestAxis",lib_pGetClosestAxis}, {"P_SpawnParaloop",lib_pSpawnParaloop}, {"P_BossTargetPlayer",lib_pBossTargetPlayer}, diff --git a/src/lua_hooklib.c b/src/lua_hooklib.c index d9344f65f..1e6a5cb29 100644 --- a/src/lua_hooklib.c +++ b/src/lua_hooklib.c @@ -430,6 +430,9 @@ void LUAh_PlayerJoin(int playernum) void LUAh_PreThinkFrame(void) { hook_p hookp; + // variables used by perf stats + int hook_index = 0; + precise_t time_taken = 0; if (!gL || !(hooksAvailable[hook_PreThinkFrame/8] & (1<<(hook_PreThinkFrame%8)))) return; @@ -437,19 +440,32 @@ void LUAh_PreThinkFrame(void) for (hookp = roothook; hookp; hookp = hookp->next) { - if (hookp->type != hook_PreThinkFrame) - continue; - - lua_pushfstring(gL, FMT_HOOKID, hookp->id); - lua_gettable(gL, LUA_REGISTRYINDEX); - if (lua_pcall(gL, 0, 0, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; + if (hookp->type == hook_PreThinkFrame) + { + if (cv_perfstats.value == 4) + time_taken = I_GetPreciseTime(); + lua_pushfstring(gL, FMT_HOOKID, hookp->id); + lua_gettable(gL, LUA_REGISTRYINDEX); + if (lua_pcall(gL, 0, 0, 1)) { + if (!hookp->error || cv_debug & DBG_LUA) + CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); + lua_pop(gL, 1); + hookp->error = true; + } + if (cv_perfstats.value == 4) + { + lua_Debug ar; + time_taken = I_GetPreciseTime() - time_taken; + // we need the function, let's just retrieve it again + lua_pushfstring(gL, FMT_HOOKID, hookp->id); + lua_gettable(gL, LUA_REGISTRYINDEX); + lua_getinfo(gL, ">S", &ar); + PS_SetPreThinkFrameHookInfo(hook_index, time_taken, ar.short_src); + hook_index++; + } } - } + } lua_pop(gL, 1); // Pop error handler } @@ -498,6 +514,9 @@ void LUAh_ThinkFrame(void) void LUAh_PostThinkFrame(void) { hook_p hookp; + // variables used by perf stats + int hook_index = 0; + precise_t time_taken = 0; if (!gL || !(hooksAvailable[hook_PostThinkFrame/8] & (1<<(hook_PostThinkFrame%8)))) return; @@ -505,19 +524,31 @@ void LUAh_PostThinkFrame(void) for (hookp = roothook; hookp; hookp = hookp->next) { - if (hookp->type != hook_PostThinkFrame) - continue; - - lua_pushfstring(gL, FMT_HOOKID, hookp->id); - lua_gettable(gL, LUA_REGISTRYINDEX); - if (lua_pcall(gL, 0, 0, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; + if (hookp->type == hook_PostThinkFrame) + { + if (cv_perfstats.value == 5) + time_taken = I_GetPreciseTime(); + lua_pushfstring(gL, FMT_HOOKID, hookp->id); + lua_gettable(gL, LUA_REGISTRYINDEX); + if (lua_pcall(gL, 0, 0, 1)) { + if (!hookp->error || cv_debug & DBG_LUA) + CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); + lua_pop(gL, 1); + hookp->error = true; + } + if (cv_perfstats.value == 5) + { + lua_Debug ar; + time_taken = I_GetPreciseTime() - time_taken; + // we need the function, let's just retrieve it again + lua_pushfstring(gL, FMT_HOOKID, hookp->id); + lua_gettable(gL, LUA_REGISTRYINDEX); + lua_getinfo(gL, ">S", &ar); + PS_SetPostThinkFrameHookInfo(hook_index, time_taken, ar.short_src); + hook_index++; + } } } - lua_pop(gL, 1); // Pop error handler } diff --git a/src/lua_hud.h b/src/lua_hud.h index 26b8cf0b0..db759bbfa 100644 --- a/src/lua_hud.h +++ b/src/lua_hud.h @@ -31,6 +31,7 @@ enum hud { hud_battlecomebacktimer, // comeback timer in battlefullscreen. separated for ease of use. hud_wanted, hud_speedometer, + hud_statdisplay, hud_freeplay, hud_rankings, // Tab rankings diff --git a/src/lua_hudlib.c b/src/lua_hudlib.c index f58d9ca72..c7b1ec38e 100644 --- a/src/lua_hudlib.c +++ b/src/lua_hudlib.c @@ -11,6 +11,7 @@ /// \brief custom HUD rendering library for Lua scripting #include "doomdef.h" +#include "fastcmp.h" #ifdef HAVE_BLUA #include "r_defs.h" #include "r_local.h" @@ -54,6 +55,7 @@ static const char *const hud_disable_options[] = { "battlecomebacktimer", // come back timer in battlefullscreen "wanted", "speedometer", + "statdisplay", "freeplay", "rankings", NULL}; @@ -345,6 +347,118 @@ static int libd_cachePatch(lua_State *L) return 1; } +// this is structured like getSprite2Patch in vanilla 2.2 +// v.getSpritePatch(skin, sprite, [frame, [angle, [rollangle]]]) +static int libd_getSpritePatch(lua_State *L) +{ + UINT32 i; // sprite prefix + INT32 skn = -1; // skin number + UINT32 frame = 0; // 'A' + UINT8 angle = 0; + spritedef_t *sprdef; + spriteframe_t *sprframe; +#ifdef ROTSPRITE + spriteinfo_t *sprinfo; +#endif + HUDONLY + + // mashing together the stuff from getSprite2Patch: + // get skin first! + if (!lua_isnoneornil(L, 1)) // ONLY do this if we have a skin + { + if (lua_isnumber(L, 1)) // find skin by number + { + skn = lua_tonumber(L, 1); + if (skn < 0 || skn >= MAXSKINS) + return luaL_error(L, "skin number %d out of range (0 - %d)", skn, MAXSKINS-1); + if (skn >= numskins) + return 0; + } + else // find skin by name + { + const char *name = luaL_checkstring(L, 1); + for (skn = 0; skn < numskins; skn++) + if (fastcmp(skins[skn].name, name)) + break; + if (skn >= numskins) + return 0; + } + } + + lua_remove(L, 1); // remove skin now + + if (lua_isnumber(L, 1)) // sprite number given, e.g. SPR_THOK + { + i = lua_tonumber(L, 1); + if (i >= NUMSPRITES) + return 0; + } + else if (lua_isstring(L, 1)) // sprite prefix name given, e.g. "THOK" + { + const char *name = lua_tostring(L, 1); + for (i = 0; i < NUMSPRITES; i++) + if (fastcmp(name, sprnames[i])) + break; + if (i >= NUMSPRITES) + return 0; + } + else + return 0; + + // get outta dodge if we're a playersprite and have no skin + if ((i == SPR_PLAY) && (skn < 0)) + return luaL_error(L, "You must provide a skin for player sprites!"); + + if (skn < 0) // standard sprite + { + sprdef = &sprites[i]; + sprinfo = &spriteinfo[i]; + } + else // player skin + { + sprdef = &skins[skn].spritedef; + sprinfo = &skins[skn].sprinfo; + } + + // set frame number + frame = luaL_optinteger(L, 2, 0); + frame &= FF_FRAMEMASK; // ignore any bits that are not the actual frame, just in case + if (frame >= sprdef->numframes) + return 0; + // set angle number + sprframe = &sprdef->spriteframes[frame]; + angle = luaL_optinteger(L, 3, 1); + + // convert WAD editor angle numbers (1-8) to internal angle numbers (0-7) + // keep 0 the same since we'll make it default to angle 1 (which is internally 0) + // in case somebody didn't know that angle 0 really just maps all 8 angles to the same patch + if (angle != 0) + angle--; + + if (angle >= 8) // out of range? + angle = (angle & 7); // modulus angle by 8 + + // rotsprite????? + if (lua_isnumber(L, 4) && (cv_spriteroll.value)) + { + angle_t rollangle = luaL_checkangle(L, 4); + INT32 rot = R_GetRollAngle(rollangle); + + if (rot) { + patch_t *rotsprite = Patch_GetRotatedSprite(sprframe, frame, angle, sprframe->flip & (1<lumppat[angle], PU_STATIC), META_PATCH); + lua_pushboolean(L, (sprframe->flip & (1<colormap = colormap; } +void LUA_HUD_AddDrawStretched( + huddrawlist_h list, + fixed_t x, + fixed_t y, + fixed_t hscale, + fixed_t vscale, + patch_t *patch, + INT32 flags, + UINT8 *colormap +) +{ + size_t i = AllocateDrawItem(list); + drawitem_t *item = &list->items[i]; + item->type = DI_DrawStretched; + item->x = x; + item->y = y; + item->hscale = hscale; + item->vscale = vscale; + item->patch = patch; + item->flags = flags; + item->colormap = colormap; +} + void LUA_HUD_AddDrawNum( huddrawlist_h list, INT32 x, @@ -377,6 +401,9 @@ void LUA_HUD_DrawList(huddrawlist_h list) case DI_DrawScaled: V_DrawFixedPatch(item->x, item->y, item->scale, item->flags, item->patch, item->colormap); break; + case DI_DrawStretched: + V_DrawStretchyFixedPatch(item->x, item->y, item->hscale, item->vscale, item->flags, item->patch, item->colormap); + break; case DI_DrawNum: V_DrawTallNum(item->x, item->y, item->flags, item->num); break; diff --git a/src/lua_hudlib_drawlist.h b/src/lua_hudlib_drawlist.h index 992578778..4354b6f95 100644 --- a/src/lua_hudlib_drawlist.h +++ b/src/lua_hudlib_drawlist.h @@ -42,6 +42,16 @@ void LUA_HUD_AddDraw( INT32 flags, UINT8 *colormap ); +void LUA_HUD_AddDrawStretched( + huddrawlist_h list, + fixed_t x, + fixed_t y, + fixed_t hscale, + fixed_t vscale, + patch_t *patch, + INT32 flags, + UINT8 *colormap +); void LUA_HUD_AddDrawScaled( huddrawlist_h list, fixed_t x, diff --git a/src/lua_mobjlib.c b/src/lua_mobjlib.c index cfc5c8e5f..9a7ea9828 100644 --- a/src/lua_mobjlib.c +++ b/src/lua_mobjlib.c @@ -83,8 +83,11 @@ static const udata_field_t mobj_fields[] = { FIELD(mobj_t, snext, udatalib_getter_mobj, mobj_snext_noset), FIELD(mobj_t, sprev, mobj_sprev_unimplemented, mobj_sprev_unimplemented), FIELD(mobj_t, angle, udatalib_getter_angle, mobj_angle_setter), + FIELD(mobj_t, pitch, udatalib_getter_angle, udatalib_setter_angle), + FIELD(mobj_t, roll, udatalib_getter_angle, udatalib_setter_angle), FIELD(mobj_t, rollangle, udatalib_getter_angle, udatalib_setter_angle), FIELD(mobj_t, sloperoll, udatalib_getter_angle, mobj_sloperoll_noop), + FIELD(mobj_t, slopepitch, udatalib_getter_angle, mobj_sloperoll_noop), // Macro fails here { "rollsum", 0, mobj_rollsum_getter, mobj_rollsum_noset }, FIELD(mobj_t, sprite, udatalib_getter_spritenum, udatalib_setter_spritenum), @@ -143,6 +146,7 @@ static const udata_field_t mobj_fields[] = { FIELD(mobj_t, cvmem, udatalib_getter_int32, udatalib_setter_int32), FIELD(mobj_t, standingslope, udatalib_getter_slope, mobj_standingslope_noset), FIELD(mobj_t, colorized, udatalib_getter_boolean, udatalib_setter_boolean), + FIELD(mobj_t, mirrored, udatalib_getter_boolean, udatalib_setter_boolean), FIELD(mobj_t, rollmodel, udatalib_getter_boolean, udatalib_setter_boolean), { NULL }, }; @@ -217,7 +221,7 @@ UNIMPLEMENTED(mobjnum) // For some dumb reason it is valid to set sloperoll, even though it is read // only -int mobj_sloperoll_noop(lua_State *L) { return 0; } +int mobj_sloperoll_noop(lua_State *L) { (void)L; return 0; } // Now other getters/setters with arbitary logic @@ -415,13 +419,48 @@ int mobj_localskin_setter(lua_State *L) { mobj_t *mo = GETMO(); - // TODO - add ability to set localskin to non-player mobjs - // Will probably just need to reimplement SetLocalPlayerSkin as something - // like SetLocalObjectSkin - if (!mo->player) - return luaL_error(L, "mobj.localskin can't be set for non-player mobjs!"); + if (mo->player) + { + SetLocalPlayerSkin(mo->player - players, luaL_optstring(L, 2, "none"), NULL); + } + else + { + INT32 i; + char skin[SKINNAMESIZE+1]; // all skin names are limited to this length + strlcpy(skin, luaL_optstring(L, 2, "none"), sizeof skin); + strlwr(skin); // all skin names are lowercase + + if (strcasecmp(skin, "none")) + { + // Try localskins + for (i = 0; i < numlocalskins; i++) + { + if (stricmp(localskins[i].name, skin) == 0) + { + mo->localskin = &localskins[i]; + mo->skinlocal = true; + return 0; + } + } + + // Try other skins + for (i = 0; i < numskins; i++) + { + if (fastcmp(skins[i].name, skin)) + { + mo->localskin = &skins[i]; + mo->skinlocal = false; + return 0; + } + } + } + else + { + mo->localskin = 0; + mo->skinlocal = false; + } + } - SetLocalPlayerSkin(mo->player - players, luaL_checkstring(L, 2), NULL); return 0; } @@ -596,7 +635,9 @@ int mobj_rollsum_getter(lua_State *L) { mobj_t *mo = GETMO(); - angle_t rollsum = mo->rollangle + cv_sloperoll.value ? mo->sloperoll : 0; + angle_t pitchnroll = P_MobjPitchAndRoll(mo); + + angle_t rollsum = mo->rollangle + pitchnroll; if (mo->player) { diff --git a/src/lua_playerlib.c b/src/lua_playerlib.c index 1b095f7a5..eb537d51f 100644 --- a/src/lua_playerlib.c +++ b/src/lua_playerlib.c @@ -303,7 +303,7 @@ int player_localskin_setter(lua_State *L) { player_t *plr = GETPLAYER(); - SetLocalPlayerSkin(plr - players, luaL_checkstring(L, 2), NULL); + SetLocalPlayerSkin(plr - players, luaL_optstring(L, 2, "none"), NULL); return 0; } diff --git a/src/m_anigif.c b/src/m_anigif.c index 8071f030d..744651319 100644 --- a/src/m_anigif.c +++ b/src/m_anigif.c @@ -465,19 +465,23 @@ static size_t gifframe_size = 8192; static void GIF_rgbconvert(UINT8 *linear, UINT8 *scr) { UINT8 r, g, b; - size_t src = 0, dest = 0; - size_t size = (vid.width * vid.height * 3); + size_t src, dest; + int x, y; InitColorLUT(); - while (src < size) + for (x = 0; x < vid.width; x += scrbuf_downscaleamt) { - r = (UINT8)linear[src]; - g = (UINT8)linear[src + 1]; - b = (UINT8)linear[src + 2]; - scr[dest] = colorlookup[r >> SHIFTCOLORBITS][g >> SHIFTCOLORBITS][b >> SHIFTCOLORBITS]; - src += (3 * scrbuf_downscaleamt); - dest += scrbuf_downscaleamt; + for (y = 0; y < vid.height; y += scrbuf_downscaleamt) + { + dest = y*vid.width + x; + src = dest*3; + + r = (UINT8)linear[src]; + g = (UINT8)linear[src + 1]; + b = (UINT8)linear[src + 2]; + scr[dest] = colorlookup[r >> SHIFTCOLORBITS][g >> SHIFTCOLORBITS][b >> SHIFTCOLORBITS]; + } } } #endif @@ -514,7 +518,7 @@ static void GIF_framewrite(void) { UINT8 *linear = HWR_GetScreenshot(); GIF_rgbconvert(linear, movie_screen); - free(linear); + //free(linear); // Allocated 'statically', no need to free now } #endif } @@ -530,7 +534,7 @@ static void GIF_framewrite(void) { UINT8 *linear = HWR_GetScreenshot(); GIF_rgbconvert(linear, screens[0]); - free(linear); + //free(linear); // Allocated 'statically', no need to free now } #endif diff --git a/src/m_fixed.h b/src/m_fixed.h index 2cb1ddd2e..4e4c79c65 100644 --- a/src/m_fixed.h +++ b/src/m_fixed.h @@ -20,11 +20,6 @@ #include #endif -// Was this just for the #define USEASM? -//#ifdef _WIN32_WCE -//#include "sdl12/SRB2CE/cehelp.h" -//#endif - /*! \brief bits of the fraction */ @@ -37,12 +32,7 @@ /** \brief Redefinition of INT32 as fixed_t unit used as fixed_t */ - -//Max number a stat can have -#define MAXSTAT 9 - typedef INT32 fixed_t; - typedef UINT32 ufixed_t; /*! @@ -63,7 +53,6 @@ FUNCMATH FUNCINLINE static ATTRINLINE fixed_t FloatToFixed(float f) #define FIXED_TO_FLOAT(x) FixedToFloat(x) // (((float)(x)) / ((float)FRACUNIT)) #define FLOAT_TO_FIXED(f) FloatToFixed(f) // (fixed_t)((f) * ((float)FRACUNIT)) - /** \brief The FixedMul function \param a fixed_t number diff --git a/src/m_menu.c b/src/m_menu.c index dd3d111d9..80e0ba5db 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -95,6 +95,7 @@ #define SLIDER_RANGE 10 #define SLIDER_WIDTH (8*SLIDER_RANGE+6) #define SERVERS_PER_PAGE 11 +#define MAXSTAT 9 //Max number a stat can have typedef enum { @@ -146,6 +147,8 @@ boolean browselocalskins = false; boolean menuactive = false; boolean fromlevelselect = false; +static INT32 coolalphatimer = 9; + typedef enum { LLM_CREATESERVER, @@ -222,6 +225,7 @@ static void M_GetAllEmeralds(INT32 choice); static void M_DestroyRobots(INT32 choice); //static void M_LevelSelectWarp(INT32 choice); static void M_Credits(INT32 choice); +static void M_MusicTest(INT32 choice); static void M_PandorasBox(INT32 choice); static void M_EmblemHints(INT32 choice); static char *M_GetConditionString(condition_t cond); @@ -271,12 +275,16 @@ static menu_t SP_TimeAttackDef, SP_ReplayDef, SP_GuestReplayDef, SP_GhostDef; // Multiplayer #ifndef NONET static void M_PreStartServerMenu(INT32 choice); +#ifdef MASTERSERVER static void M_PreStartServerMenuChoice(event_t *ev); static void M_PreConnectMenu(INT32 choice); static void M_PreConnectMenuChoice(event_t *ev); +#endif static void M_StartServerMenu(INT32 choice); +#ifdef MASTERSERVER static void M_ConnectMenu(INT32 choice); static void M_ConnectMenuModChecks(INT32 choice); +#endif static void M_Refresh(INT32 choice); static void M_Connect(INT32 choice); #endif @@ -310,9 +318,9 @@ static void M_ChangeControl(INT32 choice); static void M_ResetControls(INT32 choice); // Video & Sound -menu_t OP_VideoOptionsDef, OP_VideoModeDef; +menu_t OP_VideoOptionsDef, OP_VideoModeDef, OP_ExpOptionsDef, OP_ColorOptionsDef; #ifdef HWRENDER -menu_t OP_OpenGLOptionsDef, OP_OpenGLColorDef; +menu_t OP_OpenGLOptionsDef; #endif menu_t OP_SoundOptionsDef; menu_t OP_SoundAdvancedDef; @@ -382,11 +390,12 @@ static UINT8 playback_enterheld = 0; // horrid hack to prevent holding the butto // Drawing functions static void M_DrawGenericMenu(void); static void M_DrawGenericBackgroundMenu(void); -//static void M_DrawGenericScrollMenu(void); +static void M_DrawGenericScrollMenu(void); static void M_DrawCenteredMenu(void); static void M_DrawAddons(void); static void M_DrawSkyRoom(void); static void M_DrawChecklist(void); +static void M_DrawMusicTest(void); static void M_DrawEmblemHints(void); static void M_DrawPauseMenu(void); static void M_DrawLevelSelectOnly(boolean leftfade, boolean rightfade); @@ -401,10 +410,8 @@ static void M_DrawControl(void); static void M_DrawVideoMenu(void); static void M_DrawHUDOptions(void); static void M_DrawVideoMode(void); +static void M_DrawColorMenu(void); static void M_DrawMonitorToggles(void); -#ifdef HWRENDER -static void M_OGL_DrawColorMenu(void); -#endif static void M_DrawMPMainMenu(void); #ifndef NONET static void M_DrawConnectMenu(void); @@ -421,6 +428,7 @@ static boolean M_ExitPandorasBox(void); static boolean M_QuitMultiPlayerMenu(void); static void M_HandleAddons(INT32 choice); static void M_HandleSoundTest(INT32 choice); +static void M_HandleMusicTest(INT32 choice); static void M_HandleImageDef(INT32 choice); //static void M_HandleLoadSave(INT32 choice); static void M_HandleLevelStats(INT32 choice); @@ -430,6 +438,7 @@ static void M_ConnectLastServer(INT32 choice); #endif static void M_HandleSetupMultiPlayer(INT32 choice); static void M_HandleVideoMode(INT32 choice); +static void M_ResetCvars(void); static void M_HandleMonitorToggles(INT32 choice); // Consvar onchange functions @@ -461,7 +470,9 @@ CV_PossibleValue_t gametype_cons_t[NUMGAMETYPES+1]; consvar_t cv_newgametype = {"newgametype", "Race", CV_HIDEN|CV_CALL, gametype_cons_t, Newgametype_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_showallmaps = {"showallmaps", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL }; +consvar_t cv_showallmaps = {"showallmaps", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_showmusicfilename = {"showmusicfilename", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t serversort_cons_t[] = { {0,"Ping"}, @@ -852,6 +863,12 @@ static menuitem_t SR_UnlockChecklistMenu[] = {IT_SUBMENU | IT_STRING, NULL, "NEXT", &MainDef, 192}, }; +static menuitem_t SR_MusicTestMenu[] = +{ + {IT_KEYHANDLER | IT_STRING, NULL, "", M_HandleMusicTest, 0}, +}; + + static menuitem_t SR_EmblemHintMenu[] = { {IT_STRING|IT_CVAR, NULL, "Medal Radar", &cv_itemfinder, 10}, @@ -1046,7 +1063,11 @@ static menuitem_t MP_MainMenu[] = {IT_HEADER, NULL, "Join a game", NULL, 132-24}, #ifndef NONET +#ifndef MASTERSERVER + {IT_GRAYEDOUT, NULL, "Internet server browser...",NULL, 142-24}, +#else {IT_STRING|IT_CALL, NULL, "Internet server browser...",M_PreConnectMenu, 142-24}, +#endif {IT_STRING|IT_CALL, NULL, "Join last server", M_ConnectLastServer, 150-24}, {IT_STRING|IT_KEYHANDLER, NULL, "Specify IPv4 address:", M_HandleConnectIP, 158-24}, #else @@ -1063,7 +1084,11 @@ static menuitem_t MP_MainMenu[] = static menuitem_t MP_ServerMenu[] = { {IT_STRING|IT_CVAR, NULL, "Max. Player Count", &cv_maxplayers, 10}, +#ifndef MASTERSERVER + {IT_GRAYEDOUT, NULL, "Advertise", NULL, 20}, +#else {IT_STRING|IT_CVAR, NULL, "Advertise", &cv_advertise, 20}, +#endif {IT_STRING|IT_CVAR|IT_CV_STRING, NULL, "Server Name", &cv_servername, 30}, {IT_STRING|IT_CVAR, NULL, "Game Type", &cv_newgametype, 68}, @@ -1082,7 +1107,7 @@ static menuitem_t MP_OfflineServerMenu[] = {IT_WHITESTRING|IT_CALL, NULL, "Start", M_StartServer, 130}, }; - +//Char select static menuitem_t MP_PlayerSetupMenu[] = { {IT_KEYHANDLER | IT_STRING, NULL, "Name", M_HandleSetupMultiPlayer, 0}, @@ -1090,6 +1115,9 @@ static menuitem_t MP_PlayerSetupMenu[] = {IT_KEYHANDLER | IT_STRING, NULL, "Color", M_HandleSetupMultiPlayer, 152}, }; + + + #ifndef NONET static menuitem_t MP_ConnectMenu[] = { @@ -1152,9 +1180,22 @@ static menuitem_t OP_ControlsMenu[] = {IT_CALL | IT_STRING, NULL, "Player 3 Controls...", &M_Setup3PControlsMenu, 30}, {IT_CALL | IT_STRING, NULL, "Player 4 Controls...", &M_Setup4PControlsMenu, 40}, + + {IT_SUBMENU | IT_STRING, NULL, "Mouse Options...", &OP_MouseOptionsDef, 60}, - {IT_STRING | IT_CVAR, NULL, "Controls per key", &cv_controlperkey, 60}, - {IT_STRING | IT_CVAR, NULL, "Digital turn easing", &cv_turnsmooth, 70}, + {IT_STRING | IT_CVAR, NULL, "Controls per key", &cv_controlperkey, 80}, + {IT_STRING | IT_CVAR, NULL, "Digital turn easing", &cv_turnsmooth, 90}, +}; + +static const char* OP_ControlsTooltips[] = +{ + "Setup player 1 controls.", + "Setup player 2 controls.", + "Setup player 3 controls.", + "Setup player 4 controls.", + "Options for mouse control.", + "Allowed amount of controls per key.", + "Turn smoothing for non-analog turning.", }; static menuitem_t OP_AllControlsMenu[] = @@ -1271,22 +1312,32 @@ static menuitem_t OP_JoystickSetMenu[] = {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*8)+5}, }; -/*static menuitem_t OP_MouseOptionsMenu[] = +//WTF +static menuitem_t OP_MouseOptionsMenu[] = { {IT_STRING | IT_CVAR, NULL, "Use Mouse", &cv_usemouse, 10}, - {IT_STRING | IT_CVAR, NULL, "First-Person MouseLook", &cv_alwaysfreelook, 30}, - {IT_STRING | IT_CVAR, NULL, "Third-Person MouseLook", &cv_chasefreelook, 40}, - {IT_STRING | IT_CVAR, NULL, "Mouse Move", &cv_mousemove, 50}, - {IT_STRING | IT_CVAR, NULL, "Invert Mouse", &cv_invertmouse, 60}, + //{IT_STRING | IT_CVAR, NULL, "First-Person MouseLook", &cv_alwaysfreelook, 30}, + //{IT_STRING | IT_CVAR, NULL, "Third-Person MouseLook", &cv_chasefreelook, 40}, + {IT_STRING | IT_CVAR, NULL, "Mouse Turning", &cv_mouseturn, 20}, + {IT_STRING | IT_CVAR, NULL, "Invert Mouse", &cv_invertmouse, 30}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Mouse X Speed", &cv_mousesens, 70}, + NULL, "Mouse X Speed", &cv_mousesens, 40}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Mouse Y Speed", &cv_mouseysens, 80}, + NULL, "Mouse Y Speed", &cv_mouseysens, 50}, }; -static menuitem_t OP_Mouse2OptionsMenu[] = +static const char* OP_MouseTooltips[] = +{ + "Enable the use of the mouse.", + "Turn using the mouse.", + "Invert mouse movements.", + "Mouse horizontal sensitivity.", + "Mouse vertical sensitivity.", +}; + +/*static menuitem_t OP_Mouse2OptionsMenu[] = { {IT_STRING | IT_CVAR, NULL, "Use Mouse 2", &cv_usemouse2, 10}, {IT_STRING | IT_CVAR, NULL, "Second Mouse Serial Port", @@ -1308,27 +1359,58 @@ static menuitem_t OP_VideoOptionsMenu[] = {IT_STRING|IT_CVAR, NULL, "Fullscreen", &cv_fullscreen, 20}, #endif {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Gamma", &cv_usegamma, 30}, + NULL, "Brightness", &cv_globalgamma, 30}, - {IT_STRING | IT_CVAR, NULL, "Draw Distance", &cv_drawdist, 45}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, + NULL, "Saturation", &cv_globalsaturation , 40}, + + {IT_SUBMENU|IT_STRING, NULL, "Advanced Color Settings...", &OP_ColorOptionsDef, 50}, + + {IT_STRING | IT_CVAR, NULL, "Draw Distance", &cv_drawdist, 65}, //{IT_STRING | IT_CVAR, NULL, "NiGHTS Draw Dist", &cv_drawdist_nights, 55}, - {IT_STRING | IT_CVAR, NULL, "Weather Draw Distance",&cv_drawdist_precip, 55}, + {IT_STRING | IT_CVAR, NULL, "Weather Draw Distance",&cv_drawdist_precip, 75}, //{IT_STRING | IT_CVAR, NULL, "Weather Density", &cv_precipdensity, 65}, - {IT_STRING | IT_CVAR, NULL, "Skyboxes", &cv_skybox, 65}, - {IT_STRING | IT_CVAR, NULL, "Field of View", &cv_fov, 75}, - - {IT_STRING | IT_CVAR, NULL, "Show FPS", &cv_ticrate, 90}, - {IT_STRING | IT_CVAR, NULL, "Vertical Sync", &cv_vidwait, 100}, - {IT_STRING | IT_CVAR, NULL, "FPS Cap", &cv_fpscap, 110}, - {IT_STRING | IT_CVAR, NULL, "Drift spark pulse size",&cv_driftsparkpulse, 125}, - {IT_STRING | IT_CVAR, NULL, "Uppercase Menu", &cv_menucaps, 135}, + {IT_STRING | IT_CVAR, NULL, "Skyboxes", &cv_skybox, 85}, + {IT_STRING | IT_CVAR, NULL, "Field of View", &cv_fov, 95}, + {IT_STRING | IT_CVAR, NULL, "Show FPS", &cv_ticrate, 105}, + {IT_STRING | IT_CVAR, NULL, "Vertical Sync", &cv_vidwait, 115}, + {IT_STRING | IT_CVAR, NULL, "FPS Cap", &cv_fpscap, 125}, + {IT_STRING | IT_CVAR, NULL, "Drift spark pulse size",&cv_driftsparkpulse, 135}, + {IT_STRING | IT_CVAR, NULL, "Uppercase Menu", &cv_menucaps, 145}, #ifdef HWRENDER - {IT_SUBMENU|IT_STRING, NULL, "OpenGL Options...", &OP_OpenGLOptionsDef, 145}, + {IT_SUBMENU|IT_STRING, NULL, "OpenGL Options...", &OP_OpenGLOptionsDef, 155}, #endif + {IT_SUBMENU|IT_STRING, NULL, "Experimental Options...", &OP_ExpOptionsDef, 165}, + }; +static const char* OP_VideoTooltips[] = +{ + "Resolution game runs at.", +#if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) + "Enable fullscreen.", +#endif + "Gamma (brightness) of the game.", + NULL, + NULL, + "How far away objects are drawn.", + "How far away weather is drawn.", + "Toggle being able to see the sky.", + "Player field of view.", + "Show current game framerate and select the style.", + "Sync game framerate to refresh rate of monitor.", + "Set manual framerate cap.", + "Size of drift spark pulse.", + "Force menu to only use uppercase.", +#ifdef HWRENDER + "Options for OpenGL renderer.", +#endif + "Experimental graphical options.", +}; + + enum { op_video_res = 0, @@ -1336,6 +1418,8 @@ enum op_video_fullscreen, #endif op_video_gamma, + op_video_sat, + op_video_color, op_video_dd, op_video_wdd, //op_video_wd, @@ -1349,6 +1433,7 @@ enum #ifdef HWRENDER op_video_ogl, #endif + op_video_exp, }; static menuitem_t OP_VideoModeMenu[] = @@ -1356,37 +1441,145 @@ static menuitem_t OP_VideoModeMenu[] = {IT_KEYHANDLER | IT_NOTHING, NULL, "", M_HandleVideoMode, '\0'}, // dummy menuitem for the control func }; +static menuitem_t OP_ColorOptionsMenu[] = +{ + {IT_STRING | IT_CALL, NULL, "Reset all", M_ResetCvars, 0}, + + {IT_HEADER, NULL, "Red", NULL, 9}, + {IT_DISABLED, NULL, NULL, NULL, 35}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_rhue, 15}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_rsaturation, 20}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_rgamma, 25}, + + {IT_HEADER, NULL, "Yellow", NULL, 34}, + {IT_DISABLED, NULL, NULL, NULL, 73}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_yhue, 40}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_ysaturation, 45}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_ygamma, 50}, + + {IT_HEADER, NULL, "Green", NULL, 59}, + {IT_DISABLED, NULL, NULL, NULL, 112}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_ghue, 65}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_gsaturation, 70}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_ggamma, 75}, + + {IT_HEADER, NULL, "Cyan", NULL, 84}, + {IT_DISABLED, NULL, NULL, NULL, 255}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_chue, 90}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_csaturation, 95}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_cgamma, 100}, + + {IT_HEADER, NULL, "Blue", NULL, 109}, + {IT_DISABLED, NULL, NULL, NULL, 152}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_bhue, 115}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_bsaturation, 120}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_bgamma, 125}, + + {IT_HEADER, NULL, "Magenta", NULL, 134}, + {IT_DISABLED, NULL, NULL, NULL, 181}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_mhue, 140}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_msaturation, 145}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_mgamma, 150}, +}; + +static menuitem_t OP_ExpOptionsMenu[] = +{ + {IT_HEADER, NULL, "Experimental Options", NULL, 10}, + {IT_STRING | IT_CVAR, NULL, "Weather Interpolation", &cv_precipinterp, 25}, + {IT_STRING | IT_CVAR, NULL, "Less Weather Effects", &cv_lessprecip, 35}, + + {IT_STRING | IT_CVAR, NULL, "VHS effect", &cv_vhseffect, 55}, + + {IT_STRING | IT_CVAR, NULL, "FFloorclip", &cv_ffloorclip, 75}, + {IT_STRING | IT_CVAR, NULL, "Spriteclip", &cv_spriteclip, 85}, +#ifdef HWRENDER + {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_grscreentextures, 75}, + + {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_grpalettedepth, 85}, + + {IT_STRING | IT_CVAR, NULL, "Splitwall/Slope texture fix", &cv_splitwallfix, 105}, + {IT_STRING | IT_CVAR, NULL, "Slope midtexture peg fix", &cv_slopepegfix, 115}, + {IT_STRING | IT_CVAR, NULL, "ZFighting fix for fofs", &cv_fofzfightfix, 125}, + {IT_STRING | IT_CVAR, NULL, "FOF wall cutoff for slopes", &cv_grfofcut, 135}, +#endif +}; + +static const char* OP_ExpTooltips[] = +{ + NULL, + "Should weather be interpolated? Weather should look about the\nsame but perform a bit better when disabled.", + "When weather is on this will cut the object amount used in half.", + "Show a VHS-like effect when the game is paused\n or youre rewinding replays.", + "Hides 3DFloors which are not visible\npotentially resulting in a performance boost.", + "Hides Sprites which are not visible\npotentially resulting in a performance boost.", +#ifdef HWRENDER + "Should the game do Screen Textures? Provides a good boost to frames\nat the cost of some visual effects not working when disabled.", + "Change the depth of the Palette in Palette rendering mod\n 16 bits is like software looks ingame\nwhile 24 bits is how software looks in screenshots.", + "Fixes issues that resulted in Textures sticking from the ground sometimes.\n This may be CPU heavy and result in worse performance in some cases.", + "Fixes issues that resulted in Textures not being properly skewed\n example: Fences on slopes that didnt show proper.\n This may be CPU heavy and result in worse performance in some cases.", + "Fixes issues that resulted in Textures on Floor over Floors\nZFighting heavily.", + "Toggle for FOF wall cutoff with slopes.", +#endif +}; + +enum +{ + op_exp_header, + op_exp_precipinter, + op_exp_lessprecip, + op_exp_vhs, + op_exp_ffclip, + op_exp_sprclip, +#ifdef HWRENDER + op_exp_grscrtx, + op_exp_spltwal, + op_exp_pegging, + op_exp_fofzfight, + op_exp_fofcut, +#endif +}; + + #ifdef HWRENDER static menuitem_t OP_OpenGLOptionsMenu[] = { - {IT_STRING | IT_CVAR, NULL, "3D Models", &cv_grmdls, 5}, - {IT_STRING | IT_CVAR, NULL, "Fallback Player 3D Model", &cv_grfallbackplayermodel, 15}, + {IT_STRING | IT_CVAR, NULL, "3D Models", &cv_grmdls, 15}, + {IT_STRING | IT_CVAR, NULL, "Fallback Player 3D Model", &cv_grfallbackplayermodel, 20}, {IT_STRING | IT_CVAR, NULL, "Shaders", &cv_grshaders, 25}, //{IT_STRING|IT_CVAR, NULL, "Use custom Shaders", &cv_grusecustomshaders, 35}, - {IT_STRING | IT_CVAR, NULL, "Palette Rendering", &cv_grpaletteshader, 35}, - {IT_STRING | IT_CVAR, NULL, "Flashpals in Palette Renderer", &cv_grflashpal, 45}, - {IT_STRING | IT_CVAR, NULL, "Min Shader Brightness", &cv_secbright, 55}, + {IT_STRING | IT_CVAR, NULL, "Palette Rendering", &cv_grpaletterendering, 30}, + {IT_STRING | IT_CVAR, NULL, "Flashpals in Palette Renderer", &cv_grflashpal, 35}, + {IT_STRING | IT_CVAR, NULL, "Min Shader Brightness", &cv_secbright, 40}, - {IT_STRING|IT_CVAR, NULL, "Texture Quality", &cv_scr_depth, 70}, - {IT_STRING|IT_CVAR, NULL, "Texture Filter", &cv_grfiltermode, 80}, - {IT_STRING|IT_CVAR, NULL, "Anisotropic", &cv_granisotropicmode, 90}, + {IT_STRING|IT_CVAR, NULL, "Texture Quality", &cv_scr_depth, 50}, + {IT_STRING|IT_CVAR, NULL, "Texture Filter", &cv_grfiltermode, 55}, + {IT_STRING|IT_CVAR, NULL, "Anisotropic", &cv_granisotropicmode, 60}, + {IT_STRING|IT_CVAR, NULL, "Visual Portals", &cv_grportals, 65}, - {IT_STRING|IT_CVAR, NULL, "Visual Portals", &cv_grportals, 100}, - - {IT_STRING|IT_CVAR, NULL, "Wall Contrast Style", &cv_grfakecontrast, 120}, - {IT_STRING|IT_CVAR, NULL, "Slope Contrast", &cv_grslopecontrast, 130}, - {IT_STRING|IT_CVAR, NULL, "Sprite Billboarding", &cv_grspritebillboarding, 140}, - {IT_STRING|IT_CVAR, NULL, "Software Perspective", &cv_grshearing, 150}, - {IT_STRING|IT_CVAR, NULL, "Rendering Distance", &cv_grrenderdistance, 160}, - - {IT_SUBMENU|IT_STRING, NULL, "Gamma...", &OP_OpenGLColorDef, 170}, + {IT_STRING|IT_CVAR, NULL, "Wall Contrast Style", &cv_grfakecontrast, 75}, + {IT_STRING|IT_CVAR, NULL, "Slope Contrast", &cv_grslopecontrast, 80}, + {IT_STRING|IT_CVAR, NULL, "Sprite Billboarding", &cv_grspritebillboarding, 85}, + {IT_STRING|IT_CVAR, NULL, "Software Perspective", &cv_grshearing, 90}, + {IT_STRING|IT_CVAR, NULL, "Rendering Distance", &cv_grrenderdistance, 95}, }; -static menuitem_t OP_OpenGLColorMenu[] = +static const char* OP_OpenGLTooltips[] = { - {IT_STRING|IT_CVAR|IT_CV_SLIDER, NULL, "Red", &cv_grgammared, 10}, - {IT_STRING|IT_CVAR|IT_CV_SLIDER, NULL, "Green", &cv_grgammagreen, 20}, - {IT_STRING|IT_CVAR|IT_CV_SLIDER, NULL, "Blue", &cv_grgammablue, 30}, + "Use 3D models.", + "Fallback 3D model for characters that don't have any.", + "Graphical Shaders.", + "Recreates the look of software mode.", + "Flash palettes for palette rendering.", + "Minimum shader brightness. This is set in sector brightness values.", + "Bit-depth of textures.", + "Filter to use on textures.", + "Anisotropic filtering.", + "Recreates an effect from software mode that is used on some maps.", + "The look of the wall contrast effect.", + "Wall contrast but for slopes.", + "Should sprites always face the camera?", + "Recreates the look of software mode camera perspective.", + "How far the game world should be drawn.", }; #endif @@ -1417,14 +1610,34 @@ static menuitem_t OP_SoundOptionsMenu[] = {IT_STRING|IT_CVAR, NULL, "Chat Notifications", &cv_chatnotifications, 75}, {IT_STRING|IT_CVAR, NULL, "Character voices", &cv_kartvoices, 85}, {IT_STRING|IT_CVAR, NULL, "Powerup Warning", &cv_kartinvinsfx, 95}, - - {IT_KEYHANDLER|IT_STRING, NULL, "Sound Test", M_HandleSoundTest, 110}, + + {IT_KEYHANDLER|IT_STRING, NULL, "Sound Test", M_HandleSoundTest, 105}, + {IT_STRING|IT_CALL, NULL, "Music Test", M_MusicTest, 115}, {IT_STRING|IT_CVAR, NULL, "Play Music While Unfocused", &cv_playmusicifunfocused, 125}, {IT_STRING|IT_CVAR, NULL, "Play SFX While Unfocused", &cv_playsoundifunfocused, 135}, {IT_STRING|IT_SUBMENU, NULL, "Advanced Settings...", &OP_SoundAdvancedDef, 155} }; +static const char* OP_SoundTooltips[] = +{ + "Turn Sound effects on or off.", + "Volume of sound effects.", + "Turn Sound effects on or off.", + "Volume of music.", + "Reverse left and right channels of audio.", + "Surround Sound.", + "Chat notification sound.", + "Frequency of character voice lines.", + "Should the powerup warning be a sound effect or music?", + "Testing sounds...", + "Testing music...", + "Should the games music play while unfocused?", + "Should the games sound play while unfocused?", + "Options for advanced sound settings.", +}; + + static menuitem_t OP_SoundAdvancedMenu[] = { #ifdef HAVE_OPENMPT @@ -1443,6 +1656,24 @@ static menuitem_t OP_SoundAdvancedMenu[] = {IT_STRING | IT_CVAR, NULL, "Invulnerability Music", &cv_supermusic, 137}, }; +static const char* OP_SoundAdvancedTooltips[] = +{ +#ifdef HAVE_OPENMPT + NULL, + + "Filter used to resample tracker instruments.", + "Resample tracker modules to sound similar to Paula hardware.", +#if OPENMPT_API_VERSION_MAJOR < 1 && OPENMPT_API_VERSION_MINOR > 4 + "Which Amiga should be used for .mod playback?", +#endif + "How far should the four channels in .mod be panned?", +#endif + NULL, + "Should the Grow music be on or off?", + "Should the Invulnerability music be on or off?", + +}; + static menuitem_t OP_DataOptionsMenu[] = { @@ -1571,21 +1802,40 @@ static menuitem_t OP_HUDOptionsMenu[] = static menuitem_t OP_ChatOptionsMenu[] = { // will ANYONE who doesn't know how to use the console want to touch this one? - {IT_STRING | IT_CVAR, NULL, "Chat Mode", &cv_consolechat, 10}, // nonetheless... + {IT_STRING | IT_CVAR, NULL, "Chat Mode", &cv_consolechat, 5}, // nonetheless... {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Chat Box Width", &cv_chatwidth, 25}, + NULL, "Chat Box Width", &cv_chatwidth, 20}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Chat Box Height", &cv_chatheight, 35}, + NULL, "Chat Box Height", &cv_chatheight, 30}, - {IT_STRING | IT_CVAR, NULL, "Chat Background Tint", &cv_chatbacktint, 50}, - {IT_STRING | IT_CVAR, NULL, "Message Fadeout Time", &cv_chattime, 60}, - {IT_STRING | IT_CVAR, NULL, "Spam Protection", &cv_chatspamprotection, 70}, - {IT_STRING | IT_CVAR, NULL, "Max Chat Messages", &cv_chatlogsize, 80}, + {IT_STRING | IT_CVAR, NULL, "Chat Background Tint", &cv_chatbacktint, 45}, + {IT_STRING | IT_CVAR, NULL, "Message Fadeout Time", &cv_chattime, 55}, + {IT_STRING | IT_CVAR, NULL, "Spam Protection", &cv_chatspamprotection, 65}, + {IT_STRING | IT_CVAR, NULL, "Max Chat Messages", &cv_chatlogsize, 75}, - {IT_STRING | IT_CVAR, NULL, "Local ping display", &cv_showping, 100}, // shows ping next to framerate if we want to. - {IT_STRING | IT_CVAR, NULL, "Ping measurement", &cv_pingmeasurement, 110}, - {IT_STRING | IT_CVAR, NULL, "Ping icon", &cv_pingicon, 120}, + {IT_STRING | IT_CVAR, NULL, "Local ping display", &cv_showping, 95}, // shows ping above the framerate if we want to. + {IT_STRING | IT_CVAR, NULL, "Ping display style", &cv_pingstyle, 105}, + {IT_STRING | IT_CVAR, NULL, "Ping measurement", &cv_pingmeasurement, 115}, + {IT_STRING | IT_CVAR, NULL, "Ping icon", &cv_pingicon, 125}, + + {IT_STRING | IT_CVAR, NULL, "Show IP address in playerlist", &cv_shownodeip, 135}, +}; + +static const char* OP_ChatOptionsTooltips[] = +{ + "Chat mode used for in-game chat.", + "Width of chat box.", + "Height of chat box.", + "Chatbox background.", + "Fadeout time for new chat message.", + "Spam protection for in-game chat.", + "Maxiumum amount of chat messages to look back at.", + "Show player ping.", + "Choose the looks of the ping display.", // this is ass idk english lmao + "Measurement used for ping.", + "Visibility of ping icon.", + "Should Player IP addresses be printed when using\nthe nodes or listplayers command?", }; static menuitem_t OP_GameOptionsMenu[] = @@ -1607,6 +1857,21 @@ static menuitem_t OP_GameOptionsMenu[] = {IT_STRING | IT_CVAR, NULL, "Restrict Character Changes", &cv_restrictskinchange, 150}, }; +static const char* OP_GameTooltips[] = +{ + "Toggles for all in-game items.", + "Driving speed of game in race mode.", + "Crazier item rolls.", + "Mirror mode.", + "Number of laps.", + "Countdown for other players when people finish.", + "Time limit for battle mode.", + "Number of bumpers to start with in battle mode.", + "Allow players to come back via karma in battle mode.", + "Force everyone to use the same character.", + "Prevent character changes.", +}; + static menuitem_t OP_ServerOptionsMenu[] = { #ifndef NONET @@ -1630,12 +1895,37 @@ static menuitem_t OP_ServerOptionsMenu[] = #endif }; +static const char* OP_ServerOptionsTooltips[] = +{ +#ifndef NONET + "Name of server.", +#endif + "Length of intermission after races.", + "How the next map to be played is choosen.", + "How long map voting is.", + "How often should other gamemodes appear.", +#ifndef NONET + "Max amount of players allowed in this server.", + "Allow players to join this server.", + "Allow players to download addons.", + "Who has permission to pause the server?", + "Completely mute in game chat.", + "Options for advanced server settings.", +#endif +}; + #ifndef NONET static menuitem_t OP_AdvServerOptionsMenu[] = { - {IT_STRING | IT_CVAR | IT_CV_STRING, - NULL, "Server Browser Address", &cv_masterserver, 10}, +#ifndef MASTERSERVER + {IT_GRAYEDOUT, + NULL, "Server Browser Address", NULL, 10}, +#else + {IT_STRING | IT_CVAR | IT_CV_STRING, + + NULL, "Server Browser Address", &cv_masterserver, 10}, +#endif {IT_STRING | IT_CVAR, NULL, "Attempts to resynchronise", &cv_resynchattempts, 40}, {IT_STRING | IT_CVAR, NULL, "Delay limit (frames)", &cv_maxping, 50}, {IT_STRING | IT_CVAR, NULL, "Delay timeout (s)", &cv_pingtimeout, 60}, @@ -1651,6 +1941,24 @@ static menuitem_t OP_AdvServerOptionsMenu[] = }; #endif +#ifndef NONET +static const char* OP_AdvServerOptionsTooltips[] = +{ + + "Server used for master server.", + "Attempts to resynchronise player to server.", + "Maximum allowed delay.", + "Delay timeout in seconds.", + "Connection timeout in tics.", + "Join timeout in tics", + "Max file size sent in kilobytes.", + "Packet rate for file transfers.", + "Log ip addresses of players who join.", + "Log player resync attempts.", + "Log player file transfers.", +}; +#endif + /*static menuitem_t OP_NetgameOptionsMenu[] = { {IT_STRING | IT_CVAR, NULL, "Time Limit", &cv_timelimit, 10}, @@ -1720,22 +2028,52 @@ static menuitem_t OP_MonitorToggleMenu[] = static menuitem_t OP_SaturnMenu[] = { {IT_HEADER, NULL, "Saturn Options", NULL, 0}, - {IT_STRING | IT_CVAR, NULL, "Serverqueue waittime", &cv_connectawaittime, 15}, - {IT_STRING | IT_CVAR, NULL, "Skin Select Spinning Speed", &cv_skinselectspin, 35}, - {IT_STRING | IT_CVAR, NULL, "Input Display outside of RA", &cv_showinput, 45}, - {IT_STRING | IT_CVAR, NULL, "Small Speedometer", &cv_newspeedometer, 55}, - {IT_STRING | IT_CVAR, NULL, "Colourized HUD", &cv_colorizedhud, 65}, - {IT_STRING | IT_CVAR, NULL, "Colourized Itembox", &cv_colorizeditembox, 75}, - {IT_STRING | IT_CVAR, NULL, "Colourized HUD Color", &cv_colorizedhudcolor, 85}, - {IT_STRING | IT_CVAR, NULL, "Show Lap Emblem", &cv_showlapemblem, 95}, - {IT_STRING | IT_CVAR, NULL, "Show Minimap Names", &cv_showminimapnames, 105}, - {IT_STRING | IT_CVAR, NULL, "Small Minimap Players", &cv_minihead, 115}, - {IT_STRING | IT_CVAR, NULL, "Less Midnight Channel Flicker", &cv_lessflicker, 125}, - {IT_SUBMENU|IT_STRING, NULL, "Player distortion...", &OP_PlayerDistortDef, 140}, - {IT_SUBMENU|IT_STRING, NULL, "Hud Offsets...", &OP_HudOffsetDef, 155}, + {IT_STRING | IT_CVAR, NULL, "Serverqueue waittime", &cv_connectawaittime, 10}, - {IT_SUBMENU|IT_STRING, NULL, "Saturn Credits", &OP_SaturnCreditsDef, 170}, // uwu + {IT_STRING | IT_CVAR, NULL, "Skin Select Spinning Speed", &cv_skinselectspin, 20}, + {IT_STRING | IT_CVAR, NULL, "Input Display outside of RA", &cv_showinput, 25}, + {IT_STRING | IT_CVAR, NULL, "Speedometer Style", &cv_newspeedometer, 30}, + {IT_STRING | IT_CVAR, NULL, "Stat Display", &cv_showstats, 35}, + {IT_STRING | IT_CVAR, NULL, "Higher Resolution Portraits", &cv_highresportrait, 40}, + {IT_STRING | IT_CVAR, NULL, "Colourized HUD", &cv_colorizedhud, 45}, + {IT_STRING | IT_CVAR, NULL, "Colourized Itembox", &cv_colorizeditembox, 50}, + {IT_STRING | IT_CVAR, NULL, "Colourized HUD Color", &cv_colorizedhudcolor, 55}, + {IT_STRING | IT_CVAR, NULL, "Show Lap Emblem", &cv_showlapemblem, 60}, + {IT_STRING | IT_CVAR, NULL, "Show Minimap Names", &cv_showminimapnames, 65}, + {IT_STRING | IT_CVAR, NULL, "Small Minimap Players", &cv_minihead, 70}, + {IT_STRING | IT_CVAR, NULL, "Show Cecho Messages", &cv_cechotoggle, 80}, + {IT_STRING | IT_CVAR, NULL, "Show Localskin Menus", &cv_showlocalskinmenus, 85}, + + {IT_STRING | IT_CVAR, NULL, "Less Midnight Channel Flicker", &cv_lessflicker, 95}, + + {IT_SUBMENU|IT_STRING, NULL, "Sprite Distortion...", &OP_PlayerDistortDef, 105}, + {IT_SUBMENU|IT_STRING, NULL, "Hud Offsets...", &OP_HudOffsetDef, 110}, + + {IT_SUBMENU|IT_STRING, NULL, "Saturn Credits", &OP_SaturnCreditsDef, 120}, // uwu +}; + +static const char* OP_SaturnTooltips[] = +{ + NULL, + "How long can the game wait before it kicks you out from the server\nconnecting screen.", + "How much speen do you want?", + "Displays the input display outside of Record Attack. Also adjusts the\nposition scale to match.", + "Change what style the speedometer is.", + "Enable the stat display.", + "Enable the use of the higher resolution want icons instead of rank\nfor some places.", + "Enable colourized hud.", + "Enable the colourized itembox when colourized hud is enabled.", + "The color to use instead of the player color when colourized hud is enabled.", + "Show the big 'LAP' text on a lap change.", + "Show player names on the minimap.", + "Minimize the player icons on the minimap.", + "Show the big Cecho Messages.", + "Show Localskin Menus.", + "Disables the flicker effect on Midnight Channel.", + "Options for sprite distortion effects.", + "Move position of HUD elements.", + "See the people who helped make this project possible!", }; enum @@ -1745,7 +2083,10 @@ enum sm_skinselspeed, sm_input, sm_speedometer, + sm_statdisplay, + sm_highresport, sm_colorhud, + sm_coloritem, sm_colorhud_customcolor, sm_lapemblem, sm_mapnames, @@ -1758,23 +2099,43 @@ enum static menuitem_t OP_PlayerDistortMenu[] = { - {IT_HEADER, NULL, "Player Distortion", NULL, 0}, + {IT_HEADER, NULL, "Sprite Distortion", NULL, 0}, - {IT_STRING | IT_CVAR, NULL, "Rotate players on slopes", &cv_sloperoll, 20}, - {IT_STRING | IT_CVAR, NULL, "Slope rotation distance", &cv_sloperolldist, 35}, - {IT_STRING | IT_CVAR, NULL, "Rotate players when sliptiding", &cv_sliptideroll, 50}, - {IT_STRING | IT_CVAR, NULL, "Player stretch factor", &cv_gravstretch, 65}, - {IT_STRING | IT_CVAR, NULL, "Squish Sound Effect", &cv_slamsound, 80}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop", &cv_saltyhop, 110}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop Sound Effect", &cv_saltyhopsfx, 125}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop Squish", &cv_saltysquish, 140}, + {IT_STRING | IT_CVAR, NULL, "Sprite Rotation", &cv_spriteroll, 15}, + {IT_STRING | IT_CVAR, NULL, "Sprite Slope Rotation", &cv_sloperoll, 30}, + {IT_STRING | IT_CVAR, NULL, "Slope Rotation Distance", &cv_sloperolldist, 45}, + {IT_STRING | IT_CVAR, NULL, "Rotate Players when Sliptiding", &cv_sliptideroll, 60}, + {IT_STRING | IT_CVAR, NULL, "Rotate Sparks and Boost Trails", &cv_sparkroll, 75}, + {IT_STRING | IT_CVAR, NULL, "Player Stretch Factor", &cv_gravstretch, 90}, + {IT_STRING | IT_CVAR, NULL, "Squish Sound Effect", &cv_slamsound, 105}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop", &cv_saltyhop, 120}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop Sound Effect", &cv_saltyhopsfx, 135}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop Squish", &cv_saltysquish, 150}, +}; + +static const char* OP_PlayerDistortTooltips[] = +{ + NULL, + "Sprite rotation features.", + "Sprite rotation on slopes. Can either be just players or all objects.", + "Distance object rotation should be visable.", + "Player rotation when sliptiding.", + "Rotation of a player's boost trails and drift sparks.", + "Player squash and stretch.", + "Player landing sound effect.", + "Kart hopping while drifting. This is purely visual.", + "Player hop sound effect.", + "Player hop squash and stretch.", }; enum { + spriteheader, + spriterotate, sloperotate, slrotatedist, sliptide, + sparkrotate, stretchyplayer, squishsound, salthmmm, @@ -1786,31 +2147,53 @@ static menuitem_t OP_HudOffsetMenu[] = { {IT_HEADER, NULL, "Kart Hud Offsets", NULL, 0}, - {IT_STRING | IT_CVAR, NULL, "Itembox Horizontal Offset", &cv_item_xoffset, 20}, - {IT_STRING | IT_CVAR, NULL, "Itembox Vertical Offset", &cv_item_yoffset, 30}, - {IT_STRING | IT_CVAR, NULL, "Timer Horizontal Offset", &cv_time_xoffset, 45}, - {IT_STRING | IT_CVAR, NULL, "Timer Vertical Offset", &cv_time_yoffset, 55}, - {IT_STRING | IT_CVAR, NULL, "Lapcount Horizontal Offset", &cv_laps_xoffset, 70}, - {IT_STRING | IT_CVAR, NULL, "Lapcount Vertical Offset", &cv_laps_yoffset, 80}, - {IT_STRING | IT_CVAR, NULL, "Speedometer Horizontal Offset", &cv_spdm_xoffset, 95}, - {IT_STRING | IT_CVAR, NULL, "Speedometer Vertical Offset", &cv_spdm_yoffset, 105}, - {IT_STRING | IT_CVAR, NULL, "Miniranking Horizontal Offset", &cv_face_xoffset, 120}, - {IT_STRING | IT_CVAR, NULL, "Miniranking Vertical Offset", &cv_face_yoffset, 130}, - {IT_STRING | IT_CVAR, NULL, "Minimap Horizontal Offset", &cv_mini_xoffset, 145}, - {IT_STRING | IT_CVAR, NULL, "Minimap Vertical Offset", &cv_mini_yoffset, 155}, + {IT_STRING | IT_CALL, NULL, "Reset all", M_ResetCvars, 5}, + + {IT_HEADER, NULL, "Itembox", NULL, 15}, + {IT_STRING | IT_CVAR, NULL, "Horizontal Offset", &cv_item_xoffset, 20}, + {IT_STRING | IT_CVAR, NULL, "Vertical Offset", &cv_item_yoffset, 25}, + + {IT_HEADER, NULL, "Timer", NULL, 35}, + {IT_STRING | IT_CVAR, NULL, "Horizontal Offset", &cv_time_xoffset, 40}, + {IT_STRING | IT_CVAR, NULL, "Vertical Offset", &cv_time_yoffset, 45}, + + {IT_HEADER, NULL, "Lap Count", NULL, 55}, + {IT_STRING | IT_CVAR, NULL, "Horizontal Offset", &cv_laps_xoffset, 60}, + {IT_STRING | IT_CVAR, NULL, "Vertical Offset", &cv_laps_yoffset, 65}, + + {IT_HEADER, NULL, "Speedometer", NULL, 75}, + {IT_STRING | IT_CVAR, NULL, "Horizontal Offset", &cv_speed_xoffset, 80}, + {IT_STRING | IT_CVAR, NULL, "Vertical Offset", &cv_speed_yoffset, 85}, + + {IT_HEADER, NULL, "Mini Rankings", NULL, 95}, + {IT_STRING | IT_CVAR, NULL, "Horizontal Offset", &cv_face_xoffset, 100}, + {IT_STRING | IT_CVAR, NULL, "Vertical Offset", &cv_face_yoffset, 105}, + + {IT_HEADER, NULL, "Minimap", NULL, 115}, + {IT_STRING | IT_CVAR, NULL, "Horizontal Offset", &cv_mini_xoffset, 120}, + {IT_STRING | IT_CVAR, NULL, "Vertical Offset", &cv_mini_yoffset, 125}, + + {IT_HEADER, NULL, "Position / R.A. Wheel", NULL, 135}, + {IT_STRING | IT_CVAR, NULL, "Horizontal Offset", &cv_posi_xoffset, 140}, + {IT_STRING | IT_CVAR, NULL, "Vertical Offset", &cv_posi_yoffset, 145}, + + {IT_HEADER, NULL, "Stat Display", NULL, 155}, + {IT_STRING | IT_CVAR, NULL, "Horizontal Offset", &cv_stat_xoffset, 160}, + {IT_STRING | IT_CVAR, NULL, "Vertical Offset", &cv_stat_yoffset, 165}, }; static menuitem_t OP_SaturnCreditsMenu[] = { {IT_HEADER, NULL, "Saturn Credits", NULL, 0}, - {IT_HEADER, NULL, "Thanks to all contributers <3", NULL, 25}, + {IT_HEADER, NULL, "Thanks to all contributers <3", NULL, 15}, - {IT_STRING2+IT_SPACE, NULL, "alufolie91 aka Alug", NULL, 30}, - {IT_STRING2+IT_SPACE, NULL, "Indev", NULL, 40}, - {IT_STRING2+IT_SPACE, NULL, "Haya", NULL, 50}, - {IT_STRING2+IT_SPACE, NULL, "Nepdisk", NULL, 60}, - {IT_STRING2+IT_SPACE, NULL, "xyzzy", NULL, 70}, + {IT_STRING2+IT_SPACE, NULL, "alufolie91 aka Alug", NULL, 20}, + {IT_STRING2+IT_SPACE, NULL, "Indev", NULL, 30}, + {IT_STRING2+IT_SPACE, NULL, "Haya", NULL, 40}, + {IT_STRING2+IT_SPACE, NULL, "Nepdisk", NULL, 50}, + {IT_STRING2+IT_SPACE, NULL, "xyzzy", NULL, 60}, + {IT_STRING2+IT_SPACE, NULL, "Chearii", NULL, 70}, {IT_STRING+IT_SPACE, NULL, "", NULL, 73}, // dummy text @@ -1834,6 +2217,13 @@ static menuitem_t OP_SaturnCreditsMenu[] = {IT_STRING, NULL, "", NULL, 200}, // dummy text III }; +static const char* OP_CreditTooltips[] = +{ + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + "Thanks everyone! <3" +}; + + static menuitem_t OP_BirdMenu[] = { {IT_HEADER, NULL, "Crazy", NULL, 0}, @@ -1848,10 +2238,42 @@ static menuitem_t OP_BirdMenu[] = //{IT_STRING | IT_CVAR, NULL, "Encore Choices", &cv_encorevotes, 90}, {IT_HEADER, NULL, "Music", NULL, 70}, - {IT_STRING | IT_CVAR, NULL, "Resume Level Music", &cv_resume, 80}, - {IT_STRING | IT_CVAR, NULL, "Restart Special Music", &cv_resetspecialmusic, 90}, + {IT_STRING | IT_CVAR, NULL, "Music Features", &cv_birdmusic, 80}, + {IT_STRING | IT_CVAR, NULL, "Resume Level Music", &cv_resume, 95}, + {IT_STRING | IT_CVAR, NULL, "Restart Special Music", &cv_resetspecialmusic, 105}, - {IT_STRING | IT_SUBMENU, NULL, "Advanced Music Options...", &OP_AdvancedBirdDef, 120}, + {IT_STRING | IT_SUBMENU, NULL, "Advanced Music Options...", &OP_AdvancedBirdDef, 130}, +}; + +static const char* OP_BirdTooltips[] = +{ + NULL, + "Options for screen tilting.", + NULL, + "Show player names in replay playback.", + "Show FREE PLAY text when in a empty server.", + //NULL, + //"Only show one battle choice in map vote", + //"Amount of encore choices in map vote.", + NULL, + "Global toggle for all bird music features.", + "Resume level music from last position after music change.", + "Restart Special music if item is used again.", + "Options for advanced music settings.", +}; + +enum +{ + headercrzy, + tiltmenu, + headerhud, + viewpointext, + freeplaytext, + headermusic, + birdmusic, + lvlresum, + spclresum, + advmusic, }; static menuitem_t OP_ForkedBirdMenu[] = @@ -1872,8 +2294,14 @@ static menuitem_t OP_TiltMenu[] = {IT_STRING | IT_CVAR, NULL, "Smoothing Divisor", &cv_tiltsmoothing, 20}, {IT_STRING | IT_CVAR, NULL, "Also Tilt During Quakes", &cv_actionmovie, 40}, +}; - {IT_STRING | IT_CVAR, NULL, "\x85" "Window Shaking During Quakes", &cv_windowquake, 60}, +static const char* OP_TiltTooltips[] = +{ + "Camera tilting during gameplay.", + "Tilt camera while turning.", + "Smoothing value used.", + "Tilt during screen quakes.", }; enum @@ -1897,6 +2325,17 @@ static menuitem_t OP_AdvancedBirdMenu[] = {IT_STRING | IT_CVAR, NULL, "Resync Special Music Only", &cv_music_resync_powerups_only, 70}, }; +static const char* OP_AdvancedBirdTooltips[] = +{ + "Music fading.", + "Fade in music after Invincibility.", + "Fade in music after Grow.", + "Fade out music before respawning.", + "Fade in music while respawning.", + "Threshold for syncing music.", + "Only sync special music.", +}; + enum { fading, @@ -1924,6 +2363,7 @@ menu_t MISC_AddonsDef = M_DrawAddons, 50, 28, 0, + NULL, NULL }; @@ -1936,7 +2376,8 @@ menu_t MISC_ReplayHutDef = M_DrawReplayHut, 30, 80, 0, - M_QuitReplayHut + M_QuitReplayHut, + NULL }; menu_t MISC_ReplayOptionsDef = @@ -1948,6 +2389,7 @@ menu_t MISC_ReplayOptionsDef = M_DrawGenericMenu, 27, 40, 0, + NULL, NULL }; @@ -1960,6 +2402,7 @@ menu_t MISC_ReplayStartDef = M_DrawReplayStartMenu, 30, 90, 0, + NULL, NULL }; @@ -1972,6 +2415,7 @@ menu_t PlaybackMenuDef = { //BASEVIDWIDTH/2 - 94, 2, BASEVIDWIDTH/2 - 88, 2, 0, + NULL, NULL }; @@ -2083,7 +2527,8 @@ menu_t SR_PandoraDef = M_DrawGenericMenu, 60, 40, 0, - M_ExitPandorasBox + M_ExitPandorasBox, + NULL }; menu_t SR_MainDef = CENTERMENUSTYLE(NULL, SR_MainMenu, &MainDef, 72); @@ -2098,8 +2543,23 @@ menu_t SR_UnlockChecklistDef = M_DrawChecklist, 280, 185, 0, + NULL, NULL }; + +menu_t SR_MusicTestDef = +{ + NULL, + sizeof (SR_MusicTestMenu)/sizeof (menuitem_t), + &OP_SoundOptionsDef, + SR_MusicTestMenu, + M_DrawMusicTest, + 60, 150, + 0, + NULL, + NULL +}; + menu_t SR_EmblemHintDef = { NULL, @@ -2109,6 +2569,7 @@ menu_t SR_EmblemHintDef = M_DrawEmblemHints, 60, 150, 0, + NULL, NULL }; @@ -2136,6 +2597,7 @@ menu_t SP_LevelStatsDef = M_DrawLevelStats, 280, 185, 0, + NULL, NULL }; @@ -2148,7 +2610,9 @@ static menu_t SP_TimeAttackDef = M_DrawTimeAttackMenu, 34, 40, 0, - M_QuitTimeAttackMenu + M_QuitTimeAttackMenu, + NULL, + NULL }; static menu_t SP_ReplayDef = { @@ -2159,6 +2623,8 @@ static menu_t SP_ReplayDef = M_DrawTimeAttackMenu, 34, 40, 0, + NULL, + NULL, NULL }; static menu_t SP_GuestReplayDef = @@ -2170,6 +2636,8 @@ static menu_t SP_GuestReplayDef = M_DrawTimeAttackMenu, 34, 40, 0, + NULL, + NULL, NULL }; static menu_t SP_GhostDef = @@ -2181,6 +2649,7 @@ static menu_t SP_GhostDef = M_DrawTimeAttackMenu, 34, 40, 0, + NULL, NULL }; @@ -2253,10 +2722,11 @@ menu_t MP_MainDef = 42, 30, 0, #ifndef NONET - M_CancelConnect + M_CancelConnect, #else - NULL + NULL, #endif + NULL }; menu_t MP_OfflineServerDef = MAPICONMENUSTYLE("M_MULTI", MP_OfflineServerMenu, &MP_MainDef); @@ -2273,7 +2743,8 @@ menu_t MP_ConnectDef = M_DrawConnectMenu, 27,24, 0, - M_CancelConnect + M_CancelConnect, + NULL }; #endif menu_t MP_PlayerSetupDef = @@ -2285,7 +2756,8 @@ menu_t MP_PlayerSetupDef = M_DrawSetupMultiPlayerMenu, 36, 14, 0, - M_QuitMultiPlayerMenu + M_QuitMultiPlayerMenu, + NULL }; // Options @@ -2298,10 +2770,13 @@ menu_t OP_MainDef = M_DrawGenericMenu, 60, 30, 0, + NULL, NULL }; menu_t OP_ControlsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_ControlsMenu, &OP_MainDef, 60, 30); +//WTF +menu_t OP_MouseOptionsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_MouseOptionsMenu, &OP_ControlsDef, 60, 30); menu_t OP_AllControlsDef = CONTROLMENUSTYLE(OP_AllControlsMenu, &OP_ControlsDef); menu_t OP_Joystick1Def = DEFAULTMENUSTYLE("M_CONTRO", OP_Joystick1Menu, &OP_AllControlsDef, 60, 30); menu_t OP_Joystick2Def = DEFAULTMENUSTYLE("M_CONTRO", OP_Joystick2Menu, &OP_AllControlsDef, 60, 30); @@ -2316,6 +2791,7 @@ menu_t OP_JoystickSetDef = M_DrawJoystick, 50, 40, 0, + NULL, NULL }; @@ -2326,8 +2802,9 @@ menu_t OP_VideoOptionsDef = &OP_MainDef, OP_VideoOptionsMenu, M_DrawVideoMenu, - 30, 30, + 30, 20, 0, + NULL, NULL }; @@ -2340,9 +2817,23 @@ menu_t OP_VideoModeDef = M_DrawVideoMode, 48, 26, 0, + NULL, NULL }; +menu_t OP_ColorOptionsDef = +{ + "M_VIDEO", + sizeof (OP_ColorOptionsMenu)/sizeof (menuitem_t), + &OP_VideoOptionsDef, + OP_ColorOptionsMenu, + M_DrawColorMenu, + 30, 30, + 0, + NULL, + {NULL} +}; + menu_t OP_SoundOptionsDef = { "M_SOUND", @@ -2350,11 +2841,13 @@ menu_t OP_SoundOptionsDef = &OP_MainDef, OP_SoundOptionsMenu, M_DrawSkyRoom, - 30, 30, + 30, 20, 0, + NULL, NULL }; + menu_t OP_HUDOptionsDef = { "M_HUD", @@ -2364,17 +2857,19 @@ menu_t OP_HUDOptionsDef = M_DrawHUDOptions, 30, 20, 0, + NULL, NULL }; + menu_t OP_ChatOptionsDef = DEFAULTMENUSTYLE("M_HUD", OP_ChatOptionsMenu, &OP_HUDOptionsDef, 30, 30); menu_t OP_SoundAdvancedDef = DEFAULTMENUSTYLE("M_SOUND", OP_SoundAdvancedMenu, &OP_SoundOptionsDef, 30, 30); -menu_t OP_GameOptionsDef = DEFAULTMENUSTYLE("M_GAME", OP_GameOptionsMenu, &OP_MainDef, 30, 30); -menu_t OP_ServerOptionsDef = DEFAULTMENUSTYLE("M_SERVER", OP_ServerOptionsMenu, &OP_MainDef, 24, 30); +menu_t OP_GameOptionsDef = DEFAULTMENUSTYLE("M_GAME", OP_GameOptionsMenu, &OP_MainDef, 30, 20); +menu_t OP_ServerOptionsDef = DEFAULTMENUSTYLE("M_SERVER", OP_ServerOptionsMenu, &OP_MainDef, 24, 20); #ifndef NONET -menu_t OP_AdvServerOptionsDef = DEFAULTMENUSTYLE("M_SERVER", OP_AdvServerOptionsMenu, &OP_ServerOptionsDef, 24, 30); +menu_t OP_AdvServerOptionsDef = DEFAULTMENUSTYLE("M_SERVER", OP_AdvServerOptionsMenu, &OP_ServerOptionsDef, 24, 20); #endif //menu_t OP_NetgameOptionsDef = DEFAULTMENUSTYLE("M_SERVER", OP_NetgameOptionsMenu, &OP_ServerOptionsDef, 30, 30); @@ -2389,25 +2884,16 @@ menu_t OP_MonitorToggleDef = M_DrawMonitorToggles, 47, 30, 0, + NULL, NULL }; #ifdef HWRENDER -menu_t OP_OpenGLOptionsDef = DEFAULTMENUSTYLE("M_VIDEO", OP_OpenGLOptionsMenu, &OP_VideoOptionsDef, 30, 20); - -menu_t OP_OpenGLColorDef = -{ - "M_VIDEO", - sizeof (OP_OpenGLColorMenu)/sizeof (menuitem_t), - &OP_OpenGLOptionsDef, - OP_OpenGLColorMenu, - M_OGL_DrawColorMenu, - 60, 40, - 0, - NULL -}; +menu_t OP_OpenGLOptionsDef = DEFAULTSCROLLSTYLE("M_VIDEO", OP_OpenGLOptionsMenu, &OP_VideoOptionsDef, 30, 30); #endif +menu_t OP_ExpOptionsDef = DEFAULTMENUSTYLE("M_VIDEO", OP_ExpOptionsMenu, &OP_VideoOptionsDef, 30, 30); + menu_t OP_DataOptionsDef = DEFAULTMENUSTYLE("M_DATA", OP_DataOptionsMenu, &OP_MainDef, 60, 30); menu_t OP_ScreenshotOptionsDef = DEFAULTMENUSTYLE("M_SCSHOT", OP_ScreenshotOptionsMenu, &OP_DataOptionsDef, 30, 30); menu_t OP_AddonsOptionsDef = DEFAULTMENUSTYLE("M_ADDONS", OP_AddonsOptionsMenu, &OP_DataOptionsDef, 30, 30); @@ -2417,9 +2903,9 @@ menu_t OP_DiscordOptionsDef = DEFAULTMENUSTYLE(NULL, OP_DiscordOptionsMenu, &OP_ #endif menu_t OP_EraseDataDef = DEFAULTMENUSTYLE("M_DATA", OP_EraseDataMenu, &OP_DataOptionsDef, 30, 30); -menu_t OP_SaturnDef = DEFAULTMENUSTYLE(NULL, OP_SaturnMenu, &OP_MainDef, 30, 15); +menu_t OP_SaturnDef = DEFAULTSCROLLSTYLE(NULL, OP_SaturnMenu, &OP_MainDef, 30, 30); menu_t OP_PlayerDistortDef = DEFAULTMENUSTYLE("M_VIDEO", OP_PlayerDistortMenu, &OP_SaturnDef, 30, 30); -menu_t OP_HudOffsetDef = DEFAULTMENUSTYLE(NULL, OP_HudOffsetMenu, &OP_SaturnDef, 30, 20); +menu_t OP_HudOffsetDef = DEFAULTSCROLLSTYLE(NULL, OP_HudOffsetMenu, &OP_SaturnDef, 30, 30); menu_t OP_SaturnCreditsDef = DEFAULTMENUSTYLE(NULL, OP_SaturnCreditsMenu, &OP_SaturnDef, 30, 10); menu_t OP_BirdDef = DEFAULTMENUSTYLE(NULL, OP_BirdMenu, &OP_MainDef, 30, 30); @@ -2434,6 +2920,7 @@ menu_t OP_ForkedBirdDef = { M_DrawLocalSkinMenu, 30, 6, 0, + NULL, NULL }; @@ -2690,18 +3177,26 @@ void Addons_option_Onchange(void) void PDistort_menu_Onchange(void) { - UINT16 status; - - if (cv_sloperoll.value) + if (!cv_spriteroll.value) { - status = IT_STRING | IT_CVAR; + OP_PlayerDistortMenu[sloperotate].status = IT_GRAYEDOUT; + OP_PlayerDistortMenu[sliptide].status = IT_GRAYEDOUT; } else { - status = IT_GRAYEDOUT; + OP_PlayerDistortMenu[sloperotate].status = IT_STRING | IT_CVAR; + OP_PlayerDistortMenu[sliptide].status = IT_STRING | IT_CVAR; } - OP_PlayerDistortMenu[2].status = status; + if ((cv_sloperoll.value) && (cv_spriteroll.value)) //enable/disable sloperotate distance + OP_PlayerDistortMenu[slrotatedist].status = IT_STRING | IT_CVAR; + else + OP_PlayerDistortMenu[slrotatedist].status = IT_GRAYEDOUT; + + if ((cv_sloperoll.value == 2) && (cv_spriteroll.value)) //enable/disable sparkroll depending on which setting + OP_PlayerDistortMenu[sparkrotate].status = IT_STRING | IT_CVAR; + else + OP_PlayerDistortMenu[sparkrotate].status = IT_GRAYEDOUT; } void Bird_menu_Onchange(void) @@ -2709,31 +3204,50 @@ void Bird_menu_Onchange(void) UINT16 status; if (cv_tilting.value) - { status = IT_STRING | IT_CVAR; - } else - { status = IT_GRAYEDOUT; - } OP_TiltMenu[tiltwturning].status = status; OP_TiltMenu[smoothening].status = status; OP_TiltMenu[tiltwquakes].status = status; if (cv_fading.value) - { status = IT_STRING | IT_CVAR; - } else - { status = IT_GRAYEDOUT; - } OP_AdvancedBirdMenu[fadeinvinc].status = status; OP_AdvancedBirdMenu[fadegrow].status = status; OP_AdvancedBirdMenu[respawnfadeout].status = status; OP_AdvancedBirdMenu[respawnfadein].status = status; + + if (cv_birdmusic.value) + { + OP_BirdMenu[lvlresum].status = IT_STRING | IT_CVAR; + OP_BirdMenu[spclresum].status = IT_STRING | IT_CVAR; + OP_BirdMenu[advmusic].status = IT_STRING | IT_SUBMENU; + } + else + { + OP_BirdMenu[lvlresum].status = IT_GRAYEDOUT; + OP_BirdMenu[spclresum].status = IT_GRAYEDOUT; + OP_BirdMenu[advmusic].status = IT_GRAYEDOUT; + } +} + +//menu code is nice +void Saturn_menu_Onchange(void) +{ + UINT16 status; + + if (cv_colorizedhud.value) + status = IT_STRING | IT_CVAR; + else + status = IT_GRAYEDOUT; + + OP_SaturnMenu[sm_coloritem].status = status; + OP_SaturnMenu[sm_colorhud_customcolor].status = status; } // ========================================================================== @@ -2837,6 +3351,19 @@ static boolean M_ChangeStringCvar(INT32 choice) return false; } +// resets all cvars on a menu - assumes that all that have itemactions are cvars +static void M_ResetCvars(void) +{ + INT32 i; + consvar_t *cv; + for (i = 0; i < currentMenu->numitems; i++) + { + if (!(currentMenu->menuitems[i].status & IT_CVAR) || !(cv = (consvar_t *)currentMenu->menuitems[i].itemaction)) + continue; + CV_SetValue(cv, atoi(cv->defaultvalue)); + } +} + static void M_NextOpt(void) { INT16 oldItemOn = itemOn; // prevent infinite loop @@ -3252,6 +3779,7 @@ boolean M_Responder(event_t *ev) case KEY_DOWNARROW: M_NextOpt(); S_StartSound(NULL, sfx_menu1); + coolalphatimer = 9; /*if (currentMenu == &SP_PlayerDef) { Z_Free(char_notes); @@ -3262,6 +3790,7 @@ boolean M_Responder(event_t *ev) case KEY_UPARROW: M_PrevOpt(); S_StartSound(NULL, sfx_menu1); + coolalphatimer = 9; /*if (currentMenu == &SP_PlayerDef) { Z_Free(char_notes); @@ -3648,10 +4177,18 @@ void M_StartControlPanel(void) MPauseMenu[mpause_psetup].status = IT_DISABLED; MISC_ChangeTeamMenu[0].status = IT_DISABLED; MISC_ChangeSpectateMenu[0].status = IT_DISABLED; + + MPauseMenu[mpause_addlocalskins].status = IT_STRING | IT_CALL; + MPauseMenu[mpause_localskin].status = IT_STRING | IT_CALL; // Reset these in case splitscreen messes things up MPauseMenu[mpause_addons].alphaKey = 8; - MPauseMenu[mpause_addlocalskins].alphaKey = 16; + + if (IsPlayerAdmin(consoleplayer)) + MPauseMenu[mpause_addlocalskins].alphaKey = 16; + else + MPauseMenu[mpause_addlocalskins].alphaKey = 24; + MPauseMenu[mpause_scramble].alphaKey = 8; MPauseMenu[mpause_switchmap].alphaKey = 24; @@ -3668,9 +4205,21 @@ void M_StartControlPanel(void) { MPauseMenu[mpause_switchmap].status = IT_STRING | IT_CALL; MPauseMenu[mpause_addons].status = IT_STRING | IT_CALL; + if (G_GametypeHasTeams()) MPauseMenu[mpause_scramble].status = IT_STRING | IT_SUBMENU; } + + if (server || (!cv_showlocalskinmenus.value)) + { + MPauseMenu[mpause_addlocalskins].status = IT_DISABLED; + MPauseMenu[mpause_localskin].status = IT_DISABLED; + + MPauseMenu[mpause_options].alphaKey = 64; + MPauseMenu[mpause_title].alphaKey = 80; + MPauseMenu[mpause_quit].alphaKey = 88; + } + if (splitscreen) { @@ -3929,14 +4478,33 @@ void M_Init(void) #ifdef HWRENDER // Permanently hide some options based on render mode if (rendermode == render_soft) + { OP_VideoOptionsMenu[op_video_ogl].status = IT_DISABLED; + OP_ExpOptionsMenu[op_exp_grscrtx].status = IT_DISABLED; + OP_ExpOptionsMenu[op_exp_spltwal].status = IT_DISABLED; + OP_ExpOptionsMenu[op_exp_pegging].status = IT_DISABLED; + OP_ExpOptionsMenu[op_exp_fofzfight].status = IT_DISABLED; + OP_ExpOptionsMenu[op_exp_fofcut].status = IT_DISABLED; + } + + if (rendermode == render_opengl){ + OP_ExpOptionsMenu[op_exp_ffclip].status = IT_DISABLED; + OP_ExpOptionsMenu[op_exp_sprclip].status = IT_DISABLED; + } #endif - if (!snw_speedo) // why bother? + if (!snw_speedo && !kartzspeedo) // why bother? OP_SaturnMenu[sm_speedometer].status = IT_GRAYEDOUT; - - if (!clr_hud){ // uhguauhauguuhee + + if (!snw_speedo && kartzspeedo) + OP_SaturnMenu[sm_speedometer].text = "Speedometer (No Small)"; + + if (snw_speedo && !kartzspeedo) + OP_SaturnMenu[sm_speedometer].text = "Speedometer (No PMeter)"; + + if (!clr_hud){ // uhguauhauguuhee OP_SaturnMenu[sm_colorhud].status = IT_GRAYEDOUT; + OP_SaturnMenu[sm_coloritem].status = IT_GRAYEDOUT; OP_SaturnMenu[sm_colorhud_customcolor].status = IT_GRAYEDOUT; } @@ -4263,6 +4831,58 @@ static void M_DrawMenuTitle(void) } } +// TODO: This is fucking terrible. +static void M_DrawSplitText(INT32 x, INT32 y, INT32 option, const char* str, INT32 box_x, INT32 alpha) +{ + const char* icopy = strdup(str); + const char** clines = NULL; + INT16 num_lines = 0; + + if (icopy == NULL) return; + + char* token = strtok(icopy, "\n"); + + while (token != NULL) + { + const char* line = strdup(token); + + if (line == NULL) return; + + clines = (const char**)realloc(clines, (num_lines + 1) * sizeof(const char*)); + clines[num_lines] = line; + num_lines++; + + token = strtok(NULL, "\n"); + } + + free(icopy); + + INT16 yoffset; + yoffset = (((5*10 - num_lines*10))); + + // Draw BG first,,, + for (int i = 0; i < num_lines; i++) + { + V_DrawFill(0, (y + yoffset - 6)+5, vid.width, 11, 239|V_SNAPTOBOTTOM|V_SNAPTOLEFT); + yoffset += 11; + } + + yoffset = (((5*10 - num_lines*10))); + + // THEN the text + for (int i = 0; i < num_lines; i++) + { + V_DrawCenteredThinString(x, y + yoffset, option, clines[i]); + V_DrawCenteredThinString(x, y + yoffset, option|V_YELLOWMAP|((9 - alpha) << V_ALPHASHIFT), clines[i]); + yoffset += 10; + // Remember to free the memory for each line when you're done with it. + free((void*)clines[i]); + } + + free(clines); +} + + static void M_DrawGenericMenu(void) { INT32 x, y, w, i, cursory = 0; @@ -4405,6 +5025,172 @@ static void M_DrawGenericMenu(void) W_CachePatchName("M_CURSOR", PU_CACHE)); V_DrawString(currentMenu->x, cursory, lowercase|highlightflags, currentMenu->menuitems[itemOn].text); } + + + // dumb hack + // tooltips + + if (currentMenu == &OP_ControlsDef) + { + if (!(OP_ControlsTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_ControlsTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_MouseOptionsDef) + { + if (!(OP_MouseTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_MouseTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_VideoOptionsDef) + { + if (!(OP_VideoTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_VideoTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_SoundOptionsDef) + { + if (!(OP_SoundTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_SoundTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_SoundAdvancedDef) + { + if (!(OP_SoundAdvancedTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_SoundAdvancedTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_ExpOptionsDef) + { + if (!(OP_ExpTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_ExpTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_ChatOptionsDef) + { + if (!(OP_ChatOptionsTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_ChatOptionsTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + + + if (currentMenu == &OP_GameOptionsDef) + { + if (!(OP_GameTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_GameTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + + if (currentMenu == &OP_ServerOptionsDef) + { + if (!(OP_ServerOptionsTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_ServerOptionsTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + + if (currentMenu == &OP_AdvServerOptionsDef) + { + if (!(OP_AdvServerOptionsTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_AdvServerOptionsTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + + + + if (currentMenu == &OP_PlayerDistortDef) + { + if (!(OP_PlayerDistortTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_PlayerDistortTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + + + + if (currentMenu == &OP_SaturnCreditsDef) // C: + { + if (!(OP_CreditTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_CreditTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_BirdDef) + { + if (!(OP_BirdTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_BirdTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_TiltDef) + { + if (!(OP_TiltTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_TiltTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + if (currentMenu == &OP_AdvancedBirdDef) + { + if (!(OP_AdvancedBirdTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_AdvancedBirdTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } + + } static void M_DrawGenericBackgroundMenu(void) @@ -4415,8 +5201,10 @@ static void M_DrawGenericBackgroundMenu(void) #define scrollareaheight 72 + + // note that alphakey is multiplied by 2 for scrolling menus to allow greater usage in UINT8 range. -/*static void M_DrawGenericScrollMenu(void) +static void M_DrawGenericScrollMenu(void) { INT32 x, y, i, max, bottom, tempcentery, cursory = 0; @@ -4545,8 +5333,33 @@ static void M_DrawGenericBackgroundMenu(void) // DRAW THE SKULL CURSOR V_DrawScaledPatch(currentMenu->x - 24, cursory, 0, W_CachePatchName("M_CURSOR", PU_CACHE)); -}*/ +#ifdef HWRENDER + // dumb hack + // tooltips + if (currentMenu == &OP_OpenGLOptionsDef) + { + if (!(OP_OpenGLTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_OpenGLTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } +#endif + + + + if (currentMenu == &OP_SaturnDef) + { + if (!(OP_SaturnTooltips[itemOn] == NULL)) + { + M_DrawSplitText(BASEVIDWIDTH / 2, BASEVIDHEIGHT-50, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM, OP_SaturnTooltips[itemOn], 30, coolalphatimer); + if (coolalphatimer > 0 && interpTimerHackAllow) + coolalphatimer--; + } + } +} static void M_DrawPauseMenu(void) { @@ -4935,24 +5748,23 @@ boolean M_CanShowLevelInList(INT32 mapnum, INT32 gt) //return false; // Should the map be hidden? <-- well imma wanna toggle it, its just annoying being unable to select hell maps in mapselect - if (cv_showallmaps.value) + if ((mapheaderinfo[mapnum]->menuflags & LF2_HIDEINMENU && mapnum+1 != gamemap) && (gt == GT_RACE && (mapheaderinfo[mapnum]->typeoflevel & TOL_RACE))) // map hell { - if ((mapheaderinfo[mapnum]->menuflags & LF2_HIDEINMENU && mapnum+1 != gamemap) && (gt == GT_RACE && (mapheaderinfo[mapnum]->typeoflevel & TOL_RACE))) - return true; // map hell - } - else if ((mapheaderinfo[mapnum]->menuflags & LF2_HIDEINMENU && mapnum+1 != gamemap) && (gt == GT_RACE && (mapheaderinfo[mapnum]->typeoflevel & TOL_RACE))) + if (cv_showallmaps.value) + return true; + else return false; + } // same goes here, just show every map if i want to - if (cv_showallmaps.value) + if (M_MapLocked(mapnum+1)) // not unlocked { - if (M_MapLocked(mapnum+1)) - return true; // not unlocked - } - else if (M_MapLocked(mapnum+1)) - return false; // not unlocked - - + if (cv_showallmaps.value) + return true; + else + return false; + } + /*if (gt == GT_COOP && (mapheaderinfo[mapnum]->typeoflevel & TOL_COOP)) return true; @@ -5496,6 +6308,8 @@ static void M_AddonsClearName(INT32 choice) M_StopMessage(choice); } +int errorshitspam = 0; // prevent the warning screen from crapping itself when errors get spammed lmao + // returns whether to do message draw static boolean M_AddonsRefresh(void) { @@ -5524,10 +6338,11 @@ static boolean M_AddonsRefresh(void) else message = va("%c%s\x80\nA file was not loaded.\nCheck the console log for more information.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname); } - else if (refreshdirmenu & (REFRESHDIR_WARNING|REFRESHDIR_ERROR)) + else if ((refreshdirmenu & (REFRESHDIR_WARNING | REFRESHDIR_ERROR)) && !errorshitspam) { S_StartSound(NULL, sfx_s224); message = va("%c%s\x80\nA file was loaded with %s.\nCheck the console log for more information.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname, ((refreshdirmenu & REFRESHDIR_ERROR) ? "errors" : "warnings")); + errorshitspam = 1; // you already said that shit } else if (majormods && !prevmajormods) { @@ -5702,6 +6517,64 @@ static void M_AddonExec(INT32 ch) COM_BufAddText(va("exec \"%s%s\"", menupath, dirmenu[dir_on[menudepthleft]]+DIR_STRING)); } +// static void M_AddonAutoLoad(INT32 ch); +// exports mods to a file, which helps in autoloading that file +// +static void M_AddonAutoLoad(INT32 ch) +{ + // initalize these variables // + const char *path; + FILE *autoloadconfigfile; + + // check our controls // + if (ch != 'y' && ch != KEY_ENTER && ch != KEY_RSHIFT) + { + S_StartSound(NULL, sfx_s26d); + return; + } + + // first, find the file // + path = va("%s"PATHSEP"%s", srb2home, AUTOLOADCONFIGFILENAME); + autoloadconfigfile = fopen(path, "a"); + + // then, execute the addon and store it in our autoload.cfg // + switch (dirmenu[dir_on[menudepthleft]][DIR_TYPE]) + { + case EXT_FOLDER: + M_StartMessage(va("%c%s\x80\nAutoloading folders is not supported as of yet. \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); + break; + case EXT_TXT: + case EXT_CFG: + CONS_Printf("Added the \x82%s\x80 console script to the autoload configuration list.\n", dirmenu[dir_on[menudepthleft]]+DIR_STRING); + fprintf(autoloadconfigfile, "%s\n", dirmenu[dir_on[menudepthleft]]+DIR_STRING); + + S_StartSound(NULL, sfx_s221); + break; + case EXT_LUA: + case EXT_SOC: + case EXT_WAD: + case EXT_KART: + case EXT_PK3: + default: + if (!(refreshdirmenu & REFRESHDIR_MAX)) + { + CONS_Printf("Added \x82%s\x80 to the autoload configuration list.\n", dirmenu[dir_on[menudepthleft]]+DIR_STRING); + fprintf(autoloadconfigfile, "%s\n", dirmenu[dir_on[menudepthleft]]+DIR_STRING); + + S_StartSound(NULL, sfx_s221); + } + else + { + M_StartMessage(va("%c%s\x80\nToo many add-ons are loaded! \nYou need to restart the game to autoload more add-ons and folders. \nYou can still autoload console scripts though. \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); + S_StartSound(NULL, sfx_s26d); + } + break; + } + + // lastly, do some last things and close the autoload config file // + fclose(autoloadconfigfile); +} + #define len menusearch[0] static boolean M_ChangeStringAddons(INT32 choice) { @@ -5870,12 +6743,16 @@ static void M_HandleAddons(INT32 choice) if (DumbStartsWith("KC_", dirmenu[dir_on[menudepthleft]]+DIR_STRING) || DumbStartsWith("kc_", dirmenu[dir_on[menudepthleft]]+DIR_STRING)) { M_StartMessage(va("%c%s\x80\nYou are loading a local skin.\nLocal skins will not be usable\nafter going back from\nthe title screen.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); COM_BufAddText(va("addskins \"%s%s\"", menupath, dirmenu[dir_on[menudepthleft]]+DIR_STRING)); + errorshitspam = 0; // reset it so it can show the warning screen again lmao } else S_StartSound(NULL, sfx_s26d); } else + { COM_BufAddText(va("addfile \"%s%s\"", menupath, dirmenu[dir_on[menudepthleft]]+DIR_STRING)); + errorshitspam = 0; // reset it so it can show the warning screen again lmao + } break; default: S_StartSound(NULL, sfx_s26d); @@ -5886,6 +6763,53 @@ static void M_HandleAddons(INT32 choice) } break; + case KEY_RSHIFT: + { + boolean refresh = true; + if (!dirmenu[dir_on[menudepthleft]]) + S_StartSound(NULL, sfx_s26d); + else + { + switch (dirmenu[dir_on[menudepthleft]][DIR_TYPE]) + { + case EXT_FOLDER: + M_StartMessage(va("%c%s%s\x80\nAutoloading a folder is not yet suppported. \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), M_AddonsHeaderPath(), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); + S_StartSound(NULL, sfx_s26d); + break; + case EXT_UP: + S_StartSound(NULL, sfx_s224); + M_StartMessage(va("%c%s%s\x80\nNice try. \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), M_AddonsHeaderPath(), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); + break; + case EXT_TXT: + case EXT_CFG: + if ((strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, CONFIGFILENAME) == 0) + || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, AUTOLOADCONFIGFILENAME) == 0) + || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, "kartserv.cfg") == 0) + || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, "kartexec.cfg") == 0)) + { + M_StartMessage(va("%c%s\x80\nYou can't autoload this builds' base console scripts, silly!\n They're already autoloaded on startup! \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); + S_StartSound(NULL, sfx_s26d); + } + else + M_StartMessage(va("%c%s\x80\nYou're trying to autoload a console script. \nIgnore my warning anyways? \n\n(Press 'Y' to confirm)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),M_AddonAutoLoad,MM_YESNO); + break; + case EXT_LUA: + case EXT_SOC: + case EXT_WAD: + case EXT_KART: + case EXT_PK3: + M_StartMessage(va("%c%s\x80\nYou are trying to mark an addon to autoload\nat startup. This will skip modifiedgame checks. \n\n(Press 'Y' to confirm)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),M_AddonAutoLoad,MM_YESNO); + break; + default: + M_StartMessage(va("%c%s\x80\nIt may be dangerous to autoload this file. \nBut you're the boss, and I'm just hand-written code.\n Proceed? \n\n(Press 'Y' to confirm)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),M_AddonAutoLoad,MM_YESNO); + break; + } + } + if (refresh) + refreshdirmenu |= REFRESHDIR_NORMAL; + } + break; + case KEY_ESCAPE: exitmenu = true; break; @@ -6918,6 +7842,8 @@ static void M_Options(INT32 choice) OP_MainMenu[4].status = OP_MainMenu[5].status = (Playing() && !(server || IsPlayerAdmin(consoleplayer))) ? (IT_GRAYEDOUT) : (IT_STRING|IT_SUBMENU); OP_MainMenu[8].status = (Playing()) ? (IT_GRAYEDOUT) : (IT_STRING|IT_CALL); // Play credits + + OP_MainMenu[11].status = (!cv_showlocalskinmenus.value) ? (IT_DISABLED) : (IT_CALL|IT_STRING); #ifdef HAVE_DISCORDRPC OP_DataOptionsMenu[4].status = (Playing()) ? (IT_GRAYEDOUT) : (IT_STRING|IT_SUBMENU); // Erase data @@ -7349,6 +8275,397 @@ static void M_HandleSoundTest(INT32 choice) } } +static musicdef_t *curplaying = NULL; +static INT32 st_sel = 0; +static tic_t st_time = 0; +static size_t st_namescroll = 0; +static size_t st_namescrollstate = 0; +//static patch_t* st_radio[9]; +//static patch_t* st_launchpad[4]; + +static void M_MusicTest(INT32 choice) +{ + INT32 ul = skyRoomMenuTranslations[choice-1]; + UINT8 i; + char buf[8]; + + if (!S_PrepareSoundTest()) + { + M_StartMessage(M_GetText("No selectable tracks found.\n"),NULL,MM_NOTHING); + return; + } + + /*STRBUFCPY(buf, "M_RADIOn"); + for (i = 0; i < 9; i++) + { + if (st_radio[i]) + W_UnlockCachedPatch(st_radio[i]); + buf[7] = (char)('0'+i); + st_radio[i] = W_CachePatchName(buf, PU_STATIC); + } + + STRBUFCPY(buf, "M_LPADn"); + for (i = 0; i < 4; i++) + { + if (st_launchpad[i]) + W_UnlockCachedPatch(st_launchpad[i]); + buf[6] = (char)('0'+i); + st_launchpad[i] = W_CachePatchName(buf, PU_STATIC); + }*/ + + curplaying = NULL; + st_time = 0; + + st_sel = 0; + + M_SetupNextMenu(&SR_MusicTestDef); +} + +static void M_DrawMusicTest(void) +{ + INT32 x, y, i; + char* title; + //fixed_t hscale = FRACUNIT/2, vscale = FRACUNIT/2, bounce = 0; + //UINT8 frame[4] = {0, 0, -1, SKINCOLOR_RUBY}; + + // let's handle the ticker first. ideally we'd tick this somewhere else, BUT... + if (curplaying) + { + { + fixed_t work; + //angle_t ang; + //bpm = FixedDiv((60*TICRATE)<= (FRACUNIT << (FRACBITS - 2))) // prevent overflow jump - takes about 15 minutes of loop on the same song to reach + st_time = work; + + //work = FixedDiv(work*180, bpm); + //frame[0] = 8-(work/(20<>ANGLETOFINESHIFT) & FINEMASK; + //bounce = (FINESINE(ang) - FRACUNIT/2); + //hscale -= bounce/16; + //vscale += bounce/16; + + st_time += renderdeltatics; + } + } + + x = 90<title[0] && curplaying->alttitle[0]) + titl = va("%s - %s - ", curplaying->title, curplaying->alttitle); + else if (curplaying->title[0]) + titl = va("%s - ", curplaying->title); + else + titl = va("%s - ", curplaying->source); + } + else + titl = "NONE - "; + + i = V_LevelNameWidth(titl); + + st_scroll += renderdeltatics; + + while (st_scroll >= (i << FRACBITS)) + st_scroll -= i << FRACBITS; + + x -= st_scroll >> FRACBITS; + + while (x < BASEVIDWIDTH-y) + x += i; + while (x > y) + { + x -= i; + V_DrawLevelTitle(x, 24, 0, titl); + } + + if (curplaying && curplaying->authors[0]) + V_DrawRightAlignedThinString(BASEVIDWIDTH-16, 46, V_ALLOWLOWERCASE, curplaying->authors); + + if (curplaying) + { + if (!curplaying->usage[0]) + V_DrawString(vid.dupx, vid.height - 10*vid.dupy, V_NOSCALESTART|V_ALLOWLOWERCASE, va("%.6s", curplaying->name)); + else { + V_DrawSmallString(vid.dupx, vid.height - 5*vid.dupy, V_NOSCALESTART|V_ALLOWLOWERCASE, va("%.6s - %.255s\n", curplaying->name, curplaying->usage)); + } + + if (cv_showmusicfilename.value) + V_DrawSmallString(0, 0, V_SNAPTOTOP|V_SNAPTOLEFT|V_ALLOWLOWERCASE, curplaying->filename); + } + } + + V_DrawFill(20, 60, 280, 128, 239); + + { + INT32 t, b, q, m = 128; + + if (numsoundtestdefs <= 8) + { + t = 0; + b = numsoundtestdefs - 1; + i = 0; + } + else + { + q = m; + m = (5*m)/numsoundtestdefs; + if (st_sel < 3) + { + t = 0; + b = 7; + i = 0; + } + else if (st_sel >= numsoundtestdefs-4) + { + t = numsoundtestdefs - 8; + b = numsoundtestdefs - 1; + i = q-m; + } + else + { + t = st_sel - 3; + b = st_sel + 4; + i = (t * (q-m))/(numsoundtestdefs - 8); + } + } + + V_DrawFill(20+280-1, 60 + i, 1, m, 0); + + if (t != 0) + V_DrawString(20+280+4, 60+4 - (skullAnimCounter/5), V_YELLOWMAP, "\x1A"); + + if (b != numsoundtestdefs - 1) + V_DrawString(20+280+4, 60+128-12 + (skullAnimCounter/5), V_YELLOWMAP, "\x1B"); + + x = 24; + y = 64; + + if (renderisnewtic) ++st_namescroll; + + while (t <= b) + { + if (t == st_sel) + V_DrawFill(20, y-4, 280-1, 16, 237); + + { + const size_t MAXLENGTH = 34; + const tic_t SCROLLSPEED = TICRATE/5; // Number of tics for name being scrolled by 1 letter + size_t nameoffset = 0; + size_t namelength = strlen(soundtestdefs[t]->source); + if (soundtestdefs[t]->title[0]) + namelength = strlen(soundtestdefs[t]->title); + + char buf[MAXLENGTH+1]; + + if (t == st_sel && namelength > MAXLENGTH) + { + switch (st_namescrollstate) + { + case 0: + { + // Scroll forward + nameoffset = (st_namescroll/SCROLLSPEED) % (namelength - MAXLENGTH + 1); + + if (nameoffset == namelength - MAXLENGTH) + { + st_namescroll = 0; + st_namescrollstate++; + } + } + break; + + case 1: + { + nameoffset = namelength - MAXLENGTH; + + // Show name end for 1 second, then start scrolling back + if (st_namescroll == TICRATE) + { + st_namescroll = 0; + st_namescrollstate++; + } + } + break; + + case 2: + { + // Scroll back + nameoffset = (namelength - MAXLENGTH - 1) - (st_namescroll/SCROLLSPEED) % (namelength - MAXLENGTH); + + if (nameoffset == 0) + { + st_namescroll = 0; + st_namescrollstate++; + } + } + break; + + case 3: + { + nameoffset = 0; + + // Show name beginning for 1 second, then start scrolling forward again + if (st_namescroll == TICRATE) + { + st_namescroll = 0; + st_namescrollstate = 0; + } + } + break; + } + } + + if (soundtestdefs[t]->title[0]) + strncpy(buf, soundtestdefs[t]->title + nameoffset, MAXLENGTH); + else + strncpy(buf, soundtestdefs[t]->source + nameoffset, MAXLENGTH); + buf[MAXLENGTH] = 0; + + V_DrawString(x, y, (t == st_sel ? V_YELLOWMAP : 0)|V_ALLOWLOWERCASE|V_MONOSPACE, buf); + if (curplaying == soundtestdefs[t]) + { + V_DrawFill(20+280-9, y-4, 8, 16, 230); + //V_DrawCharacter(165+140-8, y, '\x19' | V_YELLOWMAP, false); + //V_DrawFixedPatch((165+140-9)<= numsoundtestdefs-1) + st_sel = 0; + { + S_StartSound(NULL, sfx_menu1); + } + st_namescroll = 0; + st_namescrollstate = 0; + break; + case KEY_UPARROW: + if (!st_sel--) + st_sel = numsoundtestdefs-1; + { + S_StartSound(NULL, sfx_menu1); + } + st_namescroll = 0; + st_namescrollstate = 0; + break; + case KEY_PGDN: + if (st_sel < numsoundtestdefs-1) + { + st_sel += 3; + if (st_sel >= numsoundtestdefs-1) + st_sel = numsoundtestdefs-1; + S_StartSound(NULL, sfx_menu1); + } + st_namescroll = 0; + st_namescrollstate = 0; + break; + case KEY_PGUP: + if (st_sel) + { + st_sel -= 3; + if (st_sel < 0) + st_sel = 0; + S_StartSound(NULL, sfx_menu1); + } + st_namescroll = 0; + st_namescrollstate = 0; + break; + case KEY_BACKSPACE: + if (curplaying) + { + S_StopSounds(); + S_StopMusic(); + curplaying = NULL; + st_time = 0; + S_StartSound(NULL, sfx_skid); + } + break; + case KEY_ESCAPE: + exitmenu = true; + st_namescroll = 0; + st_namescrollstate = 0; + break; + + case KEY_RIGHTARROW: + case KEY_LEFTARROW: + case KEY_ENTER: + S_StopSounds(); + S_StopMusic(); + st_time = 0; + curplaying = soundtestdefs[st_sel]; + S_ChangeMusicInternal(curplaying->name, true); + break; + + default: + break; + } + if (exitmenu) + { + Z_Free(soundtestdefs); + soundtestdefs = NULL; + + if (currentMenu->prevMenu) + M_SetupNextMenu(currentMenu->prevMenu); + else + M_ClearMenus(true); + } +} + // Entering secrets menu /*static void M_SecretsMenu(INT32 choice) { @@ -9240,6 +10557,7 @@ static void M_Refresh(INT32 choice) #endif/*MASTERSERVER*/ } +#ifdef MASTERSERVER static void M_DrawServerCountAndHorizontalBar(void) { const char *text; @@ -9282,6 +10600,7 @@ static void M_DrawServerCountAndHorizontalBar(void) V_DrawFill(1, currentMenu->y+32, center - radius - 2, 1, 0); V_DrawFill(center + radius + 2, currentMenu->y+32, BASEVIDWIDTH - 1, 1, 0); } +#endif static void M_DrawServerLines(INT32 x, INT32 page) { @@ -9344,6 +10663,7 @@ static void M_DrawConnectMenu(void) highlightflags, va("%u of %d", serverlistpage+1, numPages)); // Did you change the Server Browser address? Have a little reminder. + #ifdef MASTERSERVER if (CV_IsSetToDefault(&cv_masterserver)) mservflags = mservflags|highlightflags|V_30TRANS; else @@ -9352,6 +10672,7 @@ static void M_DrawConnectMenu(void) mservflags, va("MS: %s", cv_masterserver.string)); M_DrawServerCountAndHorizontalBar(); + #endif // When switching pages, slide the old page and the // new page across the screen @@ -9461,6 +10782,7 @@ void M_SortServerList(void) #ifndef NONET #ifdef UPDATE_ALERT +#ifdef MASTERSERVER static void M_CheckMODVersion(int id) { char updatestring[500]; @@ -9477,12 +10799,15 @@ static void M_CheckMODVersion(int id) #endif } } +#endif //MASTERSERVER #endif/*UPDATE_ALERT*/ #if defined (UPDATE_ALERT) && defined (HAVE_THREADS) +#ifdef MASTERSERVER static void Check_new_version_thread (int *id) { + M_SetWaitingMode(M_WAITING_VERSION); M_CheckMODVersion(*id); @@ -9495,9 +10820,12 @@ Check_new_version_thread (int *id) { free(id); } + } +#endif #endif/*defined (UPDATE_ALERT) && defined (HAVE_THREADS)*/ +#ifdef MASTERSERVER static void M_ConnectMenu(INT32 choice) { (void)choice; @@ -9542,12 +10870,13 @@ static void M_ConnectMenu(INT32 choice) #endif/*defined (MASTERSERVER) && defined (HAVE_THREADS)*/ } + static void M_ConnectMenuModChecks(INT32 choice) { (void)choice; // okay never mind we want to COMMUNICATE to the player pre-emptively instead of letting them try and then get confused when it doesn't work - if (modifiedgame) + if (modifiedgame || autoloaded) { M_StartMessage(M_GetText("You have addons loaded.\nYou won't be able to join netgames!\n\nTo play online, restart the game\nand don't load any addons.\nSRB2Kart will automatically add\neverything you need when you join.\n\n(Press a key)\n"),M_ConnectMenu,MM_EVENTHANDLER); return; @@ -9555,8 +10884,15 @@ static void M_ConnectMenuModChecks(INT32 choice) M_ConnectMenu(-1); } +#endif boolean firstDismissedNagThisBoot = true; +#ifdef MASTERSERVER + +enum { + CONNECT_MENU, + STARTSERVER_MENU, +} connect_error_continue = CONNECT_MENU; static void M_HandleMasterServerResetChoice(event_t *ev) { @@ -9584,31 +10920,37 @@ static void M_HandleMasterServerResetChoice(event_t *ev) } } } + } +void M_PopupMasterServerConnectError(void) +{ + if (!CV_IsSetToDefault(&cv_masterserver) && cv_masterserver_nagattempts.value > 0) + { + M_StartMessage(M_GetText("There was a problem connecting to\ncustom Master Server\n\nYou've changed the Server Browser address.\nUnless you're from the future, this probably isn't what you want.\n\n\x83Press Accel\x80 to fix this and continue.\n"), connect_error_continue == STARTSERVER_MENU ? M_PreStartServerMenuChoice : M_PreConnectMenuChoice,MM_EVENTHANDLER); + } + else + { + M_StartMessage(M_GetText("There was a problem connecting to\nthe Master Server\n\nCheck the console for details.\n"), NULL, MM_NOTHING); + } +} +#endif + static void M_PreStartServerMenu(INT32 choice) { + (void)choice; - - if (!CV_IsSetToDefault(&cv_masterserver) && cv_masterserver_nagattempts.value > 0) - { - M_StartMessage(M_GetText("Hey! You've changed the Server Browser address.\n\nYou won't be able to host games on the official Server Browser.\nUnless you're from the future, this probably isn't what you want.\n\n\x83Press Accel\x80 to fix this and continue.\x80\nPress any other key to continue anyway.\n"),M_PreStartServerMenuChoice,MM_EVENTHANDLER); - return; - } - +#ifdef MASTERSERVER + connect_error_continue = STARTSERVER_MENU; +#endif M_StartServerMenu(-1); -} +} +#ifdef MASTERSERVER static void M_PreConnectMenu(INT32 choice) { (void)choice; - - if (!CV_IsSetToDefault(&cv_masterserver) && cv_masterserver_nagattempts.value > 0) - { - M_StartMessage(M_GetText("Hey! You've changed the Server Browser address.\n\nYou won't be able to see games from the official Server Browser.\nUnless you're from the future, this probably isn't what you want.\n\n\x83Press Accel\x80 to fix this and continue.\x80\nPress any other key to continue anyway.\n"),M_PreConnectMenuChoice,MM_EVENTHANDLER); - return; - } - + connect_error_continue = CONNECT_MENU; M_ConnectMenuModChecks(-1); } @@ -9623,6 +10965,7 @@ static void M_PreConnectMenuChoice(event_t *ev) M_HandleMasterServerResetChoice(ev); M_ConnectMenuModChecks(-1); } +#endif #endif //NONET //=========================================================================== @@ -9851,7 +11194,9 @@ static void M_DrawLevelSelectOnly(boolean leftfade, boolean rightfade) static void M_DrawServerMenu(void) { + M_DrawLevelSelectOnly(false, false); + #ifdef MASTERSERVER if (currentMenu == &MP_ServerDef && cv_advertise.value) // Remind players where they're hosting. { int mservflags = V_ALLOWLOWERCASE; @@ -9861,7 +11206,9 @@ static void M_DrawServerMenu(void) mservflags = mservflags|warningflags; V_DrawCenteredThinString(BASEVIDWIDTH/2, BASEVIDHEIGHT-12, mservflags, va("Master Server: %s", cv_masterserver.string)); } + #endif M_DrawGenericMenu(); + } static void M_MapChange(INT32 choice) @@ -10231,6 +11578,9 @@ static boolean setupm_skinlockedselect; #define SKINGRIDWIDTH 8 #define SKINGRIDHEIGHT 6 +#define SKINGRIDNEWWIDTH 8 +#define SKINGRIDNEWHEIGHT 9 + static char *sortNames[] = { "Name", "Internal name", @@ -10262,6 +11612,8 @@ static void M_DrawSetupMultiPlayerMenu(void) INT32 sltw, actw, hetw; UINT8 skintodisplay; INT32 nameboxaddy = 0; + int statoffset = 0; + int gridyoffset = 0; mx = MP_PlayerSetupDef.x; my = MP_PlayerSetupDef.y; @@ -10272,9 +11624,12 @@ static void M_DrawSetupMultiPlayerMenu(void) // use generic drawer for cursor, items and title M_DrawGenericMenu(); - // draw name string + // Offsets switch (cv_skinselectmenu.value) { + case SKINMENUTYPE_EXTENDED: + nameboxaddy = 6; + break; case SKINMENUTYPE_GRID: nameboxaddy = 6; break; @@ -10283,6 +11638,8 @@ static void M_DrawSetupMultiPlayerMenu(void) break; } + + M_DrawTextBox(mx + 32, my - 8 + nameboxaddy, MAXPLAYERNAME, 1); V_DrawString(mx + 40, my + nameboxaddy, V_ALLOWLOWERCASE, setupm_name); @@ -10294,6 +11651,32 @@ static void M_DrawSetupMultiPlayerMenu(void) st = V_StringWidth(skins[setupm_fakeskin].realname, 0); switch (cv_skinselectmenu.value) { + case SKINMENUTYPE_EXTENDED: +#define GETSELECTEDSKINNAME (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].realname : skins[setupm_fakeskin].realname) +#define GETSELECTEDSPEED (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartspeed : skins[setupm_fakeskin].kartspeed) +#define GETSELECTEDWEIGHT (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartweight : skins[setupm_fakeskin].kartweight) + + statoffset = 0; + tw = V_StringWidth("Character", 0);//V_StringWidth(GETSELECTEDSKINNAME, 0); + st = V_StringWidth(GETSELECTEDSKINNAME, 0); + + INT32 selectedskin = (itemOn == 1 && setupm_skinselect < numskins ? skinsorted[setupm_skinselect] : setupm_fakeskin); + speed = skins[selectedskin].kartspeed; + weight = skins[selectedskin].kartweight; + + V_DrawString((mx+(tw/2)) - (st/2), my + 37, + ((MP_PlayerSetupMenu[2].status & IT_TYPE) == IT_SPACE ? V_TRANSLUCENT : 0) | highlightflags | V_ALLOWLOWERCASE, + GETSELECTEDSKINNAME); + if (statdp == true) + statoffset = 50; + else + statoffset = 113; + + V_DrawString(statx - statoffset, staty - 10, V_6WIDTHSPACE, va("\x84%dS \x87%dW", GETSELECTEDSPEED, GETSELECTEDWEIGHT)); +#undef GETSELECTEDSKINNAME +#undef GETSELECTEDSPEED +#undef GETSELECTEDWEIGHT + break; case SKINMENUTYPE_GRID: #define GETSELECTEDSKINNAME (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].realname : skins[setupm_fakeskin].realname) tw = V_StringWidth("Character", 0);//V_StringWidth(GETSELECTEDSKINNAME, 0); @@ -10344,6 +11727,16 @@ static void M_DrawSetupMultiPlayerMenu(void) st = V_StringWidth(KartColor_Names[setupm_fakecolor], 0); switch (cv_skinselectmenu.value) { + case SKINMENUTYPE_EXTENDED: + V_DrawString(mx, my + 164, highlightflags | V_ALLOWLOWERCASE, KartColor_Names[setupm_fakecolor]); // SRB2kart + if (itemOn == 2) + { + V_DrawCharacter(mx - 10/* - st*/ - (skullAnimCounter/5), my + 164, + '\x1C' | highlightflags, false); // left arrow + V_DrawCharacter(mx + 2 + st + (skullAnimCounter/5), my + 164, + '\x1D' | highlightflags, false); // right arrow + } + break; case SKINMENUTYPE_GRID: case SKINMENUTYPE_2D: V_DrawString(mx, my + 152, highlightflags | V_ALLOWLOWERCASE, KartColor_Names[setupm_fakecolor]); // SRB2kart @@ -10371,6 +11764,52 @@ static void M_DrawSetupMultiPlayerMenu(void) switch (cv_skinselectmenu.value) { + case SKINMENUTYPE_EXTENDED: + // SRB2Kart: draw the stat backer + //This is where stats and shit would go. + // gonna put the sorttype here as well + V_DrawSmallString(statx-3, staty-37, V_6WIDTHSPACE|highlightflags, "Sort:"); + V_DrawSmallString(statx+17, staty-37, V_6WIDTHSPACE|highlightflags, sortNames[cv_skinselectgridsort.value]); + if (itemOn == 1) + V_DrawSmallString(statx+101, staty-37, V_6WIDTHSPACE|highlightflags, "BS: change"); + +#define GETSELECTEDSPEED (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartspeed : skins[setupm_fakeskin].kartspeed) +#define GETSELECTEDWEIGHT (itemOn == 1 && setupm_skinselect < numskins ? skins[skinsorted[setupm_skinselect]].kartweight : skins[setupm_fakeskin].kartweight) + + if (statdp == true) + { + int i; + //Background + V_DrawScaledPatch(statx - 50, staty + 4, 0, W_CachePatchName("K_STATNB", PU_CACHE)); + + //Speed + for (i = 0; i < GETSELECTEDSPEED; i++) // draw the stat bars + { + if (i == 0) + V_DrawScaledPatch(statx - 45, staty + 63, 0, W_CachePatchName("K_STATN1", PU_CACHE)); + else if (i == GETSELECTEDSPEED -1 ) + V_DrawScaledPatch(statx - 45, staty + 63 -(5 *i), 0, W_CachePatchName("K_STATN3", PU_CACHE)); + else + V_DrawScaledPatch(statx - 45, staty + 63 -(5 *i), 0, W_CachePatchName("K_STATN2", PU_CACHE)); + } + + //Weight + for (i = 0; i < GETSELECTEDWEIGHT; i++) // draw the stat bars + { + + if (i == 0) + V_DrawScaledPatch(statx - 30, staty + 63, 0, W_CachePatchName("K_STATN4", PU_CACHE)); + else if (i == GETSELECTEDWEIGHT -1) + V_DrawScaledPatch(statx - 30, staty + 63 -(5 *i), 0, W_CachePatchName("K_STATN6", PU_CACHE)); + else + V_DrawScaledPatch(statx - 30, staty + 63 -(5 *i), 0, W_CachePatchName("K_STATN5", PU_CACHE)); + } + } +#undef GETSELECTEDSPEED +#undef GETSELECTEDWEIGHT + + + break; case SKINMENUTYPE_GRID: // SRB2Kart: draw the stat backer // labels @@ -10457,6 +11896,47 @@ static void M_DrawSetupMultiPlayerMenu(void) switch (cv_skinselectmenu.value) { + //Skin grid stuff + case SKINMENUTYPE_EXTENDED: + gridyoffset = 10; + for (s = 0; s < SKINGRIDNEWWIDTH*SKINGRIDNEWHEIGHT; s++) + { + INT32 x = ((s % SKINGRIDNEWWIDTH) * 18) + ((BASEVIDWIDTH / 2) - (18 * SKINGRIDNEWWIDTH) - 8) + 100 + SKINXSHIFT; //BASEVIDWIDTH / 2 - ((icons + 1) * 24) - 4; + INT32 y = ((s / SKINGRIDNEWWIDTH) * 18) + ((BASEVIDHEIGHT / 2) - (18 * (SKINGRIDNEWWIDTH/2)) + gridyoffset); //BASEVIDWIDTH / 2 - ((icons + 1) * 24) - 4; + INT32 calcs = s + (setupm_skinypos * SKINGRIDNEWWIDTH); + INT32 skinn; + patch_t *face; + UINT8 *cmap; + + if (calcs < numskins) + skinn = skinsorted[calcs]; + else if (s % SKINGRIDNEWWIDTH == 0) + break; //really conveniant place to break out here + else + { + V_DrawFill(x, y, 16, 16, 239); + continue; + } + + face = facerankprefix[skinn]; + cmap = R_GetTranslationColormap(skinn, skins[skinn].prefcolor, GTC_MENUCACHE); + + V_DrawFixedPatch(x << FRACBITS, y << FRACBITS, FRACUNIT, 0, face, cmap); + } + + if (itemOn == 1) //has to be on skin select part + { + patch_t *cursor; + INT32 curx = (((setupm_skinselect % SKINGRIDNEWWIDTH) * 18) + ((BASEVIDWIDTH / 2) - (18 * SKINGRIDNEWWIDTH/2)) + SKINXSHIFT) + 20; + INT32 cury = (((setupm_skinselect / SKINGRIDNEWWIDTH) - setupm_skinypos) * 18) + ((BASEVIDHEIGHT / 2) - (18 * (SKINGRIDNEWWIDTH/2))+ gridyoffset); + + UINT8 cursorframe = (I_GetTime() / 4) % 7; + + cursor = W_CachePatchName(va("K_CHILI%d", cursorframe + 1), PU_CACHE); + V_DrawFixedPatch((curx << FRACBITS) - (FRACUNIT), (cury << FRACBITS) - (FRACUNIT), FRACUNIT+(FRACUNIT>>3), 0, cursor, NULL); + } + + break; case SKINMENUTYPE_GRID: for (s = 0; s < SKINGRIDWIDTH*SKINGRIDHEIGHT; s++) { @@ -10591,7 +12071,11 @@ static void M_DrawSetupMultiPlayerMenu(void) #define charw 72 #define indexwidth 8 { - const INT32 colwidth = ((BASEVIDWIDTH-(2*mx))-charw)/(2*indexwidth); + INT32 colwidth = ((BASEVIDWIDTH-(2*mx))-charw)/(2*indexwidth); + + if (cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED) + colwidth = colwidth - 10; + INT32 j = -colwidth; INT16 col = setupm_fakecolor - colwidth; INT32 x = mx; @@ -10694,6 +12178,13 @@ static void M_DrawSetupMultiPlayerMenu(void) else sprdef = &skins[0].spritedef; break; + case SKINMENUTYPE_EXTENDED: + skintodisplay = (itemOn == 1 && setupm_skinselect < numskins ? skinsorted[setupm_skinselect] : setupm_fakeskin); + if (R_SkinAvailable(skins[skintodisplay].name) != -1) + sprdef = &skins[R_SkinAvailable(skins[skintodisplay].name)].spritedef; + else + sprdef = &skins[0].spritedef; + break; case SKINMENUTYPE_GRID: skintodisplay = (itemOn == 1 && setupm_skinselect < numskins ? skinsorted[setupm_skinselect] : setupm_fakeskin); if (R_SkinAvailable(skins[skintodisplay].name) != -1) @@ -10731,7 +12222,7 @@ static void M_DrawSetupMultiPlayerMenu(void) patch = W_CachePatchNum(sprframe->lumppat[speenframe], PU_CACHE); // draw box around guy - V_DrawFill(mx + 43 - (charw/2), my+65, charw, 84, 239); + V_DrawFill(mx + 36 - (charw/2), my+65, charw, 84, 239); // draw player sprite if (setupm_fakecolor) // inverse should never happen @@ -10740,13 +12231,13 @@ static void M_DrawSetupMultiPlayerMenu(void) if (skins[skintodisplay].flags & SF_HIRES) { - V_DrawFixedPatch((mx+43)<= ((setupm_skinypos-1)+SKINGRIDHEIGHT)*8 && setupm_skinypos < (ROUNDSKINSUPTO8/8)-SKINGRIDHEIGHT) - setupm_skinypos++; + + if (cv_skinselectmenu.value == SKINMENUTYPE_GRID){ + if (setupm_skinselect >= ((setupm_skinypos-1)+SKINGRIDHEIGHT)*8 && setupm_skinypos < (ROUNDSKINSUPTO8/8)-SKINGRIDHEIGHT) + setupm_skinypos++; + } + else if (cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED){ + if (setupm_skinselect >= ((setupm_skinypos-1)+SKINGRIDHEIGHT)*8+24 && setupm_skinypos < (ROUNDSKINSUPTO8/8)-SKINGRIDHEIGHT+24) + setupm_skinypos++; + } } else { @@ -10829,7 +12327,7 @@ static void M_HandleSetupMultiPlayer(INT32 choice) S_StartSound(NULL,sfx_menu1); // Tails break; } - else if (cv_skinselectmenu.value == SKINMENUTYPE_GRID) + else if (cv_skinselectmenu.value == SKINMENUTYPE_GRID || cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED) { if (itemOn == 1) { @@ -10848,8 +12346,16 @@ static void M_HandleSetupMultiPlayer(INT32 choice) else if (itemOn == 2) { setupm_skinselect = numskins - 1; - setupm_skinypos = (((numskins / SKINGRIDWIDTH) - (SKINGRIDHEIGHT-1)) > 0 ? ((numskins / SKINGRIDWIDTH) - (SKINGRIDHEIGHT-1)) : 0); - M_PrevOpt(); + if (cv_skinselectmenu.value == SKINMENUTYPE_GRID){ + setupm_skinypos = (((numskins / SKINGRIDWIDTH) - (SKINGRIDHEIGHT-1)) > 0 ? ((numskins / SKINGRIDWIDTH) - (SKINGRIDHEIGHT-1)) : 0); + M_PrevOpt(); + } + else if (cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED){ + setupm_skinypos = (((numskins / SKINGRIDWIDTH) - (SKINGRIDHEIGHT-1)-2) > 0 ? ((numskins / SKINGRIDWIDTH) - (SKINGRIDHEIGHT-1)-2) : 0); + M_PrevOpt(); + + } + } else M_PrevOpt(); @@ -10881,7 +12387,7 @@ static void M_HandleSetupMultiPlayer(INT32 choice) } break; } - else if (cv_skinselectmenu.value == SKINMENUTYPE_GRID && itemOn == 1) + else if ((cv_skinselectmenu.value == SKINMENUTYPE_GRID || cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED) && itemOn == 1) { if (setupm_skinselect > 0) { @@ -10893,7 +12399,10 @@ static void M_HandleSetupMultiPlayer(INT32 choice) { INT32 roundedskins = ROUNDSKINSUPTO8; setupm_skinselect = roundedskins-1; - setupm_skinypos = (((roundedskins/8) - SKINGRIDHEIGHT) > 0 ? (roundedskins/8) - SKINGRIDHEIGHT : 0); + if (cv_skinselectmenu.value == SKINMENUTYPE_GRID) + setupm_skinypos = (((roundedskins/8) - SKINGRIDHEIGHT) > 0 ? (roundedskins/8) - SKINGRIDHEIGHT : 0); + else if (cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED) + setupm_skinypos = (((roundedskins/8) - SKINGRIDHEIGHT-2) > 0 ? (roundedskins/8) - SKINGRIDHEIGHT-2 : 0); } S_StartSound(NULL, sfx_menu1); break; @@ -10931,13 +12440,19 @@ static void M_HandleSetupMultiPlayer(INT32 choice) } break; } - else if (cv_skinselectmenu.value == SKINMENUTYPE_GRID && itemOn == 1) + else if ((cv_skinselectmenu.value == SKINMENUTYPE_GRID || cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED) && itemOn == 1) { if (setupm_skinselect < ROUNDSKINSUPTO8 - 1) { setupm_skinselect++; - if (setupm_skinselect >= ((setupm_skinypos-1)+SKINGRIDHEIGHT)*8 && setupm_skinypos < (ROUNDSKINSUPTO8/8)-SKINGRIDHEIGHT) - setupm_skinypos++; + if (cv_skinselectmenu.value == SKINMENUTYPE_GRID){ + if (setupm_skinselect >= ((setupm_skinypos-1)+SKINGRIDHEIGHT)*8 && setupm_skinypos < (ROUNDSKINSUPTO8/8)-SKINGRIDHEIGHT) + setupm_skinypos++; + } + else if (cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED){ + if (setupm_skinselect >= ((setupm_skinypos-1)+SKINGRIDHEIGHT)*8+24 && setupm_skinypos < (ROUNDSKINSUPTO8/8)-SKINGRIDHEIGHT+24) + setupm_skinypos++; + } } else { @@ -10979,7 +12494,7 @@ static void M_HandleSetupMultiPlayer(INT32 choice) setupm_name[l-1] =0; } } - else if (cv_skinselectmenu.value == SKINMENUTYPE_GRID && itemOn == 1) + else if ((cv_skinselectmenu.value == SKINMENUTYPE_GRID || cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED) && itemOn == 1) { // change sort for select menu (damn now i have to add another cvar...) // now we have the cvar @@ -10998,7 +12513,6 @@ static void M_HandleSetupMultiPlayer(INT32 choice) } } break; - case KEY_DEL: if (cv_skinselectmenu.value) BREAKWHENLOCKED @@ -11034,7 +12548,7 @@ static void M_HandleSetupMultiPlayer(INT32 choice) S_StartSound(NULL,sfx_menu1); } } - else if (cv_skinselectmenu.value == SKINMENUTYPE_GRID && itemOn == 1 && setupm_skinselect < numskins) + else if ((cv_skinselectmenu.value == SKINMENUTYPE_GRID || cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED ) && itemOn == 1 && setupm_skinselect < numskins) { setupm_fakeskin = skinsorted[setupm_skinselect]; S_StartSound(NULL, sfx_s221); @@ -11042,16 +12556,22 @@ static void M_HandleSetupMultiPlayer(INT32 choice) break; default: - if (choice < 32 || choice > 127 || itemOn != 0) + if (choice < 32 || choice > 127) break; - l = strlen(setupm_name); - if (l < MAXPLAYERNAME) - { - S_StartSound(NULL,sfx_menu1); // Tails - setupm_name[l] =(char)choice; - setupm_name[l+1] =0; + if (itemOn == 0){ + l = strlen(setupm_name); + if (l < MAXPLAYERNAME) + { + S_StartSound(NULL,sfx_menu1); // Tails + setupm_name[l] =(char)choice; + setupm_name[l+1] =0; + } } break; + + + + } #undef BREAKWHENLOCKED @@ -11086,6 +12606,12 @@ case SKINMENUTYPE_2D:\ MP_PlayerSetupMenu[2].alphaKey = 164;\ MP_PlayerSetupDef.y = 6;\ break;\ +case SKINMENUTYPE_EXTENDED:\ + MP_PlayerSetupMenu[0].alphaKey = 6;\ + MP_PlayerSetupMenu[1].alphaKey = 25;\ + MP_PlayerSetupMenu[2].alphaKey = 152;\ + MP_PlayerSetupDef.y = 6;\ + break;\ case SKINMENUTYPE_GRID:\ MP_PlayerSetupMenu[0].alphaKey = 6;\ MP_PlayerSetupMenu[1].alphaKey = 25;\ @@ -11115,6 +12641,7 @@ static void M_SetupMultiPlayer(INT32 choice) setupm_cvskin = &cv_skin; setupm_cvcolor = &cv_playercolor; setupm_cvname = &cv_playername; + setupm_skinxpos = 4; setupm_skinypos = 0; setupm_skinlockedselect = false; @@ -11265,7 +12792,7 @@ static boolean M_QuitMultiPlayerMenu(void) } // you know what? always putting these in the buffer won't hurt anything. COM_BufAddText (va("%s \"%s\"\n",setupm_cvskin->name,skins[setupm_fakeskin].name)); - COM_BufAddText (va("%s %d\n",setupm_cvcolor->name,setupm_fakecolor)); + COM_BufAddText (va("%s %d\n",setupm_cvcolor->name,setupm_fakecolor)); return true; } @@ -12369,6 +13896,118 @@ static void M_DrawVideoMode(void) W_CachePatchName("M_CURSOR", PU_CACHE)); } +// Just M_DrawGenericScrollMenu but showing a backing behind the headers. +static void M_DrawColorMenu(void) +{ + INT32 x, y, i, max, tempcentery, cursory = 0; + + // DRAW MENU + x = currentMenu->x; + y = currentMenu->y; + + if ((currentMenu->menuitems[itemOn].alphaKey*2 - currentMenu->menuitems[0].alphaKey*2) <= scrollareaheight) + tempcentery = currentMenu->y - currentMenu->menuitems[0].alphaKey*2; + else if ((currentMenu->menuitems[currentMenu->numitems-1].alphaKey*2 - currentMenu->menuitems[itemOn].alphaKey*2) <= scrollareaheight) + tempcentery = currentMenu->y - currentMenu->menuitems[currentMenu->numitems-1].alphaKey*2 + 2*scrollareaheight; + else + tempcentery = currentMenu->y - currentMenu->menuitems[itemOn].alphaKey*2 + scrollareaheight; + + for (i = 0; i < currentMenu->numitems; i++) + { + if (currentMenu->menuitems[i].status != IT_DISABLED && currentMenu->menuitems[i].alphaKey*2 + tempcentery >= currentMenu->y) + break; + } + + for (max = currentMenu->numitems; max > 0; max--) + { + if (currentMenu->menuitems[max].status != IT_DISABLED && currentMenu->menuitems[max-1].alphaKey*2 + tempcentery <= (currentMenu->y + 2*scrollareaheight)) + break; + } + + if (i) + V_DrawString(currentMenu->x - 20, currentMenu->y, V_YELLOWMAP, "\x1A"); // up arrow + if (max != currentMenu->numitems) + V_DrawString(currentMenu->x - 20, currentMenu->y + 2*scrollareaheight, V_YELLOWMAP, "\x1B"); // down arrow + + // draw title (or big pic) + M_DrawMenuTitle(); + + for (; i < max; i++) + { + y = currentMenu->menuitems[i].alphaKey*2 + tempcentery; + if (i == itemOn) + cursory = y; + switch (currentMenu->menuitems[i].status & IT_DISPLAY) + { + case IT_PATCH: + case IT_DYBIGSPACE: + case IT_BIGSLIDER: + case IT_STRING2: + case IT_DYLITLSPACE: + case IT_GRAYPATCH: + case IT_TRANSTEXT2: + // unsupported + break; + case IT_NOTHING: + break; + case IT_STRING: + case IT_WHITESTRING: + if (i != itemOn && (currentMenu->menuitems[i].status & IT_DISPLAY)==IT_STRING) + V_DrawString(x, y, 0, currentMenu->menuitems[i].text); + else + V_DrawString(x, y, V_YELLOWMAP, currentMenu->menuitems[i].text); + + // Cvar specific handling + switch (currentMenu->menuitems[i].status & IT_TYPE) + case IT_CVAR: + { + consvar_t *cv = (consvar_t *)currentMenu->menuitems[i].itemaction; + switch (currentMenu->menuitems[i].status & IT_CVARTYPE) + { + case IT_CV_SLIDER: + M_DrawSlider(x, y, cv, (i == itemOn)); + case IT_CV_NOPRINT: // color use this + case IT_CV_INVISSLIDER: // monitor toggles use this + break; + case IT_CV_STRING: + if (y + 12 > (currentMenu->y + 2*scrollareaheight)) + break; + M_DrawTextBox(x, y + 4, MAXSTRINGLENGTH, 1); + V_DrawString(x + 8, y + 12, V_ALLOWLOWERCASE, cv->string); + if (skullAnimCounter < 4 && i == itemOn) + V_DrawCharacter(x + 8 + V_StringWidth(cv->string, 0), y + 12, + '_' | 0x80, false); + y += 16; + break; + default: + V_DrawRightAlignedString(BASEVIDWIDTH - x, y, + ((cv->flags & CV_CHEAT) && !CV_IsSetToDefault(cv) ? V_REDMAP : V_YELLOWMAP), cv->string); + break; + } + break; + } + break; + case IT_TRANSTEXT: + V_DrawString(x, y, V_TRANSLUCENT, currentMenu->menuitems[i].text); + break; + case IT_QUESTIONMARKS: + V_DrawString(x, y, V_TRANSLUCENT|V_OLDSPACING, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); + break; + case IT_HEADERTEXT: + V_DrawString(x-16, y, V_YELLOWMAP, currentMenu->menuitems[i].text); + //V_DrawFill(19, y, 281, 9, currentMenu->menuitems[i+1].alphaKey); + //V_DrawFill(300, y, 1, 9, 26); + //M_DrawLevelPlatterHeader(y - (lsheadingheight - 12), currentMenu->menuitems[i].text, false); + break; + } + } + + // DRAW THE SKULL CURSOR + V_DrawScaledPatch(currentMenu->x - 24, cursory, 0, + W_CachePatchName("M_CURSOR", PU_CACHE)); +} + + // special menuitem key handler for video mode list static void M_HandleVideoMode(INT32 ch) { @@ -12822,20 +14461,6 @@ static void M_QuitSRB2(INT32 choice) // ===================================================================== // OpenGL specific options // ===================================================================== - -// ===================== -// M_OGL_DrawColorMenu() -// ===================== -static void M_OGL_DrawColorMenu(void) -{ - INT32 mx, my; - - mx = currentMenu->x; - my = currentMenu->y; - M_DrawGenericMenu(); // use generic drawer for cursor, items and title - V_DrawString(mx, my + currentMenu->menuitems[0].alphaKey - 10, - highlightflags, "Gamma correction"); -} #endif #ifdef HAVE_DISCORDRPC diff --git a/src/m_menu.h b/src/m_menu.h index a27f6c70b..8d1ebb723 100644 --- a/src/m_menu.h +++ b/src/m_menu.h @@ -147,6 +147,8 @@ boolean M_CanShowLevelInList(INT32 mapnum, INT32 gt); #define MAXSTRINGLENGTH 32 +#define MAXTOOLTIPS 255 + typedef union { struct menu_s *submenu; // IT_SUBMENU @@ -184,6 +186,7 @@ typedef struct menu_s INT16 x, y; // x, y of menu INT16 lastOn; // last item user was on in menu boolean (*quitroutine)(void); // called before quit a menu return true if we can + const char* tooltips[MAXTOOLTIPS]; // tooltips! give me that info bitch } menu_t; void M_SetupNextMenu(menu_t *menudef); @@ -242,6 +245,7 @@ extern description_t description[MAXSKINS]; extern consvar_t cv_showfocuslost; extern consvar_t cv_newgametype, cv_nextmap, cv_chooseskin, cv_serversort; extern consvar_t cv_showallmaps; +extern consvar_t cv_showmusicfilename; extern CV_PossibleValue_t gametype_cons_t[]; extern char dummystaffname[22]; @@ -269,6 +273,9 @@ void PDistort_menu_Onchange(void); // Bird menu updating void Bird_menu_Onchange(void); +// Saturn menu updating +void Saturn_menu_Onchange(void); + void M_ReplayHut(INT32 choice); void M_SetPlaybackMenuPointer(void); @@ -278,6 +285,10 @@ INT32 HU_GetHighlightColor(void); void M_PopupMasterServerRules(void); +#ifdef MASTERSERVER +void M_PopupMasterServerConnectError(void); +#endif + // These defines make it a little easier to make menus #define DEFAULTMENUSTYLE(header, source, prev, x, y)\ {\ @@ -288,6 +299,20 @@ void M_PopupMasterServerRules(void); M_DrawGenericMenu,\ x, y,\ 0,\ + NULL,\ + NULL\ +} + +#define DEFAULTSCROLLSTYLE(header, source, prev, x, y)\ +{\ + header,\ + sizeof(source)/sizeof(menuitem_t),\ + prev,\ + source,\ + M_DrawGenericScrollMenu,\ + x, y,\ + 0,\ + NULL,\ NULL\ } @@ -300,6 +325,7 @@ void M_PopupMasterServerRules(void); M_DrawPauseMenu,\ x, y,\ 0,\ + NULL,\ NULL\ } @@ -312,6 +338,7 @@ void M_PopupMasterServerRules(void); M_DrawCenteredMenu,\ BASEVIDWIDTH/2, y,\ 0,\ + NULL,\ NULL\ } @@ -324,6 +351,7 @@ void M_PopupMasterServerRules(void); M_DrawServerMenu,\ 24,40,\ 0,\ + NULL,\ NULL\ } @@ -336,6 +364,7 @@ void M_PopupMasterServerRules(void); M_DrawControl,\ 26, 40,\ 0,\ + NULL,\ NULL\ } @@ -348,6 +377,7 @@ void M_PopupMasterServerRules(void); M_DrawImageDef,\ 0, 0,\ 0,\ + NULL,\ NULL\ } diff --git a/src/m_misc.c b/src/m_misc.c index 0601bb17d..db41f291a 100644 --- a/src/m_misc.c +++ b/src/m_misc.c @@ -193,7 +193,7 @@ INT32 M_MapNumber(char first, char second) // ========================================================================== // some libcs has no access function, make our own -#if defined (_WIN32_WCE) || defined (_WII) +#if 0 int access(const char *path, int amode) { int accesshandle = -1; diff --git a/src/m_misc.h b/src/m_misc.h index 0ce4aaf45..b79965b62 100644 --- a/src/m_misc.h +++ b/src/m_misc.h @@ -41,6 +41,8 @@ void M_StopMovie(void); // the file where game vars and settings are saved #define CONFIGFILENAME "kartconfig.cfg" +// autoload! +#define AUTOLOADCONFIGFILENAME "autoload.cfg" INT32 M_MapNumber(char first, char second); diff --git a/src/m_perfstats.c b/src/m_perfstats.c index 11c0414b0..04e51a657 100644 --- a/src/m_perfstats.c +++ b/src/m_perfstats.c @@ -63,7 +63,10 @@ static ps_metric_t ps_removecount = {0}; ps_metric_t ps_checkposition_calls = {0}; +ps_metric_t ps_lua_prethinkframe_time = {0}; ps_metric_t ps_lua_thinkframe_time = {0}; +ps_metric_t ps_lua_postthinkframe_time = {0}; + ps_metric_t ps_lua_mobjhooks = {0}; ps_metric_t ps_otherlogictime = {0}; @@ -156,7 +159,9 @@ perfstatrow_t gamelogic_rows[] = { {" mobjs ", " Mobjs: ", &ps_thlist_times[THINK_MOBJ], PS_TIME|PS_LEVEL}, {" dynslop", " Dynamic slopes: ", &ps_thlist_times[THINK_DYNSLOPE], PS_TIME|PS_LEVEL}, {" precip ", " Precipitation: ", &ps_thlist_times[THINK_PRECIP], PS_TIME|PS_LEVEL},*/ + {" lprethinkf", " LUAh_PreThinkFrame:", &ps_lua_prethinkframe_time, PS_TIME|PS_LEVEL}, {" lthinkf", " LUAh_ThinkFrame:", &ps_lua_thinkframe_time, PS_TIME|PS_LEVEL}, + {" lpostthinkf", " LUAh_PostThinkFrame:", &ps_lua_postthinkframe_time, PS_TIME|PS_LEVEL}, {" other ", " Other: ", &ps_otherlogictime, PS_TIME|PS_LEVEL}, {0} }; @@ -189,10 +194,43 @@ int ps_frame_index = 0; int ps_tick_index = 0; // dynamically allocated resizeable array for thinkframe hook stats +ps_hookinfo_t *prethinkframe_hooks = NULL; +int prethinkframe_hooks_length = 0; +int prethinkframe_hooks_capacity = 16; + ps_hookinfo_t *thinkframe_hooks = NULL; int thinkframe_hooks_length = 0; int thinkframe_hooks_capacity = 16; +ps_hookinfo_t *postthinkframe_hooks = NULL; +int postthinkframe_hooks_length = 0; +int postthinkframe_hooks_capacity = 16; + +void PS_SetPreThinkFrameHookInfo(int index, precise_t time_taken, char* short_src) +{ + if (!prethinkframe_hooks) + { + // array needs to be initialized + prethinkframe_hooks = Z_Calloc(sizeof(ps_hookinfo_t) * prethinkframe_hooks_capacity, PU_STATIC, NULL); + } + if (index >= prethinkframe_hooks_capacity) + { + // array needs more space, realloc with double size + int new_capacity = prethinkframe_hooks_capacity * 2; + prethinkframe_hooks = Z_Realloc(prethinkframe_hooks, + sizeof(ps_hookinfo_t) * new_capacity, PU_STATIC, NULL); + // initialize new memory with zeros so the pointers in the structs are null + memset(&prethinkframe_hooks[prethinkframe_hooks_capacity], 0, + sizeof(ps_hookinfo_t) * prethinkframe_hooks_capacity); + prethinkframe_hooks_capacity = new_capacity; + } + prethinkframe_hooks[index].time_taken.value.p = time_taken; + memcpy(prethinkframe_hooks[index].short_src, short_src, LUA_IDSIZE * sizeof(char)); + // since the values are set sequentially from begin to end, the last call should leave + // the correct value to this variable + prethinkframe_hooks_length = index + 1; +} + void PS_SetThinkFrameHookInfo(int index, precise_t time_taken, char* short_src) { if (!thinkframe_hooks) @@ -218,6 +256,33 @@ void PS_SetThinkFrameHookInfo(int index, precise_t time_taken, char* short_src) thinkframe_hooks_length = index + 1; } +void PS_SetPostThinkFrameHookInfo(int index, precise_t time_taken, char* short_src) +{ + if (!postthinkframe_hooks) + { + // array needs to be initialized + postthinkframe_hooks = Z_Calloc(sizeof(ps_hookinfo_t) * postthinkframe_hooks_capacity, PU_STATIC, NULL); + } + if (index >= postthinkframe_hooks_capacity) + { + // array needs more space, realloc with double size + int new_capacity = postthinkframe_hooks_capacity * 2; + postthinkframe_hooks = Z_Realloc(postthinkframe_hooks, + sizeof(ps_hookinfo_t) * new_capacity, PU_STATIC, NULL); + // initialize new memory with zeros so the pointers in the structs are null + memset(&postthinkframe_hooks[postthinkframe_hooks_capacity], 0, + sizeof(ps_hookinfo_t) * postthinkframe_hooks_capacity); + postthinkframe_hooks_capacity = new_capacity; + } + postthinkframe_hooks[index].time_taken.value.p = time_taken; + memcpy(postthinkframe_hooks[index].short_src, short_src, LUA_IDSIZE * sizeof(char)); + // since the values are set sequentially from begin to end, the last call should leave + // the correct value to this variable + postthinkframe_hooks_length = index + 1; +} + + + static boolean PS_HighResolution(void) { return (vid.width >= 640 && vid.height >= 400); @@ -578,7 +643,11 @@ void PS_UpdateTickStats(void) ps_tictime.value.p - ps_playerthink_time.value.p - ps_thinkertime.value.p - - ps_lua_thinkframe_time.value.p; + ps_lua_prethinkframe_time.value.p - + ps_lua_thinkframe_time.value.p - + ps_lua_postthinkframe_time.value.p; + + PS_CountThinkers(); } @@ -590,21 +659,37 @@ void PS_UpdateTickStats(void) PS_UpdateRowHistories(misc_calls_rows, false); } } - if (cv_perfstats.value == 3 && cv_ps_samplesize.value > 1 && PS_IsLevelActive()) + if (cv_ps_samplesize.value > 1) { - int i; - for (i = 0; i < thinkframe_hooks_length; i++) + if(cv_perfstats.value >= 3 && PS_IsLevelActive()) { - PS_UpdateMetricHistory(&thinkframe_hooks[i].time_taken, true, false, false); + int i; + if (cv_perfstats.value == 3) + { + for (i = 0; i < thinkframe_hooks_length; i++) + PS_UpdateMetricHistory(&thinkframe_hooks[i].time_taken, true, false, false); + } + else if (cv_perfstats.value == 4) + { + for (i = 0; i < prethinkframe_hooks_length; i++) + PS_UpdateMetricHistory(&prethinkframe_hooks[i].time_taken, true, false, false); + } + else if (cv_perfstats.value == 5) + { + for (i = 0; i < postthinkframe_hooks_length; i++) + PS_UpdateMetricHistory(&postthinkframe_hooks[i].time_taken, true, false, false); + } } - } - if (cv_perfstats.value && cv_ps_samplesize.value > 1) - { - ps_tick_index++; - if (ps_tick_index >= cv_ps_samplesize.value) - ps_tick_index = 0; - if (ps_tick_samples_left) - ps_tick_samples_left--; + if (cv_perfstats.value) + { + ps_tick_index++; + if (ps_tick_index >= cv_ps_samplesize.value) + ps_tick_index = 0; + if (ps_tick_samples_left) + ps_tick_samples_left--; + + } + } } @@ -624,7 +709,7 @@ static void PS_DrawDescriptorHeader(void) int samples_left = max(ps_frame_samples_left, ps_tick_samples_left); int x, y; - if (cv_perfstats.value == 3) + if (cv_perfstats.value >= 3) { x = 2; y = 0; @@ -717,21 +802,20 @@ static void PS_DrawGameLogicStats(void) #define WIDTH 106 #define HEIGHT 4 #define MAX_X 214 -#define MAX_Y 192 +#define MAX_Y 182 #define START_X 2 #define START_Y 4 #define PAGE_ENTRIES ((MAX_Y - START_Y) / HEIGHT) -static void PS_DrawThinkFrameStats(void) +static void draw_think_frame_stats(int hook_length, ps_hookinfo_t *hook) { char s[100]; int i; - int maxpage = thinkframe_hooks_length/PAGE_ENTRIES + 1; - int page = max(1, min(cv_ps_thinkframe_page.value, maxpage)); - - int pagestart = min((page - 1)*PAGE_ENTRIES, thinkframe_hooks_length); - int pageend = min(pagestart + PAGE_ENTRIES, thinkframe_hooks_length); + int maxpage = 0; + int page = 0; + int pagestart = 0; + int pageend = 0; // text writing position int x = START_X; int y = START_Y; @@ -741,19 +825,44 @@ static void PS_DrawThinkFrameStats(void) last_mod_name[0] = '\0'; INT32 total = 0; + //Decide page length based and drawn text on choosen thinker type + if (cv_perfstats.value == 3){ + maxpage = thinkframe_hooks_length/PAGE_ENTRIES + 1; + page = max(1, min(cv_ps_thinkframe_page.value, maxpage)); + pagestart = min((page - 1)*PAGE_ENTRIES, thinkframe_hooks_length); + pageend = min(pagestart + PAGE_ENTRIES, thinkframe_hooks_length); + + V_DrawSmallString(MAX_X-50, MAX_Y+2*HEIGHT, V_MONOSPACE | V_GREENMAP, "ThinkFrame"); + } + else if (cv_perfstats.value == 4){ + maxpage = prethinkframe_hooks_length/PAGE_ENTRIES + 1; + page = max(1, min(cv_ps_thinkframe_page.value, maxpage)); + pagestart = min((page - 1)*PAGE_ENTRIES, prethinkframe_hooks_length); + pageend = min(pagestart + PAGE_ENTRIES, prethinkframe_hooks_length); + V_DrawSmallString(MAX_X-60, MAX_Y+2*HEIGHT, V_MONOSPACE | V_GREENMAP, "PreThinkFrame"); + } + else if (cv_perfstats.value == 5){ + maxpage = postthinkframe_hooks_length/PAGE_ENTRIES + 1; + page = max(1, min(cv_ps_thinkframe_page.value, maxpage)); + pagestart = min((page - 1)*PAGE_ENTRIES, postthinkframe_hooks_length); + pageend = min(pagestart + PAGE_ENTRIES, postthinkframe_hooks_length); + V_DrawSmallString(MAX_X-65, MAX_Y+2*HEIGHT, V_MONOSPACE | V_GREENMAP, "PostThinkFrame"); + + } + PS_DrawDescriptorHeader(); - for (i = 0; i < thinkframe_hooks_length; i++) + for (i = 0; i < hook_length; i++) { #define NEXT_ROW() y += HEIGHT; - INT32 value = PS_GetMetricScreenValue(&thinkframe_hooks[i].time_taken, true); + INT32 value = PS_GetMetricScreenValue(&hook[i].time_taken, true); total += value; if (i < pagestart || i >= pageend) continue; - char* str = thinkframe_hooks[i].short_src; + char* str = hook[i].short_src; char* tempstr = tempbuffer; int len = (int)strlen(str); char* str_ptr; @@ -808,6 +917,8 @@ static void PS_DrawThinkFrameStats(void) snprintf(s, sizeof s - 1, "PAGE %d", page); V_DrawSmallString(START_X, MAX_Y+2*HEIGHT, V_MONOSPACE | V_GREENMAP, s); } + + } void PS_ThinkFrame_Page_OnChange(void) @@ -828,6 +939,24 @@ void PS_ThinkFrame_Page_OnChange(void) #undef PAGE_ENTRIES + + +static void PS_DrawPreThinkFrameStats(void) +{ + draw_think_frame_stats(prethinkframe_hooks_length, prethinkframe_hooks); +} + +static void PS_DrawThinkFrameStats(void) +{ + draw_think_frame_stats(thinkframe_hooks_length, thinkframe_hooks); +} + +static void PS_DrawPostThinkFrameStats(void) +{ + draw_think_frame_stats(postthinkframe_hooks_length, postthinkframe_hooks); +} + + void M_DrawPerfStats(void) { if (cv_perfstats.value == 1) // rendering @@ -841,7 +970,7 @@ void M_DrawPerfStats(void) // tics when frame skips happen PS_DrawGameLogicStats(); } - else if (cv_perfstats.value == 3) // lua thinkframe + else if (cv_perfstats.value >= 3) // lua thinkframe { if (!PS_IsLevelActive()) return; @@ -850,13 +979,23 @@ void M_DrawPerfStats(void) // Low resolutions can't really use V_DrawSmallString that is used by thinkframe stats. // A low-res version using V_DrawThinString could be implemented, // but it would have much less space for information. - V_DrawThinString(80, 92, V_MONOSPACE | V_ALLOWLOWERCASE | V_YELLOWMAP, "Perfstats 3 is not available"); + V_DrawThinString(80, 92, V_MONOSPACE | V_ALLOWLOWERCASE | V_YELLOWMAP, "Lua Perfstats is not available"); V_DrawThinString(80, 100, V_MONOSPACE | V_ALLOWLOWERCASE | V_YELLOWMAP, "for resolutions below 640x400."); + return; } - else + if (cv_perfstats.value == 3) { PS_DrawThinkFrameStats(); } + else if (cv_perfstats.value == 4) + { + PS_DrawPreThinkFrameStats(); + } + else if (cv_perfstats.value == 5) + { + PS_DrawPostThinkFrameStats(); + } + } } @@ -867,10 +1006,18 @@ static void PS_ClearHistory(void) Z_FreeTags(PU_PERFSTATS, PU_PERFSTATS); // thinkframe hook metric history pointers need to be cleared manually + for (i = 0; i < prethinkframe_hooks_length; i++) + { + prethinkframe_hooks[i].time_taken.history = NULL; + } for (i = 0; i < thinkframe_hooks_length; i++) { thinkframe_hooks[i].time_taken.history = NULL; } + for (i = 0; i < postthinkframe_hooks_length; i++) + { + postthinkframe_hooks[i].time_taken.history = NULL; + } ps_frame_index = ps_tick_index = 0; // PS_UpdateMetricHistory will set these correctly when it runs diff --git a/src/m_perfstats.h b/src/m_perfstats.h index d9ce6d171..ade7efd33 100644 --- a/src/m_perfstats.h +++ b/src/m_perfstats.h @@ -44,12 +44,17 @@ extern ps_metric_t ps_thlist_times[]; extern ps_metric_t ps_checkposition_calls; +extern ps_metric_t ps_lua_prethinkframe_time; extern ps_metric_t ps_lua_thinkframe_time; +extern ps_metric_t ps_lua_postthinkframe_time; extern ps_metric_t ps_lua_mobjhooks; extern ps_metric_t ps_otherlogictime; +void PS_SetPreThinkFrameHookInfo(int index, precise_t time_taken, char* short_src); void PS_SetThinkFrameHookInfo(int index, precise_t time_taken, char* short_src); +void PS_SetPostThinkFrameHookInfo(int index, precise_t time_taken, char* short_src); + void PS_UpdateTickStats(void); diff --git a/src/mserv.c b/src/mserv.c index 5c33cfe88..3b5d84b46 100644 --- a/src/mserv.c +++ b/src/mserv.c @@ -57,8 +57,12 @@ static void Command_Listserv_f(void); #endif/*MASTERSERVER*/ + + static void Update_parameters (void); +#ifdef MASTERSERVER + static void MasterServer_OnChange(void); static void Advertise_OnChange(void); @@ -69,16 +73,26 @@ static CV_PossibleValue_t masterserver_update_rate_cons_t[] = { {0, NULL} }; +#endif + +#ifdef MASTERSERVER consvar_t cv_masterserver = {"masterserver", "https://ms.kartkrew.org/ms/api", CV_SAVE|CV_CALL, NULL, MasterServer_OnChange, 0, NULL, NULL, 0, 0, NULL}; +#endif + +#ifdef HOLEPUNCH consvar_t cv_rendezvousserver = {"holepunchserver", "relay.kartkrew.org", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; +#endif + consvar_t cv_servername = {"servername", "SRB2Kart server", CV_SAVE|CV_CALL|CV_NOINIT, NULL, Update_parameters, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_server_contact = {"server_contact", "", CV_SAVE|CV_CALL|CV_NOINIT, NULL, Update_parameters, 0, NULL, NULL, 0, 0, NULL}; - +#ifdef MASTERSERVER consvar_t cv_masterserver_update_rate = {"masterserver_update_rate", "15", CV_SAVE|CV_CALL|CV_NOINIT, masterserver_update_rate_cons_t, MasterClient_Ticker, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_advertise = {"advertise", "No", CV_NETVAR|CV_CALL|CV_NOINIT, CV_YesNo, Advertise_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_masterserver_nagattempts = {"masterserver_nagattempts", "5", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; +#endif + #if defined (MASTERSERVER) && defined (HAVE_THREADS) int ms_QueryId; @@ -98,6 +112,7 @@ UINT16 current_port = 0; void AddMServCommands(void) { #ifndef NONET +#ifdef MASTERSERVER CV_RegisterVar(&cv_masterserver); CV_RegisterVar(&cv_masterserver_update_rate); CV_RegisterVar(&cv_masterserver_timeout); @@ -105,7 +120,11 @@ void AddMServCommands(void) CV_RegisterVar(&cv_masterserver_token); CV_RegisterVar(&cv_masterserver_nagattempts); CV_RegisterVar(&cv_advertise); +#endif +#ifdef HOLEPUNCH CV_RegisterVar(&cv_rendezvousserver); +#endif + CV_RegisterVar(&cv_servername); CV_RegisterVar(&cv_server_contact); #ifdef MASTERSERVER @@ -121,7 +140,7 @@ static void WarnGUI (void) #ifdef HAVE_THREADS I_lock_mutex(&m_menu_mutex); #endif - M_StartMessage(M_GetText("There was a problem connecting to\nthe Master Server\n\nCheck the console for details.\n"), NULL, MM_NOTHING); + M_PopupMasterServerConnectError(); #ifdef HAVE_THREADS I_unlock_mutex(m_menu_mutex); #endif @@ -548,19 +567,20 @@ Update_parameters (void) } #endif/*MASTERSERVER*/ } - +#ifdef MASTERSERVER static void MasterServer_OnChange(void) { -#ifdef MASTERSERVER + UnregisterServer(); Set_api(cv_masterserver.string); if (Online()) RegisterServer(); -#endif/*MASTERSERVER*/ -} +} +#endif/*MASTERSERVER*/ +#ifdef MASTERSERVER static void Advertise_OnChange(void) { @@ -596,3 +616,4 @@ Advertise_OnChange(void) M_PopupMasterServerRules(); } } +#endif diff --git a/src/mserv.h b/src/mserv.h index c4c2d078f..5a74771a4 100644 --- a/src/mserv.h +++ b/src/mserv.h @@ -51,18 +51,25 @@ typedef struct #endif // ================================ GLOBALS =============================== - -extern consvar_t cv_masterserver, cv_servername; +#ifdef MASTERSERVER +extern consvar_t cv_masterserver; +#endif +extern consvar_t cv_servername; extern consvar_t cv_server_contact; +#ifdef MASTERSERVER extern consvar_t cv_masterserver_update_rate; extern consvar_t cv_masterserver_timeout; extern consvar_t cv_masterserver_debug; extern consvar_t cv_masterserver_token; -extern consvar_t cv_rendezvousserver; extern consvar_t cv_advertise; extern consvar_t cv_masterserver_nagattempts; +#endif + +#ifdef HOLEPUNCH +extern consvar_t cv_rendezvousserver; +#endif #ifdef HAVE_THREADS extern int ms_QueryId; @@ -71,7 +78,7 @@ extern I_mutex ms_QueryId_mutex; extern msg_server_t *ms_ServerList; extern I_mutex ms_ServerList_mutex; #endif - +#ifdef MASTERSERVER void RegisterServer(void); void UnregisterServer(void); @@ -97,3 +104,5 @@ int HMS_compare_mod_version (char *buffer, size_t size_of_buffer); const char * HMS_fetch_rules (char *buffer, size_t size_of_buffer); #endif + +#endif \ No newline at end of file diff --git a/src/p_inter.c b/src/p_inter.c index 07f4860e9..9e333ebe2 100644 --- a/src/p_inter.c +++ b/src/p_inter.c @@ -2348,7 +2348,7 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) } target->player->playerstate = PST_DEAD; - if (cv_fading.value && P_IsLocalPlayer(target->player)) + if (cv_fading.value && cv_birdmusic.value && P_IsLocalPlayer(target->player)) { if (netgame || multiplayer) ms = cv_respawntime.value * 1000; diff --git a/src/p_local.h b/src/p_local.h index bb7c62046..df8df412e 100644 --- a/src/p_local.h +++ b/src/p_local.h @@ -142,7 +142,6 @@ extern consvar_t cv_quaketilt; extern consvar_t cv_tiltsmoothing; extern consvar_t cv_actionmovie; -extern consvar_t cv_windowquake; extern fixed_t t_cam_dist, t_cam_height, t_cam_rotate; extern fixed_t t_cam2_dist, t_cam2_height, t_cam2_rotate; diff --git a/src/p_mobj.c b/src/p_mobj.c index 12653d39d..5ad802f92 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -6063,13 +6063,22 @@ static void P_AddOverlay(mobj_t *thing) static void P_RemoveOverlay(mobj_t *thing) { mobj_t *mo; + if (overlaycap == thing) + { + P_SetTarget(&overlaycap, thing->hnext); + P_SetTarget(&thing->hnext, NULL); + return; + } + for (mo = overlaycap; mo; mo = mo->hnext) - if (mo->hnext == thing) - { - P_SetTarget(&mo->hnext, thing->hnext); - P_SetTarget(&thing->hnext, NULL); - return; - } + { + if (mo->hnext != thing) + continue; + + P_SetTarget(&mo->hnext, thing->hnext); + P_SetTarget(&thing->hnext, NULL); + return; + } } void P_RunShadows(void) @@ -6175,12 +6184,14 @@ static void P_RemoveShadow(mobj_t *thing) } for (mo = shadowcap; mo; mo = mo->hnext) - if (mo->hnext == thing) - { - P_SetTarget(&mo->hnext, thing->hnext); - P_SetTarget(&thing->hnext, NULL); - return; - } + { + if (mo->hnext != thing) + continue; + + P_SetTarget(&mo->hnext, thing->hnext); + P_SetTarget(&thing->hnext, NULL); + return; + } } void A_BossDeath(mobj_t *mo); @@ -6240,6 +6251,87 @@ static void P_KoopaThinker(mobj_t *koopa) } } +// +// P_RollPitchMobj +// Assigns slopepitch and sloperoll to objects, and resets said values when slope-rolling +// is turned off completely. +// +void P_RollPitchMobj(mobj_t* mobj) +{ + boolean usedist = false; + + if (cv_sloperolldist.value > 0) + usedist = true; + + if ((cv_spriteroll.value) && (cv_sloperoll.value == 2)) + { + K_RollMobjBySlopes(mobj, usedist); + } + else + { + mobj->sloperoll = FixedAngle(0); + mobj->slopepitch = FixedAngle(0); + } +} + +angle_t P_MobjPitchAndRoll(mobj_t *mobj) +{ + spritedef_t *sprdef; + spriteframe_t *sprframe; + angle_t ang = 0; + angle_t camang = 0; + angle_t return_angle = 0; + + if (!cv_spriteroll.value) + return 0; + + if (P_MobjWasRemoved(mobj)) + return 0; + + size_t rot = mobj->frame & FF_FRAMEMASK; + boolean papersprite = (mobj->frame & FF_PAPERSPRITE); + + if (mobj->skin && mobj->sprite == SPR_PLAY) + { + sprdef = &((skin_t *)mobj->skin)->spritedef; + + if (rot >= sprdef->numframes) + sprdef = &sprites[mobj->sprite]; + } + else + { + sprdef = &sprites[mobj->sprite]; + } + + if (rot >= sprdef->numframes) + { + sprdef = &sprites[states[S_UNKNOWN].sprite]; + rot = states[S_UNKNOWN].frame&FF_FRAMEMASK; + } + + sprframe = &sprdef->spriteframes[rot]; + + // No sprite frame? I guess it is possible + if (!sprframe) return 0; + + if (sprframe->rotate != SRF_SINGLE || papersprite) + { + ang = R_PointToAngle(mobj->x, mobj->y) - mobj->angle; + camang = R_PointToAngle(mobj->x, mobj->y); + } + + return_angle = FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), mobj->roll) + + FixedMul(FINESINE((ang) >> ANGLETOFINESHIFT), mobj->pitch); + + if (cv_sloperoll.value) + { + return_angle += FixedMul(FINECOSINE((camang) >> ANGLETOFINESHIFT), mobj->sloperoll) + + FixedMul(FINESINE((camang) >> ANGLETOFINESHIFT), mobj->slopepitch); + } + + return return_angle; +} + // // P_MobjThinker // @@ -6382,6 +6474,12 @@ void P_MobjThinker(mobj_t *mobj) return; } + if (mobj->state == &states[S_PLAY_SIGN]) // hack to make the player sign icon roll with the sign itself + { + mobj->slopepitch = mobj->target->slopepitch; + mobj->sloperoll = mobj->target->sloperoll; + } + P_AddOverlay(mobj); break; case MT_SHADOW: @@ -6390,7 +6488,12 @@ void P_MobjThinker(mobj_t *mobj) P_RemoveMobj(mobj); return; } - + + if (mobj->state == &states[S_SHADOW] && cv_sloperoll.value == 2) + { + mobj->slopepitch = mobj->target->slopepitch; + mobj->sloperoll = mobj->target->sloperoll; + } P_AddShadow(mobj); break; /*case MT_BLACKORB: @@ -6417,6 +6520,7 @@ void P_MobjThinker(mobj_t *mobj) P_RemoveMobj(mobj); return; } + P_RollPitchMobj(mobj); break; case MT_SMOLDERING: if (leveltime % 2 == 0) @@ -7845,6 +7949,7 @@ void P_MobjThinker(mobj_t *mobj) fixed_t distbarrier = 512*mapobjectscale; fixed_t distaway; + P_RollPitchMobj(mobj); P_SpawnGhostMobj(mobj); if (mobj->threshold > 0) @@ -7912,6 +8017,7 @@ void P_MobjThinker(mobj_t *mobj) } else { + P_RollPitchMobj(mobj); P_SpawnGhostMobj(mobj); mobj->angle = R_PointToAngle2(0, 0, mobj->momx, mobj->momy); P_InstaThrust(mobj, mobj->angle, mobj->movefactor); @@ -7945,6 +8051,9 @@ void P_MobjThinker(mobj_t *mobj) mobj->momx = mobj->momy = 0; mobj->health = 1; } + + P_RollPitchMobj(mobj); + if (mobj->threshold > 0) mobj->threshold--; break; @@ -7992,6 +8101,8 @@ void P_MobjThinker(mobj_t *mobj) || (mobj->state >= &states[S_SSMINE_DEPLOY8] && mobj->state <= &states[S_SSMINE_DEPLOY13])) A_GrenadeRing(mobj); + P_RollPitchMobj(mobj); + if (mobj->threshold > 0) mobj->threshold--; break; @@ -8202,6 +8313,8 @@ void P_MobjThinker(mobj_t *mobj) } P_MoveOrigin(mobj, destx, desty, mobj->target->z); + mobj->spriteyoffset = mobj->target->spriteyoffset; + mobj->spritexoffset = mobj->target->spritexoffset; break; } case MT_ROCKETSNEAKER: @@ -8344,6 +8457,10 @@ void P_MobjThinker(mobj_t *mobj) } } } + + // fancy sign rotation + P_RollPitchMobj(mobj); + break; case MT_CDUFO: if (!mobj->spawnpoint || mobj->fuse) @@ -9524,6 +9641,10 @@ mobj_t *P_SpawnMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type) mobj->height = info->height; mobj->flags = info->flags; mobj->sloperoll = 0; + mobj->slopepitch = 0; + + mobj->pitch_sprite = 0; + mobj->roll_sprite = 0; mobj->health = info->spawnhealth; @@ -10359,7 +10480,7 @@ void P_SpawnPrecipitation(void) subsector_t *precipsector = NULL; precipmobj_t *rainmo = NULL; - if (dedicated || !(cv_drawdist_precip.value) || curWeather == PRECIP_NONE || curWeather == PRECIP_STORM_NORAIN) // SRB2Kart + if (dedicated || /*!cv_precipdensity*/!cv_drawdist_precip.value || curWeather == PRECIP_NONE) // SRB2Kart return; // Use the blockmap to narrow down our placing patterns @@ -10370,8 +10491,16 @@ void P_SpawnPrecipitation(void) //for (j = 0; j < cv_precipdensity.value; ++j) -- density is 1 for kart always { - x = basex + ((M_RandomKey(MAPBLOCKUNITS<<3)<>3); - y = basey + ((M_RandomKey(MAPBLOCKUNITS<<3)<>3); + if (cv_lessprecip.value) + { + x = basex*1.5 + ((M_RandomKey(MAPBLOCKUNITS<<3)<>3); + y = basey*1.5 + ((M_RandomKey(MAPBLOCKUNITS<<3)<>3); + } + else + { + x = basex + ((M_RandomKey(MAPBLOCKUNITS<<3)<>3); + y = basey + ((M_RandomKey(MAPBLOCKUNITS<<3)<>3); + } precipsector = R_IsPointInSubsector(x, y); @@ -10402,13 +10531,22 @@ void P_SpawnPrecipitation(void) } else // everything else. rainmo = P_SpawnRainMobj(x, y, height, MT_RAIN); - if (curWeather == PRECIP_BLANK) - rainmo->precipflags |= PCF_INVISIBLE; // Randomly assign a height, now that floorz is set. rainmo->z = M_RandomRange(rainmo->floorz>>FRACBITS, rainmo->ceilingz>>FRACBITS)<type, x>>FRACBITS, y>>FRACBITS); + CONS_Alert(CONS_ERROR, "Failed to spawn map thing #%d at %d, %d. This will crash vanilla clients!\n", mthing->type, x>>FRACBITS, y>>FRACBITS); return; } diff --git a/src/p_mobj.h b/src/p_mobj.h index 67a579c11..5d26f9b44 100644 --- a/src/p_mobj.h +++ b/src/p_mobj.h @@ -283,9 +283,9 @@ typedef struct mobj_s struct mobj_s **sprev; // killough 8/11/98: change to ptr-to-ptr // More drawing info: to determine current sprite. - angle_t angle; // orientation - angle_t old_angle; // orientation interpolation - angle_t old_angle2; + angle_t angle, pitch, roll; // orientation + angle_t old_angle, old_pitch, old_roll; // orientation interpolation + angle_t old_angle2, old_pitch2, old_roll2; angle_t rollangle; spritenum_t sprite; // used to find patch_t and flip value UINT32 frame; // frame number, plus bits see p_pspr.h @@ -302,7 +302,10 @@ typedef struct mobj_s fixed_t stretchslam; // "squish" effect when you land //sloperollangle - angle_t sloperoll, reservezangle, reservexydir; + angle_t sloperoll, slopepitch; + angle_t old_sloperoll, old_slopepitch; + angle_t old_sloperoll2, old_slopepitch2; + angle_t pitch_sprite, roll_sprite; struct msecnode_s *touching_sectorlist; // a linked list of sectors where this object appears @@ -395,6 +398,7 @@ typedef struct mobj_s boolean resetinterp; // if true, some fields should not be interpolated (see R_InterpolateMobjState implementation) boolean colorized; // Whether the mobj uses the rainbow colormap + boolean mirrored; // The object's rotations will be mirrored left to right, e.g., see frame AL from the right and AR from the left boolean rollmodel; // OpenGL: Should this model rotate? tic_t slamsoundtimer; @@ -432,9 +436,9 @@ typedef struct precipmobj_s struct precipmobj_s **sprev; // killough 8/11/98: change to ptr-to-ptr // More drawing info: to determine current sprite. - angle_t angle; // orientation - angle_t old_angle; // orientation interpolation - angle_t old_angle2; + angle_t angle, pitch, roll; // orientation + angle_t old_angle, old_pitch, old_roll; // orientation interpolation + angle_t old_angle2, old_pitch2, old_roll2; angle_t rollangle; spritenum_t sprite; // used to find patch_t and flip value UINT32 frame; // frame number, plus bits see p_pspr.h @@ -451,7 +455,10 @@ typedef struct precipmobj_s fixed_t stretchslam; // "squish" effect when you land //sloperollangle - angle_t sloperoll, reservezangle, reservexydir; + angle_t sloperoll, slopepitch; + angle_t old_sloperoll, old_slopepitch; + angle_t old_sloperoll2, old_slopepitch2; + angle_t pitch_sprite, roll_sprite; struct mprecipsecnode_s *touching_sectorlist; // a linked list of sectors where this object appears @@ -493,6 +500,10 @@ void P_AddCachedAction(mobj_t *mobj, INT32 statenum); // check mobj against water content, before movement code void P_MobjCheckWater(mobj_t *mobj); +// fancy sprite rotation +void P_RollPitchMobj(mobj_t *mobj); +angle_t P_MobjPitchAndRoll(mobj_t *mobj); + // Player spawn points void P_SpawnPlayer(INT32 playernum); void P_MovePlayerToSpawn(INT32 playernum, mapthing_t *mthing); diff --git a/src/p_pspr.h b/src/p_pspr.h index e74266002..5ac1d1d84 100644 --- a/src/p_pspr.h +++ b/src/p_pspr.h @@ -37,6 +37,8 @@ /// \brief Frame flags: only the frame number #define FF_FRAMEMASK 0x1ff +/// \brief Frame flags: Flip sprite horizontally +#define FF_HORIZONTALFLIP 0x400 /// \brief Frame flags: Thin, paper-like sprite (for collision equivalent, see MF_PAPERCOLLISION) #define FF_PAPERSPRITE 0x800 /// \brief Frame flags: Simple stateless animation diff --git a/src/p_saveg.c b/src/p_saveg.c index 64153a279..3ac86eae6 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -1976,14 +1976,28 @@ static void LoadMobjThinker(actionf_p1 thinker) mobj->thinker.function.acp1 = thinker; mobj->rollangle = 0; - mobj->spritexoffset = mobj->spriteyoffset = mobj->old_spritexoffset = mobj->old_spriteyoffset = FRACUNIT; - mobj->spritexscale = mobj->spriteyscale = mobj->old_spritexscale = mobj->old_spriteyscale = FRACUNIT; - mobj->realxscale = mobj->realyscale = FRACUNIT; + + mobj->pitch = 0; + mobj->roll = 0; + + mobj->sloperoll = 0; + mobj->slopepitch = 0; + + mobj->pitch_sprite = 0; + mobj->roll_sprite = 0; + + mobj->spritexoffset = mobj->old_spritexoffset = 0; + mobj->spriteyoffset = mobj->old_spriteyoffset = 0; + mobj->spritexscale = mobj->old_spritexscale = FRACUNIT; + mobj->spriteyscale = mobj->old_spriteyscale = FRACUNIT; + mobj->realxscale = FRACUNIT; + mobj->realyscale = FRACUNIT; + mobj->stretchslam = 0; mobj->slamsoundtimer = 0; - mobj->sloperoll = mobj->reservezangle = mobj->reservexydir = 0; - + mobj->mirrored = 0; + mobj->z = z; mobj->floorz = floorz; mobj->ceilingz = ceilingz; diff --git a/src/p_setup.c b/src/p_setup.c index d8dcbb877..0ad4844b9 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -2936,7 +2936,9 @@ boolean P_SetupLevel(boolean skipprecip) // Make sure all sounds are stopped before Z_FreeTags. S_StopSounds(); - S_ClearSfx(); + + if (!S_PrecacheSound()) + S_ClearSfx(); // As oddly named as this is, this handles music only. // We should be fine starting it here. @@ -3148,7 +3150,11 @@ boolean P_SetupLevel(boolean skipprecip) // Correct missing sidedefs & deep water trick HWR_CorrectSWTricks(); HWR_CreatePlanePolygons((INT32)numnodes - 1); + + if (HWR_ShouldUsePaletteRendering()) //unsure if this is the right place, but seems to work since we dont have HWR_LoadLevel like srb2 + HWR_SetMapPalette(); } + #endif // oh god I hope this helps @@ -3490,11 +3496,8 @@ UINT16 P_PartialAddWadFile(const char *wadfilename, boolean local) if (wadfiles[wadnum]->important) partadd_important = true; - - if (local) - wadfiles[wadnum]->localfile = true; - else - wadfiles[wadnum]->localfile = false; + + wadfiles[wadnum]->localfile = local; // // search for sound replacements @@ -3503,11 +3506,12 @@ UINT16 P_PartialAddWadFile(const char *wadfilename, boolean local) for (i = 0; i < numlumps; i++, lumpinfo++) { name = lumpinfo->name; + lumpnum_t lumpnum = i|(wadnum<<16); if (name[0] == 'D') { if (name[1] == 'S') for (j = 1; j < NUMSFX; j++) { - if (S_sfx[j].name && !strnicmp(S_sfx[j].name, name + 2, 6)) + if (S_sfx[j].name && !strnicmp(S_sfx[j].name, name + 2, 6) && S_sfx[j].lumpnum != lumpnum && S_sfx[j].lumpnum != LUMPERROR) { // the sound will be reloaded when needed, // since sfx->data will be NULL @@ -3515,6 +3519,10 @@ UINT16 P_PartialAddWadFile(const char *wadfilename, boolean local) I_FreeSfx(&S_sfx[j]); + // Re-cache it + if (S_PrecacheSound()) + S_sfx[j].data = I_GetSfx(&S_sfx[j]); + sreplaces++; } } @@ -3554,6 +3562,11 @@ UINT16 P_PartialAddWadFile(const char *wadfilename, boolean local) // S_LoadMusicDefs(wadnum); + // + // edit music defs for stuff like musictest + // + S_LoadMTDefs(wadnum); + // // search for maps // @@ -3587,6 +3600,9 @@ UINT16 P_PartialAddWadFile(const char *wadfilename, boolean local) if (!mapsadded) CONS_Printf(M_GetText("No maps added\n")); + // TODO: Experimental SPRTINFO support, test first + R_LoadSpriteInfoLumps(wadnum, wadfiles[wadnum]->numlumps); + refreshdirmenu &= ~REFRESHDIR_GAMEDATA; // Under usual circumstances we'd wait for REFRESHDIR_GAMEDATA to disappear the next frame, but it's a bit too dangerous for that... partadd_stage = 0; return wadnum; diff --git a/src/p_spec.c b/src/p_spec.c index 0ac38da01..dc2ea796d 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -2002,14 +2002,53 @@ void P_LinedefExecute(INT16 tag, mobj_t *actor, sector_t *caller) // void P_SwitchWeather(INT32 weathernum) { - boolean purge = true; - boolean raintype = (PRECIP_SNOW || PRECIP_RAIN || PRECIP_STORM || PRECIP_STORM_NOSTRIKES || PRECIP_BLANK); + boolean purge = false; + INT32 swap = 0; - if (weathernum == curWeather) - return; - - if (weathernum == raintype && curWeather == raintype) - purge = false; + switch (weathernum) + { + case PRECIP_NONE: // None + if (curWeather == PRECIP_NONE) + return; // Nothing to do. + purge = true; + break; + case PRECIP_STORM: // Storm + case PRECIP_STORM_NOSTRIKES: // Storm w/ no lightning + case PRECIP_RAIN: // Rain + if (curWeather == PRECIP_SNOW || curWeather == PRECIP_BLANK || curWeather == PRECIP_STORM_NORAIN) + swap = PRECIP_RAIN; + break; + case PRECIP_SNOW: // Snow + if (curWeather == PRECIP_SNOW) + return; // Nothing to do. + if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM || curWeather == PRECIP_STORM_NOSTRIKES || curWeather == PRECIP_BLANK || curWeather == PRECIP_STORM_NORAIN) + swap = PRECIP_SNOW; // Need to delete the other precips. + break; + case PRECIP_STORM_NORAIN: // Storm w/o rain + if (curWeather == PRECIP_SNOW + || curWeather == PRECIP_STORM + || curWeather == PRECIP_STORM_NOSTRIKES + || curWeather == PRECIP_RAIN + || curWeather == PRECIP_BLANK) + swap = PRECIP_STORM_NORAIN; + else if (curWeather == PRECIP_STORM_NORAIN) + return; + break; + case PRECIP_BLANK: + if (curWeather == PRECIP_SNOW + || curWeather == PRECIP_STORM + || curWeather == PRECIP_STORM_NOSTRIKES + || curWeather == PRECIP_RAIN) + swap = PRECIP_BLANK; + else if (curWeather == PRECIP_STORM_NORAIN) + swap = PRECIP_BLANK; + else if (curWeather == PRECIP_BLANK) + return; + break; + default: + CONS_Debug(DBG_GAMELOGIC, "P_SwitchWeather: Unknown weather type %d.\n", weathernum); + break; + } if (purge) { @@ -2026,7 +2065,7 @@ void P_SwitchWeather(INT32 weathernum) P_RemovePrecipMobj(precipmobj); } } - else // Rather than respawn all that crap, reuse it! + else if (swap && !((swap == PRECIP_BLANK && curWeather == PRECIP_STORM_NORAIN) || (swap == PRECIP_STORM_NORAIN && curWeather == PRECIP_BLANK))) // Rather than respawn all that crap, reuse it! { thinker_t *think; precipmobj_t *precipmobj; @@ -2038,7 +2077,7 @@ void P_SwitchWeather(INT32 weathernum) continue; // not a precipmobj thinker precipmobj = (precipmobj_t *)think; - if (weathernum == PRECIP_RAIN || weathernum == PRECIP_STORM || weathernum == PRECIP_STORM_NOSTRIKES) // Snow To Rain + if (swap == PRECIP_RAIN) // Snow To Rain { precipmobj->flags = mobjinfo[MT_RAIN].flags; st = &states[mobjinfo[MT_RAIN].spawnstate]; @@ -2053,7 +2092,7 @@ void P_SwitchWeather(INT32 weathernum) precipmobj->precipflags |= PCF_RAIN; //think->function.acp1 = (actionf_p1)P_RainThinker; } - else if (weathernum == PRECIP_SNOW) // Rain To Snow + else if (swap == PRECIP_SNOW) // Rain To Snow { INT32 z; @@ -2078,7 +2117,7 @@ void P_SwitchWeather(INT32 weathernum) //think->function.acp1 = (actionf_p1)P_SnowThinker; } - else // Remove precip, but keep it around for reuse. + else if (swap == PRECIP_BLANK || swap == PRECIP_STORM_NORAIN) // Remove precip, but keep it around for reuse. { //think->function.acp1 = (actionf_p1)P_NullPrecipThinker; @@ -2092,31 +2131,48 @@ void P_SwitchWeather(INT32 weathernum) case PRECIP_SNOW: // snow curWeather = PRECIP_SNOW; - if (purge) + if (!swap) P_SpawnPrecipitation(); break; case PRECIP_RAIN: // rain { + boolean dontspawn = false; + + if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM || curWeather == PRECIP_STORM_NOSTRIKES) + dontspawn = true; + curWeather = PRECIP_RAIN; - if (purge) + if (!dontspawn && !swap) P_SpawnPrecipitation(); break; } case PRECIP_STORM: // storm { + boolean dontspawn = false; + + if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM || curWeather == PRECIP_STORM_NOSTRIKES) + dontspawn = true; + curWeather = PRECIP_STORM; - if (purge) + if (!dontspawn && !swap) P_SpawnPrecipitation(); break; } case PRECIP_STORM_NOSTRIKES: // storm w/o lightning { - if (purge) + boolean dontspawn = false; + + if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM || curWeather == PRECIP_STORM_NOSTRIKES) + dontspawn = true; + + curWeather = PRECIP_STORM_NOSTRIKES; + + if (!dontspawn && !swap) P_SpawnPrecipitation(); break; @@ -2124,11 +2180,14 @@ void P_SwitchWeather(INT32 weathernum) case PRECIP_STORM_NORAIN: // storm w/o rain curWeather = PRECIP_STORM_NORAIN; + if (!swap) + P_SpawnPrecipitation(); + break; - case PRECIP_BLANK: //preloaded + case PRECIP_BLANK: curWeather = PRECIP_BLANK; - if (purge) + if (!swap) P_SpawnPrecipitation(); break; @@ -3568,8 +3627,8 @@ void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *rovers case 5: // Spikes // Don't do anything. In Soviet Russia, spikes find you. break; - case 6: // Death Pit (Camera Mod) - case 7: // Death Pit (No Camera Mod) + case 6: // Death Pit (Camera Tilt) + case 7: // Death Pit (No Camera Tilt) if (roversector || P_MobjReadyToTrigger(player->mo, sector)) P_DamageMobj(player->mo, NULL, NULL, 10000); break; @@ -3626,8 +3685,8 @@ void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *rovers { case 1: // Trigger Linedef Exec (Pushable Objects) break; - case 2: // Linedef executor requires all players present+doesn't require touching floor - case 3: // Linedef executor requires all players present + case 2: // Linedef executor requires all players present+doesn't require touching floor // Trigger Linedef Exec (Anywhere, All Players) + case 3: // Linedef executor requires all players present // Trigger Linedef Exec (Floor Touch, All Players) /// \todo check continues for proper splitscreen support? for (i = 0; i < MAXPLAYERS; i++) if (playeringame[i] && !players[i].bot && players[i].mo && (gametype != GT_COOP || players[i].lives > 0)) @@ -3684,16 +3743,16 @@ void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *rovers } } /* FALLTHRU */ - case 4: // Linedef executor that doesn't require touching floor - case 5: // Linedef executor - case 6: // Linedef executor (7 Emeralds) - case 7: // Linedef executor (NiGHTS Mare) + case 4: // Linedef executor that doesn't require touching floor // Trigger Linedef Exec (Anywhere in Sector) + case 5: // Linedef executor // Trigger Linedef Exec (Floor Touch) + case 6: // Linedef executor (7 Emeralds) // unused + case 7: // SRB2kart: Linedef executor (Race Lap) if (!player->bot) P_LinedefExecute(sector->tag, player->mo, sector); break; - case 8: // Tells pushable things to check FOFs + case 8: // Tells pushable things to check FOFs // Check for Linedef Executor on FOFs break; - case 9: // Egg trap capsule + case 9: // Egg trap capsule // unused { thinker_t *th; mobj_t *mo2; @@ -3733,12 +3792,12 @@ void P_ProcessSpecialSector(player_t *player, sector_t *sector, sector_t *rovers P_DoPlayerExit(&players[i]); break; } - case 10: // Special Stage Time/Rings + case 10: // Special Stage Time/Rings // unused case 11: // Custom Gravity break; - case 12: // Lua sector special + case 12: // SRB2kart: Invert Encore Remap break; - case 15: // Invert Encore Remap + case 15: // no idea but keep it dont want anything to break break; } DoneSection2: diff --git a/src/p_tick.c b/src/p_tick.c index 38900db9f..6bad0f856 100644 --- a/src/p_tick.c +++ b/src/p_tick.c @@ -662,7 +662,10 @@ void P_Ticker(boolean run) ps_checkposition_calls.value.i = 0; #ifdef HAVE_BLUA + PS_START_TIMING(ps_lua_prethinkframe_time); LUAh_PreThinkFrame(); + PS_STOP_TIMING(ps_lua_prethinkframe_time); + #endif PS_START_TIMING(ps_playerthink_time); @@ -772,8 +775,6 @@ void P_Ticker(boolean run) quake.x = M_RandomRange(-ir,ir); quake.y = M_RandomRange(-ir,ir); quake.z = M_RandomRange(-ir,ir); - if (cv_windowquake.value) - I_CursedWindowMovement(FixedInt(quake.x), FixedInt(quake.y)); ir >>= 2; ir = M_RandomRange(-ir,ir); if (ir < 0) @@ -825,7 +826,11 @@ void P_Ticker(boolean run) D_MapChange(gamemap, gametype, encoremode, true, 0, false, false); #ifdef HAVE_BLUA + + PS_START_TIMING(ps_lua_postthinkframe_time); LUAh_PostThinkFrame(); + PS_STOP_TIMING(ps_lua_postthinkframe_time); + #endif } @@ -920,6 +925,8 @@ void P_PreTicker(INT32 frames) // Run shield positioning //P_RunShields(); P_RunOverlays(); + + P_RunShadows(); P_UpdateSpecials(); P_RespawnSpecials(); diff --git a/src/p_user.c b/src/p_user.c index 9a660b70e..e759aba4d 100644 --- a/src/p_user.c +++ b/src/p_user.c @@ -1281,13 +1281,17 @@ void P_RestoreMusic(player_t *player) if (wantedmus == 2 && cv_growmusic.value) { S_ChangeMusicInternal("kgrow", true); - S_SetRestoreMusicFadeInCvar(&cv_growmusicfade); + + if (cv_birdmusic.value) + S_SetRestoreMusicFadeInCvar(&cv_growmusicfade); } // Item - Invincibility else if (wantedmus == 1 && cv_supermusic.value) { S_ChangeMusicInternal("kinvnc", true); - S_SetRestoreMusicFadeInCvar(&cv_invincmusicfade); + + if (cv_birdmusic.value) + S_SetRestoreMusicFadeInCvar(&cv_invincmusicfade); } else { @@ -1297,14 +1301,20 @@ void P_RestoreMusic(player_t *player) if (G_RaceGametype() && player->laps >= (UINT8)(cv_numlaps.value - 1)) S_SpeedMusic(1.2f); #endif - if (mapmusresume && cv_resume.value) - position = mapmusresume; - else - position = mapmusposition; + if (cv_birdmusic.value) + { + if (mapmusresume && cv_resume.value) + position = mapmusresume; + else + position = mapmusposition; - S_ChangeMusicEx(mapmusname, mapmusflags, true, position, 0, - S_GetRestoreMusicFadeIn()); - S_ClearRestoreMusicFadeInCvar(); + S_ChangeMusicEx(mapmusname, mapmusflags, true, position, 0, + S_GetRestoreMusicFadeIn()); + S_ClearRestoreMusicFadeInCvar(); + } + else + S_ChangeMusicEx(mapmusname, mapmusflags, true, mapmusposition, 0, 0); + mapmusresume = 0; } } @@ -1687,11 +1697,15 @@ mobj_t *P_SpawnGhostMobj(mobj_t *mobj) else ghost->angle = mobj->angle; + ghost->pitch = mobj->pitch; + ghost->roll = mobj->roll; + ghost->sprite = mobj->sprite; ghost->frame = mobj->frame; ghost->tics = -1; ghost->frame &= ~FF_TRANSMASK; ghost->frame |= tr_trans50<slopepitch = mobj->slopepitch; ghost->sloperoll = mobj->sloperoll; ghost->fuse = ghost->info->damage; @@ -1714,6 +1728,10 @@ mobj_t *P_SpawnGhostMobj(mobj_t *mobj) ghost->old_y = mobj->old_y2; ghost->old_z = mobj->old_z2; ghost->old_angle = (mobj->player ? mobj->player->old_frameangle2 : mobj->old_angle2); + ghost->old_pitch = mobj->old_pitch2; + ghost->old_roll = mobj->old_roll2; + ghost->old_sloperoll = mobj->old_sloperoll2; + ghost->old_slopepitch = mobj->old_slopepitch2; return ghost; } @@ -7159,7 +7177,6 @@ consvar_t cv_quaketilt = {"quaketilt", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, consvar_t cv_tiltsmoothing = {"tiltsmoothing", "32", CV_SAVE, CV_Natural, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_actionmovie = {"actionmovie", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_windowquake = {"windowquake", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; fixed_t t_cam_dist = -42; fixed_t t_cam_height = -42; @@ -8063,7 +8080,7 @@ boolean P_SpectatorJoinGame(player_t *player) // Pressing fire assigns you to a team that needs players if allowed. // Partial code reproduction from p_tick.c autobalance code. else if (G_GametypeHasTeams()) - { + { INT32 changeto = 0; INT32 z, numplayersred = 0, numplayersblue = 0; @@ -8099,6 +8116,10 @@ boolean P_SpectatorJoinGame(player_t *player) player->kartstuff[k_spectatewait] = 0; player->ctfteam = changeto; player->playerstate = PST_REBORN; + + //center camera if its not already + if ((P_IsLocalPlayer(player)) && localaiming[0] != 0) + localaiming[0] = 0; //Reset away view if (P_IsLocalPlayer(player) && displayplayers[0] != consoleplayer) @@ -8113,7 +8134,7 @@ boolean P_SpectatorJoinGame(player_t *player) } // Joining in game from firing. else - { + { if (player->mo) { P_RemoveMobj(player->mo); @@ -8124,6 +8145,10 @@ boolean P_SpectatorJoinGame(player_t *player) player->kartstuff[k_spectatewait] = 0; player->playerstate = PST_REBORN; + //center camera if its not already + if ((P_IsLocalPlayer(player)) && localaiming[0] != 0) + localaiming[0] = 0; + //Reset away view if (P_IsLocalPlayer(player) && displayplayers[0] != consoleplayer) displayplayers[0] = consoleplayer; diff --git a/src/r_data.c b/src/r_data.c index 4010aae0b..7c6697298 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -28,6 +28,7 @@ #ifdef HWRENDER #include "hardware/hw_main.h" +#include "hardware/hw_glob.h" // HWR_ClearLightTables #endif #ifdef _WIN32 @@ -39,11 +40,7 @@ #endif // Not sure if this is necessary, but it was in w_wad.c, so I'm putting it here too -Shadow Hog -#ifdef _WIN32_WCE -#define AVOID_ERRNO -#else #include -#endif // // Texture definition. @@ -1143,8 +1140,9 @@ void R_ClearColormaps(void) memset(extra_colormaps, 0, sizeof (extra_colormaps)); #ifdef HWRENDER - HWR_ClearLightTableCache(); -#endif + if (rendermode == render_opengl) + HWR_ClearLightTables(); +#endif } /*INT32 R_ColormapNumForName(char *name) @@ -1325,7 +1323,7 @@ INT32 R_CreateColormap(char *p1, char *p2, char *p3) extra_colormaps[mapnum].fadeend = (UINT16)fadeend; extra_colormaps[mapnum].fog = fog; - if (rendermode == render_soft || rendermode == render_opengl) + if (rendermode != render_none) { double r, g, b, cbrightness; int p; @@ -1416,16 +1414,20 @@ INT32 R_CreateColormap(char *p1, char *p2, char *p3) // Thanks to quake2 source! // utils3/qdata/images.c -UINT8 NearestColor(UINT8 r, UINT8 g, UINT8 b) +UINT8 NearestPaletteColor(UINT8 r, UINT8 g, UINT8 b, RGBA_t *palette) { int dr, dg, db; int distortion, bestdistortion = 256 * 256 * 4, bestcolor = 0, i; + // Use local palette if none specified + if (palette == NULL) + palette = pLocalPalette; + for (i = 0; i < 256; i++) { - dr = r - pLocalPalette[i].s.red; - dg = g - pLocalPalette[i].s.green; - db = b - pLocalPalette[i].s.blue; + dr = r - palette[i].s.red; + dg = g - palette[i].s.green; + db = b - palette[i].s.blue; distortion = dr*dr + dg*dg + db*db; if (distortion < bestdistortion) { diff --git a/src/r_data.h b/src/r_data.h index 6a8806988..ec1146322 100644 --- a/src/r_data.h +++ b/src/r_data.h @@ -100,7 +100,8 @@ void R_MakeInvertmap(void); #endif const char *R_ColormapNameForNum(INT32 num); -UINT8 NearestColor(UINT8 r, UINT8 g, UINT8 b); +UINT8 NearestPaletteColor(UINT8 r, UINT8 g, UINT8 b, RGBA_t *palette); +#define NearestColor(r, g, b) NearestPaletteColor(r, g, b, NULL) extern INT32 numtextures; diff --git a/src/r_defs.h b/src/r_defs.h index fa978ced2..085d25e0b 100644 --- a/src/r_defs.h +++ b/src/r_defs.h @@ -63,7 +63,6 @@ typedef struct INT32 fadergba; // The colour the colourmaps fade to lighttable_t *colormap; - #ifdef HWRENDER // The id of the hardware lighttable. Zero means it does not exist yet. @@ -407,6 +406,8 @@ typedef enum ST_NEGATIVE } slopetype_t; +#define HORIZONSPECIAL 41 + typedef struct line_s { // Vertices, from v1 to v2. diff --git a/src/r_draw.c b/src/r_draw.c index ae30df6cc..4e4ffbe29 100644 --- a/src/r_draw.c +++ b/src/r_draw.c @@ -110,11 +110,12 @@ INT32 ds_y, ds_x1, ds_x2; lighttable_t *ds_colormap; fixed_t ds_xfrac, ds_yfrac, ds_xstep, ds_ystep; -UINT8 *ds_source; // start of a 64*64 tile image +UINT8 *ds_source; // points to the start of a flat UINT8 *ds_transmap; // one of the translucency tables -pslope_t *ds_slope; // Current slope being used -floatv3_t ds_su, ds_sv, ds_sz; // Vectors for... stuff? +// Vectors for Software's tilted slope drawers +floatv3_t *ds_su, *ds_sv, *ds_sz; +floatv3_t *ds_sup, *ds_svp, *ds_szp; float focallengthf, zeroheight; /** \brief Variable flat sizes @@ -579,6 +580,33 @@ UINT8* R_GetLocalTranslationColormap(skin_t *skin, skin_t *localskin, skincolors return RGetTranslationColormap(( skin - skins ), color, flags, false); } +patch_t* R_GetSkinFaceRank(player_t* ply) +{ + if (ply->skinlocal && ply->localskin) + return localfacerankprefix[ply->localskin - 1]; + else if (ply->localskin) + return facerankprefix[ply->localskin - 1]; + return facerankprefix[ply->skin]; +} + +patch_t* R_GetSkinFaceWant(player_t* ply) +{ + if (ply->skinlocal && ply->localskin) + return localfacewantprefix[ply->localskin - 1]; + else if (ply->localskin) + return facewantprefix[ply->localskin - 1]; + return facewantprefix[ply->skin]; +} + +patch_t* R_GetSkinFaceMini(player_t* ply) +{ + if (ply->skinlocal && ply->localskin) + return localfacemmapprefix[ply->localskin - 1]; + else if (ply->localskin) + return facemmapprefix[ply->localskin - 1]; + return facemmapprefix[ply->skin]; +} + /** \brief Flushes cache of translation colormaps. Flushes cache of translation colormaps, but doesn't actually free the diff --git a/src/r_draw.h b/src/r_draw.h index b4e3fb651..58775fe1d 100644 --- a/src/r_draw.h +++ b/src/r_draw.h @@ -60,6 +60,7 @@ extern INT32 dc_texheight; extern INT32 ds_y, ds_x1, ds_x2; extern lighttable_t *ds_colormap; extern fixed_t ds_xfrac, ds_yfrac, ds_xstep, ds_ystep; +extern INT32 ds_waterofs, ds_bgofs; extern UINT8 *ds_source; // start of a 64*64 tile image extern UINT8 *ds_transmap; @@ -69,8 +70,9 @@ typedef struct { float x, y, z; } floatv3_t; -extern pslope_t *ds_slope; // Current slope being used -extern floatv3_t ds_su, ds_sv, ds_sz; // Vectors for... stuff? +// Vectors for Software's tilted slope drawers +extern floatv3_t *ds_su, *ds_sv, *ds_sz; +extern floatv3_t *ds_sup, *ds_svp, *ds_szp; extern float focallengthf, zeroheight; // Variable flat sizes @@ -117,6 +119,9 @@ extern lumpnum_t viewborderlump[8]; void R_InitTranslationTables(void); UINT8* R_GetTranslationColormap(INT32 skinnum, skincolors_t color, UINT8 flags); UINT8* R_GetLocalTranslationColormap(skin_t *skin, skin_t *localskin, skincolors_t color, UINT8 flags, boolean local); +patch_t* R_GetSkinFaceRank(player_t* ply); +patch_t* R_GetSkinFaceWant(player_t* ply); +patch_t* R_GetSkinFaceMini(player_t* ply); void R_FlushTranslationColormapCache(void); UINT8 R_GetColorByName(const char *name); @@ -150,10 +155,14 @@ void R_DrawSpan_8(void); void R_CalcTiltedLighting(fixed_t start, fixed_t end); void R_DrawTiltedSpan_8(void); void R_DrawTiltedTranslucentSpan_8(void); +#ifndef NOWATER +void R_DrawTiltedTranslucentWaterSpan_8(void); +#endif void R_DrawTiltedSplat_8(void); void R_DrawSplat_8(void); void R_DrawTranslucentSplat_8(void); void R_DrawTranslucentSpan_8(void); +void R_DrawTranslucentWaterSpan_8(void); void R_Draw2sMultiPatchColumn_8(void); void R_Draw2sMultiPatchTranslucentColumn_8(void); void R_DrawFogSpan_8(void); diff --git a/src/r_draw8.c b/src/r_draw8.c index 7f1c0763c..93a0796a3 100644 --- a/src/r_draw8.c +++ b/src/r_draw8.c @@ -542,16 +542,19 @@ void R_DrawTranslatedColumn_8(void) */ void R_DrawSpan_8 (void) { - UINT32 xposition; - UINT32 yposition; - UINT32 xstep, ystep; + fixed_t xposition; + fixed_t yposition; + fixed_t xstep, ystep; UINT8 *source; UINT8 *colormap; UINT8 *dest; const UINT8 *deststop = screens[0] + vid.rowbytes * vid.height; - size_t count; + size_t count = (ds_x2 - ds_x1 + 1); + + xposition = ds_xfrac; yposition = ds_yfrac; + xstep = ds_xstep; ystep = ds_ystep; // SoM: we only need 6 bits for the integer part (0 thru 63) so the rest // can be used for the fraction part. This allows calculation of the memory address in the @@ -560,13 +563,12 @@ void R_DrawSpan_8 (void) // bit per power of two (obviously) // Ok, because I was able to eliminate the variable spot below, this function is now FASTER // than the original span renderer. Whodathunkit? - xposition = ds_xfrac << nflatshiftup; yposition = ds_yfrac << nflatshiftup; - xstep = ds_xstep << nflatshiftup; ystep = ds_ystep << nflatshiftup; + xposition <<= nflatshiftup; yposition <<= nflatshiftup; + xstep <<= nflatshiftup; ystep <<= nflatshiftup; source = ds_source; colormap = ds_colormap; dest = ylookup[ds_y] + columnofs[ds_x1]; - count = ds_x2 - ds_x1 + 1; if (dest+8 > deststop) return; @@ -576,35 +578,35 @@ void R_DrawSpan_8 (void) // SoM: Why didn't I see this earlier? the spot variable is a waste now because we don't // have the uber complicated math to calculate it now, so that was a memory write we didn't // need! - dest[0] = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + dest[0] = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; - dest[1] = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + dest[1] = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; - dest[2] = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + dest[2] = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; - dest[3] = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + dest[3] = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; - dest[4] = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + dest[4] = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; - dest[5] = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + dest[5] = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; - dest[6] = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + dest[6] = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; - dest[7] = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + dest[7] = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; @@ -613,7 +615,7 @@ void R_DrawSpan_8 (void) } while (count-- && dest <= deststop) { - *dest++ = colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]]; + *dest++ = colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]]; xposition += xstep; yposition += ystep; } @@ -664,22 +666,22 @@ void R_DrawTiltedSpan_8(void) double endz, endu, endv; UINT32 stepu, stepv; - iz = ds_sz.z + ds_sz.y*(centery-ds_y) + ds_sz.x*(ds_x1-centerx); + iz = ds_szp->z + ds_szp->y*(centery-ds_y) + ds_szp->x*(ds_x1-centerx); // Lighting is simple. It's just linear interpolation from start to end { float planelightfloat = PLANELIGHTFLOAT; float lightstart, lightend; - lightend = (iz + ds_sz.x*width) * planelightfloat; + lightend = (iz + ds_szp->x*width) * planelightfloat; lightstart = iz * planelightfloat; R_CalcTiltedLighting(FLOAT_TO_FIXED(lightstart), FLOAT_TO_FIXED(lightend)); //CONS_Printf("tilted lighting %f to %f (foc %f)\n", lightstart, lightend, focallengthf); } - uz = ds_su.z + ds_su.y*(centery-ds_y) + ds_su.x*(ds_x1-centerx); - vz = ds_sv.z + ds_sv.y*(centery-ds_y) + ds_sv.x*(ds_x1-centerx); + uz = ds_sup->z + ds_sup->y*(centery-ds_y) + ds_sup->x*(ds_x1-centerx); + vz = ds_svp->z + ds_svp->y*(centery-ds_y) + ds_svp->x*(ds_x1-centerx); dest = ylookup[ds_y] + columnofs[ds_x1]; source = ds_source; @@ -698,9 +700,9 @@ void R_DrawTiltedSpan_8(void) *dest = colormap[source[((v >> nflatyshift) & nflatmask) | (u >> nflatxshift)]]; dest++; - iz += ds_sz.x; - uz += ds_su.x; - vz += ds_sv.x; + iz += ds_szp->x; + uz += ds_sup->x; + vz += ds_svp->x; } while (--width >= 0); #else #define SPANSIZE 16 @@ -710,9 +712,9 @@ void R_DrawTiltedSpan_8(void) startu = uz*startz; startv = vz*startz; - izstep = ds_sz.x * SPANSIZE; - uzstep = ds_su.x * SPANSIZE; - vzstep = ds_sv.x * SPANSIZE; + izstep = ds_szp->x * SPANSIZE; + uzstep = ds_sup->x * SPANSIZE; + vzstep = ds_svp->x * SPANSIZE; //x1 = 0; width++; @@ -754,9 +756,9 @@ void R_DrawTiltedSpan_8(void) else { double left = width; - iz += ds_sz.x * left; - uz += ds_su.x * left; - vz += ds_sv.x * left; + iz += ds_szp->x * left; + uz += ds_sup->x * left; + vz += ds_svp->x * left; endz = 1.f/iz; endu = uz*endz; @@ -800,22 +802,22 @@ void R_DrawTiltedTranslucentSpan_8(void) double endz, endu, endv; UINT32 stepu, stepv; - iz = ds_sz.z + ds_sz.y*(centery-ds_y) + ds_sz.x*(ds_x1-centerx); + iz = ds_szp->z + ds_szp->y*(centery-ds_y) + ds_szp->x*(ds_x1-centerx); // Lighting is simple. It's just linear interpolation from start to end { float planelightfloat = PLANELIGHTFLOAT; float lightstart, lightend; - lightend = (iz + ds_sz.x*width) * planelightfloat; + lightend = (iz + ds_szp->x*width) * planelightfloat; lightstart = iz * planelightfloat; R_CalcTiltedLighting(FLOAT_TO_FIXED(lightstart), FLOAT_TO_FIXED(lightend)); //CONS_Printf("tilted lighting %f to %f (foc %f)\n", lightstart, lightend, focallengthf); } - uz = ds_su.z + ds_su.y*(centery-ds_y) + ds_su.x*(ds_x1-centerx); - vz = ds_sv.z + ds_sv.y*(centery-ds_y) + ds_sv.x*(ds_x1-centerx); + uz = ds_sup->z + ds_sup->y*(centery-ds_y) + ds_sup->x*(ds_x1-centerx); + vz = ds_svp->z + ds_svp->y*(centery-ds_y) + ds_svp->x*(ds_x1-centerx); dest = ylookup[ds_y] + columnofs[ds_x1]; source = ds_source; @@ -833,9 +835,9 @@ void R_DrawTiltedTranslucentSpan_8(void) colormap = planezlight[tiltlighting[ds_x1++]] + (ds_colormap - colormaps); *dest = *(ds_transmap + (colormap[source[((v >> nflatyshift) & nflatmask) | (u >> nflatxshift)]] << 8) + *dest); dest++; - iz += ds_sz.x; - uz += ds_su.x; - vz += ds_sv.x; + iz += ds_szp->x; + uz += ds_sup->x; + vz += ds_svp->x; } while (--width >= 0); #else #define SPANSIZE 16 @@ -845,9 +847,9 @@ void R_DrawTiltedTranslucentSpan_8(void) startu = uz*startz; startv = vz*startz; - izstep = ds_sz.x * SPANSIZE; - uzstep = ds_su.x * SPANSIZE; - vzstep = ds_sv.x * SPANSIZE; + izstep = ds_szp->x * SPANSIZE; + uzstep = ds_sup->x * SPANSIZE; + vzstep = ds_svp->x * SPANSIZE; //x1 = 0; width++; @@ -889,9 +891,9 @@ void R_DrawTiltedTranslucentSpan_8(void) else { double left = width; - iz += ds_sz.x * left; - uz += ds_su.x * left; - vz += ds_sv.x * left; + iz += ds_szp->x * left; + uz += ds_sup->x * left; + vz += ds_svp->x * left; endz = 1.f/iz; endu = uz*endz; @@ -915,6 +917,145 @@ void R_DrawTiltedTranslucentSpan_8(void) #endif } +#ifndef NOWATER +/** \brief The R_DrawTiltedTranslucentWaterSpan_8 function + Like DrawTiltedTranslucentSpan, but for water +*/ +void R_DrawTiltedTranslucentWaterSpan_8(void) +{ + // x1, x2 = ds_x1, ds_x2 + int width = ds_x2 - ds_x1; + double iz, uz, vz; + UINT32 u, v; + int i; + + UINT8 *source; + UINT8 *colormap; + UINT8 *dest; + UINT8 *dsrc; + + double startz, startu, startv; + double izstep, uzstep, vzstep; + double endz, endu, endv; + UINT32 stepu, stepv; + + iz = ds_szp->z + ds_szp->y*(centery-ds_y) + ds_szp->x*(ds_x1-centerx); + + // Lighting is simple. It's just linear interpolation from start to end + { + float planelightfloat = BASEVIDWIDTH*BASEVIDWIDTH/vid.width / (zeroheight - FIXED_TO_FLOAT(viewz)) / 21.0f; + float lightstart, lightend; + + lightend = (iz + ds_szp->x*width) * planelightfloat; + lightstart = iz * planelightfloat; + + R_CalcTiltedLighting(FLOAT_TO_FIXED(lightstart), FLOAT_TO_FIXED(lightend)); + //CONS_Printf("tilted lighting %f to %f (foc %f)\n", lightstart, lightend, focallengthf); + } + + uz = ds_sup->z + ds_sup->y*(centery-ds_y) + ds_sup->x*(ds_x1-centerx); + vz = ds_svp->z + ds_svp->y*(centery-ds_y) + ds_svp->x*(ds_x1-centerx); + + dest = ylookup[ds_y] + columnofs[ds_x1]; + dsrc = screens[1] + (ds_y+ds_bgofs)*vid.width + ds_x1; + source = ds_source; + //colormap = ds_colormap; + +#if 0 // The "perfect" reference version of this routine. Pretty slow. + // Use it only to see how things are supposed to look. + i = 0; + do + { + double z = 1.f/iz; + u = (INT64)(uz*z) + viewx; + v = (INT64)(vz*z) + viewy; + + colormap = planezlight[tiltlighting[ds_x1++]] + (ds_colormap - colormaps); + *dest = *(ds_transmap + (colormap[source[((v >> nflatyshift) & nflatmask) | (u >> nflatxshift)]] << 8) + *dsrc++); + dest++; + iz += ds_szp->x; + uz += ds_sup->x; + vz += ds_svp->x; + } while (--width >= 0); +#else +#define SPANSIZE 16 +#define INVSPAN 0.0625f + + startz = 1.f/iz; + startu = uz*startz; + startv = vz*startz; + + izstep = ds_szp->x * SPANSIZE; + uzstep = ds_sup->x * SPANSIZE; + vzstep = ds_svp->x * SPANSIZE; + //x1 = 0; + width++; + + while (width >= SPANSIZE) + { + iz += izstep; + uz += uzstep; + vz += vzstep; + + endz = 1.f/iz; + endu = uz*endz; + endv = vz*endz; + stepu = (INT64)((endu - startu) * INVSPAN); + stepv = (INT64)((endv - startv) * INVSPAN); + u = (INT64)(startu) + viewx; + v = (INT64)(startv) + viewy; + + for (i = SPANSIZE-1; i >= 0; i--) + { + colormap = planezlight[tiltlighting[ds_x1++]] + (ds_colormap - colormaps); + *dest = *(ds_transmap + (colormap[source[((v >> nflatyshift) & nflatmask) | (u >> nflatxshift)]] << 8) + *dsrc++); + dest++; + u += stepu; + v += stepv; + } + startu = endu; + startv = endv; + width -= SPANSIZE; + } + if (width > 0) + { + if (width == 1) + { + u = (INT64)(startu); + v = (INT64)(startv); + colormap = planezlight[tiltlighting[ds_x1++]] + (ds_colormap - colormaps); + *dest = *(ds_transmap + (colormap[source[((v >> nflatyshift) & nflatmask) | (u >> nflatxshift)]] << 8) + *dsrc++); + } + else + { + double left = width; + iz += ds_szp->x * left; + uz += ds_sup->x * left; + vz += ds_svp->x * left; + + endz = 1.f/iz; + endu = uz*endz; + endv = vz*endz; + left = 1.f/left; + stepu = (INT64)((endu - startu) * left); + stepv = (INT64)((endv - startv) * left); + u = (INT64)(startu) + viewx; + v = (INT64)(startv) + viewy; + + for (; width != 0; width--) + { + colormap = planezlight[tiltlighting[ds_x1++]] + (ds_colormap - colormaps); + *dest = *(ds_transmap + (colormap[source[((v >> nflatyshift) & nflatmask) | (u >> nflatxshift)]] << 8) + *dsrc++); + dest++; + u += stepu; + v += stepv; + } + } + } +#endif +} +#endif // NOWATER + void R_DrawTiltedSplat_8(void) { // x1, x2 = ds_x1, ds_x2 @@ -934,22 +1075,22 @@ void R_DrawTiltedSplat_8(void) double endz, endu, endv; UINT32 stepu, stepv; - iz = ds_sz.z + ds_sz.y*(centery-ds_y) + ds_sz.x*(ds_x1-centerx); + iz = ds_szp->z + ds_szp->y*(centery-ds_y) + ds_szp->x*(ds_x1-centerx); // Lighting is simple. It's just linear interpolation from start to end { float planelightfloat = PLANELIGHTFLOAT; float lightstart, lightend; - lightend = (iz + ds_sz.x*width) * planelightfloat; + lightend = (iz + ds_szp->x*width) * planelightfloat; lightstart = iz * planelightfloat; R_CalcTiltedLighting(FLOAT_TO_FIXED(lightstart), FLOAT_TO_FIXED(lightend)); //CONS_Printf("tilted lighting %f to %f (foc %f)\n", lightstart, lightend, focallengthf); } - uz = ds_su.z + ds_su.y*(centery-ds_y) + ds_su.x*(ds_x1-centerx); - vz = ds_sv.z + ds_sv.y*(centery-ds_y) + ds_sv.x*(ds_x1-centerx); + uz = ds_sup->z + ds_sup->y*(centery-ds_y) + ds_sup->x*(ds_x1-centerx); + vz = ds_svp->z + ds_svp->y*(centery-ds_y) + ds_svp->x*(ds_x1-centerx); dest = ylookup[ds_y] + columnofs[ds_x1]; source = ds_source; @@ -970,9 +1111,9 @@ void R_DrawTiltedSplat_8(void) if (val != TRANSPARENTPIXEL) *dest = colormap[val]; dest++; - iz += ds_sz.x; - uz += ds_su.x; - vz += ds_sv.x; + iz += ds_szp->x; + uz += ds_sup->x; + vz += ds_svp->x; } while (--width >= 0); #else #define SPANSIZE 16 @@ -982,9 +1123,9 @@ void R_DrawTiltedSplat_8(void) startu = uz*startz; startv = vz*startz; - izstep = ds_sz.x * SPANSIZE; - uzstep = ds_su.x * SPANSIZE; - vzstep = ds_sv.x * SPANSIZE; + izstep = ds_szp->x * SPANSIZE; + uzstep = ds_sup->x * SPANSIZE; + vzstep = ds_svp->x * SPANSIZE; //x1 = 0; width++; @@ -1030,9 +1171,9 @@ void R_DrawTiltedSplat_8(void) else { double left = width; - iz += ds_sz.x * left; - uz += ds_su.x * left; - vz += ds_sv.x * left; + iz += ds_szp->x * left; + uz += ds_sup->x * left; + vz += ds_svp->x * left; endz = 1.f/iz; endu = uz*endz; @@ -1280,6 +1421,88 @@ void R_DrawTranslucentSplat_8 (void) Draws the actual span with translucent. */ void R_DrawTranslucentSpan_8 (void) +{ + fixed_t xposition; + fixed_t yposition; + fixed_t xstep, ystep; + + UINT8 *source; + UINT8 *colormap; + UINT8 *dest; + const UINT8 *deststop = screens[0] + vid.rowbytes * vid.height; + + size_t count = (ds_x2 - ds_x1 + 1); + UINT32 val; + + xposition = ds_xfrac; yposition = ds_yfrac; + xstep = ds_xstep; ystep = ds_ystep; + + // SoM: we only need 6 bits for the integer part (0 thru 63) so the rest + // can be used for the fraction part. This allows calculation of the memory address in the + // texture with two shifts, an OR and one AND. (see below) + // for texture sizes > 64 the amount of precision we can allow will decrease, but only by one + // bit per power of two (obviously) + // Ok, because I was able to eliminate the variable spot below, this function is now FASTER + // than the original span renderer. Whodathunkit? + xposition <<= nflatshiftup; yposition <<= nflatshiftup; + xstep <<= nflatshiftup; ystep <<= nflatshiftup; + + source = ds_source; + colormap = ds_colormap; + dest = ylookup[ds_y] + columnofs[ds_x1]; + + while (count >= 8) + { + // SoM: Why didn't I see this earlier? the spot variable is a waste now because we don't + // have the uber complicated math to calculate it now, so that was a memory write we didn't + // need! + dest[0] = *(ds_transmap + (colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]] << 8) + dest[0]); + xposition += xstep; + yposition += ystep; + + dest[1] = *(ds_transmap + (colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]] << 8) + dest[1]); + xposition += xstep; + yposition += ystep; + + dest[2] = *(ds_transmap + (colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]] << 8) + dest[2]); + xposition += xstep; + yposition += ystep; + + dest[3] = *(ds_transmap + (colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]] << 8) + dest[3]); + xposition += xstep; + yposition += ystep; + + dest[4] = *(ds_transmap + (colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]] << 8) + dest[4]); + xposition += xstep; + yposition += ystep; + + dest[5] = *(ds_transmap + (colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]] << 8) + dest[5]); + xposition += xstep; + yposition += ystep; + + dest[6] = *(ds_transmap + (colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]] << 8) + dest[6]); + xposition += xstep; + yposition += ystep; + + dest[7] = *(ds_transmap + (colormap[source[(((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift)]] << 8) + dest[7]); + xposition += xstep; + yposition += ystep; + + dest += 8; + count -= 8; + } + while (count-- && dest <= deststop) + { + val = (((UINT32)yposition >> nflatyshift) & nflatmask) | ((UINT32)xposition >> nflatxshift); + *dest = *(ds_transmap + (colormap[source[val]] << 8) + *dest); + dest++; + xposition += xstep; + yposition += ystep; + } +} + +#ifndef NOWATER +void R_DrawTranslucentWaterSpan_8(void) { UINT32 xposition; UINT32 yposition; @@ -1288,6 +1511,7 @@ void R_DrawTranslucentSpan_8 (void) UINT8 *source; UINT8 *colormap; UINT8 *dest; + UINT8 *dsrc; size_t count; @@ -1298,12 +1522,13 @@ void R_DrawTranslucentSpan_8 (void) // bit per power of two (obviously) // Ok, because I was able to eliminate the variable spot below, this function is now FASTER // than the original span renderer. Whodathunkit? - xposition = ds_xfrac << nflatshiftup; yposition = ds_yfrac << nflatshiftup; + xposition = ds_xfrac << nflatshiftup; yposition = (ds_yfrac + ds_waterofs) << nflatshiftup; xstep = ds_xstep << nflatshiftup; ystep = ds_ystep << nflatshiftup; source = ds_source; colormap = ds_colormap; dest = ylookup[ds_y] + columnofs[ds_x1]; + dsrc = screens[1] + (ds_y+ds_bgofs)*vid.width + ds_x1; count = ds_x2 - ds_x1 + 1; while (count >= 8) @@ -1311,35 +1536,35 @@ void R_DrawTranslucentSpan_8 (void) // SoM: Why didn't I see this earlier? the spot variable is a waste now because we don't // have the uber complicated math to calculate it now, so that was a memory write we didn't // need! - dest[0] = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + dest[0]); + dest[0] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; - dest[1] = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + dest[1]); + dest[1] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; - dest[2] = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + dest[2]); + dest[2] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; - dest[3] = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + dest[3]); + dest[3] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; - dest[4] = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + dest[4]); + dest[4] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; - dest[5] = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + dest[5]); + dest[5] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; - dest[6] = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + dest[6]); + dest[6] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; - dest[7] = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + dest[7]); + dest[7] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; @@ -1348,12 +1573,12 @@ void R_DrawTranslucentSpan_8 (void) } while (count--) { - *dest = *(ds_transmap + (colormap[source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)]] << 8) + *dest); - dest++; + *dest++ = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; xposition += xstep; yposition += ystep; } } +#endif /** \brief The R_DrawFogSpan_8 function Draws the actual span with fogging. diff --git a/src/r_fps.c b/src/r_fps.c index 8aca51646..2ef5a68ba 100644 --- a/src/r_fps.c +++ b/src/r_fps.c @@ -282,6 +282,10 @@ void R_InterpolateMobjState(mobj_t *mobj, fixed_t frac, interpmobjstate_t *out) out->scale = mobj->scale; out->subsector = mobj->subsector; out->angle = mobj->player ? mobj->player->frameangle : mobj->angle; + out->pitch = mobj->pitch; + out->roll = mobj->roll; + out->slopepitch = mobj->slopepitch; + out->sloperoll = mobj->sloperoll; out->spritexscale = mobj->spritexscale; out->spriteyscale = mobj->spriteyscale; out->spritexoffset = mobj->spritexoffset; @@ -313,6 +317,14 @@ void R_InterpolateMobjState(mobj_t *mobj, fixed_t frac, interpmobjstate_t *out) { out->angle = mobj->resetinterp ? mobj->angle : R_LerpAngle(mobj->old_angle, mobj->angle, frac); } + + // pitch roll stuff + out->pitch = mobj->resetinterp ? mobj->pitch : R_LerpAngle(mobj->old_pitch, mobj->pitch, frac); + out->roll = mobj->resetinterp ? mobj->roll : R_LerpAngle(mobj->old_roll, mobj->roll, frac); + + // and the slope stuff + out->slopepitch = mobj->resetinterp ? mobj->slopepitch : R_LerpAngle(mobj->old_slopepitch, mobj->slopepitch, frac); + out->sloperoll = mobj->resetinterp ? mobj->sloperoll : R_LerpAngle(mobj->old_sloperoll, mobj->sloperoll, frac); } void R_InterpolatePrecipMobjState(precipmobj_t *mobj, fixed_t frac, interpmobjstate_t *out) @@ -755,10 +767,27 @@ void R_ResetMobjInterpolationState(mobj_t *mobj) mobj->old_z2 = mobj->old_z; mobj->old_angle2 = mobj->old_angle; mobj->old_scale2 = mobj->old_scale; + + // rotation humor + mobj->old_pitch2 = mobj->old_pitch; + mobj->old_roll2 = mobj->old_roll; + mobj->old_slopepitch2 = mobj->old_slopepitch; + mobj->old_sloperoll2 = mobj->old_sloperoll; + mobj->old_x = mobj->x; mobj->old_y = mobj->y; mobj->old_z = mobj->z; mobj->old_angle = mobj->angle; + + // rotation humor, again + + // pitch and roll first + mobj->old_pitch = mobj->pitch; + mobj->old_roll = mobj->roll; + + mobj->old_slopepitch = mobj->slopepitch; + mobj->old_sloperoll = mobj->sloperoll; + mobj->old_scale = mobj->scale; mobj->old_spritexscale = mobj->spritexscale; mobj->old_spriteyscale = mobj->spriteyscale; diff --git a/src/r_fps.h b/src/r_fps.h index 520843fd2..deb0c8788 100644 --- a/src/r_fps.h +++ b/src/r_fps.h @@ -65,6 +65,8 @@ typedef struct { fixed_t spriteyscale; fixed_t spritexoffset; fixed_t spriteyoffset; + angle_t pitch, roll; + angle_t sloperoll, slopepitch; } interpmobjstate_t; // Level interpolators diff --git a/src/r_main.c b/src/r_main.c index 1d3a6968c..44c388ec8 100644 --- a/src/r_main.c +++ b/src/r_main.c @@ -37,16 +37,6 @@ #include "hardware/hw_main.h" #endif -//profile stuff --------------------------------------------------------- -//#define TIMING -#ifdef TIMING -#include "p5prof.h" -INT64 mycount; -INT64 mytotal = 0; -//unsigned long nombre = 100000; -#endif -//profile stuff --------------------------------------------------------- - // Fineangles in the SCREENWIDTH wide window. #define FIELDOFVIEW 2048 @@ -197,7 +187,8 @@ consvar_t cv_flipcam4 = {"flipcam4", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, consvar_t cv_shadow = {"shadow", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_shadowoffs = {"offsetshadows", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_skybox = {"skybox", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_ffloorclip = {"ffloorclip", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_ffloorclip = {"r_ffloorclip", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_spriteclip = {"r_spriteclip", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_soniccd = {"soniccd", "Off", CV_NETVAR|CV_NOSHOWHELP, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_allowmlook = {"allowmlook", "Yes", CV_NETVAR, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_showhud = {"showhud", "Yes", CV_CALL, CV_YesNo, R_SetViewSize, 0, NULL, NULL, 0, 0, NULL}; @@ -207,6 +198,7 @@ consvar_t cv_translucency = {"translucency", "On", CV_SAVE, CV_OnOff, NULL, 0, N consvar_t cv_drawdist = {"drawdist", "Infinite", CV_SAVE, drawdist_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; //consvar_t cv_drawdist_nights = {"drawdist_nights", "2048", CV_SAVE, drawdist_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_drawdist_precip = {"drawdist_precip", "1024", CV_SAVE, drawdist_precip_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_lessprecip = {"lessweathereffects", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; //consvar_t cv_precipdensity = {"precipdensity", "Moderate", CV_SAVE, precipdensity_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; // cap fov, fov too high tears software apart. @@ -352,7 +344,7 @@ INT32 R_PointOnSide(fixed_t x, fixed_t y, node_t *restrict node) } // killough 5/2/98: reformatted -INT32 R_PointOnSegSide(fixed_t x, fixed_t y, seg_t *restrict line) +INT32 R_PointOnSegSide(fixed_t x, fixed_t y, seg_t *line) { fixed_t lx = line->v1->x; fixed_t ly = line->v1->y; @@ -369,10 +361,9 @@ INT32 R_PointOnSegSide(fixed_t x, fixed_t y, seg_t *restrict line) y -= ly; // Try to quickly decide by looking at sign bits. - // also use a mask to avoid branch prediction - INT32 mask = (ldy ^ ldx ^ x ^ y) >> 31; - return (mask & ((ldy ^ x) < 0)) | // (left is negative) - (~mask & (FixedMul(y, ldx>>FRACBITS) >= FixedMul(ldy>>FRACBITS, x))); + if ((ldy ^ ldx ^ x ^ y) < 0) + return (ldy ^ x) < 0; // (left is negative) + return FixedMul(y, ldx>>FRACBITS) >= FixedMul(ldy>>FRACBITS, x); } // @@ -404,6 +395,7 @@ angle_t R_PointToAngle(fixed_t x, fixed_t y) 0; } +// This version uses 64-bit variables to avoid overflows with large values. angle_t R_PointToAngle64(INT64 x, INT64 y) { return (y -= viewy, (x -= viewx) || y) ? @@ -689,14 +681,8 @@ static inline void R_InitLightTables(void) } } -//#define WOUGHMP_WOUGHMP // I got a fish-eye lens - I'll make a rap video with a couple of friends -// it's kinda laggy sometimes - static struct { angle_t rollangle; // pre-shifted by fineshift -#ifdef WOUGHMP_WOUGHMP - fixed_t fisheye; -#endif fixed_t zoomneeded; INT32 *scrmap; @@ -708,9 +694,6 @@ static struct { boolean use; } viewmorph = { 0, -#ifdef WOUGHMP_WOUGHMP - 0, -#endif FRACUNIT, NULL, @@ -729,39 +712,20 @@ void R_CheckViewMorph(void) fixed_t temp; INT32 end, vx, vy, pos, usedpos; INT32 usedx, usedy, halfwidth = vid.width/2, halfheight = vid.height/2; -#ifdef WOUGHMP_WOUGHMP - float fisheyemap[MAXVIDWIDTH/2 + 1]; -#endif angle_t rollangle = players[displayplayers[0]].viewrollangle; -#ifdef WOUGHMP_WOUGHMP - fixed_t fisheye = cv_cam2_turnmultiplier.value; // temporary test value -#endif rollangle >>= ANGLETOFINESHIFT; rollangle = ((rollangle+2) & ~3) & FINEMASK; // Limit the distinct number of angles to reduce recalcs from angles changing a lot. -#ifdef WOUGHMP_WOUGHMP - fisheye &= ~0x7FF; // Same -#endif if (rollangle == viewmorph.rollangle && -#ifdef WOUGHMP_WOUGHMP - fisheye == viewmorph.fisheye && -#endif viewmorph.scrmapsize == vid.width*vid.height) return; // No change viewmorph.rollangle = rollangle; -#ifdef WOUGHMP_WOUGHMP - viewmorph.fisheye = fisheye; -#endif - if (viewmorph.rollangle == 0 -#ifdef WOUGHMP_WOUGHMP - && viewmorph.fisheye == 0 -#endif - ) + if (viewmorph.rollangle == 0) { viewmorph.use = false; viewmorph.x1 = 0; @@ -789,22 +753,6 @@ void R_CheckViewMorph(void) x1 = (vid.width*fabsf(rollcos) + vid.height*fabsf(rollsin)) / vid.width; y1 = (vid.height*fabsf(rollcos) + vid.width*fabsf(rollsin)) / vid.height; -#ifdef WOUGHMP_WOUGHMP - if (fisheye) - { - float f = FIXED_TO_FLOAT(fisheye); - for (vx = 0; vx <= halfwidth; vx++) - fisheyemap[vx] = 1.0f / cos(atan(vx * f / halfwidth)); - - f = cos(atan(f)); - if (f < 1.0f) - { - x1 /= f; - y1 /= f; - } - } -#endif - temp = max(x1, y1)*FRACUNIT; if (temp < FRACUNIT) temp = FRACUNIT; @@ -832,11 +780,6 @@ void R_CheckViewMorph(void) x1 = -(halfwidth * rollcos - halfheight * rollsin); y1 = -(halfheight * rollcos + halfwidth * rollsin); -#ifdef WOUGHMP_WOUGHMP - if (fisheye) - viewmorph.x1 = (INT32)(halfwidth - (halfwidth * fabsf(rollcos) + halfheight * fabsf(rollsin)) * fisheyemap[halfwidth]); - else -#endif viewmorph.x1 = (INT32)(halfwidth - (halfwidth * fabsf(rollcos) + halfheight * fabsf(rollsin))); //CONS_Printf("saving %d cols\n", viewmorph.x1); @@ -883,35 +826,6 @@ void R_CheckViewMorph(void) //CONS_Printf("Top left corner is %f %f\n", x1, y1); -#ifdef WOUGHMP_WOUGHMP - if (fisheye) - { - for (vy = 0; vy < halfheight; vy++) - { - x2 = x1; - y2 = y1; - x1 -= rollsin; - y1 += rollcos; - - for (vx = 0; vx < vid.width; vx++) - { - usedx = halfwidth + x2*fisheyemap[(int) floorf(fabsf(y2*zoomfactor))]; - usedy = halfheight + y2*fisheyemap[(int) floorf(fabsf(x2*zoomfactor))]; - - usedpos = usedx + usedy*vid.width; - - viewmorph.scrmap[pos] = usedpos; - viewmorph.scrmap[end-pos] = end-usedpos; - - x2 += rollcos; - y2 += rollsin; - pos++; - } - } - } - else - { -#endif x1 += halfwidth; y1 += halfheight; @@ -937,9 +851,6 @@ void R_CheckViewMorph(void) pos++; } } -#ifdef WOUGHMP_WOUGHMP - } -#endif viewmorph.use = true; } @@ -1068,6 +979,16 @@ void R_ExecuteSetViewSize(void) dy = FixedMul(abs(dy), fovtan); yslopetab[i] = FixedDiv(centerx*FRACUNIT, dy); } + + if (ds_su) + Z_Free(ds_su); + if (ds_sv) + Z_Free(ds_sv); + if (ds_sz) + Z_Free(ds_sz); + + ds_su = ds_sv = ds_sz = NULL; + ds_sup = ds_svp = ds_szp = NULL; } memset(scalelight, 0xFF, sizeof(scalelight)); @@ -1811,26 +1732,15 @@ void R_RenderPlayerView(player_t *player) // The head node is the last node output. -//profile stuff --------------------------------------------------------- -#ifdef TIMING - mytotal = 0; - ProfZeroTimer(); -#endif ps_numbspcalls.value.i = ps_numpolyobjects.value.i = ps_numdrawnodes.value.i = 0; PS_START_TIMING(ps_bsptime); R_RenderBSPNode((INT32)numnodes - 1); PS_STOP_TIMING(ps_bsptime); - ps_numsprites.value.i = visspritecount; PS_START_TIMING(ps_sw_spritecliptime); R_ClipSprites(); PS_STOP_TIMING(ps_sw_spritecliptime); -#ifdef TIMING - RDMSR(0x10, &mycount); - mytotal += mycount; // 64bit add - - CONS_Debug(DBG_RENDER, "RenderBSPNode: 0x%d %d\n", *((INT32 *)&mytotal + 1), (INT32)mytotal); -#endif -//profile stuff --------------------------------------------------------- + + ps_numsprites.value.i = numvisiblesprites; // PORTAL RENDERING PS_START_TIMING(ps_sw_portaltime); @@ -1916,6 +1826,7 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_drawdist); //CV_RegisterVar(&cv_drawdist_nights); CV_RegisterVar(&cv_drawdist_precip); + CV_RegisterVar(&cv_lessprecip); CV_RegisterVar(&cv_fov); CV_RegisterVar(&cv_chasecam); @@ -1926,6 +1837,7 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_shadowoffs); CV_RegisterVar(&cv_skybox); CV_RegisterVar(&cv_ffloorclip); + CV_RegisterVar(&cv_spriteclip); CV_RegisterVar(&cv_cam_dist); CV_RegisterVar(&cv_cam_still); @@ -1959,13 +1871,14 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_quaketilt); CV_RegisterVar(&cv_tiltsmoothing); CV_RegisterVar(&cv_actionmovie); - CV_RegisterVar(&cv_windowquake); CV_RegisterVar(&cv_driftsparkpulse); CV_RegisterVar(&cv_gravstretch); CV_RegisterVar(&cv_sloperoll); + CV_RegisterVar(&cv_spriteroll); CV_RegisterVar(&cv_sliptideroll); CV_RegisterVar(&cv_sloperolldist); + CV_RegisterVar(&cv_sparkroll); CV_RegisterVar(&cv_showhud); CV_RegisterVar(&cv_translucenthud); diff --git a/src/r_main.h b/src/r_main.h index d6c966857..dadb1c9cf 100644 --- a/src/r_main.h +++ b/src/r_main.h @@ -111,9 +111,9 @@ extern consvar_t cv_homremoval; extern consvar_t cv_chasecam, cv_chasecam2, cv_chasecam3, cv_chasecam4; extern consvar_t cv_flipcam, cv_flipcam2, cv_flipcam3, cv_flipcam4; extern consvar_t cv_shadow, cv_shadowoffs; -extern consvar_t cv_ffloorclip; +extern consvar_t cv_ffloorclip, cv_spriteclip; extern consvar_t cv_translucency; -extern consvar_t /*cv_precipdensity,*/ cv_drawdist, /*cv_drawdist_nights,*/ cv_drawdist_precip; +extern consvar_t /*cv_precipdensity,*/ cv_drawdist, /*cv_drawdist_nights,*/ cv_drawdist_precip, cv_lessprecip; extern consvar_t cv_fov; extern consvar_t cv_skybox; extern consvar_t cv_tailspickup; diff --git a/src/r_patch.c b/src/r_patch.c index 4c5bc0f2d..f69be9de3 100644 --- a/src/r_patch.c +++ b/src/r_patch.c @@ -629,7 +629,7 @@ static void R_ParseSpriteInfo(boolean spr2) strlwr(skinName); Z_Free(sprinfoToken); - skinnum = R_SkinAvailable(skinName); + skinnum = R_AnySkinAvailable(skinName); if (skinnum == -1) I_Error("Error parsing SPRTINFO lump: Unknown skin \"%s\"", skinName); @@ -640,6 +640,22 @@ static void R_ParseSpriteInfo(boolean spr2) { R_ParseSpriteInfoFrame(info); Z_Free(sprinfoToken); + if (spr2) + { + if (!foundskins) + I_Error("Error parsing SPRTINFO lump: No skins specified in this sprite2 definition"); + for (i = 0; i < foundskins; i++) + { + size_t skinnum = skinnumbers[i]; + skin_t *skin; + if (allskins[skinnum].localskin) + skin = &localskins[allskins[skinnum].localnum]; + else + skin = &skins[allskins[skinnum].localnum]; + M_Memcpy(&skin->sprinfo, info, sizeof(spriteinfo_t)); + } + } + else M_Memcpy(&spriteinfo[sprnum], info, sizeof(spriteinfo_t)); } else @@ -694,6 +710,7 @@ void R_ParseSPRTINFOLump(UINT16 wadNum, UINT16 lumpNum) sprinfoToken = M_GetToken(sprinfoText); while (sprinfoToken != NULL) { + CONS_Printf("Attempting to parse le SPRTINFO lump for ya..\n"); if (!stricmp(sprinfoToken, "SPRITE")) R_ParseSpriteInfo(false); else if (!stricmp(sprinfoToken, "SPRITE2")) diff --git a/src/r_plane.c b/src/r_plane.c index 3578bd7b4..f89e10330 100644 --- a/src/r_plane.c +++ b/src/r_plane.c @@ -29,13 +29,6 @@ #include "p_tick.h" #include "r_fps.h" -#ifdef TIMING -#include "p5prof.h" - INT64 mycount; - INT64 mytotal = 0; - UINT32 nombre = 100000; -#endif - // // opening // @@ -163,6 +156,47 @@ void R_PortalRestoreClipValues(INT32 start, INT32 end, INT16 *ceil, INT16 *floor } } +// +// Water ripple effect!! +// Needs the height of the plane, and the vertical position of the span. +// Sets planeripple.xfrac and planeripple.yfrac, added to ds_xfrac and ds_yfrac, if the span is not tilted. +// + +#ifndef NOWATER +INT32 ds_bgofs; +INT32 ds_waterofs; + +struct +{ + INT32 offset; + fixed_t xfrac, yfrac; + boolean active; +} planeripple; + +static void R_CalculatePlaneRipple(visplane_t *plane, INT32 y, fixed_t plheight, boolean calcfrac) +{ + fixed_t distance = FixedMul(plheight, yslope[y]); + const INT32 yay = (planeripple.offset + (distance>>9)) & 8191; + + // ripples da water texture + ds_bgofs = FixedDiv(FINESINE(yay), (1<<12) + (distance>>11))>>FRACBITS; + + if (calcfrac) + { + angle_t angle = (plane->viewangle + plane->plangle)>>ANGLETOFINESHIFT; + angle = (angle + 2048) & 8191; // 90 degrees + planeripple.xfrac = FixedMul(FINECOSINE(angle), (ds_bgofs< 64 the amount of precision we can allow will decrease, but only by one - // bit per power of two (obviously) - // Ok, because I was able to eliminate the variable spot below, this function is now FASTER - // than the original span renderer. Whodathunkit? - xposition = ds_xfrac << nflatshiftup; yposition = (ds_yfrac + waterofs) << nflatshiftup; - xstep = ds_xstep << nflatshiftup; ystep = ds_ystep << nflatshiftup; - - source = ds_source; - colormap = ds_colormap; - dest = ylookup[ds_y] + columnofs[ds_x1]; - dsrc = screens[1] + (ds_y+ds_bgofs)*vid.width + ds_x1; - count = ds_x2 - ds_x1 + 1; - - while (count >= 8) - { - // SoM: Why didn't I see this earlier? the spot variable is a waste now because we don't - // have the uber complicated math to calculate it now, so that was a memory write we didn't - // need! - dest[0] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - - dest[1] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - - dest[2] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - - dest[3] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - - dest[4] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - - dest[5] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - - dest[6] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - - dest[7] = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - - dest += 8; - count -= 8; - } - while (count--) - { - *dest++ = colormap[*(ds_transmap + (source[((yposition >> nflatyshift) & nflatmask) | (xposition >> nflatxshift)] << 8) + *dsrc++)]; - xposition += xstep; - yposition += ystep; - } -} -#endif - void R_MapPlane(INT32 y, INT32 x1, INT32 x2) { angle_t angle, planecos, planesin; - fixed_t distance, span; + fixed_t distance = 0, span; size_t pindex; #ifdef RANGECHECK @@ -273,63 +220,80 @@ void R_MapPlane(INT32 y, INT32 x1, INT32 x2) I_Error("R_MapPlane: %d, %d at %d", x1, x2, y); #endif - // from r_splats's R_RenderFloorSplat - if (x1 >= vid.width) x1 = vid.width - 1; + if (x1 >= vid.width) + x1 = vid.width - 1; - angle = (currentplane->viewangle + currentplane->plangle)>>ANGLETOFINESHIFT; - planecos = FINECOSINE(angle); - planesin = FINESINE(angle); - - if (planeheight != cachedheight[y]) + if (!currentplane->slope) { - cachedheight[y] = planeheight; - distance = cacheddistance[y] = FixedMul(planeheight, yslope[y]); - ds_xstep = cachedxstep[y] = FixedMul(distance, basexscale); - ds_ystep = cachedystep[y] = FixedMul(distance, baseyscale); + angle = (currentplane->viewangle + currentplane->plangle)>>ANGLETOFINESHIFT; + planecos = FINECOSINE(angle); + planesin = FINESINE(angle); - if ((span = abs(centery-y))) + if (planeheight != cachedheight[y]) { - ds_xstep = cachedxstep[y] = FixedMul(planesin, planeheight) / span; - ds_ystep = cachedystep[y] = FixedMul(planecos, planeheight) / span; - } - } - else - { - distance = cacheddistance[y]; - ds_xstep = cachedxstep[y]; - ds_ystep = cachedystep[y]; - } + cachedheight[y] = planeheight; + cacheddistance[y] = distance = FixedMul(planeheight, yslope[y]); + span = abs(centery - y); - ds_xfrac = xoffs + FixedMul(planecos, distance) + (x1 - centerx) * ds_xstep; - ds_yfrac = yoffs - FixedMul(planesin, distance) + (x1 - centerx) * ds_ystep; + if (span) // don't divide by zero + { + ds_xstep = FixedMul(planesin, planeheight) / span; + ds_ystep = FixedMul(planecos, planeheight) / span; + } + else + { + ds_xstep = FixedMul(distance, basexscale); + ds_ystep = FixedMul(distance, baseyscale); + } + + cachedxstep[y] = ds_xstep; + cachedystep[y] = ds_ystep; + } + else + { + distance = cacheddistance[y]; + ds_xstep = cachedxstep[y]; + ds_ystep = cachedystep[y]; + } + + ds_xfrac = xoffs + FixedMul(planecos, distance) + (x1 - centerx) * ds_xstep; + ds_yfrac = yoffs - FixedMul(planesin, distance) + (x1 - centerx) * ds_ystep; + } #ifndef NOWATER - if (itswater) + if (planeripple.active) { - const INT32 yay = (wtofs + (distance>>9) ) & 8191; - // ripples da water texture - ds_bgofs = FixedDiv(FINESINE(yay), (1<<12) + (distance>>11))>>FRACBITS; - angle = (currentplane->viewangle + currentplane->plangle + xtoviewangle[x1])>>ANGLETOFINESHIFT; + // Needed for ds_bgofs + R_CalculatePlaneRipple(currentplane, y, planeheight, (!currentplane->slope)); - angle = (angle + 2048) & 8191; // 90 degrees - ds_xfrac += FixedMul(FINECOSINE(angle), (ds_bgofs<slope) + { + ds_sup = &ds_su[y]; + ds_svp = &ds_sv[y]; + ds_szp = &ds_sz[y]; + } + else + { + ds_xfrac += planeripple.xfrac; + ds_yfrac += planeripple.yfrac; + } - if (y+ds_bgofs>=viewheight) + if ((y + ds_bgofs) >= viewheight) ds_bgofs = viewheight-y-1; - if (y+ds_bgofs<0) + if ((y + ds_bgofs) < 0) ds_bgofs = -y; } #endif - pindex = distance >> LIGHTZSHIFT; - if (pindex >= MAXLIGHTZ) - pindex = MAXLIGHTZ - 1; - if (currentplane->slope) ds_colormap = colormaps; else - ds_colormap = planezlight[pindex]; + { + pindex = distance >> LIGHTZSHIFT; + if (pindex >= MAXLIGHTZ) + pindex = MAXLIGHTZ - 1; + ds_colormap = planezlight[pindex]; + } if (encoremap && !currentplane->noencore) ds_colormap += (256*32); @@ -340,19 +304,7 @@ void R_MapPlane(INT32 y, INT32 x1, INT32 x2) ds_x1 = x1; ds_x2 = x2; - // profile drawer -#ifdef TIMING - ProfZeroTimer(); -#endif - spanfunc(); - -#ifdef TIMING - RDMSR(0x10, &mycount); - mytotal += mycount; // 64bit add - if (!(nombre--)) - I_Error("spanfunc() CPU Spy reports: 0x%d %d\n", *((INT32 *)&mytotal+1), (INT32)mytotal); -#endif } // @@ -404,7 +356,7 @@ static visplane_t *new_visplane(unsigned hash) visplane_t *check = freetail; if (!check) { - check = calloc(1, sizeof (*check)); + check = malloc(sizeof (*check)); if (check == NULL) I_Error("%s: Out of memory", "new_visplane"); // FIXME: ugly } else @@ -696,9 +648,9 @@ void R_DrawPlanes(void) R_DrawSinglePlane(pl); } } + #ifndef NOWATER - waterofs = (leveltime & 1)*16384; - wtofs = ((leveltime-1)*140) + ((rendertimefrac*140) / FRACUNIT); + R_UpdatePlaneRipple(); #endif } @@ -744,6 +696,100 @@ static void R_DrawSkyPlane(visplane_t *pl) } } +// Potentially override other stuff for now cus we're mean. :< But draw a slope plane! +// I copied ZDoom's code and adapted it to SRB2... -Red +void R_CalculateSlopeVectors(pslope_t *slope, fixed_t planeviewx, fixed_t planeviewy, fixed_t planeviewz, fixed_t planexscale, fixed_t planeyscale, fixed_t planexoffset, fixed_t planeyoffset, angle_t planeviewangle, angle_t planeangle, float fudge) +{ + floatv3_t p, m, n; + float ang; + float vx, vy, vz; + float xscale = FIXED_TO_FLOAT(planexscale); + float yscale = FIXED_TO_FLOAT(planeyscale); + // compiler complains when P_GetSlopeZAt is used in FLOAT_TO_FIXED directly + // use this as a temp var to store P_GetSlopeZAt's return value each time + fixed_t temp; + + vx = FIXED_TO_FLOAT(planeviewx+planexoffset); + vy = FIXED_TO_FLOAT(planeviewy-planeyoffset); + vz = FIXED_TO_FLOAT(planeviewz); + + temp = P_GetZAt(slope, planeviewx, planeviewy); + zeroheight = FIXED_TO_FLOAT(temp); + + // p is the texture origin in view space + // Don't add in the offsets at this stage, because doing so can result in + // errors if the flat is rotated. + ang = ANG2RAD(ANGLE_270 - planeviewangle); + p.x = vx * cos(ang) - vy * sin(ang); + p.z = vx * sin(ang) + vy * cos(ang); + temp = P_GetZAt(slope, -planexoffset, planeyoffset); + p.y = FIXED_TO_FLOAT(temp) - vz; + + // m is the v direction vector in view space + ang = ANG2RAD(ANGLE_180 - (planeviewangle + planeangle)); + m.x = yscale * cos(ang); + m.z = yscale * sin(ang); + + // n is the u direction vector in view space + n.x = xscale * sin(ang); + n.z = -xscale * cos(ang); + + ang = ANG2RAD(planeangle); + temp = P_GetZAt(slope, planeviewx + FLOAT_TO_FIXED(yscale * sin(ang)), planeviewy + FLOAT_TO_FIXED(yscale * cos(ang))); + m.y = FIXED_TO_FLOAT(temp) - zeroheight; + temp = P_GetZAt(slope, planeviewx + FLOAT_TO_FIXED(xscale * cos(ang)), planeviewy - FLOAT_TO_FIXED(xscale * sin(ang))); + n.y = FIXED_TO_FLOAT(temp) - zeroheight; + + m.x /= fudge; + m.y /= fudge; + m.z /= fudge; + + n.x *= fudge; + n.y *= fudge; + n.z *= fudge; + + // Eh. I tried making this stuff fixed-point and it exploded on me. Here's a macro for the only floating-point vector function I recall using. +#define CROSS(d, v1, v2) \ +d->x = (v1.y * v2.z) - (v1.z * v2.y);\ +d->y = (v1.z * v2.x) - (v1.x * v2.z);\ +d->z = (v1.x * v2.y) - (v1.y * v2.x) + CROSS(ds_sup, p, m); + CROSS(ds_svp, p, n); + CROSS(ds_szp, m, n); +#undef CROSS + + ds_sup->z *= focallengthf; + ds_svp->z *= focallengthf; + ds_szp->z *= focallengthf; + + // Premultiply the texture vectors with the scale factors +#define SFMULT 65536.f + ds_sup->x *= (SFMULT * (1<y *= (SFMULT * (1<z *= (SFMULT * (1<x *= (SFMULT * (1<y *= (SFMULT * (1<z *= (SFMULT * (1<slope, pl->viewx, pl->viewy, pl->viewz, FRACUNIT, FRACUNIT, xoff, yoff, pl->viewangle, pl->plangle, fudge); +} + + void R_DrawSinglePlane(visplane_t *pl) { INT32 light = 0; @@ -763,7 +809,7 @@ void R_DrawSinglePlane(visplane_t *pl) } #ifndef NOWATER - itswater = false; + planeripple.active = false; #endif spanfunc = basespanfunc; @@ -852,14 +898,13 @@ void R_DrawSinglePlane(visplane_t *pl) else light = (pl->lightlevel >> LIGHTSEGSHIFT); #ifndef NOWATER - if (pl->ffloor->flags & FF_RIPPLE - && !pl->slope - ) + if (pl->ffloor->flags & FF_RIPPLE) { INT32 top, bottom; UINT8 *scr; - itswater = true; + planeripple.active = true; + if (spanfunc == R_DrawTranslucentSpan_8) { spanfunc = R_DrawTranslucentWaterSpan_8; @@ -966,17 +1011,12 @@ void R_DrawSinglePlane(visplane_t *pl) if (light < 0) light = 0; - if (pl->slope) { - // Potentially override other stuff for now cus we're mean. :< But draw a slope plane! - // I copied ZDoom's code and adapted it to SRB2... -fickle - floatv3_t p, m, n; - float ang; - float vx, vy, vz; - // compiler complains when P_GetZAt is used in FLOAT_TO_FIXED directly - // use this as a temp var to store P_GetZAt's return value each time + if (pl->slope) + { + float fudgecanyon = 0; fixed_t temp; // Okay, look, don't ask me why this works, but without this setup there's a disgusting-looking misalignment with the textures. -fickle - const float fudge = ((1<plangle & (ANGLE_90-1)); @@ -1028,74 +1068,31 @@ void R_DrawSinglePlane(visplane_t *pl) yoffs += (pl->slope->o.y + (1 << (31-nflatshiftup))) & ~((1 << (32-nflatshiftup))-1); } - xoffs = (fixed_t)(xoffs*fudge); - yoffs = (fixed_t)(yoffs/fudge); + xoffs = (fixed_t)(xoffs*fudgecanyon); + yoffs = (fixed_t)(yoffs/fudgecanyon); + +#ifndef NOWATER + if (planeripple.active) + { + fixed_t plheight = abs(P_GetZAt(pl->slope, pl->viewx, pl->viewy) - pl->viewz); - vx = FIXED_TO_FLOAT(pl->viewx+xoffs); - vy = FIXED_TO_FLOAT(pl->viewy-yoffs); - vz = FIXED_TO_FLOAT(pl->viewz); + R_PlaneBounds(pl); - temp = P_GetZAt(pl->slope, pl->viewx, pl->viewy); - zeroheight = FIXED_TO_FLOAT(temp); - -#define ANG2RAD(angle) ((float)((angle)*M_PIl)/ANGLE_180) - - // p is the texture origin in view space - // Don't add in the offsets at this stage, because doing so can result in - // errors if the flat is rotated. - ang = ANG2RAD(ANGLE_270 - pl->viewangle); - p.x = vx * cos(ang) - vy * sin(ang); - p.z = vx * sin(ang) + vy * cos(ang); - temp = P_GetZAt(pl->slope, -xoffs, yoffs); - p.y = FIXED_TO_FLOAT(temp) - vz; - - // m is the v direction vector in view space - ang = ANG2RAD(ANGLE_180 - (pl->viewangle + pl->plangle)); - m.x = cos(ang); - m.z = sin(ang); - - // n is the u direction vector in view space - n.x = sin(ang); - n.z = -cos(ang); - - ang = ANG2RAD(pl->plangle); - temp = P_GetZAt(pl->slope, pl->viewx + FLOAT_TO_FIXED(sin(ang)), pl->viewy + FLOAT_TO_FIXED(cos(ang))); - m.y = FIXED_TO_FLOAT(temp) - zeroheight; - temp = P_GetZAt(pl->slope, pl->viewx + FLOAT_TO_FIXED(cos(ang)), pl->viewy - FLOAT_TO_FIXED(sin(ang))); - n.y = FIXED_TO_FLOAT(temp) - zeroheight; - - m.x /= fudge; - m.y /= fudge; - m.z /= fudge; - - n.x *= fudge; - n.y *= fudge; - n.z *= fudge; - - // Eh. I tried making this stuff fixed-point and it exploded on me. Here's a macro for the only floating-point vector function I recall using. -#define CROSS(d, v1, v2) \ - d.x = (v1.y * v2.z) - (v1.z * v2.y);\ - d.y = (v1.z * v2.x) - (v1.x * v2.z);\ - d.z = (v1.x * v2.y) - (v1.y * v2.x) - CROSS(ds_su, p, m); - CROSS(ds_sv, p, n); - CROSS(ds_sz, m, n); -#undef CROSS - - ds_su.z *= focallengthf; - ds_sv.z *= focallengthf; - ds_sz.z *= focallengthf; - - // Premultiply the texture vectors with the scale factors -#define SFMULT 65536.f*(1<high; x < pl->low; x++) + { + R_CalculatePlaneRipple(pl, x, plheight, true); + R_SetSlopePlaneVectors(pl, x, (xoffs + planeripple.xfrac), (yoffs + planeripple.yfrac), fudgecanyon); + } + } + else +#endif + R_SetSlopePlaneVectors(pl, 0, xoffs, yoffs, fudgecanyon); +#ifndef NOWATER + if (spanfunc == R_DrawTranslucentWaterSpan_8) + spanfunc = R_DrawTiltedTranslucentWaterSpan_8; + else +#endif if (spanfunc == R_DrawTranslucentSpan_8) spanfunc = R_DrawTiltedTranslucentSpan_8; else if (spanfunc == splatfunc) diff --git a/src/r_plane.h b/src/r_plane.h index a109aef15..96217b387 100644 --- a/src/r_plane.h +++ b/src/r_plane.h @@ -82,6 +82,7 @@ void R_ClearPlanes(void); void R_MapPlane(INT32 y, INT32 x1, INT32 x2); void R_MakeSpans(INT32 x, INT32 t1, INT32 b1, INT32 t2, INT32 b2); void R_DrawPlanes(void); +void R_CalculateSlopeVectors(pslope_t *slope, fixed_t planeviewx, fixed_t planeviewy, fixed_t planeviewz, fixed_t planexscale, fixed_t planeyscale, fixed_t planexoffset, fixed_t planeyoffset, angle_t planeviewangle, angle_t planeangle, float fudge); visplane_t *R_FindPlane(fixed_t height, INT32 picnum, INT32 lightlevel, fixed_t xoff, fixed_t yoff, angle_t plangle, extracolormap_t *planecolormap, ffloor_t *ffloor , polyobj_t *polyobj diff --git a/src/r_segs.c b/src/r_segs.c index 53f12ecc6..8eb3c9b41 100644 --- a/src/r_segs.c +++ b/src/r_segs.c @@ -690,7 +690,7 @@ static void R_DrawRepeatMaskedColumn(column_t *col) { while (sprtopscreen < sprbotscreen) { R_DrawMaskedColumn(col); - if ((INT64)sprtopscreen + dc_texheight*spryscale > (INT64)INT32_MAX) // prevent overflow + if (sprtopscreen + (INT64)dc_texheight*spryscale > (INT64)INT32_MAX) // prevent overflow sprtopscreen = INT32_MAX; else sprtopscreen += dc_texheight*spryscale; @@ -755,7 +755,7 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) if (pfloor->master->flags & ML_TFERLINE) { - size_t linenum = curline->linedef-backsector->lines[0]; + size_t linenum = min(curline->linedef-backsector->lines[0], pfloor->master->frontsector->linecount); newline = pfloor->master->frontsector->lines[0] + linenum; texnum = R_GetTextureNum(sides[newline->sidenum[0]].midtexture); } @@ -1248,19 +1248,6 @@ static boolean R_FFloorCanClip(visffloor_t *pfloor) #define HEIGHTBITS 12 #define HEIGHTUNIT (1<>FRACBITS; - - //profile stuff --------------------------------------------------------- -#ifdef TIMING - ProfZeroTimer(); -#endif colfunc(); -#ifdef TIMING - RDMSR(0x10,&mycount); - mytotal += mycount; //64bit add - - if (nombre--==0) - I_Error("R_DrawColumn CPU Spy reports: 0x%d %d\n", *((INT32 *)&mytotal+1), - (INT32)mytotal); -#endif - //profile stuff --------------------------------------------------------- // dont draw anything more for this column, since // a midtexture blocks the view @@ -2653,8 +2626,22 @@ void R_StoreWallRange(INT32 start, INT32 stop) { ffloor[i].f_pos >>= 4; ffloor[i].f_pos_slope >>= 4; - ffloor[i].f_frac = (centeryfrac>>4) - FixedMul(ffloor[i].f_pos, rw_scale); - ffloor[i].f_step = ((centeryfrac>>4) - FixedMul(ffloor[i].f_pos_slope, ds_p->scale2) - ffloor[i].f_frac)/(range); + if (linedef->special == 41) // Horizon lines extend FOFs in contact with them too. + { + ffloor[i].f_step = 0; + ffloor[i].f_frac = (centeryfrac>>4); + topfrac++; // Prevent 1px HOM + } + else + { +#ifdef ESLOPE + ffloor[i].f_frac = (centeryfrac>>4) - FixedMul(ffloor[i].f_pos, rw_scale); + ffloor[i].f_step = ((centeryfrac>>4) - FixedMul(ffloor[i].f_pos_slope, ds_p->scale2) - ffloor[i].f_frac)/(range); +#else + ffloor[i].f_step = FixedMul(-rw_scalestep, ffloor[i].f_pos); + ffloor[i].f_frac = (centeryfrac>>4) - FixedMul(ffloor[i].f_pos, rw_scale); +#endif + } } } diff --git a/src/r_things.c b/src/r_things.c index 86588da82..6cc11b49f 100644 --- a/src/r_things.c +++ b/src/r_things.c @@ -143,11 +143,11 @@ static void R_InstallSpriteLump(UINT16 wad, // graphics patch // rotsprite #ifdef ROTSPRITE - for (r = 0; r < 16; r++) - { - sprtemp[frame].rotated[0][r] = NULL; - sprtemp[frame].rotated[1][r] = NULL; - } + for (r = 0; r < 16; r++) + { + sprtemp[frame].rotated[0][r] = NULL; + sprtemp[frame].rotated[1][r] = NULL; + } #endif/*ROTSPRITE*/ @@ -589,7 +589,8 @@ void R_DelSpriteDefs(UINT16 wadnum) // // GAME FUNCTIONS // -UINT32 visspritecount; +UINT32 visspritecount, numvisiblesprites; + static UINT32 clippedvissprites; static vissprite_t *visspritechunks[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {NULL}; @@ -642,9 +643,12 @@ void R_InitSprites(void) // it can be is do before loading config for skin cvar possible value R_InitSkins(); - for (i = 0; i < numwadfiles; i++) + for (i = 0; i < numwadfiles; i++) + { R_AddSkins((UINT16)i, false); - + R_LoadSpriteInfoLumps(i, wadfiles[i]->numlumps); + } + // // check if all sprites have frames // @@ -661,7 +665,7 @@ void R_InitSprites(void) // void R_ClearSprites(void) { - visspritecount = clippedvissprites = 0; + visspritecount = numvisiblesprites = clippedvissprites = 0; } // @@ -940,10 +944,10 @@ static void R_DrawVisSprite(vissprite_t *vis) { vis->scale = FixedMul(vis->scale, this_scale); vis->scalestep = FixedMul(vis->scalestep, this_scale); - vis->xiscale = FixedDiv(vis->xiscale,this_scale); + vis->xiscale = FixedDiv(vis->xiscale, this_scale); vis->isScaled = true; } - dc_texturemid = FixedDiv(dc_texturemid,this_scale); + dc_texturemid = FixedDiv(dc_texturemid, this_scale); } spryscale = vis->scale; @@ -1311,15 +1315,19 @@ static void R_ProjectSprite(mobj_t *thing) size_t rot; UINT8 flip; - /*boolean vflip = (!(thing->eflags & MFE_VERTICALFLIP) != !R_ThingVerticallyFlipped(thing)); + /*boolean vflip = (!(thing->eflags & MFE_VERTICALFLIP) != !R_ThingVerticallyFlipped(thing));*/ + boolean mirrored = thing->mirrored; - boolean hflip = (!R_ThingHorizontallyFlipped(thing) != !mirrored);*/ + boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); INT32 lindex; vissprite_t *vis; + + spritecut_e cut = SC_NONE; angle_t ang = 0; // gcc 4.6 and lower fix + angle_t camang = 0; fixed_t iscale; fixed_t scalestep; // toast '16 fixed_t offset, offset2; @@ -1339,6 +1347,7 @@ static void R_ProjectSprite(mobj_t *thing) patch_t *rotsprite = NULL; INT32 rollangle = 0; angle_t rollsum = 0; + angle_t pitchnroll = 0; angle_t sliptiderollangle = 0; #endif @@ -1393,11 +1402,11 @@ static void R_ProjectSprite(mobj_t *thing) rot = thing->frame&FF_FRAMEMASK; //Fab : 02-08-98: 'skin' override spritedef currently used for skin - if (thing->skin && thing->sprite == SPR_PLAY) + if ((thing->skin || thing->localskin) && thing->sprite == SPR_PLAY) { sprdef = &((skin_t *)( (thing->localskin) ? thing->localskin : thing->skin ))->spritedef; #ifdef ROTSPRITE - sprinfo = &spriteinfo[thing->sprite]; + sprinfo = &((skin_t *)( (thing->localskin) ? thing->localskin : thing->skin ))->sprinfo; #endif if (rot >= sprdef->numframes) @@ -1436,9 +1445,16 @@ static void R_ProjectSprite(mobj_t *thing) I_Error("R_ProjectSprite: sprframes NULL for sprite %d\n", thing->sprite); #endif - if (sprframe->rotate != SRF_SINGLE || papersprite) + if (sprframe->rotate != SRF_SINGLE || papersprite || (cv_sloperoll.value == 2 && cv_spriteroll.value)) { ang = R_PointToAngle (interp.x, interp.y) - interp.angle; + camang = R_PointToAngle (interp.x, interp.y); + } + + if (sprframe->rotate != SRF_SINGLE || papersprite) + { + if (mirrored) + ang = InvAngle(ang); if (papersprite) ang_scale = abs(FINESINE(ang>>ANGLETOFINESHIFT)); } @@ -1468,7 +1484,7 @@ static void R_ProjectSprite(mobj_t *thing) } I_Assert(lump < max_spritelumps); - + if (thing->localskin && ((skin_t *)thing->localskin)->flags & SF_HIRES) this_scale = FixedMul(this_scale, ((skin_t *)thing->localskin)->highresscale); else if (thing->skin && ((skin_t *)thing->skin)->flags & SF_HIRES) @@ -1480,34 +1496,63 @@ static void R_ProjectSprite(mobj_t *thing) spr_topoffset = spritecachedinfo[lump].topoffset; #ifdef ROTSPRITE + pitchnroll = 0; // set this to 0, non-paper sprites will affect this value - if (thing->player) + if (cv_spriteroll.value) { - sliptiderollangle = FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), ((cv_sloperoll.value == 1) ? thing->player->sliproll*(thing->player->sliptidemem) : 0)); - } - else - sliptiderollangle = 0; - - if ((thing->rollangle)||(thing->sloperoll)||sliptiderollangle) - { - if (thing->player) - rollsum = (thing->rollangle) + (thing->sloperoll) + sliptiderollangle; - else - rollsum = (thing->rollangle) + (thing->sloperoll); - - rollangle = R_GetRollAngle(rollsum); - rotsprite = Patch_GetRotatedSprite(sprframe, (thing->frame & FF_FRAMEMASK), rot, flip, false, sprinfo, rollangle); - - if (rotsprite != NULL) + if (papersprite) { - spr_width = rotsprite->width << FRACBITS; - spr_height = rotsprite->height << FRACBITS; - spr_offset = rotsprite->leftoffset << FRACBITS; - spr_topoffset = rotsprite->topoffset << FRACBITS; - spr_topoffset += FEETADJUST; + if (ang >= ANGLE_180) + { + // Makes Software act much more sane like OpenGL + rollangle = InvAngle(thing->rollangle); + } + else + { + rollangle = thing->rollangle; + } + } + else + { + // this is very messy, but it on-the-fly calculates rotations for all the + // pitch and roll variables + pitchnroll = FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), interp.roll) + + FixedMul(FINESINE((ang) >> ANGLETOFINESHIFT), interp.pitch) + + FixedMul(FINECOSINE((camang) >> ANGLETOFINESHIFT), interp.sloperoll) + + FixedMul(FINESINE((camang) >> ANGLETOFINESHIFT), interp.slopepitch); - // flip -> rotate, not rotate -> flip - flip = 0; + rollangle = thing->rollangle; + } + + if ((rollangle) || (pitchnroll) || (thing->player && thing->player->sliproll)) + { + rollsum = pitchnroll; + + if (thing->player) + { + sliptiderollangle = + cv_sliptideroll.value ? thing->player->sliproll * (thing->player->sliptidemem) : 0; + rollsum += thing->rollangle + + FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), sliptiderollangle); + } + else + rollsum += thing->rollangle; + + rollangle = R_GetRollAngle(rollsum); + rotsprite = Patch_GetRotatedSprite( + sprframe, (thing->frame & FF_FRAMEMASK), rot, flip, false, sprinfo, rollangle); + + if (rotsprite != NULL) + { + spr_width = rotsprite->width << FRACBITS; + spr_height = rotsprite->height << FRACBITS; + spr_offset = rotsprite->leftoffset << FRACBITS; + spr_topoffset = rotsprite->topoffset << FRACBITS; + spr_topoffset += FEETADJUST; + + // flip -> rotate, not rotate -> flip + flip = 0; + } } } #endif @@ -1515,6 +1560,7 @@ static void R_ProjectSprite(mobj_t *thing) // calculate edges of the shape spritexscale = interp.spritexscale; spriteyscale = interp.spriteyscale; + if (spritexscale < 1 || spriteyscale < 1) return; @@ -1533,6 +1579,8 @@ static void R_ProjectSprite(mobj_t *thing) spr_offset += interp.spritexoffset * flipoffset; spr_topoffset += interp.spriteyoffset * flipoffset; } + + flip = !flip != !hflip; if (flip) offset = spr_offset - spr_width; @@ -1757,7 +1805,7 @@ static void R_ProjectSprite(mobj_t *thing) //Fab: lumppat is the lump number of the patch to use, this is different // than lumpid for sprites-in-pwad : the graphics are patched #ifdef ROTSPRITE - if (rotsprite != NULL) + if ((rotsprite != NULL) && (cv_spriteroll.value)) vis->patch = rotsprite; else #endif @@ -2193,6 +2241,14 @@ void R_SortVisSprites(void) bestscale = bestdispoffset = INT32_MAX; for (ds = unsorted.next; ds != &unsorted; ds = ds->next) { + // Remove this sprite if it was determined to not be visible + if (ds->cut & SC_NOTVISIBLE) + { + ds->next->prev = ds->prev; + ds->prev->next = ds->next; + continue; + } + if (ds->sortscale < bestscale) { bestscale = ds->sortscale; @@ -2206,12 +2262,15 @@ void R_SortVisSprites(void) best = ds; } } - best->next->prev = best->prev; - best->prev->next = best->next; - best->next = &vsprsortedhead; - best->prev = vsprsortedhead.prev; - vsprsortedhead.prev->next = best; - vsprsortedhead.prev = best; + if (best) + { + best->next->prev = best->prev; + best->prev->next = best->next; + best->next = &vsprsortedhead; + best->prev = vsprsortedhead.prev; + vsprsortedhead.prev->next = best; + vsprsortedhead.prev = best; + } } } @@ -2573,9 +2632,47 @@ static void R_DrawPrecipitationSprite(vissprite_t *spr) R_DrawPrecipitationVisSprite(spr); } -// R_ClipSprites +static boolean R_CheckSpriteVisible(vissprite_t *spr, INT32 x1, INT32 x2) +{ + INT16 sz = spr->sz; + INT16 szt = spr->szt; + + fixed_t texturemid, yscale, scalestep = spr->scalestep; + INT32 height; + + if (scalestep) + { + height = spr->patch->height; + yscale = spr->scale; + scalestep = FixedMul(scalestep, spr->spriteyscale); + + if (spr->thingscale != FRACUNIT) + texturemid = FixedDiv(spr->texturemid, max(spr->thingscale, 1)); + else + texturemid = spr->texturemid; + } + + for (INT32 x = x1; x <= x2; x++) + { + if (scalestep) + { + fixed_t top = centeryfrac - FixedMul(texturemid, yscale); + fixed_t bottom = top + (height * yscale); + szt = (INT16)(top >> FRACBITS); + sz = (INT16)(bottom >> FRACBITS); + yscale += scalestep; + } + + if (spr->cliptop[x] < spr->clipbot[x] && sz > spr->cliptop[x] && szt < spr->clipbot[x]) + return true; + } + + return false; +} + +// R_ClipVisSprite // Clips vissprites without drawing, so that portals can work. -Red -void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2) +static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2) { drawseg_t *ds; INT32 x; @@ -2756,8 +2853,15 @@ void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2) spr->clipbot[x] = (INT16)viewheight; if (spr->cliptop[x] == -2) - //Fab : 26-04-98: was -1, now clips against console bottom - spr->cliptop[x] = (INT16)con_clipviewtop; + spr->cliptop[x] = -1; + } + + // Check if it'll be visible + // Not done for floorsprites. + if (cv_spriteclip.value) + { + if (!R_CheckSpriteVisible(spr, x1, x2)) + spr->cut |= SC_NOTVISIBLE; } } @@ -2826,6 +2930,13 @@ void R_ClipSprites(void) for (; clippedvissprites < visspritecount; clippedvissprites++) { vissprite_t *spr = R_GetVisSprite(clippedvissprites); + + if (cv_spriteclip.value + && (spr->szt > vid.height || spr->sz < 0)) + { + spr->cut |= SC_NOTVISIBLE; + continue; + } if (spr->x2 < cx) { @@ -2844,6 +2955,9 @@ void R_ClipSprites(void) } R_ClipVisSprite(spr, spr->x1, spr->x2); + + if ((spr->cut & SC_NOTVISIBLE) == 0) + numvisiblesprites++; } } @@ -2923,6 +3037,7 @@ UINT8 skinstatscount[9][9] = { UINT8 skinsorted[MAXSKINS]; skin_t localskins[MAXSKINS]; skin_t allskins[MAXSKINS*2]; + // FIXTHIS: don't work because it must be inistilised before the config load //#define SKINVALUES #ifdef SKINVALUES @@ -3015,6 +3130,7 @@ void R_InitSkins(void) skin->spritedef.numframes = sprites[SPR_PLAY].numframes; skin->spritedef.spriteframes = sprites[SPR_PLAY].spriteframes; + skin->sprinfo = spriteinfo[SPR_PLAY]; ST_LoadFaceGraphics(skin->facerank, skin->facewant, skin->facemmap, 0); // Set values for Sonic skin @@ -3539,6 +3655,7 @@ next_token: free(buf2); lump++; // if no sprite defined use spirte just after this one + INT32 sprnum; if (skin->sprite[0] == '\0') { const char *csprname = W_CheckNameForNumPwad(wadnum, lump); @@ -3549,6 +3666,9 @@ next_token: lastlump++; // allocate (or replace) sprite frames, and set spritedef R_AddSingleSpriteDef(csprname, &skin->spritedef, wadnum, lump, lastlump); + + // i feel like generally most skin authors just use PLAY here, so just assume PLAY + sprnum = SPR_PLAY; } else { @@ -3596,6 +3716,8 @@ next_token: R_AddSingleSpriteDef(sprname, &skin->spritedef, wadnum, lstart, lend); } + sprnum = numspritelumps - 1; + // I don't particularly care about skipping to the end of the used frames. // We could be using frames from ANYWHERE in the current WAD file, including // right before us, which is a terrible idea. diff --git a/src/r_things.h b/src/r_things.h index f20e34552..823bad9a8 100644 --- a/src/r_things.h +++ b/src/r_things.h @@ -79,6 +79,7 @@ typedef struct { char name[SKINNAMESIZE+1]; // INT16 descriptive name of the skin spritedef_t spritedef; + spriteinfo_t sprinfo; UINT16 wadnum; char sprite[4]; // Sprite name, if seperated from S_SKIN. skinflags_t flags; @@ -114,7 +115,10 @@ typedef enum SC_NONE = 0, SC_TOP = 1, SC_BOTTOM = 2, - SC_VFLIP = 3 + SC_VFLIP = 3, + SC_NOTVISIBLE = 4, + SC_CUTMASK = SC_TOP|SC_BOTTOM|SC_NOTVISIBLE, + SC_FLAGMASK = ~SC_CUTMASK } spritecut_e; // A vissprite_t is a thing that will be drawn during a refresh, @@ -175,10 +179,9 @@ typedef struct vissprite_s INT32 dispoffset; // copy of info->dispoffset, affects ordering but not drawing } vissprite_t; -extern UINT32 visspritecount; +extern UINT32 visspritecount, numvisiblesprites; void R_ClipSprites(void); -void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2); UINT8 *R_GetSpriteTranslation(vissprite_t *vis); diff --git a/src/s_sound.c b/src/s_sound.c index 30e40c7e0..a2f81f210 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -27,6 +27,8 @@ #include "r_sky.h" // skyflatnum #include "p_local.h" // camera info #include "m_misc.h" // for tunes command +#include "m_cond.h" // for conditionsets +#include "m_menu.h" // bird music stuff #ifdef HAVE_BLUA #include "lua_hook.h" // MusicChange hook @@ -39,7 +41,6 @@ static boolean S_AdjustSoundParams(const mobj_t *listener, const mobj_t *source, INT32 *vol, INT32 *sep, INT32 *pitch, sfxinfo_t *sfxinfo); #endif -CV_PossibleValue_t soundvolume_cons_t[] = {{0, "MIN"}, {31, "MAX"}, {0, NULL}}; static void SetChannelsNum(void); static void Command_Tunes_f(void); static void Command_RestartAudio_f(void); @@ -51,6 +52,7 @@ static void Command_ShowMusicCredit_f(void); static void GameMIDIMusic_OnChange(void); #endif static void GameSounds_OnChange(void); +static void SoundPrecache_OnChange(void); static void GameDigiMusic_OnChange(void); static void BufferSize_OnChange(void); @@ -72,14 +74,16 @@ consvar_t cv_audbuffersize = {"buffersize", "2048", CV_SAVE, audbuffersize_cons_ consvar_t stereoreverse = {"stereoreverse", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // if true, all sounds are loaded at game startup -static consvar_t precachesound = {"precachesound", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t precachesound = {"precachesound", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, SoundPrecache_OnChange, 0, NULL, NULL, 0, 0, NULL}; // actual general (maximum) sound & music volume, saved into the config +static CV_PossibleValue_t soundvolume_cons_t[] = {{0, "MIN"}, {31, "MAX"}, {0, NULL}}; consvar_t cv_soundvolume = {"soundvolume", "18", CV_SAVE, soundvolume_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_digmusicvolume = {"digmusicvolume", "18", CV_SAVE, soundvolume_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; #ifndef NO_MIDI consvar_t cv_midimusicvolume = {"midimusicvolume", "18", CV_SAVE, soundvolume_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; #endif + // number of channels available consvar_t cv_numChannels = {"snd_channels", "64", CV_SAVE|CV_CALL, CV_Unsigned, SetChannelsNum, 0, NULL, NULL, 0, 0, NULL}; @@ -96,6 +100,9 @@ consvar_t cv_gamesounds = {"sounds", "On", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, consvar_t cv_playmusicifunfocused = {"playmusicifunfocused", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_playsoundifunfocused = {"playsoundsifunfocused", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_pausemusic = {"playmusicifpaused", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; + +//bird music stuff static CV_PossibleValue_t music_resync_threshold_cons_t[] = { {0, "MIN"}, {1000, "MAX"}, @@ -106,6 +113,15 @@ consvar_t cv_music_resync_threshold = {"music_resync_threshold", "0", CV_SAVE|CV consvar_t cv_music_resync_powerups_only = {"music_resync_powerups_only", "No", CV_SAVE|CV_CALL, CV_YesNo, I_UpdateSongLagConditions, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_invincmusicfade = {"invincmusicfade", "300", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_growmusicfade = {"growmusicfade", "500", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_respawnfademusicout = {"respawnfademusicout", "1000", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_respawnfademusicback = {"respawnfademusicback", "500", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_resetspecialmusic = {"resetspecialmusic", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_resume = {"resume", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_fading = {"fading", "Off", CV_SAVE|CV_CALL, CV_OnOff, Bird_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_birdmusic = {"birdmusicstuff", "No", CV_SAVE|CV_CALL, CV_YesNo, Bird_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; + #ifdef HAVE_OPENMPT openmpt_module *openmpt_mhandle = NULL; @@ -122,7 +138,6 @@ consvar_t cv_amigafilter = {"amigafilter", "1", CV_SAVE|CV_CALL, amigafilter_con static CV_PossibleValue_t amigatype_cons_t[] = {{0, "auto"}, {1, "a500"}, {2, "a1200"}, {0, NULL}}; consvar_t cv_amigatype = {"amigatype", "0", CV_SAVE|CV_CALL|CV_NOINIT, amigatype_cons_t, AmigaType_OnChange, 0, NULL, NULL, 0, 0, NULL}; #endif - #endif #define S_MAX_VOLUME 127 @@ -270,11 +285,25 @@ void S_RegisterSoundStuff(void) CV_RegisterVar(&cv_gamemidimusic); #endif + //bird music stuff CV_RegisterVar(&cv_playmusicifunfocused); CV_RegisterVar(&cv_playsoundifunfocused); + CV_RegisterVar(&cv_pausemusic); CV_RegisterVar(&cv_music_resync_threshold); CV_RegisterVar(&cv_music_resync_powerups_only); + + CV_RegisterVar(&cv_invincmusicfade); + CV_RegisterVar(&cv_growmusicfade); + + CV_RegisterVar(&cv_respawnfademusicout); + CV_RegisterVar(&cv_respawnfademusicback); + + CV_RegisterVar(&cv_resetspecialmusic); + + CV_RegisterVar(&cv_resume); + CV_RegisterVar(&cv_fading); + CV_RegisterVar(&cv_birdmusic); COM_AddCommand("tunes", Command_Tunes_f); COM_AddCommand("restartaudio", Command_RestartAudio_f); @@ -315,7 +344,6 @@ static void SetChannelsNum(void) channels[i].sfxinfo = 0; } - // Retrieve the lump number of sfx // lumpnum_t S_GetSfxLumpNum(sfxinfo_t *sfx) @@ -350,6 +378,10 @@ boolean S_SoundDisabled(void) ); } +boolean S_PrecacheSound(void) +{ + return (!sound_disabled && (M_CheckParm("-precachesound") || precachesound.value)); +} // Stop all sounds, load level info, THEN start sounds. void S_StopSounds(void) @@ -431,7 +463,6 @@ static INT32 S_ScaleVolumeWithSplitscreen(INT32 volume) ) / FRACUNIT; } - void S_StartSoundAtVolume(const void *origin_p, sfxenum_t sfx_id, INT32 volume) { const mobj_t *origin = (const mobj_t *)origin_p; @@ -1234,15 +1265,19 @@ void S_InitSfxChannels(INT32 sfxVolume) S_sfx[i].lumpnum = LUMPERROR; } - // precache sounds if requested by cmdline, or precachesound var true - if (!sound_disabled && (M_CheckParm("-precachesound") || precachesound.value)) + // Precache sounds if requested + if (S_PrecacheSound()) { // Initialize external data (all sounds) at start, keep static. CONS_Printf(M_GetText("Loading sounds... ")); - for (i = 1; i < NUMSFX; i++) - if (S_sfx[i].name) - S_sfx[i].data = I_GetSfx(&S_sfx[i]); + for (i = 1; i < sfx_freeslot0; i++) + if (S_sfx[i].name && !S_sfx[i].data) + S_sfx[i].data = I_GetSfx(&S_sfx[i]); + + for (i = sfx_freeslot0; i < NUMSFX; i++) + if (S_sfx[i].priority && !S_sfx[i].data) + S_sfx[i].data = I_GetSfx(&S_sfx[i]); CONS_Printf(M_GetText(" pre-cached all sound data\n")); } @@ -1400,6 +1435,8 @@ void S_LoadMusicDefs(UINT16 wadnum) //CONS_Printf("S_LoadMusicDefs: Added song '%s'\n", def->name); } } + + strncpy(def->filename, wadfiles[wadnum]->filename, 256); skip_lump: stoken = strtok(NULL, "\r\n "); @@ -1422,19 +1459,33 @@ skip_lump: free(buf2); return; } - + if (!stricmp(stoken, "usage")) { -#if 0 // Ignore for now STRBUFCPY(def->usage, value); for (value = def->usage; *value; value++) if (*value == '_') *value = ' '; // turn _ into spaces. //CONS_Printf("S_LoadMusicDefs: Set usage to '%s'\n", def->usage); -#endif } else if (!stricmp(stoken, "source")) { STRBUFCPY(def->source, value); for (value = def->source; *value; value++) if (*value == '_') *value = ' '; // turn _ into spaces. //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + } else if (!stricmp(stoken, "title")) { + def->use_info = true; + STRBUFCPY(def->title, value); + for (value = def->title; *value; value++) + if (*value == '_') *value = ' '; // turn _ into spaces. + //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + } else if (!stricmp(stoken, "alttitle")) { + STRBUFCPY(def->alttitle, value); + for (value = def->alttitle; *value; value++) + if (*value == '_') *value = ' '; // turn _ into spaces. + //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + } else if (!stricmp(stoken, "authors")) { + STRBUFCPY(def->authors, value); + for (value = def->authors; *value; value++) + if (*value == '_') *value = ' '; // turn _ into spaces. + //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); } else { CONS_Alert(CONS_WARNING, "MUSICDEF: Invalid field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); } @@ -1461,6 +1512,168 @@ void S_InitMusicDefs(void) S_LoadMusicDefs(i); } +// +// search for music definition in wad +// +static UINT16 W_CheckForMusicInfoInPwad(UINT16 wadid) +{ + UINT16 i; + lumpinfo_t *lump_p; + + lump_p = wadfiles[wadid]->lumpinfo; + for (i = 0; i < wadfiles[wadid]->numlumps; i++, lump_p++) + if (memcmp(lump_p->name, "MUSCINFO", 8) == 0) + return i; + + return INT16_MAX; // not found +} + +void S_LoadMTDefs(UINT16 wadnum) +{ + UINT16 lump; + char *buf; + char *buf2; + char *stoken; + char *value; + size_t size; + musicdef_t *def, *prev; + UINT16 line = 1; // for better error msgs + + lump = W_CheckForMusicInfoInPwad(wadnum); + if (lump == INT16_MAX) + return; + + buf = W_CacheLumpNumPwad(wadnum, lump, PU_CACHE); + size = W_LumpLengthPwad(wadnum, lump); + + // for strtok + buf2 = malloc(size+1); + if (!buf2) + I_Error("S_LoadMTDefs: No more free memory\n"); + M_Memcpy(buf2,buf,size); + buf2[size] = '\0'; + + def = prev = NULL; + + stoken = strtok (buf2, "\r\n "); + // Find music def + while (stoken) + { + /*if ((stoken[0] == '/' && stoken[1] == '/') + || (stoken[0] == '#')) // skip comments + { + stoken = strtok(NULL, "\r\n"); // skip end of line + if (def) + stoken = strtok(NULL, "\r\n= "); + else + stoken = strtok(NULL, "\r\n "); + line++; + } + else*/ if (!stricmp(stoken, "lump")) + { + value = strtok(NULL, "\r\n "); + + if (!value) + { + CONS_Alert(CONS_WARNING, "MUSICDEF: Lump '%s' is missing name. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); + stoken = strtok(NULL, "\r\n"); // skip end of line + goto skip_lump; + } + + // No existing musicdefs + if (!musicdefstart) + { + musicdefstart = Z_Calloc(sizeof (musicdef_t), PU_STATIC, NULL); + STRBUFCPY(musicdefstart->name, value); + strlwr(musicdefstart->name); + def = musicdefstart; + //CONS_Printf("S_LoadMusicDefs: Initialized musicdef w/ song '%s'\n", def->name); + } + else + { + def = musicdefstart; + + // Search if this is a replacement + //CONS_Printf("S_LoadMusicDefs: Searching for song replacement...\n"); + while (def) + { + if (!stricmp(def->name, value)) + { + //CONS_Printf("S_LoadMusicDefs: Found song replacement '%s'\n", def->name); + break; + } + + prev = def; + def = def->next; + } + + // Nothing found, abort. + if (!def) + { + CONS_Alert(CONS_WARNING, "MUSCINFO: Music def for '%s' does not exist. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); + free(buf2); + return; + } + } + +skip_lump: + stoken = strtok(NULL, "\r\n "); + line++; + } + else + { + value = strtok(NULL, "\r\n= "); + + if (!value) + { + CONS_Alert(CONS_WARNING, "MUSCINFO: Field '%s' is missing value. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); + stoken = strtok(NULL, "\r\n"); // skip end of line + goto skip_field; + } + + if (!def) + { + CONS_Alert(CONS_ERROR, "MUSCINFO: No music definition before field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); + free(buf2); + return; + } + + if (!stricmp(stoken, "title")) { + def->use_info = true; + STRBUFCPY(def->title, value); + for (value = def->title; *value; value++) + if (*value == '_') *value = ' '; // turn _ into spaces. + //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + } else if (!stricmp(stoken, "alttitle")) { + STRBUFCPY(def->alttitle, value); + for (value = def->alttitle; *value; value++) + if (*value == '_') *value = ' '; // turn _ into spaces. + //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + } else if (!stricmp(stoken, "authors")) { + STRBUFCPY(def->authors, value); + for (value = def->authors; *value; value++) + if (*value == '_') *value = ' '; // turn _ into spaces. + //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + } else { + CONS_Alert(CONS_WARNING, "MUSCINFO: Invalid field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); + } + +skip_field: + stoken = strtok(NULL, "\r\n= "); + line++; + } + } + + free(buf2); + return; +} + +void S_InitMTDefs(void) +{ + UINT16 i; + for (i = 0; i < numwadfiles; i++) + S_LoadMTDefs(i); +} // // S_FindMusicCredit @@ -1522,6 +1735,41 @@ void S_ShowMusicCredit(void) S_ShowSpecifiedMusicCredit(music_name); } +musicdef_t **soundtestdefs = NULL; +INT32 numsoundtestdefs = 0; + +// +// S_PrepareSoundTest +// +// Prepare sound test. What am I, your butler? +// +boolean S_PrepareSoundTest(void) +{ + musicdef_t *def; + INT32 pos = numsoundtestdefs = 0; + + for (def = musicdefstart; def; def = def->next) + { + numsoundtestdefs++; + } + + if (!numsoundtestdefs) + return false; + + if (soundtestdefs) + Z_Free(soundtestdefs); + + if (!(soundtestdefs = Z_Malloc(numsoundtestdefs*sizeof(musicdef_t *), PU_STATIC, NULL))) + I_Error("S_PrepareSoundTest(): could not allocate soundtestdefs."); + + for (def = musicdefstart; def /*&& i < numsoundtestdefs*/; def = def->next) + { + soundtestdefs[pos++] = def; + } + + return true; +} + /// ------------------------ /// Music Status /// ------------------------ @@ -1699,7 +1947,8 @@ static boolean S_PlayMusic(boolean looping, UINT32 fadeinms) if (S_MusicDisabled()) return false; - I_UpdateSongLagConditions(); + if (cv_birdmusic.value) + I_UpdateSongLagConditions(); if ((!fadeinms && !I_PlaySong(looping)) || (fadeinms && !I_FadeInPlaySong(fadeinms, looping))) @@ -1807,8 +2056,7 @@ void S_ChangeMusicEx(const char *mmusic, UINT16 mflags, boolean looping, UINT32 } } -void -S_ChangeMusicSpecial (const char *mmusic) +void S_ChangeMusicSpecial (const char *mmusic) { if (cv_resetspecialmusic.value) S_ChangeMusic(mmusic, MUSIC_FORCERESET, true); @@ -1823,7 +2071,7 @@ void S_StopMusic(void) || demo.title) // SRB2Kart: Demos don't interrupt title screen music return; - if (strcasecmp(music_name, mapmusname) == 0) + if ((cv_birdmusic.value) && (strcasecmp(music_name, mapmusname) == 0)) mapmusresume = I_GetSongPosition(); if (I_SongPaused()) @@ -1895,14 +2143,12 @@ void S_SetMusicVolume(INT32 digvolume, INT32 seqvolume) } } -void -S_SetRestoreMusicFadeInCvar (consvar_t *cv) +void S_SetRestoreMusicFadeInCvar (consvar_t *cv) { music_refade_cv = cv; } -int -S_GetRestoreMusicFadeIn (void) +int S_GetRestoreMusicFadeIn (void) { if (music_refade_cv && cv_fading.value) return music_refade_cv->value; @@ -1910,15 +2156,13 @@ S_GetRestoreMusicFadeIn (void) return 0; } -void -S_SetMusicUsage (int type) +void S_SetMusicUsage (int type) { music_usage = type; I_UpdateSongLagConditions(); } -int -S_MusicUsage (void) +int S_MusicUsage (void) { return music_usage; } @@ -2126,34 +2370,47 @@ static void Command_ShowMusicCredit_f(void) } } -void GameSounds_OnChange(void) +static void GameSounds_OnChange(void) { if (M_CheckParm("-nosound") || M_CheckParm("-noaudio")) return; - if (sound_disabled) + if (sound_disabled && cv_gamesounds.value) { sound_disabled = false; I_StartupSound(); // will return early if initialised S_InitSfxChannels(cv_soundvolume.value); S_StartSound(NULL, sfx_strpst); } - else + else if (!sound_disabled && !cv_gamesounds.value) { sound_disabled = true; S_StopSounds(); } } +static void SoundPrecache_OnChange(void) +{ + if (S_PrecacheSound()) + { + S_InitSfxChannels(cv_soundvolume.value); + } + else if (!S_PrecacheSound()) + { + S_ClearSfx(); + if (!sound_disabled) + S_InitSfxChannels(cv_soundvolume.value); + } +} -void GameDigiMusic_OnChange(void) +static void GameDigiMusic_OnChange(void) { if (M_CheckParm("-nomusic") || M_CheckParm("-noaudio")) return; else if (M_CheckParm("-nodigmusic")) return; - if (digital_disabled) + if (digital_disabled && cv_gamedigimusic.value) { digital_disabled = false; I_StartupSound(); // will return early if initialised @@ -2164,7 +2421,7 @@ void GameDigiMusic_OnChange(void) else S_ChangeMusicInternal("titles", looptitle); } - else + else if (!digital_disabled && !cv_gamedigimusic.value) { digital_disabled = true; if (S_MusicType() != MU_MID) @@ -2191,21 +2448,21 @@ void GameDigiMusic_OnChange(void) #ifdef HAVE_OPENMPT -void ModFilter_OnChange(void) +static void ModFilter_OnChange(void) { if (openmpt_mhandle) openmpt_module_set_render_param(openmpt_mhandle, OPENMPT_MODULE_RENDER_INTERPOLATIONFILTER_LENGTH, cv_modfilter.value); } -void StereoSep_OnChange(void) +static void StereoSep_OnChange(void) { if (openmpt_mhandle) openmpt_module_set_render_param(openmpt_mhandle, OPENMPT_MODULE_RENDER_STEREOSEPARATION_PERCENT, cv_stereosep.value); } -void AmigaFilter_OnChange(void) +static void AmigaFilter_OnChange(void) { if (openmpt_mhandle) openmpt_module_ctl_set(openmpt_mhandle, "render.resampler.emulate_amiga", cv_amigafilter.value ? "1" : "0"); @@ -2213,7 +2470,7 @@ void AmigaFilter_OnChange(void) #if OPENMPT_API_VERSION_MAJOR < 1 && OPENMPT_API_VERSION_MINOR > 4 -void AmigaType_OnChange(void) +static void AmigaType_OnChange(void) { if (openmpt_mhandle) openmpt_module_ctl_set_text(openmpt_mhandle, "render.resampler.emulate_amiga_type", cv_amigatype.string); @@ -2224,21 +2481,21 @@ void AmigaType_OnChange(void) #endif #endif -void BufferSize_OnChange(void) +static void BufferSize_OnChange(void) { if (sound_started) COM_ImmedExecute("restartaudio"); } #ifndef NO_MIDI -void GameMIDIMusic_OnChange(void) +static void GameMIDIMusic_OnChange(void) { if (M_CheckParm("-nomusic") || M_CheckParm("-noaudio")) return; else if (M_CheckParm("-nomidimusic")) return; - if (midi_disabled) + if (midi_disabled && cv_gamemidimusic.value) { midi_disabled = false; I_InitMusic(); @@ -2247,7 +2504,7 @@ void GameMIDIMusic_OnChange(void) else S_ChangeMusicInternal("titles", looptitle); } - else + else if (!midi_disabled && !cv_gamemidimusic.value) { midi_disabled = true; if (S_MusicType() == MU_MID) diff --git a/src/s_sound.h b/src/s_sound.h index bc1a73563..12efb9c44 100644 --- a/src/s_sound.h +++ b/src/s_sound.h @@ -37,11 +37,12 @@ extern consvar_t cv_audbuffersize; //extern consvar_t cv_resetmusic; extern consvar_t cv_gamedigimusic; #ifndef NO_MIDI -extern consvar_t cv_gamemidimusic; +extern consvar_t cv_gamemidimusic, cv_midimusicvolume; #endif extern consvar_t cv_gamesounds; extern consvar_t cv_playmusicifunfocused; extern consvar_t cv_playsoundifunfocused; +extern consvar_t cv_pausemusic; #ifdef HAVE_OPENMPT extern consvar_t cv_modfilter; @@ -52,10 +53,23 @@ extern consvar_t cv_amigatype; #endif #endif +//bird music stuff extern consvar_t cv_music_resync_threshold; extern consvar_t cv_music_resync_powerups_only; -extern CV_PossibleValue_t soundvolume_cons_t[]; +extern consvar_t cv_invincmusicfade; +extern consvar_t cv_growmusicfade; + +extern consvar_t cv_respawnfademusicout; +extern consvar_t cv_respawnfademusicback; + +extern consvar_t cv_resetspecialmusic; + +extern consvar_t cv_resume; +extern consvar_t cv_fading; +extern consvar_t cv_birdmusic; + +extern consvar_t precachesound; typedef enum { @@ -104,7 +118,6 @@ lumpnum_t S_GetSfxLumpNum(sfxinfo_t *sfx); boolean S_SoundDisabled(void); - // // Start sound for thing at using from sounds.h // @@ -126,6 +139,7 @@ boolean S_MusicDisabled(void); boolean S_MusicPlaying(void); boolean S_MusicPaused(void); boolean S_MusicNotInFocus(void); +boolean S_PrecacheSound(void); musictype_t S_MusicType(void); const char *S_MusicName(void); boolean S_MusicInfo(char *mname, UINT16 *mflags, boolean *looping); @@ -144,11 +158,24 @@ boolean S_SpeedMusic(float speed); typedef struct musicdef_s { char name[7]; - //char usage[256]; + char usage[256]; char source[256]; + char filename[256]; + // for the music test stuff + // generally if these are present on vanilla the game would throw up a warning + // a sacrifice i suppose + char title[256]; + char alttitle[256]; + char authors[256]; + boolean use_info; struct musicdef_s *next; } musicdef_t; +extern musicdef_t *musicdefstart; +extern musicdef_t **soundtestdefs; +extern INT32 numsoundtestdefs; +extern UINT8 soundtestpage; + extern struct cursongcredit { musicdef_t *def; @@ -157,14 +184,17 @@ extern struct cursongcredit UINT8 trans; } cursongcredit; -extern musicdef_t *musicdefstart; void S_LoadMusicDefs(UINT16 wadnum); void S_InitMusicDefs(void); +void S_LoadMTDefs(UINT16 wadnum); +void S_InitMTDefs(void); musicdef_t *S_FindMusicCredit(const char *musname); void S_ShowSpecifiedMusicCredit(const char *musname); void S_ShowMusicCredit(void); +boolean S_PrepareSoundTest(void); + // // Music Seeking // @@ -218,7 +248,6 @@ void S_StopMusic(void); void S_PauseAudio(void); void S_ResumeAudio(void); - // // Music Fading // diff --git a/src/screen.c b/src/screen.c index c3f87688d..d7aa1407e 100644 --- a/src/screen.c +++ b/src/screen.c @@ -70,6 +70,8 @@ consvar_t cv_shittyscreen = {"televisionsignal", "Okay", CV_NOSHOWHELP, shittysc static void SCR_ChangeFullscreen (void); +static INT32 SCR_FPSflags(void); + consvar_t cv_fullscreen = {"fullscreen", "Yes", CV_SAVE|CV_CALL, CV_YesNo, SCR_ChangeFullscreen, 0, NULL, NULL, 0, 0, NULL}; // ========================================================================= @@ -231,6 +233,30 @@ void SCR_Startup(void) CV_RegisterVar(&cv_menucaps); CV_RegisterVar(&cv_constextsize); + CV_RegisterVar(&cv_globalgamma); + CV_RegisterVar(&cv_globalsaturation); + + CV_RegisterVar(&cv_rhue); + CV_RegisterVar(&cv_yhue); + CV_RegisterVar(&cv_ghue); + CV_RegisterVar(&cv_chue); + CV_RegisterVar(&cv_bhue); + CV_RegisterVar(&cv_mhue); + + CV_RegisterVar(&cv_rgamma); + CV_RegisterVar(&cv_ygamma); + CV_RegisterVar(&cv_ggamma); + CV_RegisterVar(&cv_cgamma); + CV_RegisterVar(&cv_bgamma); + CV_RegisterVar(&cv_mgamma); + + CV_RegisterVar(&cv_rsaturation); + CV_RegisterVar(&cv_ysaturation); + CV_RegisterVar(&cv_gsaturation); + CV_RegisterVar(&cv_csaturation); + CV_RegisterVar(&cv_bsaturation); + CV_RegisterVar(&cv_msaturation); + V_SetPalette(0); } @@ -411,6 +437,14 @@ void SCR_CalculateFPS(void) #endif } +// this is pretty dumb, but has to be done like this, otherwise the fps counter just disappears sometimes for no reason lol +static INT32 SCR_FPSflags(void) +{ + if (!cv_translucenthud.value) return V_SNAPTOBOTTOM|V_SNAPTORIGHT|V_HUDTRANS; // eee kinda works ig + + return (((10-cv_translucenthud.value)*V_10TRANS) & V_ALPHAMASK) | V_SNAPTOBOTTOM|V_SNAPTORIGHT; +} + void SCR_DisplayTicRate(void) { const UINT8 *ticcntcolor = NULL; @@ -418,40 +452,66 @@ void SCR_DisplayTicRate(void) UINT32 benchmark = (cap == 0) ? I_GetRefreshRate() : cap; INT32 x = 318; double fps = round(averageFPS); + INT32 fpsflags = SCR_FPSflags(); + const char *fps_string; + + INT32 ticcntcolor2 = 0; if (gamestate == GS_NULL) return; - // draw "FPS" - if (cv_ticrate.value == 1) - V_DrawFixedPatch(306< (benchmark - 5)) - ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_MINT, GTC_CACHE); - else if (fps < 20) - ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_RASPBERRY, GTC_CACHE); - - if (cap != 0) + // new kart counter + if ((cv_ticrate.value == 1) || (cv_ticrate.value == 2)) { - UINT32 digits = 1; - UINT32 c2 = cap; + // draw "FPS" + if (cv_ticrate.value == 1) + V_DrawFixedPatch(306< (benchmark - 5)) + ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_MINT, GTC_CACHE); + else if (fps < 20) + ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_RASPBERRY, GTC_CACHE); - while (c2 > 0) + if (cap != 0) { - c2 = c2 / 10; - digits++; + UINT32 digits = 1; + UINT32 c2 = cap; + + while (c2 > 0) + { + c2 = c2 / 10; + digits++; + } + + // draw total frame: + V_DrawPingNum(x, 190, fpsflags, cap, ticcntcolor); + + x -= digits * 4; + + // draw "/" + V_DrawFixedPatch(x< (benchmark - 5)) + ticcntcolor2 = V_GREENMAP; + else if (fps < 20) + ticcntcolor2 = V_REDMAP; - // draw our actual framerate - V_DrawPingNum(x, 190, V_SNAPTOBOTTOM|V_SNAPTORIGHT, fps, ticcntcolor); + if (cap != 0) + fps_string = va("%d/%d\x82", (INT32)fps, cap); + else + fps_string = va("%d\x82", (INT32)fps); + + if (cv_ticrate.value == 3) + V_DrawRightAlignedString(319, 181, V_YELLOWMAP|fpsflags, "FPS"); + + V_DrawRightAlignedString(319, 190, ticcntcolor2|fpsflags, fps_string); + } } // SCR_DisplayLocalPing @@ -460,9 +520,12 @@ void SCR_DisplayTicRate(void) void SCR_DisplayLocalPing(void) { UINT32 ping = playerpingtable[consoleplayer]; // consoleplayer's ping is everyone's ping in a splitnetgame :P + INT32 fpsflags = SCR_FPSflags(); + if (cv_showping.value == 1 || (cv_showping.value == 2 && ping > servermaxping)) // only show 2 (warning) if our ping is at a bad level { - INT32 dispy = cv_ticrate.value ? 160 : 181; - HU_drawPing(307, dispy, ping, V_SNAPTORIGHT | V_SNAPTOBOTTOM); + INT32 dispy = (cv_ticrate.value == 1) ? 165 : ((cv_ticrate.value == 2 || cv_ticrate.value == 4) ? 172 : ((cv_ticrate.value == 3) ? 163 : 181)); // absolute buttpain + + HU_drawPing(308, dispy, ping, fpsflags); } } diff --git a/src/screen.h b/src/screen.h index a4ddbfdb1..478890c49 100644 --- a/src/screen.h +++ b/src/screen.h @@ -39,13 +39,8 @@ // we try to re-allocate a minimum of buffers for stability of the memory, // so all the small-enough tables based on screen size, are allocated once // and for all at the maximum size. -#if defined (_WIN32_WCE) -#define MAXVIDWIDTH 320 -#define MAXVIDHEIGHT 200 -#else -#define MAXVIDWIDTH 2560 // don't set this too high because actually -#define MAXVIDHEIGHT 1440 // lots of tables are allocated with the MAX size. -#endif +#define MAXVIDWIDTH 3840 // don't set this too high because actually +#define MAXVIDHEIGHT 2160 // lots of tables are allocated with the MAX size. #define BASEVIDWIDTH 320 // NEVER CHANGE THIS! This is the original #define BASEVIDHEIGHT 200 // resolution of the graphics. @@ -77,11 +72,18 @@ typedef struct viddef_s #ifdef HWRENDER INT32/*fixed_t*/ fsmalldupx, fsmalldupy; INT32/*fixed_t*/ fmeddupx, fmeddupy; + INT32 glstate; #endif } viddef_t; #define VIDWIDTH vid.width #define VIDHEIGHT vid.height +enum +{ + VID_GL_LIBRARY_LOADED = 1, + VID_GL_LIBRARY_ERROR = -1, +}; + // internal additional info for vesa modes only typedef struct { diff --git a/src/sdl/Srb2SDL-vc10.vcxproj b/src/sdl/Srb2SDL-vc10.vcxproj index 813e31a98..e51799314 100644 --- a/src/sdl/Srb2SDL-vc10.vcxproj +++ b/src/sdl/Srb2SDL-vc10.vcxproj @@ -218,6 +218,7 @@ + @@ -364,6 +365,7 @@ + diff --git a/src/sdl/Srb2SDL-vc10.vcxproj.filters b/src/sdl/Srb2SDL-vc10.vcxproj.filters index f197a394b..2234d7620 100644 --- a/src/sdl/Srb2SDL-vc10.vcxproj.filters +++ b/src/sdl/Srb2SDL-vc10.vcxproj.filters @@ -215,6 +215,9 @@ Hw_Hardware + + + Hw_Hardware Hw_Hardware @@ -617,6 +620,9 @@ Hw_Hardware + + + Hw_Hardware Hw_Hardware diff --git a/src/sdl/hwsym_sdl.c b/src/sdl/hwsym_sdl.c index 4af37ee42..64f9b7da9 100644 --- a/src/sdl/hwsym_sdl.c +++ b/src/sdl/hwsym_sdl.c @@ -74,17 +74,19 @@ void *hwSym(const char *funcName,void *handle) { void *funcPointer = NULL; #ifdef HWRENDER - if (0 == strcmp("SetPalette", funcName)) + if (0 == strcmp("SetTexturePalette", funcName)) funcPointer = &OglSdlSetPalette; GETFUNC(Init); + GETFUNC(SetupGLInfo); GETFUNC(Draw2DLine); GETFUNC(DrawPolygon); + GETFUNC(DrawIndexedTriangles); GETFUNC(SetBlend); GETFUNC(ClearBuffer); GETFUNC(SetTexture); GETFUNC(UpdateTexture); - GETFUNC(ReadRect); + GETFUNC(ReadScreenTexture); GETFUNC(GClipRect); GETFUNC(ClearMipMapCache); GETFUNC(SetSpecialState); @@ -94,30 +96,26 @@ void *hwSym(const char *funcName,void *handle) GETFUNC(SetTransform); GETFUNC(PostImgRedraw); GETFUNC(FlushScreenTextures); - GETFUNC(StartScreenWipe); - GETFUNC(EndScreenWipe); GETFUNC(DoScreenWipe); - GETFUNC(DrawIntermissionBG); + GETFUNC(DrawScreenTexture); GETFUNC(MakeScreenTexture); - GETFUNC(MakeScreenFinalTexture); + GETFUNC(RenderVhsEffect); GETFUNC(DrawScreenFinalTexture); GETFUNC(RenderSkyDome); - GETFUNC(LoadShaders); - GETFUNC(KillShaders); + GETFUNC(InitShaders); + GETFUNC(LoadShader); + GETFUNC(CompileShader); GETFUNC(SetShader); GETFUNC(UnSetShader); GETFUNC(SetShaderInfo); - GETFUNC(LoadCustomShader); - GETFUNC(InitCustomShaders); - GETFUNC(StartBatching); - GETFUNC(RenderBatches); - - GETFUNC(AddLightTable); - GETFUNC(ClearLightTableCache); + GETFUNC(SetPaletteLookup); + GETFUNC(CreateLightTable); + GETFUNC(ClearLightTables); + GETFUNC(SetScreenPalette); #else //HWRENDER if (0 == strcmp("FinishUpdate", funcName)) diff --git a/src/sdl/i_system.c b/src/sdl/i_system.c index 7a9d48678..c04434347 100644 --- a/src/sdl/i_system.c +++ b/src/sdl/i_system.c @@ -420,7 +420,7 @@ static void I_ReportSignal(int num, int coredumped) { //static char msg[] = "oh no! back to reality!\r\n"; const char * sigmsg; - char msg[128]; + char msg[256]; switch (num) { @@ -459,15 +459,23 @@ static void I_ReportSignal(int num, int coredumped) sprintf(msg, "%s (core dumped)", sigmsg); else strcat(msg, " (core dumped)"); - - sigmsg = msg; } + else + { + sprintf(msg, "%s", sigmsg); + } + +#ifdef HAVE_LIBBACKTRACE + strncat(msg, "\n\nCrash report has been saved into srb2kart-crash-log.txt", 255); +#elif defined(_WIN32) && !defined(__MINGW64__) + strncat(msg, "\n\nCrash report has been saved into srb2kart.rpt", 255); +#endif I_OutputMsg("\nProcess killed by signal: %s\n\n", sigmsg); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Process killed by signal", - sigmsg, NULL); + msg, NULL); } #ifndef NEWSIGNALHANDLER @@ -666,6 +674,7 @@ void I_GetConsoleEvents(void) return; ev.type = ev_console; + ev.data1 = 0; if (read(STDIN_FILENO, &key, 1) == -1 || !key) return; @@ -692,7 +701,7 @@ void I_GetConsoleEvents(void) } else return; } - else + else if (tty_con.cursor < sizeof (tty_con.buffer)) { // push regular character ev.data1 = tty_con.buffer[tty_con.cursor] = key; @@ -1034,12 +1043,6 @@ INT32 I_GetKey (void) return rc; } -void -I_CursedWindowMovement (int xd, int yd) -{ - SDL_SetWindowPosition(window, window_x + xd, window_y + yd); -} - // // I_JoyScale // diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 82e279093..89c7bf555 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -640,9 +640,6 @@ static void Impl_HandleWindowEvent(SDL_WindowEvent evt) break; case SDL_WINDOWEVENT_MAXIMIZED: break; - case SDL_WINDOWEVENT_MOVED: - window_x = evt.data1; - window_y = evt.data2; } if (mousefocus && kbfocus) @@ -1451,10 +1448,10 @@ void I_FinishUpdate(void) if (I_SkipFrame()) return; - if (cv_ticrate.value) + if (cv_ticrate.value && st_overlay) SCR_DisplayTicRate(); - if (cv_showping.value && netgame && consoleplayer != serverplayer) + if (cv_showping.value && netgame && consoleplayer != serverplayer && st_overlay) SCR_DisplayLocalPing(); #ifdef HAVE_DISCORDRPC @@ -1790,10 +1787,8 @@ static SDL_bool Impl_CreateWindow(SDL_bool fullscreen) flags |= SDL_WINDOW_BORDERLESS; #ifdef HWRENDER - if (rendermode == render_opengl) - { + if (vid.glstate == VID_GL_LIBRARY_LOADED) flags |= SDL_WINDOW_OPENGL; - } if (msaa) { @@ -1805,12 +1800,12 @@ static SDL_bool Impl_CreateWindow(SDL_bool fullscreen) // Some GPU drivers may give us a 16-bit depth buffer since the // default value for SDL_GL_DEPTH_SIZE is 16. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); -#endif - + // request stencil buffer. If there are problems on weaker hw the bit count could be reduced // If only something like 1-bit or 2-bit stencil is available on some gpus then should implement limit for maxportals based on that. // 4 bits would be enough for current limit in maxportals (12) SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 4); +#endif // Create a window window = SDL_CreateWindow("SRB2Kart "VERSIONSTRING, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, @@ -1824,7 +1819,8 @@ static SDL_bool Impl_CreateWindow(SDL_bool fullscreen) // Renderer-specific stuff #ifdef HWRENDER - if (rendermode == render_opengl) + if ((rendermode == render_opengl) + && (vid.glstate != VID_GL_LIBRARY_ERROR)) { sdlglcontext = SDL_GL_CreateContext(window); if (sdlglcontext == NULL) @@ -2112,51 +2108,52 @@ void I_StartupGraphics(void) if (rendermode == render_opengl) { HWD.pfnInit = hwSym("Init",NULL); + HWD.pfnSetupGLInfo = hwSym("SetupGLInfo",NULL); HWD.pfnFinishUpdate = NULL; HWD.pfnDraw2DLine = hwSym("Draw2DLine",NULL); HWD.pfnDrawPolygon = hwSym("DrawPolygon",NULL); + HWD.pfnDrawIndexedTriangles = hwSym("DrawIndexedTriangles",NULL); HWD.pfnSetBlend = hwSym("SetBlend",NULL); HWD.pfnClearBuffer = hwSym("ClearBuffer",NULL); HWD.pfnSetTexture = hwSym("SetTexture",NULL); HWD.pfnUpdateTexture = hwSym("UpdateTexture",NULL); - HWD.pfnReadRect = hwSym("ReadRect",NULL); + HWD.pfnReadScreenTexture= hwSym("ReadScreenTexture",NULL); HWD.pfnGClipRect = hwSym("GClipRect",NULL); HWD.pfnClearMipMapCache = hwSym("ClearMipMapCache",NULL); HWD.pfnSetSpecialState = hwSym("SetSpecialState",NULL); - HWD.pfnSetPalette = hwSym("SetPalette",NULL); + HWD.pfnSetTexturePalette= hwSym("SetTexturePalette",NULL); HWD.pfnGetTextureUsed = hwSym("GetTextureUsed",NULL); HWD.pfnDrawModel = hwSym("DrawModel",NULL); HWD.pfnCreateModelVBOs = hwSym("CreateModelVBOs",NULL); HWD.pfnSetTransform = hwSym("SetTransform",NULL); HWD.pfnPostImgRedraw = hwSym("PostImgRedraw",NULL); HWD.pfnFlushScreenTextures=hwSym("FlushScreenTextures",NULL); - HWD.pfnStartScreenWipe = hwSym("StartScreenWipe",NULL); - HWD.pfnEndScreenWipe = hwSym("EndScreenWipe",NULL); HWD.pfnDoScreenWipe = hwSym("DoScreenWipe",NULL); - HWD.pfnDrawIntermissionBG=hwSym("DrawIntermissionBG",NULL); + HWD.pfnDrawScreenTexture= hwSym("DrawScreenTexture",NULL); HWD.pfnMakeScreenTexture= hwSym("MakeScreenTexture",NULL); - HWD.pfnMakeScreenFinalTexture=hwSym("MakeScreenFinalTexture",NULL); + HWD.pfnRenderVhsEffect = hwSym("RenderVhsEffect",NULL); HWD.pfnDrawScreenFinalTexture=hwSym("DrawScreenFinalTexture",NULL); HWD.pfnRenderSkyDome = hwSym("RenderSkyDome",NULL); - HWD.pfnLoadShaders = hwSym("LoadShaders",NULL); - HWD.pfnKillShaders = hwSym("KillShaders",NULL); - HWD.pfnSetShader = hwSym("SetShader",NULL); - HWD.pfnUnSetShader = hwSym("UnSetShader",NULL); + HWD.pfnInitShaders = hwSym("InitShaders",NULL); + HWD.pfnLoadShader = hwSym("LoadShader",NULL); + HWD.pfnCompileShader = hwSym("CompileShader",NULL); + HWD.pfnSetShader = hwSym("SetShader",NULL); + HWD.pfnUnSetShader = hwSym("UnSetShader",NULL); HWD.pfnSetShaderInfo = hwSym("SetShaderInfo",NULL); - HWD.pfnLoadCustomShader = hwSym("LoadCustomShader",NULL); - HWD.pfnInitCustomShaders = hwSym("InitCustomShaders",NULL); - HWD.pfnStartBatching = hwSym("StartBatching",NULL); - HWD.pfnRenderBatches = hwSym("RenderBatches",NULL); + HWD.pfnSetPaletteLookup = hwSym("SetPaletteLookup",NULL); + HWD.pfnCreateLightTable = hwSym("CreateLightTable",NULL); + HWD.pfnClearLightTables = hwSym("ClearLightTables",NULL); + HWD.pfnSetScreenPalette = hwSym("SetScreenPalette",NULL); - HWD.pfnAddLightTable = hwSym("AddLightTable",NULL); - HWD.pfnClearLightTableCache = hwSym("ClearLightTableCache",NULL); - - if (!HWD.pfnInit()) // load the OpenGL library + vid.glstate = HWD.pfnInit() ? VID_GL_LIBRARY_LOADED : VID_GL_LIBRARY_ERROR; // let load the OpenGL library + if (vid.glstate == VID_GL_LIBRARY_ERROR) + { rendermode = render_soft; + } } #endif @@ -2246,8 +2243,6 @@ void I_ShutdownGraphics(void) I_OutputMsg("shut down\n"); #ifdef HWRENDER - if (GLUhandle) - hwClose(GLUhandle); if (sdlglcontext) { SDL_GL_DeleteContext(sdlglcontext); diff --git a/src/sdl/mixer_sound.c b/src/sdl/mixer_sound.c index 57072ee3c..b34ccb18a 100644 --- a/src/sdl/mixer_sound.c +++ b/src/sdl/mixer_sound.c @@ -624,7 +624,7 @@ static void count_music_bytes(int chan, void *stream, int len, void *udata) return; music_bytes += len; - if (gamestate == GS_LEVEL) + if ((gamestate == GS_LEVEL) && (cv_birdmusic.value)) Countstutter(len); } @@ -696,8 +696,8 @@ static void mix_gme(void *udata, Uint8 *stream, int len) music_volume = 18; // apply volume to stream - for (i = 0, p = (short *)stream; i < len/2; i++, p++) - *p = ((INT32)*p) * (music_volume*internal_volume/100)*2 / 40; + for (i = 0, p = (short *)stream; i < len / 2; i++, p++) + *p = ((INT32)*p) * music_volume * internal_volume / 100 / 20; } #endif @@ -721,8 +721,8 @@ static void mix_openmpt(void *udata, Uint8 *stream, int len) music_volume = 18; // apply volume to stream - for (i = 0, p = (short *)stream; i < len/2; i++, p++) - *p = ((INT32)*p) * (music_volume*internal_volume/100)*2 / 40; + for (i = 0, p = (short *)stream; i < len / 2; i++, p++) + *p = ((INT32)*p) * music_volume * internal_volume / 100 / 20; } #endif @@ -1375,7 +1375,7 @@ void I_SetMusicVolume(UINT8 volume) Mix_VolumeMusic(get_real_volume(music_volume)); } -boolean I_SetSongTrack(int track) +boolean I_SetSongTrack(INT32 track) { #ifdef HAVE_LIBGME diff --git a/src/sdl/ogl_sdl.c b/src/sdl/ogl_sdl.c index b3f7be3fa..251c6ae0c 100644 --- a/src/sdl/ogl_sdl.c +++ b/src/sdl/ogl_sdl.c @@ -70,18 +70,10 @@ PFNglGetString pglGetString; /** \brief SDL video display surface */ INT32 oglflags = 0; -void *GLUhandle = NULL; SDL_GLContext sdlglcontext = 0; void *GetGLFunc(const char *proc) { - if (strncmp(proc, "glu", 3) == 0) - { - if (GLUhandle) - return hwSym(proc, GLUhandle); - else - return NULL; - } return SDL_GL_GetProcAddress(proc); } @@ -89,7 +81,6 @@ boolean LoadGL(void) { #ifndef STATIC_OPENGL const char *OGLLibname = NULL; - const char *GLULibname = NULL; if (M_CheckParm("-OGLlib") && M_IsNextParm()) OGLLibname = M_GetNextParm(); @@ -102,43 +93,6 @@ boolean LoadGL(void) CONS_Printf("If you know what is the OpenGL library's name, use -OGLlib\n"); return 0; } - -#if 0 - GLULibname = "/proc/self/exe"; -#elif defined (_WIN32) - GLULibname = "GLU32.DLL"; -#elif defined (__MACH__) - GLULibname = "/System/Library/Frameworks/OpenGL.framework/Libraries/libGLU.dylib"; -#elif defined (macintos) - GLULibname = "OpenGLLibrary"; -#elif defined (__unix__) - GLULibname = "libGLU.so.1"; -#elif defined (__HAIKU__) - GLULibname = "libGLU.so"; -#else - GLULibname = NULL; -#endif - - if (M_CheckParm("-GLUlib") && M_IsNextParm()) - GLULibname = M_GetNextParm(); - - if (GLULibname) - { - GLUhandle = hwOpen(GLULibname); - if (GLUhandle) - return SetupGLfunc(); - else - { - CONS_Alert(CONS_ERROR, "Could not load GLU Library: %s\n", GLULibname); - if (!M_CheckParm("-GLUlib")) - CONS_Printf("If you know what is the GLU library's name, use -GLUlib\n"); - } - } - else - { - CONS_Alert(CONS_ERROR, "Could not load GLU Library\n"); - CONS_Printf("If you know what is the GLU library's name, use -GLUlib\n"); - } #endif return SetupGLfunc(); } @@ -182,6 +136,19 @@ boolean OglSdlSurface(INT32 w, INT32 h) GL_DBG_Printf("OpenGL %s\n", gl_version); GL_DBG_Printf("GPU: %s\n", gl_renderer); GL_DBG_Printf("Extensions: %s\n", gl_extensions); + + if (strcmp((const char*)gl_renderer, "GDI Generic") == 0 && + strcmp((const char*)gl_version, "1.1.0") == 0) + { + // Oh no... Windows gave us the GDI Generic rasterizer, so something is wrong... + // The game will crash later on when unsupported OpenGL commands are encountered. + // Instead of a nondescript crash, show a more informative error message. + // Also set the renderer variable back to software so the next launch won't + // repeat this error. + I_Error("OpenGL Error: Failed to access the GPU. Possible reasons include:\n" + "- GPU vendor has dropped OpenGL support on your GPU and OS. (Old GPU?)\n" + "- GPU drivers are missing or broken. You may need to update your drivers."); + } } first_init = true; @@ -189,6 +156,8 @@ boolean OglSdlSurface(INT32 w, INT32 h) pglGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maximumAnisotropy); else maximumAnisotropy = 1; + + SetupGLInfo(); SetupGLFunc4(); @@ -236,17 +205,15 @@ void OglSdlFinishUpdate(boolean waitvbl) HWR_DrawScreenFinalTexture(realwidth, realheight); } -EXPORT void HWRAPI(OglSdlSetPalette) (RGBA_t *palette, RGBA_t *pgamma) +EXPORT void HWRAPI(OglSdlSetPalette) (RGBA_t *palette) { - INT32 i = -1; - UINT32 redgamma = pgamma->s.red, greengamma = pgamma->s.green, - bluegamma = pgamma->s.blue; + INT32 i; for (i = 0; i < 256; i++) { - myPaletteData[i].s.red = (UINT8)MIN((palette[i].s.red * redgamma) /127, 255); - myPaletteData[i].s.green = (UINT8)MIN((palette[i].s.green * greengamma)/127, 255); - myPaletteData[i].s.blue = (UINT8)MIN((palette[i].s.blue * bluegamma) /127, 255); + myPaletteData[i].s.red = palette[i].s.red; + myPaletteData[i].s.green = palette[i].s.green; + myPaletteData[i].s.blue = palette[i].s.blue; myPaletteData[i].s.alpha = palette[i].s.alpha; } Flush(); diff --git a/src/sdl/ogl_sdl.h b/src/sdl/ogl_sdl.h index 2d6209f2b..ad153da93 100644 --- a/src/sdl/ogl_sdl.h +++ b/src/sdl/ogl_sdl.h @@ -18,8 +18,6 @@ #include "../v_video.h" -extern void *GLUhandle; - boolean OglSdlSurface(INT32 w, INT32 h); void OglSdlFinishUpdate(boolean vidwait); @@ -30,5 +28,5 @@ extern Uint16 realwidth; extern Uint16 realheight; #ifdef _CREATE_DLL_ -EXPORT void HWRAPI( OglSdlSetPalette ) (RGBA_t *palette, RGBA_t *pgamma); +EXPORT void HWRAPI( OglSdlSetPalette ) (RGBA_t *palette); #endif diff --git a/src/sdl/sdl_sound.c b/src/sdl/sdl_sound.c index 5c93642bd..2f8fa7b5d 100644 --- a/src/sdl/sdl_sound.c +++ b/src/sdl/sdl_sound.c @@ -1476,7 +1476,7 @@ void I_SetMusicVolume(UINT8 volume) (void)volume; } -boolean I_SetSongTrack(int track) +boolean I_SetSongTrack(INT32 track) { (void)track; return false; diff --git a/src/sounds.c b/src/sounds.c index d949c27ab..51961b906 100644 --- a/src/sounds.c +++ b/src/sounds.c @@ -14,6 +14,8 @@ #include "doomtype.h" #include "i_sound.h" #include "sounds.h" +#include "s_sound.h" //for soundprecaching +#include "m_argv.h" #include "r_defs.h" #include "r_things.h" #include "z_zone.h" @@ -1031,8 +1033,10 @@ sfxenum_t S_AddSoundFx(const char *name, boolean singular, INT32 flags, boolean S_sfx[i].skinsound = -1; S_sfx[i].usefulness = -1; - /// \todo if precached load it here - S_sfx[i].data = NULL; + if (S_PrecacheSound()) + S_sfx[i].data = I_GetSfx(&S_sfx[i]); + else + S_sfx[i].data = NULL; return i; } } diff --git a/src/st_stuff.c b/src/st_stuff.c index 9bc182d17..b4b4a3d49 100644 --- a/src/st_stuff.c +++ b/src/st_stuff.c @@ -245,7 +245,7 @@ void ST_doPaletteStuff(void) palette = 0; #ifdef HWRENDER - if ((rendermode == render_opengl && !cv_grpaletteshader.value) || (rendermode == render_opengl && cv_grpaletteshader.value && !cv_grflashpal.value)) + if (rendermode == render_opengl && !HWR_PalRenderFlashpal()) palette = 0; // No flashpals here in OpenGL #endif @@ -254,7 +254,7 @@ void ST_doPaletteStuff(void) st_palette = palette; #ifdef HWRENDER - if (rendermode == render_soft || (rendermode == render_opengl && cv_grpaletteshader.value && cv_grflashpal.value)) + if (rendermode == render_soft || (rendermode == render_opengl && HWR_PalRenderFlashpal())) #else if (rendermode != render_none) #endif @@ -1971,8 +1971,8 @@ static void ST_overlayDrawer(void) strlcpy(name, player_names[stplyr-players], 13);*/ // Show name of player being displayed - V_DrawCenteredString((BASEVIDWIDTH/2), BASEVIDHEIGHT-40, 0, M_GetText("VIEWPOINT:")); - V_DrawCenteredString((BASEVIDWIDTH/2), BASEVIDHEIGHT-32, V_ALLOWLOWERCASE, player_names[stplyr-players]); + V_DrawCenteredString((BASEVIDWIDTH/2), BASEVIDHEIGHT-40, V_HUDTRANS, M_GetText("VIEWPOINT:")); + V_DrawCenteredString((BASEVIDWIDTH/2), BASEVIDHEIGHT-32, V_HUDTRANS|V_ALLOWLOWERCASE, player_names[stplyr-players]); } } else if (!demo.title) @@ -2207,7 +2207,7 @@ void ST_Drawer(void) //25/08/99: Hurdler: palette changes is done for all players, // not only player1! That's why this part // of code is moved somewhere else. - if (rendermode == render_soft || (rendermode == render_opengl && cv_grpaletteshader.value && cv_grflashpal.value)) + if (rendermode == render_soft || (rendermode == render_opengl && HWR_PalRenderFlashpal())) #endif if (rendermode != render_none) ST_doPaletteStuff(); diff --git a/src/v_video.c b/src/v_video.c index 3bcd9db50..37060efeb 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -39,13 +39,40 @@ UINT8 *screens[5]; // screens[3] = fade screen start // screens[4] = fade screen end, postimage tempoarary buffer -static CV_PossibleValue_t gamma_cons_t[] = {{0, "MIN"}, {4, "MAX"}, {0, NULL}}; -static void CV_usegamma_OnChange(void); - -static CV_PossibleValue_t fps_cons_t[] = {{0, "No"}, {1, "Normal"}, {2, "Compact"}, {0, NULL}}; +static CV_PossibleValue_t fps_cons_t[] = {{0, "No"}, {1, "Normal"}, {2, "Compact"}, {3, "Old"}, {4, "Old Compact"}, {0, NULL}}; consvar_t cv_ticrate = {"showfps", "No", CV_SAVE, fps_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_usegamma = {"gamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_usegamma_OnChange, 0, NULL, NULL, 0, 0, NULL}; +static void CV_palette_OnChange(void); + +static CV_PossibleValue_t gamma_cons_t[] = {{-15, "MIN"}, {5, "MAX"}, {0, NULL}}; +consvar_t cv_globalgamma = {"gamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +static CV_PossibleValue_t saturation_cons_t[] = {{0, "MIN"}, {10, "MAX"}, {0, NULL}}; +consvar_t cv_globalsaturation = {"saturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +#define huecoloursteps 4 + +static CV_PossibleValue_t hue_cons_t[] = {{0, "MIN"}, {(huecoloursteps*6)-1, "MAX"}, {0, NULL}}; +consvar_t cv_rhue = {"rhue", "0", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_yhue = {"yhue", "4", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_ghue = {"ghue", "8", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_chue = {"chue", "12", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_bhue = {"bhue", "16", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_mhue = {"mhue", "20", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_rgamma = {"rgamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_ygamma = {"ygamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_ggamma = {"ggamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_cgamma = {"cgamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_bgamma = {"bgamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_mgamma = {"mgamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_rsaturation = {"rsaturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_ysaturation = {"ysaturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_gsaturation = {"gsaturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_csaturation = {"csaturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_bsaturation = {"bsaturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_msaturation = {"msaturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_allcaps = {"allcaps", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -57,9 +84,209 @@ consvar_t cv_constextsize = {"con_textsize", "Medium", CV_SAVE|CV_CALL, constext consvar_t cv_menucaps = {"menucaps", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +// local copy of the palette for V_GetColor() +RGBA_t *pLocalPalette = NULL; -const UINT8 gammatable[5][256] = +/* +The following was an extremely helpful resource when developing my Colour Cube LUT. +http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter24.html +Please check it out if you're trying to maintain this. +toast 18/04/17 +*/ + +float Cubepal[2][2][2][3]; + +// returns whether to apply cube, selectively avoiding expensive operations +static boolean InitCube(void) { + boolean apply = false; + UINT8 q; + float working[2][2][2][3] = // the initial positions of the corners of the colour cube! + { + { + { + {0.0, 0.0, 0.0}, // black corner + {0.0, 0.0, 1.0} // blue corner + }, + { + {0.0, 1.0, 0.0}, // green corner + {0.0, 1.0, 1.0} // cyan corner + } + }, + { + { + {1.0, 0.0, 0.0}, // red corner + {1.0, 0.0, 1.0} // magenta corner + }, + { + {1.0, 1.0, 0.0}, // yellow corner + {1.0, 1.0, 1.0} // white corner + } + } + }; + float desatur[3]; // grey + float globalgammamul, globalgammaoffs; + boolean doinggamma; + +#define diffcons(cv) (cv.value != atoi(cv.defaultvalue)) + + doinggamma = diffcons(cv_globalgamma); + +#define gammascale 8 + globalgammamul = (cv_globalgamma.value ? ((255 - (gammascale*abs(cv_globalgamma.value)))/255.0) : 1.0); + globalgammaoffs = ((cv_globalgamma.value > 0) ? ((gammascale*cv_globalgamma.value)/255.0) : 0.0); + desatur[0] = desatur[1] = desatur[2] = globalgammaoffs + (0.33*globalgammamul); + + if (doinggamma + || diffcons(cv_rhue) + || diffcons(cv_yhue) + || diffcons(cv_ghue) + || diffcons(cv_chue) + || diffcons(cv_bhue) + || diffcons(cv_mhue) + || diffcons(cv_rgamma) + || diffcons(cv_ygamma) + || diffcons(cv_ggamma) + || diffcons(cv_cgamma) + || diffcons(cv_bgamma) + || diffcons(cv_mgamma)) // set the gamma'd/hued positions (saturation is done later) + { + float mod, tempgammamul, tempgammaoffs; + + apply = true; + + working[0][0][0][0] = working[0][0][0][1] = working[0][0][0][2] = globalgammaoffs; + working[1][1][1][0] = working[1][1][1][1] = working[1][1][1][2] = globalgammaoffs+globalgammamul; + +#define dohue(hue, gamma, loc) \ + tempgammamul = (gamma ? ((255 - (gammascale*abs(gamma)))/255.0)*globalgammamul : globalgammamul);\ + tempgammaoffs = ((gamma > 0) ? ((gammascale*gamma)/255.0) + globalgammaoffs : globalgammaoffs);\ + mod = ((hue % huecoloursteps)*(tempgammamul)/huecoloursteps);\ + switch (hue/huecoloursteps)\ + {\ + case 0:\ + default:\ + loc[0] = tempgammaoffs+tempgammamul;\ + loc[1] = tempgammaoffs+mod;\ + loc[2] = tempgammaoffs;\ + break;\ + case 1:\ + loc[0] = tempgammaoffs+tempgammamul-mod;\ + loc[1] = tempgammaoffs+tempgammamul;\ + loc[2] = tempgammaoffs;\ + break;\ + case 2:\ + loc[0] = tempgammaoffs;\ + loc[1] = tempgammaoffs+tempgammamul;\ + loc[2] = tempgammaoffs+mod;\ + break;\ + case 3:\ + loc[0] = tempgammaoffs;\ + loc[1] = tempgammaoffs+tempgammamul-mod;\ + loc[2] = tempgammaoffs+tempgammamul;\ + break;\ + case 4:\ + loc[0] = tempgammaoffs+mod;\ + loc[1] = tempgammaoffs;\ + loc[2] = tempgammaoffs+tempgammamul;\ + break;\ + case 5:\ + loc[0] = tempgammaoffs+tempgammamul;\ + loc[1] = tempgammaoffs;\ + loc[2] = tempgammaoffs+tempgammamul-mod;\ + break;\ + } + dohue(cv_rhue.value, cv_rgamma.value, working[1][0][0]); + dohue(cv_yhue.value, cv_ygamma.value, working[1][1][0]); + dohue(cv_ghue.value, cv_ggamma.value, working[0][1][0]); + dohue(cv_chue.value, cv_cgamma.value, working[0][1][1]); + dohue(cv_bhue.value, cv_bgamma.value, working[0][0][1]); + dohue(cv_mhue.value, cv_mgamma.value, working[1][0][1]); +#undef dohue + } + +#define dosaturation(a, e) a = ((1 - work)*e + work*a) +#define docvsat(cv_sat, hue, gamma, r, g, b) \ + if diffcons(cv_sat)\ + {\ + float work, mod, tempgammamul, tempgammaoffs;\ + apply = true;\ + work = (cv_sat.value/10.0);\ + mod = ((hue % huecoloursteps)*(1.0)/huecoloursteps);\ + if (hue & huecoloursteps)\ + mod = 2-mod;\ + else\ + mod += 1;\ + tempgammamul = (gamma ? ((255 - (gammascale*abs(gamma)))/255.0)*globalgammamul : globalgammamul);\ + tempgammaoffs = ((gamma > 0) ? ((gammascale*gamma)/255.0) + globalgammaoffs : globalgammaoffs);\ + for (q = 0; q < 3; q++)\ + dosaturation(working[r][g][b][q], (tempgammaoffs+(desatur[q]*mod*tempgammamul)));\ + } + + docvsat(cv_rsaturation, cv_rhue.value, cv_rgamma.value, 1, 0, 0); + docvsat(cv_ysaturation, cv_yhue.value, cv_ygamma.value, 1, 1, 0); + docvsat(cv_gsaturation, cv_ghue.value, cv_ggamma.value, 0, 1, 0); + docvsat(cv_csaturation, cv_chue.value, cv_cgamma.value, 0, 1, 1); + docvsat(cv_bsaturation, cv_bhue.value, cv_bgamma.value, 0, 0, 1); + docvsat(cv_msaturation, cv_mhue.value, cv_mgamma.value, 1, 0, 1); + +#undef gammascale + + if diffcons(cv_globalsaturation) + { + float work = (cv_globalsaturation.value/10.0); + + apply = true; + + for (q = 0; q < 3; q++) + { + dosaturation(working[1][0][0][q], desatur[q]); + dosaturation(working[0][1][0][q], desatur[q]); + dosaturation(working[0][0][1][q], desatur[q]); + + dosaturation(working[1][1][0][q], 2*desatur[q]); + dosaturation(working[0][1][1][q], 2*desatur[q]); + dosaturation(working[1][0][1][q], 2*desatur[q]); + } + } + +#undef dosaturation + +#undef diffcons + + if (!apply) + return false; + +#define dowork(i, j, k, l) \ + if (working[i][j][k][l] > 1.0)\ + working[i][j][k][l] = 1.0;\ + else if (working[i][j][k][l] < 0.0)\ + working[i][j][k][l] = 0.0;\ + Cubepal[i][j][k][l] = working[i][j][k][l] + for (q = 0; q < 3; q++) + { + dowork(0, 0, 0, q); + dowork(1, 0, 0, q); + dowork(0, 1, 0, q); + dowork(1, 1, 0, q); + dowork(0, 0, 1, q); + dowork(1, 0, 1, q); + dowork(0, 1, 1, q); + dowork(1, 1, 1, q); + } +#undef dowork + + return true; +} + +/* +So it turns out that the way gamma was implemented previously, the default +colour profile of the game was messed up. Since this bad decision has been +around for a long time, and the intent is to keep the base game looking the +same, I'm not gonna be the one to remove this base modification. +toast 20/04/17 +*/ +const UINT8 correctiontable[256] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32, 33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48, @@ -75,80 +302,12 @@ const UINT8 gammatable[5][256] = 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, - 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255}, - - {2,4,5,7,8,10,11,12,14,15,16,18,19,20,21,23,24,25,26,27,29,30,31, - 32,33,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,54,55, - 56,57,58,59,60,61,62,63,64,65,66,67,69,70,71,72,73,74,75,76,77, - 78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98, - 99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114, - 115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,129, - 130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145, - 146,147,148,148,149,150,151,152,153,154,155,156,157,158,159,160, - 161,162,163,163,164,165,166,167,168,169,170,171,172,173,174,175, - 175,176,177,178,179,180,181,182,183,184,185,186,186,187,188,189, - 190,191,192,193,194,195,196,196,197,198,199,200,201,202,203,204, - 205,205,206,207,208,209,210,211,212,213,214,214,215,216,217,218, - 219,220,221,222,222,223,224,225,226,227,228,229,230,230,231,232, - 233,234,235,236,237,237,238,239,240,241,242,243,244,245,245,246, - 247,248,249,250,251,252,252,253,254,255}, - - {4,7,9,11,13,15,17,19,21,22,24,26,27,29,30,32,33,35,36,38,39,40,42, - 43,45,46,47,48,50,51,52,54,55,56,57,59,60,61,62,63,65,66,67,68,69, - 70,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,92,93, - 94,95,96,97,98,100,101,102,103,104,105,106,107,108,109,110,111,112, - 113,114,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128, - 129,130,131,132,133,133,134,135,136,137,138,139,140,141,142,143,144, - 144,145,146,147,148,149,150,151,152,153,153,154,155,156,157,158,159, - 160,160,161,162,163,164,165,166,166,167,168,169,170,171,172,172,173, - 174,175,176,177,178,178,179,180,181,182,183,183,184,185,186,187,188, - 188,189,190,191,192,193,193,194,195,196,197,197,198,199,200,201,201, - 202,203,204,205,206,206,207,208,209,210,210,211,212,213,213,214,215, - 216,217,217,218,219,220,221,221,222,223,224,224,225,226,227,228,228, - 229,230,231,231,232,233,234,235,235,236,237,238,238,239,240,241,241, - 242,243,244,244,245,246,247,247,248,249,250,251,251,252,253,254,254, - 255}, - - {8,12,16,19,22,24,27,29,31,34,36,38,40,41,43,45,47,49,50,52,53,55, - 57,58,60,61,63,64,65,67,68,70,71,72,74,75,76,77,79,80,81,82,84,85, - 86,87,88,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107, - 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124, - 125,126,127,128,129,130,131,132,133,134,135,135,136,137,138,139,140, - 141,142,143,143,144,145,146,147,148,149,150,150,151,152,153,154,155, - 155,156,157,158,159,160,160,161,162,163,164,165,165,166,167,168,169, - 169,170,171,172,173,173,174,175,176,176,177,178,179,180,180,181,182, - 183,183,184,185,186,186,187,188,189,189,190,191,192,192,193,194,195, - 195,196,197,197,198,199,200,200,201,202,202,203,204,205,205,206,207, - 207,208,209,210,210,211,212,212,213,214,214,215,216,216,217,218,219, - 219,220,221,221,222,223,223,224,225,225,226,227,227,228,229,229,230, - 231,231,232,233,233,234,235,235,236,237,237,238,238,239,240,240,241, - 242,242,243,244,244,245,246,246,247,247,248,249,249,250,251,251,252, - 253,253,254,254,255}, - - {16,23,28,32,36,39,42,45,48,50,53,55,57,60,62,64,66,68,69,71,73,75,76, - 78,80,81,83,84,86,87,89,90,92,93,94,96,97,98,100,101,102,103,105,106, - 107,108,109,110,112,113,114,115,116,117,118,119,120,121,122,123,124, - 125,126,128,128,129,130,131,132,133,134,135,136,137,138,139,140,141, - 142,143,143,144,145,146,147,148,149,150,150,151,152,153,154,155,155, - 156,157,158,159,159,160,161,162,163,163,164,165,166,166,167,168,169, - 169,170,171,172,172,173,174,175,175,176,177,177,178,179,180,180,181, - 182,182,183,184,184,185,186,187,187,188,189,189,190,191,191,192,193, - 193,194,195,195,196,196,197,198,198,199,200,200,201,202,202,203,203, - 204,205,205,206,207,207,208,208,209,210,210,211,211,212,213,213,214, - 214,215,216,216,217,217,218,219,219,220,220,221,221,222,223,223,224, - 224,225,225,226,227,227,228,228,229,229,230,230,231,232,232,233,233, - 234,234,235,235,236,236,237,237,238,239,239,240,240,241,241,242,242, - 243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251, - 251,252,252,253,254,254,255,255} -}; - -// local copy of the palette for V_GetColor() -RGBA_t *pLocalPalette = NULL; + 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255}; // keep a copy of the palette so that we can get the RGB value for a color index at any time. static void LoadPalette(const char *lumpname) { - const UINT8 *usegamma = gammatable[cv_usegamma.value]; + boolean cube = InitCube(); lumpnum_t lumpnum = W_GetNumForName(lumpname); size_t i, palsize = W_LumpLength(lumpnum)/3; UINT8 *pal; @@ -160,10 +319,48 @@ static void LoadPalette(const char *lumpname) pal = W_CacheLumpNum(lumpnum, PU_CACHE); for (i = 0; i < palsize; i++) { - pLocalPalette[i].s.red = usegamma[*pal++]; - pLocalPalette[i].s.green = usegamma[*pal++]; - pLocalPalette[i].s.blue = usegamma[*pal++]; + pLocalPalette[i].s.red = correctiontable[*pal++]; + pLocalPalette[i].s.green = correctiontable[*pal++]; + pLocalPalette[i].s.blue = correctiontable[*pal++]; pLocalPalette[i].s.alpha = 0xFF; + + // lerp of colour cubing! + if (cube) + { + float working[4][3]; + float linear; + UINT8 q; + + linear = (pLocalPalette[i].s.red/255.0); +#define dolerp(e1, e2) ((1 - linear)*e1 + linear*e2) + for (q = 0; q < 3; q++) + { + working[0][q] = dolerp(Cubepal[0][0][0][q], Cubepal[1][0][0][q]); + working[1][q] = dolerp(Cubepal[0][1][0][q], Cubepal[1][1][0][q]); + working[2][q] = dolerp(Cubepal[0][0][1][q], Cubepal[1][0][1][q]); + working[3][q] = dolerp(Cubepal[0][1][1][q], Cubepal[1][1][1][q]); + } + linear = (pLocalPalette[i].s.green/255.0); + for (q = 0; q < 3; q++) + { + working[0][q] = dolerp(working[0][q], working[1][q]); + working[1][q] = dolerp(working[2][q], working[3][q]); + } + linear = (pLocalPalette[i].s.blue/255.0); + for (q = 0; q < 3; q++) + { + working[0][q] = 255*dolerp(working[0][q], working[1][q]); + if (working[0][q] > 255.0) + working[0][q] = 255.0; + else if (working[0][q] < 0.0) + working[0][q] = 0.0; + } +#undef dowork + + pLocalPalette[i].s.red = (UINT8)(working[0][0]); + pLocalPalette[i].s.green = (UINT8)(working[0][1]); + pLocalPalette[i].s.blue = (UINT8)(working[0][2]); + } } } @@ -201,17 +398,8 @@ void V_SetPalette(INT32 palettenum) LoadMapPalette(); #ifdef HWRENDER - if (rendermode != render_soft && rendermode != render_none) { - // in palette rendering mode, we already manage our palette ourselves - if (cv_grpaletteshader.value == 1) - { - // reset our palette lookups n shit - gl_palette_initialized = false; - InitPalette(palettenum, true); - } - else - HWR_SetPalette(pLocalPalette); - } + if (rendermode != render_soft && rendermode != render_none) + HWR_SetPalette(&pLocalPalette[palettenum*256]); #if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) else #endif @@ -224,15 +412,8 @@ void V_SetPaletteLump(const char *pal) { LoadPalette(pal); #ifdef HWRENDER - if (rendermode != render_soft && rendermode != render_none) { - if (cv_grpaletteshader.value == 1) - { - // reset our palette lookups n shit - gl_palette_initialized = false; - InitPalette(0, false); - } + if (rendermode != render_soft && rendermode != render_none) HWR_SetPalette(pLocalPalette); - } #if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) else #endif @@ -244,7 +425,7 @@ void V_SetPaletteLump(const char *pal) #endif } -static void CV_usegamma_OnChange(void) +static void CV_palette_OnChange(void) { // reload palette LoadMapPalette(); @@ -692,10 +873,12 @@ void V_DrawBlock(INT32 x, INT32 y, INT32 scrn, INT32 width, INT32 height, const // // Fills a box of pixels with a single color, NOTE: scaled to screen size // +// alug: now with translucency support X) void V_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 c) { UINT8 *dest; const UINT8 *deststop; + UINT32 alphalevel = ((c & V_ALPHAMASK) >> V_ALPHASHIFT); if (rendermode == render_none) return; @@ -749,6 +932,7 @@ void V_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 c) if (x >= vid.width || y >= vid.height) return; // off the screen + if (x < 0) { w += x; @@ -762,18 +946,44 @@ void V_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 c) if (w <= 0 || h <= 0) return; // zero width/height wouldn't draw anything + if (x + w > vid.width) - w = vid.width - x; + w = vid.width-x; if (y + h > vid.height) - h = vid.height - y; + h = vid.height-y; dest = screens[0] + y*vid.width + x; deststop = screens[0] + vid.rowbytes * vid.height; - c &= 255; + if (alphalevel) + { + if (alphalevel == 13) + alphalevel = hudminusalpha[cv_translucenthud.value]; + else if (alphalevel == 14) + alphalevel = 10 - cv_translucenthud.value; + else if (alphalevel == 15) + alphalevel = hudplusalpha[cv_translucenthud.value]; - for (;(--h >= 0) && dest < deststop; dest += vid.width) - memset(dest, c, w * vid.bpp); + if (alphalevel >= 10) + return; // invis + } + + c &= 255; + + if (alphalevel) + { + const UINT8 *fadetable = ((UINT8 *)transtables + ((alphalevel-1)<= 0) && dest < deststop; dest += vid.width) + { + for (x = 0; x < w; x++) + dest[x] = fadetable[dest[x]]; + } + } + else + { + for (;(--h >= 0) && dest < deststop; dest += vid.width) + memset(dest, c, w * vid.bpp); + } } #ifdef HWRENDER @@ -1152,11 +1362,23 @@ void V_DrawVhsEffect(boolean rewind) if (rewind) V_DrawVhsEffect(false); // experimentation - upbary -= FixedMul(vid.dupy * (rewind ? 3 : 1.8f), renderdeltatics); - downbary += FixedMul(vid.dupy * (rewind ? 2 : 1), renderdeltatics); + if (renderisnewtic) + { + upbary -= (vid.dupy * (rewind ? 3 : 1.8f)); + downbary += (vid.dupy * (rewind ? 2 : 1)); + } + if (upbary < -barsize) upbary = vid.height; if (downbary > vid.height) downbary = -barsize; +#ifdef HWRENDER + if (rendermode == render_opengl) + { + HWR_RenderVhsEffect(upbary, downbary, updistort, downdistort, barsize); + return; + } +#endif + for (y = 0; y < vid.height; y+=2) { thismapstart = normalmapstart; diff --git a/src/v_video.h b/src/v_video.h index 7a9471deb..f8a005456 100644 --- a/src/v_video.h +++ b/src/v_video.h @@ -27,8 +27,12 @@ extern UINT8 *screens[5]; -extern const UINT8 gammatable[5][256]; -extern consvar_t cv_ticrate, cv_usegamma, cv_allcaps, cv_constextsize, cv_menucaps; +extern consvar_t cv_ticrate, cv_allcaps, cv_constextsize, cv_menucaps,\ +cv_globalgamma, cv_globalsaturation, \ +cv_rhue, cv_yhue, cv_ghue, cv_chue, cv_bhue, cv_mhue,\ +cv_rgamma, cv_ygamma, cv_ggamma, cv_cgamma, cv_bgamma, cv_mgamma, \ +cv_rsaturation, cv_ysaturation, cv_gsaturation, cv_csaturation, cv_bsaturation, cv_msaturation; + // Allocates buffer screens, call before R_Init. void V_Init(void); diff --git a/src/w_wad.c b/src/w_wad.c index 0914ec963..76c622999 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -36,11 +36,7 @@ #define ZWAD #ifdef ZWAD -#ifdef _WIN32_WCE -#define AVOID_ERRNO -#else #include -#endif #include "lzf.h" #endif @@ -70,6 +66,7 @@ #include "p_setup.h" // P_ScanThings #endif #include "m_misc.h" // M_MapNumber +#include "p_setup.h" // P_PartialAddFile mayb #ifdef HWRENDER #include "r_data.h" @@ -145,7 +142,7 @@ static char filenamebuf[MAX_WADPATH]; // This #if is copied from filesrch.c, so not sure if it is 100% suitable for // this -#if defined (_WIN32) && !defined (_XBOX) +#if defined (_WIN32) //#define WIN32_LEAN_AND_MEAN #define RPC_NO_WINDOWS_H #include @@ -202,7 +199,7 @@ FILE *W_OpenWadFile(const char **filename, boolean useerrors) // If findfile finds the file, the full path will be returned // in filenamebuf == *filename. - if (findfile(filenamebuf, NULL, true)) + if (findfile(filenamebuf, NULL, true) == FS_FOUND) { if ((handle = fopen_utf8(*filename, "rb")) == NULL) { @@ -696,18 +693,6 @@ static lumpinfo_t* ResGetLumpsZip (FILE* handle, UINT16* nlmp) return lumpinfo; } -static void W_ReadFileShaders(wadfile_t *wadfile) -{ -#ifdef HWRENDER - if (rendermode == render_opengl) - { - HWR_LoadShaders(numwadfiles - 1, W_FileHasFolders(wadfile)); - } -#else - (void)wadfile; -#endif -} - // Allocate a wadfile, setup the lumpinfo (directory) and // lumpcache, add the wadfile to the current active wadfiles // @@ -772,13 +757,10 @@ UINT16 W_InitFile(const char *filename, const char *lumpname, UINT16 *wadnump, b { if (!memcmp(wadfiles[i]->md5sum, md5sum, 16)) { - if (!local) { - CONS_Alert(CONS_ERROR, M_GetText("%s is already loaded\n"), filename); - if (handle) - fclose(handle); - return INT16_MAX; - } - CONS_Alert(CONS_WARNING, M_GetText("%s is a local skin that is already loaded\n"), filename); + CONS_Alert(CONS_ERROR, M_GetText("%s is already loaded\n"), filename); + if (handle) + fclose(handle); + return INT16_MAX; } } #endif @@ -844,7 +826,8 @@ UINT16 W_InitFile(const char *filename, const char *lumpname, UINT16 *wadnump, b numwadfiles++; // must come BEFORE W_LoadDehackedLumps, so any addfile called by COM_BufInsertText called by Lua doesn't overwrite what we just loaded // Read shaders from file - W_ReadFileShaders(wadfile); + if (rendermode == render_opengl && (vid.glstate == VID_GL_LIBRARY_LOADED)) + HWR_LoadCustomShadersFromFile(numwadfiles - 1, (type == RET_PK3)); // TODO: HACK ALERT - Load Lua & SOC stuff right here. I feel like this should be out of this place, but... Let's stick with this for now. switch (wadfile->type) @@ -943,6 +926,28 @@ INT32 W_InitMultipleFiles(char **filenames, boolean addons) return overallrc; } +INT32 W_AddAutoloadedLocalFiles(char **filenames) +{ + UINT16 rc = 1; + INT32 overallrc = 1; + + // will be realloced as lumps are added + for (; *filenames; filenames++) + { + rc = P_PartialAddWadFile(*filenames, true); + if (rc == UINT16_MAX) + CONS_Printf(M_GetText("Errors occurred while loading %s; not added.\n"), *filenames); + overallrc &= (rc != UINT16_MAX) ? 1 : 0; + } + + if (!numwadfiles) + I_Error("W_AddAutoloadedLocalFiles: no files found"); + + if (P_PartialAddGetStage() >= 0) + P_MultiSetupWadFiles(true); + return overallrc; +} + /** Make sure a lump number is valid. * Compiles away to nothing if PARANOIA is not defined. */ @@ -2137,6 +2142,10 @@ int W_VerifyNMUSlumps(const char *filename) {"MKFNT", 5}, // Kart font changes {"K_", 2}, // Kart graphic changes {"MUSICDEF", 8}, // Kart song definitions + {"SP_", 3}, // Speedometer changes do not count either. + {"SC_", 3}, // Colored speedometer stuff too. + {"SPRTINFO", 8}, // Sprite info + {"MUSCINFO", 8}, // Music test definitions #ifdef HWRENDER {"SHADERS", 7}, diff --git a/src/w_wad.h b/src/w_wad.h index 52e726d80..4b083ece6 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -145,6 +145,9 @@ void W_UnloadWadFile(UINT16 num); // so that it stops with a message if a file was not found, but not if all is okay. INT32 W_InitMultipleFiles(char **filenames, boolean addons); +// Used for autoload. Uses P_AddWadFileLocal instead of W_InitFiles. +INT32 W_AddAutoloadedLocalFiles(char **filenames); + #define W_FileHasFolders(wadfile) ((wadfile)->type == RET_PK3) const char *W_CheckNameForNumPwad(UINT16 wad, UINT16 lump); diff --git a/src/win32/Makefile.cfg b/src/win32/Makefile.cfg index c087703a1..4f8b39485 100644 --- a/src/win32/Makefile.cfg +++ b/src/win32/Makefile.cfg @@ -10,10 +10,9 @@ ifdef MINGW64 HAVE_LIBGME=1 LIBGME_CFLAGS=-I../libs/gme/include LIBGME_LDFLAGS=-L../libs/gme/win64 -lgme - ifdef HAVE_OPENMPT LIBOPENMPT_CFLAGS?=-I../libs/libopenmpt/inc - LIBOPENMPT_LDFLAGS?=-L../libs/libopenmpt/lib/x86_64 -llibopenmpt + LIBOPENMPT_LDFLAGS?=-L../libs/libopenmpt/lib/x86_64 -lopenmpt endif SDL_CFLAGS?=-I../libs/SDL2/x86_64-w64-mingw32/include/SDL2 -I../libs/SDL2_mixer/x86_64-w64-mingw32/include/SDL2 -Dmain=SDL_main @@ -22,13 +21,10 @@ else HAVE_LIBGME=1 LIBGME_CFLAGS=-I../libs/gme/include LIBGME_LDFLAGS=-L../libs/gme/win32 -lgme - - ifdef HAVE_OPENMPT LIBOPENMPT_CFLAGS?=-I../libs/libopenmpt/inc - LIBOPENMPT_LDFLAGS?=-L../libs/libopenmpt/lib/x86 -llibopenmpt + LIBOPENMPT_LDFLAGS?=-L../libs/libopenmpt/lib/x86 -lopenmpt endif - SDL_CFLAGS?=-I../libs/SDL2/i686-w64-mingw32/include/SDL2 -I../libs/SDL2_mixer/i686-w64-mingw32/include/SDL2 -Dmain=SDL_main SDL_LDFLAGS?=-L../libs/SDL2/i686-w64-mingw32/lib -L../libs/SDL2_mixer/i686-w64-mingw32/lib -lmingw32 -lSDL2main -lSDL2 -mwindows endif @@ -69,7 +65,7 @@ ifndef MINGW64 endif # name of the exefile - EXENAME?=srb2kart.exe + EXENAME?=srb2kart-saturn.exe i_system_o+=$(OBJDIR)/SRB2.res #i_main_o+=$(OBJDIR)/win_dbg.o diff --git a/src/y_inter.c b/src/y_inter.c index e23669951..ba5f89785 100644 --- a/src/y_inter.c +++ b/src/y_inter.c @@ -541,11 +541,20 @@ void Y_IntermissionDrawer(void) // i fucking hate this i fucking hate this i hate this so much if (!players[data.match.num[i]].skinlocal) { if (!players[data.match.num[i]].localskin) - V_DrawMappedPatch(x+16, y-4, 0, facerankprefix[*data.match.character[i]], colormap); + if (cv_highresportrait.value) + V_DrawSmallMappedPatch(x+16, y-4, 0, facewantprefix[*data.match.character[i]], colormap); + else + V_DrawMappedPatch(x+16, y-4, 0, facerankprefix[*data.match.character[i]], colormap); else - V_DrawMappedPatch(x+16, y-4, 0, facerankprefix[players[data.match.num[i]].localskin - 1], colormap); + if (cv_highresportrait.value) + V_DrawSmallMappedPatch(x+16, y-4, 0, facewantprefix[players[data.match.num[i]].localskin - 1], colormap); + else + V_DrawMappedPatch(x+16, y-4, 0, facerankprefix[players[data.match.num[i]].localskin - 1], colormap); } else { - V_DrawMappedPatch(x+16, y-4, 0, localfacerankprefix[players[data.match.num[i]].localskin - 1], colormap); + if (cv_highresportrait.value) + V_DrawSmallMappedPatch(x+16, y-4, 0, localfacewantprefix[players[data.match.num[i]].localskin - 1], colormap); + else + V_DrawMappedPatch(x+16, y-4, 0, localfacerankprefix[players[data.match.num[i]].localskin - 1], colormap); } } @@ -1320,7 +1329,10 @@ void Y_VoteDrawer(void) if (players[i].skincolor) { UINT8 *colormap = R_GetTranslationColormap(players[i].skin, players[i].skincolor, GTC_CACHE); - V_DrawMappedPatch(x+24, y+9, V_SNAPTOLEFT, (players[i].skinlocal ? localfacerankprefix : facerankprefix)[((players[i].localskin) ? players[i].localskin-1 : players[i].skin)], colormap); + if (cv_highresportrait.value) + V_DrawSmallMappedPatch(x+24, y+9, V_SNAPTOLEFT, (players[i].skinlocal ? localfacewantprefix : facewantprefix)[((players[i].localskin) ? players[i].localskin-1 : players[i].skin)], colormap); + else + V_DrawMappedPatch(x+24, y+9, V_SNAPTOLEFT, (players[i].skinlocal ? localfacerankprefix : facerankprefix)[((players[i].localskin) ? players[i].localskin-1 : players[i].skin)], colormap); } if (!splitscreen && i == consoleplayer) diff --git a/src/z_zone.c b/src/z_zone.c index 5b60e78c4..b0223460b 100644 --- a/src/z_zone.c +++ b/src/z_zone.c @@ -574,6 +574,9 @@ void Z_ChangeTag(void *ptr, INT32 tag) I_Error("Internal memory management error: " "tried to make block purgable but it has no owner"); + // No, please, don't make my PU_STATIC patch NULL! It supposed to be always valid! + if (block->tag < 10) return; + block->tag = tag; }