id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
34,610
|
constrainedfilestreambuf.cpp
|
OpenMW_openmw/components/files/constrainedfilestreambuf.cpp
|
#include "constrainedfilestreambuf.hpp"
#include <algorithm>
#include <filesystem>
#include <limits>
namespace Files
{
namespace File = Platform::File;
ConstrainedFileStreamBuf::ConstrainedFileStreamBuf(
const std::filesystem::path& fname, std::size_t start, std::size_t length)
: mOrigin(start)
{
mFile = File::open(fname);
mSize = length != std::numeric_limits<std::size_t>::max() ? length : File::size(mFile) - start;
if (start != 0)
File::seek(mFile, start);
setg(nullptr, nullptr, nullptr);
}
std::streambuf::int_type ConstrainedFileStreamBuf::underflow()
{
if (gptr() == egptr())
{
const std::size_t toRead = std::min((mOrigin + mSize) - (File::tell(mFile)), sizeof(mBuffer));
// Read in the next chunk of data, and set the read pointers on success
// Failure will throw exception.
const std::size_t got = File::read(mFile, mBuffer, toRead);
setg(mBuffer, mBuffer, mBuffer + got);
}
if (gptr() == egptr())
return traits_type::eof();
return traits_type::to_int_type(*gptr());
}
std::streambuf::pos_type ConstrainedFileStreamBuf::seekoff(
off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode)
{
if ((mode & std::ios_base::out) || !(mode & std::ios_base::in))
return traits_type::eof();
// new file position, relative to mOrigin
size_t newPos;
switch (whence)
{
case std::ios_base::beg:
newPos = offset;
break;
case std::ios_base::cur:
newPos = (File::tell(mFile) - mOrigin - (egptr() - gptr())) + offset;
break;
case std::ios_base::end:
newPos = mSize + offset;
break;
default:
return traits_type::eof();
}
if (newPos > mSize)
return traits_type::eof();
File::seek(mFile, mOrigin + newPos);
// Clear read pointers so underflow() gets called on the next read attempt.
setg(nullptr, nullptr, nullptr);
return newPos;
}
std::streambuf::pos_type ConstrainedFileStreamBuf::seekpos(pos_type pos, std::ios_base::openmode mode)
{
if ((mode & std::ios_base::out) || !(mode & std::ios_base::in))
return traits_type::eof();
if (static_cast<std::size_t>(pos) > mSize)
return traits_type::eof();
File::seek(mFile, mOrigin + pos);
// Clear read pointers so underflow() gets called on the next read attempt.
setg(nullptr, nullptr, nullptr);
return pos;
}
}
| 2,763
|
C++
|
.cpp
| 71
| 29.56338
| 106
| 0.571215
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,611
|
macospath.cpp
|
OpenMW_openmw/components/files/macospath.cpp
|
#include "macospath.hpp"
#if defined(macintosh) || defined(Macintosh) || defined(__APPLE__) || defined(__MACH__)
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <mach-o/dyld.h>
#include <pwd.h>
#include <unistd.h>
#include <vector>
#include <components/debug/debuglog.hpp>
#include <components/misc/strings/lower.hpp>
namespace
{
std::filesystem::path getBinaryPath()
{
uint32_t bufsize = 0;
_NSGetExecutablePath(nullptr, &bufsize);
std::vector<char> buf(bufsize);
if (_NSGetExecutablePath(buf.data(), &bufsize) == 0)
{
std::filesystem::path path = std::filesystem::path(buf.begin(), buf.end());
if (std::filesystem::is_symlink(path))
{
return std::filesystem::read_symlink(path);
}
return path;
}
else
{
Log(Debug::Warning) << "Not enough buffer size to get executable path: " << bufsize;
throw std::runtime_error("Failed to get executable path");
}
}
std::filesystem::path getUserHome()
{
const char* dir = getenv("HOME");
if (dir == nullptr)
{
struct passwd* pwd = getpwuid(getuid());
if (pwd != nullptr)
{
dir = pwd->pw_dir;
}
}
if (dir == nullptr)
return std::filesystem::path();
else
return std::filesystem::path(dir);
}
}
namespace Files
{
MacOsPath::MacOsPath(const std::string& application_name)
: mName(application_name)
{
std::filesystem::path binary_path = getBinaryPath();
std::error_code ec;
std::filesystem::current_path(binary_path.parent_path(), ec);
if (ec.value() != 0)
Log(Debug::Warning) << "Error " << ec.message() << " when changing current directory";
}
std::filesystem::path MacOsPath::getUserConfigPath() const
{
std::filesystem::path userPath(getUserHome());
userPath /= "Library/Preferences/";
return userPath / mName;
}
std::filesystem::path MacOsPath::getUserDataPath() const
{
std::filesystem::path userPath(getUserHome());
userPath /= "Library/Application Support/";
return userPath / mName;
}
std::filesystem::path MacOsPath::getGlobalConfigPath() const
{
std::filesystem::path globalPath("/Library/Preferences/");
return globalPath / mName;
}
std::filesystem::path MacOsPath::getCachePath() const
{
std::filesystem::path userPath(getUserHome());
userPath /= "Library/Caches";
return userPath / mName;
}
std::filesystem::path MacOsPath::getLocalPath() const
{
return std::filesystem::path("../Resources/");
}
std::filesystem::path MacOsPath::getGlobalDataPath() const
{
std::filesystem::path globalDataPath("/Library/Application Support/");
return globalDataPath / mName;
}
std::filesystem::path MacOsPath::getInstallPath() const
{
std::filesystem::path installPath;
std::filesystem::path homePath = getUserHome();
if (!homePath.empty())
{
std::filesystem::path wineDefaultRegistry(homePath);
wineDefaultRegistry /= ".wine/system.reg";
if (std::filesystem::is_regular_file(wineDefaultRegistry))
{
std::ifstream file(wineDefaultRegistry);
bool isRegEntry = false;
std::string line;
std::string mwpath;
while (std::getline(file, line))
{
if (line[0] == '[') // we found an entry
{
if (isRegEntry)
{
break;
}
isRegEntry = (line.find("Softworks\\\\Morrowind]") != std::string::npos);
}
else if (isRegEntry)
{
if (line[0] == '"') // empty line means new registry key
{
std::string key = line.substr(1, line.find('"', 1) - 1);
if (strcasecmp(key.c_str(), "Installed Path") == 0)
{
std::string::size_type valuePos = line.find('=') + 2;
mwpath = line.substr(valuePos, line.rfind('"') - valuePos);
std::string::size_type pos = mwpath.find("\\");
while (pos != std::string::npos)
{
mwpath.replace(pos, 2, "/");
pos = mwpath.find("\\", pos + 1);
}
break;
}
}
}
}
if (!mwpath.empty())
{
// Change drive letter to lowercase, so we could use ~/.wine/dosdevice symlinks
mwpath[0] = Misc::StringUtils::toLower(mwpath[0]);
installPath /= homePath;
installPath /= ".wine/dosdevices/";
installPath /= mwpath;
if (!std::filesystem::is_directory(installPath))
{
installPath.clear();
}
}
}
}
return installPath;
}
} /* namespace Files */
#endif /* defined(macintosh) || defined(Macintosh) || defined(__APPLE__) || defined(__MACH__) */
| 5,766
|
C++
|
.cpp
| 155
| 24.593548
| 99
| 0.499642
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,612
|
windowspath.cpp
|
OpenMW_openmw/components/files/windowspath.cpp
|
#include "windowspath.hpp"
#if defined(_WIN32) || defined(__WINDOWS__)
#include <array>
#include <cstring>
#define FAR
#define NEAR
#include <shlobj.h>
#include <shlwapi.h>
#include <winreg.h>
#undef NEAR
#undef FAR
#include <components/debug/debuglog.hpp>
/**
* \namespace Files
*/
namespace Files
{
WindowsPath::WindowsPath(const std::string& application_name)
: mName(application_name)
{
std::error_code ec;
current_path(getLocalPath(), ec);
if (ec.value() != 0)
Log(Debug::Warning) << "Error " << ec.value() << " when changing current directory";
}
std::filesystem::path WindowsPath::getUserConfigPath() const
{
std::filesystem::path userPath = std::filesystem::current_path();
WCHAR path[MAX_PATH + 1] = {};
if (SUCCEEDED(SHGetFolderPathW(nullptr, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, nullptr, 0, path)))
{
userPath = std::filesystem::path(path);
}
return userPath / "My Games" / mName;
}
std::filesystem::path WindowsPath::getUserDataPath() const
{
// Have some chaos, windows people!
return getUserConfigPath();
}
std::filesystem::path WindowsPath::getGlobalConfigPath() const
{
std::filesystem::path globalPath = std::filesystem::current_path();
WCHAR path[MAX_PATH + 1] = {};
if (SUCCEEDED(SHGetFolderPathW(nullptr, CSIDL_PROGRAM_FILES | CSIDL_FLAG_CREATE, nullptr, 0, path)))
{
globalPath = std::filesystem::path(path);
}
return globalPath / mName;
}
std::filesystem::path WindowsPath::getLocalPath() const
{
std::filesystem::path localPath = std::filesystem::current_path() / "";
WCHAR path[MAX_PATH + 1] = {};
if (GetModuleFileNameW(nullptr, path, MAX_PATH + 1) > 0)
{
localPath = std::filesystem::path(path).parent_path() / "";
}
// lookup exe path
return localPath;
}
std::filesystem::path WindowsPath::getGlobalDataPath() const
{
return getGlobalConfigPath();
}
std::filesystem::path WindowsPath::getCachePath() const
{
return getUserConfigPath() / "cache";
}
std::filesystem::path WindowsPath::getInstallPath() const
{
std::filesystem::path installPath{};
if (HKEY hKey; RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Bethesda Softworks\\Morrowind", 0,
KEY_READ | KEY_WOW64_32KEY, &hKey)
== ERROR_SUCCESS)
{
// Key existed, let's try to read the install dir
std::array<wchar_t, 512> buf{};
DWORD len = static_cast<DWORD>(buf.size() * sizeof(wchar_t));
if (RegQueryValueExW(hKey, L"Installed Path", nullptr, nullptr, reinterpret_cast<LPBYTE>(buf.data()), &len)
== ERROR_SUCCESS)
{
installPath = std::filesystem::path(buf.data());
}
RegCloseKey(hKey);
}
return installPath;
}
} /* namespace Files */
#endif /* defined(_WIN32) || defined(__WINDOWS__) */
| 3,151
|
C++
|
.cpp
| 90
| 27.5
| 119
| 0.60653
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,613
|
qtconversion.cpp
|
OpenMW_openmw/components/files/qtconversion.cpp
|
#include "qtconversion.hpp"
#include <components/misc/strings/conversion.hpp>
QString Files::pathToQString(const std::filesystem::path& path)
{
const auto tmp = path.u8string();
return QString::fromUtf8(Misc::StringUtils::u8StringToString(tmp.data()), tmp.size());
}
QString Files::pathToQString(std::filesystem::path&& path)
{
const auto tmp = path.u8string();
return QString::fromUtf8(Misc::StringUtils::u8StringToString(tmp.data()), tmp.size());
}
std::filesystem::path Files::pathFromQString(QStringView path)
{
const auto tmp = path.toUtf8();
return std::filesystem::path{ Misc::StringUtils::stringToU8String(tmp) };
}
std::filesystem::path Files::pathFromQString(QString&& path)
{
const auto tmp = path.toUtf8();
return std::filesystem::path{ Misc::StringUtils::stringToU8String(tmp) };
}
| 833
|
C++
|
.cpp
| 22
| 35.136364
| 90
| 0.742857
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,614
|
conversion.cpp
|
OpenMW_openmw/components/files/conversion.cpp
|
#include "conversion.hpp"
#include <components/misc/strings/conversion.hpp>
std::string Files::pathToUnicodeString(const std::filesystem::path& path)
{
return Misc::StringUtils::u8StringToString(path.u8string());
}
std::string Files::pathToUnicodeString(std::filesystem::path&& path)
{
return Misc::StringUtils::u8StringToString(path.u8string());
}
std::filesystem::path Files::pathFromUnicodeString(std::string_view path)
{
return Misc::StringUtils::stringToU8String(path);
}
std::filesystem::path Files::pathFromUnicodeString(std::string&& path)
{
return Misc::StringUtils::stringToU8String(std::move(path));
}
std::filesystem::path Files::pathFromUnicodeString(const char* path)
{
return Misc::StringUtils::stringToU8String(path);
}
| 763
|
C++
|
.cpp
| 22
| 32.454545
| 73
| 0.782016
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,615
|
collections.cpp
|
OpenMW_openmw/components/files/collections.cpp
|
#include "collections.hpp"
#include "conversion.hpp"
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/lower.hpp>
namespace Files
{
Collections::Collections()
: mDirectories()
, mCollections()
{
}
Collections::Collections(const Files::PathContainer& directories)
: mDirectories(directories)
, mCollections()
{
}
const MultiDirCollection& Collections::getCollection(const std::string& extension) const
{
std::string ext = Misc::StringUtils::lowerCase(extension);
auto iter = mCollections.find(ext);
if (iter == mCollections.end())
{
std::pair<MultiDirCollectionContainer::iterator, bool> result
= mCollections.emplace(ext, MultiDirCollection(mDirectories, ext));
iter = result.first;
}
return iter->second;
}
std::filesystem::path Collections::getPath(const std::string& file) const
{
for (auto iter = mDirectories.rbegin(); iter != mDirectories.rend(); iter++)
{
for (const auto& iter2 : std::filesystem::directory_iterator(*iter))
{
const auto& path = iter2.path();
const auto str = Files::pathToUnicodeString(path.filename());
if (Misc::StringUtils::ciEqual(file, str))
return path;
}
}
throw std::runtime_error("file " + file + " not found");
}
bool Collections::doesExist(const std::string& file) const
{
for (auto iter = mDirectories.rbegin(); iter != mDirectories.rend(); iter++)
{
for (const auto& iter2 : std::filesystem::directory_iterator(*iter))
{
const auto& path = iter2.path();
const auto str = Files::pathToUnicodeString(path.filename());
if (Misc::StringUtils::ciEqual(file, str))
return true;
}
}
return false;
}
const Files::PathContainer& Collections::getPaths() const
{
return mDirectories;
}
}
| 2,133
|
C++
|
.cpp
| 61
| 26.016393
| 92
| 0.593006
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,616
|
androidpath.cpp
|
OpenMW_openmw/components/files/androidpath.cpp
|
#include "androidpath.hpp"
#if defined(__ANDROID__)
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <jni.h>
#include <pwd.h>
#include <unistd.h>
static const char* g_path_global; //< Path to global directory root, e.g. /data/data/com.libopenmw.openmw
static const char* g_path_user; //< Path to user root, e.g. /sdcard/Android/data/com.libopenmw.openmw
/**
* \brief Called by java code to set up directory paths
*/
extern "C" JNIEXPORT void JNICALL Java_ui_activity_GameActivity_getPathToJni(
JNIEnv* env, jobject obj, jstring global, jstring user)
{
g_path_global = env->GetStringUTFChars(global, nullptr);
g_path_user = env->GetStringUTFChars(user, nullptr);
}
namespace Files
{
AndroidPath::AndroidPath(const std::string& application_name) {}
// /sdcard/Android/data/com.libopenmw.openmw/config
std::filesystem::path AndroidPath::getUserConfigPath() const
{
return std::filesystem::path(g_path_user) / "config";
}
// /sdcard/Android/data/com.libopenmw.openmw/
// (so that saves are placed at /sdcard/Android/data/com.libopenmw.openmw/saves)
std::filesystem::path AndroidPath::getUserDataPath() const
{
return std::filesystem::path(g_path_user);
}
// /data/data/com.libopenmw.openmw/cache
// (supposed to be "official" android cache location)
std::filesystem::path AndroidPath::getCachePath() const
{
return std::filesystem::path(g_path_global) / "cache";
}
// /data/data/com.libopenmw.openmw/files/config
// (note the addition of "files")
std::filesystem::path AndroidPath::getGlobalConfigPath() const
{
return std::filesystem::path(g_path_global) / "files" / "config";
}
std::filesystem::path AndroidPath::getLocalPath() const
{
return std::filesystem::path("./");
}
// /sdcard/Android/data/com.libopenmw.openmw
// (so that the data is at /sdcard/Android/data/com.libopenmw.openmw/data)
std::filesystem::path AndroidPath::getGlobalDataPath() const
{
return std::filesystem::path(g_path_user);
}
std::filesystem::path AndroidPath::getInstallPath() const
{
return std::filesystem::path();
}
} /* namespace Files */
#endif /* defined(__Android__) */
| 2,281
|
C++
|
.cpp
| 61
| 32.967213
| 105
| 0.694785
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,617
|
configfileparser.cpp
|
OpenMW_openmw/components/files/configfileparser.cpp
|
// This file's contents is largely lifted from boost::program_options with only minor modification.
// Its original preamble (without updated dates) from those source files is below:
// Copyright Vladimir Prus 2002-2004.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "configfileparser.hpp"
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/detail/convert.hpp>
namespace Files
{
namespace
{
/** Standalone parser for config files in ini-line format.
The parser is a model of single-pass lvalue iterator, and
default constructor creates past-the-end-iterator. The typical usage is:
config_file_iterator i(is, ... set of options ...), e;
for(; i !=e; ++i) {
*i;
}
Syntax conventions:
- config file can not contain positional options
- '#' is comment character: it is ignored together with
the rest of the line.
- variable assignments are in the form
name '=' value.
spaces around '=' are trimmed.
- Section names are given in brackets.
The actual option name is constructed by combining current section
name and specified option name, with dot between. If section_name
already contains dot at the end, new dot is not inserted. For example:
@verbatim
[gui.accessibility]
visual_bell=yes
@endverbatim
will result in option "gui.accessibility.visual_bell" with value
"yes" been returned.
TODO: maybe, we should just accept a pointer to options_description
class.
*/
class common_config_file_iterator : public boost::eof_iterator<common_config_file_iterator, bpo::option>
{
public:
common_config_file_iterator() { found_eof(); }
common_config_file_iterator(const std::set<std::string>& allowed_options, bool allow_unregistered = false);
virtual ~common_config_file_iterator() {}
public: // Method required by eof_iterator
void get();
#if BOOST_WORKAROUND(_MSC_VER, <= 1900)
void decrement() {}
void advance(difference_type) {}
#endif
protected: // Stubs for derived classes
// Obtains next line from the config file
// Note: really, this design is a bit ugly
// The most clean thing would be to pass 'line_iterator' to
// constructor of this class, but to avoid templating this class
// we'd need polymorphic iterator, which does not exist yet.
virtual bool getline(std::string&)
{
return false;
}
protected:
/** Adds another allowed option. If the 'name' ends with
'*', then all options with the same prefix are
allowed. For example, if 'name' is 'foo*', then 'foo1' and
'foo_bar' are allowed. */
void add_option(const char* name);
// Returns true if 's' is a registered option name.
bool allowed_option(const std::string& s) const;
// That's probably too much data for iterator, since
// it will be copied, but let's not bother for now.
std::set<std::string> allowed_options;
// Invariant: no element is prefix of other element.
std::set<std::string> allowed_prefixes;
std::string m_prefix;
bool m_allow_unregistered = false;
};
common_config_file_iterator::common_config_file_iterator(
const std::set<std::string>& allowed_options, bool allow_unregistered)
: allowed_options(allowed_options)
, m_allow_unregistered(allow_unregistered)
{
for (std::set<std::string>::const_iterator i = allowed_options.begin(); i != allowed_options.end(); ++i)
{
add_option(i->c_str());
}
}
void common_config_file_iterator::add_option(const char* name)
{
std::string s(name);
assert(!s.empty());
if (*s.rbegin() == '*')
{
s.resize(s.size() - 1);
bool bad_prefixes(false);
// If 's' is a prefix of one of allowed suffix, then
// lower_bound will return that element.
// If some element is prefix of 's', then lower_bound will
// return the next element.
std::set<std::string>::iterator i = allowed_prefixes.lower_bound(s);
if (i != allowed_prefixes.end())
{
if (i->find(s) == 0)
bad_prefixes = true;
}
if (i != allowed_prefixes.begin())
{
--i;
if (s.find(*i) == 0)
bad_prefixes = true;
}
if (bad_prefixes)
boost::throw_exception(
bpo::error("options '" + std::string(name) + "' and '" + *i
+ "*' will both match the same "
"arguments from the configuration file"));
allowed_prefixes.insert(s);
}
}
std::string trim_ws(const std::string& s)
{
std::string::size_type n, n2;
n = s.find_first_not_of(" \t\r\n");
if (n == std::string::npos)
return std::string();
else
{
n2 = s.find_last_not_of(" \t\r\n");
return s.substr(n, n2 - n + 1);
}
}
void common_config_file_iterator::get()
{
std::string s;
std::string::size_type n;
bool found = false;
while (this->getline(s))
{
// strip '#' comments and whitespace
if (s.find('#') == s.find_first_not_of(" \t\r\n"))
continue;
s = trim_ws(s);
if (!s.empty())
{
// Handle section name
if (*s.begin() == '[' && *s.rbegin() == ']')
{
m_prefix = s.substr(1, s.size() - 2);
if (*m_prefix.rbegin() != '.')
m_prefix += '.';
}
else if ((n = s.find('=')) != std::string::npos)
{
std::string name = m_prefix + trim_ws(s.substr(0, n));
std::string value = trim_ws(s.substr(n + 1));
bool registered = allowed_option(name);
if (!registered && !m_allow_unregistered)
boost::throw_exception(bpo::unknown_option(name));
found = true;
this->value().string_key = name;
this->value().value.clear();
this->value().value.push_back(value);
this->value().unregistered = !registered;
this->value().original_tokens.clear();
this->value().original_tokens.push_back(name);
this->value().original_tokens.push_back(value);
break;
}
else
{
boost::throw_exception(
bpo::invalid_config_file_syntax(s, bpo::invalid_syntax::unrecognized_line));
}
}
}
if (!found)
found_eof();
}
bool common_config_file_iterator::allowed_option(const std::string& s) const
{
std::set<std::string>::const_iterator i = allowed_options.find(s);
if (i != allowed_options.end())
return true;
// If s is "pa" where "p" is allowed prefix then
// lower_bound should find the element after "p".
// This depends on 'allowed_prefixes' invariant.
i = allowed_prefixes.lower_bound(s);
if (i != allowed_prefixes.begin() && s.find(*--i) == 0)
return true;
return false;
}
template <class charT>
class basic_config_file_iterator : public Files::common_config_file_iterator
{
public:
basic_config_file_iterator() { found_eof(); }
/** Creates a config file parser for the specified stream.
*/
basic_config_file_iterator(std::basic_istream<charT>& is, const std::set<std::string>& allowed_options,
bool allow_unregistered = false);
private: // base overrides
bool getline(std::string&);
private: // internal data
std::shared_ptr<std::basic_istream<charT>> is;
};
template <class charT>
basic_config_file_iterator<charT>::basic_config_file_iterator(
std::basic_istream<charT>& is, const std::set<std::string>& allowed_options, bool allow_unregistered)
: common_config_file_iterator(allowed_options, allow_unregistered)
{
this->is.reset(&is, bpo::detail::null_deleter());
get();
}
template <class charT>
bool basic_config_file_iterator<charT>::getline(std::string& s)
{
std::basic_string<charT> in;
if (std::getline(*is, in))
{
s = bpo::to_internal(in);
return true;
}
else
{
return false;
}
}
}
template <class charT>
bpo::basic_parsed_options<charT> parse_config_file(
std::basic_istream<charT>& is, const bpo::options_description& desc, bool allow_unregistered)
{
std::set<std::string> allowed_options;
const std::vector<boost::shared_ptr<bpo::option_description>>& options = desc.options();
for (unsigned i = 0; i < options.size(); ++i)
{
const bpo::option_description& d = *options[i];
if (d.long_name().empty())
boost::throw_exception(
bpo::error("abbreviated option names are not permitted in options configuration files"));
allowed_options.insert(d.long_name());
}
// Parser return char strings
bpo::parsed_options result(&desc);
copy(basic_config_file_iterator<charT>(is, allowed_options, allow_unregistered),
basic_config_file_iterator<charT>(), back_inserter(result.options));
// Convert char strings into desired type.
return bpo::basic_parsed_options<charT>(result);
}
template bpo::basic_parsed_options<char> parse_config_file(
std::basic_istream<char>& is, const bpo::options_description& desc, bool allow_unregistered);
}
| 11,266
|
C++
|
.cpp
| 253
| 30.766798
| 119
| 0.52328
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,618
|
configurationmanager.cpp
|
OpenMW_openmw/components/files/configurationmanager.cpp
|
#include "configurationmanager.hpp"
#include <fstream>
#include <components/debug/debuglog.hpp>
#include <components/fallback/validate.hpp>
#include <components/files/configfileparser.hpp>
#include <components/misc/strings/conversion.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
/**
* \namespace Files
*/
namespace Files
{
namespace bpo = boost::program_options;
#if defined(_WIN32) || defined(__WINDOWS__)
static const char* const applicationName = "OpenMW";
#else
static const char* const applicationName = "openmw";
#endif
static constexpr auto localToken = u8"?local?";
static constexpr auto userConfigToken = u8"?userconfig?";
static constexpr auto userDataToken = u8"?userdata?";
static constexpr auto globalToken = u8"?global?";
ConfigurationManager::ConfigurationManager(bool silent)
: mFixedPath(applicationName)
, mSilent(silent)
{
setupTokensMapping();
// Initialize with fixed paths, will be overridden in `readConfiguration`.
mUserDataPath = mFixedPath.getUserDataPath();
mScreenshotPath = mFixedPath.getUserDataPath() / "screenshots";
}
ConfigurationManager::~ConfigurationManager() {}
void ConfigurationManager::setupTokensMapping()
{
mTokensMapping.insert(std::make_pair(localToken, &FixedPath<>::getLocalPath));
mTokensMapping.insert(std::make_pair(userConfigToken, &FixedPath<>::getUserConfigPath));
mTokensMapping.insert(std::make_pair(userDataToken, &FixedPath<>::getUserDataPath));
mTokensMapping.insert(std::make_pair(globalToken, &FixedPath<>::getGlobalDataPath));
}
static bool hasReplaceConfig(const bpo::variables_map& variables)
{
if (variables["replace"].empty())
return false;
for (const std::string& var : variables["replace"].as<std::vector<std::string>>())
{
if (var == "config")
return true;
}
return false;
}
void ConfigurationManager::readConfiguration(
bpo::variables_map& variables, const bpo::options_description& description, bool quiet)
{
bool silent = mSilent;
mSilent = quiet;
// ensure defaults are present
bpo::store(bpo::parsed_options(&description), variables);
std::optional<bpo::variables_map> config = loadConfig(mFixedPath.getLocalPath(), description);
if (config)
mActiveConfigPaths.push_back(mFixedPath.getLocalPath());
else
{
mActiveConfigPaths.push_back(mFixedPath.getGlobalConfigPath());
config = loadConfig(mFixedPath.getGlobalConfigPath(), description);
}
if (!config)
{
if (!quiet)
Log(Debug::Error) << "Neither local config nor global config are available.";
mSilent = silent;
return;
}
std::stack<std::filesystem::path> extraConfigDirs;
addExtraConfigDirs(extraConfigDirs, variables);
if (!hasReplaceConfig(variables))
addExtraConfigDirs(extraConfigDirs, *config);
std::vector<bpo::variables_map> parsedConfigs{ *std::move(config) };
std::set<std::filesystem::path>
alreadyParsedPaths; // needed to prevent infinite loop in case of a circular link
alreadyParsedPaths.insert(mActiveConfigPaths.front());
while (!extraConfigDirs.empty())
{
auto path = extraConfigDirs.top();
extraConfigDirs.pop();
if (alreadyParsedPaths.count(path) > 0)
{
if (!quiet)
Log(Debug::Warning) << "Repeated config dir: " << path;
continue;
}
alreadyParsedPaths.insert(path);
config = loadConfig(path, description);
if (config && hasReplaceConfig(*config) && parsedConfigs.size() > 1)
{
mActiveConfigPaths.resize(1);
parsedConfigs.resize(1);
Log(Debug::Info) << "Skipping previous configs except " << (mActiveConfigPaths.front() / "openmw.cfg")
<< " due to replace=config in " << (path / "openmw.cfg");
}
mActiveConfigPaths.emplace_back(std::move(path));
if (config)
{
addExtraConfigDirs(extraConfigDirs, *config);
parsedConfigs.push_back(*std::move(config));
}
}
for (auto it = parsedConfigs.rbegin(); it != parsedConfigs.rend(); ++it)
{
auto composingVariables = separateComposingVariables(variables, description);
for (auto& [k, v] : *it)
{
auto variable = variables.find(k);
if (variable == variables.end())
variables.insert({ k, v });
else if (variable->second.defaulted())
variable->second = v;
}
mergeComposingVariables(variables, composingVariables, description);
}
mUserDataPath = variables["user-data"]
.as<Files::MaybeQuotedPath>()
.u8string(); // This call to u8string is redundant, but required to build on MSVC 14.26 due
// to implementation bugs.
if (mUserDataPath.empty())
{
if (!quiet)
Log(Debug::Warning) << "Error: `user-data` is not specified";
mUserDataPath = mFixedPath.getUserDataPath();
}
mScreenshotPath = mUserDataPath / "screenshots";
std::filesystem::create_directories(getUserConfigPath());
std::filesystem::create_directories(mScreenshotPath);
// probably not necessary but validate the creation of the screenshots directory and fallback to the original
// behavior if it fails
if (!std::filesystem::is_directory(mScreenshotPath))
mScreenshotPath = mUserDataPath;
if (!quiet)
{
Log(Debug::Info) << "Logs dir: " << getUserConfigPath();
Log(Debug::Info) << "User data dir: " << mUserDataPath;
Log(Debug::Info) << "Screenshots dir: " << mScreenshotPath;
}
mSilent = silent;
}
void ConfigurationManager::addExtraConfigDirs(
std::stack<std::filesystem::path>& dirs, const bpo::variables_map& variables) const
{
auto configIt = variables.find("config");
if (configIt == variables.end())
return;
Files::PathContainer newDirs = asPathContainer(configIt->second.as<Files::MaybeQuotedPathContainer>());
for (auto it = newDirs.rbegin(); it != newDirs.rend(); ++it)
dirs.push(*it);
}
void ConfigurationManager::addCommonOptions(bpo::options_description& description)
{
auto addOption = description.add_options();
addOption("config",
bpo::value<Files::MaybeQuotedPathContainer>()
->default_value(Files::MaybeQuotedPathContainer(), "")
->multitoken()
->composing(),
"additional config directories");
addOption("replace",
bpo::value<std::vector<std::string>>()
->default_value(std::vector<std::string>(), "")
->multitoken()
->composing(),
"settings where the values from the current source should replace those from lower-priority sources "
"instead of being appended");
addOption("user-data", bpo::value<Files::MaybeQuotedPath>()->default_value(Files::MaybeQuotedPath(), ""),
"set user data directory (used for saves, screenshots, etc)");
addOption("resources",
boost::program_options::value<Files::MaybeQuotedPath>()->default_value(
Files::MaybeQuotedPath(), "resources"),
"set resources directory");
}
bpo::variables_map separateComposingVariables(
bpo::variables_map& variables, const bpo::options_description& description)
{
bpo::variables_map composingVariables;
for (auto itr = variables.begin(); itr != variables.end();)
{
if (description.find(itr->first, false).semantic()->is_composing())
{
composingVariables.emplace(*itr);
itr = variables.erase(itr);
}
else
++itr;
}
return composingVariables;
}
void mergeComposingVariables(
bpo::variables_map& first, bpo::variables_map& second, const bpo::options_description& description)
{
// There are a few places this assumes all variables are present in second, but it's never crashed in the wild,
// so it looks like that's guaranteed.
std::set<std::string> replacedVariables;
if (description.find_nothrow("replace", false))
{
auto replace = second["replace"];
if (!replace.defaulted() && !replace.empty())
{
std::vector<std::string> replaceVector = replace.as<std::vector<std::string>>();
replacedVariables.insert(replaceVector.begin(), replaceVector.end());
}
}
for (const auto& option : description.options())
{
if (option->semantic()->is_composing())
{
std::string name = option->canonical_display_name();
auto firstPosition = first.find(name);
if (firstPosition == first.end())
{
first.emplace(name, second[name]);
continue;
}
if (replacedVariables.count(name) || firstPosition->second.defaulted() || firstPosition->second.empty())
{
firstPosition->second = second[name];
continue;
}
if (second[name].defaulted() || second[name].empty())
continue;
boost::any& firstValue = firstPosition->second.value();
const boost::any& secondValue = second[name].value();
if (firstValue.type() == typeid(Files::MaybeQuotedPathContainer))
{
auto& firstPathContainer = boost::any_cast<Files::MaybeQuotedPathContainer&>(firstValue);
const auto& secondPathContainer
= boost::any_cast<const Files::MaybeQuotedPathContainer&>(secondValue);
firstPathContainer.insert(
firstPathContainer.end(), secondPathContainer.begin(), secondPathContainer.end());
}
else if (firstValue.type() == typeid(std::vector<std::string>))
{
auto& firstVector = boost::any_cast<std::vector<std::string>&>(firstValue);
const auto& secondVector = boost::any_cast<const std::vector<std::string>&>(secondValue);
firstVector.insert(firstVector.end(), secondVector.begin(), secondVector.end());
}
else if (firstValue.type() == typeid(Fallback::FallbackMap))
{
auto& firstMap = boost::any_cast<Fallback::FallbackMap&>(firstValue);
const auto& secondMap = boost::any_cast<const Fallback::FallbackMap&>(secondValue);
std::map<std::string, std::string> tempMap(secondMap.mMap);
tempMap.merge(firstMap.mMap);
firstMap.mMap.swap(tempMap);
}
else
Log(Debug::Error)
<< "Unexpected composing variable type. Curse boost and their blasted arcane templates.";
}
}
}
void ConfigurationManager::processPath(std::filesystem::path& path, const std::filesystem::path& basePath) const
{
const auto str = path.u8string();
if (str.empty() || str[0] != u8'?')
{
if (!path.is_absolute())
path = basePath / path;
return;
}
const auto pos = str.find('?', 1);
if (pos != std::u8string::npos && pos != 0)
{
auto tokenIt = mTokensMapping.find(str.substr(0, pos + 1));
if (tokenIt != mTokensMapping.end())
{
auto tempPath(((mFixedPath).*(tokenIt->second))());
if (pos < str.length() - 1)
{
// There is something after the token, so we should
// append it to the path
tempPath /= str.substr(pos + 1, str.length() - pos);
}
path = std::move(tempPath);
}
else
{
if (!mSilent)
Log(Debug::Warning) << "Path starts with unknown token: " << path;
path.clear();
}
}
}
void ConfigurationManager::processPaths(Files::PathContainer& dataDirs, const std::filesystem::path& basePath) const
{
for (auto& path : dataDirs)
processPath(path, basePath);
}
void ConfigurationManager::processPaths(
boost::program_options::variables_map& variables, const std::filesystem::path& basePath) const
{
for (auto& [name, var] : variables)
{
if (var.defaulted())
continue;
if (var.value().type() == typeid(MaybeQuotedPathContainer))
{
auto& pathContainer = boost::any_cast<MaybeQuotedPathContainer&>(var.value());
for (MaybeQuotedPath& path : pathContainer)
processPath(path, basePath);
}
else if (var.value().type() == typeid(MaybeQuotedPath))
{
std::filesystem::path& path = boost::any_cast<Files::MaybeQuotedPath&>(var.value());
processPath(path, basePath);
}
}
}
void ConfigurationManager::filterOutNonExistingPaths(Files::PathContainer& dataDirs) const
{
dataDirs.erase(std::remove_if(dataDirs.begin(), dataDirs.end(),
[this](const std::filesystem::path& p) {
bool exists = std::filesystem::is_directory(p);
if (!exists && !mSilent)
Log(Debug::Warning) << "No such dir: " << p;
return !exists;
}),
dataDirs.end());
}
std::optional<bpo::variables_map> ConfigurationManager::loadConfig(
const std::filesystem::path& path, const bpo::options_description& description) const
{
std::filesystem::path cfgFile(path);
cfgFile /= openmwCfgFile;
if (std::filesystem::is_regular_file(cfgFile))
{
if (!mSilent)
Log(Debug::Info) << "Loading config file: " << cfgFile;
std::ifstream configFileStream(cfgFile);
if (configFileStream.is_open())
{
bpo::variables_map variables;
bpo::store(Files::parse_config_file(configFileStream, description, true), variables);
processPaths(variables, path);
return variables;
}
else if (!mSilent)
Log(Debug::Error) << "Loading failed.";
}
return std::nullopt;
}
const std::filesystem::path& ConfigurationManager::getGlobalPath() const
{
return mFixedPath.getGlobalConfigPath();
}
const std::filesystem::path& ConfigurationManager::getUserConfigPath() const
{
if (mActiveConfigPaths.empty())
return mFixedPath.getUserConfigPath();
else
return mActiveConfigPaths.back();
}
const std::filesystem::path& ConfigurationManager::getUserDataPath() const
{
return mUserDataPath;
}
const std::filesystem::path& ConfigurationManager::getLocalPath() const
{
return mFixedPath.getLocalPath();
}
const std::filesystem::path& ConfigurationManager::getCachePath() const
{
return mFixedPath.getCachePath();
}
const std::filesystem::path& ConfigurationManager::getInstallPath() const
{
return mFixedPath.getInstallPath();
}
const std::filesystem::path& ConfigurationManager::getScreenshotPath() const
{
return mScreenshotPath;
}
void parseArgs(
int argc, const char* const argv[], bpo::variables_map& variables, const bpo::options_description& description)
{
bpo::store(bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run(), variables);
}
void parseConfig(std::istream& stream, bpo::variables_map& variables, const bpo::options_description& description)
{
bpo::store(Files::parse_config_file(stream, description, true), variables);
}
std::istream& operator>>(std::istream& istream, MaybeQuotedPath& MaybeQuotedPath)
{
// If the stream starts with a double quote, read from stream using boost::filesystem::path rules (which are not
// the same as std::filesystem::path rules), then discard anything remaining. This prevents
// boost::program_options getting upset that we've not consumed the whole stream. If it doesn't start with a
// double quote, read the whole thing verbatim.
// This function's implementation and comments have a history of being changed by well-meaning but incorrect
// OpenMW developers. Please be very careful you aren't joining them. If you're insufficiently apprehensive,
// here's a 737-word GitLab comment to scare you:
// https://gitlab.com/OpenMW/openmw/-/merge_requests/2979#note_1371082428.
if (istream.peek() == '"')
{
std::string intermediate;
// std::filesystem::path would use '"', '\' here.
// We use & because it's easier when copying and pasting Windows paths, which have many backslashes and few
// ampersands, and because it's backwards-compatible with the previous format, which used
// boost::filesystem::path's operator>>.
istream >> std::quoted(intermediate, '"', '&');
static_cast<std::filesystem::path&>(MaybeQuotedPath) = Misc::StringUtils::stringToU8String(intermediate);
if (istream && !istream.eof() && istream.peek() != EOF)
{
std::string remainder{ std::istreambuf_iterator(istream), {} };
Log(Debug::Warning) << "Trailing data in path setting. Used '" << MaybeQuotedPath << "' but '"
<< remainder << "' remained";
}
}
else
{
std::string intermediate{ std::istreambuf_iterator(istream), {} };
static_cast<std::filesystem::path&>(MaybeQuotedPath) = Misc::StringUtils::stringToU8String(intermediate);
}
return istream;
}
PathContainer asPathContainer(const MaybeQuotedPathContainer& MaybeQuotedPathContainer)
{
PathContainer res;
res.reserve(MaybeQuotedPathContainer.size());
for (const auto& maybeQuotedPath : MaybeQuotedPathContainer)
{
res.emplace_back(maybeQuotedPath.u8string()); // This call to u8string is redundant, but required to build
// on MSVC 14.26 due to implementation bugs.
}
return res;
}
} /* namespace Files */
| 19,725
|
C++
|
.cpp
| 432
| 33.93287
| 120
| 0.587627
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,619
|
openfile.cpp
|
OpenMW_openmw/components/files/openfile.cpp
|
#include "openfile.hpp"
#include "conversion.hpp"
#include <cstring>
#include <fstream>
namespace Files
{
std::unique_ptr<std::ifstream> openBinaryInputFileStream(const std::filesystem::path& path)
{
auto stream = std::make_unique<std::ifstream>(path, std::ios::binary);
if (!stream->is_open())
throw std::system_error(errno, std::generic_category(),
"Failed to open '" + Files::pathToUnicodeString(path) + "' for reading");
stream->exceptions(std::ios::badbit);
return stream;
}
}
| 556
|
C++
|
.cpp
| 16
| 29.125
| 95
| 0.650558
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,620
|
hash.cpp
|
OpenMW_openmw/components/files/hash.cpp
|
#include "hash.hpp"
#include <extern/smhasher/MurmurHash3.h>
#include <array>
#include <cstdint>
#include <istream>
#include <string>
namespace Files
{
std::array<std::uint64_t, 2> getHash(std::string_view fileName, std::istream& stream)
{
std::array<std::uint64_t, 2> hash{ 0, 0 };
try
{
const auto start = stream.tellg();
const auto exceptions = stream.exceptions();
stream.exceptions(std::ios_base::badbit);
while (stream)
{
std::array<char, 4096> value;
stream.read(value.data(), value.size());
const std::streamsize read = stream.gcount();
if (read == 0)
break;
std::array<std::uint64_t, 2> blockHash{ 0, 0 };
MurmurHash3_x64_128(value.data(), static_cast<int>(read), hash.data(), blockHash.data());
hash = blockHash;
}
stream.clear();
stream.exceptions(exceptions);
stream.seekg(start);
}
catch (const std::exception& e)
{
std::string message = "Error while reading \"";
message += fileName;
message += "\" to get hash: ";
message += e.what();
throw std::runtime_error(message);
}
return hash;
}
}
| 1,383
|
C++
|
.cpp
| 42
| 22.904762
| 105
| 0.522422
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,621
|
constrainedfilestream.cpp
|
OpenMW_openmw/components/files/constrainedfilestream.cpp
|
#include <filesystem>
#include "constrainedfilestream.hpp"
namespace Files
{
IStreamPtr openConstrainedFileStream(const std::filesystem::path& filename, std::size_t start, std::size_t length)
{
return std::make_unique<ConstrainedFileStream>(
std::make_unique<ConstrainedFileStreamBuf>(filename, start, length));
}
}
| 350
|
C++
|
.cpp
| 10
| 30.6
| 118
| 0.739645
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,622
|
linuxpath.cpp
|
OpenMW_openmw/components/files/linuxpath.cpp
|
#include "linuxpath.hpp"
#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
#include <cstring>
#include <fstream>
#include <pwd.h>
#include <unistd.h>
#include <components/debug/debuglog.hpp>
#include <components/misc/strings/lower.hpp>
namespace
{
std::filesystem::path getUserHome()
{
const char* dir = getenv("HOME");
if (dir == nullptr)
{
struct passwd* pwd = getpwuid(getuid());
if (pwd != nullptr)
{
dir = pwd->pw_dir;
}
}
if (dir == nullptr)
return {};
else
return dir;
}
std::filesystem::path getEnv(const std::string& envVariable, const std::filesystem::path& fallback)
{
const char* result = getenv(envVariable.c_str());
if (!result)
return fallback;
std::filesystem::path dir(result);
if (dir.empty())
return fallback;
else
return dir;
}
}
/**
* \namespace Files
*/
namespace Files
{
LinuxPath::LinuxPath(const std::string& application_name)
: mName(application_name)
{
std::error_code ec;
current_path(getLocalPath(), ec);
const auto err = ec.value();
if (err != 0)
{
Log(Debug::Warning) << "Error " << err << " " << std::generic_category().message(errno)
<< " when changing current directory";
}
}
std::filesystem::path LinuxPath::getUserConfigPath() const
{
return getEnv("XDG_CONFIG_HOME", getUserHome() / ".config") / mName;
}
std::filesystem::path LinuxPath::getUserDataPath() const
{
return getEnv("XDG_DATA_HOME", getUserHome() / ".local/share") / mName;
}
std::filesystem::path LinuxPath::getCachePath() const
{
return getEnv("XDG_CACHE_HOME", getUserHome() / ".cache") / mName;
}
std::filesystem::path LinuxPath::getGlobalConfigPath() const
{
std::filesystem::path globalPath(GLOBAL_CONFIG_PATH);
return globalPath / mName;
}
std::filesystem::path LinuxPath::getLocalPath() const
{
auto localPath = std::filesystem::current_path() / "";
static const std::filesystem::path statusPaths[]
= { "/proc/self/exe", "/proc/self/file", "/proc/curproc/exe", "/proc/curproc/file" };
for (const auto& path : statusPaths)
{
std::error_code ec;
const auto binPath = read_symlink(path, ec);
if (ec.value() != -1)
{
localPath = binPath.parent_path() / "";
break;
}
}
return localPath;
}
std::filesystem::path LinuxPath::getGlobalDataPath() const
{
std::filesystem::path globalDataPath(GLOBAL_DATA_PATH);
return globalDataPath / mName;
}
std::filesystem::path LinuxPath::getInstallPath() const
{
std::filesystem::path installPath;
std::filesystem::path homePath = getUserHome();
if (!homePath.empty())
{
std::filesystem::path wineDefaultRegistry(homePath);
wineDefaultRegistry /= ".wine/system.reg";
if (std::filesystem::is_regular_file(wineDefaultRegistry))
{
std::ifstream file(wineDefaultRegistry);
bool isRegEntry = false;
std::string line;
std::string mwpath;
while (std::getline(file, line))
{
if (line[0] == '[') // we found an entry
{
if (isRegEntry)
{
break;
}
isRegEntry = (line.find("Softworks\\\\Morrowind]") != std::string::npos);
}
else if (isRegEntry)
{
if (line[0] == '"') // empty line means new registry key
{
std::string key = line.substr(1, line.find('"', 1) - 1);
if (strcasecmp(key.c_str(), "Installed Path") == 0)
{
std::string::size_type valuePos = line.find('=') + 2;
mwpath = line.substr(valuePos, line.rfind('"') - valuePos);
std::string::size_type pos = mwpath.find("\\");
while (pos != std::string::npos)
{
mwpath.replace(pos, 2, "/");
pos = mwpath.find("\\", pos + 1);
}
break;
}
}
}
}
if (!mwpath.empty())
{
// Change drive letter to lowercase, so we could use
// ~/.wine/dosdevices symlinks
mwpath[0] = Misc::StringUtils::toLower(mwpath[0]);
installPath /= homePath;
installPath /= ".wine/dosdevices/";
installPath /= mwpath;
if (!std::filesystem::is_directory(installPath))
{
installPath.clear();
}
}
}
}
return installPath;
}
} /* namespace Files */
#endif /* defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) */
| 5,716
|
C++
|
.cpp
| 157
| 23.522293
| 110
| 0.478756
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,623
|
locals.cpp
|
OpenMW_openmw/components/compiler/locals.cpp
|
#include "locals.hpp"
#include <algorithm>
#include <iterator>
#include <ostream>
#include <stdexcept>
#include <components/misc/strings/lower.hpp>
namespace Compiler
{
const std::vector<std::string>& Locals::get(char type) const
{
switch (type)
{
case 's':
return mShorts;
case 'l':
return mLongs;
case 'f':
return mFloats;
}
throw std::logic_error("Unknown variable type");
}
int Locals::searchIndex(char type, std::string_view name) const
{
const std::vector<std::string>& collection = get(type);
auto iter = std::find(collection.begin(), collection.end(), name);
if (iter == collection.end())
return -1;
return static_cast<int>(iter - collection.begin());
}
bool Locals::search(char type, std::string_view name) const
{
return searchIndex(type, name) != -1;
}
std::vector<std::string>& Locals::get(char type)
{
switch (type)
{
case 's':
return mShorts;
case 'l':
return mLongs;
case 'f':
return mFloats;
}
throw std::logic_error("Unknown variable type");
}
char Locals::getType(std::string_view name) const
{
if (search('s', name))
return 's';
if (search('l', name))
return 'l';
if (search('f', name))
return 'f';
return ' ';
}
int Locals::getIndex(std::string_view name) const
{
int index = searchIndex('s', name);
if (index != -1)
return index;
index = searchIndex('l', name);
if (index != -1)
return index;
return searchIndex('f', name);
}
void Locals::write(std::ostream& localFile) const
{
localFile << get('s').size() << ' ' << get('l').size() << ' ' << get('f').size() << std::endl;
std::copy(get('s').begin(), get('s').end(), std::ostream_iterator<std::string>(localFile, " "));
std::copy(get('l').begin(), get('l').end(), std::ostream_iterator<std::string>(localFile, " "));
std::copy(get('f').begin(), get('f').end(), std::ostream_iterator<std::string>(localFile, " "));
}
void Locals::declare(char type, std::string_view name)
{
get(type).push_back(Misc::StringUtils::lowerCase(name));
}
void Locals::clear()
{
get('s').clear();
get('l').clear();
get('f').clear();
}
}
| 2,596
|
C++
|
.cpp
| 84
| 22.619048
| 104
| 0.528537
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,624
|
quickfileparser.cpp
|
OpenMW_openmw/components/compiler/quickfileparser.cpp
|
#include "quickfileparser.hpp"
#include "scanner.hpp"
#include "skipparser.hpp"
Compiler::QuickFileParser::QuickFileParser(ErrorHandler& errorHandler, const Context& context, Locals& locals)
: Parser(errorHandler, context)
, mDeclarationParser(errorHandler, context, locals)
{
}
bool Compiler::QuickFileParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
return true;
}
bool Compiler::QuickFileParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (keyword == Scanner::K_end)
return false;
if (keyword == Scanner::K_short || keyword == Scanner::K_long || keyword == Scanner::K_float)
{
mDeclarationParser.reset();
scanner.putbackKeyword(keyword, loc);
scanner.scan(mDeclarationParser);
return true;
}
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
return true;
}
bool Compiler::QuickFileParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (code != Scanner::S_newline)
{
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
}
return true;
}
void Compiler::QuickFileParser::parseEOF(Scanner& scanner) {}
| 1,320
|
C++
|
.cpp
| 39
| 29.538462
| 110
| 0.714623
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,625
|
discardparser.cpp
|
OpenMW_openmw/components/compiler/discardparser.cpp
|
#include "discardparser.hpp"
#include "scanner.hpp"
namespace Compiler
{
DiscardParser::DiscardParser(ErrorHandler& errorHandler, const Context& context)
: Parser(errorHandler, context)
, mState(StartState)
{
}
bool DiscardParser::parseInt(int value, const TokenLoc& loc, Scanner& scanner)
{
if (mState == StartState || mState == MinusState)
{
if (isEmpty())
mTokenLoc = loc;
start();
return false;
}
return Parser::parseInt(value, loc, scanner);
}
bool DiscardParser::parseFloat(float value, const TokenLoc& loc, Scanner& scanner)
{
if (mState == StartState || mState == MinusState)
{
if (isEmpty())
mTokenLoc = loc;
start();
return false;
}
return Parser::parseFloat(value, loc, scanner);
}
bool DiscardParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
if (mState == StartState)
{
if (isEmpty())
mTokenLoc = loc;
start();
return false;
}
return Parser::parseName(name, loc, scanner);
}
bool DiscardParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (code == Scanner::S_minus && mState == StartState)
{
if (isEmpty())
mTokenLoc = loc;
start();
mState = MinusState;
return true;
}
return Parser::parseSpecial(code, loc, scanner);
}
void DiscardParser::reset()
{
mState = StartState;
mTokenLoc = TokenLoc();
Parser::reset();
}
const TokenLoc& DiscardParser::getTokenLoc() const
{
return mTokenLoc;
}
}
| 1,856
|
C++
|
.cpp
| 65
| 19.907692
| 97
| 0.557497
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,626
|
opcodes.cpp
|
OpenMW_openmw/components/compiler/opcodes.cpp
|
#include "opcodes.hpp"
namespace Compiler::Control
{
const char* controls[numberOfControls] = { "playercontrols", "playerfighting", "playerjumping", "playerlooking",
"playermagic", "playerviewswitch", "vanitymode" };
}
| 232
|
C++
|
.cpp
| 6
| 35.5
| 116
| 0.733333
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,627
|
lineparser.cpp
|
OpenMW_openmw/components/compiler/lineparser.cpp
|
#include "lineparser.hpp"
#include <memory>
#include <components/esm/refid.hpp>
#include <components/misc/strings/lower.hpp>
#include "context.hpp"
#include "declarationparser.hpp"
#include "errorhandler.hpp"
#include "extensions.hpp"
#include "generator.hpp"
#include "locals.hpp"
#include "scanner.hpp"
#include "skipparser.hpp"
namespace Compiler
{
void LineParser::parseExpression(Scanner& scanner, const TokenLoc& loc)
{
mExprParser.reset();
if (!mExplicit.empty())
{
mExprParser.parseName(mExplicit, loc, scanner);
if (mState == MemberState)
mExprParser.parseSpecial(Scanner::S_member, loc, scanner);
else
mExprParser.parseSpecial(Scanner::S_ref, loc, scanner);
}
scanner.scan(mExprParser);
char type = mExprParser.append(mCode);
mState = EndState;
switch (type)
{
case 'l':
Generator::report(mCode, mLiterals, "%d");
break;
case 'f':
Generator::report(mCode, mLiterals, "%f");
break;
default:
throw std::runtime_error("Unknown expression result type");
}
}
LineParser::LineParser(ErrorHandler& errorHandler, const Context& context, Locals& locals, Literals& literals,
std::vector<Interpreter::Type_Code>& code, bool allowExpression)
: Parser(errorHandler, context)
, mLocals(locals)
, mLiterals(literals)
, mCode(code)
, mState(BeginState)
, mReferenceMember(false)
, mButtons(0)
, mType(0)
, mExprParser(errorHandler, context, locals, literals)
, mAllowExpression(allowExpression)
{
}
bool LineParser::parseInt(int value, const TokenLoc& loc, Scanner& scanner)
{
if (mAllowExpression && mState == BeginState)
{
scanner.putbackInt(value, loc);
parseExpression(scanner, loc);
return true;
}
else if (mState == SetState)
{
// Allow ints to be used as variable names
return parseName(loc.mLiteral, loc, scanner);
}
return Parser::parseInt(value, loc, scanner);
}
bool LineParser::parseFloat(float value, const TokenLoc& loc, Scanner& scanner)
{
if (mAllowExpression && mState == BeginState)
{
scanner.putbackFloat(value, loc);
parseExpression(scanner, loc);
return true;
}
return Parser::parseFloat(value, loc, scanner);
}
bool LineParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
if (mState == SetState)
{
std::string name2 = Misc::StringUtils::lowerCase(name);
mName = name2;
// local variable?
char type = mLocals.getType(name2);
if (type != ' ')
{
mType = type;
mState = SetLocalVarState;
return true;
}
type = getContext().getGlobalType(name2);
if (type != ' ')
{
mType = type;
mState = SetGlobalVarState;
return true;
}
mState = SetPotentialMemberVarState;
return true;
}
if (mState == SetMemberVarState)
{
mMemberName = Misc::StringUtils::lowerCase(name);
std::pair<char, bool> type = getContext().getMemberType(mMemberName, ESM::RefId::stringRefId(mName));
if (type.first != ' ')
{
mState = SetMemberVarState2;
mType = type.first;
mReferenceMember = type.second;
return true;
}
getErrorHandler().error("Unknown variable", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
return false;
}
if (mState == MessageState)
{
GetArgumentsFromMessageFormat processor;
processor.process(name);
std::string arguments = processor.getArguments();
if (!arguments.empty())
{
mExprParser.reset();
mExprParser.parseArguments(arguments, scanner, mCode, -1, true);
}
mName = name;
mButtons = 0;
mState = MessageButtonState;
return true;
}
if (mState == MessageButtonState)
{
Generator::pushString(mCode, mLiterals, name);
mState = MessageButtonState;
++mButtons;
return true;
}
if (mState == BeginState && getContext().isId(ESM::RefId::stringRefId(name)))
{
mState = PotentialExplicitState;
mExplicit = Misc::StringUtils::lowerCase(name);
return true;
}
if (mState == BeginState && mAllowExpression)
{
std::string name2 = Misc::StringUtils::lowerCase(name);
char type = mLocals.getType(name2);
if (type != ' ')
{
scanner.putbackName(name, loc);
parseExpression(scanner, loc);
return true;
}
type = getContext().getGlobalType(name2);
if (type != ' ')
{
scanner.putbackName(name, loc);
parseExpression(scanner, loc);
return true;
}
}
return Parser::parseName(name, loc, scanner);
}
bool LineParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (mState == MessageState)
{
if (const Extensions* extensions = getContext().getExtensions())
{
std::string argumentType; // ignored
bool hasExplicit = false; // ignored
if (extensions->isInstruction(keyword, argumentType, hasExplicit))
{
// pretend this is not a keyword
std::string name = loc.mLiteral;
if (name.size() >= 2 && name[0] == '"' && name[name.size() - 1] == '"')
name = name.substr(1, name.size() - 2);
return parseName(name, loc, scanner);
}
}
}
if (mState == SetMemberVarState)
{
mMemberName = loc.mLiteral;
std::pair<char, bool> type = getContext().getMemberType(mMemberName, ESM::RefId::stringRefId(mName));
if (type.first != ' ')
{
mState = SetMemberVarState2;
mType = type.first;
mReferenceMember = type.second;
return true;
}
}
if (mState == SetPotentialMemberVarState && keyword == Scanner::K_to)
{
getErrorHandler().warning("Unknown variable", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
return false;
}
if (mState == SetState)
{
// allow keywords to be used as variable names when assigning a value to a variable.
return parseName(loc.mLiteral, loc, scanner);
}
if (mState == BeginState || mState == ExplicitState)
{
// check for custom extensions
if (const Extensions* extensions = getContext().getExtensions())
{
std::string argumentType;
bool hasExplicit = mState == ExplicitState;
if (extensions->isInstruction(keyword, argumentType, hasExplicit))
{
if (!hasExplicit && mState == ExplicitState)
{
getErrorHandler().warning("Stray explicit reference", loc);
mExplicit.clear();
}
std::vector<Interpreter::Type_Code> code;
int optionals = mExprParser.parseArguments(argumentType, scanner, code, keyword);
mCode.insert(mCode.end(), code.begin(), code.end());
extensions->generateInstructionCode(keyword, mCode, mLiterals, mExplicit, optionals);
SkipParser skip(getErrorHandler(), getContext(), true);
scanner.scan(skip);
mState = EndState;
return true;
}
char returnType;
if (extensions->isFunction(keyword, returnType, argumentType, hasExplicit))
{
if (!hasExplicit && mState == ExplicitState)
{
getErrorHandler().warning("Stray explicit reference", loc);
mExplicit.clear();
}
if (mAllowExpression)
{
scanner.putbackKeyword(keyword, loc);
parseExpression(scanner, loc);
}
else
{
std::vector<Interpreter::Type_Code> code;
int optionals = mExprParser.parseArguments(argumentType, scanner, code, keyword);
mCode.insert(mCode.end(), code.begin(), code.end());
extensions->generateFunctionCode(keyword, mCode, mLiterals, mExplicit, optionals);
SkipParser skip(getErrorHandler(), getContext(), true);
scanner.scan(skip);
}
mState = EndState;
return true;
}
}
}
if (mState == ExplicitState)
{
// drop stray explicit reference
getErrorHandler().warning("Stray explicit reference", loc);
mState = BeginState;
mExplicit.clear();
}
if (mState == BeginState)
{
switch (keyword)
{
case Scanner::K_short:
case Scanner::K_long:
case Scanner::K_float:
{
if (!getContext().canDeclareLocals())
{
getErrorHandler().error("Local variables cannot be declared in this context", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
return true;
}
DeclarationParser declaration(getErrorHandler(), getContext(), mLocals);
if (declaration.parseKeyword(keyword, loc, scanner))
scanner.scan(declaration);
return false;
}
case Scanner::K_set:
mState = SetState;
return true;
case Scanner::K_messagebox:
mState = MessageState;
scanner.enableStrictKeywords();
return true;
case Scanner::K_return:
Generator::exit(mCode);
mState = EndState;
return true;
case Scanner::K_else:
getErrorHandler().warning("Stray else", loc);
mState = EndState;
return true;
case Scanner::K_endif:
getErrorHandler().warning("Stray endif", loc);
mState = EndState;
return true;
case Scanner::K_begin:
getErrorHandler().warning("Stray begin", loc);
mState = EndState;
return true;
}
}
else if (mState == SetLocalVarState && keyword == Scanner::K_to)
{
mExprParser.reset();
scanner.scan(mExprParser);
std::vector<Interpreter::Type_Code> code;
char type = mExprParser.append(code);
Generator::assignToLocal(mCode, mLocals.getType(mName), mLocals.getIndex(mName), code, type);
mState = EndState;
return true;
}
else if (mState == SetGlobalVarState && keyword == Scanner::K_to)
{
mExprParser.reset();
scanner.scan(mExprParser);
std::vector<Interpreter::Type_Code> code;
char type = mExprParser.append(code);
Generator::assignToGlobal(mCode, mLiterals, mType, mName, code, type);
mState = EndState;
return true;
}
else if (mState == SetMemberVarState2 && keyword == Scanner::K_to)
{
mExprParser.reset();
scanner.scan(mExprParser);
std::vector<Interpreter::Type_Code> code;
char type = mExprParser.append(code);
Generator::assignToMember(mCode, mLiterals, mType, mMemberName, mName, code, type, !mReferenceMember);
mState = EndState;
return true;
}
return Parser::parseKeyword(keyword, loc, scanner);
}
bool LineParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (mState == EndState && code == Scanner::S_open)
{
getErrorHandler().warning("Stray '[' or '(' at the end of the line", loc);
return true;
}
if (code == Scanner::S_newline && (mState == EndState || mState == BeginState))
return false;
if (code == Scanner::S_ref && mState == SetPotentialMemberVarState)
{
getErrorHandler().warning("Stray explicit reference", loc);
mState = SetState;
return true;
}
if (code == Scanner::S_ref && mState == PotentialExplicitState)
{
mState = ExplicitState;
return true;
}
if (code == Scanner::S_member && mState == PotentialExplicitState && mAllowExpression)
{
mState = MemberState;
parseExpression(scanner, loc);
mState = EndState;
return true;
}
if (code == Scanner::S_newline && mState == MessageButtonState)
{
Generator::message(mCode, mLiterals, mName, mButtons);
return false;
}
if (code == Scanner::S_member && mState == SetPotentialMemberVarState)
{
mState = SetMemberVarState;
return true;
}
if (mAllowExpression && mState == BeginState
&& (code == Scanner::S_open || code == Scanner::S_minus || code == Scanner::S_plus))
{
scanner.putbackSpecial(code, loc);
parseExpression(scanner, loc);
mState = EndState;
return true;
}
return Parser::parseSpecial(code, loc, scanner);
}
void LineParser::reset()
{
mState = BeginState;
mName.clear();
mExplicit.clear();
}
void GetArgumentsFromMessageFormat::visitedPlaceholder(
Placeholder placeholder, char /*padding*/, int /*width*/, int /*precision*/, Notation /*notation*/)
{
switch (placeholder)
{
case StringPlaceholder:
mArguments += 'S';
break;
case IntegerPlaceholder:
mArguments += 'l';
break;
case FloatPlaceholder:
mArguments += 'f';
break;
default:
break;
}
}
}
| 15,752
|
C++
|
.cpp
| 415
| 24.727711
| 114
| 0.517508
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,628
|
extensions.cpp
|
OpenMW_openmw/components/compiler/extensions.cpp
|
#include "extensions.hpp"
#include <cassert>
#include <stdexcept>
#include "generator.hpp"
#include "literals.hpp"
namespace Compiler
{
Extensions::Extensions()
: mNextKeywordIndex(-1)
{
}
int Extensions::searchKeyword(const std::string& keyword) const
{
auto iter = mKeywords.find(keyword);
if (iter == mKeywords.end())
return 0;
return iter->second;
}
bool Extensions::isFunction(
int keyword, ScriptReturn& returnType, ScriptArgs& argumentType, bool& explicitReference) const
{
auto iter = mFunctions.find(keyword);
if (iter == mFunctions.end())
return false;
if (explicitReference && iter->second.mCodeExplicit == -1)
explicitReference = false;
returnType = iter->second.mReturn;
argumentType = iter->second.mArguments;
return true;
}
bool Extensions::isInstruction(int keyword, ScriptArgs& argumentType, bool& explicitReference) const
{
auto iter = mInstructions.find(keyword);
if (iter == mInstructions.end())
return false;
if (explicitReference && iter->second.mCodeExplicit == -1)
explicitReference = false;
argumentType = iter->second.mArguments;
return true;
}
void Extensions::registerFunction(
std::string_view keyword, ScriptReturn returnType, std::string_view argumentType, int code, int codeExplicit)
{
Function function;
if (argumentType.find('/') == std::string_view::npos)
{
function.mSegment = 5;
assert(code >= 33554432 && code <= 67108863);
assert(codeExplicit == -1 || (codeExplicit >= 33554432 && codeExplicit <= 67108863));
}
else
{
function.mSegment = 3;
assert(code >= 0x20000 && code <= 0x2ffff);
assert(codeExplicit == -1 || (codeExplicit >= 0x20000 && codeExplicit <= 0x2ffff));
}
int keywordIndex = mNextKeywordIndex--;
mKeywords.emplace(keyword, keywordIndex);
function.mReturn = returnType;
function.mArguments = argumentType;
function.mCode = code;
function.mCodeExplicit = codeExplicit;
mFunctions.emplace(keywordIndex, std::move(function));
}
void Extensions::registerInstruction(
std::string_view keyword, std::string_view argumentType, int code, int codeExplicit)
{
Instruction instruction;
if (argumentType.find('/') == std::string_view::npos)
{
instruction.mSegment = 5;
assert(code >= 33554432 && code <= 67108863);
assert(codeExplicit == -1 || (codeExplicit >= 33554432 && codeExplicit <= 67108863));
}
else
{
instruction.mSegment = 3;
assert(code >= 0x20000 && code <= 0x2ffff);
assert(codeExplicit == -1 || (codeExplicit >= 0x20000 && codeExplicit <= 0x2ffff));
}
int keywordIndex = mNextKeywordIndex--;
mKeywords.emplace(keyword, keywordIndex);
instruction.mArguments = argumentType;
instruction.mCode = code;
instruction.mCodeExplicit = codeExplicit;
mInstructions.emplace(keywordIndex, std::move(instruction));
}
void Extensions::generateFunctionCode(int keyword, std::vector<Interpreter::Type_Code>& code, Literals& literals,
const std::string& id, int optionalArguments) const
{
assert(optionalArguments >= 0);
auto iter = mFunctions.find(keyword);
if (iter == mFunctions.end())
throw std::logic_error("unknown custom function keyword");
if (optionalArguments && iter->second.mSegment != 3)
throw std::logic_error("functions with optional arguments must be placed into segment 3");
if (!id.empty())
{
if (iter->second.mCodeExplicit == -1)
throw std::logic_error("explicit references not supported");
int index = literals.addString(id);
Generator::pushInt(code, literals, index);
}
switch (iter->second.mSegment)
{
case 3:
if (optionalArguments >= 256)
throw std::logic_error("number of optional arguments is too large for segment 3");
code.push_back(Generator::segment3(
id.empty() ? iter->second.mCode : iter->second.mCodeExplicit, optionalArguments));
break;
case 5:
code.push_back(Generator::segment5(id.empty() ? iter->second.mCode : iter->second.mCodeExplicit));
break;
default:
throw std::logic_error("unsupported code segment");
}
}
void Extensions::generateInstructionCode(int keyword, std::vector<Interpreter::Type_Code>& code, Literals& literals,
const std::string& id, int optionalArguments) const
{
assert(optionalArguments >= 0);
auto iter = mInstructions.find(keyword);
if (iter == mInstructions.end())
throw std::logic_error("unknown custom instruction keyword");
if (optionalArguments && iter->second.mSegment != 3)
throw std::logic_error("instructions with optional arguments must be placed into segment 3");
if (!id.empty())
{
if (iter->second.mCodeExplicit == -1)
throw std::logic_error("explicit references not supported");
int index = literals.addString(id);
Generator::pushInt(code, literals, index);
}
switch (iter->second.mSegment)
{
case 3:
if (optionalArguments >= 256)
throw std::logic_error("number of optional arguments is too large for segment 3");
code.push_back(Generator::segment3(
id.empty() ? iter->second.mCode : iter->second.mCodeExplicit, optionalArguments));
break;
case 5:
code.push_back(Generator::segment5(id.empty() ? iter->second.mCode : iter->second.mCodeExplicit));
break;
default:
throw std::logic_error("unsupported code segment");
}
}
void Extensions::listKeywords(std::vector<std::string>& keywords) const
{
for (const auto& mKeyword : mKeywords)
keywords.push_back(mKeyword.first);
}
}
| 6,501
|
C++
|
.cpp
| 155
| 31.806452
| 120
| 0.606609
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,629
|
skipparser.cpp
|
OpenMW_openmw/components/compiler/skipparser.cpp
|
#include "skipparser.hpp"
#include "errorhandler.hpp"
#include "scanner.hpp"
namespace Compiler
{
SkipParser::SkipParser(ErrorHandler& errorHandler, const Context& context, bool reportStrayArguments)
: Parser(errorHandler, context)
, mReportStrayArguments(reportStrayArguments)
{
}
void SkipParser::reportStrayArgument(const TokenLoc& loc)
{
if (mReportStrayArguments)
getErrorHandler().warning("Extra argument", loc);
}
bool SkipParser::parseInt(int value, const TokenLoc& loc, Scanner& scanner)
{
reportStrayArgument(loc);
return true;
}
bool SkipParser::parseFloat(float value, const TokenLoc& loc, Scanner& scanner)
{
reportStrayArgument(loc);
return true;
}
bool SkipParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
reportStrayArgument(loc);
return true;
}
bool SkipParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
reportStrayArgument(loc);
return true;
}
bool SkipParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (code == Scanner::S_newline)
{
if (mReportStrayArguments)
scanner.putbackSpecial(code, loc);
return false;
}
reportStrayArgument(loc);
return true;
}
}
| 1,430
|
C++
|
.cpp
| 47
| 23.638298
| 105
| 0.658909
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,630
|
generator.cpp
|
OpenMW_openmw/components/compiler/generator.cpp
|
#include "generator.hpp"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <stdexcept>
#include "literals.hpp"
namespace
{
void opPushInt(Compiler::Generator::CodeContainer& code, int value)
{
code.push_back(Compiler::Generator::segment0(0, value));
}
void opFetchIntLiteral(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(4));
}
void opFetchFloatLiteral(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(5));
}
void opIntToFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(3));
}
void opFloatToInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(6));
}
void opStoreLocalShort(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(0));
}
void opStoreLocalLong(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(1));
}
void opStoreLocalFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(2));
}
void opNegateInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(7));
}
void opNegateFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(8));
}
void opAddInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(9));
}
void opAddFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(10));
}
void opSubInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(11));
}
void opSubFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(12));
}
void opMulInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(13));
}
void opMulFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(14));
}
void opDivInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(15));
}
void opDivFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(16));
}
void opIntToFloat1(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(17));
}
void opReturn(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(20));
}
void opMessageBox(Compiler::Generator::CodeContainer& code, int buttons)
{
code.push_back(Compiler::Generator::segment3(0, buttons));
}
void opReport(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(58));
}
void opFetchLocalShort(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(21));
}
void opFetchLocalLong(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(22));
}
void opFetchLocalFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(23));
}
void opJumpForward(Compiler::Generator::CodeContainer& code, int offset)
{
code.push_back(Compiler::Generator::segment0(1, offset));
}
void opJumpBackward(Compiler::Generator::CodeContainer& code, int offset)
{
code.push_back(Compiler::Generator::segment0(2, offset));
}
/*
Currently unused
void opSkipOnZero (Compiler::Generator::CodeContainer& code)
{
code.push_back (Compiler::Generator::segment5 (24));
}
*/
void opSkipOnNonZero(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(25));
}
void opEqualInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(26));
}
void opNonEqualInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(27));
}
void opLessThanInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(28));
}
void opLessOrEqualInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(29));
}
void opGreaterThanInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(30));
}
void opGreaterOrEqualInt(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(31));
}
void opEqualFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(32));
}
void opNonEqualFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(33));
}
void opLessThanFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(34));
}
void opLessOrEqualFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(35));
}
void opGreaterThanFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(36));
}
void opGreaterOrEqualFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(37));
}
void opStoreGlobalShort(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(39));
}
void opStoreGlobalLong(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(40));
}
void opStoreGlobalFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(41));
}
void opFetchGlobalShort(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(42));
}
void opFetchGlobalLong(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(43));
}
void opFetchGlobalFloat(Compiler::Generator::CodeContainer& code)
{
code.push_back(Compiler::Generator::segment5(44));
}
void opStoreMemberShort(Compiler::Generator::CodeContainer& code, bool global)
{
code.push_back(Compiler::Generator::segment5(global ? 65 : 59));
}
void opStoreMemberLong(Compiler::Generator::CodeContainer& code, bool global)
{
code.push_back(Compiler::Generator::segment5(global ? 66 : 60));
}
void opStoreMemberFloat(Compiler::Generator::CodeContainer& code, bool global)
{
code.push_back(Compiler::Generator::segment5(global ? 67 : 61));
}
void opFetchMemberShort(Compiler::Generator::CodeContainer& code, bool global)
{
code.push_back(Compiler::Generator::segment5(global ? 68 : 62));
}
void opFetchMemberLong(Compiler::Generator::CodeContainer& code, bool global)
{
code.push_back(Compiler::Generator::segment5(global ? 69 : 63));
}
void opFetchMemberFloat(Compiler::Generator::CodeContainer& code, bool global)
{
code.push_back(Compiler::Generator::segment5(global ? 70 : 64));
}
}
namespace Compiler::Generator
{
void pushInt(CodeContainer& code, Literals& literals, int value)
{
int index = literals.addInteger(value);
opPushInt(code, index);
opFetchIntLiteral(code);
}
void pushFloat(CodeContainer& code, Literals& literals, float value)
{
int index = literals.addFloat(value);
opPushInt(code, index);
opFetchFloatLiteral(code);
}
void pushString(CodeContainer& code, Literals& literals, const std::string& value)
{
int index = literals.addString(value);
opPushInt(code, index);
}
void assignToLocal(CodeContainer& code, char localType, int localIndex, const CodeContainer& value, char valueType)
{
opPushInt(code, localIndex);
std::copy(value.begin(), value.end(), std::back_inserter(code));
if (localType != valueType)
{
if (localType == 'f' && valueType == 'l')
{
opIntToFloat(code);
}
else if ((localType == 'l' || localType == 's') && valueType == 'f')
{
opFloatToInt(code);
}
}
switch (localType)
{
case 'f':
opStoreLocalFloat(code);
break;
case 's':
opStoreLocalShort(code);
break;
case 'l':
opStoreLocalLong(code);
break;
default:
assert(0);
}
}
void negate(CodeContainer& code, char valueType)
{
switch (valueType)
{
case 'l':
opNegateInt(code);
break;
case 'f':
opNegateFloat(code);
break;
default:
assert(0);
}
}
void add(CodeContainer& code, char valueType1, char valueType2)
{
if (valueType1 == 'l' && valueType2 == 'l')
{
opAddInt(code);
}
else
{
if (valueType1 == 'l')
opIntToFloat1(code);
if (valueType2 == 'l')
opIntToFloat(code);
opAddFloat(code);
}
}
void sub(CodeContainer& code, char valueType1, char valueType2)
{
if (valueType1 == 'l' && valueType2 == 'l')
{
opSubInt(code);
}
else
{
if (valueType1 == 'l')
opIntToFloat1(code);
if (valueType2 == 'l')
opIntToFloat(code);
opSubFloat(code);
}
}
void mul(CodeContainer& code, char valueType1, char valueType2)
{
if (valueType1 == 'l' && valueType2 == 'l')
{
opMulInt(code);
}
else
{
if (valueType1 == 'l')
opIntToFloat1(code);
if (valueType2 == 'l')
opIntToFloat(code);
opMulFloat(code);
}
}
void div(CodeContainer& code, char valueType1, char valueType2)
{
if (valueType1 == 'l' && valueType2 == 'l')
{
opDivInt(code);
}
else
{
if (valueType1 == 'l')
opIntToFloat1(code);
if (valueType2 == 'l')
opIntToFloat(code);
opDivFloat(code);
}
}
void convert(CodeContainer& code, char fromType, char toType)
{
if (fromType != toType)
{
if (fromType == 'f' && toType == 'l')
opFloatToInt(code);
else if (fromType == 'l' && toType == 'f')
opIntToFloat(code);
else
throw std::logic_error("illegal type conversion");
}
}
void exit(CodeContainer& code)
{
opReturn(code);
}
void message(CodeContainer& code, Literals& literals, const std::string& message, int buttons)
{
assert(buttons >= 0);
if (buttons >= 256)
throw std::runtime_error("A message box can't have more than 255 buttons");
int index = literals.addString(message);
opPushInt(code, index);
opMessageBox(code, buttons);
}
void report(CodeContainer& code, Literals& literals, const std::string& message)
{
int index = literals.addString(message);
opPushInt(code, index);
opReport(code);
}
void fetchLocal(CodeContainer& code, char localType, int localIndex)
{
opPushInt(code, localIndex);
switch (localType)
{
case 'f':
opFetchLocalFloat(code);
break;
case 's':
opFetchLocalShort(code);
break;
case 'l':
opFetchLocalLong(code);
break;
default:
assert(0);
}
}
void jump(CodeContainer& code, int offset)
{
if (offset > 0)
opJumpForward(code, offset);
else if (offset < 0)
opJumpBackward(code, -offset);
else
throw std::logic_error("infinite loop");
}
void jumpOnZero(CodeContainer& code, int offset)
{
opSkipOnNonZero(code);
if (offset < 0)
--offset; // compensate for skip instruction
jump(code, offset);
}
void compare(CodeContainer& code, char op, char valueType1, char valueType2)
{
if (valueType1 == 'l' && valueType2 == 'l')
{
switch (op)
{
case 'e':
opEqualInt(code);
break;
case 'n':
opNonEqualInt(code);
break;
case 'l':
opLessThanInt(code);
break;
case 'L':
opLessOrEqualInt(code);
break;
case 'g':
opGreaterThanInt(code);
break;
case 'G':
opGreaterOrEqualInt(code);
break;
default:
assert(0);
}
}
else
{
if (valueType1 == 'l')
opIntToFloat1(code);
if (valueType2 == 'l')
opIntToFloat(code);
switch (op)
{
case 'e':
opEqualFloat(code);
break;
case 'n':
opNonEqualFloat(code);
break;
case 'l':
opLessThanFloat(code);
break;
case 'L':
opLessOrEqualFloat(code);
break;
case 'g':
opGreaterThanFloat(code);
break;
case 'G':
opGreaterOrEqualFloat(code);
break;
default:
assert(0);
}
}
}
void assignToGlobal(CodeContainer& code, Literals& literals, char localType, const std::string& name,
const CodeContainer& value, char valueType)
{
int index = literals.addString(name);
opPushInt(code, index);
std::copy(value.begin(), value.end(), std::back_inserter(code));
if (localType != valueType)
{
if (localType == 'f' && (valueType == 'l' || valueType == 's'))
{
opIntToFloat(code);
}
else if ((localType == 'l' || localType == 's') && valueType == 'f')
{
opFloatToInt(code);
}
}
switch (localType)
{
case 'f':
opStoreGlobalFloat(code);
break;
case 's':
opStoreGlobalShort(code);
break;
case 'l':
opStoreGlobalLong(code);
break;
default:
assert(0);
}
}
void fetchGlobal(CodeContainer& code, Literals& literals, char localType, const std::string& name)
{
int index = literals.addString(name);
opPushInt(code, index);
switch (localType)
{
case 'f':
opFetchGlobalFloat(code);
break;
case 's':
opFetchGlobalShort(code);
break;
case 'l':
opFetchGlobalLong(code);
break;
default:
assert(0);
}
}
void assignToMember(CodeContainer& code, Literals& literals, char localType, const std::string& name,
const std::string& id, const CodeContainer& value, char valueType, bool global)
{
int index = literals.addString(name);
opPushInt(code, index);
index = literals.addString(id);
opPushInt(code, index);
std::copy(value.begin(), value.end(), std::back_inserter(code));
if (localType != valueType)
{
if (localType == 'f' && (valueType == 'l' || valueType == 's'))
{
opIntToFloat(code);
}
else if ((localType == 'l' || localType == 's') && valueType == 'f')
{
opFloatToInt(code);
}
}
switch (localType)
{
case 'f':
opStoreMemberFloat(code, global);
break;
case 's':
opStoreMemberShort(code, global);
break;
case 'l':
opStoreMemberLong(code, global);
break;
default:
assert(0);
}
}
void fetchMember(CodeContainer& code, Literals& literals, char localType, const std::string& name,
const std::string& id, bool global)
{
int index = literals.addString(name);
opPushInt(code, index);
index = literals.addString(id);
opPushInt(code, index);
switch (localType)
{
case 'f':
opFetchMemberFloat(code, global);
break;
case 's':
opFetchMemberShort(code, global);
break;
case 'l':
opFetchMemberLong(code, global);
break;
default:
assert(0);
}
}
}
| 18,330
|
C++
|
.cpp
| 579
| 21.920553
| 119
| 0.559018
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,631
|
controlparser.cpp
|
OpenMW_openmw/components/compiler/controlparser.cpp
|
#include "controlparser.hpp"
#include <algorithm>
#include <iterator>
#include <stdexcept>
#include "errorhandler.hpp"
#include "generator.hpp"
#include "scanner.hpp"
#include "skipparser.hpp"
namespace Compiler
{
bool ControlParser::parseIfBody(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (keyword == Scanner::K_endif || keyword == Scanner::K_elseif || keyword == Scanner::K_else)
{
std::pair<Codes, Codes> entry;
if (mState != IfElseBodyState)
mExprParser.append(entry.first);
std::copy(mCodeBlock.begin(), mCodeBlock.end(), std::back_inserter(entry.second));
mIfCode.push_back(entry);
mCodeBlock.clear();
if (keyword == Scanner::K_endif)
{
// store code for if-cascade
Codes codes;
for (auto iter(mIfCode.rbegin()); iter != mIfCode.rend(); ++iter)
{
Codes block;
if (iter != mIfCode.rbegin())
Generator::jump(iter->second, static_cast<int>(codes.size() + 1));
if (!iter->first.empty())
{
// if or elseif
std::copy(iter->first.begin(), iter->first.end(), std::back_inserter(block));
Generator::jumpOnZero(block, static_cast<int>(iter->second.size() + 1));
}
std::copy(iter->second.begin(), iter->second.end(), std::back_inserter(block));
std::swap(codes, block);
std::copy(block.begin(), block.end(), std::back_inserter(codes));
}
std::copy(codes.begin(), codes.end(), std::back_inserter(mCode));
mIfCode.clear();
mState = IfEndifState;
}
else if (keyword == Scanner::K_elseif)
{
mExprParser.reset();
scanner.scan(mExprParser);
mState = IfElseifEndState;
}
else if (keyword == Scanner::K_else)
{
mState = IfElseJunkState; /// \todo should be IfElseEndState; add an option for that
}
return true;
}
else if (keyword == Scanner::K_if || keyword == Scanner::K_while)
{
// nested
ControlParser parser(getErrorHandler(), getContext(), mLocals, mLiterals);
if (parser.parseKeyword(keyword, loc, scanner))
scanner.scan(parser);
parser.appendCode(mCodeBlock);
return true;
}
else
{
mLineParser.reset();
if (mLineParser.parseKeyword(keyword, loc, scanner))
scanner.scan(mLineParser);
return true;
}
}
bool ControlParser::parseWhileBody(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (keyword == Scanner::K_endwhile)
{
Codes loop;
Codes expr;
mExprParser.append(expr);
Generator::jump(loop, -static_cast<int>(mCodeBlock.size() + expr.size()));
std::copy(expr.begin(), expr.end(), std::back_inserter(mCode));
Codes skip;
Generator::jumpOnZero(skip, static_cast<int>(mCodeBlock.size() + loop.size() + 1));
std::copy(skip.begin(), skip.end(), std::back_inserter(mCode));
std::copy(mCodeBlock.begin(), mCodeBlock.end(), std::back_inserter(mCode));
Codes loop2;
Generator::jump(loop2, -static_cast<int>(mCodeBlock.size() + expr.size() + skip.size()));
if (loop.size() != loop2.size())
throw std::logic_error("Internal compiler error: failed to generate a while loop");
std::copy(loop2.begin(), loop2.end(), std::back_inserter(mCode));
mState = WhileEndwhileState;
return true;
}
else if (keyword == Scanner::K_if || keyword == Scanner::K_while)
{
// nested
ControlParser parser(getErrorHandler(), getContext(), mLocals, mLiterals);
if (parser.parseKeyword(keyword, loc, scanner))
scanner.scan(parser);
parser.appendCode(mCodeBlock);
return true;
}
else
{
mLineParser.reset();
if (mLineParser.parseKeyword(keyword, loc, scanner))
scanner.scan(mLineParser);
return true;
}
}
ControlParser::ControlParser(ErrorHandler& errorHandler, const Context& context, Locals& locals, Literals& literals)
: Parser(errorHandler, context)
, mLocals(locals)
, mLiterals(literals)
, mLineParser(errorHandler, context, locals, literals, mCodeBlock)
, mExprParser(errorHandler, context, locals, literals)
, mState(StartState)
{
}
void ControlParser::appendCode(std::vector<Interpreter::Type_Code>& code) const
{
std::copy(mCode.begin(), mCode.end(), std::back_inserter(code));
}
bool ControlParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
if (mState == IfBodyState || mState == IfElseifBodyState || mState == IfElseBodyState
|| mState == WhileBodyState)
{
scanner.putbackName(name, loc);
mLineParser.reset();
scanner.scan(mLineParser);
return true;
}
else if (mState == IfElseJunkState)
{
getErrorHandler().warning("Extra text after else", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
mState = IfElseBodyState;
return true;
}
return Parser::parseName(name, loc, scanner);
}
bool ControlParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (mState == StartState)
{
if (keyword == Scanner::K_if || keyword == Scanner::K_elseif)
{
if (keyword == Scanner::K_elseif)
getErrorHandler().warning("elseif without matching if", loc);
mExprParser.reset();
scanner.scan(mExprParser);
mState = IfEndState;
return true;
}
else if (keyword == Scanner::K_while)
{
mExprParser.reset();
scanner.scan(mExprParser);
mState = WhileEndState;
return true;
}
}
else if (mState == IfBodyState || mState == IfElseifBodyState || mState == IfElseBodyState)
{
if (parseIfBody(keyword, loc, scanner))
return true;
}
else if (mState == WhileBodyState)
{
if (parseWhileBody(keyword, loc, scanner))
return true;
}
else if (mState == IfElseJunkState)
{
getErrorHandler().warning("Extra text after else", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
mState = IfElseBodyState;
return true;
}
return Parser::parseKeyword(keyword, loc, scanner);
}
bool ControlParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (code == Scanner::S_newline)
{
switch (mState)
{
case IfEndState:
mState = IfBodyState;
return true;
case IfElseifEndState:
mState = IfElseifBodyState;
return true;
case IfElseEndState:
mState = IfElseBodyState;
return true;
case IfElseJunkState:
mState = IfElseBodyState;
return true;
case WhileEndState:
mState = WhileBodyState;
return true;
case IfBodyState:
case IfElseifBodyState:
case IfElseBodyState:
case WhileBodyState:
return true; // empty line
case IfEndifState:
case WhileEndwhileState:
return false;
default:;
}
}
else if (mState == IfElseJunkState)
{
getErrorHandler().warning("Extra text after else", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
mState = IfElseBodyState;
return true;
}
return Parser::parseSpecial(code, loc, scanner);
}
void ControlParser::reset()
{
mCode.clear();
mCodeBlock.clear();
mIfCode.clear();
mState = StartState;
Parser::reset();
}
}
| 9,023
|
C++
|
.cpp
| 235
| 25.885106
| 120
| 0.532241
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,632
|
literals.cpp
|
OpenMW_openmw/components/compiler/literals.cpp
|
#include "literals.hpp"
#include <algorithm>
#include <cstring>
namespace Compiler
{
int Literals::addInteger(Interpreter::Type_Integer value)
{
int index = static_cast<int>(mIntegers.size());
mIntegers.push_back(value);
return index;
}
int Literals::addFloat(Interpreter::Type_Float value)
{
int index = static_cast<int>(mFloats.size());
mFloats.push_back(value);
return index;
}
int Literals::addString(const std::string& value)
{
int index = static_cast<int>(mStrings.size());
mStrings.push_back(value);
return index;
}
void Literals::clear()
{
mIntegers.clear();
mFloats.clear();
mStrings.clear();
}
}
| 761
|
C++
|
.cpp
| 30
| 19.2
| 61
| 0.620833
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,633
|
nullerrorhandler.cpp
|
OpenMW_openmw/components/compiler/nullerrorhandler.cpp
|
#include "nullerrorhandler.hpp"
void Compiler::NullErrorHandler::report(const std::string& message, const TokenLoc& loc, Type type) {}
void Compiler::NullErrorHandler::report(const std::string& message, Type type) {}
| 219
|
C++
|
.cpp
| 3
| 71.333333
| 102
| 0.785047
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
34,634
|
streamerrorhandler.cpp
|
OpenMW_openmw/components/compiler/streamerrorhandler.cpp
|
#include "streamerrorhandler.hpp"
#include <sstream>
#include <components/debug/debuglog.hpp>
#include "tokenloc.hpp"
namespace Compiler
{
// Report error to the user.
void StreamErrorHandler::report(const std::string& message, const TokenLoc& loc, Type type)
{
Debug::Level logLevel = Debug::Info; // Usually script warnings are not too important
if (type == ErrorMessage)
logLevel = Debug::Error;
std::stringstream text;
if (type == ErrorMessage)
text << "Error: ";
else
text << "Warning: ";
if (!mContext.empty())
text << mContext << " ";
text << "line " << loc.mLine + 1 << ", column " << loc.mColumn + 1 << " (" << loc.mLiteral << "): " << message;
Log(logLevel) << text.str();
}
// Report a file related error
void StreamErrorHandler::report(const std::string& message, Type type)
{
Debug::Level logLevel = Debug::Info;
if (type == ErrorMessage)
logLevel = Debug::Error;
std::stringstream text;
if (type == ErrorMessage)
text << "Error: ";
else
text << "Warning: ";
if (!mContext.empty())
text << mContext << " ";
text << "file: " << message << std::endl;
Log(logLevel) << text.str();
}
void StreamErrorHandler::setContext(const std::string& context)
{
mContext = context;
}
StreamErrorHandler::StreamErrorHandler() = default;
ContextOverride::ContextOverride(StreamErrorHandler& handler, const std::string& context)
: mHandler(handler)
, mContext(handler.mContext)
{
mHandler.setContext(context);
}
ContextOverride::~ContextOverride()
{
mHandler.setContext(mContext);
}
}
| 1,836
|
C++
|
.cpp
| 54
| 26.388889
| 119
| 0.590574
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,635
|
parser.cpp
|
OpenMW_openmw/components/compiler/parser.cpp
|
#include "parser.hpp"
#include "errorhandler.hpp"
#include "exception.hpp"
#include "scanner.hpp"
#include <components/misc/strings/lower.hpp>
namespace Compiler
{
// Report the error and throw an exception.
[[noreturn]] void Parser::reportSeriousError(const std::string& message, const TokenLoc& loc)
{
mErrorHandler.error(message, loc);
throw SourceException();
}
// Report the warning without throwing an exception.
void Parser::reportWarning(const std::string& message, const TokenLoc& loc)
{
mErrorHandler.warning(message, loc);
}
// Report an unexpected EOF condition.
[[noreturn]] void Parser::reportEOF()
{
mErrorHandler.endOfFile();
throw EOFException();
}
// Return error handler
ErrorHandler& Parser::getErrorHandler()
{
return mErrorHandler;
}
// Return context
const Context& Parser::getContext() const
{
return mContext;
}
std::string Parser::toLower(const std::string& name)
{
std::string lowerCase = Misc::StringUtils::lowerCase(name);
return lowerCase;
}
Parser::Parser(ErrorHandler& errorHandler, const Context& context)
: mErrorHandler(errorHandler)
, mContext(context)
, mOptional(false)
, mEmpty(true)
{
}
// destructor
Parser::~Parser() = default;
// Handle an int token.
// \return fetch another token?
//
// - Default-implementation: Report an error.
bool Parser::parseInt(int value, const TokenLoc& loc, Scanner& scanner)
{
if (!(mOptional && mEmpty))
reportSeriousError("Unexpected numeric value", loc);
else
scanner.putbackInt(value, loc);
return false;
}
// Handle a float token.
// \return fetch another token?
//
// - Default-implementation: Report an error.
bool Parser::parseFloat(float value, const TokenLoc& loc, Scanner& scanner)
{
if (!(mOptional && mEmpty))
reportSeriousError("Unexpected floating point value", loc);
else
scanner.putbackFloat(value, loc);
return false;
}
// Handle a name token.
// \return fetch another token?
//
// - Default-implementation: Report an error.
bool Parser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
if (!(mOptional && mEmpty))
reportSeriousError("Unexpected name", loc);
else
scanner.putbackName(name, loc);
return false;
}
// Handle a keyword token.
// \return fetch another token?
//
// - Default-implementation: Report an error.
bool Parser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (!(mOptional && mEmpty))
reportSeriousError("Unexpected keyword", loc);
else
scanner.putbackKeyword(keyword, loc);
return false;
}
// Handle a special character token.
// \return fetch another token?
//
// - Default-implementation: Report an error.
bool Parser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (!(mOptional && mEmpty))
reportSeriousError("Unexpected special token", loc);
else
scanner.putbackSpecial(code, loc);
return false;
}
bool Parser::parseComment(const std::string& comment, const TokenLoc& loc, Scanner& scanner)
{
return true;
}
// Handle an EOF token.
//
// - Default-implementation: Report an error.
void Parser::parseEOF(Scanner& scanner)
{
reportEOF();
}
void Parser::reset()
{
mOptional = false;
mEmpty = true;
}
void Parser::setOptional(bool optional)
{
mOptional = optional;
}
void Parser::start()
{
mEmpty = false;
}
bool Parser::isEmpty() const
{
return mEmpty;
}
}
| 4,014
|
C++
|
.cpp
| 137
| 22.642336
| 97
| 0.625326
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,636
|
scriptparser.cpp
|
OpenMW_openmw/components/compiler/scriptparser.cpp
|
#include "scriptparser.hpp"
#include "errorhandler.hpp"
#include "scanner.hpp"
#include "skipparser.hpp"
namespace Compiler
{
ScriptParser::ScriptParser(ErrorHandler& errorHandler, const Context& context, Locals& locals, bool end)
: Parser(errorHandler, context)
, mOutput(locals)
, mLineParser(errorHandler, context, locals, mOutput.getLiterals(), mOutput.getCode())
, mControlParser(errorHandler, context, locals, mOutput.getLiterals())
, mEnd(end)
{
}
Interpreter::Program ScriptParser::getProgram() const
{
return mOutput.getProgram();
}
bool ScriptParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
mLineParser.reset();
if (mLineParser.parseName(name, loc, scanner))
scanner.scan(mLineParser);
return true;
}
bool ScriptParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (keyword == Scanner::K_while || keyword == Scanner::K_if || keyword == Scanner::K_elseif)
{
mControlParser.reset();
if (mControlParser.parseKeyword(keyword, loc, scanner))
scanner.scan(mControlParser);
mControlParser.appendCode(mOutput.getCode());
return true;
}
/// \todo add an option to disable this nonsense
if (keyword == Scanner::K_endif)
{
// surplus endif
getErrorHandler().warning("endif without matching if/elseif", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
return true;
}
if (keyword == Scanner::K_end && mEnd)
{
return false;
}
mLineParser.reset();
if (mLineParser.parseKeyword(keyword, loc, scanner))
scanner.scan(mLineParser);
return true;
}
bool ScriptParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (code == Scanner::S_newline) // empty line
return true;
if (code == Scanner::S_open) /// \todo Option to switch this off
{
scanner.putbackSpecial(code, loc);
return parseKeyword(Scanner::K_if, loc, scanner);
}
mLineParser.reset();
if (mLineParser.parseSpecial(code, loc, scanner))
scanner.scan(mLineParser);
return true;
}
void ScriptParser::parseEOF(Scanner& scanner)
{
if (mEnd)
Parser::parseEOF(scanner);
}
void ScriptParser::reset()
{
mLineParser.reset();
mOutput.clear();
}
}
| 2,672
|
C++
|
.cpp
| 78
| 25.833333
| 108
| 0.610097
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,637
|
declarationparser.cpp
|
OpenMW_openmw/components/compiler/declarationparser.cpp
|
#include "declarationparser.hpp"
#include <components/misc/strings/lower.hpp>
#include "context.hpp"
#include "errorhandler.hpp"
#include "extensions.hpp"
#include "locals.hpp"
#include "scanner.hpp"
#include "skipparser.hpp"
Compiler::DeclarationParser::DeclarationParser(ErrorHandler& errorHandler, const Context& context, Locals& locals)
: Parser(errorHandler, context)
, mLocals(locals)
, mState(State_Begin)
, mType(0)
{
}
bool Compiler::DeclarationParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
if (mState == State_Name)
{
std::string name2 = ::Misc::StringUtils::lowerCase(name);
char type = mLocals.getType(name2);
if (type != ' ')
getErrorHandler().warning("Local variable re-declaration", loc);
else
mLocals.declare(mType, name2);
mState = State_End;
return true;
}
else if (mState == State_End)
{
getErrorHandler().warning("Extra text after local variable declaration", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
return false;
}
return Parser::parseName(name, loc, scanner);
}
bool Compiler::DeclarationParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (mState == State_Begin)
{
switch (keyword)
{
case Scanner::K_short:
mType = 's';
break;
case Scanner::K_long:
mType = 'l';
break;
case Scanner::K_float:
mType = 'f';
break;
default:
mType = 0;
}
if (mType)
{
mState = State_Name;
return true;
}
}
else if (mState == State_Name)
{
// allow keywords to be used as local variable names. MW script compiler, you suck!
if (const Extensions* extensions = getContext().getExtensions())
{
std::string argumentType;
bool hasExplicit = false;
char returnType;
if (extensions->isFunction(keyword, returnType, argumentType, hasExplicit))
getErrorHandler().warning("Local variable declaration shadows a function", loc);
}
return parseName(loc.mLiteral, loc, scanner);
}
else if (mState == State_End)
{
getErrorHandler().warning("Extra text after local variable declaration", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
return false;
}
return Parser::parseKeyword(keyword, loc, scanner);
}
bool Compiler::DeclarationParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (mState == State_End)
{
if (code != Scanner::S_newline)
{
getErrorHandler().warning("Extra text after local variable declaration", loc);
SkipParser skip(getErrorHandler(), getContext());
scanner.scan(skip);
}
return false;
}
return Parser::parseSpecial(code, loc, scanner);
}
bool Compiler::DeclarationParser::parseInt(int value, const TokenLoc& loc, Scanner& scanner)
{
if (mState == State_Name)
{
// Allow integers to be used as variable names
getErrorHandler().warning("Integer is used as a local variable name", loc);
return parseName(loc.mLiteral, loc, scanner);
}
return Parser::parseInt(value, loc, scanner);
}
void Compiler::DeclarationParser::reset()
{
mState = State_Begin;
}
| 3,606
|
C++
|
.cpp
| 111
| 25.18018
| 114
| 0.622593
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,639
|
junkparser.cpp
|
OpenMW_openmw/components/compiler/junkparser.cpp
|
#include "junkparser.hpp"
#include "scanner.hpp"
Compiler::JunkParser::JunkParser(ErrorHandler& errorHandler, const Context& context, int ignoreKeyword)
: Parser(errorHandler, context)
, mIgnoreKeyword(ignoreKeyword)
{
}
bool Compiler::JunkParser::parseInt(int value, const TokenLoc& loc, Scanner& scanner)
{
scanner.putbackInt(value, loc);
return false;
}
bool Compiler::JunkParser::parseFloat(float value, const TokenLoc& loc, Scanner& scanner)
{
scanner.putbackFloat(value, loc);
return false;
}
bool Compiler::JunkParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
scanner.putbackName(name, loc);
return false;
}
bool Compiler::JunkParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (keyword == mIgnoreKeyword)
reportWarning("Ignoring found junk", loc);
else
scanner.putbackKeyword(keyword, loc);
return false;
}
bool Compiler::JunkParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (code == Scanner::S_member)
reportWarning("Ignoring found junk", loc);
else
scanner.putbackSpecial(code, loc);
return false;
}
| 1,195
|
C++
|
.cpp
| 38
| 27.894737
| 103
| 0.738676
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,640
|
fileparser.cpp
|
OpenMW_openmw/components/compiler/fileparser.cpp
|
#include "fileparser.hpp"
#include <components/misc/strings/algorithm.hpp>
#include "scanner.hpp"
#include "tokenloc.hpp"
namespace Compiler
{
FileParser::FileParser(ErrorHandler& errorHandler, Context& context)
: Parser(errorHandler, context)
, mScriptParser(errorHandler, context, mLocals, true)
, mState(BeginState)
{
}
Interpreter::Program FileParser::getProgram() const
{
return mScriptParser.getProgram();
}
const Locals& FileParser::getLocals() const
{
return mLocals;
}
bool FileParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
if (mState == NameState)
{
mName = name;
mState = BeginCompleteState;
return true;
}
if (mState == EndNameState)
{
// optional repeated name after end statement
if (!Misc::StringUtils::ciEqual(mName, name))
reportWarning("Names for script " + mName + " do not match", loc);
mState = EndCompleteState;
return false; // we are stopping here, because there might be more garbage on the end line,
// that we must ignore.
//
/// \todo allow this workaround to be disabled for newer scripts
}
if (mState == BeginCompleteState)
{
reportWarning("Stray string (" + name + ") after begin statement", loc);
return true;
}
return Parser::parseName(name, loc, scanner);
}
bool FileParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (mState == BeginState && keyword == Scanner::K_begin)
{
mState = NameState;
scanner.enableTolerantNames(); /// \todo disable
return true;
}
if (mState == NameState)
{
// keywords can be used as script names too. Thank you Morrowind for another
// syntactic perversity :(
mName = loc.mLiteral;
mState = BeginCompleteState;
return true;
}
if (mState == EndNameState)
{
// optional repeated name after end statement
if (!Misc::StringUtils::ciEqual(mName, loc.mLiteral))
reportWarning("Names for script " + mName + " do not match", loc);
mState = EndCompleteState;
return false; // we are stopping here, because there might be more garbage on the end line,
// that we must ignore.
//
/// \todo allow this workaround to be disabled for newer scripts
}
return Parser::parseKeyword(keyword, loc, scanner);
}
bool FileParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (code == Scanner::S_newline)
{
if (mState == BeginState)
return true;
if (mState == BeginCompleteState)
{
// parse the script body
mScriptParser.reset();
scanner.scan(mScriptParser);
mState = EndNameState;
return true;
}
if (mState == EndCompleteState || mState == EndNameState)
{
// we are done here -> ignore the rest of the script
return false;
}
}
return Parser::parseSpecial(code, loc, scanner);
}
void FileParser::parseEOF(Scanner& scanner)
{
if (mState != EndNameState && mState != EndCompleteState)
Parser::parseEOF(scanner);
}
void FileParser::reset()
{
mState = BeginState;
mName.clear();
mScriptParser.reset();
Parser::reset();
}
}
| 3,899
|
C++
|
.cpp
| 110
| 24.863636
| 103
| 0.557207
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,641
|
stringparser.cpp
|
OpenMW_openmw/components/compiler/stringparser.cpp
|
#include "stringparser.hpp"
#include <algorithm>
#include <iterator>
#include <components/misc/strings/lower.hpp>
#include "context.hpp"
#include "extensions.hpp"
#include "generator.hpp"
#include "scanner.hpp"
namespace Compiler
{
StringParser::StringParser(ErrorHandler& errorHandler, const Context& context, Literals& literals)
: Parser(errorHandler, context)
, mLiterals(literals)
, mSmashCase(false)
, mDiscard(false)
{
}
bool StringParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
start();
mTokenLoc = loc;
if (!mDiscard)
{
if (mSmashCase)
Generator::pushString(mCode, mLiterals, Misc::StringUtils::lowerCase(name));
else
Generator::pushString(mCode, mLiterals, name);
}
return false;
}
bool StringParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (const Extensions* extensions = getContext().getExtensions())
{
std::string argumentType; // ignored
bool hasExplicit = false; // ignored
if (extensions->isInstruction(keyword, argumentType, hasExplicit))
{
// pretend this is not a keyword
std::string name = loc.mLiteral;
if (name.size() >= 2 && name[0] == '"' && name[name.size() - 1] == '"')
name = name.substr(1, name.size() - 2);
return parseName(name, loc, scanner);
}
}
if (keyword == Scanner::K_end || keyword == Scanner::K_begin || keyword == Scanner::K_short
|| keyword == Scanner::K_long || keyword == Scanner::K_float || keyword == Scanner::K_if
|| keyword == Scanner::K_endif || keyword == Scanner::K_else || keyword == Scanner::K_elseif
|| keyword == Scanner::K_while || keyword == Scanner::K_endwhile || keyword == Scanner::K_return
|| keyword == Scanner::K_messagebox || keyword == Scanner::K_set || keyword == Scanner::K_to)
{
// pretend this is not a keyword
std::string name = loc.mLiteral;
if (name.size() >= 2 && name[0] == '"' && name[name.size() - 1] == '"')
name = name.substr(1, name.size() - 2);
return parseName(name, loc, scanner);
}
return Parser::parseKeyword(keyword, loc, scanner);
}
bool StringParser::parseInt(int value, const TokenLoc& loc, Scanner& scanner)
{
reportWarning("Treating integer argument as a string", loc);
return parseName(loc.mLiteral, loc, scanner);
}
void StringParser::append(std::vector<Interpreter::Type_Code>& code)
{
std::copy(mCode.begin(), mCode.end(), std::back_inserter(code));
}
void StringParser::reset()
{
mCode.clear();
mSmashCase = false;
mTokenLoc = TokenLoc();
mDiscard = false;
Parser::reset();
}
void StringParser::smashCase()
{
mSmashCase = true;
}
const TokenLoc& StringParser::getTokenLoc() const
{
return mTokenLoc;
}
void StringParser::discard()
{
mDiscard = true;
}
}
| 3,273
|
C++
|
.cpp
| 89
| 28.359551
| 108
| 0.583018
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,642
|
scanner.cpp
|
OpenMW_openmw/components/compiler/scanner.cpp
|
#include "scanner.hpp"
#include <cassert>
#include <sstream>
#include "errorhandler.hpp"
#include "exception.hpp"
#include "extensions.hpp"
#include "parser.hpp"
#include <components/misc/strings/conversion.hpp>
#include <components/misc/strings/lower.hpp>
namespace
{
bool startsComparisonOperator(const Compiler::MultiChar& c)
{
return c == '=' || c == '<' || c == '>' || c == '!';
}
bool validComparisonOperatorCharacter(const Compiler::MultiChar& c)
{
return startsComparisonOperator(c) || c == ' ' || c == '\t';
}
}
namespace Compiler
{
bool Scanner::get(MultiChar& c)
{
if (!c.getFrom(mStream))
return false;
mPrevLoc = mLoc;
if (c == '\n')
{
mStrictKeywords = false;
mTolerantNames = false;
mExpectName = false;
mLoc.mColumn = 0;
++mLoc.mLine;
mLoc.mLiteral.clear();
mIgnoreSpecial = true;
}
else
{
++mLoc.mColumn;
c.appendTo(mLoc.mLiteral);
}
return true;
}
void Scanner::putback(MultiChar& c)
{
c.putback(mStream);
mLoc = mPrevLoc;
}
bool Scanner::scanToken(Parser& parser)
{
switch (mPutback)
{
case Putback_Special:
{
mPutback = Putback_None;
// Replicate behaviour from scanSpecial so putting something back doesn't change the way it's handled
if (mExpectName && (mPutbackCode == S_member || mPutbackCode == S_minus))
{
mExpectName = false;
bool cont = false;
bool tolerant = mTolerantNames;
mTolerantNames = true;
MultiChar c{ mPutbackCode == S_member ? '.' : '-' };
scanName(c, parser, cont);
mTolerantNames = tolerant;
return cont;
}
return parser.parseSpecial(mPutbackCode, mPutbackLoc, *this);
}
case Putback_Integer:
mPutback = Putback_None;
return parser.parseInt(mPutbackInteger, mPutbackLoc, *this);
case Putback_Float:
mPutback = Putback_None;
return parser.parseFloat(mPutbackFloat, mPutbackLoc, *this);
case Putback_Name:
mPutback = Putback_None;
return parser.parseName(mPutbackName, mPutbackLoc, *this);
case Putback_Keyword:
mPutback = Putback_None;
return parser.parseKeyword(mPutbackCode, mPutbackLoc, *this);
case Putback_None:
break;
}
MultiChar c;
if (!get(c))
{
parser.parseEOF(*this);
return false;
}
else if (c == ';')
{
std::string comment;
c.appendTo(comment);
while (get(c))
{
if (c == '\n')
{
putback(c);
break;
}
else
c.appendTo(comment);
}
TokenLoc loc(mLoc);
mLoc.mLiteral.clear();
return parser.parseComment(comment, loc, *this);
}
else if (c.isWhitespace())
{
mLoc.mLiteral.clear();
return true;
}
else if (c == ':')
{
// treat : as a whitespace :(
mLoc.mLiteral.clear();
return true;
}
else if (c.isAlpha() || c == '_' || c == '"')
{
mIgnoreSpecial = false;
bool cont = false;
if (scanName(c, parser, cont))
{
mLoc.mLiteral.clear();
return cont;
}
}
else if (c.isDigit())
{
mIgnoreSpecial = false;
bool cont = false;
bool scanned = mExpectName ? scanName(c, parser, cont) : scanInt(c, parser, cont);
if (scanned)
{
mLoc.mLiteral.clear();
return cont;
}
}
else if (c == 13) // linux compatibility hack
{
return true;
}
else
{
bool cont = false;
if (scanSpecial(c, parser, cont))
{
mLoc.mLiteral.clear();
return cont;
}
}
TokenLoc loc(mLoc);
mLoc.mLiteral.clear();
mErrorHandler.error("Syntax error", loc);
throw SourceException();
}
bool Scanner::scanInt(MultiChar& c, Parser& parser, bool& cont)
{
assert(c != '\0');
std::string value;
c.appendTo(value);
while (get(c))
{
if (c.isDigit())
{
c.appendTo(value);
}
else if (!c.isMinusSign() && isStringCharacter(c))
{
/// workaround that allows names to begin with digits
return scanName(c, parser, cont, value);
}
else if (c == '.')
{
return scanFloat(value, parser, cont);
}
else
{
putback(c);
break;
}
}
TokenLoc loc(mLoc);
mLoc.mLiteral.clear();
cont = parser.parseInt(Misc::StringUtils::toNumeric<int>(value, 0), loc, *this);
return true;
}
bool Scanner::scanFloat(const std::string& intValue, Parser& parser, bool& cont)
{
std::string value = intValue + ".";
MultiChar c;
bool empty = intValue.empty() || intValue == "-";
bool error = false;
while (get(c))
{
if (c.isDigit())
{
c.appendTo(value);
empty = false;
}
else if (c.isAlpha() || c == '_')
error = true;
else
{
putback(c);
break;
}
}
if (empty || error)
return false;
TokenLoc loc(mLoc);
mLoc.mLiteral.clear();
cont = parser.parseFloat(Misc::StringUtils::toNumeric<float>(value, 0.0f), loc, *this);
return true;
}
static const char* sKeywords[] = {
"begin",
"end",
"short",
"long",
"float",
"if",
"endif",
"else",
"elseif",
"while",
"endwhile",
"return",
"messagebox",
"set",
"to",
nullptr,
};
bool Scanner::scanName(MultiChar& c, Parser& parser, bool& cont, std::string name)
{
c.appendTo(name);
if (!scanName(name))
return false;
else if (name.empty())
return true;
TokenLoc loc(mLoc);
mLoc.mLiteral.clear();
if (name.size() >= 2 && name[0] == '"' && name[name.size() - 1] == '"')
{
name = name.substr(1, name.size() - 2);
// allow keywords enclosed in ""
/// \todo optionally disable
if (mStrictKeywords)
{
cont = parser.parseName(name, loc, *this);
return true;
}
}
int i = 0;
std::string lowerCase = Misc::StringUtils::lowerCase(name);
bool isKeyword = false;
for (; sKeywords[i]; ++i)
if (lowerCase == sKeywords[i])
{
isKeyword = true;
break;
}
// Russian localization and some mods use a quirk - add newline character directly
// to compiled bytecode via HEX-editor to implement multiline messageboxes.
// Of course, original editor can not compile such script.
// Allow messageboxes to bypass the "incomplete string or name" error.
if (lowerCase == "messagebox")
enableIgnoreNewlines();
else if (isKeyword)
mIgnoreNewline = false;
if (sKeywords[i])
{
cont = parser.parseKeyword(i, loc, *this);
return true;
}
if (mExtensions)
{
if (int keyword = mExtensions->searchKeyword(lowerCase))
{
cont = parser.parseKeyword(keyword, loc, *this);
return true;
}
}
cont = parser.parseName(name, loc, *this);
return true;
}
bool Scanner::scanName(std::string& name)
{
MultiChar c;
bool error = false;
while (get(c))
{
if (!name.empty() && name[0] == '"')
{
if (c == '"')
{
c.appendTo(name);
break;
}
// ignoring escape sequences for now, because they are messing up stupid Windows path names.
// else if (c=='\\')
// {
// if (!get (c))
// {
// error = true;
// mErrorHandler.error ("incomplete escape sequence", mLoc);
// break;
// }
// }
else if (c == '\n')
{
if (mIgnoreNewline)
mErrorHandler.warning("string contains newline character, make sure that it is intended", mLoc);
else
{
bool allWhitespace = true;
for (size_t i = 1; i < name.size(); i++)
{
// ignore comments
if (name[i] == ';')
break;
else if (name[i] != '\t' && name[i] != ' ' && name[i] != '\r')
{
allWhitespace = false;
break;
}
}
if (allWhitespace)
{
name.clear();
mLoc.mLiteral.clear();
mErrorHandler.warning("unterminated empty string", mLoc);
return true;
}
error = true;
mErrorHandler.error("incomplete string or name", mLoc);
break;
}
}
}
else if (!(c == '"' && name.empty()))
{
if (!isStringCharacter(c) && !(mTolerantNames && (c == '.' || c == '-')))
{
putback(c);
break;
}
}
c.appendTo(name);
}
return !error;
}
bool Scanner::scanSpecial(MultiChar& c, Parser& parser, bool& cont)
{
bool expectName = mExpectName;
mExpectName = false;
int special = -1;
if (c == '\n')
special = S_newline;
else if (mIgnoreSpecial)
{
// Ignore junk special characters
TokenLoc loc = mLoc;
while (get(c))
{
if (c.isAlpha() || c == '_' || c == '"' || c.isDigit() || c == ';' || c == '\n')
{
putback(c);
break;
}
c.appendTo(loc.mLiteral);
}
mErrorHandler.warning("Stray special character at start of line", loc);
cont = true;
return true;
}
else if (c == '(' || c == '[') /// \todo option to disable the use of [ as alias for (
special = S_open;
else if (c == ')' || c == ']') /// \todo option to disable the use of ] as alias for )
special = S_close;
else if (c == '.')
{
MultiChar next;
// check, if this starts a float literal
if (get(next))
{
putback(next);
if (next.isDigit())
return scanFloat("", parser, cont);
}
special = S_member;
}
else if (startsComparisonOperator(c))
{
TokenLoc loc = mLoc;
std::string op;
c.appendTo(op);
while (get(c))
{
if (validComparisonOperatorCharacter(c))
c.appendTo(op);
else
{
putback(c);
break;
}
}
size_t end = op.size();
while (end > 0 && (op[end - 1] == '\t' || op[end - 1] == ' '))
--end;
switch (op[0])
{
case '=':
special = S_cmpEQ;
if (end != 2 || op[1] != '=')
mErrorHandler.warning("invalid operator " + op.substr(0, end) + ", treating it as ==", loc);
break;
case '<':
special = S_cmpLT;
if (op[1] == '=')
{
special = S_cmpLE;
if (end != 2)
mErrorHandler.warning("invalid operator " + op.substr(0, end) + ", treating it as <=", loc);
}
else if (end != 1)
mErrorHandler.warning("invalid operator " + op.substr(0, end) + ", treating it as <", loc);
break;
case '>':
special = S_cmpGT;
if (op[1] == '=')
{
special = S_cmpGE;
if (end != 2)
mErrorHandler.warning("invalid operator " + op.substr(0, end) + ", treating it as >=", loc);
}
else if (end != 1)
mErrorHandler.warning("invalid operator " + op.substr(0, end) + ", treating it as >", loc);
break;
case '!':
special = S_cmpNE;
if (end != 2 || op[1] != '=')
mErrorHandler.warning("invalid operator " + op.substr(0, end) + ", treating it as !=", loc);
break;
default:
return false;
}
}
else if (c.isMinusSign())
{
MultiChar next;
if (get(next))
{
if (next == '>')
special = S_ref;
else
{
putback(next);
special = S_minus;
}
}
else
special = S_minus;
}
else if (c == '+')
special = S_plus;
else if (c == '*')
special = S_mult;
else if (c == '/')
special = S_div;
else
return false;
if (special == S_newline)
mLoc.mLiteral = "<newline>";
else if (expectName && (special == S_member || special == S_minus))
{
bool tolerant = mTolerantNames;
mTolerantNames = true;
bool out = scanName(c, parser, cont);
mTolerantNames = tolerant;
return out;
}
TokenLoc loc(mLoc);
mLoc.mLiteral.clear();
cont = parser.parseSpecial(special, loc, *this);
return true;
}
bool Scanner::isStringCharacter(MultiChar& c, bool lookAhead)
{
if (lookAhead && c.isMinusSign())
{
/// \todo disable this when doing more stricter compiling. Also, find out who is
/// responsible for allowing it in the first place and meet up with that person in
/// a dark alley.
MultiChar next;
if (next.peek(mStream) && isStringCharacter(next, false))
return true;
}
return c.isAlpha() || c.isDigit() || c == '_' ||
/// \todo disable this when doing more stricter compiling
c == '`' || c == '\'';
}
// constructor
Scanner::Scanner(ErrorHandler& errorHandler, std::istream& inputStream, const Extensions* extensions)
: mErrorHandler(errorHandler)
, mStream(inputStream)
, mExtensions(extensions)
, mPutback(Putback_None)
, mPutbackCode(0)
, mPutbackInteger(0)
, mPutbackFloat(0)
, mStrictKeywords(false)
, mTolerantNames(false)
, mIgnoreNewline(false)
, mExpectName(false)
, mIgnoreSpecial(true)
{
}
void Scanner::scan(Parser& parser)
{
while (scanToken(parser))
;
mExpectName = false;
}
void Scanner::putbackSpecial(int code, const TokenLoc& loc)
{
mPutback = Putback_Special;
mPutbackCode = code;
mPutbackLoc = loc;
}
void Scanner::putbackInt(int value, const TokenLoc& loc)
{
mPutback = Putback_Integer;
mPutbackInteger = value;
mPutbackLoc = loc;
}
void Scanner::putbackFloat(float value, const TokenLoc& loc)
{
mPutback = Putback_Float;
mPutbackFloat = value;
mPutbackLoc = loc;
}
void Scanner::putbackName(const std::string& name, const TokenLoc& loc)
{
mPutback = Putback_Name;
mPutbackName = name;
mPutbackLoc = loc;
}
void Scanner::putbackKeyword(int keyword, const TokenLoc& loc)
{
mPutback = Putback_Keyword;
mPutbackCode = keyword;
mPutbackLoc = loc;
}
void Scanner::listKeywords(std::vector<std::string>& keywords)
{
for (int i = 0; Compiler::sKeywords[i]; ++i)
keywords.emplace_back(Compiler::sKeywords[i]);
if (mExtensions)
mExtensions->listKeywords(keywords);
}
void Scanner::enableIgnoreNewlines()
{
mIgnoreNewline = true;
}
void Scanner::enableStrictKeywords()
{
mStrictKeywords = true;
}
void Scanner::enableTolerantNames()
{
mTolerantNames = true;
}
void Scanner::enableExpectName()
{
mExpectName = true;
}
}
| 18,694
|
C++
|
.cpp
| 581
| 19.578313
| 120
| 0.442281
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,643
|
output.cpp
|
OpenMW_openmw/components/compiler/output.cpp
|
#include "output.hpp"
#include <algorithm>
#include <cassert>
#include <iterator>
#include "locals.hpp"
namespace Compiler
{
Output::Output(Locals& locals)
: mLocals(locals)
{
}
Interpreter::Program Output::getProgram() const
{
return Interpreter::Program{
.mInstructions = mCode,
.mIntegers = mLiterals.getIntegers(),
.mFloats = mLiterals.getFloats(),
.mStrings = mLiterals.getStrings(),
};
}
const Literals& Output::getLiterals() const
{
return mLiterals;
}
const std::vector<Interpreter::Type_Code>& Output::getCode() const
{
return mCode;
}
const Locals& Output::getLocals() const
{
return mLocals;
}
Literals& Output::getLiterals()
{
return mLiterals;
}
std::vector<Interpreter::Type_Code>& Output::getCode()
{
return mCode;
}
Locals& Output::getLocals()
{
return mLocals;
}
void Output::clear()
{
mLiterals.clear();
mCode.clear();
mLocals.clear();
}
}
| 1,121
|
C++
|
.cpp
| 51
| 15.823529
| 70
| 0.591124
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,644
|
exprparser.cpp
|
OpenMW_openmw/components/compiler/exprparser.cpp
|
#include "exprparser.hpp"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <components/esm/refid.hpp>
#include <components/misc/strings/lower.hpp>
#include "context.hpp"
#include "discardparser.hpp"
#include "errorhandler.hpp"
#include "extensions.hpp"
#include "generator.hpp"
#include "junkparser.hpp"
#include "locals.hpp"
#include "scanner.hpp"
#include "stringparser.hpp"
namespace Compiler
{
int ExprParser::getPriority(char op)
{
switch (op)
{
case '(':
return 0;
case 'e': // ==
case 'n': // !=
case 'l': // <
case 'L': // <=
case 'g': // <
case 'G': // >=
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
case 'm':
return 4;
}
return 0;
}
char ExprParser::getOperandType(int Index) const
{
assert(!mOperands.empty());
assert(Index >= 0);
assert(Index < static_cast<int>(mOperands.size()));
return mOperands[mOperands.size() - 1 - Index];
}
char ExprParser::getOperator() const
{
assert(!mOperators.empty());
return mOperators[mOperators.size() - 1];
}
bool ExprParser::isOpen() const
{
return std::find(mOperators.begin(), mOperators.end(), '(') != mOperators.end();
}
void ExprParser::popOperator()
{
assert(!mOperators.empty());
mOperators.resize(mOperators.size() - 1);
}
void ExprParser::popOperand()
{
assert(!mOperands.empty());
mOperands.resize(mOperands.size() - 1);
}
void ExprParser::replaceBinaryOperands()
{
char t1 = getOperandType(1);
char t2 = getOperandType();
popOperand();
popOperand();
if (t1 == t2)
mOperands.push_back(t1);
else if (t1 == 'f' || t2 == 'f')
mOperands.push_back('f');
else
throw std::logic_error("Failed to determine result operand type");
}
void ExprParser::pop()
{
char op = getOperator();
switch (op)
{
case 'm':
Generator::negate(mCode, getOperandType());
popOperator();
break;
case '+':
Generator::add(mCode, getOperandType(1), getOperandType());
popOperator();
replaceBinaryOperands();
break;
case '-':
Generator::sub(mCode, getOperandType(1), getOperandType());
popOperator();
replaceBinaryOperands();
break;
case '*':
Generator::mul(mCode, getOperandType(1), getOperandType());
popOperator();
replaceBinaryOperands();
break;
case '/':
Generator::div(mCode, getOperandType(1), getOperandType());
popOperator();
replaceBinaryOperands();
break;
case 'e':
case 'n':
case 'l':
case 'L':
case 'g':
case 'G':
Generator::compare(mCode, op, getOperandType(1), getOperandType());
popOperator();
popOperand();
popOperand();
mOperands.push_back('l');
break;
default:
throw std::logic_error("Unknown operator");
}
}
void ExprParser::pushIntegerLiteral(int value)
{
mNextOperand = false;
mOperands.push_back('l');
Generator::pushInt(mCode, mLiterals, value);
}
void ExprParser::pushFloatLiteral(float value)
{
mNextOperand = false;
mOperands.push_back('f');
Generator::pushFloat(mCode, mLiterals, value);
}
void ExprParser::pushBinaryOperator(char c)
{
while (!mOperators.empty() && getPriority(getOperator()) >= getPriority(c))
pop();
mOperators.push_back(c);
mNextOperand = true;
}
void ExprParser::close()
{
while (getOperator() != '(')
pop();
popOperator();
}
int ExprParser::parseArguments(const std::string& arguments, Scanner& scanner)
{
return parseArguments(arguments, scanner, mCode);
}
bool ExprParser::handleMemberAccess(const std::string& name)
{
mMemberOp = false;
std::string name2 = Misc::StringUtils::lowerCase(name);
auto id = ESM::RefId::stringRefId(Misc::StringUtils::lowerCase(mExplicit));
std::pair<char, bool> type = getContext().getMemberType(name2, id);
if (type.first != ' ')
{
Generator::fetchMember(mCode, mLiterals, type.first, name2, id.getRefIdString(), !type.second);
mNextOperand = false;
mExplicit.clear();
mOperands.push_back(type.first == 'f' ? 'f' : 'l');
return true;
}
return false;
}
ExprParser::ExprParser(
ErrorHandler& errorHandler, const Context& context, Locals& locals, Literals& literals, bool argument)
: Parser(errorHandler, context)
, mLocals(locals)
, mLiterals(literals)
, mNextOperand(true)
, mFirst(true)
, mArgument(argument)
, mRefOp(false)
, mMemberOp(false)
{
}
bool ExprParser::parseInt(int value, const TokenLoc& loc, Scanner& scanner)
{
if (!mExplicit.empty())
return Parser::parseInt(value, loc, scanner);
mFirst = false;
if (mNextOperand)
{
start();
pushIntegerLiteral(value);
mTokenLoc = loc;
return true;
}
else
{
scanner.putbackInt(value, loc);
return false;
}
}
bool ExprParser::parseFloat(float value, const TokenLoc& loc, Scanner& scanner)
{
if (!mExplicit.empty())
return Parser::parseFloat(value, loc, scanner);
mFirst = false;
if (mNextOperand)
{
start();
pushFloatLiteral(value);
mTokenLoc = loc;
return true;
}
else
{
scanner.putbackFloat(value, loc);
return false;
}
}
bool ExprParser::parseName(const std::string& name, const TokenLoc& loc, Scanner& scanner)
{
if (!mExplicit.empty())
{
if (!mRefOp)
{
if (mMemberOp && handleMemberAccess(name))
return true;
return Parser::parseName(name, loc, scanner);
}
else
{
mExplicit.clear();
getErrorHandler().warning("Stray explicit reference", loc);
}
}
mFirst = false;
if (mNextOperand)
{
start();
std::string name2 = Misc::StringUtils::lowerCase(name);
char type = mLocals.getType(name2);
if (type != ' ')
{
Generator::fetchLocal(mCode, type, mLocals.getIndex(name2));
mNextOperand = false;
mOperands.push_back(type == 'f' ? 'f' : 'l');
return true;
}
type = getContext().getGlobalType(name2);
if (type != ' ')
{
Generator::fetchGlobal(mCode, mLiterals, type, name2);
mNextOperand = false;
mOperands.push_back(type == 'f' ? 'f' : 'l');
return true;
}
if (mExplicit.empty() && getContext().isId(ESM::RefId::stringRefId(name2)))
{
mExplicit = name2;
return true;
}
// This is terrible, but of course we must have this for legacy content.
// Convert the string to a number even if it's impossible and use it as a number literal.
// Can't use stof/atof or to_string out of locale concerns.
float number;
std::stringstream stream(name2);
stream >> number;
stream.str(std::string());
stream.clear();
stream << number;
pushFloatLiteral(number);
mTokenLoc = loc;
getErrorHandler().warning("Parsing a non-variable string as a number: " + stream.str(), loc);
return true;
}
else
{
scanner.putbackName(name, loc);
return false;
}
}
bool ExprParser::parseKeyword(int keyword, const TokenLoc& loc, Scanner& scanner)
{
if (const Extensions* extensions = getContext().getExtensions())
{
char returnType; // ignored
std::string argumentType; // ignored
bool hasExplicit = false; // ignored
bool isInstruction = extensions->isInstruction(keyword, argumentType, hasExplicit);
if (isInstruction
|| (mExplicit.empty() && extensions->isFunction(keyword, returnType, argumentType, hasExplicit)))
{
std::string name = loc.mLiteral;
if (name.size() >= 2 && name[0] == '"' && name[name.size() - 1] == '"')
name = name.substr(1, name.size() - 2);
if (isInstruction || mLocals.getType(Misc::StringUtils::lowerCase(name)) != ' ')
{
// pretend this is not a keyword
return parseName(name, loc, scanner);
}
}
}
if (keyword == Scanner::K_end || keyword == Scanner::K_begin || keyword == Scanner::K_short
|| keyword == Scanner::K_long || keyword == Scanner::K_float || keyword == Scanner::K_if
|| keyword == Scanner::K_endif || keyword == Scanner::K_else || keyword == Scanner::K_elseif
|| keyword == Scanner::K_while || keyword == Scanner::K_endwhile || keyword == Scanner::K_return
|| keyword == Scanner::K_messagebox || keyword == Scanner::K_set || keyword == Scanner::K_to)
{
return parseName(loc.mLiteral, loc, scanner);
}
mFirst = false;
if (!mExplicit.empty())
{
if (mRefOp && mNextOperand)
{
// check for custom extensions
if (const Extensions* extensions = getContext().getExtensions())
{
char returnType;
std::string argumentType;
bool hasExplicit = true;
if (extensions->isFunction(keyword, returnType, argumentType, hasExplicit))
{
if (!hasExplicit)
{
getErrorHandler().warning("Stray explicit reference", loc);
mExplicit.clear();
}
start();
mTokenLoc = loc;
int optionals = parseArguments(argumentType, scanner);
extensions->generateFunctionCode(keyword, mCode, mLiterals, mExplicit, optionals);
mOperands.push_back(returnType);
mExplicit.clear();
mRefOp = false;
mNextOperand = false;
return true;
}
}
}
return Parser::parseKeyword(keyword, loc, scanner);
}
if (mNextOperand)
{
// check for custom extensions
if (const Extensions* extensions = getContext().getExtensions())
{
start();
char returnType;
std::string argumentType;
bool hasExplicit = false;
if (extensions->isFunction(keyword, returnType, argumentType, hasExplicit))
{
mTokenLoc = loc;
int optionals = parseArguments(argumentType, scanner);
extensions->generateFunctionCode(keyword, mCode, mLiterals, "", optionals);
mOperands.push_back(returnType);
mNextOperand = false;
return true;
}
}
}
else
{
scanner.putbackKeyword(keyword, loc);
return false;
}
return Parser::parseKeyword(keyword, loc, scanner);
}
bool ExprParser::parseSpecial(int code, const TokenLoc& loc, Scanner& scanner)
{
if (!mExplicit.empty())
{
if (mRefOp && code == Scanner::S_open)
{
/// \todo add option to disable this workaround
mOperators.push_back('(');
mTokenLoc = loc;
return true;
}
if (!mRefOp && code == Scanner::S_ref)
{
mRefOp = true;
return true;
}
if (!mMemberOp && code == Scanner::S_member)
{
mMemberOp = true;
return true;
}
return Parser::parseSpecial(code, loc, scanner);
}
mFirst = false;
if (code == Scanner::S_newline)
{
// end marker
if (mTokenLoc.mLiteral.empty())
mTokenLoc = loc;
scanner.putbackSpecial(code, loc);
return false;
}
if (code == Scanner::S_minus && mNextOperand)
{
// unary
mOperators.push_back('m');
mTokenLoc = loc;
return true;
}
if (code == Scanner::S_plus && mNextOperand)
{
// Also unary, but +, just ignore it
mTokenLoc = loc;
return true;
}
if (code == Scanner::S_open)
{
if (mNextOperand)
{
mOperators.push_back('(');
mTokenLoc = loc;
return true;
}
else
{
scanner.putbackSpecial(code, loc);
return false;
}
}
if (code == Scanner::S_close && !mNextOperand)
{
if (isOpen())
{
close();
return true;
}
mTokenLoc = loc;
scanner.putbackSpecial(code, loc);
return false;
}
if (!mNextOperand)
{
mTokenLoc = loc;
char c = 0; // comparison
switch (code)
{
case Scanner::S_plus:
c = '+';
break;
case Scanner::S_minus:
c = '-';
break;
case Scanner::S_mult:
pushBinaryOperator('*');
return true;
case Scanner::S_div:
pushBinaryOperator('/');
return true;
case Scanner::S_cmpEQ:
c = 'e';
break;
case Scanner::S_cmpNE:
c = 'n';
break;
case Scanner::S_cmpLT:
c = 'l';
break;
case Scanner::S_cmpLE:
c = 'L';
break;
case Scanner::S_cmpGT:
c = 'g';
break;
case Scanner::S_cmpGE:
c = 'G';
break;
}
if (c)
{
if (mArgument && !isOpen())
{
// expression ends here
// Thank you Morrowind for this rotten syntax :(
scanner.putbackSpecial(code, loc);
return false;
}
pushBinaryOperator(c);
return true;
}
}
return Parser::parseSpecial(code, loc, scanner);
}
void ExprParser::reset()
{
mOperands.clear();
mOperators.clear();
mNextOperand = true;
mCode.clear();
mFirst = true;
mExplicit.clear();
mRefOp = false;
mMemberOp = false;
Parser::reset();
}
char ExprParser::append(std::vector<Interpreter::Type_Code>& code)
{
if (mOperands.empty() && mOperators.empty())
{
getErrorHandler().error("Missing expression", mTokenLoc);
return 'l';
}
if (mNextOperand || mOperands.empty())
{
getErrorHandler().error("Syntax error in expression", mTokenLoc);
return 'l';
}
while (!mOperators.empty())
pop();
std::copy(mCode.begin(), mCode.end(), std::back_inserter(code));
assert(mOperands.size() == 1);
return mOperands[0];
}
int ExprParser::parseArguments(const std::string& arguments, Scanner& scanner,
std::vector<Interpreter::Type_Code>& code, int ignoreKeyword, bool expectNames)
{
bool optional = false;
int optionalCount = 0;
ExprParser parser(getErrorHandler(), getContext(), mLocals, mLiterals, true);
StringParser stringParser(getErrorHandler(), getContext(), mLiterals);
DiscardParser discardParser(getErrorHandler(), getContext());
JunkParser junkParser(getErrorHandler(), getContext(), ignoreKeyword);
std::stack<std::vector<Interpreter::Type_Code>> stack;
for (char argument : arguments)
{
if (argument == '/')
{
optional = true;
}
else if (argument == 'S' || argument == 'c' || argument == 'x')
{
stringParser.reset();
if (optional || argument == 'x')
stringParser.setOptional(true);
if (argument == 'c')
stringParser.smashCase();
if (argument == 'x')
stringParser.discard();
scanner.enableExpectName();
scanner.scan(stringParser);
if ((optional || argument == 'x') && stringParser.isEmpty())
break;
if (argument != 'x')
{
std::vector<Interpreter::Type_Code> tmp;
stringParser.append(tmp);
stack.push(tmp);
if (optional)
++optionalCount;
}
else
getErrorHandler().warning("Extra argument", stringParser.getTokenLoc());
}
else if (argument == 'X')
{
parser.reset();
parser.setOptional(true);
scanner.scan(parser);
if (parser.isEmpty())
break;
else
getErrorHandler().warning("Extra argument", parser.getTokenLoc());
}
else if (argument == 'z')
{
discardParser.reset();
discardParser.setOptional(true);
scanner.scan(discardParser);
if (discardParser.isEmpty())
break;
else
getErrorHandler().warning("Extra argument", discardParser.getTokenLoc());
}
else if (argument == 'j')
{
/// \todo disable this when operating in strict mode
junkParser.reset();
scanner.scan(junkParser);
}
else
{
parser.reset();
if (optional)
parser.setOptional(true);
if (expectNames)
scanner.enableExpectName();
scanner.scan(parser);
if (optional && parser.isEmpty())
break;
std::vector<Interpreter::Type_Code> tmp;
char type = parser.append(tmp);
if (type != argument)
Generator::convert(tmp, type, argument);
stack.push(tmp);
if (optional)
++optionalCount;
}
}
while (!stack.empty())
{
std::vector<Interpreter::Type_Code>& tmp = stack.top();
std::copy(tmp.begin(), tmp.end(), std::back_inserter(code));
stack.pop();
}
return optionalCount;
}
const TokenLoc& ExprParser::getTokenLoc() const
{
return mTokenLoc;
}
}
| 21,086
|
C++
|
.cpp
| 621
| 21.191626
| 113
| 0.482631
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,645
|
errorhandler.cpp
|
OpenMW_openmw/components/compiler/errorhandler.cpp
|
#include "errorhandler.hpp"
namespace Compiler
{
ErrorHandler::ErrorHandler()
: mWarnings(0)
, mErrors(0)
, mWarningsMode(1)
, mDowngradeErrors(false)
{
}
ErrorHandler::~ErrorHandler() = default;
// Was compiling successful?
bool ErrorHandler::isGood() const
{
return mErrors == 0;
}
// Return number of errors
int ErrorHandler::countErrors() const
{
return mErrors;
}
// Return number of warnings
int ErrorHandler::countWarnings() const
{
return mWarnings;
}
// Generate a warning message.
void ErrorHandler::warning(const std::string& message, const TokenLoc& loc)
{
if (mWarningsMode == 1 ||
// temporarily change from mode 2 to mode 1 if error downgrading is enabled to
// avoid infinite recursion
(mWarningsMode == 2 && mDowngradeErrors))
{
++mWarnings;
report(message, loc, WarningMessage);
}
else if (mWarningsMode == 2)
error(message, loc);
}
// Generate an error message.
void ErrorHandler::error(const std::string& message, const TokenLoc& loc)
{
if (mDowngradeErrors)
{
warning(message, loc);
return;
}
++mErrors;
report(message, loc, ErrorMessage);
}
// Generate an error message for an unexpected EOF.
void ErrorHandler::endOfFile()
{
++mErrors;
report("unexpected end of file", ErrorMessage);
}
// Remove all previous error/warning events
void ErrorHandler::reset()
{
mErrors = mWarnings = 0;
}
void ErrorHandler::setWarningsMode(int mode)
{
mWarningsMode = mode;
}
void ErrorHandler::downgradeErrors(bool downgrade)
{
mDowngradeErrors = downgrade;
}
ErrorDowngrade::ErrorDowngrade(ErrorHandler& handler)
: mHandler(handler)
{
mHandler.downgradeErrors(true);
}
ErrorDowngrade::~ErrorDowngrade()
{
mHandler.downgradeErrors(false);
}
}
| 2,134
|
C++
|
.cpp
| 80
| 19.6
| 90
| 0.609252
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,646
|
protocol.cpp
|
OpenMW_openmw/components/navmeshtool/protocol.cpp
|
#include "protocol.hpp"
#include <components/serialization/binaryreader.hpp>
#include <components/serialization/binarywriter.hpp>
#include <components/serialization/format.hpp>
#include <components/serialization/sizeaccumulator.hpp>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include <string>
namespace NavMeshTool
{
namespace
{
std::string formatMagic(const char (&value)[std::size(messageMagic)])
{
std::ostringstream stream;
for (const char v : value)
{
if (std::isprint(v) && !std::isspace(v))
stream << '\'' << v << '\'';
else
stream << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2)
<< static_cast<int>(v);
stream << ' ';
}
return stream.str();
}
template <Serialization::Mode mode>
struct Format : Serialization::Format<mode, Format<mode>>
{
using Serialization::Format<mode, Format<mode>>::operator();
template <class Visitor, class T>
auto operator()(Visitor&& visitor, T& value) const
-> std::enable_if_t<std::is_same_v<std::decay_t<T>, Message>>
{
if constexpr (mode == Serialization::Mode::Write)
visitor(*this, messageMagic);
else
{
static_assert(mode == Serialization::Mode::Read);
char magic[std::size(messageMagic)];
visitor(*this, magic);
if (std::memcmp(magic, messageMagic, sizeof(magic)) != 0)
throw std::runtime_error("Bad navmeshtool message magic: " + formatMagic(magic));
}
visitor(*this, value.mType);
visitor(*this, value.mSize);
if constexpr (mode == Serialization::Mode::Write)
visitor(*this, value.mData, value.mSize);
else
visitor(*this, value.mData);
}
template <class Visitor, class T>
auto operator()(Visitor&& visitor, T& value) const
-> std::enable_if_t<std::is_same_v<std::decay_t<T>, ExpectedCells>>
{
visitor(*this, value.mCount);
}
template <class Visitor, class T>
auto operator()(Visitor&& visitor, T& value) const
-> std::enable_if_t<std::is_same_v<std::decay_t<T>, ProcessedCells>>
{
visitor(*this, value.mCount);
}
template <class Visitor, class T>
auto operator()(Visitor&& visitor, T& value) const
-> std::enable_if_t<std::is_same_v<std::decay_t<T>, ExpectedTiles>>
{
visitor(*this, value.mCount);
}
template <class Visitor, class T>
auto operator()(Visitor&& visitor, T& value) const
-> std::enable_if_t<std::is_same_v<std::decay_t<T>, GeneratedTiles>>
{
visitor(*this, value.mCount);
}
};
template <class T>
std::vector<std::byte> serializeToVector(const T& value)
{
constexpr Format<Serialization::Mode::Write> format;
Serialization::SizeAccumulator sizeAccumulator;
format(sizeAccumulator, value);
std::vector<std::byte> buffer(sizeAccumulator.value());
format(Serialization::BinaryWriter(buffer.data(), buffer.data() + buffer.size()), value);
return buffer;
}
template <class T>
std::vector<std::byte> serializeImpl(const T& value)
{
const auto data = serializeToVector(value);
const Message message{ static_cast<std::uint64_t>(T::sMessageType), static_cast<std::uint64_t>(data.size()),
data.data() };
return serializeToVector(message);
}
}
std::vector<std::byte> serialize(const ExpectedCells& value)
{
return serializeImpl(value);
}
std::vector<std::byte> serialize(const ProcessedCells& value)
{
return serializeImpl(value);
}
std::vector<std::byte> serialize(const ExpectedTiles& value)
{
return serializeImpl(value);
}
std::vector<std::byte> serialize(const GeneratedTiles& value)
{
return serializeImpl(value);
}
const std::byte* deserialize(const std::byte* begin, const std::byte* end, Message& message)
{
try
{
constexpr Format<Serialization::Mode::Read> format;
Serialization::BinaryReader reader(begin, end);
format(reader, message);
return message.mData + message.mSize;
}
catch (const Serialization::NotEnoughData&)
{
return begin;
}
}
TypedMessage decode(const Message& message)
{
constexpr Format<Serialization::Mode::Read> format;
Serialization::BinaryReader reader(message.mData, message.mData + message.mSize);
switch (static_cast<MessageType>(message.mType))
{
case MessageType::ExpectedCells:
{
ExpectedCells value;
format(reader, value);
return value;
}
case MessageType::ProcessedCells:
{
ProcessedCells value;
format(reader, value);
return value;
}
case MessageType::ExpectedTiles:
{
ExpectedTiles value;
format(reader, value);
return value;
}
case MessageType::GeneratedTiles:
{
GeneratedTiles value;
format(reader, value);
return value;
}
}
throw std::logic_error("Unsupported message type: " + std::to_string(message.mType));
}
}
| 6,081
|
C++
|
.cpp
| 160
| 26.18125
| 120
| 0.541836
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,647
|
serialization.cpp
|
OpenMW_openmw/components/lua/serialization.cpp
|
#include "serialization.hpp"
#include <osg/Matrixf>
#include <osg/Quat>
#include <osg/Vec2f>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include <components/misc/color.hpp>
#include <components/misc/endianness.hpp>
#include "luastate.hpp"
#include "utilpackage.hpp"
namespace LuaUtil
{
constexpr unsigned char FORMAT_VERSION = 0;
enum class SerializedType : char
{
NUMBER = 0x0,
LONG_STRING = 0x1,
BOOLEAN = 0x2,
TABLE_START = 0x3,
TABLE_END = 0x4,
VEC2 = 0x10,
VEC3 = 0x11,
TRANSFORM_M = 0x12,
TRANSFORM_Q = 0x13,
VEC4 = 0x14,
COLOR = 0x15,
// All values should be lesser than 0x20 (SHORT_STRING_FLAG).
};
constexpr unsigned char SHORT_STRING_FLAG = 0x20; // 0b001SSSSS. SSSSS = string length
constexpr unsigned char CUSTOM_FULL_FLAG = 0x40; // 0b01TTTTTT + 32bit dataSize
constexpr unsigned char CUSTOM_COMPACT_FLAG = 0x80; // 0b1SSSSTTT. SSSS = dataSize, TTT = (typeName size - 1)
static void appendType(BinaryData& out, SerializedType type)
{
out.push_back(static_cast<char>(type));
}
template <typename T>
static void appendValue(BinaryData& out, T v)
{
v = Misc::toLittleEndian(v);
out.append(reinterpret_cast<const char*>(&v), sizeof(v));
}
template <typename T>
static T getValue(std::string_view& binaryData)
{
if (binaryData.size() < sizeof(T))
throw std::runtime_error("Unexpected end of serialized data.");
T v;
std::memcpy(&v, binaryData.data(), sizeof(T));
binaryData = binaryData.substr(sizeof(T));
return Misc::fromLittleEndian(v);
}
static void appendString(BinaryData& out, std::string_view str)
{
if (str.size() < 32)
out.push_back(SHORT_STRING_FLAG | char(str.size()));
else
{
appendType(out, SerializedType::LONG_STRING);
appendValue<uint32_t>(out, str.size());
}
out.append(str.data(), str.size());
}
static void appendData(BinaryData& out, const void* data, size_t dataSize)
{
out.append(reinterpret_cast<const char*>(data), dataSize);
}
void UserdataSerializer::append(BinaryData& out, std::string_view typeName, const void* data, size_t dataSize)
{
assert(!typeName.empty() && typeName.size() <= 64);
if (typeName.size() <= 8 && dataSize < 16)
{ // Compact form: 0b1SSSSTTT. SSSS = dataSize, TTT = (typeName size - 1).
unsigned char t = CUSTOM_COMPACT_FLAG | (dataSize << 3) | (typeName.size() - 1);
out.push_back(t);
}
else
{ // Full form: 0b01TTTTTT + 32bit dataSize.
unsigned char t = CUSTOM_FULL_FLAG | (typeName.size() - 1);
out.push_back(t);
appendValue<uint32_t>(out, dataSize);
}
out.append(typeName.data(), typeName.size());
appendData(out, data, dataSize);
}
void UserdataSerializer::appendRefNum(BinaryData& out, ESM::RefNum refnum)
{
static_assert(sizeof(ESM::RefNum) == 8);
refnum.mIndex = Misc::toLittleEndian(refnum.mIndex);
refnum.mContentFile = Misc::toLittleEndian(refnum.mContentFile);
append(out, sRefNumTypeName, &refnum, sizeof(ESM::RefNum));
}
bool BasicSerializer::serialize(BinaryData& out, const sol::userdata& data) const
{
appendRefNum(out, cast<ESM::RefNum>(data));
return true;
}
bool BasicSerializer::deserialize(std::string_view typeName, std::string_view binaryData, lua_State* lua) const
{
if (typeName != sRefNumTypeName)
return false;
ESM::RefNum refnum = loadRefNum(binaryData);
if (mAdjustContentFilesIndexFn)
refnum.mContentFile = mAdjustContentFilesIndexFn(refnum.mContentFile);
sol::stack::push<ESM::RefNum>(lua, refnum);
return true;
}
ESM::RefNum UserdataSerializer::loadRefNum(std::string_view data)
{
if (data.size() != sizeof(ESM::RefNum))
throw std::runtime_error("Incorrect serialization format. Size of RefNum doesn't match.");
ESM::RefNum refnum;
std::memcpy(&refnum, data.data(), sizeof(ESM::RefNum));
refnum.mIndex = Misc::fromLittleEndian(refnum.mIndex);
refnum.mContentFile = Misc::fromLittleEndian(refnum.mContentFile);
return refnum;
}
static void serializeUserdata(
BinaryData& out, const sol::userdata& data, const UserdataSerializer* customSerializer)
{
if (data.is<osg::Vec2f>())
{
appendType(out, SerializedType::VEC2);
osg::Vec2f v = data.as<osg::Vec2f>();
appendValue<double>(out, v.x());
appendValue<double>(out, v.y());
return;
}
if (data.is<osg::Vec3f>())
{
appendType(out, SerializedType::VEC3);
osg::Vec3f v = data.as<osg::Vec3f>();
appendValue<double>(out, v.x());
appendValue<double>(out, v.y());
appendValue<double>(out, v.z());
return;
}
if (data.is<TransformM>())
{
appendType(out, SerializedType::TRANSFORM_M);
osg::Matrixf matrix = data.as<TransformM>().mM;
for (size_t i = 0; i < 4; i++)
for (size_t j = 0; j < 4; j++)
appendValue<double>(out, matrix(i, j));
return;
}
if (data.is<TransformQ>())
{
appendType(out, SerializedType::TRANSFORM_Q);
osg::Quat quat = data.as<TransformQ>().mQ;
for (size_t i = 0; i < 4; i++)
appendValue<double>(out, quat[i]);
return;
}
if (data.is<osg::Vec4f>())
{
appendType(out, SerializedType::VEC4);
osg::Vec4f v = data.as<osg::Vec4f>();
appendValue<double>(out, v.x());
appendValue<double>(out, v.y());
appendValue<double>(out, v.z());
appendValue<double>(out, v.w());
return;
}
if (data.is<Misc::Color>())
{
appendType(out, SerializedType::COLOR);
Misc::Color v = data.as<Misc::Color>();
appendValue<float>(out, v.r());
appendValue<float>(out, v.g());
appendValue<float>(out, v.b());
appendValue<float>(out, v.a());
return;
}
if (customSerializer && customSerializer->serialize(out, data))
return;
else
throw std::runtime_error("Value is not serializable.");
}
static void serialize(
BinaryData& out, const sol::object& obj, const UserdataSerializer* customSerializer, int recursionCounter)
{
if (obj.get_type() == sol::type::lightuserdata)
throw std::runtime_error("Light userdata is not allowed to be serialized.");
if (obj.is<sol::function>())
throw std::runtime_error("Functions are not allowed to be serialized.");
else if (obj.is<sol::userdata>())
serializeUserdata(out, obj, customSerializer);
else if (obj.is<sol::lua_table>())
{
if (recursionCounter >= 32)
throw std::runtime_error(
"Can not serialize more than 32 nested tables. Likely the table contains itself.");
sol::table table = obj;
appendType(out, SerializedType::TABLE_START);
for (auto& [key, value] : table)
{
serialize(out, key, customSerializer, recursionCounter + 1);
serialize(out, value, customSerializer, recursionCounter + 1);
}
appendType(out, SerializedType::TABLE_END);
}
else if (obj.is<double>())
{
appendType(out, SerializedType::NUMBER);
appendValue<double>(out, obj.as<double>());
}
else if (obj.is<std::string_view>())
appendString(out, obj.as<std::string_view>());
else if (obj.is<bool>())
{
char v = obj.as<bool>() ? 1 : 0;
appendType(out, SerializedType::BOOLEAN);
out.push_back(v);
}
else
throw std::runtime_error("Unknown Lua type.");
}
static void deserializeImpl(
lua_State* lua, std::string_view& binaryData, const UserdataSerializer* customSerializer, bool readOnly)
{
if (binaryData.empty())
throw std::runtime_error("Unexpected end of serialized data.");
unsigned char type = binaryData[0];
binaryData = binaryData.substr(1);
if (type & (CUSTOM_COMPACT_FLAG | CUSTOM_FULL_FLAG))
{
size_t typeNameSize, dataSize;
if (type & CUSTOM_COMPACT_FLAG)
{ // Compact form: 0b1SSSSTTT. SSSS = dataSize, TTT = (typeName size - 1).
typeNameSize = (type & 7) + 1;
dataSize = (type >> 3) & 15;
}
else
{ // Full form: 0b01TTTTTT + 32bit dataSize.
typeNameSize = (type & 63) + 1;
dataSize = getValue<uint32_t>(binaryData);
}
std::string_view typeName = binaryData.substr(0, typeNameSize);
std::string_view data = binaryData.substr(typeNameSize, dataSize);
binaryData = binaryData.substr(typeNameSize + dataSize);
if (!customSerializer || !customSerializer->deserialize(typeName, data, lua))
throw std::runtime_error("Unknown type in serialized data: " + std::string(typeName));
return;
}
if (type & SHORT_STRING_FLAG)
{
size_t size = type & 0x1f;
sol::stack::push<std::string_view>(lua, binaryData.substr(0, size));
binaryData = binaryData.substr(size);
return;
}
switch (static_cast<SerializedType>(type))
{
case SerializedType::NUMBER:
sol::stack::push<double>(lua, getValue<double>(binaryData));
return;
case SerializedType::BOOLEAN:
sol::stack::push<bool>(lua, getValue<char>(binaryData) != 0);
return;
case SerializedType::LONG_STRING:
{
uint32_t size = getValue<uint32_t>(binaryData);
sol::stack::push<std::string_view>(lua, binaryData.substr(0, size));
binaryData = binaryData.substr(size);
return;
}
case SerializedType::TABLE_START:
{
lua_createtable(lua, 0, 0);
while (!binaryData.empty() && binaryData[0] != char(SerializedType::TABLE_END))
{
deserializeImpl(lua, binaryData, customSerializer, readOnly);
deserializeImpl(lua, binaryData, customSerializer, readOnly);
lua_settable(lua, -3);
}
if (binaryData.empty())
throw std::runtime_error("Unexpected end of serialized data.");
binaryData = binaryData.substr(1);
if (readOnly)
sol::stack::push(lua, makeReadOnly(sol::stack::pop<sol::table>(lua)));
return;
}
case SerializedType::TABLE_END:
throw std::runtime_error("Unexpected end of table during deserialization.");
case SerializedType::VEC2:
{
float x = getValue<double>(binaryData);
float y = getValue<double>(binaryData);
sol::stack::push<osg::Vec2f>(lua, osg::Vec2f(x, y));
return;
}
case SerializedType::VEC3:
{
float x = getValue<double>(binaryData);
float y = getValue<double>(binaryData);
float z = getValue<double>(binaryData);
sol::stack::push<osg::Vec3f>(lua, osg::Vec3f(x, y, z));
return;
}
case SerializedType::TRANSFORM_M:
{
osg::Matrixf mat;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
mat(i, j) = getValue<double>(binaryData);
sol::stack::push<TransformM>(lua, asTransform(mat));
return;
}
case SerializedType::TRANSFORM_Q:
{
osg::Quat q;
for (int i = 0; i < 4; i++)
q[i] = getValue<double>(binaryData);
sol::stack::push<TransformQ>(lua, asTransform(q));
return;
}
case SerializedType::VEC4:
{
float x = getValue<double>(binaryData);
float y = getValue<double>(binaryData);
float z = getValue<double>(binaryData);
float w = getValue<double>(binaryData);
sol::stack::push<osg::Vec4f>(lua, osg::Vec4f(x, y, z, w));
return;
}
case SerializedType::COLOR:
{
float r = getValue<float>(binaryData);
float g = getValue<float>(binaryData);
float b = getValue<float>(binaryData);
float a = getValue<float>(binaryData);
sol::stack::push<Misc::Color>(lua, Misc::Color(r, g, b, a));
return;
}
}
throw std::runtime_error("Unknown type in serialized data: " + std::to_string(type));
}
BinaryData serialize(const sol::object& obj, const UserdataSerializer* customSerializer)
{
if (obj == sol::nil)
return "";
BinaryData res;
res.push_back(FORMAT_VERSION);
serialize(res, obj, customSerializer, 0);
return res;
}
sol::object deserialize(
lua_State* lua, std::string_view binaryData, const UserdataSerializer* customSerializer, bool readOnly)
{
if (binaryData.empty())
return sol::nil;
if (binaryData[0] != FORMAT_VERSION)
throw std::runtime_error("Incorrect version of Lua serialization format: "
+ std::to_string(static_cast<unsigned>(binaryData[0])));
binaryData = binaryData.substr(1);
deserializeImpl(lua, binaryData, customSerializer, readOnly);
if (!binaryData.empty())
throw std::runtime_error("Unexpected data after serialized object");
return sol::stack::pop<sol::object>(lua);
}
}
| 14,642
|
C++
|
.cpp
| 360
| 29.638889
| 115
| 0.559195
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,648
|
yamlloader.cpp
|
OpenMW_openmw/components/lua/yamlloader.cpp
|
#include "yamlloader.hpp"
#include <charconv>
#include <cmath>
#include <limits>
#include <regex>
#include <stdexcept>
#include <system_error>
#include <vector>
#include <sol/object.hpp>
#include <sol/state_view.hpp>
#include <yaml-cpp/yaml.h>
#include <components/misc/strings/format.hpp>
#include <components/misc/strings/lower.hpp>
namespace LuaUtil
{
namespace
{
constexpr uint64_t maxDepth = 250;
enum class ScalarType
{
Boolean,
Decimal,
Float,
Hexadecimal,
Infinity,
NotNumber,
Null,
Octal,
String
};
sol::object loadAll(const std::vector<YAML::Node>& rootNodes, const sol::state_view& lua);
sol::object getNode(const YAML::Node& node, const sol::state_view& lua, uint64_t depth);
sol::table getMap(const YAML::Node& node, const sol::state_view& lua, uint64_t depth);
sol::table getArray(const YAML::Node& node, const sol::state_view& lua, uint64_t depth);
ScalarType getScalarType(const YAML::Node& node);
sol::object getScalar(const YAML::Node& node, const sol::state_view& lua);
[[noreturn]] void nodeError(const YAML::Node& node, const std::string& message);
}
sol::object loadYaml(const std::string& input, const sol::state_view& lua)
{
std::vector<YAML::Node> rootNodes = YAML::LoadAll(input);
return loadAll(rootNodes, lua);
}
sol::object loadYaml(std::istream& input, const sol::state_view& lua)
{
std::vector<YAML::Node> rootNodes = YAML::LoadAll(input);
return loadAll(rootNodes, lua);
}
namespace
{
sol::object loadAll(const std::vector<YAML::Node>& rootNodes, const sol::state_view& lua)
{
if (rootNodes.empty())
return sol::nil;
if (rootNodes.size() == 1)
return getNode(rootNodes[0], lua, 0);
sol::table documentsTable(lua, sol::create);
for (const auto& root : rootNodes)
{
documentsTable.add(getNode(root, lua, 1));
}
return documentsTable;
}
sol::object getNode(const YAML::Node& node, const sol::state_view& lua, uint64_t depth)
{
if (depth >= maxDepth)
throw std::runtime_error("Maximum layers depth exceeded, probably caused by a circular reference");
++depth;
if (node.IsMap())
return getMap(node, lua, depth);
else if (node.IsSequence())
return getArray(node, lua, depth);
else if (node.IsScalar())
return getScalar(node, lua);
else if (node.IsNull())
return sol::nil;
nodeError(node, "An unknown YAML node encountered");
}
sol::table getMap(const YAML::Node& node, const sol::state_view& lua, uint64_t depth)
{
sol::table childTable(lua, sol::create);
for (const auto& pair : node)
{
if (pair.first.IsMap())
nodeError(pair.first, "Only scalar nodes can be used as keys, encountered map instead");
if (pair.first.IsSequence())
nodeError(pair.first, "Only scalar nodes can be used as keys, encountered array instead");
if (pair.first.IsNull())
nodeError(pair.first, "Only scalar nodes can be used as keys, encountered null instead");
auto key = getNode(pair.first, lua, depth);
if (key.get_type() == sol::type::number && std::isnan(key.as<double>()))
nodeError(pair.first, "Only scalar nodes can be used as keys, encountered nan instead");
childTable[key] = getNode(pair.second, lua, depth);
}
return childTable;
}
sol::table getArray(const YAML::Node& node, const sol::state_view& lua, uint64_t depth)
{
sol::table childTable(lua, sol::create);
for (const auto& child : node)
{
childTable.add(getNode(child, lua, depth));
}
return childTable;
}
ScalarType getScalarType(const YAML::Node& node)
{
const auto& tag = node.Tag();
const auto& value = node.Scalar();
if (tag == "!")
return ScalarType::String;
// Note that YAML allows to explicitely specify a scalar type via tag (e.g. "!!bool"), but it makes no
// sense in Lua:
// 1. Both integers and floats use the "number" type prior to Lua 5.3
// 2. Strings can be quoted, which is more readable than "!!str"
// 3. Most of possible conversions are invalid or their result is unclear
// So ignore this feature for now.
if (tag != "?")
nodeError(node, "An invalid tag '" + tag + "' encountered");
if (value.empty())
return ScalarType::Null;
// Resolve type according to YAML 1.2 Core Schema (see https://yaml.org/spec/1.2.2/#103-core-schema)
static const std::regex boolRegex("true|True|TRUE|false|False|FALSE", std::regex_constants::extended);
if (std::regex_match(node.Scalar(), boolRegex))
return ScalarType::Boolean;
static const std::regex decimalRegex("[-+]?[0-9]+", std::regex_constants::extended);
if (std::regex_match(node.Scalar(), decimalRegex))
return ScalarType::Decimal;
static const std::regex floatRegex(
"[-+]?([.][0-9]+|[0-9]+([.][0-9]*)?)([eE][-+]?[0-9]+)?", std::regex_constants::extended);
if (std::regex_match(node.Scalar(), floatRegex))
return ScalarType::Float;
static const std::regex octalRegex("0o[0-7]+", std::regex_constants::extended);
if (std::regex_match(node.Scalar(), octalRegex))
return ScalarType::Octal;
static const std::regex hexdecimalRegex("0x[0-9a-fA-F]+", std::regex_constants::extended);
if (std::regex_match(node.Scalar(), hexdecimalRegex))
return ScalarType::Hexadecimal;
static const std::regex infinityRegex("[-+]?([.]inf|[.]Inf|[.]INF)", std::regex_constants::extended);
if (std::regex_match(node.Scalar(), infinityRegex))
return ScalarType::Infinity;
static const std::regex nanRegex("[.]nan|[.]NaN|[.]NAN", std::regex_constants::extended);
if (std::regex_match(node.Scalar(), nanRegex))
return ScalarType::NotNumber;
static const std::regex nullRegex("null|Null|NULL|~", std::regex_constants::extended);
if (std::regex_match(node.Scalar(), nullRegex))
return ScalarType::Null;
return ScalarType::String;
}
sol::object getScalar(const YAML::Node& node, const sol::state_view& lua)
{
auto type = getScalarType(node);
const auto& value = node.Scalar();
switch (type)
{
case ScalarType::Null:
return sol::nil;
case ScalarType::String:
return sol::make_object<std::string>(lua, value);
case ScalarType::NotNumber:
return sol::make_object<double>(lua, std::nan(""));
case ScalarType::Infinity:
{
if (!value.empty() && value[0] == '-')
return sol::make_object<double>(lua, -std::numeric_limits<double>::infinity());
return sol::make_object<double>(lua, std::numeric_limits<double>::infinity());
}
case ScalarType::Boolean:
{
if (Misc::StringUtils::lowerCase(value) == "true")
return sol::make_object<bool>(lua, true);
if (Misc::StringUtils::lowerCase(value) == "false")
return sol::make_object<bool>(lua, false);
nodeError(node, "Can not read a boolean value '" + value + "'");
}
case ScalarType::Decimal:
{
int offset = 0;
// std::from_chars does not support "+" sign
if (!value.empty() && value[0] == '+')
++offset;
int result = 0;
const auto status = std::from_chars(value.data() + offset, value.data() + value.size(), result);
if (status.ec == std::errc())
return sol::make_object<int>(lua, result);
nodeError(node, "Can not read a decimal value '" + value + "'");
}
case ScalarType::Float:
{
// Not all compilers support std::from_chars for floats
double result = 0.0;
bool success = YAML::convert<double>::decode(node, result);
if (success)
return sol::make_object<double>(lua, result);
nodeError(node, "Can not read a float value '" + value + "'");
}
case ScalarType::Hexadecimal:
{
int result = 0;
const auto status = std::from_chars(value.data() + 2, value.data() + value.size(), result, 16);
if (status.ec == std::errc())
return sol::make_object<int>(lua, result);
nodeError(node, "Can not read a hexadecimal value '" + value + "'");
}
case ScalarType::Octal:
{
int result = 0;
const auto status = std::from_chars(value.data() + 2, value.data() + value.size(), result, 8);
if (status.ec == std::errc())
return sol::make_object<int>(lua, result);
nodeError(node, "Can not read an octal value '" + value + "'");
}
default:
nodeError(node, "An unknown scalar '" + value + "' encountered");
}
}
[[noreturn]] void nodeError(const YAML::Node& node, const std::string& message)
{
const auto& mark = node.Mark();
std::string error = Misc::StringUtils::format(
" at line=%d column=%d position=%d", mark.line + 1, mark.column + 1, mark.pos + 1);
throw std::runtime_error(message + error);
}
}
}
| 10,799
|
C++
|
.cpp
| 225
| 34.182222
| 116
| 0.532655
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,649
|
utilpackage.cpp
|
OpenMW_openmw/components/lua/utilpackage.cpp
|
#include "utilpackage.hpp"
#include <algorithm>
#include <array>
#include <iomanip>
#include <limits>
#include <sstream>
#include <components/misc/color.hpp>
#include <components/misc/mathutil.hpp>
#include "luastate.hpp"
#include "util.hpp"
#include "shapes/box.hpp"
namespace sol
{
template <>
struct is_automagical<LuaUtil::Vec2> : std::false_type
{
};
template <>
struct is_automagical<LuaUtil::Vec3> : std::false_type
{
};
template <>
struct is_automagical<LuaUtil::Vec4> : std::false_type
{
};
template <>
struct is_automagical<Misc::Color> : std::false_type
{
};
template <>
struct is_automagical<LuaUtil::TransformM> : std::false_type
{
};
template <>
struct is_automagical<LuaUtil::TransformQ> : std::false_type
{
};
template <>
struct is_automagical<LuaUtil::Box> : std::false_type
{
};
}
namespace LuaUtil
{
namespace
{
template <typename T>
float zero(const T& v)
{
return 0.f;
}
template <typename T>
float one(const T& v)
{
return 1.f;
}
template <typename T, std::size_t I>
float get(const T& v)
{
return v[I];
}
// Creates bindings for all possible permutations (repetition allowed) of x,y,z,w fields
template <typename T>
void addSwizzleFields(sol::usertype<T>& type)
{
// Generate mapping of swizzle characters to their getter functions
constexpr auto components = []() {
std::array<std::pair<char, float (*)(const T&)>, T::num_components + 2> arr;
// 0/1 Components
arr[T::num_components] = { '0', zero<T> };
arr[T::num_components + 1] = { '1', one<T> };
// x,y,z,w components
if constexpr (T::num_components > 1)
{
arr[0] = { 'x', get<T, 0> };
arr[1] = { 'y', get<T, 1> };
}
if constexpr (T::num_components > 2)
arr[2] = { 'z', get<T, 2> };
if constexpr (T::num_components > 3)
arr[3] = { 'w', get<T, 3> };
return arr;
}();
// Iterate over the permutations
for (const auto& comp1 : components)
{
// Single component swizzle
type[std::string{ comp1.first }] = sol::readonly_property([=](const T& v) { return comp1.second(v); });
for (const auto& comp2 : components)
{
// Two component swizzles
type[std::string{ comp1.first, comp2.first }]
= sol::readonly_property([=](const T& v) { return Vec2(comp1.second(v), comp2.second(v)); });
for (const auto& comp3 : components)
{
// Three component swizzles
type[std::string{ comp1.first, comp2.first, comp3.first }] = sol::readonly_property(
[=](const T& v) { return Vec3(comp1.second(v), comp2.second(v), comp3.second(v)); });
for (const auto& comp4 : components)
{
// Four component swizzles
type[std::string{ comp1.first, comp2.first, comp3.first, comp4.first }]
= sol::readonly_property([=](const T& v) {
return Vec4(comp1.second(v), comp2.second(v), comp3.second(v), comp4.second(v));
});
}
}
}
}
}
template <typename T>
void addVectorMethods(sol::usertype<T>& vectorType)
{
vectorType[sol::meta_function::unary_minus] = [](const T& a) { return -a; };
vectorType[sol::meta_function::addition] = [](const T& a, const T& b) { return a + b; };
vectorType[sol::meta_function::subtraction] = [](const T& a, const T& b) { return a - b; };
vectorType[sol::meta_function::equal_to] = [](const T& a, const T& b) { return a == b; };
vectorType[sol::meta_function::multiplication] = sol::overload(
[](const T& a, float c) { return a * c; }, [](const T& a, const T& b) { return a * b; });
vectorType[sol::meta_function::division] = [](const T& a, float c) { return a / c; };
vectorType["dot"] = [](const T& a, const T b) { return a * b; };
vectorType["length"] = &T::length;
vectorType["length2"] = &T::length2;
vectorType["normalize"] = [](const T& v) {
float len = v.length();
if (len == 0)
return std::make_tuple(T(), 0.f);
else
return std::make_tuple(v * (1.f / len), len);
};
vectorType["emul"] = [](const T& a, const T& b) {
T result;
for (int i = 0; i < T::num_components; ++i)
result[i] = a[i] * b[i];
return result;
};
vectorType["ediv"] = [](const T& a, const T& b) {
T result;
for (int i = 0; i < T::num_components; ++i)
result[i] = a[i] / b[i];
return result;
};
vectorType[sol::meta_function::to_string] = [](const T& v) {
std::stringstream ss;
ss << std::setprecision(std::numeric_limits<typename T::value_type>::max_exponent10);
ss << "(" << v[0];
for (int i = 1; i < T::num_components; ++i)
ss << ", " << v[i];
ss << ")";
return ss.str();
};
addSwizzleFields(vectorType);
}
}
sol::table initUtilPackage(lua_State* L)
{
sol::state_view lua(L);
sol::table util(lua, sol::create);
// Lua bindings for Vec2
util["vector2"] = [](float x, float y) { return Vec2(x, y); };
sol::usertype<Vec2> vec2Type = lua.new_usertype<Vec2>("Vec2");
addVectorMethods<Vec2>(vec2Type);
vec2Type["rotate"] = &Misc::rotateVec2f;
// Lua bindings for Vec3
util["vector3"] = [](float x, float y, float z) { return Vec3(x, y, z); };
sol::usertype<Vec3> vec3Type = lua.new_usertype<Vec3>("Vec3");
addVectorMethods<Vec3>(vec3Type);
vec3Type[sol::meta_function::involution] = [](const Vec3& a, const Vec3& b) { return a ^ b; };
vec3Type["cross"] = [](const Vec3& a, const Vec3& b) { return a ^ b; };
// Lua bindings for Vec4
util["vector4"] = [](float x, float y, float z, float w) { return Vec4(x, y, z, w); };
sol::usertype<Vec4> vec4Type = lua.new_usertype<Vec4>("Vec4");
addVectorMethods<Vec4>(vec4Type);
// Lua bindings for Box
util["box"] = sol::overload([](const Vec3& center, const Vec3& halfSize) { return Box(center, halfSize); },
[](const TransformM& transform) { return Box(transform.mM); },
[](const TransformQ& transform) { return Box(Vec3(), Vec3(1, 1, 1), transform.mQ); });
sol::usertype<Box> boxType = lua.new_usertype<Box>("Box");
boxType["center"] = sol::readonly_property([](const Box& b) { return b.mCenter; });
boxType["halfSize"] = sol::readonly_property([](const Box& b) { return b.mHalfSize; });
boxType["transform"] = sol::readonly_property([](const Box& b) { return TransformM{ b.asTransform() }; });
boxType["vertices"] = sol::readonly_property([lua](const Box& b) {
sol::table table(lua, sol::create);
const auto vertices = b.vertices();
for (size_t i = 0; i < vertices.size(); ++i)
table[toLuaIndex(i)] = vertices[i];
return table;
});
boxType[sol::meta_function::equal_to] = [](const Box& a, const Box& b) { return a == b; };
boxType[sol::meta_function::to_string] = [](const Box& b) {
std::stringstream ss;
ss << "Box{ ";
ss << "center(" << b.mCenter.x() << ", " << b.mCenter.y() << ", " << b.mCenter.z() << ") ";
ss << "halfSize(" << b.mHalfSize.x() << ", " << b.mHalfSize.y() << ", " << b.mHalfSize.z() << ")";
ss << " }";
return ss.str();
};
// Lua bindings for Color
sol::usertype<Misc::Color> colorType = lua.new_usertype<Misc::Color>("Color");
colorType["r"] = sol::readonly_property([](const Misc::Color& c) { return c.r(); });
colorType["g"] = sol::readonly_property([](const Misc::Color& c) { return c.g(); });
colorType["b"] = sol::readonly_property([](const Misc::Color& c) { return c.b(); });
colorType["a"] = sol::readonly_property([](const Misc::Color& c) { return c.a(); });
colorType[sol::meta_function::to_string] = [](const Misc::Color& c) { return c.toString(); };
colorType["asRgba"] = [](const Misc::Color& c) { return Vec4(c.r(), c.g(), c.b(), c.a()); };
colorType["asRgb"] = [](const Misc::Color& c) { return Vec3(c.r(), c.g(), c.b()); };
colorType["asHex"] = [](const Misc::Color& c) { return c.toHex(); };
sol::table color(lua, sol::create);
color["rgba"] = [](float r, float g, float b, float a) { return Misc::Color(r, g, b, a); };
color["rgb"] = [](float r, float g, float b) { return Misc::Color(r, g, b, 1); };
color["hex"] = [](std::string_view hex) { return Misc::Color::fromHex(hex); };
util["color"] = LuaUtil::makeReadOnly(color);
// Lua bindings for Transform
sol::usertype<TransformM> transMType = lua.new_usertype<TransformM>("TransformM");
sol::usertype<TransformQ> transQType = lua.new_usertype<TransformQ>("TransformQ");
sol::table transforms(lua, sol::create);
util["transform"] = LuaUtil::makeReadOnly(transforms);
transforms["identity"] = sol::make_object(lua, TransformQ{ osg::Quat() });
transforms["move"] = sol::overload([](const Vec3& v) { return TransformM{ osg::Matrixf::translate(v) }; },
[](float x, float y, float z) { return TransformM{ osg::Matrixf::translate(x, y, z) }; });
transforms["scale"] = sol::overload([](const Vec3& v) { return TransformM{ osg::Matrixf::scale(v) }; },
[](float x, float y, float z) { return TransformM{ osg::Matrixf::scale(x, y, z) }; });
transforms["rotate"] = [](float angle, const Vec3& axis) { return TransformQ{ osg::Quat(angle, axis) }; };
transforms["rotateX"] = [](float angle) { return TransformQ{ osg::Quat(angle, Vec3(-1, 0, 0)) }; };
transforms["rotateY"] = [](float angle) { return TransformQ{ osg::Quat(angle, Vec3(0, -1, 0)) }; };
transforms["rotateZ"] = [](float angle) { return TransformQ{ osg::Quat(angle, Vec3(0, 0, -1)) }; };
transMType[sol::meta_function::multiplication]
= sol::overload([](const TransformM& a, const Vec3& b) { return a.mM.preMult(b); },
[](const TransformM& a, const TransformM& b) { return TransformM{ b.mM * a.mM }; },
[](const TransformM& a, const TransformQ& b) {
TransformM res{ a.mM };
res.mM.preMultRotate(b.mQ);
return res;
});
transMType[sol::meta_function::to_string] = [](const TransformM& m) {
osg::Vec3f trans, scale;
osg::Quat rotation, so;
m.mM.decompose(trans, rotation, scale, so);
osg::Quat::value_type rot_angle, so_angle;
osg::Vec3f rot_axis, so_axis;
rotation.getRotate(rot_angle, rot_axis);
so.getRotate(so_angle, so_axis);
std::stringstream ss;
ss << "TransformM{ ";
if (trans.length2() > 0)
ss << "move(" << trans.x() << ", " << trans.y() << ", " << trans.z() << ") ";
if (rot_angle != 0)
ss << "rotation(angle=" << rot_angle << ", axis=(" << rot_axis.x() << ", " << rot_axis.y() << ", "
<< rot_axis.z() << ")) ";
if (scale.x() != 1 || scale.y() != 1 || scale.z() != 1)
ss << "scale(" << scale.x() << ", " << scale.y() << ", " << scale.z() << ") ";
if (so_angle != 0)
ss << "rotation(angle=" << so_angle << ", axis=(" << so_axis.x() << ", " << so_axis.y() << ", "
<< so_axis.z() << ")) ";
ss << "}";
return ss.str();
};
transMType["apply"] = [](const TransformM& a, const Vec3& b) { return a.mM.preMult(b); },
transMType["inverse"] = [](const TransformM& m) {
TransformM res;
if (!res.mM.invert_4x3(m.mM))
throw std::runtime_error("This Transform is not invertible");
return res;
};
transMType["getYaw"] = [](const TransformM& m) {
osg::Vec3f angles = Misc::toEulerAnglesXZ(m.mM);
return angles.z();
};
transMType["getPitch"] = [](const TransformM& m) {
osg::Vec3f angles = Misc::toEulerAnglesXZ(m.mM);
return angles.x();
};
transMType["getAnglesXZ"] = [](const TransformM& m) {
osg::Vec3f angles = Misc::toEulerAnglesXZ(m.mM);
return std::make_tuple(angles.x(), angles.z());
};
transMType["getAnglesZYX"] = [](const TransformM& m) {
osg::Vec3f angles = Misc::toEulerAnglesZYX(m.mM);
return std::make_tuple(angles.z(), angles.y(), angles.x());
};
transQType[sol::meta_function::multiplication]
= sol::overload([](const TransformQ& a, const Vec3& b) { return a.mQ * b; },
[](const TransformQ& a, const TransformQ& b) { return TransformQ{ b.mQ * a.mQ }; },
[](const TransformQ& a, const TransformM& b) {
TransformM res{ b };
res.mM.postMultRotate(a.mQ);
return res;
});
transQType[sol::meta_function::to_string] = [](const TransformQ& q) {
osg::Quat::value_type angle;
osg::Vec3f axis;
q.mQ.getRotate(angle, axis);
std::stringstream ss;
ss << "TransformQ{ rotation(angle=" << angle << ", axis=(" << axis.x() << ", " << axis.y() << ", "
<< axis.z() << ")) }";
return ss.str();
};
transQType["apply"] = [](const TransformQ& a, const Vec3& b) { return a.mQ * b; },
transQType["inverse"] = [](const TransformQ& q) { return TransformQ{ q.mQ.inverse() }; };
transQType["getYaw"] = [](const TransformQ& q) {
osg::Vec3f angles = Misc::toEulerAnglesXZ(q.mQ);
return angles.z();
};
transQType["getPitch"] = [](const TransformQ& q) {
osg::Vec3f angles = Misc::toEulerAnglesXZ(q.mQ);
return angles.x();
};
transQType["getAnglesXZ"] = [](const TransformQ& q) {
osg::Vec3f angles = Misc::toEulerAnglesXZ(q.mQ);
return std::make_tuple(angles.x(), angles.z());
};
transQType["getAnglesZYX"] = [](const TransformQ& q) {
osg::Vec3f angles = Misc::toEulerAnglesZYX(q.mQ);
return std::make_tuple(angles.z(), angles.y(), angles.x());
};
// Utility functions
util["clamp"] = [](double value, double from, double to) { return std::clamp(value, from, to); };
// NOTE: `util["clamp"] = std::clamp<float>` causes error 'AddressSanitizer: stack-use-after-scope'
util["normalizeAngle"] = &Misc::normalizeAngle;
util["makeReadOnly"] = [](const sol::table& tbl) { return makeReadOnly(tbl, /*strictIndex=*/false); };
util["makeStrictReadOnly"] = [](const sol::table& tbl) { return makeReadOnly(tbl, /*strictIndex=*/true); };
util["remap"] = [](double value, double min, double max, double newMin, double newMax) {
return newMin + (value - min) * (newMax - newMin) / (max - min);
};
util["round"] = [](double value) { return round(value); };
if (lua["bit32"] != sol::nil)
{
sol::table bit = lua["bit32"];
util["bitOr"] = bit["bor"];
util["bitAnd"] = bit["band"];
util["bitXor"] = bit["bxor"];
util["bitNot"] = bit["bnot"];
}
else
{
util["bitOr"] = [](unsigned a, sol::variadic_args va) {
for (const auto& v : va)
a |= cast<unsigned>(v);
return a;
};
util["bitAnd"] = [](unsigned a, sol::variadic_args va) {
for (const auto& v : va)
a &= cast<unsigned>(v);
return a;
};
util["bitXor"] = [](unsigned a, sol::variadic_args va) {
for (const auto& v : va)
a ^= cast<unsigned>(v);
return a;
};
util["bitNot"] = [](unsigned a) { return ~a; };
}
util["loadCode"] = [](const std::string& code, const sol::table& env, sol::this_state s) {
sol::state_view lua(s);
sol::load_result res = lua.load(code, "", sol::load_mode::text);
if (!res.valid())
throw std::runtime_error("Lua error: " + res.get<std::string>());
sol::function fn = res;
sol::environment newEnv(lua, sol::create, env);
newEnv[sol::metatable_key][sol::meta_function::new_index] = env;
sol::set_environment(newEnv, fn);
return fn;
};
return util;
}
}
| 17,956
|
C++
|
.cpp
| 366
| 36.95082
| 119
| 0.506354
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,650
|
inputactions.cpp
|
OpenMW_openmw/components/lua/inputactions.cpp
|
#include "inputactions.hpp"
#include <queue>
#include <set>
#include <components/debug/debuglog.hpp>
#include <components/misc/strings/format.hpp>
#include "luastate.hpp"
namespace LuaUtil
{
namespace InputAction
{
namespace
{
std::string_view typeName(Type actionType)
{
switch (actionType)
{
case Type::Boolean:
return "Boolean";
case Type::Number:
return "Number";
case Type::Range:
return "Range";
default:
throw std::logic_error("Unknown input action type");
}
}
}
MultiTree::Node MultiTree::insert()
{
size_t nextId = size();
mChildren.push_back({});
mParents.push_back({});
return nextId;
}
bool MultiTree::validateTree() const
{
std::vector<bool> complete(size(), false);
traverse([&complete](Node node) { complete[node] = true; });
return std::find(complete.begin(), complete.end(), false) == complete.end();
}
template <typename Function>
void MultiTree::traverse(Function callback) const
{
std::queue<Node> nodeQueue;
std::vector<bool> complete(size(), false);
for (Node root = 0; root < size(); ++root)
{
if (!complete[root])
nodeQueue.push(root);
while (!nodeQueue.empty())
{
Node node = nodeQueue.back();
nodeQueue.pop();
bool isComplete = true;
for (Node parent : mParents[node])
isComplete = isComplete && complete[parent];
complete[node] = isComplete;
if (isComplete)
{
callback(node);
for (Node child : mChildren[node])
nodeQueue.push(child);
}
}
}
}
bool MultiTree::multiEdge(Node target, const std::vector<Node>& source)
{
mParents[target].reserve(mParents[target].size() + source.size());
for (Node s : source)
{
mParents[target].push_back(s);
mChildren[s].push_back(target);
}
bool validTree = validateTree();
if (!validTree)
{
for (Node s : source)
{
mParents[target].pop_back();
mChildren[s].pop_back();
}
}
return validTree;
}
namespace
{
bool validateActionValue(sol::object value, Type type)
{
switch (type)
{
case Type::Boolean:
return value.get_type() == sol::type::boolean;
case Type::Number:
return value.get_type() == sol::type::number;
case Type::Range:
if (value.get_type() != sol::type::number)
return false;
double d = value.as<double>();
return 0.0 <= d && d <= 1.0;
}
throw std::invalid_argument("Unknown action type");
}
}
void Registry::insert(const Info& info)
{
if (mIds.find(info.mKey) != mIds.end())
throw std::domain_error(Misc::StringUtils::format("Action key \"%s\" is already in use", info.mKey));
if (info.mKey.empty())
throw std::domain_error("Action key can't be an empty string");
if (info.mL10n.empty())
throw std::domain_error("Localization context can't be empty");
if (!validateActionValue(info.mDefaultValue, info.mType))
throw std::logic_error(Misc::StringUtils::format(
"Invalid value: \"%s\" for action \"%s\"", LuaUtil::toString(info.mDefaultValue), info.mKey));
Id id = mBindingTree.insert();
mKeys.push_back(info.mKey);
mIds[std::string(info.mKey)] = id;
mInfo.push_back(info);
mHandlers.push_back({});
mBindings.push_back({});
mValues.push_back(info.mDefaultValue);
}
std::optional<std::string> Registry::nextKey(std::string_view key) const
{
auto it = mIds.find(key);
if (it == mIds.end())
return std::nullopt;
auto nextId = it->second + 1;
if (nextId >= mKeys.size())
return std::nullopt;
return mKeys.at(nextId);
}
std::optional<Info> Registry::operator[](std::string_view actionKey)
{
auto iter = mIds.find(actionKey);
if (iter == mIds.end())
return std::nullopt;
return mInfo[iter->second];
}
Registry::Id Registry::safeIdByKey(std::string_view key)
{
auto iter = mIds.find(key);
if (iter == mIds.end())
throw std::logic_error(Misc::StringUtils::format("Unknown action key: \"%s\"", key));
return iter->second;
}
bool Registry::bind(
std::string_view key, const LuaUtil::Callback& callback, const std::vector<std::string_view>& dependencies)
{
Id id = safeIdByKey(key);
std::vector<Id> dependencyIds;
dependencyIds.reserve(dependencies.size());
for (std::string_view s : dependencies)
dependencyIds.push_back(safeIdByKey(s));
bool validEdge = mBindingTree.multiEdge(id, dependencyIds);
if (validEdge)
mBindings[id].push_back(Binding{
callback,
std::move(dependencyIds),
});
return validEdge;
}
sol::object Registry::valueOfType(std::string_view key, Type type)
{
Id id = safeIdByKey(key);
Info info = mInfo[id];
if (info.mType != type)
throw std::logic_error(
Misc::StringUtils::format("Attempt to get value of type \"%s\" from action \"%s\" with type \"%s\"",
typeName(type), key, typeName(info.mType)));
return mValues[id];
}
void Registry::update(double dt)
{
std::vector<sol::object> dependencyValues;
mBindingTree.traverse([this, &dependencyValues, dt](Id node) {
sol::main_object newValue = mValues[node];
std::vector<Binding>& bindings = mBindings[node];
bindings.erase(std::remove_if(bindings.begin(), bindings.end(),
[&](const Binding& binding) {
if (!binding.mCallback.isValid())
return true;
dependencyValues.clear();
for (Id parent : binding.mDependencies)
dependencyValues.push_back(mValues[parent]);
try
{
newValue = sol::main_object(
binding.mCallback.call(dt, newValue, sol::as_args(dependencyValues)));
}
catch (std::exception& e)
{
if (!validateActionValue(newValue, mInfo[node].mType))
Log(Debug::Error) << Misc::StringUtils::format(
"Error due to invalid value of action \"%s\"(\"%s\"): ", mKeys[node],
LuaUtil::toString(newValue))
<< e.what();
else
Log(Debug::Error) << "Error in callback: " << e.what();
}
return false;
}),
bindings.end());
if (!validateActionValue(newValue, mInfo[node].mType))
Log(Debug::Error) << Misc::StringUtils::format(
"Invalid value of action \"%s\": %s", mKeys[node], LuaUtil::toString(newValue));
if (mValues[node] != newValue)
{
mValues[node] = sol::object(newValue);
std::vector<LuaUtil::Callback>& handlers = mHandlers[node];
handlers.erase(std::remove_if(handlers.begin(), handlers.end(),
[&](const LuaUtil::Callback& handler) {
if (!handler.isValid())
return true;
handler.tryCall(newValue);
return false;
}),
handlers.end());
}
});
}
}
namespace InputTrigger
{
Registry::Id Registry::safeIdByKey(std::string_view key)
{
auto it = mIds.find(key);
if (it == mIds.end())
throw std::domain_error(Misc::StringUtils::format("Unknown trigger key \"%s\"", key));
return it->second;
}
void Registry::insert(const Info& info)
{
if (mIds.find(info.mKey) != mIds.end())
throw std::domain_error(Misc::StringUtils::format("Trigger key \"%s\" is already in use", info.mKey));
if (info.mKey.empty())
throw std::domain_error("Trigger key can't be an empty string");
if (info.mL10n.empty())
throw std::domain_error("Localization context can't be empty");
Id id = mIds.size();
mIds[info.mKey] = id;
mInfo.push_back(info);
mHandlers.push_back({});
}
std::optional<Info> Registry::operator[](std::string_view key)
{
auto iter = mIds.find(key);
if (iter == mIds.end())
return std::nullopt;
return mInfo[iter->second];
}
void Registry::registerHandler(std::string_view key, const LuaUtil::Callback& callback)
{
Id id = safeIdByKey(key);
mHandlers[id].push_back(callback);
}
void Registry::activate(std::string_view key)
{
Id id = safeIdByKey(key);
std::vector<LuaUtil::Callback>& handlers = mHandlers[id];
handlers.erase(std::remove_if(handlers.begin(), handlers.end(),
[&](const LuaUtil::Callback& handler) {
if (!handler.isValid())
return true;
handler.tryCall();
return false;
}),
handlers.end());
}
}
}
| 11,736
|
C++
|
.cpp
| 272
| 25.503676
| 120
| 0.448077
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,651
|
asyncpackage.cpp
|
OpenMW_openmw/components/lua/asyncpackage.cpp
|
#include "asyncpackage.hpp"
namespace sol
{
template <>
struct is_automagical<LuaUtil::AsyncPackageId> : std::false_type
{
};
template <>
struct is_automagical<LuaUtil::Callback> : std::false_type
{
};
}
namespace LuaUtil
{
struct TimerCallback
{
AsyncPackageId mAsyncId;
std::string mName;
};
Callback Callback::fromLua(const sol::table& t)
{
const sol::object& function = t.raw_get<sol::object>(1);
const sol::object& asyncPackageId = t.raw_get<sol::object>(2);
if (!function.is<sol::main_protected_function>() || !asyncPackageId.is<AsyncPackageId>())
throw std::domain_error("Expected an async:callback, received a table");
return Callback{ function.as<sol::main_protected_function>(), asyncPackageId.as<AsyncPackageId>().mHiddenData };
}
sol::table Callback::makeMetatable(lua_State* L)
{
sol::table callbackMeta = sol::table::create(L);
callbackMeta[sol::meta_function::call] = [](const sol::table& callback, sol::variadic_args va) {
return Callback::fromLua(callback).call(sol::as_args(va));
};
callbackMeta[sol::meta_function::to_string] = [] { return "Callback"; };
callbackMeta[sol::meta_function::metatable] = false;
callbackMeta["isCallback"] = true;
return callbackMeta;
}
sol::table Callback::make(const AsyncPackageId& asyncId, sol::main_protected_function fn, sol::table metatable)
{
sol::table c = sol::table::create(fn.lua_state(), 2);
c.raw_set(1, std::move(fn), 2, asyncId);
c[sol::metatable_key] = metatable;
return c;
}
bool Callback::isLuaCallback(const sol::object& t)
{
if (!t.is<sol::table>())
return false;
sol::object meta = sol::table(t)[sol::metatable_key];
if (!meta.is<sol::table>())
return false;
return sol::table(meta).raw_get_or<bool, std::string_view, bool>("isCallback", false);
}
sol::function getAsyncPackageInitializer(
lua_State* L, std::function<double()> simulationTimeFn, std::function<double()> gameTimeFn)
{
sol::state_view lua(L);
using TimerType = ScriptsContainer::TimerType;
sol::usertype<AsyncPackageId> api = lua.new_usertype<AsyncPackageId>("AsyncPackage");
api["registerTimerCallback"]
= [](const AsyncPackageId& asyncId, std::string_view name, sol::main_protected_function callback) {
asyncId.mContainer->registerTimerCallback(asyncId.mScriptId, name, std::move(callback));
return TimerCallback{ asyncId, std::string(name) };
};
api["newSimulationTimer"] = [simulationTimeFn](const AsyncPackageId&, double delay,
const TimerCallback& callback, sol::main_object callbackArg) {
callback.mAsyncId.mContainer->setupSerializableTimer(TimerType::SIMULATION_TIME, simulationTimeFn() + delay,
callback.mAsyncId.mScriptId, callback.mName, std::move(callbackArg));
};
api["newGameTimer"] = [gameTimeFn](const AsyncPackageId&, double delay, const TimerCallback& callback,
sol::main_object callbackArg) {
callback.mAsyncId.mContainer->setupSerializableTimer(TimerType::GAME_TIME, gameTimeFn() + delay,
callback.mAsyncId.mScriptId, callback.mName, std::move(callbackArg));
};
api["newUnsavableSimulationTimer"]
= [simulationTimeFn](const AsyncPackageId& asyncId, double delay, sol::main_protected_function callback) {
asyncId.mContainer->setupUnsavableTimer(
TimerType::SIMULATION_TIME, simulationTimeFn() + delay, asyncId.mScriptId, std::move(callback));
};
api["newUnsavableGameTimer"]
= [gameTimeFn](const AsyncPackageId& asyncId, double delay, sol::main_protected_function callback) {
asyncId.mContainer->setupUnsavableTimer(
TimerType::GAME_TIME, gameTimeFn() + delay, asyncId.mScriptId, std::move(callback));
};
sol::table callbackMeta = Callback::makeMetatable(L);
api["callback"] = [callbackMeta](const AsyncPackageId& asyncId, sol::main_protected_function fn) -> sol::table {
return Callback::make(asyncId, std::move(fn), callbackMeta);
};
auto initializer = [](sol::table hiddenData) {
ScriptId id = hiddenData[ScriptsContainer::sScriptIdKey];
return AsyncPackageId{ id.mContainer, id.mIndex, std::move(hiddenData) };
};
return sol::make_object(lua, initializer);
}
}
| 4,747
|
C++
|
.cpp
| 96
| 39.833333
| 120
| 0.637284
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,652
|
luastate.cpp
|
OpenMW_openmw/components/lua/luastate.cpp
|
#include "luastate.hpp"
#ifndef NO_LUAJIT
#include <luajit.h>
#endif // NO_LUAJIT
#include <filesystem>
#include <fstream>
#include <components/debug/debuglog.hpp>
#include <components/files/conversion.hpp>
#include <components/vfs/manager.hpp>
#include "scriptscontainer.hpp"
#include "utf8.hpp"
namespace LuaUtil
{
static VFS::Path::Normalized packageNameToVfsPath(std::string_view packageName, const VFS::Manager& vfs)
{
std::string pathValue(packageName);
std::replace(pathValue.begin(), pathValue.end(), '.', '/');
VFS::Path::Normalized pathWithInit(pathValue + "/init.lua");
pathValue.append(".lua");
VFS::Path::Normalized path(pathValue);
if (vfs.exists(path))
return path;
else if (vfs.exists(pathWithInit))
return pathWithInit;
else
throw std::runtime_error("module not found: " + std::string(packageName));
}
static std::filesystem::path packageNameToPath(
std::string_view packageName, const std::vector<std::filesystem::path>& searchDirs)
{
std::string path(packageName);
std::replace(path.begin(), path.end(), '.', '/');
std::string pathWithInit = path + "/init.lua";
path.append(".lua");
for (const auto& base : searchDirs)
{
std::filesystem::path p1 = base / path;
if (std::filesystem::exists(p1))
return p1;
std::filesystem::path p2 = base / pathWithInit;
if (std::filesystem::exists(p2))
return p2;
}
throw std::runtime_error("module not found: " + std::string(packageName));
}
static const std::string safeFunctions[] = { "assert", "error", "ipairs", "next", "pairs", "pcall", "select",
"tonumber", "tostring", "type", "unpack", "xpcall", "rawequal", "rawget", "rawset", "setmetatable" };
static const std::string safePackages[] = { "coroutine", "math", "string", "table", "utf8" };
static constexpr int64_t countHookStep = 1000;
bool LuaState::sProfilerEnabled = true;
void LuaState::countHook(lua_State* L, lua_Debug* ar)
{
LuaState* self;
(void)lua_getallocf(L, reinterpret_cast<void**>(&self));
if (self->mActiveScriptIdStack.empty())
return;
const ScriptId& activeScript = self->mActiveScriptIdStack.back();
activeScript.mContainer->addInstructionCount(activeScript.mIndex, countHookStep);
self->mWatchdogInstructionCounter += countHookStep;
if (self->mSettings.mInstructionLimit > 0
&& self->mWatchdogInstructionCounter > self->mSettings.mInstructionLimit)
{
lua_pushstring(L,
"Lua instruction count exceeded, probably an infinite loop in a script. "
"To change the limit set \"[Lua] instruction limit per call\" in settings.cfg");
lua_error(L);
}
}
void* LuaState::trackingAllocator(void* ud, void* ptr, size_t osize, size_t nsize)
{
LuaState* self = static_cast<LuaState*>(ud);
const uint64_t smallAllocSize = self->mSettings.mSmallAllocMaxSize;
const uint64_t memoryLimit = self->mSettings.mMemoryLimit;
if (!ptr)
osize = 0;
int64_t smallAllocDelta = 0, bigAllocDelta = 0;
if (osize <= smallAllocSize)
smallAllocDelta -= osize;
else
bigAllocDelta -= osize;
if (nsize <= smallAllocSize)
smallAllocDelta += nsize;
else
bigAllocDelta += nsize;
if (bigAllocDelta > 0 && memoryLimit > 0 && self->mTotalMemoryUsage + nsize - osize > memoryLimit)
{
Log(Debug::Error) << "Lua realloc " << osize << "->" << nsize
<< " is blocked because Lua memory limit (configurable in settings.cfg) is exceeded";
return nullptr;
}
void* newPtr = nullptr;
if (nsize == 0)
free(ptr);
else
{
newPtr = realloc(ptr, nsize);
if (!newPtr)
{
Log(Debug::Error) << "Lua realloc " << osize << "->" << nsize << " failed";
return nullptr;
}
}
self->mTotalMemoryUsage += smallAllocDelta + bigAllocDelta;
self->mSmallAllocMemoryUsage += smallAllocDelta;
if (bigAllocDelta != 0)
{
auto it = osize > smallAllocSize ? self->mBigAllocOwners.find(ptr) : self->mBigAllocOwners.end();
ScriptId id;
if (it != self->mBigAllocOwners.end())
{
if (it->second.mContainer)
id = ScriptId{ *it->second.mContainer, it->second.mScriptIndex };
if (ptr != newPtr || nsize <= smallAllocSize)
self->mBigAllocOwners.erase(it);
}
else if (bigAllocDelta > 0)
{
if (!self->mActiveScriptIdStack.empty())
id = self->mActiveScriptIdStack.back();
bigAllocDelta = nsize;
}
if (id.mIndex >= 0)
{
if (static_cast<size_t>(id.mIndex) >= self->mMemoryUsage.size())
self->mMemoryUsage.resize(id.mIndex + 1);
self->mMemoryUsage[id.mIndex] += bigAllocDelta;
}
if (id.mContainer)
{
id.mContainer->addMemoryUsage(id.mIndex, bigAllocDelta);
if (newPtr && nsize > smallAllocSize)
self->mBigAllocOwners.emplace(newPtr, AllocOwner{ id.mContainer->mThis, id.mIndex });
}
}
return newPtr;
}
lua_State* LuaState::createLuaRuntime(LuaState* luaState)
{
if (sProfilerEnabled)
{
Log(Debug::Info) << "Initializing LuaUtil::LuaState with profiler";
lua_State* L = lua_newstate(&trackingAllocator, luaState);
if (L)
return L;
else
{
sProfilerEnabled = false;
Log(Debug::Error)
<< "Failed to initialize LuaUtil::LuaState with custom allocator; disabling Lua profiler";
}
}
Log(Debug::Info) << "Initializing LuaUtil::LuaState without profiler";
lua_State* L = luaL_newstate();
if (!L)
throw std::runtime_error("Can't create Lua runtime");
return L;
}
LuaState::LuaState(const VFS::Manager* vfs, const ScriptsConfiguration* conf, const LuaStateSettings& settings)
: mSettings(settings)
, mLuaHolder(createLuaRuntime(this))
, mSol(mLuaHolder.get())
, mConf(conf)
, mVFS(vfs)
{
if (sProfilerEnabled)
lua_sethook(mLuaHolder.get(), &countHook, LUA_MASKCOUNT, countHookStep);
protectedCall([&](LuaView& view) {
auto& sol = view.sol();
sol.open_libraries(sol::lib::base, sol::lib::coroutine, sol::lib::math, sol::lib::bit32, sol::lib::string,
sol::lib::table, sol::lib::os, sol::lib::debug);
#ifndef NO_LUAJIT
sol.open_libraries(sol::lib::jit);
#endif // NO_LUAJIT
sol["math"]["randomseed"](static_cast<unsigned>(std::time(nullptr)));
sol["math"]["randomseed"] = [] {};
sol["utf8"] = LuaUtf8::initUtf8Package(sol);
sol["writeToLog"] = [](std::string_view s) { Log(Debug::Level::Info) << s; };
sol["setEnvironment"]
= [](const sol::environment& env, const sol::function& fn) { sol::set_environment(env, fn); };
sol["loadFromVFS"] = [this](std::string_view packageName) {
return loadScriptAndCache(packageNameToVfsPath(packageName, *mVFS));
};
sol["loadInternalLib"] = [this](std::string_view packageName) { return loadInternalLib(packageName); };
// Some fixes for compatibility between different Lua versions
if (sol["unpack"] == sol::nil)
sol["unpack"] = sol["table"]["unpack"];
else if (sol["table"]["unpack"] == sol::nil)
sol["table"]["unpack"] = sol["unpack"];
if (LUA_VERSION_NUM <= 501)
{
sol.script(R"(
local _pairs = pairs
local _ipairs = ipairs
pairs = function(v) return (rawget(getmetatable(v) or {}, '__pairs') or _pairs)(v) end
ipairs = function(v) return (rawget(getmetatable(v) or {}, '__ipairs') or _ipairs)(v) end
)");
}
sol.script(R"(
local printToLog = function(...)
local strs = {}
for i = 1, select('#', ...) do
strs[i] = tostring(select(i, ...))
end
return writeToLog(table.concat(strs, '\t'))
end
printGen = function(name) return function(...) return printToLog(name, ...) end end
function requireGen(env, loaded, loadFn)
return function(packageName)
local p = loaded[packageName]
if p == nil then
local loader = loadFn(packageName)
setEnvironment(env, loader)
p = loader(packageName)
loaded[packageName] = p
end
return p
end
end
function createStrictIndexFn(tbl)
return function(_, key)
local res = tbl[key]
if res ~= nil then
return res
else
error('Key not found: '..tostring(key), 2)
end
end
end
function pairsForReadOnly(v)
local nextFn, t, firstKey = pairs(getmetatable(v).t)
return function(_, k) return nextFn(t, k) end, v, firstKey
end
function ipairsForReadOnly(v)
local nextFn, t, firstKey = ipairs(getmetatable(v).t)
return function(_, k) return nextFn(t, k) end, v, firstKey
end
function lenForReadOnly(v)
return #getmetatable(v).t
end
local function nextForArray(array, index)
index = (index or 0) + 1
if index <= #array then
return index, array[index]
end
end
function ipairsForArray(array)
return nextForArray, array, 0
end
getmetatable('').__metatable = false
getSafeMetatable = function(v)
if type(v) ~= 'table' then error('getmetatable is allowed only for tables', 2) end
return getmetatable(v)
end
)");
mSandboxEnv = sol::table(sol, sol::create);
mSandboxEnv["_VERSION"] = sol["_VERSION"];
for (const std::string& s : safeFunctions)
{
if (sol[s] == sol::nil)
throw std::logic_error("Lua function not found: " + s);
mSandboxEnv[s] = sol[s];
}
for (const std::string& s : safePackages)
{
if (sol[s] == sol::nil)
throw std::logic_error("Lua package not found: " + s);
mCommonPackages[s] = mSandboxEnv[s] = makeReadOnly(sol[s]);
}
mSandboxEnv["getmetatable"] = sol["getSafeMetatable"];
mCommonPackages["os"] = mSandboxEnv["os"]
= makeReadOnly(tableFromPairs<std::string_view, sol::function>(sol,
{ { "date", sol["os"]["date"] }, { "difftime", sol["os"]["difftime"] },
{ "time", sol["os"]["time"] } }));
});
}
sol::table makeReadOnly(const sol::table& table, bool strictIndex)
{
if (table == sol::nil)
return table;
if (table.is<sol::userdata>())
return table; // it is already userdata, no sense to wrap it again
lua_State* luaState = table.lua_state();
sol::state_view lua(luaState);
sol::table meta(lua, sol::create);
meta["t"] = table;
if (strictIndex)
meta[sol::meta_method::index] = lua["createStrictIndexFn"](table);
else
meta[sol::meta_method::index] = table;
meta[sol::meta_method::pairs] = lua["pairsForReadOnly"];
meta[sol::meta_method::ipairs] = lua["ipairsForReadOnly"];
meta[sol::meta_method::length] = lua["lenForReadOnly"];
meta[sol::meta_method::type] = "ReadOnlyTable";
lua_newuserdata(luaState, 0);
sol::stack::push(luaState, meta);
lua_setmetatable(luaState, -2);
return sol::stack::pop<sol::table>(luaState);
}
sol::table getMutableFromReadOnly(const sol::userdata& ro)
{
return ro[sol::metatable_key].get<sol::table>()["t"];
}
void LuaState::addCommonPackage(std::string packageName, sol::object package)
{
if (!package.is<sol::function>())
package = makeReadOnly(std::move(package));
mCommonPackages.insert_or_assign(std::move(packageName), std::move(package));
}
sol::protected_function_result LuaState::runInNewSandbox(const VFS::Path::Normalized& path,
const std::string& envName, const std::map<std::string, sol::object>& packages, const sol::object& hiddenData)
{
// TODO
sol::protected_function script = loadScriptAndCache(path);
sol::environment env(mSol, sol::create, mSandboxEnv);
env["print"] = mSol["printGen"](envName + ":");
env["_G"] = env;
env[sol::metatable_key]["__metatable"] = false;
ScriptId scriptId;
if (hiddenData.is<sol::table>())
scriptId = hiddenData.as<sol::table>()
.get<sol::optional<ScriptId>>(ScriptsContainer::sScriptIdKey)
.value_or(ScriptId{});
auto maybeRunLoader = [&hiddenData, scriptId](const sol::object& package) -> sol::object {
if (package.is<sol::function>())
return call(scriptId, package.as<sol::function>(), hiddenData);
else
return package;
};
sol::table loaded(mSol, sol::create);
for (const auto& [key, value] : mCommonPackages)
loaded[key] = maybeRunLoader(value);
for (const auto& [key, value] : packages)
loaded[key] = maybeRunLoader(value);
env["require"] = mSol["requireGen"](env, loaded, mSol["loadFromVFS"]);
sol::set_environment(env, script);
return call(scriptId, script);
}
sol::environment LuaState::newInternalLibEnvironment()
{
// TODO
sol::environment env(mSol, sol::create, mSandboxEnv);
sol::table loaded(mSol, sol::create);
for (const std::string& s : safePackages)
loaded[s] = static_cast<sol::object>(mSandboxEnv[s]);
env["require"] = mSol["requireGen"](env, loaded, mSol["loadInternalLib"]);
return env;
}
sol::protected_function_result LuaState::throwIfError(sol::protected_function_result&& res)
{
if (!res.valid())
throw std::runtime_error(std::string("Lua error: ") += res.get<sol::error>().what());
else
return std::move(res);
}
sol::function LuaState::loadScriptAndCache(const VFS::Path::Normalized& path)
{
auto iter = mCompiledScripts.find(path);
if (iter != mCompiledScripts.end())
{
sol::load_result res = mSol.load(iter->second.as_string_view(), path.value(), sol::load_mode::binary);
// Unless we have memory corruption issues, the bytecode is valid at this point, but loading might still
// fail because we've hit our Lua memory cap
if (!res.valid())
throw std::runtime_error("Lua error: " + res.get<std::string>());
return res;
}
sol::function res = loadFromVFS(path);
mCompiledScripts[path] = res.dump();
return res;
}
sol::function LuaState::loadFromVFS(const VFS::Path::Normalized& path)
{
std::string fileContent(std::istreambuf_iterator<char>(*mVFS->get(path)), {});
sol::load_result res = mSol.load(fileContent, path.value(), sol::load_mode::text);
if (!res.valid())
throw std::runtime_error(std::string("Lua error: ") += res.get<sol::error>().what());
return res;
}
sol::function LuaState::loadInternalLib(std::string_view libName)
{
const auto path = packageNameToPath(libName, mLibSearchPaths);
std::ifstream stream(path);
std::string fileContent(std::istreambuf_iterator<char>(stream), {});
sol::load_result res = mSol.load(fileContent, Files::pathToUnicodeString(path), sol::load_mode::text);
if (!res.valid())
throw std::runtime_error("Lua error: " + res.get<std::string>());
return res;
}
std::string getLuaVersion()
{
#ifdef NO_LUAJIT
return LUA_RELEASE;
#else
return LUA_RELEASE " (" LUAJIT_VERSION ")";
#endif
}
std::string toString(const sol::object& obj)
{
if (obj == sol::nil)
return "nil";
else if (obj.get_type() == sol::type::string)
return "\"" + obj.as<std::string>() + "\"";
else
return call(sol::state_view(obj.lua_state())["tostring"], obj);
}
std::string internal::formatCastingError(const sol::object& obj, const std::type_info& t)
{
const char* typeName = t.name();
if (t == typeid(int))
typeName = "int";
else if (t == typeid(unsigned))
typeName = "uint32";
else if (t == typeid(size_t))
typeName = "size_t";
else if (t == typeid(float))
typeName = "float";
else if (t == typeid(double))
typeName = "double";
else if (t == typeid(sol::table))
typeName = "sol::table";
else if (t == typeid(sol::function) || t == typeid(sol::protected_function))
typeName = "sol::function";
else if (t == typeid(std::string) || t == typeid(std::string_view))
typeName = "string";
return std::string("Value \"") + toString(obj) + std::string("\" can not be casted to ") + typeName;
}
}
| 18,823
|
C++
|
.cpp
| 427
| 32.177986
| 118
| 0.549106
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,653
|
utf8.cpp
|
OpenMW_openmw/components/lua/utf8.cpp
|
#include <components/misc/strings/format.hpp>
#include "utf8.hpp"
namespace
{
constexpr std::string_view UTF8PATT = "[%z\x01-\x7F\xC2-\xF4][\x80-\xBF]*"; // %z is deprecated in Lua5.2
// constexpr uint32_t MAXUTF = 0x7FFFFFFFu;
constexpr uint32_t MAXUNICODE = 0x10FFFFu;
inline bool isNilOrNone(const sol::stack_proxy arg)
{
return (arg.get_type() == sol::type::lua_nil || arg.get_type() == sol::type::none);
}
inline std::int64_t getInteger(const sol::stack_proxy arg, const size_t n, std::string_view name)
{
double integer;
if (!arg.is<double>())
throw std::runtime_error(Misc::StringUtils::format("bad argument #%i to '%s' (number expected, got %s)", n,
name, sol::type_name(arg.lua_state(), arg.get_type())));
if (std::modf(arg, &integer) != 0)
throw std::runtime_error(
Misc::StringUtils::format("bad argument #%i to '%s' (number has no integer representation)", n, name));
return static_cast<std::int64_t>(integer);
}
// If the input 'pos' is negative, it is treated as counting from the end of the string,
// where -1 represents the last character position, -2 represents the second-to-last position,
// and so on. If 'pos' is non-negative, it is used as-is.
inline void relativePosition(int64_t& pos, const size_t len)
{
if (pos < 0)
pos = std::max<int64_t>(0, pos + len + 1);
}
inline void codepointToUTF8(char32_t codepoint, std::string& str)
{
if (codepoint <= 0x7Fu)
{
str.push_back(static_cast<char>(codepoint));
}
else if (codepoint <= 0x7FFu)
{
str.push_back(static_cast<char>(0xC0 | ((codepoint & 0x7C0) >> 6)));
str.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
}
else if (codepoint <= 0xFFFFu)
{
str.push_back(static_cast<char>(0xE0 | ((codepoint & 0xF000) >> 12)));
str.push_back(static_cast<char>(0x80 | ((codepoint & 0xFC0) >> 6)));
str.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
}
else if (codepoint <= MAXUNICODE)
{
str.push_back(static_cast<char>(0xF0 | ((codepoint & 0x1C0000) >> 18)));
str.push_back(static_cast<char>(0x80 | ((codepoint & 0x3F000) >> 12)));
str.push_back(static_cast<char>(0x80 | ((codepoint & 0xFC0) >> 6)));
str.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
}
else
throw std::runtime_error("Invalid codepoint");
}
// returns: first - character pos in bytes, second - character codepoint
std::pair<int64_t, int64_t> decodeNextUTF8Character(std::string_view s, std::vector<int64_t>& pos_byte)
{
const int64_t pos = pos_byte.back() - 1;
const unsigned char ch = static_cast<unsigned char>(s[pos]);
int64_t codepoint = -1;
size_t byteSize = 0;
if ((ch & 0b10000000) == 0)
{
codepoint = ch;
byteSize = 1;
}
else if ((ch & 0b11100000) == 0b11000000)
{
codepoint = ch & 0b00011111;
byteSize = 2;
}
else if ((ch & 0b11110000) == 0b11100000)
{
codepoint = ch & 0b00001111;
byteSize = 3;
}
else if ((ch & 0b11111000) == 0b11110000)
{
codepoint = ch & 0b00000111;
byteSize = 4;
}
// construct codepoint for non-ascii
for (size_t i = 1; i < byteSize; ++i)
{
// if not a continuation byte
if ((pos + i) >= s.size() || (static_cast<unsigned char>(s[pos + i]) & 0b11000000) != 0b10000000)
{
return std::make_pair(0, -1);
}
codepoint = (codepoint << 6) | (static_cast<unsigned char>(s[pos + i]) & 0b00111111);
}
std::pair<size_t, int64_t> res = std::make_pair(pos_byte.back(), codepoint);
pos_byte.push_back(pos_byte.back() + byteSize); /* the next character (if exists) starts at this byte */
return res;
}
}
namespace LuaUtf8
{
sol::table initUtf8Package(sol::state_view& lua)
{
sol::table utf8(lua, sol::create);
utf8["charpattern"] = UTF8PATT;
utf8["char"] = [](const sol::variadic_args args) -> std::string {
std::string result{};
for (size_t i = 0; i < args.size(); ++i)
{
int64_t codepoint = getInteger(args[i], (i + 1), "char");
if (codepoint < 0 || codepoint > MAXUNICODE)
throw std::runtime_error(
"bad argument #" + std::to_string(i + 1) + " to 'char' (value out of range)");
codepointToUTF8(static_cast<char32_t>(codepoint), result);
}
return result;
};
utf8["codes"] = [](std::string_view s) {
return sol::as_function(
[s, pos_byte = std::vector<int64_t>{ 1 }]() mutable -> sol::optional<std::pair<int64_t, int64_t>> {
if (pos_byte.back() <= static_cast<int64_t>(s.size()))
{
const auto pair = decodeNextUTF8Character(s, pos_byte);
if (pair.second == -1)
throw std::runtime_error(
"Invalid UTF-8 code at position " + std::to_string(pos_byte.size()));
return pair;
}
return sol::nullopt;
});
};
utf8["len"] = [](std::string_view s,
const sol::variadic_args args) -> std::variant<size_t, std::pair<sol::object, int64_t>> {
const size_t len = s.size();
int64_t iv = isNilOrNone(args[0]) ? 1 : getInteger(args[0], 2, "len");
int64_t fv = isNilOrNone(args[1]) ? -1 : getInteger(args[1], 3, "len");
relativePosition(iv, len);
relativePosition(fv, len);
if (iv <= 0)
throw std::runtime_error("bad argument #2 to 'len' (initial position out of bounds)");
if (fv > static_cast<int64_t>(len))
throw std::runtime_error("bad argument #3 to 'len' (final position out of bounds)");
if (len == 0)
return len;
std::vector<int64_t> pos_byte = { iv };
while (pos_byte.back() <= fv)
{
if (decodeNextUTF8Character(s, pos_byte).second == -1)
return std::pair(sol::lua_nil, pos_byte.back());
}
return pos_byte.size() - 1;
};
utf8["codepoint"]
= [](std::string_view s, const sol::variadic_args args) -> sol::as_returns_t<std::vector<int64_t>> {
size_t len = s.size();
int64_t iv = isNilOrNone(args[0]) ? 1 : getInteger(args[0], 2, "codepoint");
int64_t fv = isNilOrNone(args[1]) ? iv : getInteger(args[1], 3, "codepoint");
relativePosition(iv, len);
relativePosition(fv, len);
if (iv <= 0)
throw std::runtime_error("bad argument #2 to 'codepoint' (initial position out of bounds)");
if (fv > static_cast<int64_t>(len))
throw std::runtime_error("bad argument #3 to 'codepoint' (final position out of bounds)");
if (iv > fv)
return sol::as_returns(std::vector<int64_t>{}); /* empty interval; return nothing */
std::vector<int64_t> pos_byte = { iv };
std::vector<int64_t> codepoints;
while (pos_byte.back() <= fv)
{
codepoints.push_back(decodeNextUTF8Character(s, pos_byte).second);
if (codepoints.back() == -1)
throw std::runtime_error("Invalid UTF-8 code at position " + std::to_string(pos_byte.size()));
}
return sol::as_returns(std::move(codepoints));
};
utf8["offset"]
= [](std::string_view s, const int64_t n, const sol::variadic_args args) -> sol::optional<int64_t> {
size_t len = s.size();
int64_t iv;
if (isNilOrNone(args[0]))
{
if (n >= 0)
iv = 1;
else
iv = s.size() + 1;
}
else
iv = getInteger(args[0], 3, "offset");
std::vector<int64_t> pos_byte = { 1 };
relativePosition(iv, len);
if (iv > static_cast<int64_t>(len) + 1)
throw std::runtime_error("bad argument #3 to 'offset' (position out of bounds)");
while (pos_byte.back() <= static_cast<int64_t>(len))
decodeNextUTF8Character(s, pos_byte);
for (auto it = pos_byte.begin(); it != pos_byte.end(); ++it)
{
if (*it == iv)
{
if (n <= 0 && it + n >= pos_byte.begin())
return *(it + n);
if (n > 0 && it + n - 1 < pos_byte.end())
return *(it + n - 1);
break;
}
else if (*it > iv) /* a continuation byte */
{
if (n == 0)
return *(it - 1); /* special case */
else
throw std::runtime_error("initial position is a continuation byte");
}
}
return sol::nullopt;
};
return utf8;
}
}
| 9,689
|
C++
|
.cpp
| 217
| 32.124424
| 119
| 0.506204
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,654
|
l10n.cpp
|
OpenMW_openmw/components/lua/l10n.cpp
|
#include "l10n.hpp"
#include <components/debug/debuglog.hpp>
#include <components/l10n/manager.hpp>
#include <components/lua/luastate.hpp>
namespace
{
struct L10nContext
{
std::shared_ptr<const l10n::MessageBundles> mData;
};
void getICUArgs(std::string_view messageId, const sol::table& table, std::vector<icu::UnicodeString>& argNames,
std::vector<icu::Formattable>& args)
{
for (auto& [key, value] : table)
{
// Argument values
if (value.is<std::string>())
args.push_back(icu::Formattable(LuaUtil::cast<std::string>(value).c_str()));
// Note: While we pass all numbers as doubles, they still seem to be handled appropriately.
// Numbers can be forced to be integers using the argType number and argStyle integer
// E.g. {var, number, integer}
else if (value.is<double>())
args.push_back(icu::Formattable(LuaUtil::cast<double>(value)));
else
{
Log(Debug::Error) << "Unrecognized argument type for key \"" << LuaUtil::cast<std::string>(key)
<< "\" when formatting message \"" << messageId << "\"";
}
// Argument names
const auto str = LuaUtil::cast<std::string>(key);
argNames.push_back(icu::UnicodeString::fromUTF8(icu::StringPiece(str.data(), str.size())));
}
}
}
namespace sol
{
template <>
struct is_automagical<L10nContext> : std::false_type
{
};
}
namespace LuaUtil
{
sol::function initL10nLoader(lua_State* L, l10n::Manager* manager)
{
sol::state_view lua(L);
sol::usertype<L10nContext> ctxDef = lua.new_usertype<L10nContext>("L10nContext");
ctxDef[sol::meta_function::call]
= [](const L10nContext& ctx, std::string_view key, sol::optional<sol::table> args) {
std::vector<icu::Formattable> argValues;
std::vector<icu::UnicodeString> argNames;
if (args)
getICUArgs(key, *args, argNames, argValues);
return ctx.mData->formatMessage(key, argNames, argValues);
};
return sol::make_object(
lua, [manager](const std::string& contextName, sol::optional<std::string> fallbackLocale) {
if (fallbackLocale)
return L10nContext{ manager->getContext(contextName, *fallbackLocale) };
else
return L10nContext{ manager->getContext(contextName) };
});
}
}
| 2,624
|
C++
|
.cpp
| 64
| 31.046875
| 115
| 0.585194
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,655
|
configuration.cpp
|
OpenMW_openmw/components/lua/configuration.cpp
|
#include "configuration.hpp"
#include <algorithm>
#include <bitset>
#include <cassert>
#include <sstream>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/format.hpp>
#include <components/misc/strings/lower.hpp>
namespace LuaUtil
{
namespace
{
const std::map<std::string, ESM::LuaScriptCfg::Flags, std::less<>> flagsByName{
{ "GLOBAL", ESM::LuaScriptCfg::sGlobal },
{ "CUSTOM", ESM::LuaScriptCfg::sCustom },
{ "PLAYER", ESM::LuaScriptCfg::sPlayer },
{ "MENU", ESM::LuaScriptCfg::sMenu },
};
const std::map<std::string, ESM::RecNameInts, std::less<>> typeTagsByName{
{ "ACTIVATOR", ESM::REC_ACTI },
{ "ARMOR", ESM::REC_ARMO },
{ "BOOK", ESM::REC_BOOK },
{ "CLOTHING", ESM::REC_CLOT },
{ "CONTAINER", ESM::REC_CONT },
{ "CREATURE", ESM::REC_CREA },
{ "DOOR", ESM::REC_DOOR },
{ "INGREDIENT", ESM::REC_INGR },
{ "LIGHT", ESM::REC_LIGH },
{ "MISC_ITEM", ESM::REC_MISC },
{ "NPC", ESM::REC_NPC_ },
{ "POTION", ESM::REC_ALCH },
{ "WEAPON", ESM::REC_WEAP },
{ "APPARATUS", ESM::REC_APPA },
{ "LOCKPICK", ESM::REC_LOCK },
{ "PROBE", ESM::REC_PROB },
{ "REPAIR", ESM::REC_REPA },
};
bool isSpace(char c)
{
return std::isspace(static_cast<unsigned char>(c));
}
}
void ScriptsConfiguration::init(ESM::LuaScriptsCfg cfg)
{
mScripts.clear();
mPathToIndex.clear();
// Find duplicates; only the last occurrence will be used (unless `sMerge` flag is used).
// Search for duplicates is case insensitive.
std::vector<bool> skip(cfg.mScripts.size(), false);
for (size_t i = 0; i < cfg.mScripts.size(); ++i)
{
const ESM::LuaScriptCfg& script = cfg.mScripts[i];
bool global = script.mFlags & ESM::LuaScriptCfg::sGlobal;
if (global && (script.mFlags & ~ESM::LuaScriptCfg::sMerge) != ESM::LuaScriptCfg::sGlobal)
throw std::runtime_error(
std::string("Global script can not have local flags: ") + script.mScriptPath.value());
if (global && (!script.mTypes.empty() || !script.mRecords.empty() || !script.mRefs.empty()))
throw std::runtime_error(std::string("Global script can not have per-type and per-object configuration")
+ script.mScriptPath.value());
auto [it, inserted] = mPathToIndex.emplace(script.mScriptPath, i);
if (inserted)
continue;
ESM::LuaScriptCfg& oldScript = cfg.mScripts[it->second];
if (global != bool(oldScript.mFlags & ESM::LuaScriptCfg::sGlobal))
throw std::runtime_error(std::string("Flags mismatch for ") + script.mScriptPath.value());
if (script.mFlags & ESM::LuaScriptCfg::sMerge)
{
oldScript.mFlags |= (script.mFlags & ~ESM::LuaScriptCfg::sMerge);
if (!script.mInitializationData.empty())
oldScript.mInitializationData = script.mInitializationData;
oldScript.mTypes.insert(oldScript.mTypes.end(), script.mTypes.begin(), script.mTypes.end());
oldScript.mRecords.insert(oldScript.mRecords.end(), script.mRecords.begin(), script.mRecords.end());
oldScript.mRefs.insert(oldScript.mRefs.end(), script.mRefs.begin(), script.mRefs.end());
skip[i] = true;
}
else
skip[it->second] = true;
}
// Filter duplicates
for (size_t i = 0; i < cfg.mScripts.size(); ++i)
{
if (!skip[i])
mScripts.push_back(std::move(cfg.mScripts[i]));
}
// Initialize mappings
mPathToIndex.clear();
for (int i = 0; i < static_cast<int>(mScripts.size()); ++i)
{
const ESM::LuaScriptCfg& s = mScripts[i];
mPathToIndex[s.mScriptPath] = i; // Stored paths are case sensitive.
for (uint32_t t : s.mTypes)
mScriptsPerType[t].push_back(i);
for (const ESM::LuaScriptCfg::PerRecordCfg& r : s.mRecords)
{
std::string_view data = r.mInitializationData.empty() ? s.mInitializationData : r.mInitializationData;
mScriptsPerRecordId[r.mRecordId].push_back(DetailedConf{ i, r.mAttach, data });
}
for (const ESM::LuaScriptCfg::PerRefCfg& r : s.mRefs)
{
std::string_view data = r.mInitializationData.empty() ? s.mInitializationData : r.mInitializationData;
mScriptsPerRefNum[ESM::RefNum{ r.mRefnumIndex, r.mRefnumContentFile }].push_back(
DetailedConf{ i, r.mAttach, data });
}
}
}
std::optional<int> ScriptsConfiguration::findId(VFS::Path::NormalizedView path) const
{
auto it = mPathToIndex.find(path);
if (it != mPathToIndex.end())
return it->second;
else
return std::nullopt;
}
ScriptIdsWithInitializationData ScriptsConfiguration::getConfByFlag(ESM::LuaScriptCfg::Flags flag) const
{
ScriptIdsWithInitializationData res;
for (size_t id = 0; id < mScripts.size(); ++id)
{
const ESM::LuaScriptCfg& script = mScripts[id];
if (script.mFlags & flag)
res[id] = script.mInitializationData;
}
return res;
}
ScriptIdsWithInitializationData ScriptsConfiguration::getLocalConf(
uint32_t type, const ESM::RefId& recordId, ESM::RefNum refnum) const
{
ScriptIdsWithInitializationData res;
auto typeIt = mScriptsPerType.find(type);
if (typeIt != mScriptsPerType.end())
for (int scriptId : typeIt->second)
res[scriptId] = mScripts[scriptId].mInitializationData;
auto recordIt = mScriptsPerRecordId.find(recordId);
if (recordIt != mScriptsPerRecordId.end())
{
for (const DetailedConf& d : recordIt->second)
{
if (d.mAttach)
res[d.mScriptId] = d.mInitializationData;
else
res.erase(d.mScriptId);
}
}
if (!refnum.hasContentFile())
return res;
auto refIt = mScriptsPerRefNum.find(refnum);
if (refIt == mScriptsPerRefNum.end())
return res;
for (const DetailedConf& d : refIt->second)
{
if (d.mAttach)
res[d.mScriptId] = d.mInitializationData;
else
res.erase(d.mScriptId);
}
return res;
}
void parseOMWScripts(ESM::LuaScriptsCfg& cfg, std::string_view data)
{
while (!data.empty())
{
// Get next line
std::string_view line = data.substr(0, data.find('\n'));
data = data.substr(std::min(line.size() + 1, data.size()));
if (!line.empty() && line.back() == '\r')
line = line.substr(0, line.size() - 1);
while (!line.empty() && isSpace(line[0]))
line = line.substr(1);
if (line.empty() || line[0] == '#') // Skip empty lines and comments
continue;
while (!line.empty() && isSpace(line.back()))
line = line.substr(0, line.size() - 1);
if (!Misc::StringUtils::ciEndsWith(line, ".lua"))
throw std::runtime_error(Misc::StringUtils::format(
"Lua script should have suffix '.lua', got: %s", std::string(line.substr(0, 300))));
// Split tags and script path
size_t semicolonPos = line.find(':');
if (semicolonPos == std::string::npos)
throw std::runtime_error(Misc::StringUtils::format("No flags found in: %s", std::string(line)));
std::string_view tagsStr = line.substr(0, semicolonPos);
std::string_view scriptPath = line.substr(semicolonPos + 1);
while (isSpace(scriptPath[0]))
scriptPath = scriptPath.substr(1);
ESM::LuaScriptCfg& script = cfg.mScripts.emplace_back();
script.mScriptPath = VFS::Path::Normalized(scriptPath);
script.mFlags = 0;
// Parse tags
size_t tagsPos = 0;
while (true)
{
while (tagsPos < tagsStr.size() && (isSpace(tagsStr[tagsPos]) || tagsStr[tagsPos] == ','))
tagsPos++;
size_t startPos = tagsPos;
while (tagsPos < tagsStr.size() && !isSpace(tagsStr[tagsPos]) && tagsStr[tagsPos] != ',')
tagsPos++;
if (startPos == tagsPos)
break;
std::string_view tagName = tagsStr.substr(startPos, tagsPos - startPos);
auto it = flagsByName.find(tagName);
auto typesIt = typeTagsByName.find(tagName);
if (it != flagsByName.end())
script.mFlags |= it->second;
else if (typesIt != typeTagsByName.end())
script.mTypes.push_back(typesIt->second);
else
throw std::runtime_error(
Misc::StringUtils::format("Unknown tag '%s' in: %s", std::string(tagName), std::string(line)));
}
}
}
std::string scriptCfgToString(const ESM::LuaScriptCfg& script)
{
std::stringstream ss;
if (script.mFlags & ESM::LuaScriptCfg::sMerge)
ss << "+ ";
for (const auto& [flagName, flag] : flagsByName)
{
if (script.mFlags & flag)
ss << flagName << " ";
}
for (uint32_t type : script.mTypes)
{
for (const auto& [tagName, t] : typeTagsByName)
{
if (type == t)
ss << tagName << " ";
}
}
ss << ": " << script.mScriptPath;
if (!script.mInitializationData.empty())
ss << " ; data " << script.mInitializationData.size() << " bytes";
if (!script.mRecords.empty())
ss << " ; " << script.mRecords.size() << " records";
if (!script.mRefs.empty())
ss << " ; " << script.mRefs.size() << " objects";
return ss.str();
}
}
| 10,562
|
C++
|
.cpp
| 238
| 32.382353
| 120
| 0.543337
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,656
|
scriptscontainer.cpp
|
OpenMW_openmw/components/lua/scriptscontainer.cpp
|
#include "scriptscontainer.hpp"
#include "scripttracker.hpp"
#include <components/esm/luascripts.hpp>
namespace
{
struct ScriptInfo
{
std::string_view mInitData;
const ESM::LuaScript* mSavedData;
};
}
namespace LuaUtil
{
static constexpr std::string_view ENGINE_HANDLERS = "engineHandlers";
static constexpr std::string_view EVENT_HANDLERS = "eventHandlers";
static constexpr std::string_view INTERFACE_NAME = "interfaceName";
static constexpr std::string_view INTERFACE = "interface";
static constexpr std::string_view HANDLER_INIT = "onInit";
static constexpr std::string_view HANDLER_SAVE = "onSave";
static constexpr std::string_view HANDLER_LOAD = "onLoad";
static constexpr std::string_view HANDLER_INTERFACE_OVERRIDE = "onInterfaceOverride";
int64_t ScriptsContainer::sInstanceCount = 0;
ScriptsContainer::ScriptsContainer(
LuaUtil::LuaState* lua, std::string_view namePrefix, ScriptTracker* tracker, bool load)
: mNamePrefix(namePrefix)
, mLua(*lua)
, mThis(std::make_shared<ScriptsContainer*>(this))
, mTracker(tracker)
{
sInstanceCount++;
registerEngineHandlers({ &mUpdateHandlers });
if (load)
{
LoadedData& data = mData.emplace<LoadedData>();
mLua.protectedCall([&](LuaView& view) {
data.mPublicInterfaces = sol::table(view.sol(), sol::create);
addPackage("openmw.interfaces", makeReadOnly(data.mPublicInterfaces));
});
}
}
void ScriptsContainer::printError(int scriptId, std::string_view msg, const std::exception& e)
{
Log(Debug::Error) << mNamePrefix << "[" << scriptPath(scriptId) << "] " << msg << ": " << e.what();
}
void ScriptsContainer::addPackage(std::string packageName, sol::object package)
{
if (!package.is<sol::userdata>())
throw std::logic_error("Expected package to be read-only: " + packageName);
mAPI.insert_or_assign(std::move(packageName), std::move(package));
}
bool ScriptsContainer::addCustomScript(int scriptId, std::string_view initData)
{
assert(mLua.getConfiguration().isCustomScript(scriptId));
bool ok = false;
mLua.protectedCall([&](LuaView& view) {
std::optional<sol::function> onInit, onLoad;
ok = addScript(view, scriptId, onInit, onLoad);
if (ok && onInit)
callOnInit(view, scriptId, *onInit, initData);
});
return ok;
}
void ScriptsContainer::addAutoStartedScripts()
{
mLua.protectedCall([&](LuaView& view) {
for (const auto& [scriptId, data] : mAutoStartScripts)
{
std::optional<sol::function> onInit, onLoad;
bool ok = addScript(view, scriptId, onInit, onLoad);
if (ok && onInit)
callOnInit(view, scriptId, *onInit, data);
}
});
}
bool ScriptsContainer::addScript(
LuaView& view, int scriptId, std::optional<sol::function>& onInit, std::optional<sol::function>& onLoad)
{
assert(scriptId >= 0 && scriptId < static_cast<int>(mLua.getConfiguration().size()));
if (hasScript(scriptId))
return false; // already present
const VFS::Path::Normalized& path = scriptPath(scriptId);
std::string debugName = mNamePrefix;
debugName.push_back('[');
debugName.append(path);
debugName.push_back(']');
LoadedData& data = ensureLoaded();
Script& script = data.mScripts[scriptId];
script.mHiddenData = view.newTable();
script.mHiddenData[sScriptIdKey] = ScriptId{ this, scriptId };
script.mHiddenData[sScriptDebugNameKey] = debugName;
script.mPath = path;
script.mStats.mAvgInstructionCount = 0;
const auto oldMemoryUsageIt = mRemovedScriptsMemoryUsage.find(scriptId);
if (oldMemoryUsageIt != mRemovedScriptsMemoryUsage.end())
{
script.mStats.mMemoryUsage = oldMemoryUsageIt->second;
mRemovedScriptsMemoryUsage.erase(oldMemoryUsageIt);
}
else
script.mStats.mMemoryUsage = 0;
try
{
sol::object scriptOutput = mLua.runInNewSandbox(path, debugName, mAPI, script.mHiddenData);
if (scriptOutput == sol::nil)
return true;
sol::object engineHandlers = sol::nil, eventHandlers = sol::nil;
for (const auto& [key, value] : cast<sol::table>(scriptOutput))
{
std::string_view sectionName = cast<std::string_view>(key);
if (sectionName == ENGINE_HANDLERS)
engineHandlers = value;
else if (sectionName == EVENT_HANDLERS)
eventHandlers = value;
else if (sectionName == INTERFACE_NAME)
script.mInterfaceName = cast<std::string>(value);
else if (sectionName == INTERFACE)
script.mInterface = cast<sol::table>(value);
else
Log(Debug::Error) << "Not supported section '" << sectionName << "' in " << debugName;
}
if (engineHandlers != sol::nil)
{
for (const auto& [key, handler] : cast<sol::table>(engineHandlers))
{
std::string_view handlerName = cast<std::string_view>(key);
sol::function fn = cast<sol::function>(handler);
if (handlerName == HANDLER_INIT)
onInit = std::move(fn);
else if (handlerName == HANDLER_LOAD)
onLoad = std::move(fn);
else if (handlerName == HANDLER_SAVE)
script.mOnSave = std::move(fn);
else if (handlerName == HANDLER_INTERFACE_OVERRIDE)
script.mOnOverride = std::move(fn);
else
{
auto it = mEngineHandlers.find(handlerName);
if (it == mEngineHandlers.end())
Log(Debug::Error) << "Not supported handler '" << handlerName << "' in " << debugName;
else
insertHandler(it->second->mList, scriptId, std::move(fn));
}
}
}
if (eventHandlers != sol::nil)
{
for (const auto& [key, fn] : cast<sol::table>(eventHandlers))
{
std::string_view eventName = cast<std::string_view>(key);
auto it = data.mEventHandlers.find(eventName);
if (it == data.mEventHandlers.end())
it = data.mEventHandlers.emplace(std::string(eventName), EventHandlerList()).first;
insertHandler(it->second, scriptId, cast<sol::function>(fn));
}
}
if (script.mInterfaceName.empty() == script.mInterface.has_value())
{
Log(Debug::Error) << debugName << ": 'interfaceName' should always be used together with 'interface'";
script.mInterfaceName.clear();
script.mInterface = sol::nil;
}
else if (script.mInterface)
{
script.mInterface = makeReadOnly(*script.mInterface);
insertInterface(scriptId, script);
}
return true;
}
catch (std::exception& e)
{
auto iter = data.mScripts.find(scriptId);
mRemovedScriptsMemoryUsage[scriptId] = iter->second.mStats.mMemoryUsage;
data.mScripts.erase(iter);
Log(Debug::Error) << "Can't start " << debugName << "; " << e.what();
return false;
}
}
bool ScriptsContainer::hasScript(int scriptId) const
{
return std::visit(
[&](auto&& variant) {
using T = std::decay_t<decltype(variant)>;
if constexpr (std::is_same_v<T, UnloadedData>)
{
const auto& conf = mLua.getConfiguration();
if (scriptId >= 0 && static_cast<size_t>(scriptId) < conf.size())
{
const auto& path = conf[scriptId].mScriptPath;
for (const ESM::LuaScript& script : variant.mScripts)
{
if (script.mScriptPath == path)
return true;
}
}
}
else if constexpr (std::is_same_v<T, LoadedData>)
{
return variant.mScripts.count(scriptId) != 0;
}
return false;
},
mData);
}
void ScriptsContainer::removeScript(int scriptId)
{
LoadedData& data = ensureLoaded();
auto scriptIter = data.mScripts.find(scriptId);
if (scriptIter == data.mScripts.end())
return; // no such script
Script& script = scriptIter->second;
if (script.mInterface)
removeInterface(scriptId, script);
mRemovedScriptsMemoryUsage[scriptId] = script.mStats.mMemoryUsage;
data.mScripts.erase(scriptIter);
for (auto& [_, handlers] : mEngineHandlers)
removeHandler(handlers->mList, scriptId);
for (auto& [_, handlers] : data.mEventHandlers)
removeHandler(handlers, scriptId);
}
void ScriptsContainer::insertInterface(int scriptId, const Script& script)
{
assert(script.mInterface);
const Script* prev = nullptr;
const Script* next = nullptr;
int nextId = 0;
LoadedData& data = ensureLoaded();
for (const auto& [otherId, otherScript] : data.mScripts)
{
if (scriptId == otherId || script.mInterfaceName != otherScript.mInterfaceName)
continue;
if (otherId < scriptId)
prev = &otherScript;
else
{
next = &otherScript;
nextId = otherId;
break;
}
}
if (prev && script.mOnOverride)
{
try
{
LuaUtil::call({ this, scriptId }, *script.mOnOverride, *prev->mInterface);
}
catch (std::exception& e)
{
printError(scriptId, "onInterfaceOverride failed", e);
}
}
if (next && next->mOnOverride)
{
try
{
LuaUtil::call({ this, nextId }, *next->mOnOverride, *script.mInterface);
}
catch (std::exception& e)
{
printError(nextId, "onInterfaceOverride failed", e);
}
}
if (next == nullptr)
data.mPublicInterfaces[script.mInterfaceName] = *script.mInterface;
}
void ScriptsContainer::removeInterface(int scriptId, const Script& script)
{
assert(script.mInterface);
const Script* prev = nullptr;
const Script* next = nullptr;
int nextId = 0;
LoadedData& data = ensureLoaded();
for (const auto& [otherId, otherScript] : data.mScripts)
{
if (scriptId == otherId || script.mInterfaceName != otherScript.mInterfaceName)
continue;
if (otherId < scriptId)
prev = &otherScript;
else
{
next = &otherScript;
nextId = otherId;
break;
}
}
if (next)
{
if (next->mOnOverride)
{
sol::object prevInterface = sol::nil;
if (prev)
prevInterface = *prev->mInterface;
try
{
LuaUtil::call({ this, nextId }, *next->mOnOverride, prevInterface);
}
catch (std::exception& e)
{
printError(nextId, "onInterfaceOverride failed", e);
}
}
}
else if (prev)
data.mPublicInterfaces[script.mInterfaceName] = *prev->mInterface;
else
data.mPublicInterfaces[script.mInterfaceName] = sol::nil;
}
void ScriptsContainer::insertHandler(std::vector<Handler>& list, int scriptId, sol::function fn)
{
list.emplace_back();
int pos = list.size() - 1;
while (pos > 0 && list[pos - 1].mScriptId > scriptId)
{
list[pos] = std::move(list[pos - 1]);
pos--;
}
list[pos].mScriptId = scriptId;
list[pos].mFn = std::move(fn);
}
void ScriptsContainer::removeHandler(std::vector<Handler>& list, int scriptId)
{
list.erase(
std::remove_if(list.begin(), list.end(), [scriptId](const Handler& h) { return h.mScriptId == scriptId; }),
list.end());
}
void ScriptsContainer::receiveEvent(std::string_view eventName, std::string_view eventData)
{
LoadedData& data = ensureLoaded();
auto it = data.mEventHandlers.find(eventName);
if (it == data.mEventHandlers.end())
return;
mLua.protectedCall([&](LuaView& view) {
sol::object data;
try
{
data = LuaUtil::deserialize(view.sol(), eventData, mSerializer);
}
catch (std::exception& e)
{
Log(Debug::Error) << mNamePrefix << " can not parse eventData for '" << eventName << "': " << e.what();
return;
}
EventHandlerList& list = it->second;
for (int i = list.size() - 1; i >= 0; --i)
{
const Handler& h = list[i];
try
{
sol::object res = LuaUtil::call({ this, h.mScriptId }, h.mFn, data);
if (res.is<bool>() && !res.as<bool>())
break; // Skip other handlers if 'false' was returned.
}
catch (std::exception& e)
{
Log(Debug::Error) << mNamePrefix << "[" << scriptPath(h.mScriptId) << "] eventHandler[" << eventName
<< "] failed. " << e.what();
}
}
});
}
void ScriptsContainer::registerEngineHandlers(std::initializer_list<EngineHandlerList*> handlers)
{
for (EngineHandlerList* h : handlers)
mEngineHandlers[h->mName] = h;
}
void ScriptsContainer::callOnInit(LuaView& view, int scriptId, const sol::function& onInit, std::string_view data)
{
try
{
LuaUtil::call({ this, scriptId }, onInit, deserialize(view.sol(), data, mSerializer));
}
catch (std::exception& e)
{
printError(scriptId, "onInit failed", e);
}
}
void ScriptsContainer::save(ESM::LuaScripts& data)
{
if (UnloadedData* unloadedData = std::get_if<UnloadedData>(&mData))
{
data.mScripts = unloadedData->mScripts;
return;
}
const auto& loadedData = std::get<LoadedData>(mData);
std::map<int, std::vector<ESM::LuaTimer>> timers;
auto saveTimerFn = [&](const Timer& timer, TimerType timerType) {
if (!timer.mSerializable)
return;
ESM::LuaTimer savedTimer;
savedTimer.mTime = timer.mTime;
savedTimer.mType = timerType;
savedTimer.mCallbackName = std::get<std::string>(timer.mCallback);
savedTimer.mCallbackArgument = timer.mSerializedArg;
timers[timer.mScriptId].push_back(std::move(savedTimer));
};
for (const Timer& timer : loadedData.mSimulationTimersQueue)
saveTimerFn(timer, TimerType::SIMULATION_TIME);
for (const Timer& timer : loadedData.mGameTimersQueue)
saveTimerFn(timer, TimerType::GAME_TIME);
data.mScripts.clear();
for (auto& [scriptId, script] : loadedData.mScripts)
{
ESM::LuaScript savedScript;
// Note: We can not use `scriptPath(scriptId)` here because `save` can be called during
// evaluating "reloadlua" command when ScriptsConfiguration is already changed.
savedScript.mScriptPath = script.mPath;
if (script.mOnSave)
{
try
{
sol::object state = LuaUtil::call({ this, scriptId }, *script.mOnSave);
savedScript.mData = serialize(state, mSerializer);
}
catch (std::exception& e)
{
printError(scriptId, "onSave failed", e);
}
}
auto timersIt = timers.find(scriptId);
if (timersIt != timers.end())
savedScript.mTimers = std::move(timersIt->second);
data.mScripts.push_back(std::move(savedScript));
}
}
void ScriptsContainer::load(const ESM::LuaScripts& data)
{
removeAllScripts();
const ScriptsConfiguration& cfg = mLua.getConfiguration();
std::map<int, ScriptInfo> scripts;
for (const auto& [scriptId, initData] : mAutoStartScripts)
scripts[scriptId] = { initData, nullptr };
for (const ESM::LuaScript& s : data.mScripts)
{
std::optional<int> scriptId = cfg.findId(s.mScriptPath);
if (!scriptId)
{
Log(Debug::Verbose) << "Ignoring " << mNamePrefix << "[" << s.mScriptPath << "]; script not registered";
continue;
}
auto it = scripts.find(*scriptId);
if (it != scripts.end())
it->second.mSavedData = &s;
else if (cfg.isCustomScript(*scriptId))
scripts[*scriptId] = { cfg[*scriptId].mInitializationData, &s };
else
Log(Debug::Verbose) << "Ignoring " << mNamePrefix << "[" << s.mScriptPath
<< "]; this script is not allowed here";
}
mLua.protectedCall([&](LuaView& view) {
UnloadedData& container = ensureUnloaded(view);
for (const auto& [scriptId, scriptInfo] : scripts)
{
if (scriptInfo.mSavedData == nullptr)
continue;
ESM::LuaScript& script = container.mScripts.emplace_back(*scriptInfo.mSavedData);
if (!script.mData.empty())
{
try
{
sol::object state = deserialize(view.sol(), script.mData, mSavedDataDeserializer);
script.mData = serialize(state, mSerializer);
}
catch (std::exception& e)
{
printError(scriptId, "onLoad failed", e);
script.mData.clear();
}
}
for (auto it = script.mTimers.begin(); it != script.mTimers.end();)
{
try
{
sol::object arg = deserialize(view.sol(), it->mCallbackArgument, mSavedDataDeserializer);
// It is important if the order of content files was changed. The deserialize-serialize
// procedure updates refnums, so timer.mSerializedArg may be not equal to
// savedTimer.mCallbackArgument.
it->mCallbackArgument = serialize(arg, mSerializer);
++it;
}
catch (std::exception& e)
{
printError(scriptId, "can not load timer", e);
it = script.mTimers.erase(it);
}
}
}
});
}
ScriptsContainer::LoadedData& ScriptsContainer::ensureLoaded()
{
mRequiredLoading = true;
if (LoadedData* data = std::get_if<LoadedData>(&mData))
return *data;
UnloadedData& unloadedData = std::get<UnloadedData>(mData);
std::vector<ESM::LuaScript> savedScripts = std::move(unloadedData.mScripts);
LoadedData& data = mData.emplace<LoadedData>();
const ScriptsConfiguration& cfg = mLua.getConfiguration();
std::map<int, ScriptInfo> scripts;
for (const auto& [scriptId, initData] : mAutoStartScripts)
scripts[scriptId] = { initData, nullptr };
for (const ESM::LuaScript& s : savedScripts)
{
std::optional<int> scriptId = cfg.findId(s.mScriptPath);
auto it = scripts.find(*scriptId);
if (it != scripts.end())
it->second.mSavedData = &s;
else if (cfg.isCustomScript(*scriptId))
scripts[*scriptId] = { cfg[*scriptId].mInitializationData, &s };
}
mLua.protectedCall([&](LuaView& view) {
data.mPublicInterfaces = sol::table(view.sol(), sol::create);
addPackage("openmw.interfaces", makeReadOnly(data.mPublicInterfaces));
for (const auto& [scriptId, scriptInfo] : scripts)
{
std::optional<sol::function> onInit, onLoad;
if (!addScript(view, scriptId, onInit, onLoad))
continue;
if (scriptInfo.mSavedData == nullptr)
{
if (onInit)
callOnInit(view, scriptId, *onInit, scriptInfo.mInitData);
continue;
}
if (onLoad)
{
try
{
sol::object state = deserialize(view.sol(), scriptInfo.mSavedData->mData, mSerializer);
sol::object initializationData = deserialize(view.sol(), scriptInfo.mInitData, mSerializer);
LuaUtil::call({ this, scriptId }, *onLoad, state, initializationData);
}
catch (std::exception& e)
{
printError(scriptId, "onLoad failed", e);
}
}
for (const ESM::LuaTimer& savedTimer : scriptInfo.mSavedData->mTimers)
{
Timer timer;
timer.mCallback = savedTimer.mCallbackName;
timer.mSerializable = true;
timer.mScriptId = scriptId;
timer.mTime = savedTimer.mTime;
try
{
timer.mArg
= sol::main_object(deserialize(view.sol(), savedTimer.mCallbackArgument, mSerializer));
// It is important if the order of content files was changed. The deserialize-serialize
// procedure updates refnums, so timer.mSerializedArg may be not equal to
// savedTimer.mCallbackArgument.
timer.mSerializedArg = serialize(timer.mArg, mSerializer);
if (savedTimer.mType == TimerType::GAME_TIME)
data.mGameTimersQueue.push_back(std::move(timer));
else
data.mSimulationTimersQueue.push_back(std::move(timer));
}
catch (std::exception& e)
{
printError(scriptId, "can not load timer", e);
}
}
}
});
std::make_heap(data.mSimulationTimersQueue.begin(), data.mSimulationTimersQueue.end());
std::make_heap(data.mGameTimersQueue.begin(), data.mGameTimersQueue.end());
if (mTracker)
mTracker->onLoad(*this);
return data;
}
ScriptsContainer::UnloadedData& ScriptsContainer::ensureUnloaded(LuaView&)
{
if (UnloadedData* data = std::get_if<UnloadedData>(&mData))
return *data;
UnloadedData data;
save(data);
mAPI.erase("openmw.interfaces");
UnloadedData& out = mData.emplace<UnloadedData>(std::move(data));
for (auto& [_, handlers] : mEngineHandlers)
handlers->mList.clear();
mRequiredLoading = false;
return out;
}
ScriptsContainer::~ScriptsContainer()
{
sInstanceCount--;
*mThis = nullptr;
}
// Note: shouldn't be called from destructor because mEngineHandlers has pointers on
// external objects that are already removed during child class destruction.
void ScriptsContainer::removeAllScripts()
{
std::visit(
[&](auto&& variant) {
using T = std::decay_t<decltype(variant)>;
if constexpr (std::is_same_v<T, UnloadedData>)
{
variant.mScripts.clear();
}
else if constexpr (std::is_same_v<T, LoadedData>)
{
for (auto& [id, script] : variant.mScripts)
{
mRemovedScriptsMemoryUsage[id] = script.mStats.mMemoryUsage;
}
variant.mScripts.clear();
for (auto& [_, handlers] : mEngineHandlers)
handlers->mList.clear();
variant.mEventHandlers.clear();
variant.mSimulationTimersQueue.clear();
variant.mGameTimersQueue.clear();
variant.mPublicInterfaces.clear();
}
},
mData);
}
ScriptsContainer::Script& ScriptsContainer::getScript(int scriptId)
{
LoadedData& data = ensureLoaded();
auto it = data.mScripts.find(scriptId);
if (it == data.mScripts.end())
throw std::logic_error("Script doesn't exist");
return it->second;
}
void ScriptsContainer::registerTimerCallback(
int scriptId, std::string_view callbackName, sol::main_protected_function callback)
{
getScript(scriptId).mRegisteredCallbacks.emplace(std::string(callbackName), std::move(callback));
}
void ScriptsContainer::insertTimer(std::vector<Timer>& timerQueue, Timer&& t)
{
timerQueue.push_back(std::move(t));
std::push_heap(timerQueue.begin(), timerQueue.end());
}
void ScriptsContainer::setupSerializableTimer(
TimerType type, double time, int scriptId, std::string_view callbackName, sol::main_object callbackArg)
{
Timer t;
t.mCallback = std::string(callbackName);
t.mScriptId = scriptId;
t.mSerializable = true;
t.mTime = time;
t.mArg = std::move(callbackArg);
t.mSerializedArg = serialize(t.mArg, mSerializer);
LoadedData& data = ensureLoaded();
insertTimer(type == TimerType::GAME_TIME ? data.mGameTimersQueue : data.mSimulationTimersQueue, std::move(t));
}
void ScriptsContainer::setupUnsavableTimer(
TimerType type, double time, int scriptId, sol::main_protected_function callback)
{
Timer t;
t.mScriptId = scriptId;
t.mSerializable = false;
t.mTime = time;
t.mCallback = mTemporaryCallbackCounter;
getScript(t.mScriptId).mTemporaryCallbacks.emplace(mTemporaryCallbackCounter, std::move(callback));
mTemporaryCallbackCounter++;
LoadedData& data = ensureLoaded();
insertTimer(type == TimerType::GAME_TIME ? data.mGameTimersQueue : data.mSimulationTimersQueue, std::move(t));
}
void ScriptsContainer::callTimer(const Timer& t)
{
try
{
Script& script = getScript(t.mScriptId);
if (t.mSerializable)
{
const std::string& callbackName = std::get<std::string>(t.mCallback);
auto it = script.mRegisteredCallbacks.find(callbackName);
if (it == script.mRegisteredCallbacks.end())
throw std::logic_error("Callback '" + callbackName + "' doesn't exist");
LuaUtil::call({ this, t.mScriptId }, it->second, t.mArg);
}
else
{
int64_t id = std::get<int64_t>(t.mCallback);
LuaUtil::call({ this, t.mScriptId }, script.mTemporaryCallbacks.at(id));
script.mTemporaryCallbacks.erase(id);
}
}
catch (std::exception& e)
{
printError(t.mScriptId, "callTimer failed", e);
}
}
void ScriptsContainer::updateTimerQueue(std::vector<Timer>& timerQueue, double time)
{
while (!timerQueue.empty() && timerQueue.front().mTime <= time)
{
callTimer(timerQueue.front());
std::pop_heap(timerQueue.begin(), timerQueue.end());
timerQueue.pop_back();
}
}
void ScriptsContainer::processTimers(double simulationTime, double gameTime)
{
LoadedData& data = ensureLoaded();
updateTimerQueue(data.mSimulationTimersQueue, simulationTime);
updateTimerQueue(data.mGameTimersQueue, gameTime);
}
static constexpr float instructionCountAvgCoef = 1.0f / 30; // averaging over approximately 30 frames
void ScriptsContainer::statsNextFrame()
{
if (LoadedData* data = std::get_if<LoadedData>(&mData))
{
for (auto& [scriptId, script] : data->mScripts)
{
// The averaging formula is: averageValue = averageValue * (1-c) + newValue * c
script.mStats.mAvgInstructionCount *= 1 - instructionCountAvgCoef;
if (script.mStats.mAvgInstructionCount < 5)
script.mStats.mAvgInstructionCount = 0; // speeding up converge to zero if newValue is zero
}
}
}
void ScriptsContainer::addInstructionCount(int scriptId, int64_t instructionCount)
{
if (LoadedData* data = std::get_if<LoadedData>(&mData))
{
auto it = data->mScripts.find(scriptId);
if (it != data->mScripts.end())
it->second.mStats.mAvgInstructionCount += instructionCount * instructionCountAvgCoef;
}
}
void ScriptsContainer::addMemoryUsage(int scriptId, int64_t memoryDelta)
{
int64_t* usage = std::visit(
[&](auto&& variant) {
using T = std::decay_t<decltype(variant)>;
if constexpr (std::is_same_v<T, LoadedData>)
{
auto it = variant.mScripts.find(scriptId);
if (it != variant.mScripts.end())
return &it->second.mStats.mMemoryUsage;
}
auto [rIt, _] = mRemovedScriptsMemoryUsage.emplace(scriptId, 0);
return &rIt->second;
},
mData);
*usage += memoryDelta;
if (mLua.getSettings().mLogMemoryUsage)
{
int64_t after = *usage;
int64_t before = after - memoryDelta;
// Logging only if one of the most significant bits of used memory size was changed.
// Otherwise it is too verbose.
if ((before ^ after) * 8 > after)
Log(Debug::Verbose) << mNamePrefix << "[" << scriptPath(scriptId) << "] memory usage " << before
<< " -> " << after;
}
}
void ScriptsContainer::collectStats(std::vector<ScriptStats>& stats) const
{
stats.resize(mLua.getConfiguration().size());
if (const LoadedData* data = std::get_if<LoadedData>(&mData))
{
for (auto& [id, script] : data->mScripts)
{
stats[id].mAvgInstructionCount += script.mStats.mAvgInstructionCount;
stats[id].mMemoryUsage += script.mStats.mMemoryUsage;
}
}
for (auto& [id, mem] : mRemovedScriptsMemoryUsage)
stats[id].mMemoryUsage += mem;
}
ScriptsContainer::Script::~Script()
{
if (mHiddenData != sol::nil)
mHiddenData[sScriptIdKey] = sol::nil;
}
}
| 32,571
|
C++
|
.cpp
| 768
| 29.425781
| 120
| 0.542674
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,657
|
storage.cpp
|
OpenMW_openmw/components/lua/storage.cpp
|
#include "storage.hpp"
#include <filesystem>
#include <fstream>
#include <components/debug/debuglog.hpp>
#include "luastate.hpp"
namespace sol
{
template <>
struct is_automagical<LuaUtil::LuaStorage::SectionView> : std::false_type
{
};
}
namespace LuaUtil
{
LuaStorage::Value LuaStorage::Section::sEmpty;
void LuaStorage::registerLifeTime(LuaUtil::LuaView& view, sol::table& res)
{
res["LIFE_TIME"] = LuaUtil::makeStrictReadOnly(tableFromPairs<std::string_view, Section::LifeTime>(view.sol(),
{
{ "Persistent", Section::LifeTime::Persistent },
{ "GameSession", Section::LifeTime::GameSession },
{ "Temporary", Section::LifeTime::Temporary },
}));
}
sol::object LuaStorage::Value::getCopy(lua_State* L) const
{
return deserialize(L, mSerializedValue);
}
sol::object LuaStorage::Value::getReadOnly(lua_State* L) const
{
if (mReadOnlyValue == sol::nil && !mSerializedValue.empty())
mReadOnlyValue = deserialize(L, mSerializedValue, nullptr, true);
return mReadOnlyValue;
}
const LuaStorage::Value& LuaStorage::Section::get(std::string_view key) const
{
checkIfActive();
auto it = mValues.find(key);
if (it != mValues.end())
return it->second;
else
return sEmpty;
}
void LuaStorage::Section::runCallbacks(sol::optional<std::string_view> changedKey)
{
mStorage->mRunningCallbacks.insert(this);
mCallbacks.erase(std::remove_if(mCallbacks.begin(), mCallbacks.end(),
[&](const Callback& callback) {
bool valid = callback.isValid();
if (valid)
callback.tryCall(mSectionName, changedKey);
return !valid;
}),
mCallbacks.end());
mMenuScriptsCallbacks.erase(std::remove_if(mMenuScriptsCallbacks.begin(), mMenuScriptsCallbacks.end(),
[&](const Callback& callback) {
bool valid = callback.isValid();
if (valid)
callback.tryCall(mSectionName, changedKey);
return !valid;
}),
mMenuScriptsCallbacks.end());
mStorage->mRunningCallbacks.erase(this);
}
void LuaStorage::Section::throwIfCallbackRecursionIsTooDeep()
{
if (mStorage->mRunningCallbacks.count(this) > 0)
throw std::runtime_error(
"Storage handler shouldn't change the storage section it handles (leads to an infinite recursion)");
if (mStorage->mRunningCallbacks.size() > 10)
throw std::runtime_error(
"Too many subscribe callbacks triggering in a chain, likely an infinite recursion");
}
void LuaStorage::Section::set(std::string_view key, const sol::object& value)
{
checkIfActive();
throwIfCallbackRecursionIsTooDeep();
if (value != sol::nil)
mValues[std::string(key)] = Value(value);
else
{
auto it = mValues.find(key);
if (it != mValues.end())
mValues.erase(it);
}
if (mStorage->mListener)
mStorage->mListener->valueChanged(mSectionName, key, value);
runCallbacks(key);
}
void LuaStorage::Section::setAll(const sol::optional<sol::table>& values)
{
checkIfActive();
throwIfCallbackRecursionIsTooDeep();
mValues.clear();
if (values)
{
for (const auto& [k, v] : *values)
mValues[cast<std::string>(k)] = Value(v);
}
if (mStorage->mListener)
mStorage->mListener->sectionReplaced(mSectionName, values);
runCallbacks(sol::nullopt);
}
sol::table LuaStorage::Section::asTable(lua_State* L)
{
checkIfActive();
sol::table res(L, sol::create);
for (const auto& [k, v] : mValues)
res[k] = v.getCopy(L);
return res;
}
void LuaStorage::initLuaBindings(LuaUtil::LuaView& view)
{
sol::usertype<SectionView> sview = view.sol().new_usertype<SectionView>("Section");
sview["get"] = [](sol::this_state s, const SectionView& section, std::string_view key) {
return section.mSection->get(key).getReadOnly(s);
};
sview["getCopy"] = [](sol::this_state s, const SectionView& section, std::string_view key) {
return section.mSection->get(key).getCopy(s);
};
sview["asTable"]
= [](sol::this_state lua, const SectionView& section) { return section.mSection->asTable(lua); };
sview["subscribe"] = [](const SectionView& section, const sol::table& callback) {
std::vector<Callback>& callbacks
= section.mForMenuScripts ? section.mSection->mMenuScriptsCallbacks : section.mSection->mCallbacks;
if (!callbacks.empty() && callbacks.size() == callbacks.capacity())
{
callbacks.erase(
std::remove_if(callbacks.begin(), callbacks.end(), [&](const Callback& c) { return !c.isValid(); }),
callbacks.end());
}
callbacks.push_back(Callback::fromLua(callback));
};
sview["reset"] = [](const SectionView& section, const sol::optional<sol::table>& newValues) {
if (section.mReadOnly)
throw std::runtime_error("Access to storage is read only");
section.mSection->setAll(newValues);
};
sview["removeOnExit"] = [](const SectionView& section) {
if (section.mReadOnly)
throw std::runtime_error("Access to storage is read only");
section.mSection->mLifeTime = Section::Temporary;
};
sview["setLifeTime"] = [](const SectionView& section, Section::LifeTime lifeTime) {
if (section.mReadOnly)
throw std::runtime_error("Access to storage is read only");
section.mSection->mLifeTime = lifeTime;
};
sview["set"] = [](const SectionView& section, std::string_view key, const sol::object& value) {
if (section.mReadOnly)
throw std::runtime_error("Access to storage is read only");
section.mSection->set(key, value);
};
}
sol::table LuaStorage::initGlobalPackage(LuaUtil::LuaView& view, LuaStorage* globalStorage)
{
sol::table res(view.sol(), sol::create);
registerLifeTime(view, res);
res["globalSection"] = [globalStorage](sol::this_state lua, std::string_view section) {
return globalStorage->getMutableSection(lua, section);
};
res["allGlobalSections"] = [globalStorage](sol::this_state lua) { return globalStorage->getAllSections(lua); };
return LuaUtil::makeReadOnly(res);
}
sol::table LuaStorage::initLocalPackage(LuaUtil::LuaView& view, LuaStorage* globalStorage)
{
sol::table res(view.sol(), sol::create);
registerLifeTime(view, res);
res["globalSection"] = [globalStorage](sol::this_state lua, std::string_view section) {
return globalStorage->getReadOnlySection(lua, section);
};
return LuaUtil::makeReadOnly(res);
}
sol::table LuaStorage::initPlayerPackage(
LuaUtil::LuaView& view, LuaStorage* globalStorage, LuaStorage* playerStorage)
{
sol::table res(view.sol(), sol::create);
registerLifeTime(view, res);
res["globalSection"] = [globalStorage](sol::this_state lua, std::string_view section) {
return globalStorage->getReadOnlySection(lua, section);
};
res["playerSection"] = [playerStorage](sol::this_state lua, std::string_view section) {
return playerStorage->getMutableSection(lua, section);
};
res["allPlayerSections"] = [playerStorage](sol::this_state lua) { return playerStorage->getAllSections(lua); };
return LuaUtil::makeReadOnly(res);
}
sol::table LuaStorage::initMenuPackage(LuaUtil::LuaView& view, LuaStorage* globalStorage, LuaStorage* playerStorage)
{
sol::table res(view.sol(), sol::create);
registerLifeTime(view, res);
res["playerSection"] = [playerStorage](sol::this_state lua, std::string_view section) {
return playerStorage->getMutableSection(lua, section, /*forMenuScripts=*/true);
};
res["globalSection"] = [globalStorage](sol::this_state lua, std::string_view section) {
return globalStorage->getReadOnlySection(lua, section);
};
res["allPlayerSections"] = [playerStorage](sol::this_state lua) { return playerStorage->getAllSections(lua); };
return LuaUtil::makeReadOnly(res);
}
void LuaStorage::clearTemporaryAndRemoveCallbacks()
{
auto it = mData.begin();
while (it != mData.end())
{
it->second->mCallbacks.clear();
// Note that we don't clear menu callbacks for permanent sections
// because starting/loading a game doesn't reset menu scripts.
if (it->second->mLifeTime == Section::Temporary)
{
it->second->mMenuScriptsCallbacks.clear();
it->second->mValues.clear();
it = mData.erase(it);
}
else
++it;
}
}
void LuaStorage::load(lua_State* L, const std::filesystem::path& path)
{
assert(mData.empty()); // Shouldn't be used before loading
try
{
std::uintmax_t fileSize = std::filesystem::file_size(path);
Log(Debug::Info) << "Loading Lua storage \"" << path << "\" (" << fileSize << " bytes)";
if (fileSize == 0)
throw std::runtime_error("Storage file has zero length");
std::ifstream fin(path, std::fstream::binary);
std::string serializedData((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>());
sol::table data = deserialize(L, serializedData);
for (const auto& [sectionName, sectionTable] : data)
{
const std::shared_ptr<Section>& section = getSection(cast<std::string_view>(sectionName));
for (const auto& [key, value] : cast<sol::table>(sectionTable))
section->set(cast<std::string_view>(key), value);
}
}
catch (std::exception& e)
{
Log(Debug::Error) << "Cannot read \"" << path << "\": " << e.what();
}
}
void LuaStorage::save(lua_State* L, const std::filesystem::path& path) const
{
sol::table data(L, sol::create);
for (const auto& [sectionName, section] : mData)
{
if (section->mLifeTime == Section::Persistent && !section->mValues.empty())
data[sectionName] = section->asTable(L);
}
std::string serializedData = serialize(data);
Log(Debug::Info) << "Saving Lua storage \"" << path << "\" (" << serializedData.size() << " bytes)";
std::ofstream fout(path, std::fstream::binary);
fout.write(serializedData.data(), serializedData.size());
fout.close();
}
const std::shared_ptr<LuaStorage::Section>& LuaStorage::getSection(std::string_view sectionName)
{
checkIfActive();
auto it = mData.find(sectionName);
if (it != mData.end())
return it->second;
auto section = std::make_shared<Section>(this, std::string(sectionName));
sectionName = section->mSectionName;
auto [newIt, _] = mData.emplace(sectionName, std::move(section));
return newIt->second;
}
sol::object LuaStorage::getSection(lua_State* L, std::string_view sectionName, bool readOnly, bool forMenuScripts)
{
checkIfActive();
const std::shared_ptr<Section>& section = getSection(sectionName);
return sol::make_object<SectionView>(L, SectionView{ section, readOnly, forMenuScripts });
}
sol::table LuaStorage::getAllSections(lua_State* L, bool readOnly)
{
checkIfActive();
sol::table res(L, sol::create);
for (const auto& [sectionName, _] : mData)
res[sectionName] = getSection(L, sectionName, readOnly);
return res;
}
}
| 12,666
|
C++
|
.cpp
| 282
| 34.223404
| 120
| 0.590464
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,658
|
scripttracker.cpp
|
OpenMW_openmw/components/lua/scripttracker.cpp
|
#include "scripttracker.hpp"
namespace LuaUtil
{
namespace
{
constexpr unsigned sMinLoadedFrames = 50;
constexpr unsigned sMaxLoadedFrames = 600;
constexpr unsigned sUsageFrameGrowth = 10;
constexpr std::size_t sMinToProcess = 1;
constexpr std::size_t sToProcessDiv = 20; // 5%
}
void ScriptTracker::onLoad(ScriptsContainer& container)
{
mLoadedScripts.emplace(container.mThis, sMinLoadedFrames + mFrame);
}
void ScriptTracker::unloadInactiveScripts(LuaView& lua)
{
// This code is technically incorrect if mFrame overflows... but at 300fps that takes about half a year
std::size_t toProcess = std::max(mLoadedScripts.size() / sToProcessDiv, sMinToProcess);
while (toProcess && !mLoadedScripts.empty())
{
--toProcess;
auto [ptr, ttl] = std::move(mLoadedScripts.front());
mLoadedScripts.pop();
ScriptsContainer* container = *ptr.get();
// Object no longer exists, cease tracking
if (!container)
continue;
// Ignore activity of local scripts in the active grid
if (container->isActive())
ttl = std::max(ttl, mFrame + sMinLoadedFrames);
else
{
bool activeSinceLastPop = container->mRequiredLoading;
if (activeSinceLastPop)
{
container->mRequiredLoading = false;
ttl = std::min(ttl + sUsageFrameGrowth, mFrame + sMaxLoadedFrames);
}
else if (ttl < mFrame)
{
container->ensureUnloaded(lua);
continue;
}
}
mLoadedScripts.emplace(std::move(ptr), ttl);
}
++mFrame;
}
}
| 1,864
|
C++
|
.cpp
| 50
| 26.22
| 111
| 0.571507
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,659
|
box.cpp
|
OpenMW_openmw/components/lua/shapes/box.cpp
|
#include "box.hpp"
namespace LuaUtil
{
Box::Box(const osg::Vec3f& center, const osg::Vec3f& halfSize, const osg::Quat& rotation)
: mCenter(center)
, mHalfSize(halfSize)
, mRotation(rotation)
{
}
Box::Box(const osg::Matrix& transform)
{
osg::Quat _;
transform.decompose(mCenter, mRotation, mHalfSize, _);
}
std::array<osg::Vec3f, 8> Box::vertices() const
{
return {
mCenter + mRotation * osg::Vec3f(-mHalfSize.x(), -mHalfSize.y(), -mHalfSize.z()),
mCenter + mRotation * osg::Vec3f(mHalfSize.x(), -mHalfSize.y(), -mHalfSize.z()),
mCenter + mRotation * osg::Vec3f(mHalfSize.x(), mHalfSize.y(), -mHalfSize.z()),
mCenter + mRotation * osg::Vec3f(-mHalfSize.x(), mHalfSize.y(), -mHalfSize.z()),
mCenter + mRotation * osg::Vec3f(-mHalfSize.x(), -mHalfSize.y(), mHalfSize.z()),
mCenter + mRotation * osg::Vec3f(mHalfSize.x(), -mHalfSize.y(), mHalfSize.z()),
mCenter + mRotation * osg::Vec3f(mHalfSize.x(), mHalfSize.y(), mHalfSize.z()),
mCenter + mRotation * osg::Vec3f(-mHalfSize.x(), mHalfSize.y(), mHalfSize.z()),
};
}
osg::Matrix Box::asTransform() const
{
osg::Matrix transform;
transform.preMultTranslate(mCenter);
transform.preMultRotate(mRotation);
transform.preMultScale(mHalfSize);
return transform;
}
bool Box::operator==(const Box& other) const
{
return mCenter == other.mCenter && mHalfSize == other.mHalfSize && mRotation == other.mRotation;
}
}
| 1,616
|
C++
|
.cpp
| 40
| 32.8
| 104
| 0.604326
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,660
|
qtconversion.cpp
|
OpenMW_openmw/components/vfs/qtconversion.cpp
|
#include "qtconversion.hpp"
#include <components/misc/strings/conversion.hpp>
QString VFS::Path::normalizedToQString(NormalizedView path)
{
return QString::fromUtf8(path.value().data(), path.value().size());
}
QString VFS::Path::normalizedToQString(Normalized&& path)
{
return QString::fromUtf8(path.value().data(), path.value().size());
}
VFS::Path::Normalized VFS::Path::normalizedFromQString(QStringView path)
{
const auto tmp = path.toUtf8();
return Normalized{ tmp };
}
VFS::Path::Normalized VFS::Path::normalizedFromQString(QString&& path)
{
const auto tmp = path.toUtf8();
return Normalized{ tmp };
}
| 638
|
C++
|
.cpp
| 20
| 29.4
| 72
| 0.740196
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,661
|
registerarchives.cpp
|
OpenMW_openmw/components/vfs/registerarchives.cpp
|
#include "registerarchives.hpp"
#include <filesystem>
#include <set>
#include <stdexcept>
#include <components/debug/debuglog.hpp>
#include <components/vfs/bsaarchive.hpp>
#include <components/vfs/filesystemarchive.hpp>
#include <components/vfs/manager.hpp>
namespace VFS
{
void registerArchives(VFS::Manager* vfs, const Files::Collections& collections,
const std::vector<std::string>& archives, bool useLooseFiles)
{
const Files::PathContainer& dataDirs = collections.getPaths();
for (std::vector<std::string>::const_iterator archive = archives.begin(); archive != archives.end(); ++archive)
{
if (collections.doesExist(*archive))
{
// Last BSA has the highest priority
const auto archivePath = collections.getPath(*archive);
Log(Debug::Info) << "Adding BSA archive " << archivePath;
vfs->addArchive(makeBsaArchive(archivePath));
}
else
{
throw std::runtime_error("Archive '" + *archive + "' not found");
}
}
if (useLooseFiles)
{
std::set<std::filesystem::path> seen;
for (const auto& dataDir : dataDirs)
{
if (seen.insert(dataDir).second)
{
Log(Debug::Info) << "Adding data directory " << dataDir;
// Last data dir has the highest priority
vfs->addArchive(std::make_unique<FileSystemArchive>(dataDir));
}
else
Log(Debug::Info) << "Ignoring duplicate data directory " << dataDir;
}
}
vfs->buildIndex();
}
}
| 1,745
|
C++
|
.cpp
| 46
| 27.434783
| 119
| 0.570414
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,662
|
manager.cpp
|
OpenMW_openmw/components/vfs/manager.cpp
|
#include "manager.hpp"
#include <cassert>
#include <stdexcept>
#include <components/files/conversion.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/vfs/recursivedirectoryiterator.hpp>
#include "archive.hpp"
#include "file.hpp"
#include "pathutil.hpp"
#include "recursivedirectoryiterator.hpp"
namespace VFS
{
Manager::Manager() = default;
Manager::~Manager() = default;
void Manager::reset()
{
mIndex.clear();
mArchives.clear();
}
void Manager::addArchive(std::unique_ptr<Archive>&& archive)
{
mArchives.push_back(std::move(archive));
}
void Manager::buildIndex()
{
mIndex.clear();
for (const auto& archive : mArchives)
archive->listResources(mIndex);
}
Files::IStreamPtr Manager::find(Path::NormalizedView name) const
{
return findNormalized(name.value());
}
Files::IStreamPtr Manager::get(const Path::Normalized& name) const
{
return getNormalized(name);
}
Files::IStreamPtr Manager::get(Path::NormalizedView name) const
{
return getNormalized(name.value());
}
Files::IStreamPtr Manager::getNormalized(std::string_view normalizedName) const
{
assert(Path::isNormalized(normalizedName));
auto ptr = findNormalized(normalizedName);
if (ptr == nullptr)
throw std::runtime_error("Resource '" + std::string(normalizedName) + "' not found");
return ptr;
}
bool Manager::exists(const Path::Normalized& name) const
{
return mIndex.find(name) != mIndex.end();
}
bool Manager::exists(Path::NormalizedView name) const
{
return mIndex.find(name) != mIndex.end();
}
std::string Manager::getArchive(const Path::Normalized& name) const
{
for (auto it = mArchives.rbegin(); it != mArchives.rend(); ++it)
{
if ((*it)->contains(name))
return (*it)->getDescription();
}
return {};
}
std::filesystem::path Manager::getAbsoluteFileName(const std::filesystem::path& name) const
{
std::string normalized = Files::pathToUnicodeString(name);
Path::normalizeFilenameInPlace(normalized);
const auto found = mIndex.find(normalized);
if (found == mIndex.end())
throw std::runtime_error("Resource '" + normalized + "' is not found");
return found->second->getPath();
}
RecursiveDirectoryRange Manager::getRecursiveDirectoryIterator(std::string_view path) const
{
if (path.empty())
return { mIndex.begin(), mIndex.end() };
std::string normalized = Path::normalizeFilename(path);
const auto it = mIndex.lower_bound(normalized);
if (it == mIndex.end() || !it->first.view().starts_with(normalized))
return { it, it };
++normalized.back();
return { it, mIndex.lower_bound(normalized) };
}
RecursiveDirectoryRange Manager::getRecursiveDirectoryIterator(VFS::Path::NormalizedView path) const
{
if (path.value().empty())
return { mIndex.begin(), mIndex.end() };
const auto it = mIndex.lower_bound(path);
if (it == mIndex.end() || !it->first.view().starts_with(path.value()))
return { it, it };
std::string copy(path.value());
++copy.back();
return { it, mIndex.lower_bound(copy) };
}
RecursiveDirectoryRange Manager::getRecursiveDirectoryIterator() const
{
return { mIndex.begin(), mIndex.end() };
}
Files::IStreamPtr Manager::findNormalized(std::string_view normalizedPath) const
{
assert(Path::isNormalized(normalizedPath));
const auto it = mIndex.find(normalizedPath);
if (it == mIndex.end())
return nullptr;
return it->second->open();
}
}
| 3,885
|
C++
|
.cpp
| 110
| 28.372727
| 104
| 0.634426
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,663
|
filesystemarchive.cpp
|
OpenMW_openmw/components/vfs/filesystemarchive.cpp
|
#include "filesystemarchive.hpp"
#include <filesystem>
#include "pathutil.hpp"
#include <components/debug/debuglog.hpp>
#include <components/files/constrainedfilestream.hpp>
#include <components/files/conversion.hpp>
namespace VFS
{
FileSystemArchive::FileSystemArchive(const std::filesystem::path& path)
: mPath(path)
{
const auto str = mPath.u8string();
std::size_t prefix = str.size();
if (prefix > 0 && str[prefix - 1] != '\\' && str[prefix - 1] != '/')
++prefix;
std::filesystem::recursive_directory_iterator iterator(mPath);
for (auto it = std::filesystem::begin(iterator), end = std::filesystem::end(iterator); it != end;)
{
const std::filesystem::directory_entry& entry = *it;
if (!entry.is_directory())
{
const std::filesystem::path& filePath = entry.path();
const std::string proper = Files::pathToUnicodeString(filePath);
VFS::Path::Normalized searchable(std::string_view{ proper }.substr(prefix));
FileSystemArchiveFile file(filePath);
const auto inserted = mIndex.emplace(std::move(searchable), std::move(file));
if (!inserted.second)
Log(Debug::Warning)
<< "Found duplicate file for '" << proper
<< "', please check your file system for two files with the same name in different cases.";
}
// Exception thrown by the operator++ may not contain the context of the error like what exact path caused
// the problem which makes it hard to understand what's going on when iteration happens over a directory
// with thousands of files and subdirectories.
const std::filesystem::path prevPath = entry.path();
std::error_code ec;
it.increment(ec);
if (ec != std::error_code())
throw std::runtime_error("Failed to recursively iterate over \"" + Files::pathToUnicodeString(mPath)
+ "\" when incrementing to the next item from \"" + Files::pathToUnicodeString(prevPath)
+ "\": " + ec.message());
}
}
void FileSystemArchive::listResources(FileMap& out)
{
for (auto& [k, v] : mIndex)
out[k] = &v;
}
bool FileSystemArchive::contains(Path::NormalizedView file) const
{
return mIndex.find(file) != mIndex.end();
}
std::string FileSystemArchive::getDescription() const
{
return "DIR: " + Files::pathToUnicodeString(mPath);
}
// ----------------------------------------------------------------------------------
FileSystemArchiveFile::FileSystemArchiveFile(const std::filesystem::path& path)
: mPath(path)
{
}
Files::IStreamPtr FileSystemArchiveFile::open()
{
return Files::openConstrainedFileStream(mPath);
}
}
| 2,982
|
C++
|
.cpp
| 66
| 35.484848
| 118
| 0.589717
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,664
|
controller.cpp
|
OpenMW_openmw/components/nifosg/controller.cpp
|
#include "controller.hpp"
#include <osg/Material>
#include <osg/MatrixTransform>
#include <osg/TexMat>
#include <osg/Texture2D>
#include <osgAnimation/Bone>
#include <osgParticle/Emitter>
#include <components/nif/data.hpp>
#include <components/sceneutil/morphgeometry.hpp>
#include "matrixtransform.hpp"
namespace NifOsg
{
ControllerFunction::ControllerFunction(const Nif::NiTimeController* ctrl)
: mFrequency(ctrl->mFrequency)
, mPhase(ctrl->mPhase)
, mStartTime(ctrl->mTimeStart)
, mStopTime(ctrl->mTimeStop)
, mExtrapolationMode(ctrl->extrapolationMode())
{
}
float ControllerFunction::calculate(float value) const
{
float time = mFrequency * value + mPhase;
if (time >= mStartTime && time <= mStopTime)
return time;
switch (mExtrapolationMode)
{
case Nif::NiTimeController::ExtrapolationMode::Cycle:
{
float delta = mStopTime - mStartTime;
if (delta <= 0)
return mStartTime;
float cycles = (time - mStartTime) / delta;
float remainder = (cycles - std::floor(cycles)) * delta;
return mStartTime + remainder;
}
case Nif::NiTimeController::ExtrapolationMode::Reverse:
{
float delta = mStopTime - mStartTime;
if (delta <= 0)
return mStartTime;
float cycles = (time - mStartTime) / delta;
float remainder = (cycles - std::floor(cycles)) * delta;
// Even number of cycles?
if ((static_cast<int>(std::fabs(std::floor(cycles))) % 2) == 0)
return mStartTime + remainder;
return mStopTime - remainder;
}
case Nif::NiTimeController::ExtrapolationMode::Constant:
default:
{
if (time < mStartTime)
return mStartTime;
if (time > mStopTime)
return mStopTime;
return time;
}
}
}
float ControllerFunction::getMaximum() const
{
return mStopTime;
}
KeyframeController::KeyframeController() {}
KeyframeController::KeyframeController(const KeyframeController& copy, const osg::CopyOp& copyop)
: osg::Object(copy, copyop)
, SceneUtil::KeyframeController(copy)
, SceneUtil::NodeCallback<KeyframeController, NifOsg::MatrixTransform*>(copy, copyop)
, mRotations(copy.mRotations)
, mXRotations(copy.mXRotations)
, mYRotations(copy.mYRotations)
, mZRotations(copy.mZRotations)
, mTranslations(copy.mTranslations)
, mScales(copy.mScales)
, mAxisOrder(copy.mAxisOrder)
{
}
KeyframeController::KeyframeController(const Nif::NiKeyframeController* keyctrl)
{
if (!keyctrl->mInterpolator.empty())
{
if (keyctrl->mInterpolator->recType == Nif::RC_NiTransformInterpolator)
{
const Nif::NiTransformInterpolator* interp
= static_cast<const Nif::NiTransformInterpolator*>(keyctrl->mInterpolator.getPtr());
const Nif::NiQuatTransform& defaultTransform = interp->mDefaultValue;
if (!interp->mData.empty())
{
mRotations = QuaternionInterpolator(interp->mData->mRotations, defaultTransform.mRotation);
mXRotations = FloatInterpolator(interp->mData->mXRotations);
mYRotations = FloatInterpolator(interp->mData->mYRotations);
mZRotations = FloatInterpolator(interp->mData->mZRotations);
mTranslations = Vec3Interpolator(interp->mData->mTranslations, defaultTransform.mTranslation);
mScales = FloatInterpolator(interp->mData->mScales, defaultTransform.mScale);
mAxisOrder = interp->mData->mAxisOrder;
}
else
{
mRotations = QuaternionInterpolator(Nif::QuaternionKeyMapPtr(), defaultTransform.mRotation);
mTranslations = Vec3Interpolator(Nif::Vector3KeyMapPtr(), defaultTransform.mTranslation);
mScales = FloatInterpolator(Nif::FloatKeyMapPtr(), defaultTransform.mScale);
}
}
}
else if (!keyctrl->mData.empty())
{
const Nif::NiKeyframeData* keydata = keyctrl->mData.getPtr();
mRotations = QuaternionInterpolator(keydata->mRotations);
mXRotations = FloatInterpolator(keydata->mXRotations);
mYRotations = FloatInterpolator(keydata->mYRotations);
mZRotations = FloatInterpolator(keydata->mZRotations);
mTranslations = Vec3Interpolator(keydata->mTranslations);
mScales = FloatInterpolator(keydata->mScales, 1.f);
mAxisOrder = keydata->mAxisOrder;
}
}
osg::Quat KeyframeController::getXYZRotation(float time) const
{
float xrot = 0, yrot = 0, zrot = 0;
if (!mXRotations.empty())
xrot = mXRotations.interpKey(time);
if (!mYRotations.empty())
yrot = mYRotations.interpKey(time);
if (!mZRotations.empty())
zrot = mZRotations.interpKey(time);
osg::Quat xr(xrot, osg::X_AXIS);
osg::Quat yr(yrot, osg::Y_AXIS);
osg::Quat zr(zrot, osg::Z_AXIS);
switch (mAxisOrder)
{
case Nif::NiKeyframeData::AxisOrder::Order_XYZ:
return xr * yr * zr;
case Nif::NiKeyframeData::AxisOrder::Order_XZY:
return xr * zr * yr;
case Nif::NiKeyframeData::AxisOrder::Order_YZX:
return yr * zr * xr;
case Nif::NiKeyframeData::AxisOrder::Order_YXZ:
return yr * xr * zr;
case Nif::NiKeyframeData::AxisOrder::Order_ZXY:
return zr * xr * yr;
case Nif::NiKeyframeData::AxisOrder::Order_ZYX:
return zr * yr * xr;
case Nif::NiKeyframeData::AxisOrder::Order_XYX:
return xr * yr * xr;
case Nif::NiKeyframeData::AxisOrder::Order_YZY:
return yr * zr * yr;
case Nif::NiKeyframeData::AxisOrder::Order_ZXZ:
return zr * xr * zr;
}
return xr * yr * zr;
}
osg::Vec3f KeyframeController::getTranslation(float time) const
{
if (!mTranslations.empty())
return mTranslations.interpKey(time);
return osg::Vec3f();
}
void KeyframeController::operator()(NifOsg::MatrixTransform* node, osg::NodeVisitor* nv)
{
auto [translation, rotation, scale] = getCurrentTransformation(nv);
if (rotation)
{
node->setRotation(*rotation);
}
else
{
// This is necessary to prevent first person animations glitching out due to RotationController
node->setRotation(node->mRotationScale);
}
if (translation)
node->setTranslation(*translation);
if (scale)
node->setScale(*scale);
traverse(node, nv);
}
KeyframeController::KfTransform KeyframeController::getCurrentTransformation(osg::NodeVisitor* nv)
{
KfTransform out;
if (hasInput())
{
float time = getInputValue(nv);
if (!mRotations.empty())
out.mRotation = mRotations.interpKey(time);
else if (!mXRotations.empty() || !mYRotations.empty() || !mZRotations.empty())
out.mRotation = getXYZRotation(time);
if (!mTranslations.empty())
out.mTranslation = mTranslations.interpKey(time);
if (!mScales.empty())
out.mScale = mScales.interpKey(time);
}
return out;
}
GeomMorpherController::GeomMorpherController() {}
GeomMorpherController::GeomMorpherController(const GeomMorpherController& copy, const osg::CopyOp& copyop)
: Controller(copy)
, SceneUtil::NodeCallback<GeomMorpherController, SceneUtil::MorphGeometry*>(copy, copyop)
, mKeyFrames(copy.mKeyFrames)
, mWeights(copy.mWeights)
{
}
GeomMorpherController::GeomMorpherController(const Nif::NiGeomMorpherController* ctrl)
{
if (ctrl->mInterpolators.size() == 0)
{
if (!ctrl->mData.empty())
{
for (const auto& morph : ctrl->mData->mMorphs)
mKeyFrames.emplace_back(morph.mKeyFrames);
}
return;
}
mKeyFrames.resize(ctrl->mInterpolators.size());
mWeights = ctrl->mWeights;
for (std::size_t i = 0, n = ctrl->mInterpolators.size(); i < n; ++i)
{
if (!ctrl->mInterpolators[i].empty() && ctrl->mInterpolators[i]->recType == Nif::RC_NiFloatInterpolator)
{
auto interpolator = static_cast<const Nif::NiFloatInterpolator*>(ctrl->mInterpolators[i].getPtr());
mKeyFrames[i] = FloatInterpolator(interpolator);
}
}
}
void GeomMorpherController::operator()(SceneUtil::MorphGeometry* node, osg::NodeVisitor* nv)
{
if (hasInput())
{
if (mKeyFrames.size() <= 1)
return;
float input = getInputValue(nv);
size_t i = 1;
for (std::vector<FloatInterpolator>::iterator it = mKeyFrames.begin() + 1; it != mKeyFrames.end();
++it, ++i)
{
float val = 0;
if (!(*it).empty())
{
val = it->interpKey(input);
if (i < mWeights.size())
val *= mWeights[i];
}
SceneUtil::MorphGeometry::MorphTarget& target = node->getMorphTarget(i);
if (target.getWeight() != val)
{
target.setWeight(val);
node->dirty();
}
}
}
}
UVController::UVController(const Nif::NiUVData* data, const std::set<unsigned int>& textureUnits)
: mUTrans(data->mKeyList[0], 0.f)
, mVTrans(data->mKeyList[1], 0.f)
, mUScale(data->mKeyList[2], 1.f)
, mVScale(data->mKeyList[3], 1.f)
, mTextureUnits(textureUnits)
{
}
UVController::UVController(const UVController& copy, const osg::CopyOp& copyop)
: osg::Object(copy, copyop)
, StateSetUpdater(copy, copyop)
, Controller(copy)
, mUTrans(copy.mUTrans)
, mVTrans(copy.mVTrans)
, mUScale(copy.mUScale)
, mVScale(copy.mVScale)
, mTextureUnits(copy.mTextureUnits)
{
}
void UVController::setDefaults(osg::StateSet* stateset)
{
osg::ref_ptr<osg::TexMat> texMat(new osg::TexMat);
for (unsigned int unit : mTextureUnits)
stateset->setTextureAttributeAndModes(unit, texMat, osg::StateAttribute::ON);
}
void UVController::apply(osg::StateSet* stateset, osg::NodeVisitor* nv)
{
if (hasInput())
{
float value = getInputValue(nv);
// First scale the UV relative to its center, then apply the offset.
// U offset is flipped regardless of the graphics library,
// while V offset is flipped to account for OpenGL Y axis convention.
osg::Vec3f uvOrigin(0.5f, 0.5f, 0.f);
osg::Vec3f uvScale(mUScale.interpKey(value), mVScale.interpKey(value), 1.f);
osg::Vec3f uvTrans(-mUTrans.interpKey(value), -mVTrans.interpKey(value), 0.f);
osg::Matrixf mat = osg::Matrixf::translate(uvOrigin);
mat.preMultScale(uvScale);
mat.preMultTranslate(-uvOrigin);
mat.setTrans(mat.getTrans() + uvTrans);
// setting once is enough because all other texture units share the same TexMat (see setDefaults).
if (!mTextureUnits.empty())
{
osg::TexMat* texMat = static_cast<osg::TexMat*>(
stateset->getTextureAttribute(*mTextureUnits.begin(), osg::StateAttribute::TEXMAT));
texMat->setMatrix(mat);
}
}
}
VisController::VisController(const Nif::NiVisController* ctrl, unsigned int mask)
: mMask(mask)
{
if (!ctrl->mInterpolator.empty())
{
if (ctrl->mInterpolator->recType != Nif::RC_NiBoolInterpolator)
return;
mInterpolator = { static_cast<const Nif::NiBoolInterpolator*>(ctrl->mInterpolator.getPtr()) };
}
else if (!ctrl->mData.empty())
mData = ctrl->mData->mKeys;
}
VisController::VisController() {}
VisController::VisController(const VisController& copy, const osg::CopyOp& copyop)
: SceneUtil::NodeCallback<VisController>(copy, copyop)
, Controller(copy)
, mData(copy.mData)
, mInterpolator(copy.mInterpolator)
, mMask(copy.mMask)
{
}
bool VisController::calculate(float time) const
{
if (!mInterpolator.empty())
return mInterpolator.interpKey(time);
if (mData->empty())
return true;
auto iter = mData->upper_bound(time);
if (iter != mData->begin())
--iter;
return iter->second;
}
void VisController::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
if (hasInput())
{
bool vis = calculate(getInputValue(nv));
node->setNodeMask(vis ? ~0 : mMask);
}
traverse(node, nv);
}
RollController::RollController(const Nif::NiRollController* ctrl)
{
if (!ctrl->mInterpolator.empty())
{
if (ctrl->mInterpolator->recType == Nif::RC_NiFloatInterpolator)
mData = FloatInterpolator(static_cast<const Nif::NiFloatInterpolator*>(ctrl->mInterpolator.getPtr()));
}
else if (!ctrl->mData.empty())
mData = FloatInterpolator(ctrl->mData->mKeyList, 1.f);
}
RollController::RollController(const RollController& copy, const osg::CopyOp& copyop)
: SceneUtil::NodeCallback<RollController, osg::MatrixTransform*>(copy, copyop)
, Controller(copy)
, mData(copy.mData)
, mStartingTime(copy.mStartingTime)
{
}
void RollController::operator()(osg::MatrixTransform* node, osg::NodeVisitor* nv)
{
traverse(node, nv);
if (hasInput())
{
double newTime = nv->getFrameStamp()->getSimulationTime();
double duration = newTime - mStartingTime;
mStartingTime = newTime;
float value = mData.interpKey(getInputValue(nv));
// Rotate around "roll" axis.
// Note: in original game rotation speed is the framerate-dependent in a very tricky way.
// Do not replicate this behaviour until we will really need it.
// For now consider controller's current value as an angular speed in radians per 1/60 seconds.
node->preMult(osg::Matrix::rotate(value * duration * 60.f, 0, 0, 1));
// Note: doing it like this means RollControllers are not compatible with KeyframeControllers.
// KeyframeController currently wins the conflict.
// However unlikely that is, NetImmerse might combine the transformations somehow.
}
}
AlphaController::AlphaController() {}
AlphaController::AlphaController(const Nif::NiAlphaController* ctrl, const osg::Material* baseMaterial)
: mBaseMaterial(baseMaterial)
{
if (!ctrl->mInterpolator.empty())
{
if (ctrl->mInterpolator->recType == Nif::RC_NiFloatInterpolator)
mData = FloatInterpolator(static_cast<const Nif::NiFloatInterpolator*>(ctrl->mInterpolator.getPtr()));
}
else if (!ctrl->mData.empty())
mData = FloatInterpolator(ctrl->mData->mKeyList, 1.f);
}
AlphaController::AlphaController(const AlphaController& copy, const osg::CopyOp& copyop)
: StateSetUpdater(copy, copyop)
, Controller(copy)
, mData(copy.mData)
, mBaseMaterial(copy.mBaseMaterial)
{
}
void AlphaController::setDefaults(osg::StateSet* stateset)
{
stateset->setAttribute(
static_cast<osg::Material*>(mBaseMaterial->clone(osg::CopyOp::DEEP_COPY_ALL)), osg::StateAttribute::ON);
}
void AlphaController::apply(osg::StateSet* stateset, osg::NodeVisitor* nv)
{
if (hasInput())
{
float value = mData.interpKey(getInputValue(nv));
osg::Material* mat = static_cast<osg::Material*>(stateset->getAttribute(osg::StateAttribute::MATERIAL));
osg::Vec4f diffuse = mat->getDiffuse(osg::Material::FRONT_AND_BACK);
diffuse.a() = value;
mat->setDiffuse(osg::Material::FRONT_AND_BACK, diffuse);
}
}
MaterialColorController::MaterialColorController() = default;
MaterialColorController::MaterialColorController(
const Nif::NiMaterialColorController* ctrl, const osg::Material* baseMaterial)
: mTargetColor(ctrl->mTargetColor)
, mBaseMaterial(baseMaterial)
{
if (!ctrl->mInterpolator.empty())
{
if (ctrl->mInterpolator->recType == Nif::RC_NiPoint3Interpolator)
mData = Vec3Interpolator(static_cast<const Nif::NiPoint3Interpolator*>(ctrl->mInterpolator.getPtr()));
}
else if (!ctrl->mData.empty())
mData = Vec3Interpolator(ctrl->mData->mKeyList, osg::Vec3f(1, 1, 1));
}
MaterialColorController::MaterialColorController(const MaterialColorController& copy, const osg::CopyOp& copyop)
: StateSetUpdater(copy, copyop)
, Controller(copy)
, mData(copy.mData)
, mTargetColor(copy.mTargetColor)
, mBaseMaterial(copy.mBaseMaterial)
{
}
void MaterialColorController::setDefaults(osg::StateSet* stateset)
{
stateset->setAttribute(
static_cast<osg::Material*>(mBaseMaterial->clone(osg::CopyOp::DEEP_COPY_ALL)), osg::StateAttribute::ON);
}
void MaterialColorController::apply(osg::StateSet* stateset, osg::NodeVisitor* nv)
{
if (hasInput())
{
osg::Vec3f value = mData.interpKey(getInputValue(nv));
osg::Material* mat = static_cast<osg::Material*>(stateset->getAttribute(osg::StateAttribute::MATERIAL));
using TargetColor = Nif::NiMaterialColorController::TargetColor;
switch (mTargetColor)
{
case TargetColor::Diffuse:
{
osg::Vec4f diffuse = mat->getDiffuse(osg::Material::FRONT_AND_BACK);
diffuse.set(value.x(), value.y(), value.z(), diffuse.a());
mat->setDiffuse(osg::Material::FRONT_AND_BACK, diffuse);
break;
}
case TargetColor::Specular:
{
osg::Vec4f specular = mat->getSpecular(osg::Material::FRONT_AND_BACK);
specular.set(value.x(), value.y(), value.z(), specular.a());
mat->setSpecular(osg::Material::FRONT_AND_BACK, specular);
break;
}
case TargetColor::Emissive:
{
osg::Vec4f emissive = mat->getEmission(osg::Material::FRONT_AND_BACK);
emissive.set(value.x(), value.y(), value.z(), emissive.a());
mat->setEmission(osg::Material::FRONT_AND_BACK, emissive);
break;
}
case TargetColor::Ambient:
default:
{
osg::Vec4f ambient = mat->getAmbient(osg::Material::FRONT_AND_BACK);
ambient.set(value.x(), value.y(), value.z(), ambient.a());
mat->setAmbient(osg::Material::FRONT_AND_BACK, ambient);
}
}
}
}
FlipController::FlipController(
const Nif::NiFlipController* ctrl, const std::vector<osg::ref_ptr<osg::Texture2D>>& textures)
: mTexSlot(0) // always affects diffuse
, mDelta(ctrl->mDelta)
, mTextures(textures)
{
if (!ctrl->mInterpolator.empty() && ctrl->mInterpolator->recType == Nif::RC_NiFloatInterpolator)
mData = static_cast<const Nif::NiFloatInterpolator*>(ctrl->mInterpolator.getPtr());
}
FlipController::FlipController(int texSlot, float delta, const std::vector<osg::ref_ptr<osg::Texture2D>>& textures)
: mTexSlot(texSlot)
, mDelta(delta)
, mTextures(textures)
{
}
FlipController::FlipController(const FlipController& copy, const osg::CopyOp& copyop)
: StateSetUpdater(copy, copyop)
, Controller(copy)
, mTexSlot(copy.mTexSlot)
, mDelta(copy.mDelta)
, mTextures(copy.mTextures)
, mData(copy.mData)
{
}
void FlipController::apply(osg::StateSet* stateset, osg::NodeVisitor* nv)
{
if (hasInput() && !mTextures.empty())
{
int curTexture = 0;
if (mDelta != 0)
curTexture = int(getInputValue(nv) / mDelta) % mTextures.size();
else
curTexture = int(mData.interpKey(getInputValue(nv))) % mTextures.size();
stateset->setTextureAttribute(mTexSlot, mTextures[curTexture]);
}
}
ParticleSystemController::ParticleSystemController(const Nif::NiParticleSystemController* ctrl)
: mEmitStart(ctrl->mEmitStartTime)
, mEmitStop(ctrl->mEmitStopTime)
{
}
ParticleSystemController::ParticleSystemController(const ParticleSystemController& copy, const osg::CopyOp& copyop)
: SceneUtil::NodeCallback<ParticleSystemController, osgParticle::ParticleProcessor*>(copy, copyop)
, Controller(copy)
, mEmitStart(copy.mEmitStart)
, mEmitStop(copy.mEmitStop)
{
}
void ParticleSystemController::operator()(osgParticle::ParticleProcessor* node, osg::NodeVisitor* nv)
{
if (hasInput())
{
float time = getInputValue(nv);
node->getParticleSystem()->setFrozen(false);
node->setEnabled(time >= mEmitStart && time < mEmitStop);
}
else
node->getParticleSystem()->setFrozen(true);
traverse(node, nv);
}
PathController::PathController(const PathController& copy, const osg::CopyOp& copyop)
: SceneUtil::NodeCallback<PathController, NifOsg::MatrixTransform*>(copy, copyop)
, Controller(copy)
, mPath(copy.mPath)
, mPercent(copy.mPercent)
, mFlags(copy.mFlags)
{
}
PathController::PathController(const Nif::NiPathController* ctrl)
: mPath(ctrl->mPathData->mKeyList, osg::Vec3f())
, mPercent(ctrl->mPercentData->mKeyList, 1.f)
, mFlags(ctrl->mPathFlags)
{
}
float PathController::getPercent(float time) const
{
float percent = mPercent.interpKey(time);
if (percent < 0.f)
percent = std::fmod(percent, 1.f) + 1.f;
else if (percent > 1.f)
percent = std::fmod(percent, 1.f);
return percent;
}
void PathController::operator()(NifOsg::MatrixTransform* node, osg::NodeVisitor* nv)
{
if (mPath.empty() || mPercent.empty() || !hasInput())
{
traverse(node, nv);
return;
}
float time = getInputValue(nv);
float percent = getPercent(time);
node->setTranslation(mPath.interpKey(percent));
traverse(node, nv);
}
}
| 23,947
|
C++
|
.cpp
| 573
| 31.082024
| 119
| 0.595895
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,665
|
particle.cpp
|
OpenMW_openmw/components/nifosg/particle.cpp
|
#include "particle.hpp"
#include <limits>
#include <optional>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/ValueObject>
#include <components/debug/debuglog.hpp>
#include <components/misc/rng.hpp>
#include <components/nif/data.hpp>
#include <components/sceneutil/morphgeometry.hpp>
#include <components/sceneutil/riggeometry.hpp>
namespace
{
class FindFirstGeometry : public osg::NodeVisitor
{
public:
FindFirstGeometry()
: osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
, mGeometry(nullptr)
{
}
void apply(osg::Node& node) override
{
if (mGeometry)
return;
traverse(node);
}
void apply(osg::Drawable& drawable) override
{
if (auto morph = dynamic_cast<SceneUtil::MorphGeometry*>(&drawable))
{
mGeometry = morph->getSourceGeometry();
return;
}
else if (auto rig = dynamic_cast<SceneUtil::RigGeometry*>(&drawable))
{
mGeometry = rig->getSourceGeometry();
return;
}
traverse(drawable);
}
void apply(osg::Geometry& geometry) override { mGeometry = &geometry; }
osg::Geometry* mGeometry;
};
class LocalToWorldAccumulator : public osg::NodeVisitor
{
public:
LocalToWorldAccumulator(osg::Matrix& matrix)
: osg::NodeVisitor()
, mMatrix(matrix)
{
}
virtual void apply(osg::Transform& transform)
{
if (&transform != mLastAppliedTransform)
{
mLastAppliedTransform = &transform;
mLastMatrix = mMatrix;
}
transform.computeLocalToWorldMatrix(mMatrix, this);
}
void accumulate(const osg::NodePath& path)
{
if (path.empty())
return;
size_t i = path.size();
for (auto rit = path.rbegin(); rit != path.rend(); rit++, --i)
{
const osg::Camera* camera = (*rit)->asCamera();
if (camera
&& (camera->getReferenceFrame() != osg::Transform::RELATIVE_RF || camera->getParents().empty()))
break;
}
for (; i < path.size(); ++i)
path[i]->accept(*this);
}
osg::Matrix& mMatrix;
std::optional<osg::Matrix> mLastMatrix;
osg::Transform* mLastAppliedTransform = nullptr;
};
}
namespace NifOsg
{
ParticleSystem::ParticleSystem()
: osgParticle::ParticleSystem()
, mQuota(std::numeric_limits<int>::max())
{
mNormalArray = new osg::Vec3Array(1);
mNormalArray->setBinding(osg::Array::BIND_OVERALL);
(*mNormalArray.get())[0] = osg::Vec3(0.3, 0.3, 0.3);
}
ParticleSystem::ParticleSystem(const ParticleSystem& copy, const osg::CopyOp& copyop)
: osgParticle::ParticleSystem(copy, copyop)
, mQuota(copy.mQuota)
{
mNormalArray = new osg::Vec3Array(1);
mNormalArray->setBinding(osg::Array::BIND_OVERALL);
(*mNormalArray.get())[0] = osg::Vec3(0.3, 0.3, 0.3);
// For some reason the osgParticle constructor doesn't copy the particles
for (int i = 0; i < copy.numParticles() - copy.numDeadParticles(); ++i)
ParticleSystem::createParticle(copy.getParticle(i));
}
void ParticleSystem::setQuota(int quota)
{
mQuota = quota;
}
osgParticle::Particle* ParticleSystem::createParticle(const osgParticle::Particle* ptemplate)
{
if (numParticles() - numDeadParticles() < mQuota)
return osgParticle::ParticleSystem::createParticle(ptemplate);
return nullptr;
}
void ParticleSystem::drawImplementation(osg::RenderInfo& renderInfo) const
{
osg::State& state = *renderInfo.getState();
if (state.useVertexArrayObject(getUseVertexArrayObject()))
{
state.getCurrentVertexArrayState()->assignNormalArrayDispatcher();
state.getCurrentVertexArrayState()->setNormalArray(state, mNormalArray);
}
else
{
state.getAttributeDispatchers().activateNormalArray(mNormalArray);
}
osgParticle::ParticleSystem::drawImplementation(renderInfo);
}
void InverseWorldMatrix::operator()(osg::MatrixTransform* node, osg::NodeVisitor* nv)
{
osg::NodePath path = nv->getNodePath();
path.pop_back();
osg::Matrix mat = osg::computeLocalToWorld(path);
mat.orthoNormalize(mat); // don't undo the scale
mat.invert(mat);
node->setMatrix(mat);
traverse(node, nv);
}
ParticleShooter::ParticleShooter(float minSpeed, float maxSpeed, float horizontalDir, float horizontalAngle,
float verticalDir, float verticalAngle, float lifetime, float lifetimeRandom)
: mMinSpeed(minSpeed)
, mMaxSpeed(maxSpeed)
, mHorizontalDir(horizontalDir)
, mHorizontalAngle(horizontalAngle)
, mVerticalDir(verticalDir)
, mVerticalAngle(verticalAngle)
, mLifetime(lifetime)
, mLifetimeRandom(lifetimeRandom)
{
}
ParticleShooter::ParticleShooter()
: mMinSpeed(0.f)
, mMaxSpeed(0.f)
, mHorizontalDir(0.f)
, mHorizontalAngle(0.f)
, mVerticalDir(0.f)
, mVerticalAngle(0.f)
, mLifetime(0.f)
, mLifetimeRandom(0.f)
{
}
ParticleShooter::ParticleShooter(const ParticleShooter& copy, const osg::CopyOp& copyop)
: osgParticle::Shooter(copy, copyop)
{
mMinSpeed = copy.mMinSpeed;
mMaxSpeed = copy.mMaxSpeed;
mHorizontalDir = copy.mHorizontalDir;
mHorizontalAngle = copy.mHorizontalAngle;
mVerticalDir = copy.mVerticalDir;
mVerticalAngle = copy.mVerticalAngle;
mLifetime = copy.mLifetime;
mLifetimeRandom = copy.mLifetimeRandom;
}
void ParticleShooter::shoot(osgParticle::Particle* particle) const
{
float hdir = mHorizontalDir + mHorizontalAngle * (2.f * Misc::Rng::rollClosedProbability() - 1.f);
float vdir = mVerticalDir + mVerticalAngle * (2.f * Misc::Rng::rollClosedProbability() - 1.f);
osg::Vec3f dir
= (osg::Quat(vdir, osg::Vec3f(0, 1, 0)) * osg::Quat(hdir, osg::Vec3f(0, 0, 1))) * osg::Vec3f(0, 0, 1);
float vel = mMinSpeed + (mMaxSpeed - mMinSpeed) * Misc::Rng::rollClosedProbability();
particle->setVelocity(dir * vel);
// Not supposed to set this here, but there doesn't seem to be a better way of doing it
particle->setLifeTime(std::max(
std::numeric_limits<float>::epsilon(), mLifetime + mLifetimeRandom * Misc::Rng::rollClosedProbability()));
}
GrowFadeAffector::GrowFadeAffector(float growTime, float fadeTime)
: mGrowTime(growTime)
, mFadeTime(fadeTime)
, mCachedDefaultSize(0.f)
{
}
GrowFadeAffector::GrowFadeAffector()
: mGrowTime(0.f)
, mFadeTime(0.f)
, mCachedDefaultSize(0.f)
{
}
GrowFadeAffector::GrowFadeAffector(const GrowFadeAffector& copy, const osg::CopyOp& copyop)
: osgParticle::Operator(copy, copyop)
{
mGrowTime = copy.mGrowTime;
mFadeTime = copy.mFadeTime;
mCachedDefaultSize = copy.mCachedDefaultSize;
}
void GrowFadeAffector::beginOperate(osgParticle::Program* program)
{
mCachedDefaultSize = program->getParticleSystem()->getDefaultParticleTemplate().getSizeRange().minimum;
}
void GrowFadeAffector::operate(osgParticle::Particle* particle, double /* dt */)
{
float size = mCachedDefaultSize;
if (particle->getAge() < mGrowTime && mGrowTime != 0.f)
size *= particle->getAge() / mGrowTime;
if (particle->getLifeTime() - particle->getAge() < mFadeTime && mFadeTime != 0.f)
size *= (particle->getLifeTime() - particle->getAge()) / mFadeTime;
particle->setSizeRange(osgParticle::rangef(size, size));
}
ParticleColorAffector::ParticleColorAffector(const Nif::NiColorData* clrdata)
: mData(clrdata->mKeyMap, osg::Vec4f(1, 1, 1, 1))
{
}
ParticleColorAffector::ParticleColorAffector() {}
ParticleColorAffector::ParticleColorAffector(const ParticleColorAffector& copy, const osg::CopyOp& copyop)
: osgParticle::Operator(copy, copyop)
{
mData = copy.mData;
}
void ParticleColorAffector::operate(osgParticle::Particle* particle, double /* dt */)
{
assert(particle->getLifeTime() > 0);
float time = static_cast<float>(particle->getAge() / particle->getLifeTime());
osg::Vec4f color = mData.interpKey(time);
float alpha = color.a();
color.a() = 1.0f;
particle->setColorRange(osgParticle::rangev4(color, color));
particle->setAlphaRange(osgParticle::rangef(alpha, alpha));
}
GravityAffector::GravityAffector(const Nif::NiGravity* gravity)
: mForce(gravity->mForce)
, mType(gravity->mType)
, mPosition(gravity->mPosition)
, mDirection(gravity->mDirection)
, mDecay(gravity->mDecay)
{
}
GravityAffector::GravityAffector(const GravityAffector& copy, const osg::CopyOp& copyop)
: osgParticle::Operator(copy, copyop)
{
mForce = copy.mForce;
mType = copy.mType;
mPosition = copy.mPosition;
mDirection = copy.mDirection;
mDecay = copy.mDecay;
mCachedWorldPosition = copy.mCachedWorldPosition;
mCachedWorldDirection = copy.mCachedWorldDirection;
}
void GravityAffector::beginOperate(osgParticle::Program* program)
{
bool absolute = (program->getReferenceFrame() == osgParticle::ParticleProcessor::ABSOLUTE_RF);
// We don't need the position for Wind gravity, except if decay is being applied
if (mType == Nif::ForceType::Point || mDecay != 0.f)
mCachedWorldPosition = absolute ? program->transformLocalToWorld(mPosition) : mPosition;
mCachedWorldDirection = absolute ? program->rotateLocalToWorld(mDirection) : mDirection;
mCachedWorldDirection.normalize();
}
void GravityAffector::operate(osgParticle::Particle* particle, double dt)
{
const float magic = 1.6f;
switch (mType)
{
case Nif::ForceType::Wind:
{
float decayFactor = 1.f;
if (mDecay != 0.f)
{
osg::Plane gravityPlane(mCachedWorldDirection, mCachedWorldPosition);
float distance = std::abs(gravityPlane.distance(particle->getPosition()));
decayFactor = std::exp(-1.f * mDecay * distance);
}
particle->addVelocity(mCachedWorldDirection * mForce * dt * decayFactor * magic);
break;
}
case Nif::ForceType::Point:
{
osg::Vec3f diff = mCachedWorldPosition - particle->getPosition();
float decayFactor = 1.f;
if (mDecay != 0.f)
decayFactor = std::exp(-1.f * mDecay * diff.length());
diff.normalize();
particle->addVelocity(diff * mForce * dt * decayFactor * magic);
break;
}
}
}
ParticleBomb::ParticleBomb(const Nif::NiParticleBomb* bomb)
: mRange(bomb->mRange)
, mStrength(bomb->mStrength)
, mDecayType(bomb->mDecayType)
, mSymmetryType(bomb->mSymmetryType)
, mPosition(bomb->mPosition)
, mDirection(bomb->mDirection)
{
}
ParticleBomb::ParticleBomb(const ParticleBomb& copy, const osg::CopyOp& copyop)
: osgParticle::Operator(copy, copyop)
{
mRange = copy.mRange;
mStrength = copy.mStrength;
mDecayType = copy.mDecayType;
mSymmetryType = copy.mSymmetryType;
mCachedWorldPosition = copy.mCachedWorldPosition;
mCachedWorldDirection = copy.mCachedWorldDirection;
}
void ParticleBomb::beginOperate(osgParticle::Program* program)
{
bool absolute = (program->getReferenceFrame() == osgParticle::ParticleProcessor::ABSOLUTE_RF);
mCachedWorldPosition = absolute ? program->transformLocalToWorld(mPosition) : mPosition;
// We don't need the direction for Spherical bomb
if (mSymmetryType != Nif::SymmetryType::Spherical)
{
mCachedWorldDirection = absolute ? program->rotateLocalToWorld(mDirection) : mDirection;
mCachedWorldDirection.normalize();
}
}
void ParticleBomb::operate(osgParticle::Particle* particle, double dt)
{
float decay = 1.f;
osg::Vec3f explosionDir;
osg::Vec3f particleDir = particle->getPosition() - mCachedWorldPosition;
float distance = particleDir.length();
particleDir.normalize();
switch (mDecayType)
{
case Nif::DecayType::None:
break;
case Nif::DecayType::Linear:
decay = 1.f - distance / mRange;
break;
case Nif::DecayType::Exponential:
decay = std::exp(-distance / mRange);
break;
}
if (decay <= 0.f)
return;
switch (mSymmetryType)
{
case Nif::SymmetryType::Spherical:
explosionDir = particleDir;
break;
case Nif::SymmetryType::Cylindrical:
explosionDir = particleDir - mCachedWorldDirection * (mCachedWorldDirection * particleDir);
explosionDir.normalize();
break;
case Nif::SymmetryType::Planar:
explosionDir = mCachedWorldDirection;
if (explosionDir * particleDir < 0)
explosionDir = -explosionDir;
break;
}
particle->addVelocity(explosionDir * mStrength * decay * dt);
}
Emitter::Emitter()
: osgParticle::Emitter()
, mFlags(0)
, mGeometryEmitterTarget(std::nullopt)
{
}
Emitter::Emitter(const Emitter& copy, const osg::CopyOp& copyop)
: osgParticle::Emitter(copy, copyop)
, mTargets(copy.mTargets)
, mPlacer(copy.mPlacer)
, mShooter(copy.mShooter)
// need a deep copy because the remainder is stored in the object
, mCounter(static_cast<osgParticle::Counter*>(copy.mCounter->clone(osg::CopyOp::DEEP_COPY_ALL)))
, mFlags(copy.mFlags)
, mGeometryEmitterTarget(copy.mGeometryEmitterTarget)
, mCachedGeometryEmitter(copy.mCachedGeometryEmitter)
{
}
Emitter::Emitter(const std::vector<int>& targets)
: mTargets(targets)
, mFlags(0)
, mGeometryEmitterTarget(std::nullopt)
{
}
void Emitter::emitParticles(double dt)
{
int n = mCounter->numParticlesToCreate(dt);
if (n == 0)
return;
osg::Matrix worldToPs;
// maybe this could be optimized by halting at the lowest common ancestor of the particle and emitter nodes
osg::NodePathList partsysNodePaths = getParticleSystem()->getParentalNodePaths();
if (!partsysNodePaths.empty())
{
osg::Matrix psToWorld = osg::computeLocalToWorld(partsysNodePaths[0]);
worldToPs = osg::Matrix::inverse(psToWorld);
}
const osg::Matrix& ltw = getLocalToWorldMatrix();
osg::Matrix emitterToPs = ltw * worldToPs;
osg::ref_ptr<osg::Vec3Array> geometryVertices = nullptr;
const bool useGeometryEmitter = mFlags & Nif::NiParticleSystemController::BSPArrayController_AtVertex;
if (useGeometryEmitter || !mTargets.empty())
{
int recIndex;
if (useGeometryEmitter)
{
if (!mGeometryEmitterTarget.has_value())
return;
recIndex = mGeometryEmitterTarget.value();
}
else
{
int randomIndex = Misc::Rng::rollClosedProbability() * (mTargets.size() - 1);
recIndex = mTargets[randomIndex];
}
// we could use a map here for faster lookup
FindGroupByRecIndex visitor(recIndex);
getParent(0)->accept(visitor);
if (!visitor.mFound)
{
Log(Debug::Info) << "Can't find emitter node" << recIndex;
return;
}
if (useGeometryEmitter)
{
if (!mCachedGeometryEmitter.lock(geometryVertices))
{
FindFirstGeometry geometryVisitor;
visitor.mFound->accept(geometryVisitor);
if (geometryVisitor.mGeometry)
{
if (auto* vertices = dynamic_cast<osg::Vec3Array*>(geometryVisitor.mGeometry->getVertexArray()))
{
mCachedGeometryEmitter = osg::observer_ptr<osg::Vec3Array>(vertices);
geometryVertices = vertices;
}
}
}
}
osg::NodePath path = visitor.mFoundPath;
path.erase(path.begin());
if (!useGeometryEmitter && (mFlags & Nif::NiParticleSystemController::BSPArrayController_AtNode)
&& path.size())
{
osg::Matrix current;
LocalToWorldAccumulator accum(current);
accum.accumulate(path);
osg::Matrix parent = accum.mLastMatrix.value_or(current);
auto p1 = parent.getTrans();
auto p2 = current.getTrans();
current.setTrans((p2 - p1) * Misc::Rng::rollClosedProbability() + p1);
emitterToPs = current * emitterToPs;
}
else
{
emitterToPs = osg::computeLocalToWorld(path) * emitterToPs;
}
}
emitterToPs.orthoNormalize(emitterToPs);
if (useGeometryEmitter && (!geometryVertices.valid() || geometryVertices->empty()))
return;
for (int i = 0; i < n; ++i)
{
osgParticle::Particle* P = getParticleSystem()->createParticle(nullptr);
if (P)
{
if (useGeometryEmitter)
P->setPosition((*geometryVertices)[Misc::Rng::rollDice(geometryVertices->getNumElements())]);
else if (mPlacer)
mPlacer->place(P);
mShooter->shoot(P);
P->transformPositionVelocity(emitterToPs);
}
}
}
FindGroupByRecIndex::FindGroupByRecIndex(unsigned int recIndex)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mFound(nullptr)
, mRecIndex(recIndex)
{
}
void FindGroupByRecIndex::apply(osg::Node& node)
{
applyNode(node);
}
void FindGroupByRecIndex::apply(osg::MatrixTransform& node)
{
applyNode(node);
}
void FindGroupByRecIndex::apply(osg::Geometry& node)
{
applyNode(node);
}
void FindGroupByRecIndex::applyNode(osg::Node& searchNode)
{
unsigned int recIndex;
if (searchNode.getUserValue("recIndex", recIndex) && mRecIndex == recIndex)
{
osg::Group* group = searchNode.asGroup();
if (!group)
group = searchNode.getParent(0);
mFound = group;
mFoundPath = getNodePath();
return;
}
traverse(searchNode);
}
PlanarCollider::PlanarCollider(const Nif::NiPlanarCollider* collider)
: mBounceFactor(collider->mBounceFactor)
, mExtents(collider->mExtents)
, mPosition(collider->mPosition)
, mXVector(collider->mXVector)
, mYVector(collider->mYVector)
, mPlane(-collider->mPlaneNormal, collider->mPlaneDistance)
{
}
PlanarCollider::PlanarCollider(const PlanarCollider& copy, const osg::CopyOp& copyop)
: osgParticle::Operator(copy, copyop)
, mBounceFactor(copy.mBounceFactor)
, mExtents(copy.mExtents)
, mPosition(copy.mPosition)
, mPositionInParticleSpace(copy.mPositionInParticleSpace)
, mXVector(copy.mXVector)
, mXVectorInParticleSpace(copy.mXVectorInParticleSpace)
, mYVector(copy.mYVector)
, mYVectorInParticleSpace(copy.mYVectorInParticleSpace)
, mPlane(copy.mPlane)
, mPlaneInParticleSpace(copy.mPlaneInParticleSpace)
{
}
void PlanarCollider::beginOperate(osgParticle::Program* program)
{
mPositionInParticleSpace = mPosition;
mPlaneInParticleSpace = mPlane;
mXVectorInParticleSpace = mXVector;
mYVectorInParticleSpace = mYVector;
if (program->getReferenceFrame() == osgParticle::ParticleProcessor::ABSOLUTE_RF)
{
mPositionInParticleSpace = program->transformLocalToWorld(mPosition);
mPlaneInParticleSpace.transform(program->getLocalToWorldMatrix());
mXVectorInParticleSpace = program->rotateLocalToWorld(mXVector);
mYVectorInParticleSpace = program->rotateLocalToWorld(mYVector);
}
}
void PlanarCollider::operate(osgParticle::Particle* particle, double dt)
{
// Does the particle in question move towards the collider?
float velDotProduct = particle->getVelocity() * mPlaneInParticleSpace.getNormal();
if (velDotProduct <= 0)
return;
// Does it intersect the collider's plane?
osg::BoundingSphere bs(particle->getPosition(), 0.f);
if (mPlaneInParticleSpace.intersect(bs) != 1)
return;
// Is it inside the collider's bounds?
osg::Vec3f relativePos = particle->getPosition() - mPositionInParticleSpace;
float xDotProduct = relativePos * mXVectorInParticleSpace;
float yDotProduct = relativePos * mYVectorInParticleSpace;
if (-mExtents.x() * 0.5f > xDotProduct || mExtents.x() * 0.5f < xDotProduct)
return;
if (-mExtents.y() * 0.5f > yDotProduct || mExtents.y() * 0.5f < yDotProduct)
return;
// Deflect the particle
osg::Vec3 reflectedVelocity = particle->getVelocity() - mPlaneInParticleSpace.getNormal() * (2 * velDotProduct);
reflectedVelocity *= mBounceFactor;
particle->setVelocity(reflectedVelocity);
}
SphericalCollider::SphericalCollider(const Nif::NiSphericalCollider* collider)
: mBounceFactor(collider->mBounceFactor)
, mSphere(collider->mCenter, collider->mRadius)
{
}
SphericalCollider::SphericalCollider()
: mBounceFactor(1.0f)
{
}
SphericalCollider::SphericalCollider(const SphericalCollider& copy, const osg::CopyOp& copyop)
: osgParticle::Operator(copy, copyop)
, mBounceFactor(copy.mBounceFactor)
, mSphere(copy.mSphere)
, mSphereInParticleSpace(copy.mSphereInParticleSpace)
{
}
void SphericalCollider::beginOperate(osgParticle::Program* program)
{
mSphereInParticleSpace = mSphere;
if (program->getReferenceFrame() == osgParticle::ParticleProcessor::ABSOLUTE_RF)
mSphereInParticleSpace.center() = program->transformLocalToWorld(mSphereInParticleSpace.center());
}
void SphericalCollider::operate(osgParticle::Particle* particle, double dt)
{
osg::Vec3f cent
= (particle->getPosition() - mSphereInParticleSpace.center()); // vector from sphere center to particle
bool insideSphere = cent.length2() <= mSphereInParticleSpace.radius2();
if (insideSphere
|| (cent * particle->getVelocity()
< 0.0f)) // if outside, make sure the particle is flying towards the sphere
{
// Collision test (finding point of contact) is performed by solving a quadratic equation:
// ||vec(cent) + vec(vel)*k|| = R /^2
// k^2 + 2*k*(vec(cent)*vec(vel))/||vec(vel)||^2 + (||vec(cent)||^2 - R^2)/||vec(vel)||^2 = 0
float b = -(cent * particle->getVelocity()) / particle->getVelocity().length2();
osg::Vec3f u = cent + particle->getVelocity() * b;
if (insideSphere || (u.length2() < mSphereInParticleSpace.radius2()))
{
float d = (mSphereInParticleSpace.radius2() - u.length2()) / particle->getVelocity().length2();
float k = insideSphere ? (std::sqrt(d) + b) : (b - std::sqrt(d));
if (k < dt)
{
// collision detected; reflect off the tangent plane
osg::Vec3f contact = particle->getPosition() + particle->getVelocity() * k;
osg::Vec3 normal = (contact - mSphereInParticleSpace.center());
normal.normalize();
float dotproduct = particle->getVelocity() * normal;
osg::Vec3 reflectedVelocity = particle->getVelocity() - normal * (2 * dotproduct);
reflectedVelocity *= mBounceFactor;
particle->setVelocity(reflectedVelocity);
}
}
}
}
}
| 25,539
|
C++
|
.cpp
| 621
| 30.953301
| 120
| 0.61017
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,666
|
matrixtransform.cpp
|
OpenMW_openmw/components/nifosg/matrixtransform.cpp
|
#include "matrixtransform.hpp"
namespace NifOsg
{
MatrixTransform::MatrixTransform(const Nif::NiTransform& transform)
: osg::MatrixTransform(transform.toMatrix())
, mScale(transform.mScale)
, mRotationScale(transform.mRotation)
{
}
MatrixTransform::MatrixTransform(const MatrixTransform& copy, const osg::CopyOp& copyop)
: osg::MatrixTransform(copy, copyop)
, mScale(copy.mScale)
, mRotationScale(copy.mRotationScale)
{
}
void MatrixTransform::setScale(float scale)
{
// Update the decomposed scale.
mScale = scale;
// Rescale the node using the known components.
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
_matrix(i, j) = mRotationScale.mValues[j][i] * mScale; // NB: column/row major difference
_inverseDirty = true;
dirtyBound();
}
void MatrixTransform::setRotation(const osg::Quat& rotation)
{
// First override the rotation ignoring the scale.
_matrix.setRotate(rotation);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
// Update the current decomposed rotation and restore the known scale.
mRotationScale.mValues[j][i] = _matrix(i, j); // NB: column/row major difference
_matrix(i, j) *= mScale;
}
}
_inverseDirty = true;
dirtyBound();
}
void MatrixTransform::setRotation(const Nif::Matrix3& rotation)
{
// Update the decomposed rotation.
mRotationScale = rotation;
// Reorient the node using the known components.
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
_matrix(i, j) = mRotationScale.mValues[j][i] * mScale; // NB: column/row major difference
_inverseDirty = true;
dirtyBound();
}
void MatrixTransform::setTranslation(const osg::Vec3f& translation)
{
// The translation is independent from the rotation and scale so we can apply it directly.
_matrix.setTrans(translation);
_inverseDirty = true;
dirtyBound();
}
}
| 2,220
|
C++
|
.cpp
| 61
| 27.901639
| 105
| 0.594595
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,667
|
fog.cpp
|
OpenMW_openmw/components/nifosg/fog.cpp
|
#include "fog.hpp"
#include <osg/Matrix>
#include <osg/State>
namespace NifOsg
{
Fog::Fog()
: osg::Fog()
{
}
Fog::Fog(const Fog& copy, const osg::CopyOp& copyop)
: osg::Fog(copy, copyop)
, mDepth(copy.mDepth)
{
}
void Fog::apply(osg::State& state) const
{
osg::Fog::apply(state);
#ifdef OSG_GL_FIXED_FUNCTION_AVAILABLE
float fov, aspect, near, far;
state.getProjectionMatrix().getPerspective(fov, aspect, near, far);
glFogf(GL_FOG_START, near * mDepth + far * (1.f - mDepth));
glFogf(GL_FOG_END, far);
#endif
}
}
| 619
|
C++
|
.cpp
| 25
| 19.52
| 75
| 0.60034
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,668
|
nifloader.cpp
|
OpenMW_openmw/components/nifosg/nifloader.cpp
|
#include "nifloader.hpp"
#include <mutex>
#include <string_view>
#include <osg/Array>
#include <osg/Geometry>
#include <osg/LOD>
#include <osg/Matrixf>
#include <osg/Sequence>
#include <osg/Switch>
#include <osg/TexGen>
#include <osg/TexMat>
#include <osg/ValueObject>
// resource
#include <components/debug/debuglog.hpp>
#include <components/misc/constants.hpp>
#include <components/misc/osguservalues.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/nif/parent.hpp>
#include <components/resource/bgsmfilemanager.hpp>
#include <components/resource/imagemanager.hpp>
// particle
#include <osgParticle/BoxPlacer>
#include <osgParticle/ConstantRateCounter>
#include <osgParticle/ModularProgram>
#include <osgParticle/ParticleSystem>
#include <osgParticle/ParticleSystemUpdater>
#include <osg/AlphaFunc>
#include <osg/BlendFunc>
#include <osg/Depth>
#include <osg/FrontFace>
#include <osg/Material>
#include <osg/PolygonMode>
#include <osg/PolygonOffset>
#include <osg/Stencil>
#include <osg/TexEnv>
#include <osg/TexEnvCombine>
#include <osg/Texture2D>
#include <components/bgsm/file.hpp>
#include <components/nif/effect.hpp>
#include <components/nif/exception.hpp>
#include <components/nif/extra.hpp>
#include <components/nif/niffile.hpp>
#include <components/nif/node.hpp>
#include <components/nif/particle.hpp>
#include <components/nif/property.hpp>
#include <components/nif/texture.hpp>
#include <components/sceneutil/depth.hpp>
#include <components/sceneutil/extradata.hpp>
#include <components/sceneutil/morphgeometry.hpp>
#include <components/sceneutil/riggeometry.hpp>
#include <components/sceneutil/skeleton.hpp>
#include <components/sceneutil/texturetype.hpp>
#include "fog.hpp"
#include "matrixtransform.hpp"
#include "particle.hpp"
namespace
{
struct DisableOptimizer : osg::NodeVisitor
{
DisableOptimizer(osg::NodeVisitor::TraversalMode mode = TRAVERSE_ALL_CHILDREN)
: osg::NodeVisitor(mode)
{
}
void apply(osg::Node& node) override
{
node.setDataVariance(osg::Object::DYNAMIC);
traverse(node);
}
void apply(osg::Drawable& node) override { traverse(node); }
};
void getAllNiNodes(const Nif::NiAVObject* node, std::vector<int>& outIndices)
{
if (const Nif::NiNode* ninode = dynamic_cast<const Nif::NiNode*>(node))
{
outIndices.push_back(ninode->recIndex);
for (const auto& child : ninode->mChildren)
if (!child.empty())
getAllNiNodes(child.getPtr(), outIndices);
}
}
bool isTypeNiGeometry(int type)
{
switch (type)
{
case Nif::RC_NiTriShape:
case Nif::RC_NiTriStrips:
case Nif::RC_NiLines:
case Nif::RC_BSLODTriShape:
case Nif::RC_BSSegmentedTriShape:
return true;
}
return false;
}
bool isTypeBSGeometry(int type)
{
switch (type)
{
case Nif::RC_BSTriShape:
case Nif::RC_BSDynamicTriShape:
case Nif::RC_BSMeshLODTriShape:
case Nif::RC_BSSubIndexTriShape:
return true;
}
return false;
}
// Collect all properties affecting the given drawable that should be handled on drawable basis rather than on the
// node hierarchy above it.
void collectDrawableProperties(
const Nif::NiAVObject* nifNode, const Nif::Parent* parent, std::vector<const Nif::NiProperty*>& out)
{
if (parent != nullptr)
collectDrawableProperties(&parent->mNiNode, parent->mParent, out);
for (const auto& property : nifNode->mProperties)
{
if (!property.empty())
{
switch (property->recType)
{
case Nif::RC_NiMaterialProperty:
case Nif::RC_NiVertexColorProperty:
case Nif::RC_NiSpecularProperty:
case Nif::RC_NiAlphaProperty:
out.push_back(property.getPtr());
break;
default:
break;
}
}
}
}
// NodeCallback used to have a node always oriented towards the camera. The node can have translation and scale
// set just like a regular MatrixTransform, but the rotation set will be overridden in order to face the camera.
class BillboardCallback : public SceneUtil::NodeCallback<BillboardCallback, osg::Node*, osgUtil::CullVisitor*>
{
public:
BillboardCallback() {}
BillboardCallback(const BillboardCallback& copy, const osg::CopyOp& copyop)
: SceneUtil::NodeCallback<BillboardCallback, osg::Node*, osgUtil::CullVisitor*>(copy, copyop)
{
}
META_Object(NifOsg, BillboardCallback)
void operator()(osg::Node* node, osgUtil::CullVisitor* cv)
{
osg::Matrix modelView = *cv->getModelViewMatrix();
// attempt to preserve scale
float mag[3];
for (int i = 0; i < 3; ++i)
{
mag[i] = std::sqrt(modelView(0, i) * modelView(0, i) + modelView(1, i) * modelView(1, i)
+ modelView(2, i) * modelView(2, i));
}
modelView.setRotate(osg::Quat());
modelView(0, 0) = mag[0];
modelView(1, 1) = mag[1];
modelView(2, 2) = mag[2];
cv->pushModelViewMatrix(new osg::RefMatrix(modelView), osg::Transform::RELATIVE_RF);
traverse(node, cv);
cv->popModelViewMatrix();
}
};
void extractTextKeys(const Nif::NiTextKeyExtraData* tk, SceneUtil::TextKeyMap& textkeys)
{
for (const Nif::NiTextKeyExtraData::TextKey& key : tk->mList)
{
std::vector<std::string> results;
Misc::StringUtils::split(key.mText, results, "\r\n");
for (std::string& result : results)
{
Misc::StringUtils::trim(result);
Misc::StringUtils::lowerCaseInPlace(result);
if (!result.empty())
textkeys.emplace(key.mTime, std::move(result));
}
}
}
}
namespace NifOsg
{
bool Loader::sShowMarkers = false;
void Loader::setShowMarkers(bool show)
{
sShowMarkers = show;
}
bool Loader::getShowMarkers()
{
return sShowMarkers;
}
unsigned int Loader::sHiddenNodeMask = 0;
void Loader::setHiddenNodeMask(unsigned int mask)
{
sHiddenNodeMask = mask;
}
unsigned int Loader::getHiddenNodeMask()
{
return sHiddenNodeMask;
}
unsigned int Loader::sIntersectionDisabledNodeMask = ~0u;
void Loader::setIntersectionDisabledNodeMask(unsigned int mask)
{
sIntersectionDisabledNodeMask = mask;
}
unsigned int Loader::getIntersectionDisabledNodeMask()
{
return sIntersectionDisabledNodeMask;
}
class LoaderImpl
{
public:
/// @param filename used for warning messages.
LoaderImpl(const std::filesystem::path& filename, unsigned int ver, unsigned int userver, unsigned int bethver)
: mFilename(filename)
, mVersion(ver)
, mUserVersion(userver)
, mBethVersion(bethver)
{
}
std::filesystem::path mFilename;
unsigned int mVersion, mUserVersion, mBethVersion;
Resource::BgsmFileManager* mMaterialManager{ nullptr };
Resource::ImageManager* mImageManager{ nullptr };
size_t mFirstRootTextureIndex{ ~0u };
bool mFoundFirstRootTexturingProperty = false;
bool mHasNightDayLabel = false;
bool mHasHerbalismLabel = false;
bool mHasStencilProperty = false;
const Nif::NiSortAdjustNode* mPushedSorter = nullptr;
const Nif::NiSortAdjustNode* mLastAppliedNoInheritSorter = nullptr;
// This is used to queue emitters that weren't attached to their node yet.
std::vector<std::pair<size_t, osg::ref_ptr<Emitter>>> mEmitterQueue;
void loadKf(Nif::FileView nif, SceneUtil::KeyframeHolder& target) const
{
const Nif::NiSequenceStreamHelper* seq = nullptr;
const size_t numRoots = nif.numRoots();
for (size_t i = 0; i < numRoots; ++i)
{
const Nif::Record* r = nif.getRoot(i);
if (r && r->recType == Nif::RC_NiSequenceStreamHelper)
{
seq = static_cast<const Nif::NiSequenceStreamHelper*>(r);
break;
}
}
if (!seq)
{
Log(Debug::Warning) << "NIFFile Warning: Found no NiSequenceStreamHelper root record. File: "
<< nif.getFilename();
return;
}
Nif::ExtraList extraList = seq->getExtraList();
if (extraList.empty())
{
Log(Debug::Warning) << "NIFFile Warning: NiSequenceStreamHelper has no text keys. File: "
<< nif.getFilename();
return;
}
if (extraList[0]->recType != Nif::RC_NiTextKeyExtraData)
{
Log(Debug::Warning) << "NIFFile Warning: First extra data was not a NiTextKeyExtraData, but a "
<< std::string_view(extraList[0]->recName) << ". File: " << nif.getFilename();
return;
}
auto textKeyExtraData = static_cast<const Nif::NiTextKeyExtraData*>(extraList[0].getPtr());
extractTextKeys(textKeyExtraData, target.mTextKeys);
Nif::NiTimeControllerPtr ctrl = seq->mController;
for (size_t i = 1; i < extraList.size() && !ctrl.empty(); i++, (ctrl = ctrl->mNext))
{
Nif::ExtraPtr extra = extraList[i];
if (extra->recType != Nif::RC_NiStringExtraData || ctrl->recType != Nif::RC_NiKeyframeController)
{
Log(Debug::Warning) << "NIFFile Warning: Unexpected extra data " << extra->recName
<< " with controller " << ctrl->recName << ". File: " << nif.getFilename();
continue;
}
// Vanilla seems to ignore the "active" flag for NiKeyframeController,
// so we don't want to skip inactive controllers here.
const Nif::NiStringExtraData* strdata = static_cast<const Nif::NiStringExtraData*>(extra.getPtr());
const Nif::NiKeyframeController* key = static_cast<const Nif::NiKeyframeController*>(ctrl.getPtr());
if (key->mData.empty() && key->mInterpolator.empty())
continue;
if (!key->mInterpolator.empty() && key->mInterpolator->recType != Nif::RC_NiTransformInterpolator)
{
Log(Debug::Error) << "Unsupported interpolator type for NiKeyframeController " << key->recIndex
<< " in " << mFilename;
continue;
}
osg::ref_ptr<SceneUtil::KeyframeController> callback = new NifOsg::KeyframeController(key);
setupController(key, callback, /*animflags*/ 0);
if (!target.mKeyframeControllers.emplace(strdata->mData, callback).second)
Log(Debug::Verbose) << "Controller " << strdata->mData << " present more than once in "
<< nif.getFilename() << ", ignoring later version";
}
}
struct HandleNodeArgs
{
unsigned int mNifVersion;
SceneUtil::TextKeyMap* mTextKeys;
std::vector<unsigned int> mBoundTextures = {};
int mAnimFlags = 0;
bool mSkipMeshes = false;
bool mHasMarkers = false;
bool mHasAnimatedParents = false;
osg::Node* mRootNode = nullptr;
};
osg::ref_ptr<osg::Node> load(Nif::FileView nif)
{
const size_t numRoots = nif.numRoots();
std::vector<const Nif::NiAVObject*> roots;
for (size_t i = 0; i < numRoots; ++i)
{
const Nif::Record* r = nif.getRoot(i);
if (!r)
continue;
const Nif::NiAVObject* nifNode = dynamic_cast<const Nif::NiAVObject*>(r);
if (nifNode)
roots.emplace_back(nifNode);
}
if (roots.empty())
throw Nif::Exception("Found no root nodes", nif.getFilename());
osg::ref_ptr<SceneUtil::TextKeyMapHolder> textkeys(new SceneUtil::TextKeyMapHolder);
osg::ref_ptr<osg::Group> created(new osg::Group);
created->setDataVariance(osg::Object::STATIC);
for (const Nif::NiAVObject* root : roots)
{
auto node = handleNode(
root, nullptr, nullptr, { .mNifVersion = nif.getVersion(), .mTextKeys = &textkeys->mTextKeys });
created->addChild(node);
}
if (mHasNightDayLabel)
created->getOrCreateUserDataContainer()->addDescription(Constants::NightDayLabel);
if (mHasHerbalismLabel)
created->getOrCreateUserDataContainer()->addDescription(Constants::HerbalismLabel);
// Attach particle emitters to their nodes which should all be loaded by now.
handleQueuedParticleEmitters(created, nif);
if (nif.getUseSkinning())
{
osg::ref_ptr<SceneUtil::Skeleton> skel = new SceneUtil::Skeleton;
skel->setStateSet(created->getStateSet());
skel->setName(created->getName());
for (unsigned int i = 0; i < created->getNumChildren(); ++i)
skel->addChild(created->getChild(i));
created->removeChildren(0, created->getNumChildren());
created = skel;
}
if (!textkeys->mTextKeys.empty())
created->getOrCreateUserDataContainer()->addUserObject(textkeys);
created->setUserValue(Misc::OsgUserValues::sFileHash, nif.getHash());
return created;
}
void applyNodeProperties(const Nif::NiAVObject* nifNode, osg::Node* applyTo,
SceneUtil::CompositeStateSetUpdater* composite, std::vector<unsigned int>& boundTextures, int animflags)
{
bool hasStencilProperty = false;
for (const auto& property : nifNode->mProperties)
{
if (property.empty())
continue;
if (property.getPtr()->recType == Nif::RC_NiStencilProperty)
{
const Nif::NiStencilProperty* stencilprop
= static_cast<const Nif::NiStencilProperty*>(property.getPtr());
if (stencilprop->mEnabled)
{
hasStencilProperty = true;
break;
}
}
}
for (const auto& property : nifNode->mProperties)
{
if (!property.empty())
{
// Get the lowest numbered recIndex of the NiTexturingProperty root node.
// This is what is overridden when a spell effect "particle texture" is used.
if (nifNode->mParents.empty() && !mFoundFirstRootTexturingProperty
&& property.getPtr()->recType == Nif::RC_NiTexturingProperty)
{
mFirstRootTextureIndex = property.getPtr()->recIndex;
mFoundFirstRootTexturingProperty = true;
}
else if (property.getPtr()->recType == Nif::RC_NiTexturingProperty)
{
if (property.getPtr()->recIndex == mFirstRootTextureIndex)
applyTo->setUserValue("overrideFx", 1);
}
handleProperty(property.getPtr(), applyTo, composite, boundTextures, animflags, hasStencilProperty);
}
}
// NiAlphaProperty is handled as a drawable property
Nif::BSShaderPropertyPtr shaderprop = nullptr;
if (isTypeNiGeometry(nifNode->recType))
shaderprop = static_cast<const Nif::NiGeometry*>(nifNode)->mShaderProperty;
else if (isTypeBSGeometry(nifNode->recType))
shaderprop = static_cast<const Nif::BSTriShape*>(nifNode)->mShaderProperty;
if (!shaderprop.empty())
handleProperty(shaderprop.getPtr(), applyTo, composite, boundTextures, animflags, hasStencilProperty);
}
static void setupController(const Nif::NiTimeController* ctrl, SceneUtil::Controller* toSetup, int animflags)
{
bool autoPlay = animflags & Nif::NiNode::AnimFlag_AutoPlay;
if (autoPlay)
toSetup->setSource(std::make_shared<SceneUtil::FrameTimeSource>());
toSetup->setFunction(std::make_shared<ControllerFunction>(ctrl));
}
static osg::ref_ptr<osg::LOD> handleLodNode(const Nif::NiLODNode* niLodNode)
{
osg::ref_ptr<osg::LOD> lod(new osg::LOD);
lod->setName(niLodNode->mName);
lod->setCenterMode(osg::LOD::USER_DEFINED_CENTER);
lod->setCenter(niLodNode->mLODCenter);
for (unsigned int i = 0; i < niLodNode->mLODLevels.size(); ++i)
{
const Nif::NiLODNode::LODRange& range = niLodNode->mLODLevels[i];
lod->setRange(i, range.mMinRange, range.mMaxRange);
}
lod->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
return lod;
}
static osg::ref_ptr<osg::Switch> handleSwitchNode(const Nif::NiSwitchNode* niSwitchNode)
{
osg::ref_ptr<osg::Switch> switchNode(new osg::Switch);
switchNode->setName(niSwitchNode->mName);
switchNode->setNewChildDefaultValue(false);
switchNode->setSingleChildOn(niSwitchNode->mInitialIndex);
return switchNode;
}
static osg::ref_ptr<osg::Sequence> prepareSequenceNode(const Nif::NiAVObject* nifNode)
{
const Nif::NiFltAnimationNode* niFltAnimationNode = static_cast<const Nif::NiFltAnimationNode*>(nifNode);
osg::ref_ptr<osg::Sequence> sequenceNode(new osg::Sequence);
sequenceNode->setName(niFltAnimationNode->mName);
if (!niFltAnimationNode->mChildren.empty())
{
if (niFltAnimationNode->swing())
sequenceNode->setDefaultTime(
niFltAnimationNode->mDuration / (niFltAnimationNode->mChildren.size() * 2));
else
sequenceNode->setDefaultTime(niFltAnimationNode->mDuration / niFltAnimationNode->mChildren.size());
}
return sequenceNode;
}
static void activateSequenceNode(osg::Group* osgNode, const Nif::NiAVObject* nifNode)
{
const Nif::NiFltAnimationNode* niFltAnimationNode = static_cast<const Nif::NiFltAnimationNode*>(nifNode);
osg::Sequence* sequenceNode = static_cast<osg::Sequence*>(osgNode);
if (niFltAnimationNode->swing())
sequenceNode->setInterval(osg::Sequence::SWING, 0, -1);
else
sequenceNode->setInterval(osg::Sequence::LOOP, 0, -1);
sequenceNode->setDuration(1.0f, -1);
sequenceNode->setMode(osg::Sequence::START);
}
osg::ref_ptr<osg::Image> handleSourceTexture(const Nif::NiSourceTexture* st) const
{
if (st)
{
if (st->mExternal)
return getTextureImage(st->mFile);
if (!st->mData.empty())
return handleInternalTexture(st->mData.getPtr());
}
return nullptr;
}
bool handleEffect(const Nif::NiAVObject* nifNode, osg::StateSet* stateset) const
{
if (nifNode->recType != Nif::RC_NiTextureEffect)
{
Log(Debug::Info) << "Unhandled effect " << nifNode->recName << " in " << mFilename;
return false;
}
const Nif::NiTextureEffect* textureEffect = static_cast<const Nif::NiTextureEffect*>(nifNode);
if (!textureEffect->mSwitchState)
return false;
if (textureEffect->mTextureType != Nif::NiTextureEffect::TextureType::EnvironmentMap)
{
Log(Debug::Info) << "Unhandled NiTextureEffect type "
<< static_cast<uint32_t>(textureEffect->mTextureType) << " in " << mFilename;
return false;
}
if (textureEffect->mTexture.empty())
{
Log(Debug::Info) << "NiTextureEffect missing source texture in " << mFilename;
return false;
}
osg::ref_ptr<osg::TexGen> texGen(new osg::TexGen);
switch (textureEffect->mCoordGenType)
{
case Nif::NiTextureEffect::CoordGenType::WorldParallel:
texGen->setMode(osg::TexGen::OBJECT_LINEAR);
break;
case Nif::NiTextureEffect::CoordGenType::WorldPerspective:
texGen->setMode(osg::TexGen::EYE_LINEAR);
break;
case Nif::NiTextureEffect::CoordGenType::SphereMap:
texGen->setMode(osg::TexGen::SPHERE_MAP);
break;
default:
Log(Debug::Info) << "Unhandled NiTextureEffect CoordGenType "
<< static_cast<uint32_t>(textureEffect->mCoordGenType) << " in " << mFilename;
return false;
}
const unsigned int uvSet = 0;
const unsigned int texUnit = 3; // FIXME
std::vector<unsigned int> boundTextures;
boundTextures.resize(3); // Dummy vector for attachNiSourceTexture
attachNiSourceTexture("envMap", textureEffect->mTexture.getPtr(), textureEffect->wrapS(),
textureEffect->wrapT(), uvSet, stateset, boundTextures);
stateset->setTextureAttributeAndModes(texUnit, texGen, osg::StateAttribute::ON);
stateset->setTextureAttributeAndModes(texUnit, createEmissiveTexEnv(), osg::StateAttribute::ON);
stateset->addUniform(new osg::Uniform("envMapColor", osg::Vec4f(1, 1, 1, 1)));
return true;
}
// Get a default dataVariance for this node to be used as a hint by optimization (post)routines
static osg::ref_ptr<osg::Group> createNode(const Nif::NiAVObject* nifNode)
{
osg::ref_ptr<osg::Group> node;
osg::Object::DataVariance dataVariance = osg::Object::UNSPECIFIED;
switch (nifNode->recType)
{
case Nif::RC_NiBillboardNode:
dataVariance = osg::Object::DYNAMIC;
break;
default:
// The Root node can be created as a Group if no transformation is required.
// This takes advantage of the fact root nodes can't have additional controllers
// loaded from an external .kf file (original engine just throws "can't find node" errors if you
// try).
if (nifNode->mParents.empty() && nifNode->mController.empty() && nifNode->mTransform.isIdentity())
node = new osg::Group;
dataVariance = nifNode->mIsBone ? osg::Object::DYNAMIC : osg::Object::STATIC;
break;
}
if (!node)
node = new NifOsg::MatrixTransform(nifNode->mTransform);
node->setDataVariance(dataVariance);
return node;
}
osg::ref_ptr<osg::Node> handleNode(
const Nif::NiAVObject* nifNode, const Nif::Parent* parent, osg::Group* parentNode, HandleNodeArgs args)
{
if (args.mRootNode && Misc::StringUtils::ciEqual(nifNode->mName, "Bounding Box"))
return nullptr;
osg::ref_ptr<osg::Group> node = createNode(nifNode);
if (nifNode->recType == Nif::RC_NiBillboardNode)
{
node->addCullCallback(new BillboardCallback);
}
node->setName(nifNode->mName);
if (parentNode)
parentNode->addChild(node);
if (!args.mRootNode)
args.mRootNode = node;
// The original NIF record index is used for a variety of features:
// - finding the correct emitter node for a particle system
// - establishing connections to the animated collision shapes, which are handled in a separate loader
// - finding a random child NiNode in NiBspArrayController
node->setUserValue("recIndex", nifNode->recIndex);
for (const auto& e : nifNode->getExtraList())
{
if (e->recType == Nif::RC_NiTextKeyExtraData && args.mTextKeys)
{
const Nif::NiTextKeyExtraData* tk = static_cast<const Nif::NiTextKeyExtraData*>(e.getPtr());
extractTextKeys(tk, *args.mTextKeys);
}
else if (e->recType == Nif::RC_NiStringExtraData)
{
const Nif::NiStringExtraData* sd = static_cast<const Nif::NiStringExtraData*>(e.getPtr());
constexpr std::string_view extraDataIdentifer = "omw:data";
// String markers may contain important information
// affecting the entire subtree of this obj
if (sd->mData == "MRK")
{
// Marker objects. These meshes are only visible in the editor.
if (!Loader::getShowMarkers() && args.mRootNode == node)
args.mHasMarkers = true;
}
else if (sd->mData == "BONE")
{
node->getOrCreateUserDataContainer()->addDescription("CustomBone");
}
else if (sd->mData.rfind(extraDataIdentifer, 0) == 0)
{
node->setUserValue(
Misc::OsgUserValues::sExtraData, sd->mData.substr(extraDataIdentifer.length()));
}
}
else if (e->recType == Nif::RC_BSXFlags)
{
if (args.mRootNode != node)
continue;
auto bsxFlags = static_cast<const Nif::NiIntegerExtraData*>(e.getPtr());
// Marker objects.
if (!Loader::getShowMarkers() && (bsxFlags->mData & 32))
args.mHasMarkers = true;
}
}
if (nifNode->recType == Nif::RC_NiBSAnimationNode || nifNode->recType == Nif::RC_NiBSParticleNode)
args.mAnimFlags = nifNode->mFlags;
if (nifNode->recType == Nif::RC_NiSortAdjustNode)
{
auto sortNode = static_cast<const Nif::NiSortAdjustNode*>(nifNode);
if (sortNode->mSubSorter.empty())
{
Log(Debug::Warning) << "Empty accumulator found in '" << nifNode->recName << "' node "
<< nifNode->recIndex;
}
else
{
if (mPushedSorter && !mPushedSorter->mSubSorter.empty()
&& mPushedSorter->mMode != Nif::NiSortAdjustNode::SortingMode::Inherit)
mLastAppliedNoInheritSorter = mPushedSorter;
mPushedSorter = sortNode;
}
}
// Hide collision shapes, but don't skip the subgraph
// We still need to animate the hidden bones so the physics system can access them
if (nifNode->recType == Nif::RC_RootCollisionNode)
{
args.mSkipMeshes = true;
node->setNodeMask(Loader::getHiddenNodeMask());
}
// We can skip creating meshes for hidden nodes if they don't have a VisController that
// might make them visible later
if (nifNode->isHidden())
{
bool hasVisController = false;
for (Nif::NiTimeControllerPtr ctrl = nifNode->mController; !ctrl.empty(); ctrl = ctrl->mNext)
{
hasVisController |= (ctrl->recType == Nif::RC_NiVisController);
if (hasVisController)
break;
}
if (!hasVisController)
args.mSkipMeshes = true; // skip child meshes, but still create the child node hierarchy for
// animating collision shapes
node->setNodeMask(Loader::getHiddenNodeMask());
}
if (nifNode->recType == Nif::RC_NiCollisionSwitch && !nifNode->collisionActive())
{
node->setNodeMask(Loader::getIntersectionDisabledNodeMask());
// Don't let the optimizer mess with this node
node->setDataVariance(osg::Object::DYNAMIC);
}
osg::ref_ptr<SceneUtil::CompositeStateSetUpdater> composite = new SceneUtil::CompositeStateSetUpdater;
applyNodeProperties(nifNode, node, composite, args.mBoundTextures, args.mAnimFlags);
const bool isNiGeometry = isTypeNiGeometry(nifNode->recType);
const bool isBSGeometry = isTypeBSGeometry(nifNode->recType);
const bool isGeometry = isNiGeometry || isBSGeometry;
if (isGeometry && !args.mSkipMeshes)
{
bool skip = false;
if (args.mNifVersion <= Nif::NIFFile::NIFVersion::VER_MW)
{
skip = (args.mHasMarkers && Misc::StringUtils::ciStartsWith(nifNode->mName, "tri editormarker"))
|| Misc::StringUtils::ciStartsWith(nifNode->mName, "shadow")
|| Misc::StringUtils::ciStartsWith(nifNode->mName, "tri shadow");
}
else
{
if (args.mHasMarkers)
skip = Misc::StringUtils::ciStartsWith(nifNode->mName, "EditorMarker")
|| Misc::StringUtils::ciStartsWith(nifNode->mName, "VisibilityEditorMarker");
}
if (!skip)
{
if (isNiGeometry)
handleNiGeometry(nifNode, parent, node, composite, args.mBoundTextures, args.mAnimFlags);
else // isBSGeometry
handleBSGeometry(nifNode, parent, node, composite, args.mBoundTextures, args.mAnimFlags);
if (!nifNode->mController.empty())
handleMeshControllers(nifNode, node, composite, args.mBoundTextures, args.mAnimFlags);
}
}
if (nifNode->recType == Nif::RC_NiParticles)
handleParticleSystem(nifNode, parent, node, composite, args.mAnimFlags);
if (composite->getNumControllers() > 0)
{
osg::Callback* cb = composite;
if (composite->getNumControllers() == 1)
cb = composite->getController(0);
if (args.mAnimFlags & Nif::NiNode::AnimFlag_AutoPlay)
node->addCullCallback(cb);
else
node->addUpdateCallback(
cb); // have to remain as UpdateCallback so AssignControllerSourcesVisitor can find it.
}
bool isAnimated = false;
handleNodeControllers(nifNode, node, args.mAnimFlags, isAnimated);
args.mHasAnimatedParents |= isAnimated;
// Make sure empty nodes and animated shapes are not optimized away so the physics system can find them.
if (isAnimated || (args.mHasAnimatedParents && ((args.mSkipMeshes || args.mHasMarkers) || isGeometry)))
node->setDataVariance(osg::Object::DYNAMIC);
// LOD and Switch nodes must be wrapped by a transform (the current node) to support transformations
// properly and we need to attach their children to the osg::LOD/osg::Switch nodes but we must return that
// transform to the caller of handleNode instead of the actual LOD/Switch nodes.
osg::ref_ptr<osg::Group> currentNode = node;
if (nifNode->recType == Nif::RC_NiSwitchNode)
{
const Nif::NiSwitchNode* niSwitchNode = static_cast<const Nif::NiSwitchNode*>(nifNode);
osg::ref_ptr<osg::Switch> switchNode = handleSwitchNode(niSwitchNode);
node->addChild(switchNode);
if (niSwitchNode->mName == Constants::NightDayLabel)
mHasNightDayLabel = true;
else if (niSwitchNode->mName == Constants::HerbalismLabel)
mHasHerbalismLabel = true;
currentNode = switchNode;
}
else if (nifNode->recType == Nif::RC_NiLODNode)
{
const Nif::NiLODNode* niLodNode = static_cast<const Nif::NiLODNode*>(nifNode);
osg::ref_ptr<osg::LOD> lodNode = handleLodNode(niLodNode);
node->addChild(lodNode);
currentNode = lodNode;
}
else if (nifNode->recType == Nif::RC_NiFltAnimationNode)
{
osg::ref_ptr<osg::Sequence> sequenceNode = prepareSequenceNode(nifNode);
node->addChild(sequenceNode);
currentNode = sequenceNode;
}
const Nif::NiNode* ninode = dynamic_cast<const Nif::NiNode*>(nifNode);
if (ninode)
{
const Nif::NiAVObjectList& children = ninode->mChildren;
const Nif::Parent currentParent{ *ninode, parent };
for (const auto& child : children)
if (!child.empty())
handleNode(child.getPtr(), ¤tParent, currentNode, args);
// Propagate effects to the the direct subgraph instead of the node itself
// This simulates their "affected node list" which Morrowind appears to replace with the subgraph (?)
// Note that the serialized affected node list is actually unused
for (const auto& effect : ninode->mEffects)
if (!effect.empty())
{
osg::ref_ptr<osg::StateSet> effectStateSet = new osg::StateSet;
if (handleEffect(effect.getPtr(), effectStateSet))
for (unsigned int i = 0; i < currentNode->getNumChildren(); ++i)
currentNode->getChild(i)->getOrCreateStateSet()->merge(*effectStateSet);
}
}
if (nifNode->recType == Nif::RC_NiFltAnimationNode)
activateSequenceNode(currentNode, nifNode);
return node;
}
static void handleMeshControllers(const Nif::NiAVObject* nifNode, osg::Node* node,
SceneUtil::CompositeStateSetUpdater* composite, const std::vector<unsigned int>& boundTextures,
int animflags)
{
for (Nif::NiTimeControllerPtr ctrl = nifNode->mController; !ctrl.empty(); ctrl = ctrl->mNext)
{
if (!ctrl->isActive())
continue;
if (ctrl->recType == Nif::RC_NiUVController)
{
const Nif::NiUVController* niuvctrl = static_cast<const Nif::NiUVController*>(ctrl.getPtr());
if (niuvctrl->mData.empty())
continue;
std::set<unsigned int> texUnits;
// UVController should only work for textures which use the given UV Set.
for (unsigned int i = 0; i < boundTextures.size(); ++i)
{
if (boundTextures[i] == niuvctrl->mUvSet)
texUnits.insert(i);
}
osg::ref_ptr<UVController> uvctrl = new UVController(niuvctrl->mData.getPtr(), texUnits);
setupController(niuvctrl, uvctrl, animflags);
composite->addController(uvctrl);
}
}
}
void handleNodeControllers(
const Nif::NiAVObject* nifNode, osg::Node* node, int animflags, bool& isAnimated) const
{
for (Nif::NiTimeControllerPtr ctrl = nifNode->mController; !ctrl.empty(); ctrl = ctrl->mNext)
{
if (!ctrl->isActive())
continue;
if (ctrl->recType == Nif::RC_NiKeyframeController)
{
const Nif::NiKeyframeController* key = static_cast<const Nif::NiKeyframeController*>(ctrl.getPtr());
if (key->mData.empty() && key->mInterpolator.empty())
continue;
if (!key->mInterpolator.empty() && key->mInterpolator->recType != Nif::RC_NiTransformInterpolator)
{
Log(Debug::Error) << "Unsupported interpolator type for NiKeyframeController " << key->recIndex
<< " in " << mFilename << ": " << key->mInterpolator->recName;
continue;
}
osg::ref_ptr<KeyframeController> callback = new KeyframeController(key);
setupController(key, callback, animflags);
node->addUpdateCallback(callback);
isAnimated = true;
}
else if (ctrl->recType == Nif::RC_NiPathController)
{
const Nif::NiPathController* path = static_cast<const Nif::NiPathController*>(ctrl.getPtr());
if (path->mPathData.empty() || path->mPercentData.empty())
continue;
osg::ref_ptr<PathController> callback(new PathController(path));
setupController(path, callback, animflags);
node->addUpdateCallback(callback);
isAnimated = true;
}
else if (ctrl->recType == Nif::RC_NiVisController)
{
const Nif::NiVisController* visctrl = static_cast<const Nif::NiVisController*>(ctrl.getPtr());
if (visctrl->mData.empty() && visctrl->mInterpolator.empty())
continue;
if (!visctrl->mInterpolator.empty()
&& visctrl->mInterpolator->recType != Nif::RC_NiBoolInterpolator)
{
Log(Debug::Error) << "Unsupported interpolator type for NiVisController " << visctrl->recIndex
<< " in " << mFilename << ": " << visctrl->mInterpolator->recName;
continue;
}
osg::ref_ptr<VisController> callback(new VisController(visctrl, Loader::getHiddenNodeMask()));
setupController(visctrl, callback, animflags);
node->addUpdateCallback(callback);
}
else if (ctrl->recType == Nif::RC_NiRollController)
{
const Nif::NiRollController* rollctrl = static_cast<const Nif::NiRollController*>(ctrl.getPtr());
if (rollctrl->mData.empty() && rollctrl->mInterpolator.empty())
continue;
if (!rollctrl->mInterpolator.empty()
&& rollctrl->mInterpolator->recType != Nif::RC_NiFloatInterpolator)
{
Log(Debug::Error) << "Unsupported interpolator type for NiRollController " << rollctrl->recIndex
<< " in " << mFilename << ": " << rollctrl->mInterpolator->recName;
continue;
}
osg::ref_ptr<RollController> callback = new RollController(rollctrl);
setupController(rollctrl, callback, animflags);
node->addUpdateCallback(callback);
isAnimated = true;
}
else if (ctrl->recType == Nif::RC_NiGeomMorpherController
|| ctrl->recType == Nif::RC_NiParticleSystemController
|| ctrl->recType == Nif::RC_NiBSPArrayController || ctrl->recType == Nif::RC_NiUVController)
{
// These controllers are handled elsewhere
}
else
Log(Debug::Info) << "Unhandled controller " << ctrl->recName << " on node " << nifNode->recIndex
<< " in " << mFilename;
}
}
void handleMaterialControllers(const Nif::NiProperty* materialProperty,
SceneUtil::CompositeStateSetUpdater* composite, int animflags, const osg::Material* baseMaterial) const
{
for (Nif::NiTimeControllerPtr ctrl = materialProperty->mController; !ctrl.empty(); ctrl = ctrl->mNext)
{
if (!ctrl->isActive())
continue;
if (ctrl->recType == Nif::RC_NiAlphaController)
{
const Nif::NiAlphaController* alphactrl = static_cast<const Nif::NiAlphaController*>(ctrl.getPtr());
if (alphactrl->mData.empty() && alphactrl->mInterpolator.empty())
continue;
if (!alphactrl->mInterpolator.empty()
&& alphactrl->mInterpolator->recType != Nif::RC_NiFloatInterpolator)
{
Log(Debug::Error)
<< "Unsupported interpolator type for NiAlphaController " << alphactrl->recIndex << " in "
<< mFilename << ": " << alphactrl->mInterpolator->recName;
continue;
}
osg::ref_ptr<AlphaController> osgctrl = new AlphaController(alphactrl, baseMaterial);
setupController(alphactrl, osgctrl, animflags);
composite->addController(osgctrl);
}
else if (ctrl->recType == Nif::RC_NiMaterialColorController)
{
const Nif::NiMaterialColorController* matctrl
= static_cast<const Nif::NiMaterialColorController*>(ctrl.getPtr());
Nif::NiInterpolatorPtr interp = matctrl->mInterpolator;
if (matctrl->mData.empty() && interp.empty())
continue;
if (mVersion <= Nif::NIFFile::VER_MW
&& matctrl->mTargetColor == Nif::NiMaterialColorController::TargetColor::Specular)
continue;
if (!interp.empty() && interp->recType != Nif::RC_NiPoint3Interpolator)
{
Log(Debug::Error) << "Unsupported interpolator type for NiMaterialColorController "
<< matctrl->recIndex << " in " << mFilename << ": " << interp->recName;
continue;
}
osg::ref_ptr<MaterialColorController> osgctrl = new MaterialColorController(matctrl, baseMaterial);
setupController(matctrl, osgctrl, animflags);
composite->addController(osgctrl);
}
else
Log(Debug::Info) << "Unexpected material controller " << ctrl->recType << " in " << mFilename;
}
}
osg::ref_ptr<osg::Image> getTextureImage(std::string_view path) const
{
if (!mImageManager)
return nullptr;
return mImageManager->getImage(
VFS::Path::toNormalized(Misc::ResourceHelpers::correctTexturePath(path, mImageManager->getVFS())));
}
static osg::ref_ptr<osg::Texture2D> attachTexture(const std::string& name, osg::ref_ptr<osg::Image> image,
bool wrapS, bool wrapT, unsigned int uvSet, osg::StateSet* stateset,
std::vector<unsigned int>& boundTextures)
{
osg::ref_ptr<osg::Texture2D> texture2d = new osg::Texture2D(image);
if (image)
texture2d->setTextureSize(image->s(), image->t());
texture2d->setWrap(osg::Texture::WRAP_S, wrapS ? osg::Texture::REPEAT : osg::Texture::CLAMP_TO_EDGE);
texture2d->setWrap(osg::Texture::WRAP_T, wrapT ? osg::Texture::REPEAT : osg::Texture::CLAMP_TO_EDGE);
unsigned int texUnit = boundTextures.size();
if (stateset)
{
stateset->setTextureAttributeAndModes(texUnit, texture2d, osg::StateAttribute::ON);
osg::ref_ptr<SceneUtil::TextureType> textureType = new SceneUtil::TextureType(name);
textureType = shareAttribute(textureType);
stateset->setTextureAttributeAndModes(texUnit, textureType, osg::StateAttribute::ON);
}
boundTextures.emplace_back(uvSet);
return texture2d;
}
osg::ref_ptr<osg::Texture2D> attachExternalTexture(const std::string& name, const std::string& path, bool wrapS,
bool wrapT, unsigned int uvSet, osg::StateSet* stateset, std::vector<unsigned int>& boundTextures) const
{
return attachTexture(name, getTextureImage(path), wrapS, wrapT, uvSet, stateset, boundTextures);
}
osg::ref_ptr<osg::Texture2D> attachNiSourceTexture(const std::string& name, const Nif::NiSourceTexture* st,
bool wrapS, bool wrapT, unsigned int uvSet, osg::StateSet* stateset,
std::vector<unsigned int>& boundTextures) const
{
return attachTexture(name, handleSourceTexture(st), wrapS, wrapT, uvSet, stateset, boundTextures);
}
static void clearBoundTextures(osg::StateSet* stateset, std::vector<unsigned int>& boundTextures)
{
if (!boundTextures.empty())
{
for (unsigned int i = 0; i < boundTextures.size(); ++i)
stateset->setTextureMode(i, GL_TEXTURE_2D, osg::StateAttribute::OFF);
boundTextures.clear();
}
}
void handleTextureControllers(const Nif::NiProperty* texProperty,
SceneUtil::CompositeStateSetUpdater* composite, osg::StateSet* stateset, int animflags) const
{
for (Nif::NiTimeControllerPtr ctrl = texProperty->mController; !ctrl.empty(); ctrl = ctrl->mNext)
{
if (!ctrl->isActive())
continue;
if (ctrl->recType == Nif::RC_NiFlipController)
{
const Nif::NiFlipController* flipctrl = static_cast<const Nif::NiFlipController*>(ctrl.getPtr());
if (!flipctrl->mInterpolator.empty()
&& flipctrl->mInterpolator->recType != Nif::RC_NiFloatInterpolator)
{
Log(Debug::Error) << "Unsupported interpolator type for NiFlipController " << flipctrl->recIndex
<< " in " << mFilename << ": " << flipctrl->mInterpolator->recName;
continue;
}
std::vector<osg::ref_ptr<osg::Texture2D>> textures;
// inherit wrap settings from the target slot
osg::Texture2D* inherit
= dynamic_cast<osg::Texture2D*>(stateset->getTextureAttribute(0, osg::StateAttribute::TEXTURE));
osg::Texture2D::WrapMode wrapS = osg::Texture2D::REPEAT;
osg::Texture2D::WrapMode wrapT = osg::Texture2D::REPEAT;
if (inherit)
{
wrapS = inherit->getWrap(osg::Texture2D::WRAP_S);
wrapT = inherit->getWrap(osg::Texture2D::WRAP_T);
}
const unsigned int uvSet = 0;
std::vector<unsigned int> boundTextures; // Dummy list for attachTexture
for (const auto& source : flipctrl->mSources)
{
if (source.empty())
continue;
// NB: not changing the stateset
osg::ref_ptr<osg::Texture2D> texture
= attachNiSourceTexture({}, source.getPtr(), wrapS, wrapT, uvSet, nullptr, boundTextures);
textures.push_back(texture);
}
osg::ref_ptr<FlipController> callback(new FlipController(flipctrl, textures));
setupController(ctrl.getPtr(), callback, animflags);
composite->addController(callback);
}
else
Log(Debug::Info) << "Unexpected texture controller " << ctrl->recName << " in " << mFilename;
}
}
void handleParticlePrograms(Nif::NiParticleModifierPtr modifier, Nif::NiParticleModifierPtr collider,
osg::Group* attachTo, osgParticle::ParticleSystem* partsys,
osgParticle::ParticleProcessor::ReferenceFrame rf) const
{
osgParticle::ModularProgram* program = new osgParticle::ModularProgram;
attachTo->addChild(program);
program->setParticleSystem(partsys);
program->setReferenceFrame(rf);
for (; !modifier.empty(); modifier = modifier->mNext)
{
if (modifier->recType == Nif::RC_NiParticleGrowFade)
{
const Nif::NiParticleGrowFade* gf = static_cast<const Nif::NiParticleGrowFade*>(modifier.getPtr());
program->addOperator(new GrowFadeAffector(gf->mGrowTime, gf->mFadeTime));
}
else if (modifier->recType == Nif::RC_NiGravity)
{
const Nif::NiGravity* gr = static_cast<const Nif::NiGravity*>(modifier.getPtr());
program->addOperator(new GravityAffector(gr));
}
else if (modifier->recType == Nif::RC_NiParticleBomb)
{
auto bomb = static_cast<const Nif::NiParticleBomb*>(modifier.getPtr());
osg::ref_ptr<osgParticle::ModularProgram> bombProgram(new osgParticle::ModularProgram);
attachTo->addChild(bombProgram);
bombProgram->setParticleSystem(partsys);
bombProgram->setReferenceFrame(rf);
bombProgram->setStartTime(bomb->mStartTime);
bombProgram->setLifeTime(bomb->mDuration);
bombProgram->setEndless(false);
bombProgram->addOperator(new ParticleBomb(bomb));
}
else if (modifier->recType == Nif::RC_NiParticleColorModifier)
{
const Nif::NiParticleColorModifier* cl
= static_cast<const Nif::NiParticleColorModifier*>(modifier.getPtr());
if (cl->mData.empty())
continue;
const Nif::NiColorData* clrdata = cl->mData.getPtr();
program->addOperator(new ParticleColorAffector(clrdata));
}
else if (modifier->recType == Nif::RC_NiParticleRotation)
{
// unused
}
else
Log(Debug::Info) << "Unhandled particle modifier " << modifier->recName << " in " << mFilename;
}
for (; !collider.empty(); collider = collider->mNext)
{
if (collider->recType == Nif::RC_NiPlanarCollider)
{
const Nif::NiPlanarCollider* planarcollider
= static_cast<const Nif::NiPlanarCollider*>(collider.getPtr());
program->addOperator(new PlanarCollider(planarcollider));
}
else if (collider->recType == Nif::RC_NiSphericalCollider)
{
const Nif::NiSphericalCollider* sphericalcollider
= static_cast<const Nif::NiSphericalCollider*>(collider.getPtr());
program->addOperator(new SphericalCollider(sphericalcollider));
}
else
Log(Debug::Info) << "Unhandled particle collider " << collider->recName << " in " << mFilename;
}
}
// Load the initial state of the particle system, i.e. the initial particles and their positions, velocity and
// colors.
static void handleParticleInitialState(
const Nif::NiAVObject* nifNode, ParticleSystem* partsys, const Nif::NiParticleSystemController* partctrl)
{
auto particleNode = static_cast<const Nif::NiParticles*>(nifNode);
if (particleNode->mData.empty())
{
partsys->setQuota(partctrl->mParticles.size());
return;
}
auto particledata = static_cast<const Nif::NiParticlesData*>(particleNode->mData.getPtr());
partsys->setQuota(particledata->mNumParticles);
osg::BoundingBox box;
int i = 0;
for (const auto& particle : partctrl->mParticles)
{
if (i++ >= particledata->mActiveCount)
break;
if (particle.mLifespan <= 0)
continue;
if (particle.mCode >= particledata->mVertices.size())
continue;
ParticleAgeSetter particletemplate(std::max(0.f, particle.mAge));
osgParticle::Particle* created = partsys->createParticle(&particletemplate);
created->setLifeTime(particle.mLifespan);
// Note this position and velocity is not correct for a particle system with absolute reference frame,
// which can not be done in this loader since we are not attached to the scene yet. Will be fixed up
// post-load in the SceneManager.
created->setVelocity(particle.mVelocity);
const osg::Vec3f& position = particledata->mVertices[particle.mCode];
created->setPosition(position);
created->setColorRange(osgParticle::rangev4(partctrl->mInitialColor, partctrl->mInitialColor));
created->setAlphaRange(osgParticle::rangef(1.f, 1.f));
float size = partctrl->mInitialSize;
if (particle.mCode < particledata->mSizes.size())
size *= particledata->mSizes[particle.mCode];
created->setSizeRange(osgParticle::rangef(size, size));
box.expandBy(osg::BoundingSphere(position, size));
}
// radius may be used to force a larger bounding box
box.expandBy(osg::BoundingSphere(osg::Vec3(0, 0, 0), particledata->mBoundingSphere.radius()));
partsys->setInitialBound(box);
}
static osg::ref_ptr<Emitter> handleParticleEmitter(const Nif::NiParticleSystemController* partctrl)
{
std::vector<int> targets;
if (partctrl->recType == Nif::RC_NiBSPArrayController && !partctrl->emitAtVertex())
{
getAllNiNodes(partctrl->mEmitter.getPtr(), targets);
}
osg::ref_ptr<Emitter> emitter = new Emitter(targets);
osgParticle::ConstantRateCounter* counter = new osgParticle::ConstantRateCounter;
if (partctrl->noAutoAdjust())
counter->setNumberOfParticlesPerSecondToCreate(partctrl->mBirthRate);
else if (partctrl->mLifetime == 0 && partctrl->mLifetimeVariation == 0)
counter->setNumberOfParticlesPerSecondToCreate(0);
else
counter->setNumberOfParticlesPerSecondToCreate(
partctrl->mParticles.size() / (partctrl->mLifetime + partctrl->mLifetimeVariation / 2));
emitter->setCounter(counter);
ParticleShooter* shooter = new ParticleShooter(partctrl->mSpeed - partctrl->mSpeedVariation * 0.5f,
partctrl->mSpeed + partctrl->mSpeedVariation * 0.5f, partctrl->mPlanarAngle,
partctrl->mPlanarAngleVariation, partctrl->mDeclination, partctrl->mDeclinationVariation,
partctrl->mLifetime, partctrl->mLifetimeVariation);
emitter->setShooter(shooter);
emitter->setFlags(partctrl->mFlags);
if (partctrl->recType == Nif::RC_NiBSPArrayController && partctrl->emitAtVertex())
{
emitter->setGeometryEmitterTarget(partctrl->mEmitter->recIndex);
}
else
{
osgParticle::BoxPlacer* placer = new osgParticle::BoxPlacer;
placer->setXRange(-partctrl->mEmitterDimensions.x() / 2.f, partctrl->mEmitterDimensions.x() / 2.f);
placer->setYRange(-partctrl->mEmitterDimensions.y() / 2.f, partctrl->mEmitterDimensions.y() / 2.f);
placer->setZRange(-partctrl->mEmitterDimensions.z() / 2.f, partctrl->mEmitterDimensions.z() / 2.f);
emitter->setPlacer(placer);
}
return emitter;
}
void handleQueuedParticleEmitters(osg::Group* rootNode, Nif::FileView nif)
{
for (const auto& emitterPair : mEmitterQueue)
{
size_t recIndex = emitterPair.first;
FindGroupByRecIndex findEmitterNode(recIndex);
rootNode->accept(findEmitterNode);
osg::Group* emitterNode = findEmitterNode.mFound;
if (!emitterNode)
{
Log(Debug::Warning)
<< "NIFFile Warning: Failed to find particle emitter emitter node (node record index "
<< recIndex << "). File: " << nif.getFilename();
continue;
}
// Emitter attached to the emitter node. Note one side effect of the emitter using the CullVisitor is
// that hiding its node actually causes the emitter to stop firing. Convenient, because MW behaves this
// way too!
emitterNode->addChild(emitterPair.second);
DisableOptimizer disableOptimizer;
emitterNode->accept(disableOptimizer);
}
mEmitterQueue.clear();
}
void handleParticleSystem(const Nif::NiAVObject* nifNode, const Nif::Parent* parent, osg::Group* parentNode,
SceneUtil::CompositeStateSetUpdater* composite, int animflags)
{
osg::ref_ptr<ParticleSystem> partsys(new ParticleSystem);
partsys->setSortMode(osgParticle::ParticleSystem::SORT_BACK_TO_FRONT);
const Nif::NiParticleSystemController* partctrl = nullptr;
for (Nif::NiTimeControllerPtr ctrl = nifNode->mController; !ctrl.empty(); ctrl = ctrl->mNext)
{
if (!ctrl->isActive())
continue;
if (ctrl->recType == Nif::RC_NiParticleSystemController
|| ctrl->recType == Nif::RC_NiBSPArrayController)
partctrl = static_cast<Nif::NiParticleSystemController*>(ctrl.getPtr());
}
if (!partctrl)
{
Log(Debug::Info) << "No particle controller found in " << mFilename;
return;
}
osgParticle::ParticleProcessor::ReferenceFrame rf = (animflags & Nif::NiNode::ParticleFlag_LocalSpace)
? osgParticle::ParticleProcessor::RELATIVE_RF
: osgParticle::ParticleProcessor::ABSOLUTE_RF;
// HACK: ParticleSystem has no setReferenceFrame method
if (rf == osgParticle::ParticleProcessor::ABSOLUTE_RF)
{
partsys->getOrCreateUserDataContainer()->addDescription("worldspace");
}
partsys->setParticleScaleReferenceFrame(osgParticle::ParticleSystem::LOCAL_COORDINATES);
handleParticleInitialState(nifNode, partsys, partctrl);
partsys->getDefaultParticleTemplate().setSizeRange(
osgParticle::rangef(partctrl->mInitialSize, partctrl->mInitialSize));
partsys->getDefaultParticleTemplate().setColorRange(
osgParticle::rangev4(partctrl->mInitialColor, partctrl->mInitialColor));
partsys->getDefaultParticleTemplate().setAlphaRange(osgParticle::rangef(1.f, 1.f));
if (!partctrl->mEmitter.empty())
{
osg::ref_ptr<Emitter> emitter = handleParticleEmitter(partctrl);
emitter->setParticleSystem(partsys);
emitter->setReferenceFrame(osgParticle::ParticleProcessor::RELATIVE_RF);
// The emitter node may not actually be handled yet, so let's delay attaching the emitter to a later
// moment. If the emitter node is placed later than the particle node, it'll have a single frame delay
// in particle processing. But that shouldn't be a game-breaking issue.
mEmitterQueue.emplace_back(partctrl->mEmitter->recIndex, emitter);
osg::ref_ptr<ParticleSystemController> callback(new ParticleSystemController(partctrl));
setupController(partctrl, callback, animflags);
emitter->setUpdateCallback(callback);
if (!(animflags & Nif::NiNode::ParticleFlag_AutoPlay))
{
partsys->setFrozen(true);
}
// Due to odd code in the ParticleSystemUpdater, particle systems will not be updated in the first frame
// So do that update manually
osg::NodeVisitor nv;
partsys->update(0.0, nv);
}
// modifiers should be attached *after* the emitter in the scene graph for correct update order
// attach to same node as the ParticleSystem, we need osgParticle Operators to get the correct
// localToWorldMatrix for transforming to particle space
handleParticlePrograms(partctrl->mModifier, partctrl->mCollider, parentNode, partsys.get(), rf);
std::vector<const Nif::NiProperty*> drawableProps;
collectDrawableProperties(nifNode, parent, drawableProps);
applyDrawableProperties(parentNode, drawableProps, composite, true, animflags);
// particle system updater (after the emitters and modifiers in the scene graph)
// I think for correct culling needs to be *before* the ParticleSystem, though osg examples do it the other
// way
osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater;
updater->addParticleSystem(partsys);
parentNode->addChild(updater);
osg::Node* toAttach = partsys.get();
if (rf == osgParticle::ParticleProcessor::RELATIVE_RF)
parentNode->addChild(toAttach);
else
{
osg::MatrixTransform* trans = new osg::MatrixTransform;
trans->setUpdateCallback(new InverseWorldMatrix);
trans->addChild(toAttach);
parentNode->addChild(trans);
}
}
void handleNiGeometryData(const Nif::NiAVObject* nifNode, const Nif::Parent* parent, osg::Geometry* geometry,
osg::Node* parentNode, SceneUtil::CompositeStateSetUpdater* composite,
const std::vector<unsigned int>& boundTextures, int animflags)
{
const Nif::NiGeometry* niGeometry = static_cast<const Nif::NiGeometry*>(nifNode);
if (niGeometry->mData.empty())
return;
bool hasPartitions = false;
if (!niGeometry->mSkin.empty())
{
const Nif::NiSkinInstance* skin = niGeometry->mSkin.getPtr();
const Nif::NiSkinPartition* partitions = skin->getPartitions();
hasPartitions = partitions != nullptr;
if (hasPartitions)
{
for (const Nif::NiSkinPartition::Partition& partition : partitions->mPartitions)
{
const std::vector<unsigned short>& trueTriangles = partition.mTrueTriangles;
if (!trueTriangles.empty())
{
geometry->addPrimitiveSet(new osg::DrawElementsUShort(
osg::PrimitiveSet::TRIANGLES, trueTriangles.size(), trueTriangles.data()));
}
for (const auto& strip : partition.mTrueStrips)
{
if (strip.size() < 3)
continue;
geometry->addPrimitiveSet(new osg::DrawElementsUShort(
osg::PrimitiveSet::TRIANGLE_STRIP, strip.size(), strip.data()));
}
}
}
}
const Nif::NiGeometryData* niGeometryData = niGeometry->mData.getPtr();
if (!hasPartitions)
{
if (niGeometry->recType == Nif::RC_NiTriShape || nifNode->recType == Nif::RC_BSLODTriShape)
{
auto data = static_cast<const Nif::NiTriShapeData*>(niGeometryData);
const std::vector<unsigned short>& triangles = data->mTriangles;
if (triangles.empty())
return;
geometry->addPrimitiveSet(
new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, triangles.size(), triangles.data()));
}
else if (niGeometry->recType == Nif::RC_NiTriStrips)
{
auto data = static_cast<const Nif::NiTriStripsData*>(niGeometryData);
bool hasGeometry = false;
for (const std::vector<unsigned short>& strip : data->mStrips)
{
if (strip.size() < 3)
continue;
geometry->addPrimitiveSet(
new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLE_STRIP, strip.size(), strip.data()));
hasGeometry = true;
}
if (!hasGeometry)
return;
}
else if (niGeometry->recType == Nif::RC_NiLines)
{
auto data = static_cast<const Nif::NiLinesData*>(niGeometryData);
const auto& line = data->mLines;
if (line.empty())
return;
geometry->addPrimitiveSet(
new osg::DrawElementsUShort(osg::PrimitiveSet::LINES, line.size(), line.data()));
}
}
const auto& vertices = niGeometryData->mVertices;
const auto& normals = niGeometryData->mNormals;
const auto& colors = niGeometryData->mColors;
if (!vertices.empty())
geometry->setVertexArray(new osg::Vec3Array(vertices.size(), vertices.data()));
if (!normals.empty())
geometry->setNormalArray(
new osg::Vec3Array(normals.size(), normals.data()), osg::Array::BIND_PER_VERTEX);
if (!colors.empty())
geometry->setColorArray(new osg::Vec4Array(colors.size(), colors.data()), osg::Array::BIND_PER_VERTEX);
const auto& uvlist = niGeometryData->mUVList;
int textureStage = 0;
for (std::vector<unsigned int>::const_iterator it = boundTextures.begin(); it != boundTextures.end();
++it, ++textureStage)
{
unsigned int uvSet = *it;
if (uvSet >= uvlist.size())
{
Log(Debug::Verbose) << "Out of bounds UV set " << uvSet << " on shape \"" << nifNode->mName
<< "\" in " << mFilename;
if (uvlist.empty())
continue;
uvSet = 0;
}
geometry->setTexCoordArray(textureStage, new osg::Vec2Array(uvlist[uvSet].size(), uvlist[uvSet].data()),
osg::Array::BIND_PER_VERTEX);
}
// osg::Material properties are handled here for two reasons:
// - if there are no vertex colors, we need to disable colorMode.
// - there are 3 "overlapping" nif properties that all affect the osg::Material, handling them
// above the actual renderable would be tedious.
std::vector<const Nif::NiProperty*> drawableProps;
collectDrawableProperties(nifNode, parent, drawableProps);
if (!niGeometry->mShaderProperty.empty())
drawableProps.emplace_back(niGeometry->mShaderProperty.getPtr());
if (!niGeometry->mAlphaProperty.empty())
drawableProps.emplace_back(niGeometry->mAlphaProperty.getPtr());
applyDrawableProperties(parentNode, drawableProps, composite, !niGeometryData->mColors.empty(), animflags);
}
void handleNiGeometry(const Nif::NiAVObject* nifNode, const Nif::Parent* parent, osg::Group* parentNode,
SceneUtil::CompositeStateSetUpdater* composite, const std::vector<unsigned int>& boundTextures,
int animflags)
{
assert(isTypeNiGeometry(nifNode->recType));
osg::ref_ptr<osg::Geometry> geom(new osg::Geometry);
handleNiGeometryData(nifNode, parent, geom, parentNode, composite, boundTextures, animflags);
// If the record had no valid geometry data in it, early-out
if (geom->empty())
return;
osg::ref_ptr<osg::Drawable> drawable = geom;
auto niGeometry = static_cast<const Nif::NiGeometry*>(nifNode);
if (!niGeometry->mSkin.empty())
{
osg::ref_ptr<SceneUtil::RigGeometry> rig(new SceneUtil::RigGeometry);
rig->setSourceGeometry(geom);
const Nif::NiSkinInstance* skin = niGeometry->mSkin.getPtr();
const Nif::NiSkinData* data = skin->mData.getPtr();
const Nif::NiAVObjectList& bones = skin->mBones;
// Assign bone weights
std::vector<SceneUtil::RigGeometry::BoneInfo> boneInfo;
std::vector<SceneUtil::RigGeometry::VertexWeights> influences;
boneInfo.resize(bones.size());
influences.resize(bones.size());
for (std::size_t i = 0; i < bones.size(); ++i)
{
boneInfo[i].mName = Misc::StringUtils::lowerCase(bones[i].getPtr()->mName);
boneInfo[i].mInvBindMatrix = data->mBones[i].mTransform.toMatrix();
boneInfo[i].mBoundSphere = data->mBones[i].mBoundSphere;
influences[i] = data->mBones[i].mWeights;
}
rig->setBoneInfo(std::move(boneInfo));
rig->setInfluences(influences);
drawable = rig;
}
for (Nif::NiTimeControllerPtr ctrl = nifNode->mController; !ctrl.empty(); ctrl = ctrl->mNext)
{
if (!ctrl->isActive())
continue;
if (ctrl->recType == Nif::RC_NiGeomMorpherController)
{
if (!niGeometry->mSkin.empty())
continue;
auto nimorphctrl = static_cast<const Nif::NiGeomMorpherController*>(ctrl.getPtr());
if (nimorphctrl->mData.empty())
continue;
const std::vector<Nif::NiMorphData::MorphData>& morphs = nimorphctrl->mData.getPtr()->mMorphs;
if (morphs.empty()
|| morphs[0].mVertices.size()
!= static_cast<const osg::Vec3Array*>(geom->getVertexArray())->size())
continue;
osg::ref_ptr<SceneUtil::MorphGeometry> morphGeom = new SceneUtil::MorphGeometry;
morphGeom->setSourceGeometry(geom);
for (unsigned int i = 0; i < morphs.size(); ++i)
morphGeom->addMorphTarget(
new osg::Vec3Array(morphs[i].mVertices.size(), morphs[i].mVertices.data()), 0.f);
osg::ref_ptr<GeomMorpherController> morphctrl = new GeomMorpherController(nimorphctrl);
setupController(ctrl.getPtr(), morphctrl, animflags);
morphGeom->setUpdateCallback(morphctrl);
drawable = morphGeom;
break;
}
}
drawable->setName(nifNode->mName);
parentNode->addChild(drawable);
}
void handleBSGeometry(const Nif::NiAVObject* nifNode, const Nif::Parent* parent, osg::Group* parentNode,
SceneUtil::CompositeStateSetUpdater* composite, const std::vector<unsigned int>& boundTextures,
int animflags)
{
assert(isTypeBSGeometry(nifNode->recType));
auto bsTriShape = static_cast<const Nif::BSTriShape*>(nifNode);
const std::vector<unsigned short>& triangles = bsTriShape->mTriangles;
if (triangles.empty())
return;
osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry);
geometry->addPrimitiveSet(
new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, triangles.size(), triangles.data()));
osg::ref_ptr<osg::Drawable> drawable = geometry;
// Some input geometry may not be used as is so it needs to be converted.
// Normals, tangents and bitangents use a special normal map-like format not equivalent to snorm8 or unorm8
auto normbyteToFloat = [](uint8_t value) { return value / 255.f * 2.f - 1.f; };
// Vertices and UV sets may be half-precision.
// OSG doesn't have a way to pass half-precision data at the moment.
auto halfToFloat = [](uint16_t value) {
uint32_t bits = static_cast<uint32_t>(value & 0x8000) << 16;
const uint32_t exp16 = (value & 0x7c00) >> 10;
uint32_t frac16 = value & 0x3ff;
if (exp16)
bits |= (exp16 + 0x70) << 23;
else if (frac16)
{
uint8_t offset = 0;
do
{
++offset;
frac16 <<= 1;
} while ((frac16 & 0x400) != 0x400);
frac16 &= 0x3ff;
bits |= (0x71 - offset) << 23;
}
bits |= frac16 << 13;
float result;
std::memcpy(&result, &bits, sizeof(float));
return result;
};
const bool fullPrec = bsTriShape->mVertDesc.mFlags & Nif::BSVertexDesc::VertexAttribute::Full_Precision;
const bool hasVertices = bsTriShape->mVertDesc.mFlags & Nif::BSVertexDesc::VertexAttribute::Vertex;
const bool hasNormals = bsTriShape->mVertDesc.mFlags & Nif::BSVertexDesc::VertexAttribute::Normals;
const bool hasColors = bsTriShape->mVertDesc.mFlags & Nif::BSVertexDesc::VertexAttribute::Vertex_Colors;
const bool hasUV = bsTriShape->mVertDesc.mFlags & Nif::BSVertexDesc::VertexAttribute::UVs;
std::vector<osg::Vec3f> vertices;
std::vector<osg::Vec3f> normals;
std::vector<osg::Vec4ub> colors;
std::vector<osg::Vec2f> uvlist;
for (auto& elem : bsTriShape->mVertData)
{
if (hasVertices)
{
if (fullPrec)
vertices.emplace_back(elem.mVertex.x(), elem.mVertex.y(), elem.mVertex.z());
else
vertices.emplace_back(halfToFloat(elem.mHalfVertex[0]), halfToFloat(elem.mHalfVertex[1]),
halfToFloat(elem.mHalfVertex[2]));
}
if (hasNormals)
normals.emplace_back(normbyteToFloat(elem.mNormal[0]), normbyteToFloat(elem.mNormal[1]),
normbyteToFloat(elem.mNormal[2]));
if (hasColors)
colors.emplace_back(elem.mVertColor[0], elem.mVertColor[1], elem.mVertColor[2], elem.mVertColor[3]);
if (hasUV)
uvlist.emplace_back(halfToFloat(elem.mUV[0]), 1.0 - halfToFloat(elem.mUV[1]));
}
if (!vertices.empty())
geometry->setVertexArray(new osg::Vec3Array(vertices.size(), vertices.data()));
if (!normals.empty())
geometry->setNormalArray(
new osg::Vec3Array(normals.size(), normals.data()), osg::Array::BIND_PER_VERTEX);
if (!colors.empty())
geometry->setColorArray(
new osg::Vec4ubArray(colors.size(), colors.data()), osg::Array::BIND_PER_VERTEX);
if (!uvlist.empty())
geometry->setTexCoordArray(
0, new osg::Vec2Array(uvlist.size(), uvlist.data()), osg::Array::BIND_PER_VERTEX);
// This is the skinning data Fallout 4 provides
// TODO: support Skyrim SE skinning data
if (!bsTriShape->mSkin.empty() && bsTriShape->mSkin->recType == Nif::RC_BSSkinInstance
&& bsTriShape->mVertDesc.mFlags & Nif::BSVertexDesc::VertexAttribute::Skinned)
{
osg::ref_ptr<SceneUtil::RigGeometry> rig(new SceneUtil::RigGeometry);
rig->setSourceGeometry(std::move(geometry));
const Nif::BSSkinInstance* skin = static_cast<const Nif::BSSkinInstance*>(bsTriShape->mSkin.getPtr());
const Nif::BSSkinBoneData* data = skin->mData.getPtr();
const Nif::NiAVObjectList& bones = skin->mBones;
std::vector<SceneUtil::RigGeometry::BoneInfo> boneInfo;
std::vector<SceneUtil::RigGeometry::BoneWeights> influences;
boneInfo.resize(bones.size());
influences.resize(vertices.size());
for (std::size_t i = 0; i < bones.size(); ++i)
{
boneInfo[i].mName = Misc::StringUtils::lowerCase(bones[i].getPtr()->mName);
boneInfo[i].mInvBindMatrix = data->mBones[i].mTransform.toMatrix();
boneInfo[i].mBoundSphere = data->mBones[i].mBoundSphere;
}
for (size_t i = 0; i < vertices.size(); i++)
{
const Nif::BSVertexData& vertData = bsTriShape->mVertData[i];
for (int j = 0; j < 4; j++)
influences[i].emplace_back(vertData.mBoneIndices[j], halfToFloat(vertData.mBoneWeights[j]));
}
rig->setBoneInfo(std::move(boneInfo));
rig->setInfluences(influences);
drawable = rig;
}
std::vector<const Nif::NiProperty*> drawableProps;
collectDrawableProperties(nifNode, parent, drawableProps);
if (!bsTriShape->mShaderProperty.empty())
drawableProps.emplace_back(bsTriShape->mShaderProperty.getPtr());
if (!bsTriShape->mAlphaProperty.empty())
drawableProps.emplace_back(bsTriShape->mAlphaProperty.getPtr());
applyDrawableProperties(parentNode, drawableProps, composite, !colors.empty(), animflags);
drawable->setName(nifNode->mName);
parentNode->addChild(drawable);
}
osg::BlendFunc::BlendFuncMode getBlendMode(int mode) const
{
switch (mode)
{
case 0:
return osg::BlendFunc::ONE;
case 1:
return osg::BlendFunc::ZERO;
case 2:
return osg::BlendFunc::SRC_COLOR;
case 3:
return osg::BlendFunc::ONE_MINUS_SRC_COLOR;
case 4:
return osg::BlendFunc::DST_COLOR;
case 5:
return osg::BlendFunc::ONE_MINUS_DST_COLOR;
case 6:
return osg::BlendFunc::SRC_ALPHA;
case 7:
return osg::BlendFunc::ONE_MINUS_SRC_ALPHA;
case 8:
return osg::BlendFunc::DST_ALPHA;
case 9:
return osg::BlendFunc::ONE_MINUS_DST_ALPHA;
case 10:
return osg::BlendFunc::SRC_ALPHA_SATURATE;
default:
Log(Debug::Info) << "Unexpected blend mode: " << mode << " in " << mFilename;
return osg::BlendFunc::SRC_ALPHA;
}
}
osg::AlphaFunc::ComparisonFunction getTestMode(int mode) const
{
switch (mode)
{
case 0:
return osg::AlphaFunc::ALWAYS;
case 1:
return osg::AlphaFunc::LESS;
case 2:
return osg::AlphaFunc::EQUAL;
case 3:
return osg::AlphaFunc::LEQUAL;
case 4:
return osg::AlphaFunc::GREATER;
case 5:
return osg::AlphaFunc::NOTEQUAL;
case 6:
return osg::AlphaFunc::GEQUAL;
case 7:
return osg::AlphaFunc::NEVER;
default:
Log(Debug::Info) << "Unexpected blend mode: " << mode << " in " << mFilename;
return osg::AlphaFunc::LEQUAL;
}
}
osg::Stencil::Function getStencilFunction(Nif::NiStencilProperty::TestFunc func) const
{
using TestFunc = Nif::NiStencilProperty::TestFunc;
switch (func)
{
case TestFunc::Never:
return osg::Stencil::NEVER;
case TestFunc::Less:
return osg::Stencil::LESS;
case TestFunc::Equal:
return osg::Stencil::EQUAL;
case TestFunc::LessEqual:
return osg::Stencil::LEQUAL;
case TestFunc::Greater:
return osg::Stencil::GREATER;
case TestFunc::NotEqual:
return osg::Stencil::NOTEQUAL;
case TestFunc::GreaterEqual:
return osg::Stencil::GEQUAL;
case TestFunc::Always:
return osg::Stencil::ALWAYS;
default:
Log(Debug::Info) << "Unexpected stencil function: " << static_cast<uint32_t>(func) << " in "
<< mFilename;
return osg::Stencil::NEVER;
}
}
osg::Stencil::Operation getStencilOperation(Nif::NiStencilProperty::Action op) const
{
using Action = Nif::NiStencilProperty::Action;
switch (op)
{
case Action::Keep:
return osg::Stencil::KEEP;
case Action::Zero:
return osg::Stencil::ZERO;
case Action::Replace:
return osg::Stencil::REPLACE;
case Action::Increment:
return osg::Stencil::INCR;
case Action::Decrement:
return osg::Stencil::DECR;
case Action::Invert:
return osg::Stencil::INVERT;
default:
Log(Debug::Info) << "Unexpected stencil operation: " << static_cast<uint32_t>(op) << " in "
<< mFilename;
return osg::Stencil::KEEP;
}
}
osg::ref_ptr<osg::Image> handleInternalTexture(const Nif::NiPixelData* pixelData) const
{
if (pixelData->mMipmaps.empty())
return nullptr;
// Not fatal, but warn the user
if (pixelData->mNumFaces != 1)
Log(Debug::Info) << "Unsupported multifaceted internal texture in " << mFilename;
using Nif::NiPixelFormat;
NiPixelFormat niPixelFormat = pixelData->mPixelFormat;
GLenum pixelformat = 0;
// Pixel row alignment. Defining it to be consistent with OSG DDS plugin
int packing = 1;
switch (niPixelFormat.mFormat)
{
case NiPixelFormat::Format::RGB:
pixelformat = GL_RGB;
break;
case NiPixelFormat::Format::RGBA:
pixelformat = GL_RGBA;
break;
case NiPixelFormat::Format::Palette:
case NiPixelFormat::Format::PaletteAlpha:
pixelformat = GL_RED; // Each color is defined by a byte.
break;
case NiPixelFormat::Format::BGR:
pixelformat = GL_BGR;
break;
case NiPixelFormat::Format::BGRA:
pixelformat = GL_BGRA;
break;
case NiPixelFormat::Format::DXT1:
pixelformat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
packing = 2;
break;
case NiPixelFormat::Format::DXT3:
pixelformat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
packing = 4;
break;
case NiPixelFormat::Format::DXT5:
pixelformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
packing = 4;
break;
default:
Log(Debug::Info) << "Unhandled internal pixel format "
<< static_cast<uint32_t>(niPixelFormat.mFormat) << " in " << mFilename;
return nullptr;
}
int width = 0;
int height = 0;
std::vector<unsigned int> mipmapOffsets;
for (unsigned int i = 0; i < pixelData->mMipmaps.size(); ++i)
{
const Nif::NiPixelData::Mipmap& mip = pixelData->mMipmaps[i];
size_t mipSize = osg::Image::computeImageSizeInBytes(
mip.mWidth, mip.mHeight, 1, pixelformat, GL_UNSIGNED_BYTE, packing);
if (mipSize + mip.mOffset > pixelData->mData.size())
{
Log(Debug::Info) << "Internal texture's mipmap data out of bounds, ignoring texture";
return nullptr;
}
if (i != 0)
mipmapOffsets.push_back(mip.mOffset);
else
{
width = mip.mWidth;
height = mip.mHeight;
}
}
if (width <= 0 || height <= 0)
{
Log(Debug::Info) << "Internal Texture Width and height must be non zero, ignoring texture";
return nullptr;
}
osg::ref_ptr<osg::Image> image(new osg::Image);
const std::vector<unsigned char>& pixels = pixelData->mData;
switch (niPixelFormat.mFormat)
{
case NiPixelFormat::Format::RGB:
case NiPixelFormat::Format::RGBA:
case NiPixelFormat::Format::BGR:
case NiPixelFormat::Format::BGRA:
case NiPixelFormat::Format::DXT1:
case NiPixelFormat::Format::DXT3:
case NiPixelFormat::Format::DXT5:
{
unsigned char* data = new unsigned char[pixels.size()];
memcpy(data, pixels.data(), pixels.size());
image->setImage(width, height, 1, pixelformat, pixelformat, GL_UNSIGNED_BYTE, data,
osg::Image::USE_NEW_DELETE, packing);
break;
}
case NiPixelFormat::Format::Palette:
case NiPixelFormat::Format::PaletteAlpha:
{
if (pixelData->mPalette.empty() || niPixelFormat.mBitsPerPixel != 8)
{
Log(Debug::Info) << "Palettized texture in " << mFilename << " is invalid, ignoring";
return nullptr;
}
pixelformat = niPixelFormat.mFormat == NiPixelFormat::Format::PaletteAlpha ? GL_RGBA : GL_RGB;
// We're going to convert the indices that pixel data contains
// into real colors using the palette.
const auto& palette = pixelData->mPalette->mColors;
const int numChannels = pixelformat == GL_RGBA ? 4 : 3;
unsigned char* data = new unsigned char[pixels.size() * numChannels];
unsigned char* pixel = data;
for (unsigned char index : pixels)
{
memcpy(pixel, &palette[index], sizeof(unsigned char) * numChannels);
pixel += numChannels;
}
for (unsigned int& offset : mipmapOffsets)
offset *= numChannels;
image->setImage(width, height, 1, pixelformat, pixelformat, GL_UNSIGNED_BYTE, data,
osg::Image::USE_NEW_DELETE, packing);
break;
}
default:
return nullptr;
}
image->setMipmapLevels(mipmapOffsets);
image->flipVertical();
return image;
}
static osg::ref_ptr<osg::TexEnvCombine> createEmissiveTexEnv()
{
osg::ref_ptr<osg::TexEnvCombine> texEnv(new osg::TexEnvCombine);
// Sum the previous colour and the emissive colour.
texEnv->setCombine_RGB(osg::TexEnvCombine::ADD);
texEnv->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
texEnv->setSource1_RGB(osg::TexEnvCombine::TEXTURE);
// Keep the previous alpha.
texEnv->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
texEnv->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
texEnv->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
return texEnv;
}
static void handleDepthFlags(osg::StateSet* stateset, bool depthTest, bool depthWrite)
{
if (!depthWrite && !depthTest)
{
stateset->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
return;
}
osg::ref_ptr<osg::Depth> depth = new osg::Depth;
depth->setWriteMask(depthWrite);
if (!depthTest)
depth->setFunction(osg::Depth::ALWAYS);
depth = shareAttribute(depth);
stateset->setAttributeAndModes(depth, osg::StateAttribute::ON);
}
void handleTextureProperty(const Nif::NiTexturingProperty* texprop, const std::string& nodeName,
osg::StateSet* stateset, SceneUtil::CompositeStateSetUpdater* composite,
std::vector<unsigned int>& boundTextures, int animflags) const
{
// overriding a parent NiTexturingProperty, so remove what was previously bound
clearBoundTextures(stateset, boundTextures);
// If this loop is changed such that the base texture isn't guaranteed to end up in texture unit 0, the
// shadow casting shader will need to be updated accordingly.
for (size_t i = 0; i < texprop->mTextures.size(); ++i)
{
const Nif::NiTexturingProperty::Texture& tex = texprop->mTextures[i];
if (tex.mEnabled || (i == Nif::NiTexturingProperty::BaseTexture && !texprop->mController.empty()))
{
std::string textureName;
switch (i)
{
// These are handled later on
case Nif::NiTexturingProperty::BaseTexture:
textureName = "diffuseMap";
break;
case Nif::NiTexturingProperty::GlowTexture:
textureName = "emissiveMap";
break;
case Nif::NiTexturingProperty::DarkTexture:
textureName = "darkMap";
break;
case Nif::NiTexturingProperty::BumpTexture:
textureName = "bumpMap";
break;
case Nif::NiTexturingProperty::DetailTexture:
textureName = "detailMap";
break;
case Nif::NiTexturingProperty::DecalTexture:
textureName = "decalMap";
break;
case Nif::NiTexturingProperty::GlossTexture:
textureName = "glossMap";
break;
default:
{
Log(Debug::Info) << "Unhandled texture stage " << i << " on shape \"" << nodeName
<< "\" in " << mFilename;
continue;
}
}
const unsigned int texUnit = boundTextures.size();
if (tex.mEnabled)
{
if (tex.mSourceTexture.empty() && texprop->mController.empty())
{
if (i == 0)
Log(Debug::Warning) << "Base texture is in use but empty on shape \"" << nodeName
<< "\" in " << mFilename;
continue;
}
if (!tex.mSourceTexture.empty())
attachNiSourceTexture(textureName, tex.mSourceTexture.getPtr(), tex.wrapS(), tex.wrapT(),
tex.mUVSet, stateset, boundTextures);
else
attachTexture(
textureName, nullptr, tex.wrapS(), tex.wrapT(), tex.mUVSet, stateset, boundTextures);
}
else
{
// Texture only comes from NiFlipController, so tex is ignored, set defaults
attachTexture(textureName, nullptr, true, true, 0, stateset, boundTextures);
}
if (i == Nif::NiTexturingProperty::GlowTexture)
{
stateset->setTextureAttributeAndModes(texUnit, createEmissiveTexEnv(), osg::StateAttribute::ON);
}
else if (i == Nif::NiTexturingProperty::DarkTexture)
{
osg::TexEnv* texEnv = new osg::TexEnv;
// Modulate both the colour and the alpha with the dark map.
texEnv->setMode(osg::TexEnv::MODULATE);
stateset->setTextureAttributeAndModes(texUnit, texEnv, osg::StateAttribute::ON);
}
else if (i == Nif::NiTexturingProperty::DetailTexture)
{
osg::TexEnvCombine* texEnv = new osg::TexEnvCombine;
// Modulate previous colour...
texEnv->setCombine_RGB(osg::TexEnvCombine::MODULATE);
texEnv->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
texEnv->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
// with the detail map's colour,
texEnv->setSource1_RGB(osg::TexEnvCombine::TEXTURE);
texEnv->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
// and a twist:
texEnv->setScale_RGB(2.f);
// Keep the previous alpha.
texEnv->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
texEnv->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
texEnv->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
stateset->setTextureAttributeAndModes(texUnit, texEnv, osg::StateAttribute::ON);
}
else if (i == Nif::NiTexturingProperty::BumpTexture)
{
// Bump maps offset the environment map.
// Set this texture to Off by default since we can't render it with the fixed-function pipeline
stateset->setTextureMode(texUnit, GL_TEXTURE_2D, osg::StateAttribute::OFF);
osg::Matrix2 bumpMapMatrix(texprop->mBumpMapMatrix.x(), texprop->mBumpMapMatrix.y(),
texprop->mBumpMapMatrix.z(), texprop->mBumpMapMatrix.w());
stateset->addUniform(new osg::Uniform("bumpMapMatrix", bumpMapMatrix));
stateset->addUniform(new osg::Uniform("envMapLumaBias", texprop->mEnvMapLumaBias));
}
else if (i == Nif::NiTexturingProperty::GlossTexture)
{
// A gloss map is an environment map mask.
// Gloss maps are only implemented in the object shaders as well.
stateset->setTextureMode(texUnit, GL_TEXTURE_2D, osg::StateAttribute::OFF);
}
else if (i == Nif::NiTexturingProperty::DecalTexture)
{
// This is only an inaccurate imitation of the original implementation,
// see https://github.com/niftools/nifskope/issues/184
osg::TexEnvCombine* texEnv = new osg::TexEnvCombine;
// Interpolate to the decal texture's colour...
texEnv->setCombine_RGB(osg::TexEnvCombine::INTERPOLATE);
texEnv->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
texEnv->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
// ...from the previous colour...
texEnv->setSource1_RGB(osg::TexEnvCombine::PREVIOUS);
texEnv->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
// using the decal texture's alpha as the factor.
texEnv->setSource2_RGB(osg::TexEnvCombine::TEXTURE);
texEnv->setOperand2_RGB(osg::TexEnvCombine::SRC_ALPHA);
// Keep the previous alpha.
texEnv->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
texEnv->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
texEnv->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
stateset->setTextureAttributeAndModes(texUnit, texEnv, osg::StateAttribute::ON);
}
}
}
handleTextureControllers(texprop, composite, stateset, animflags);
}
static Bgsm::MaterialFilePtr getShaderMaterial(
std::string_view path, Resource::BgsmFileManager* materialManager)
{
if (!materialManager)
return nullptr;
if (!Misc::StringUtils::ciEndsWith(path, ".bgem") && !Misc::StringUtils::ciEndsWith(path, ".bgsm"))
return nullptr;
std::string normalizedPath = Misc::ResourceHelpers::correctMaterialPath(path, materialManager->getVFS());
try
{
return materialManager->get(VFS::Path::Normalized(normalizedPath));
}
catch (std::exception& e)
{
Log(Debug::Error) << "Failed to load shader material: " << e.what();
return nullptr;
}
}
void handleShaderMaterialNodeProperties(
const Bgsm::MaterialFile* material, osg::StateSet* stateset, std::vector<unsigned int>& boundTextures) const
{
const unsigned int uvSet = 0;
const bool wrapS = material->wrapS();
const bool wrapT = material->wrapT();
if (material->mShaderType == Bgsm::ShaderType::Lighting)
{
const Bgsm::BGSMFile* bgsm = static_cast<const Bgsm::BGSMFile*>(material);
if (!bgsm->mDiffuseMap.empty())
attachExternalTexture(
"diffuseMap", bgsm->mDiffuseMap, wrapS, wrapT, uvSet, stateset, boundTextures);
if (!bgsm->mNormalMap.empty())
attachExternalTexture("normalMap", bgsm->mNormalMap, wrapS, wrapT, uvSet, stateset, boundTextures);
if (bgsm->mGlowMapEnabled && !bgsm->mGlowMap.empty())
attachExternalTexture("emissiveMap", bgsm->mGlowMap, wrapS, wrapT, uvSet, stateset, boundTextures);
if (bgsm->mTree)
stateset->addUniform(new osg::Uniform("useTreeAnim", true));
}
else if (material->mShaderType == Bgsm::ShaderType::Effect)
{
const Bgsm::BGEMFile* bgem = static_cast<const Bgsm::BGEMFile*>(material);
if (!bgem->mBaseMap.empty())
attachExternalTexture("diffuseMap", bgem->mBaseMap, wrapS, wrapT, uvSet, stateset, boundTextures);
bool useFalloff = bgem->mFalloff;
stateset->addUniform(new osg::Uniform("useFalloff", useFalloff));
if (useFalloff)
stateset->addUniform(new osg::Uniform("falloffParams", bgem->mFalloffParams));
}
if (material->mTwoSided)
stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
handleDepthFlags(stateset, material->mDepthTest, material->mDepthWrite);
}
void handleDecal(bool enabled, bool hasSortAlpha, osg::Node& node) const
{
if (!enabled)
return;
osg::ref_ptr<osg::StateSet> stateset = node.getOrCreateStateSet();
osg::ref_ptr<osg::PolygonOffset> polygonOffset(new osg::PolygonOffset);
polygonOffset->setUnits(SceneUtil::AutoDepth::isReversed() ? 1.f : -1.f);
polygonOffset->setFactor(SceneUtil::AutoDepth::isReversed() ? 0.65f : -0.65f);
polygonOffset = shareAttribute(polygonOffset);
stateset->setAttributeAndModes(polygonOffset, osg::StateAttribute::ON);
if (!mPushedSorter && !hasSortAlpha)
stateset->setRenderBinDetails(1, "SORT_BACK_TO_FRONT");
}
static void handleAlphaTesting(
bool enabled, osg::AlphaFunc::ComparisonFunction function, int threshold, osg::Node& node)
{
if (enabled)
{
osg::ref_ptr<osg::AlphaFunc> alphaFunc(new osg::AlphaFunc(function, threshold / 255.f));
alphaFunc = shareAttribute(alphaFunc);
node.getOrCreateStateSet()->setAttributeAndModes(alphaFunc, osg::StateAttribute::ON);
}
else if (osg::StateSet* stateset = node.getStateSet())
{
stateset->removeAttribute(osg::StateAttribute::ALPHAFUNC);
stateset->removeMode(GL_ALPHA_TEST);
}
}
void handleAlphaBlending(
bool enabled, int sourceMode, int destMode, bool sort, bool& hasSortAlpha, osg::Node& node) const
{
if (enabled)
{
osg::ref_ptr<osg::StateSet> stateset = node.getOrCreateStateSet();
osg::ref_ptr<osg::BlendFunc> blendFunc(
new osg::BlendFunc(getBlendMode(sourceMode), getBlendMode(destMode)));
// on AMD hardware, alpha still seems to be stored with an RGBA framebuffer with OpenGL.
// This might be mandated by the OpenGL 2.1 specification section 2.14.9, or might be a bug.
// Either way, D3D8.1 doesn't do that, so adapt the destination factor.
if (blendFunc->getDestination() == GL_DST_ALPHA)
blendFunc->setDestination(GL_ONE);
blendFunc = shareAttribute(blendFunc);
stateset->setAttributeAndModes(blendFunc, osg::StateAttribute::ON);
if (sort)
{
hasSortAlpha = true;
if (!mPushedSorter)
stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
}
else if (!mPushedSorter)
{
stateset->setRenderBinToInherit();
}
}
else if (osg::ref_ptr<osg::StateSet> stateset = node.getStateSet())
{
stateset->removeAttribute(osg::StateAttribute::BLENDFUNC);
stateset->removeMode(GL_BLEND);
if (!mPushedSorter)
stateset->setRenderBinToInherit();
}
}
void handleShaderMaterialDrawableProperties(const Bgsm::MaterialFile* shaderMat,
osg::ref_ptr<osg::Material> mat, osg::Node& node, bool& hasSortAlpha) const
{
mat->setAlpha(osg::Material::FRONT_AND_BACK, shaderMat->mTransparency);
handleAlphaTesting(shaderMat->mAlphaTest, osg::AlphaFunc::GREATER, shaderMat->mAlphaTestThreshold, node);
handleAlphaBlending(shaderMat->mAlphaBlend, shaderMat->mSourceBlendMode, shaderMat->mDestinationBlendMode,
true, hasSortAlpha, node);
handleDecal(shaderMat->mDecal, hasSortAlpha, node);
if (shaderMat->mShaderType == Bgsm::ShaderType::Lighting)
{
auto bgsm = static_cast<const Bgsm::BGSMFile*>(shaderMat);
mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(bgsm->mEmittanceColor, 1.f));
mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(bgsm->mSpecularColor, 1.f));
}
else if (shaderMat->mShaderType == Bgsm::ShaderType::Effect)
{
auto bgem = static_cast<const Bgsm::BGEMFile*>(shaderMat);
mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(bgem->mEmittanceColor, 1.f));
if (bgem->mSoft)
SceneUtil::setupSoftEffect(node, bgem->mSoftDepth, true, bgem->mSoftDepth);
}
}
void handleTextureSet(const Nif::BSShaderTextureSet* textureSet, bool wrapS, bool wrapT,
const std::string& nodeName, osg::StateSet* stateset, std::vector<unsigned int>& boundTextures) const
{
const unsigned int uvSet = 0;
for (size_t i = 0; i < textureSet->mTextures.size(); ++i)
{
if (textureSet->mTextures[i].empty())
continue;
switch (static_cast<Nif::BSShaderTextureSet::TextureType>(i))
{
case Nif::BSShaderTextureSet::TextureType::Base:
attachExternalTexture(
"diffuseMap", textureSet->mTextures[i], wrapS, wrapT, uvSet, stateset, boundTextures);
break;
case Nif::BSShaderTextureSet::TextureType::Normal:
attachExternalTexture(
"normalMap", textureSet->mTextures[i], wrapS, wrapT, uvSet, stateset, boundTextures);
break;
case Nif::BSShaderTextureSet::TextureType::Glow:
attachExternalTexture(
"emissiveMap", textureSet->mTextures[i], wrapS, wrapT, uvSet, stateset, boundTextures);
break;
default:
{
Log(Debug::Info) << "Unhandled texture stage " << i << " on shape \"" << nodeName << "\" in "
<< mFilename;
continue;
}
}
}
}
std::string_view getBSShaderPrefix(unsigned int type) const
{
switch (static_cast<Nif::BSShaderType>(type))
{
case Nif::BSShaderType::ShaderType_Default:
return "bs/default";
case Nif::BSShaderType::ShaderType_NoLighting:
return "bs/nolighting";
case Nif::BSShaderType::ShaderType_TallGrass:
case Nif::BSShaderType::ShaderType_Sky:
case Nif::BSShaderType::ShaderType_Skin:
case Nif::BSShaderType::ShaderType_Water:
case Nif::BSShaderType::ShaderType_Lighting30:
case Nif::BSShaderType::ShaderType_Tile:
Log(Debug::Warning) << "Unhandled BSShaderType " << type << " in " << mFilename;
return "bs/default";
}
Log(Debug::Warning) << "Unknown BSShaderType " << type << " in " << mFilename;
return "bs/default";
}
std::string_view getBSLightingShaderPrefix(unsigned int type) const
{
switch (static_cast<Nif::BSLightingShaderType>(type))
{
case Nif::BSLightingShaderType::ShaderType_Default:
return "bs/default";
case Nif::BSLightingShaderType::ShaderType_EnvMap:
case Nif::BSLightingShaderType::ShaderType_Glow:
case Nif::BSLightingShaderType::ShaderType_Parallax:
case Nif::BSLightingShaderType::ShaderType_FaceTint:
case Nif::BSLightingShaderType::ShaderType_SkinTint:
case Nif::BSLightingShaderType::ShaderType_HairTint:
case Nif::BSLightingShaderType::ShaderType_ParallaxOcc:
case Nif::BSLightingShaderType::ShaderType_MultitexLand:
case Nif::BSLightingShaderType::ShaderType_LODLand:
case Nif::BSLightingShaderType::ShaderType_Snow:
case Nif::BSLightingShaderType::ShaderType_MultiLayerParallax:
case Nif::BSLightingShaderType::ShaderType_TreeAnim:
case Nif::BSLightingShaderType::ShaderType_LODObjects:
case Nif::BSLightingShaderType::ShaderType_SparkleSnow:
case Nif::BSLightingShaderType::ShaderType_LODObjectsHD:
case Nif::BSLightingShaderType::ShaderType_EyeEnvmap:
case Nif::BSLightingShaderType::ShaderType_Cloud:
case Nif::BSLightingShaderType::ShaderType_LODNoise:
case Nif::BSLightingShaderType::ShaderType_MultitexLandLODBlend:
case Nif::BSLightingShaderType::ShaderType_Dismemberment:
case Nif::BSLightingShaderType::ShaderType_Terrain:
Log(Debug::Warning) << "Unhandled BSLightingShaderType " << type << " in " << mFilename;
return "bs/default";
}
Log(Debug::Warning) << "Unknown BSLightingShaderType " << type << " in " << mFilename;
return "bs/default";
}
void handleProperty(const Nif::NiProperty* property, osg::Node* node,
SceneUtil::CompositeStateSetUpdater* composite, std::vector<unsigned int>& boundTextures, int animflags,
bool hasStencilProperty)
{
switch (property->recType)
{
case Nif::RC_NiStencilProperty:
{
const Nif::NiStencilProperty* stencilprop = static_cast<const Nif::NiStencilProperty*>(property);
osg::ref_ptr<osg::FrontFace> frontFace = new osg::FrontFace;
using DrawMode = Nif::NiStencilProperty::DrawMode;
switch (stencilprop->mDrawMode)
{
case DrawMode::Clockwise:
frontFace->setMode(osg::FrontFace::CLOCKWISE);
break;
case DrawMode::Default:
case DrawMode::CounterClockwise:
case DrawMode::Both:
default:
frontFace->setMode(osg::FrontFace::COUNTER_CLOCKWISE);
break;
}
frontFace = shareAttribute(frontFace);
osg::StateSet* stateset = node->getOrCreateStateSet();
stateset->setAttribute(frontFace, osg::StateAttribute::ON);
if (stencilprop->mDrawMode == DrawMode::Both)
stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
else
stateset->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
if (stencilprop->mEnabled)
{
mHasStencilProperty = true;
osg::ref_ptr<osg::Stencil> stencil = new osg::Stencil;
stencil->setFunction(getStencilFunction(stencilprop->mTestFunction), stencilprop->mStencilRef,
stencilprop->mStencilMask);
stencil->setStencilFailOperation(getStencilOperation(stencilprop->mFailAction));
stencil->setStencilPassAndDepthFailOperation(getStencilOperation(stencilprop->mZFailAction));
stencil->setStencilPassAndDepthPassOperation(getStencilOperation(stencilprop->mPassAction));
stencil = shareAttribute(stencil);
stateset->setAttributeAndModes(stencil, osg::StateAttribute::ON);
}
break;
}
case Nif::RC_NiWireframeProperty:
{
const Nif::NiWireframeProperty* wireprop = static_cast<const Nif::NiWireframeProperty*>(property);
osg::ref_ptr<osg::PolygonMode> mode = new osg::PolygonMode;
mode->setMode(osg::PolygonMode::FRONT_AND_BACK,
wireprop->mEnable ? osg::PolygonMode::LINE : osg::PolygonMode::FILL);
mode = shareAttribute(mode);
node->getOrCreateStateSet()->setAttributeAndModes(mode, osg::StateAttribute::ON);
break;
}
case Nif::RC_NiZBufferProperty:
{
const Nif::NiZBufferProperty* zprop = static_cast<const Nif::NiZBufferProperty*>(property);
osg::StateSet* stateset = node->getOrCreateStateSet();
// The test function from this property seems to be ignored.
handleDepthFlags(stateset, zprop->depthTest(), zprop->depthWrite());
break;
}
// OSG groups the material properties that NIFs have separate, so we have to parse them all again when
// one changed
case Nif::RC_NiMaterialProperty:
case Nif::RC_NiVertexColorProperty:
case Nif::RC_NiSpecularProperty:
{
// Handled on drawable level so we know whether vertex colors are available
break;
}
case Nif::RC_NiAlphaProperty:
{
// Handled on drawable level to prevent RenderBin nesting issues
break;
}
case Nif::RC_NiTexturingProperty:
{
const Nif::NiTexturingProperty* texprop = static_cast<const Nif::NiTexturingProperty*>(property);
osg::StateSet* stateset = node->getOrCreateStateSet();
handleTextureProperty(texprop, node->getName(), stateset, composite, boundTextures, animflags);
node->setUserValue("applyMode", static_cast<int>(texprop->mApplyMode));
break;
}
case Nif::RC_BSShaderPPLightingProperty:
{
auto texprop = static_cast<const Nif::BSShaderPPLightingProperty*>(property);
bool shaderRequired = true;
node->setUserValue("shaderPrefix", std::string(getBSShaderPrefix(texprop->mType)));
node->setUserValue("shaderRequired", shaderRequired);
osg::StateSet* stateset = node->getOrCreateStateSet();
clearBoundTextures(stateset, boundTextures);
if (!texprop->mTextureSet.empty())
handleTextureSet(texprop->mTextureSet.getPtr(), texprop->wrapS(), texprop->wrapT(),
node->getName(), stateset, boundTextures);
handleTextureControllers(texprop, composite, stateset, animflags);
if (texprop->refraction())
SceneUtil::setupDistortion(*node, texprop->mRefraction.mStrength);
break;
}
case Nif::RC_BSShaderNoLightingProperty:
{
auto texprop = static_cast<const Nif::BSShaderNoLightingProperty*>(property);
bool shaderRequired = true;
bool useFalloff = false;
node->setUserValue("shaderPrefix", std::string(getBSShaderPrefix(texprop->mType)));
node->setUserValue("shaderRequired", shaderRequired);
osg::StateSet* stateset = node->getOrCreateStateSet();
clearBoundTextures(stateset, boundTextures);
if (!texprop->mFilename.empty())
{
const unsigned int uvSet = 0;
attachExternalTexture("diffuseMap", texprop->mFilename, texprop->wrapS(), texprop->wrapT(),
uvSet, stateset, boundTextures);
}
if (mBethVersion >= 27)
{
useFalloff = true;
stateset->addUniform(new osg::Uniform("falloffParams", texprop->mFalloffParams));
}
stateset->addUniform(new osg::Uniform("useFalloff", useFalloff));
handleTextureControllers(texprop, composite, stateset, animflags);
handleDepthFlags(stateset, texprop->depthTest(), texprop->depthWrite());
break;
}
case Nif::RC_BSLightingShaderProperty:
{
auto texprop = static_cast<const Nif::BSLightingShaderProperty*>(property);
bool shaderRequired = true;
node->setUserValue("shaderPrefix", std::string(getBSLightingShaderPrefix(texprop->mType)));
node->setUserValue("shaderRequired", shaderRequired);
osg::StateSet* stateset = node->getOrCreateStateSet();
clearBoundTextures(stateset, boundTextures);
if (Bgsm::MaterialFilePtr material = getShaderMaterial(texprop->mName, mMaterialManager))
{
handleShaderMaterialNodeProperties(material.get(), stateset, boundTextures);
break;
}
if (!texprop->mTextureSet.empty())
handleTextureSet(texprop->mTextureSet.getPtr(), texprop->wrapS(), texprop->wrapT(),
node->getName(), stateset, boundTextures);
handleTextureControllers(texprop, composite, stateset, animflags);
if (texprop->doubleSided())
stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
if (texprop->treeAnim())
stateset->addUniform(new osg::Uniform("useTreeAnim", true));
handleDepthFlags(stateset, texprop->depthTest(), texprop->depthWrite());
if (texprop->refraction())
SceneUtil::setupDistortion(*node, texprop->mRefractionStrength);
break;
}
case Nif::RC_BSEffectShaderProperty:
{
auto texprop = static_cast<const Nif::BSEffectShaderProperty*>(property);
bool shaderRequired = true;
// TODO: implement BSEffectShader as a shader
node->setUserValue("shaderPrefix", std::string("bs/nolighting"));
node->setUserValue("shaderRequired", shaderRequired);
osg::StateSet* stateset = node->getOrCreateStateSet();
clearBoundTextures(stateset, boundTextures);
if (Bgsm::MaterialFilePtr material = getShaderMaterial(texprop->mName, mMaterialManager))
{
handleShaderMaterialNodeProperties(material.get(), stateset, boundTextures);
break;
}
if (!texprop->mSourceTexture.empty())
{
const unsigned int uvSet = 0;
unsigned int texUnit = boundTextures.size();
attachExternalTexture("diffuseMap", texprop->mSourceTexture, texprop->wrapS(), texprop->wrapT(),
uvSet, stateset, boundTextures);
{
osg::ref_ptr<osg::TexMat> texMat(new osg::TexMat);
// This handles 20.2.0.7 UV settings like 4.0.0.2 UV settings (see NifOsg::UVController)
// TODO: verify
osg::Vec3f uvOrigin(0.5f, 0.5f, 0.f);
osg::Vec3f uvScale(texprop->mUVScale.x(), texprop->mUVScale.y(), 1.f);
osg::Vec3f uvTrans(-texprop->mUVOffset.x(), -texprop->mUVOffset.y(), 0.f);
osg::Matrixf mat = osg::Matrixf::translate(uvOrigin);
mat.preMultScale(uvScale);
mat.preMultTranslate(-uvOrigin);
mat.setTrans(mat.getTrans() + uvTrans);
texMat->setMatrix(mat);
stateset->setTextureAttributeAndModes(texUnit, texMat, osg::StateAttribute::ON);
}
}
bool useFalloff = texprop->useFalloff();
stateset->addUniform(new osg::Uniform("useFalloff", useFalloff));
if (useFalloff)
stateset->addUniform(new osg::Uniform("falloffParams", texprop->mFalloffParams));
handleTextureControllers(texprop, composite, stateset, animflags);
if (texprop->doubleSided())
stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
handleDepthFlags(stateset, texprop->depthTest(), texprop->depthWrite());
break;
}
case Nif::RC_NiFogProperty:
{
const Nif::NiFogProperty* fogprop = static_cast<const Nif::NiFogProperty*>(property);
osg::StateSet* stateset = node->getOrCreateStateSet();
// Vertex alpha mode appears to be broken
if (!fogprop->vertexAlpha() && fogprop->enabled())
{
osg::ref_ptr<NifOsg::Fog> fog = new NifOsg::Fog;
fog->setMode(osg::Fog::LINEAR);
fog->setColor(osg::Vec4f(fogprop->mColour, 1.f));
fog->setDepth(fogprop->mFogDepth);
fog = shareAttribute(fog);
stateset->setAttributeAndModes(fog, osg::StateAttribute::ON);
// Intentionally ignoring radial fog flag
// We don't really want to override the global setting
}
else
{
osg::ref_ptr<osg::Fog> fog = new osg::Fog;
// Shaders don't respect glDisable(GL_FOG)
fog->setMode(osg::Fog::LINEAR);
fog->setStart(10000000);
fog->setEnd(10000000);
fog = shareAttribute(fog);
stateset->setAttributeAndModes(fog, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
}
break;
}
// unused by mw
case Nif::RC_NiShadeProperty:
case Nif::RC_NiDitherProperty:
{
break;
}
default:
Log(Debug::Info) << "Unhandled " << property->recName << " in " << mFilename;
break;
}
}
struct CompareStateAttribute
{
bool operator()(
const osg::ref_ptr<osg::StateAttribute>& left, const osg::ref_ptr<osg::StateAttribute>& right) const
{
return left->compare(*right) < 0;
}
};
// global sharing of State Attributes will reduce the number of GL calls as the osg::State will check by pointer
// to see if state is the same
template <class Attribute>
static Attribute* shareAttribute(const osg::ref_ptr<Attribute>& attr)
{
using Cache = std::set<osg::ref_ptr<Attribute>, CompareStateAttribute>;
static Cache sCache;
static std::mutex sMutex;
std::lock_guard<std::mutex> lock(sMutex);
typename Cache::iterator found = sCache.find(attr);
if (found == sCache.end())
found = sCache.insert(attr).first;
return *found;
}
void applyDrawableProperties(osg::Node* node, const std::vector<const Nif::NiProperty*>& properties,
SceneUtil::CompositeStateSetUpdater* composite, bool hasVertexColors, int animflags)
{
// Specular lighting is enabled by default, but there's a quirk...
bool specEnabled = true;
osg::ref_ptr<osg::Material> mat(new osg::Material);
mat->setColorMode(hasVertexColors ? osg::Material::AMBIENT_AND_DIFFUSE : osg::Material::OFF);
// NIF material defaults don't match OpenGL defaults
mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1));
mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1));
bool hasMatCtrl = false;
bool hasSortAlpha = false;
auto setBin_BackToFront = [](osg::StateSet* ss) { ss->setRenderBinDetails(0, "SORT_BACK_TO_FRONT"); };
auto setBin_Traversal = [](osg::StateSet* ss) { ss->setRenderBinDetails(2, "TraversalOrderBin"); };
auto lightmode = Nif::NiVertexColorProperty::LightMode::LightMode_EmiAmbDif;
float emissiveMult = 1.f;
float specStrength = 1.f;
for (const Nif::NiProperty* property : properties)
{
switch (property->recType)
{
case Nif::RC_NiSpecularProperty:
{
// Specular property can turn specular lighting off.
// FIXME: NiMaterialColorController doesn't care about this.
auto specprop = static_cast<const Nif::NiSpecularProperty*>(property);
specEnabled = specprop->mEnable;
break;
}
case Nif::RC_NiMaterialProperty:
{
const Nif::NiMaterialProperty* matprop = static_cast<const Nif::NiMaterialProperty*>(property);
mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(matprop->mDiffuse, matprop->mAlpha));
mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(matprop->mAmbient, 1.f));
mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(matprop->mEmissive, 1.f));
emissiveMult = matprop->mEmissiveMult;
mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(matprop->mSpecular, 1.f));
// NIFs may provide specular exponents way above OpenGL's limit.
// They can't be used properly, but we don't need OSG to constantly harass us about it.
float glossiness = std::clamp(matprop->mGlossiness, 0.f, 128.f);
mat->setShininess(osg::Material::FRONT_AND_BACK, glossiness);
if (!matprop->mController.empty())
{
hasMatCtrl = true;
handleMaterialControllers(matprop, composite, animflags, mat);
}
break;
}
case Nif::RC_NiVertexColorProperty:
{
const Nif::NiVertexColorProperty* vertprop
= static_cast<const Nif::NiVertexColorProperty*>(property);
using VertexMode = Nif::NiVertexColorProperty::VertexMode;
switch (vertprop->mVertexMode)
{
case VertexMode::VertMode_SrcIgnore:
{
mat->setColorMode(osg::Material::OFF);
break;
}
case VertexMode::VertMode_SrcEmissive:
{
mat->setColorMode(osg::Material::EMISSION);
break;
}
case VertexMode::VertMode_SrcAmbDif:
{
lightmode = vertprop->mLightingMode;
using LightMode = Nif::NiVertexColorProperty::LightMode;
switch (lightmode)
{
case LightMode::LightMode_Emissive:
{
mat->setColorMode(osg::Material::OFF);
break;
}
case LightMode::LightMode_EmiAmbDif:
default:
{
mat->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
break;
}
}
break;
}
}
break;
}
case Nif::RC_NiAlphaProperty:
{
const Nif::NiAlphaProperty* alphaprop = static_cast<const Nif::NiAlphaProperty*>(property);
handleAlphaBlending(alphaprop->useAlphaBlending(), alphaprop->sourceBlendMode(),
alphaprop->destinationBlendMode(), !alphaprop->noSorter(), hasSortAlpha, *node);
handleAlphaTesting(alphaprop->useAlphaTesting(), getTestMode(alphaprop->alphaTestMode()),
alphaprop->mThreshold, *node);
break;
}
case Nif::RC_BSShaderPPLightingProperty:
{
auto shaderprop = static_cast<const Nif::BSShaderPPLightingProperty*>(property);
specEnabled = shaderprop->specular();
break;
}
case Nif::RC_BSLightingShaderProperty:
{
auto shaderprop = static_cast<const Nif::BSLightingShaderProperty*>(property);
if (Bgsm::MaterialFilePtr shaderMat = getShaderMaterial(shaderprop->mName, mMaterialManager))
{
handleShaderMaterialDrawableProperties(shaderMat.get(), mat, *node, hasSortAlpha);
if (shaderMat->mShaderType == Bgsm::ShaderType::Lighting)
{
auto bgsm = static_cast<const Bgsm::BGSMFile*>(shaderMat.get());
specEnabled = false; // bgsm->mSpecularEnabled; TODO: PBR specular lighting
specStrength = 1.f; // bgsm->mSpecularMult;
emissiveMult = bgsm->mEmittanceMult;
}
break;
}
mat->setAlpha(osg::Material::FRONT_AND_BACK, shaderprop->mAlpha);
mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(shaderprop->mEmissive, 1.f));
mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(shaderprop->mSpecular, 1.f));
float glossiness = std::clamp(shaderprop->mGlossiness, 0.f, 128.f);
mat->setShininess(osg::Material::FRONT_AND_BACK, glossiness);
emissiveMult = shaderprop->mEmissiveMult;
specStrength = shaderprop->mSpecStrength;
specEnabled = shaderprop->specular();
handleDecal(shaderprop->decal(), hasSortAlpha, *node);
break;
}
case Nif::RC_BSEffectShaderProperty:
{
auto shaderprop = static_cast<const Nif::BSEffectShaderProperty*>(property);
if (Bgsm::MaterialFilePtr shaderMat = getShaderMaterial(shaderprop->mName, mMaterialManager))
{
handleShaderMaterialDrawableProperties(shaderMat.get(), mat, *node, hasSortAlpha);
break;
}
handleDecal(shaderprop->decal(), hasSortAlpha, *node);
if (shaderprop->softEffect())
SceneUtil::setupSoftEffect(
*node, shaderprop->mFalloffDepth, true, shaderprop->mFalloffDepth);
break;
}
default:
break;
}
}
// While NetImmerse and Gamebryo support specular lighting, Morrowind has its support disabled.
if (mVersion <= Nif::NIFFile::VER_MW || !specEnabled)
{
mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, 0.f));
mat->setShininess(osg::Material::FRONT_AND_BACK, 0.f);
specStrength = 1.f;
}
if (lightmode == Nif::NiVertexColorProperty::LightMode::LightMode_Emissive)
{
osg::Vec4f diffuse = mat->getDiffuse(osg::Material::FRONT_AND_BACK);
diffuse = osg::Vec4f(0, 0, 0, diffuse.a());
mat->setDiffuse(osg::Material::FRONT_AND_BACK, diffuse);
mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f());
}
// If we're told to use vertex colors but there are none to use, use a default color instead.
if (!hasVertexColors)
{
switch (mat->getColorMode())
{
case osg::Material::AMBIENT:
mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1));
break;
case osg::Material::AMBIENT_AND_DIFFUSE:
mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1));
mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1));
break;
case osg::Material::EMISSION:
mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1));
break;
default:
break;
}
mat->setColorMode(osg::Material::OFF);
}
if (hasMatCtrl || mat->getColorMode() != osg::Material::OFF
|| mat->getEmission(osg::Material::FRONT_AND_BACK) != osg::Vec4f(0, 0, 0, 1)
|| mat->getDiffuse(osg::Material::FRONT_AND_BACK) != osg::Vec4f(1, 1, 1, 1)
|| mat->getAmbient(osg::Material::FRONT_AND_BACK) != osg::Vec4f(1, 1, 1, 1)
|| mat->getShininess(osg::Material::FRONT_AND_BACK) != 0
|| mat->getSpecular(osg::Material::FRONT_AND_BACK) != osg::Vec4f(0.f, 0.f, 0.f, 0.f))
{
mat = shareAttribute(mat);
node->getOrCreateStateSet()->setAttributeAndModes(mat, osg::StateAttribute::ON);
}
if (emissiveMult != 1.f)
node->getOrCreateStateSet()->addUniform(new osg::Uniform("emissiveMult", emissiveMult));
if (specStrength != 1.f)
node->getOrCreateStateSet()->addUniform(new osg::Uniform("specStrength", specStrength));
if (!mPushedSorter)
{
if (!hasSortAlpha && mHasStencilProperty)
setBin_Traversal(node->getOrCreateStateSet());
return;
}
osg::StateSet* stateset = node->getOrCreateStateSet();
auto assignBin = [&](Nif::NiSortAdjustNode::SortingMode mode, int type) {
if (mode == Nif::NiSortAdjustNode::SortingMode::Off)
{
setBin_Traversal(stateset);
return;
}
if (type == Nif::RC_NiAlphaAccumulator)
{
if (hasSortAlpha)
setBin_BackToFront(stateset);
else
setBin_Traversal(stateset);
}
else if (type == Nif::RC_NiClusterAccumulator)
setBin_BackToFront(stateset);
else
Log(Debug::Error) << "Unrecognized NiAccumulator in " << mFilename;
};
switch (mPushedSorter->mMode)
{
case Nif::NiSortAdjustNode::SortingMode::Inherit:
{
if (mLastAppliedNoInheritSorter)
assignBin(mLastAppliedNoInheritSorter->mMode, mLastAppliedNoInheritSorter->mSubSorter->recType);
else
assignBin(mPushedSorter->mMode, Nif::RC_NiAlphaAccumulator);
break;
}
case Nif::NiSortAdjustNode::SortingMode::Off:
{
setBin_Traversal(stateset);
break;
}
case Nif::NiSortAdjustNode::SortingMode::Subsort:
{
assignBin(mPushedSorter->mMode, mPushedSorter->mSubSorter->recType);
break;
}
}
}
};
osg::ref_ptr<osg::Node> Loader::load(
Nif::FileView file, Resource::ImageManager* imageManager, Resource::BgsmFileManager* materialManager)
{
LoaderImpl impl(file.getFilename(), file.getVersion(), file.getUserVersion(), file.getBethVersion());
impl.mMaterialManager = materialManager;
impl.mImageManager = imageManager;
return impl.load(file);
}
void Loader::loadKf(Nif::FileView kf, SceneUtil::KeyframeHolder& target)
{
LoaderImpl impl(kf.getFilename(), kf.getVersion(), kf.getUserVersion(), kf.getBethVersion());
impl.loadKf(kf, target);
}
}
| 142,607
|
C++
|
.cpp
| 2,660
| 36.232707
| 120
| 0.53867
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,669
|
helpviewer.cpp
|
OpenMW_openmw/components/misc/helpviewer.cpp
|
#include "helpviewer.hpp"
#include <QDesktopServices>
#include <QString>
#include <QUrl>
#include <components/version/version.hpp>
void Misc::HelpViewer::openHelp(const char* url)
{
std::string_view docsUrl = Version::getDocumentationUrl();
QString link = QString::fromUtf8(docsUrl.data(), docsUrl.size());
link.append(url);
QDesktopServices::openUrl(QUrl(link));
}
| 385
|
C++
|
.cpp
| 12
| 29.5
| 69
| 0.751351
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,670
|
color.cpp
|
OpenMW_openmw/components/misc/color.cpp
|
#include "color.hpp"
#include <algorithm>
#include <array>
#include <charconv>
#include <sstream>
#include <system_error>
namespace Misc
{
Color::Color(float r, float g, float b, float a)
: mR(std::clamp(r, 0.f, 1.f))
, mG(std::clamp(g, 0.f, 1.f))
, mB(std::clamp(b, 0.f, 1.f))
, mA(std::clamp(a, 0.f, 1.f))
{
}
std::string Color::toString() const
{
std::ostringstream ss;
ss << "(" << r() << ", " << g() << ", " << b() << ", " << a() << ')';
return ss.str();
}
Color Color::fromHex(std::string_view hex)
{
if (hex.size() != 6)
throw std::logic_error(std::string("Invalid hex color: ") += hex);
std::array<float, 3> rgb;
for (size_t i = 0; i < rgb.size(); i++)
{
auto sub = hex.substr(i * 2, 2);
int v = 0;
auto [_, ec] = std::from_chars(sub.data(), sub.data() + sub.size(), v, 16);
if (ec != std::errc())
throw std::logic_error(std::string("Invalid hex color: ") += hex);
rgb[i] = v / 255.0f;
}
return Color(rgb[0], rgb[1], rgb[2], 1);
}
std::string Color::toHex() const
{
std::string result(6, '0');
std::array<float, 3> rgb = { mR, mG, mB };
for (size_t i = 0; i < rgb.size(); i++)
{
int b = static_cast<int>(rgb[i] * 255.0f);
auto [_, ec] = std::to_chars(result.data() + i * 2, result.data() + (i + 1) * 2, b, 16);
if (ec != std::errc())
throw std::logic_error("Error when converting number to base 16");
}
return result;
}
bool operator==(const Color& l, const Color& r)
{
return l.mR == r.mR && l.mG == r.mG && l.mB == r.mB && l.mA == r.mA;
}
}
| 1,817
|
C++
|
.cpp
| 55
| 25.381818
| 100
| 0.472665
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,671
|
scalableicon.cpp
|
OpenMW_openmw/components/misc/scalableicon.cpp
|
#include "scalableicon.hpp"
#include <QApplication>
#include <QDataStream>
#include <QDebug>
#include <QDir>
#include <QFont>
#include <QIODevice>
#include <QIconEngine>
#include <QPainter>
#include <QPalette>
#include <QtSvg/QSvgRenderer>
namespace Misc
{
Q_GLOBAL_STATIC(QSet<ScalableIcon*>, ScalableIconInstances)
ScalableIcon::ScalableIcon(const QByteArray& svgContent)
: mTemplate(svgContent)
{
update();
ScalableIconInstances->insert(this);
}
ScalableIcon::~ScalableIcon()
{
if (!ScalableIconInstances.isDestroyed())
{
ScalableIconInstances->remove(this);
}
}
QIcon Misc::ScalableIcon::load(const QString& fileName)
{
if (fileName.isEmpty())
return QIcon();
QFile iconFile(fileName);
if (!iconFile.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open icon file:" << fileName;
return QIcon();
}
auto content = iconFile.readAll();
if (!content.startsWith("<?xml"))
return QIcon(fileName);
return QIcon(new ScalableIcon(content));
}
void ScalableIcon::update()
{
constexpr const char* templateColor = "#4d4d4d";
mContent = mTemplate;
auto themeColor = QApplication::palette().text().color().name().toLower().toLatin1();
mContent.replace(templateColor, themeColor);
}
void ScalableIcon::updateAllIcons()
{
for (auto engine : *ScalableIconInstances)
{
engine->update();
}
}
void ScalableIcon::paint(QPainter* painter, const QRect& rect, QIcon::Mode mode, QIcon::State state)
{
Q_UNUSED(mode);
Q_UNUSED(state);
QSvgRenderer renderer(mContent);
renderer.render(painter, rect);
}
QIconEngine* ScalableIcon::clone() const
{
return new ScalableIcon(*this);
}
QPixmap ScalableIcon::pixmap(const QSize& size, QIcon::Mode mode, QIcon::State state)
{
QPixmap pix = QPixmap(size);
pix.fill(Qt::transparent);
QPainter painter(&pix);
QRect r(QPoint(0.0, 0.0), size);
this->paint(&painter, r, mode, state);
if (mode != QIcon::Disabled)
return pix;
// For disabled icons use grayscale icons with 50% transparency
QImage img = pix.toImage();
for (int x = 0; x < img.width(); x++)
{
for (int y = 0; y < img.height(); y++)
{
QColor n = img.pixelColor(x, y);
int gray = qGray(n.red(), n.green(), n.blue());
img.setPixelColor(x, y, QColor(gray, gray, gray, n.alpha() / 2));
}
}
return QPixmap::fromImage(img, Qt::NoFormatConversion);
}
}
| 2,816
|
C++
|
.cpp
| 90
| 23.711111
| 104
| 0.597561
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,672
|
osguservalues.cpp
|
OpenMW_openmw/components/misc/osguservalues.cpp
|
#include "osguservalues.hpp"
namespace Misc
{
const std::string OsgUserValues::sFileHash = "fileHash";
const std::string OsgUserValues::sExtraData = "xData";
const std::string OsgUserValues::sXSoftEffect = "xSoftEffect";
}
| 236
|
C++
|
.cpp
| 7
| 30.857143
| 66
| 0.754386
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,673
|
display.cpp
|
OpenMW_openmw/components/misc/display.cpp
|
#include "display.hpp"
#include <numeric>
#include <string>
#include <components/misc/strings/format.hpp>
namespace Misc
{
std::string getResolutionText(int x, int y, const std::string& format)
{
int gcd = std::gcd(x, y);
if (gcd == 0)
return std::string();
int xaspect = x / gcd;
int yaspect = y / gcd;
// It is unclear how to handle 90-degree screen rotation properly.
// So far only swap aspects, apply custom formatting logic and then swap back.
// As result, 1920 x 1200 is displayed as "1200 x 1920 (10:16)"
bool flipped = false;
if (yaspect > xaspect)
{
flipped = true;
std::swap(xaspect, yaspect);
}
// 683:384 (used in 1366 x 768) is usually referred as 16:9
if (xaspect == 683 && yaspect == 384)
{
xaspect = 16;
yaspect = 9;
}
// 85:48 (used in 1360 x 768) is usually referred as 16:9
else if (xaspect == 85 && yaspect == 48)
{
xaspect = 16;
yaspect = 9;
}
// 49:36 (used in 1176 x 864) is usually referred as 4:3
else if (xaspect == 49 && yaspect == 36)
{
xaspect = 4;
yaspect = 3;
}
// 39:29 (used in 624 x 484) is usually referred as 4:3
else if (xaspect == 39 && yaspect == 29)
{
xaspect = 4;
yaspect = 3;
}
// 8:5 (used in 1440 x 900) is usually referred as 16:10
else if (xaspect == 8 && yaspect == 5)
{
xaspect = 16;
yaspect = 10;
}
// 5:3 (used in 1280 x 768) is usually referred as 15:9
else if (xaspect == 5 && yaspect == 3)
{
xaspect = 15;
yaspect = 9;
}
else
{
// everything between 21:9 and 22:9
// is usually referred as 21:9
float ratio = static_cast<float>(xaspect) / yaspect;
if (ratio >= 21 / 9.f && ratio < 22 / 9.f)
{
xaspect = 21;
yaspect = 9;
}
}
if (flipped)
std::swap(xaspect, yaspect);
return Misc::StringUtils::format(format, x, y, xaspect, yaspect);
}
}
| 2,327
|
C++
|
.cpp
| 74
| 21.851351
| 86
| 0.495768
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,674
|
rng.cpp
|
OpenMW_openmw/components/misc/rng.cpp
|
#include "rng.hpp"
#include <chrono>
#include <random>
#include <sstream>
namespace Misc::Rng
{
static Generator sGenerator;
Generator& getGenerator()
{
return sGenerator;
}
std::string serialize(const Generator& prng)
{
std::stringstream ss;
ss << prng;
return ss.str();
}
void deserialize(std::string_view data, Generator& prng)
{
std::stringstream ss;
ss << data;
ss.seekg(0);
ss >> prng;
}
unsigned int generateDefaultSeed()
{
auto res = static_cast<unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count());
return res;
}
void init(unsigned int seed)
{
sGenerator.seed(seed);
}
float rollProbability()
{
return std::uniform_real_distribution<float>(0, 1 - std::numeric_limits<float>::epsilon())(getGenerator());
}
float rollProbability(Generator& prng)
{
return std::uniform_real_distribution<float>(0, 1 - std::numeric_limits<float>::epsilon())(prng);
}
float rollClosedProbability()
{
return std::uniform_real_distribution<float>(0, 1)(getGenerator());
}
float rollClosedProbability(Generator& prng)
{
return std::uniform_real_distribution<float>(0, 1)(prng);
}
int rollDice(int max)
{
return max > 0 ? std::uniform_int_distribution<int>(0, max - 1)(getGenerator()) : 0;
}
int rollDice(int max, Generator& prng)
{
return max > 0 ? std::uniform_int_distribution<int>(0, max - 1)(prng) : 0;
}
float deviate(float mean, float deviation)
{
return std::uniform_real_distribution<float>(mean - deviation, mean + deviation)(getGenerator());
}
float deviate(float mean, float deviation, Generator& prng)
{
return std::uniform_real_distribution<float>(mean - deviation, mean + deviation)(prng);
}
}
| 1,953
|
C++
|
.cpp
| 66
| 23.590909
| 115
| 0.630819
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,675
|
messageformatparser.cpp
|
OpenMW_openmw/components/misc/messageformatparser.cpp
|
#include "messageformatparser.hpp"
namespace Misc
{
MessageFormatParser::~MessageFormatParser() {}
void MessageFormatParser::process(std::string_view m)
{
for (unsigned int i = 0; i < m.size(); ++i)
{
if (m[i] == '%')
{
if (++i < m.size())
{
if (m[i] == '%')
visitedCharacter('%');
else
{
char pad = ' ';
if (m[i] == '0' || m[i] == ' ')
{
pad = m[i];
++i;
}
int width = 0;
bool widthSet = false;
while (i < m.size() && m[i] >= '0' && m[i] <= '9')
{
width = width * 10 + (m[i] - '0');
widthSet = true;
++i;
}
if (i < m.size())
{
int precision = -1;
if (m[i] == '.')
{
precision = 0;
while (++i < m.size() && m[i] >= '0' && m[i] <= '9')
{
precision = precision * 10 + (m[i] - '0');
}
}
if (i < m.size())
{
width = (widthSet) ? width : -1;
if (m[i] == 'S' || m[i] == 's')
visitedPlaceholder(StringPlaceholder, pad, width, precision, FixedNotation);
else if (m[i] == 'd' || m[i] == 'i')
visitedPlaceholder(IntegerPlaceholder, pad, width, precision, FixedNotation);
else if (m[i] == 'f' || m[i] == 'F')
visitedPlaceholder(FloatPlaceholder, pad, width, precision, FixedNotation);
else if (m[i] == 'e' || m[i] == 'E')
visitedPlaceholder(FloatPlaceholder, pad, width, precision, ScientificNotation);
else if (m[i] == 'g' || m[i] == 'G')
visitedPlaceholder(FloatPlaceholder, pad, width, precision, ShortestNotation);
}
}
}
}
}
else
{
visitedCharacter(m[i]);
}
}
}
}
| 2,803
|
C++
|
.cpp
| 66
| 19.560606
| 116
| 0.28744
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,676
|
compression.cpp
|
OpenMW_openmw/components/misc/compression.cpp
|
#include "compression.hpp"
#include <lz4.h>
#include <cstddef>
#include <cstring>
#include <stdexcept>
#include <string>
#include <vector>
namespace Misc
{
std::vector<std::byte> compress(const std::vector<std::byte>& data)
{
const std::size_t originalSize = data.size();
std::vector<std::byte> result(
static_cast<std::size_t>(LZ4_compressBound(static_cast<int>(originalSize)) + sizeof(originalSize)));
const int size = LZ4_compress_default(reinterpret_cast<const char*>(data.data()),
reinterpret_cast<char*>(result.data()) + sizeof(originalSize), static_cast<int>(data.size()),
static_cast<int>(result.size() - sizeof(originalSize)));
if (size == 0)
throw std::runtime_error("Failed to compress");
std::memcpy(result.data(), &originalSize, sizeof(originalSize));
result.resize(static_cast<std::size_t>(size) + sizeof(originalSize));
return result;
}
std::vector<std::byte> decompress(const std::vector<std::byte>& data)
{
std::size_t originalSize;
std::memcpy(&originalSize, data.data(), sizeof(originalSize));
std::vector<std::byte> result(originalSize);
const int size = LZ4_decompress_safe(reinterpret_cast<const char*>(data.data()) + sizeof(originalSize),
reinterpret_cast<char*>(result.data()), static_cast<int>(data.size() - sizeof(originalSize)),
static_cast<int>(result.size()));
if (size < 0)
throw std::runtime_error("Failed to decompress");
if (originalSize != static_cast<std::size_t>(size))
throw std::runtime_error("Size of decompressed data (" + std::to_string(size) + ") doesn't match stored ("
+ std::to_string(originalSize) + ")");
return result;
}
}
| 1,823
|
C++
|
.cpp
| 39
| 39.282051
| 118
| 0.63764
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,677
|
resourcehelpers.cpp
|
OpenMW_openmw/components/misc/resourcehelpers.cpp
|
#include "resourcehelpers.hpp"
#include <algorithm>
#include <sstream>
#include <string_view>
#include <components/esm/common.hpp>
#include <components/esm/refid.hpp>
#include <components/misc/pathhelpers.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/pathutil.hpp>
namespace
{
bool changeExtension(std::string& path, std::string_view ext)
{
std::string::size_type pos = path.rfind('.');
if (pos != std::string::npos && path.compare(pos, path.length() - pos, ext) != 0)
{
path.replace(pos, path.length(), ext);
return true;
}
return false;
}
}
bool Misc::ResourceHelpers::changeExtensionToDds(std::string& path)
{
return changeExtension(path, ".dds");
}
std::string Misc::ResourceHelpers::correctResourcePath(
std::span<const std::string_view> topLevelDirectories, std::string_view resPath, const VFS::Manager* vfs)
{
/* Bethesda at some point converted all their BSA
* textures from tga to dds for increased load speed, but all
* texture file name references were kept as .tga.
*/
std::string correctedPath = Misc::StringUtils::lowerCase(resPath);
// Flatten slashes
std::replace(correctedPath.begin(), correctedPath.end(), '/', '\\');
auto bothSeparators = [](char a, char b) { return a == '\\' && b == '\\'; };
correctedPath.erase(std::unique(correctedPath.begin(), correctedPath.end(), bothSeparators), correctedPath.end());
// Remove leading separator
if (!correctedPath.empty() && correctedPath[0] == '\\')
correctedPath.erase(0, 1);
// Handle top level directory
bool needsPrefix = true;
for (std::string_view potentialTopLevelDirectory : topLevelDirectories)
{
if (correctedPath.starts_with(potentialTopLevelDirectory)
&& correctedPath.size() > potentialTopLevelDirectory.size()
&& correctedPath[potentialTopLevelDirectory.size()] == '\\')
{
needsPrefix = false;
break;
}
else
{
std::string topLevelPrefix = std::string{ potentialTopLevelDirectory } + '\\';
size_t topLevelPos = correctedPath.find('\\' + topLevelPrefix);
if (topLevelPos != std::string::npos)
{
correctedPath.erase(0, topLevelPos + 1);
needsPrefix = false;
break;
}
}
}
if (needsPrefix)
correctedPath = std::string{ topLevelDirectories.front() } + '\\' + correctedPath;
std::string origExt = correctedPath;
// since we know all (GOTY edition or less) textures end
// in .dds, we change the extension
bool changedToDds = changeExtensionToDds(correctedPath);
if (vfs->exists(correctedPath))
return correctedPath;
// if it turns out that the above wasn't true in all cases (not for vanilla, but maybe mods)
// verify, and revert if false (this call succeeds quickly, but fails slowly)
if (changedToDds && vfs->exists(origExt))
return origExt;
// fall back to a resource in the top level directory if it exists
std::string fallback{ topLevelDirectories.front() };
fallback += '\\';
fallback += Misc::getFileName(correctedPath);
if (vfs->exists(fallback))
return fallback;
if (changedToDds)
{
fallback = topLevelDirectories.front();
fallback += '\\';
fallback += Misc::getFileName(origExt);
if (vfs->exists(fallback))
return fallback;
}
return correctedPath;
}
std::string Misc::ResourceHelpers::correctTexturePath(std::string_view resPath, const VFS::Manager* vfs)
{
return correctResourcePath({ { "textures", "bookart" } }, resPath, vfs);
}
std::string Misc::ResourceHelpers::correctIconPath(std::string_view resPath, const VFS::Manager* vfs)
{
return correctResourcePath({ { "icons" } }, resPath, vfs);
}
std::string Misc::ResourceHelpers::correctBookartPath(std::string_view resPath, const VFS::Manager* vfs)
{
return correctResourcePath({ { "bookart", "textures" } }, resPath, vfs);
}
std::string Misc::ResourceHelpers::correctBookartPath(
std::string_view resPath, int width, int height, const VFS::Manager* vfs)
{
std::string image = correctBookartPath(resPath, vfs);
// Apparently a bug with some morrowind versions, they reference the image without the size suffix.
// So if the image isn't found, try appending the size.
if (!vfs->exists(image))
{
std::stringstream str;
str << image.substr(0, image.rfind('.')) << "_" << width << "_" << height << image.substr(image.rfind('.'));
image = Misc::ResourceHelpers::correctBookartPath(str.str(), vfs);
}
return image;
}
VFS::Path::Normalized Misc::ResourceHelpers::correctActorModelPath(
VFS::Path::NormalizedView resPath, const VFS::Manager* vfs)
{
std::string mdlname(resPath.value());
std::string::size_type p = mdlname.find_last_of('/');
if (p != std::string::npos)
mdlname.insert(mdlname.begin() + static_cast<std::string::difference_type>(p) + 1, 'x');
else
mdlname.insert(mdlname.begin(), 'x');
VFS::Path::Normalized kfname(mdlname);
if (Misc::getFileExtension(mdlname) == "nif")
kfname.changeExtension("kf");
if (!vfs->exists(kfname))
return VFS::Path::Normalized(resPath);
return mdlname;
}
std::string Misc::ResourceHelpers::correctMaterialPath(std::string_view resPath, const VFS::Manager* vfs)
{
return correctResourcePath({ { "materials" } }, resPath, vfs);
}
std::string Misc::ResourceHelpers::correctMeshPath(std::string_view resPath)
{
std::string res = "meshes\\";
res.append(resPath);
return res;
}
VFS::Path::Normalized Misc::ResourceHelpers::correctSoundPath(VFS::Path::NormalizedView resPath)
{
static constexpr VFS::Path::NormalizedView prefix("sound");
return prefix / resPath;
}
VFS::Path::Normalized Misc::ResourceHelpers::correctMusicPath(VFS::Path::NormalizedView resPath)
{
static constexpr VFS::Path::NormalizedView prefix("music");
return prefix / resPath;
}
std::string_view Misc::ResourceHelpers::meshPathForESM3(std::string_view resPath)
{
constexpr std::string_view prefix = "meshes";
if (resPath.length() < prefix.size() + 1 || !Misc::StringUtils::ciStartsWith(resPath, prefix)
|| (resPath[prefix.size()] != '/' && resPath[prefix.size()] != '\\'))
{
throw std::runtime_error("Path should start with 'meshes\\'");
}
return resPath.substr(prefix.size() + 1);
}
VFS::Path::Normalized Misc::ResourceHelpers::correctSoundPath(
VFS::Path::NormalizedView resPath, const VFS::Manager& vfs)
{
// Workaround: Bethesda at some point converted some of the files to mp3, but the references were kept as .wav.
if (!vfs.exists(resPath))
{
VFS::Path::Normalized sound(resPath);
sound.changeExtension("mp3");
return sound;
}
return VFS::Path::Normalized(resPath);
}
bool Misc::ResourceHelpers::isHiddenMarker(const ESM::RefId& id)
{
return id == "prisonmarker" || id == "divinemarker" || id == "templemarker" || id == "northmarker";
}
namespace
{
std::string getLODMeshNameImpl(std::string resPath, std::string_view pattern)
{
if (auto w = Misc::findExtension(resPath); w != std::string::npos)
resPath.insert(w, pattern);
return VFS::Path::normalizeFilename(resPath);
}
std::string getBestLODMeshName(std::string const& resPath, const VFS::Manager* vfs, std::string_view pattern)
{
if (std::string result = getLODMeshNameImpl(resPath, pattern); vfs->exists(result))
return result;
return resPath;
}
}
std::string Misc::ResourceHelpers::getLODMeshName(
int esmVersion, std::string resPath, const VFS::Manager* vfs, unsigned char lod)
{
const std::string distantMeshPattern = [&esmVersion] {
switch (esmVersion)
{
case ESM::VER_120:
case ESM::VER_130:
return "_dist";
case ESM::VER_080:
case ESM::VER_100:
return "_far";
case ESM::VER_094:
case ESM::VER_170:
return "_lod";
default:
return "";
}
}();
for (int l = lod; l >= 0; --l)
{
std::stringstream patern;
patern << distantMeshPattern << "_" << l;
std::string const meshName = getBestLODMeshName(resPath, vfs, patern.str());
if (meshName != resPath)
return meshName;
}
return getBestLODMeshName(resPath, vfs, distantMeshPattern);
}
| 8,770
|
C++
|
.cpp
| 226
| 32.814159
| 118
| 0.656871
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,678
|
thread.cpp
|
OpenMW_openmw/components/misc/thread.cpp
|
#include "thread.hpp"
#include <components/debug/debuglog.hpp>
#include <cstring>
#include <thread>
#ifdef __linux__
#include <pthread.h>
#include <sched.h>
namespace Misc
{
void setCurrentThreadIdlePriority()
{
sched_param param;
param.sched_priority = 0;
if (pthread_setschedparam(pthread_self(), SCHED_IDLE, ¶m) == 0)
Log(Debug::Verbose) << "Using idle priority for thread=" << std::this_thread::get_id();
else
Log(Debug::Warning) << "Failed to set idle priority for thread=" << std::this_thread::get_id() << ": "
<< std::generic_category().message(errno);
}
}
#elif defined(WIN32)
#include <components/misc/windows.hpp>
namespace Misc
{
void setCurrentThreadIdlePriority()
{
if (SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST))
Log(Debug::Verbose) << "Using idle priority for thread=" << std::this_thread::get_id();
else
Log(Debug::Warning) << "Failed to set idle priority for thread=" << std::this_thread::get_id() << ": "
<< GetLastError();
}
}
#elif defined(__FreeBSD__)
#include <sys/rtprio.h>
#include <sys/types.h>
namespace Misc
{
void setCurrentThreadIdlePriority()
{
struct rtprio prio;
prio.type = RTP_PRIO_IDLE;
prio.prio = RTP_PRIO_MAX;
if (rtprio_thread(RTP_SET, 0, &prio) == 0)
Log(Debug::Verbose) << "Using idle priority for thread=" << std::this_thread::get_id();
else
Log(Debug::Warning) << "Failed to set idle priority for thread=" << std::this_thread::get_id() << ": "
<< std::generic_category().message(errno);
}
}
#else
namespace Misc
{
void setCurrentThreadIdlePriority()
{
Log(Debug::Warning) << "Idle thread priority is not supported on this system";
}
}
#endif
| 1,934
|
C++
|
.cpp
| 59
| 26.254237
| 114
| 0.608275
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,679
|
esmdata.cpp
|
OpenMW_openmw/components/esmloader/esmdata.cpp
|
#include "esmdata.hpp"
#include "lessbyid.hpp"
#include "record.hpp"
#include <components/esm/defs.hpp>
#include <components/esm3/loadacti.hpp>
#include <components/esm3/loadcont.hpp>
#include <components/esm3/loaddoor.hpp>
#include <components/esm3/loadgmst.hpp>
#include <components/esm3/loadland.hpp>
#include <components/esm3/loadstat.hpp>
#include <components/esm3/variant.hpp>
#include <components/misc/strings/lower.hpp>
#include <algorithm>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
namespace EsmLoader
{
namespace
{
template <class F>
auto returnAs(F&& f)
{
using Result = decltype(std::forward<F>(f)(ESM::Static{}));
if constexpr (!std::is_same_v<Result, void>)
return Result{};
}
template <class T, class F>
auto withStatic(const ESM::RefId& refId, const std::vector<T>& values, F&& f)
{
const auto it = std::lower_bound(values.begin(), values.end(), refId, LessById{});
if (it == values.end() || it->mId != refId)
return returnAs(std::forward<F>(f));
return std::forward<F>(f)(*it);
}
template <class F>
auto withStatic(const ESM::RefId& refId, ESM::RecNameInts type, const EsmData& content, F&& f)
{
switch (type)
{
case ESM::REC_ACTI:
return withStatic(refId, content.mActivators, std::forward<F>(f));
case ESM::REC_CONT:
return withStatic(refId, content.mContainers, std::forward<F>(f));
case ESM::REC_DOOR:
return withStatic(refId, content.mDoors, std::forward<F>(f));
case ESM::REC_STAT:
return withStatic(refId, content.mStatics, std::forward<F>(f));
default:
break;
}
return returnAs(std::forward<F>(f));
}
}
EsmData::~EsmData() {}
std::string_view getModel(const EsmData& content, const ESM::RefId& refId, ESM::RecNameInts type)
{
return withStatic(refId, type, content, [](const auto& v) { return std::string_view(v.mModel); });
}
ESM::Variant getGameSetting(const std::vector<ESM::GameSetting>& records, std::string_view id)
{
auto it = std::lower_bound(records.begin(), records.end(), id, LessById{});
if (it == records.end() || it->mId != id)
throw std::runtime_error("Game settings \"" + std::string(id) + "\" is not found");
return it->mValue;
}
}
| 2,665
|
C++
|
.cpp
| 70
| 29.771429
| 106
| 0.595201
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,680
|
load.cpp
|
OpenMW_openmw/components/esmloader/load.cpp
|
#include "load.hpp"
#include "esmdata.hpp"
#include "lessbyid.hpp"
#include "record.hpp"
#include <components/debug/debuglog.hpp>
#include <components/esm/defs.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/loadacti.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/esm3/loadcont.hpp>
#include <components/esm3/loaddoor.hpp>
#include <components/esm3/loadgmst.hpp>
#include <components/esm3/loadland.hpp>
#include <components/esm3/loadstat.hpp>
#include <components/esm3/readerscache.hpp>
#include <components/files/collections.hpp>
#include <components/files/conversion.hpp>
#include <components/files/multidircollection.hpp>
#include <components/loadinglistener/loadinglistener.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/misc/strings/lower.hpp>
#include <algorithm>
#include <cstddef>
#include <filesystem>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
namespace EsmLoader
{
namespace
{
struct GetKey
{
template <class T>
decltype(auto) operator()(const T& v) const
{
return (v.mId);
}
const ESM::RefId& operator()(const ESM::Cell& v) const { return v.mId; }
std::pair<int, int> operator()(const ESM::Land& v) const { return std::pair(v.mX, v.mY); }
template <class T>
decltype(auto) operator()(const Record<T>& v) const
{
return (*this)(v.mValue);
}
};
struct CellRecords
{
Records<ESM::Cell> mValues;
std::map<std::string, std::size_t> mByName;
std::map<std::pair<int, int>, std::size_t> mByPosition;
};
template <class T, class = std::void_t<>>
struct HasId : std::false_type
{
};
template <class T>
struct HasId<T, std::void_t<decltype(T::mId)>> : std::true_type
{
};
template <class T>
constexpr bool hasId = HasId<T>::value;
template <class T>
auto loadRecord(ESM::ESMReader& reader, Records<T>& records) -> std::enable_if_t<hasId<T>>
{
T record;
bool deleted = false;
record.load(reader, deleted);
if (Misc::ResourceHelpers::isHiddenMarker(record.mId))
return;
records.emplace_back(deleted, std::move(record));
}
template <class T>
auto loadRecord(ESM::ESMReader& reader, Records<T>& records) -> std::enable_if_t<!hasId<T>>
{
T record;
bool deleted = false;
record.load(reader, deleted);
records.emplace_back(deleted, std::move(record));
}
void loadRecord(ESM::ESMReader& reader, CellRecords& records)
{
ESM::Cell record;
bool deleted = false;
record.loadNameAndData(reader, deleted);
if ((record.mData.mFlags & ESM::Cell::Interior) != 0)
{
const auto it = records.mByName.find(record.mName);
if (it == records.mByName.end())
{
record.loadCell(reader, true);
records.mByName.emplace_hint(it, record.mName, records.mValues.size());
records.mValues.emplace_back(deleted, std::move(record));
}
else
{
Record<ESM::Cell>& old = records.mValues[it->second];
old.mValue.mData = record.mData;
old.mValue.loadCell(reader, true);
}
}
else
{
const std::pair<int, int> position(record.mData.mX, record.mData.mY);
const auto it = records.mByPosition.find(position);
if (it == records.mByPosition.end())
{
record.loadCell(reader, true);
records.mByPosition.emplace_hint(it, position, records.mValues.size());
records.mValues.emplace_back(deleted, std::move(record));
}
else
{
Record<ESM::Cell>& old = records.mValues[it->second];
old.mValue.mData = record.mData;
old.mValue.loadCell(reader, true);
}
}
}
struct ShallowContent
{
Records<ESM::Activator> mActivators;
CellRecords mCells;
Records<ESM::Container> mContainers;
Records<ESM::Door> mDoors;
Records<ESM::GameSetting> mGameSettings;
Records<ESM::Land> mLands;
Records<ESM::Static> mStatics;
};
void loadRecord(const Query& query, const ESM::NAME& name, ESM::ESMReader& reader, ShallowContent& content)
{
switch (name.toInt())
{
case ESM::REC_ACTI:
if (query.mLoadActivators)
return loadRecord(reader, content.mActivators);
break;
case ESM::REC_CELL:
if (query.mLoadCells)
return loadRecord(reader, content.mCells);
break;
case ESM::REC_CONT:
if (query.mLoadContainers)
return loadRecord(reader, content.mContainers);
break;
case ESM::REC_DOOR:
if (query.mLoadDoors)
return loadRecord(reader, content.mDoors);
break;
case ESM::REC_GMST:
if (query.mLoadGameSettings)
return loadRecord(reader, content.mGameSettings);
break;
case ESM::REC_LAND:
if (query.mLoadLands)
return loadRecord(reader, content.mLands);
break;
case ESM::REC_STAT:
if (query.mLoadStatics)
return loadRecord(reader, content.mStatics);
break;
}
reader.skipRecord();
}
void loadEsm(const Query& query, ESM::ESMReader& reader, ShallowContent& content, Loading::Listener* listener)
{
Log(Debug::Info) << "Loading ESM file " << reader.getName();
while (reader.hasMoreRecs())
{
const ESM::NAME recName = reader.getRecName();
reader.getRecHeader();
if (reader.getRecordFlags() & ESM::FLAG_Ignored)
{
reader.skipRecord();
continue;
}
loadRecord(query, recName, reader, content);
if (listener != nullptr)
listener->setProgress(fileProgress * reader.getFileOffset() / reader.getFileSize());
}
}
ShallowContent shallowLoad(const Query& query, const std::vector<std::string>& contentFiles,
const Files::Collections& fileCollections, ESM::ReadersCache& readers, ToUTF8::Utf8Encoder* encoder,
Loading::Listener* listener)
{
ShallowContent result;
const std::set<std::string> supportedFormats{
".esm",
".esp",
".omwgame",
".omwaddon",
".project",
};
for (std::size_t i = 0; i < contentFiles.size(); ++i)
{
const std::string& file = contentFiles[i];
const std::string extension
= Misc::StringUtils::lowerCase(Files::pathToUnicodeString(std::filesystem::path(file).extension()));
if (supportedFormats.find(extension) == supportedFormats.end())
{
Log(Debug::Warning) << "Skipping unsupported content file: " << file;
continue;
}
if (listener != nullptr)
{
listener->setLabel(file);
listener->setProgressRange(fileProgress);
}
const Files::MultiDirCollection& collection = fileCollections.getCollection(extension);
const ESM::ReadersCache::BusyItem reader = readers.get(i);
reader->setEncoder(encoder);
reader->setIndex(static_cast<int>(i));
reader->open(collection.getPath(file));
if (query.mLoadCells)
reader->resolveParentFileIndices(readers);
loadEsm(query, *reader, result, listener);
}
return result;
}
struct WithType
{
ESM::RecNameInts mType;
template <class T>
RefIdWithType operator()(const T& v) const
{
return { v.mId, mType };
}
};
template <class T>
void addRefIdsTypes(const std::vector<T>& values, std::vector<RefIdWithType>& refIdsTypes)
{
std::transform(values.begin(), values.end(), std::back_inserter(refIdsTypes),
WithType{ static_cast<ESM::RecNameInts>(T::sRecordId) });
}
void addRefIdsTypes(EsmData& content)
{
content.mRefIdTypes.reserve(content.mActivators.size() + content.mContainers.size() + content.mDoors.size()
+ content.mStatics.size());
addRefIdsTypes(content.mActivators, content.mRefIdTypes);
addRefIdsTypes(content.mContainers, content.mRefIdTypes);
addRefIdsTypes(content.mDoors, content.mRefIdTypes);
addRefIdsTypes(content.mStatics, content.mRefIdTypes);
std::sort(content.mRefIdTypes.begin(), content.mRefIdTypes.end(), LessById{});
}
std::vector<ESM::Cell> prepareCellRecords(Records<ESM::Cell>& records)
{
std::vector<ESM::Cell> result;
for (Record<ESM::Cell>& v : records)
if (!v.mDeleted)
result.emplace_back(std::move(v.mValue));
return result;
}
}
EsmData loadEsmData(const Query& query, const std::vector<std::string>& contentFiles,
const Files::Collections& fileCollections, ESM::ReadersCache& readers, ToUTF8::Utf8Encoder* encoder,
Loading::Listener* listener)
{
Log(Debug::Info) << "Loading ESM data...";
ShallowContent content = shallowLoad(query, contentFiles, fileCollections, readers, encoder, listener);
std::ostringstream loaded;
if (query.mLoadActivators)
loaded << ' ' << content.mActivators.size() << " activators,";
if (query.mLoadCells)
loaded << ' ' << content.mCells.mValues.size() << " cells,";
if (query.mLoadContainers)
loaded << ' ' << content.mContainers.size() << " containers,";
if (query.mLoadDoors)
loaded << ' ' << content.mDoors.size() << " doors,";
if (query.mLoadGameSettings)
loaded << ' ' << content.mGameSettings.size() << " game settings,";
if (query.mLoadLands)
loaded << ' ' << content.mLands.size() << " lands,";
if (query.mLoadStatics)
loaded << ' ' << content.mStatics.size() << " statics,";
Log(Debug::Info) << "Loaded" << loaded.str();
EsmData result;
if (query.mLoadActivators)
result.mActivators = prepareRecords(content.mActivators, GetKey{});
if (query.mLoadCells)
result.mCells = prepareCellRecords(content.mCells.mValues);
if (query.mLoadContainers)
result.mContainers = prepareRecords(content.mContainers, GetKey{});
if (query.mLoadDoors)
result.mDoors = prepareRecords(content.mDoors, GetKey{});
if (query.mLoadGameSettings)
result.mGameSettings = prepareRecords(content.mGameSettings, GetKey{});
if (query.mLoadLands)
result.mLands = prepareRecords(content.mLands, GetKey{});
if (query.mLoadStatics)
result.mStatics = prepareRecords(content.mStatics, GetKey{});
addRefIdsTypes(result);
std::ostringstream prepared;
if (query.mLoadActivators)
prepared << ' ' << result.mActivators.size() << " unique activators,";
if (query.mLoadCells)
prepared << ' ' << result.mCells.size() << " unique cells,";
if (query.mLoadContainers)
prepared << ' ' << result.mContainers.size() << " unique containers,";
if (query.mLoadDoors)
prepared << ' ' << result.mDoors.size() << " unique doors,";
if (query.mLoadGameSettings)
prepared << ' ' << result.mGameSettings.size() << " unique game settings,";
if (query.mLoadLands)
prepared << ' ' << result.mLands.size() << " unique lands,";
if (query.mLoadStatics)
prepared << ' ' << result.mStatics.size() << " unique statics,";
Log(Debug::Info) << "Prepared" << prepared.str();
return result;
}
}
| 13,316
|
C++
|
.cpp
| 315
| 29.780952
| 120
| 0.553694
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,681
|
reporter.cpp
|
OpenMW_openmw/components/loadinglistener/reporter.cpp
|
#include "reporter.hpp"
#include "loadinglistener.hpp"
#include <condition_variable>
#include <cstddef>
#include <mutex>
namespace Loading
{
void Reporter::addTotal(std::size_t value)
{
const std::lock_guard lock(mMutex);
mTotal += value;
mUpdated.notify_all();
}
void Reporter::addProgress(std::size_t value)
{
const std::lock_guard lock(mMutex);
mProgress += value;
mUpdated.notify_all();
}
void Reporter::complete()
{
const std::lock_guard lock(mMutex);
mDone = true;
mUpdated.notify_all();
}
void Reporter::wait(Listener& listener) const
{
std::unique_lock lock(mMutex);
while (!mDone)
{
listener.setProgressRange(mTotal);
listener.setProgress(mProgress);
mUpdated.wait(lock);
}
}
}
| 880
|
C++
|
.cpp
| 36
| 18.083333
| 49
| 0.605483
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,682
|
gen_iconv.cpp
|
OpenMW_openmw/components/to_utf8/gen_iconv.cpp
|
// This program generates the file tables_gen.hpp
#include <iostream>
#include <cassert>
#include <iconv.h>
void tab()
{
std::cout << " ";
}
// write one number with a space in front of it and a comma after it
void num(char i, bool last)
{
// Convert i to its integer value, i.e. -128 to 127. Printing it directly
// would result in non-printable characters in the source code, which is bad.
std::cout << " " << static_cast<int>(i);
if (!last)
std::cout << ",";
}
// Write one table entry (UTF8 value), 1-5 bytes
void writeChar(char* value, int length, bool last, const std::string& comment = "")
{
assert(length >= 1 && length <= 5);
tab();
num(length, false);
for (int i = 0; i < 5; i++)
num(value[i], last && i == 4);
if (comment != "")
std::cout << " // " << comment;
std::cout << std::endl;
}
// What to write on missing characters
void writeMissing(bool last)
{
// Just write a space character
char value[5];
value[0] = ' ';
for (int i = 1; i < 5; i++)
value[i] = 0;
writeChar(value, 1, last, "not part of this charset");
}
int write_table(const std::string& charset, const std::string& tableName)
{
// Write table header
std::cout << "const static signed char " << tableName << "[] =\n{\n";
// Open conversion system
iconv_t cd = iconv_open("UTF-8", charset.c_str());
// Convert each character from 0 to 255
for (int i = 0; i < 256; i++)
{
bool last = (i == 255);
char input = i;
char* iptr = &input;
size_t ileft = 1;
char output[5];
for (int k = 0; k < 5; k++)
output[k] = 0;
char* optr = output;
size_t oleft = 5;
size_t res = iconv(cd, &iptr, &ileft, &optr, &oleft);
if (res)
writeMissing(last);
else
writeChar(output, 5 - oleft, last);
}
iconv_close(cd);
// Finish table
std::cout << "};\n";
return 0;
}
int main()
{
// Write header guard
std::cout << "#ifndef COMPONENTS_TOUTF8_TABLE_GEN_H\n#define COMPONENTS_TOUTF8_TABLE_GEN_H\n\n";
// Write namespace
std::cout << "namespace ToUTF8\n{\n\n";
// Central European and Eastern European languages that use Latin script, such as
// Polish, Czech, Slovak, Hungarian, Slovene, Bosnian, Croatian, Serbian (Latin script), Romanian and Albanian.
std::cout << "\n/// Central European and Eastern European languages that use Latin script,"
"\n/// such as Polish, Czech, Slovak, Hungarian, Slovene, Bosnian, Croatian,"
"\n/// Serbian (Latin script), Romanian and Albanian."
"\n";
write_table("WINDOWS-1250", "windows_1250");
// Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic and other languages
std::cout << "\n/// Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic"
"\n/// and other languages"
"\n";
write_table("WINDOWS-1251", "windows_1251");
// English
std::cout << "\n/// Latin alphabet used by English and some other Western languages"
"\n";
write_table("WINDOWS-1252", "windows_1252");
write_table("CP437", "cp437");
// Close namespace
std::cout << "\n}\n\n";
// Close header guard
std::cout << "#endif\n\n";
return 0;
}
| 3,387
|
C++
|
.cpp
| 97
| 29
| 115
| 0.591787
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,683
|
to_utf8.cpp
|
OpenMW_openmw/components/to_utf8/to_utf8.cpp
|
#include "to_utf8.hpp"
#include <algorithm>
#include <cassert>
#include <ios>
#include <iterator>
#include <stdexcept>
#include <components/debug/debuglog.hpp>
/* This file contains the code to translate from WINDOWS-1252 (native
charset used in English version of Morrowind) to UTF-8. The library
is designed to be extened to support more source encodings later,
which means that we may add support for Russian, Polish and Chinese
files and so on.
The code does not depend on any external library at
runtime. Instead, it uses a pregenerated table made with iconv (see
gen_iconv.cpp and the Makefile) which is located in tables_gen.hpp.
This is both faster and uses less dependencies. The tables would
only need to be regenerated if we are adding support more input
encodings. As such, there is no need to make the generator code
platform independent.
The library is optimized for the case of pure ASCII input strings,
which is the vast majority of cases at least for the English
version. A test of my version of Morrowind.esm got 130 non-ASCII vs
236195 ASCII strings, or less than 0.06% of strings containing
non-ASCII characters.
To optmize for this, ff the first pass of the string does not find
any non-ASCII characters, the entire string is passed along without
any modification.
Most of the non-ASCII strings are books, and are quite large. (The
non-ASCII characters are typically starting and ending quotation
marks.) Within these, almost all the characters are ASCII. For this
purpose, the library is also optimized for mostly-ASCII contents
even in the cases where some conversion is necessary.
*/
// Generated tables
#include "tables_gen.hpp"
using namespace ToUTF8;
namespace
{
std::string_view::iterator skipAscii(std::string_view input)
{
return std::find_if(input.begin(), input.end(), [](unsigned char v) { return v == 0 || v >= 128; });
}
std::basic_string_view<signed char> getTranslationArray(FromType sourceEncoding)
{
switch (sourceEncoding)
{
case ToUTF8::WINDOWS_1252:
return { ToUTF8::windows_1252, std::size(ToUTF8::windows_1252) };
case ToUTF8::WINDOWS_1250:
return { ToUTF8::windows_1250, std::size(ToUTF8::windows_1250) };
case ToUTF8::WINDOWS_1251:
return { ToUTF8::windows_1251, std::size(ToUTF8::windows_1251) };
case ToUTF8::CP437:
return { ToUTF8::cp437, std::size(ToUTF8::cp437) };
}
throw std::logic_error("Invalid source encoding: " + std::to_string(sourceEncoding));
}
// Make sure the output vector is large enough for 'size' bytes,
// including a terminating zero after it.
void resize(std::size_t size, BufferAllocationPolicy bufferAllocationPolicy, std::string& buffer)
{
if (buffer.size() > size)
{
buffer[size] = 0;
return;
}
if (buffer.size() == size)
return;
switch (bufferAllocationPolicy)
{
case BufferAllocationPolicy::FitToRequiredSize:
buffer.resize(size);
break;
case BufferAllocationPolicy::UseGrowFactor:
// Add some extra padding to reduce the chance of having to resize
// again later.
buffer.resize(3 * size);
// And make sure the string is zero terminated
buffer[size] = 0;
break;
}
}
}
StatelessUtf8Encoder::StatelessUtf8Encoder(FromType sourceEncoding)
: mTranslationArray(getTranslationArray(sourceEncoding))
{
}
std::string_view StatelessUtf8Encoder::getUtf8(
std::string_view input, BufferAllocationPolicy bufferAllocationPolicy, std::string& buffer) const
{
if (input.empty())
return input;
// Note: The rest of this function is designed for single-character
// input encodings only. It also assumes that the input encoding
// shares its first 128 values (0-127) with ASCII. There are no plans
// to add more encodings to this module (we are using utf8 for new
// content files), so that shouldn't be an issue.
// Compute output length, and check for pure ascii input at the same
// time.
const auto [outlen, ascii] = getLength(input);
// If we're pure ascii, then don't bother converting anything.
if (ascii)
return std::string_view(input.data(), outlen);
// Make sure the output is large enough
resize(outlen, bufferAllocationPolicy, buffer);
char* out = buffer.data();
// Translate
for (auto it = input.begin(); it != input.end() && *it != 0; ++it)
copyFromArray(*it, out);
// Make sure that we wrote the correct number of bytes
assert((out - buffer.data()) == (int)outlen);
// And make extra sure the output is null terminated
assert(buffer.size() >= outlen);
assert(buffer[outlen] == 0);
return std::string_view(buffer.data(), outlen);
}
std::string_view StatelessUtf8Encoder::getLegacyEnc(
std::string_view input, BufferAllocationPolicy bufferAllocationPolicy, std::string& buffer) const
{
if (input.empty())
return input;
// TODO: The rest of this function is designed for single-character
// input encodings only. It also assumes that the input the input
// encoding shares its first 128 values (0-127) with ASCII. These
// conditions must be checked again if you add more input encodings
// later.
// Compute output length, and check for pure ascii input at the same
// time.
const auto [outlen, ascii] = getLengthLegacyEnc(input);
// If we're pure ascii, then don't bother converting anything.
if (ascii)
return std::string_view(input.data(), outlen);
// Make sure the output is large enough
resize(outlen, bufferAllocationPolicy, buffer);
char* out = buffer.data();
// Translate
for (auto it = input.begin(); it != input.end() && *it != 0;)
copyFromArrayLegacyEnc(it, input.end(), out);
// Make sure that we wrote the correct number of bytes
assert((out - buffer.data()) == static_cast<int>(outlen));
// And make extra sure the output is null terminated
assert(buffer.size() >= outlen);
assert(buffer[outlen] == 0);
return std::string_view(buffer.data(), outlen);
}
/** Get the total length length needed to decode the given string with
the given translation array. The arrays are encoded with 6 bytes
per character, with the first giving the length and the next 5 the
actual data.
The function serves a dual purpose for optimization reasons: it
checks if the input is pure ascii (all values are <= 127). If this
is the case, then the ascii parameter is set to true, and the
caller can optimize for this case.
*/
std::pair<std::size_t, bool> StatelessUtf8Encoder::getLength(std::string_view input) const
{
// Do away with the ascii part of the string first (this is almost
// always the entire string.)
auto it = skipAscii(input);
// If we're not at the null terminator at this point, then there
// were some non-ascii characters to deal with. Go to slow-mode for
// the rest of the string.
if (it == input.end() || *it == 0)
return { it - input.begin(), true };
std::size_t len = it - input.begin();
do
{
// Find the translated length of this character in the
// lookup table.
len += mTranslationArray[static_cast<unsigned char>(*it) * 6];
++it;
} while (it != input.end() && *it != 0);
return { len, false };
}
// Translate one character 'ch' using the translation array 'arr', and
// advance the output pointer accordingly.
void StatelessUtf8Encoder::copyFromArray(unsigned char ch, char*& out) const
{
// Optimize for ASCII values
if (ch < 128)
{
*(out++) = ch;
return;
}
const signed char* in = &mTranslationArray[ch * 6];
int len = *(in++);
memcpy(out, in, len);
out += len;
}
std::pair<std::size_t, bool> StatelessUtf8Encoder::getLengthLegacyEnc(std::string_view input) const
{
// Do away with the ascii part of the string first (this is almost
// always the entire string.)
auto it = skipAscii(input);
// If we're not at the null terminator at this point, then there
// were some non-ascii characters to deal with. Go to slow-mode for
// the rest of the string.
if (it == input.end() || *it == 0)
return { it - input.begin(), true };
std::size_t len = it - input.begin();
std::size_t symbolLen = 0;
do
{
symbolLen += 1;
// Find the translated length of this character in the
// lookup table.
switch (static_cast<unsigned char>(*it))
{
case 0xe2:
symbolLen -= 2;
break;
case 0xc2:
case 0xcb:
case 0xc4:
case 0xc6:
case 0xc3:
case 0xd0:
case 0xd1:
case 0xd2:
case 0xc5:
symbolLen -= 1;
break;
default:
len += symbolLen;
symbolLen = 0;
break;
}
++it;
} while (it != input.end() && *it != 0);
return { len, false };
}
void StatelessUtf8Encoder::copyFromArrayLegacyEnc(
std::string_view::iterator& chp, std::string_view::iterator end, char*& out) const
{
unsigned char ch = *(chp++);
// Optimize for ASCII values
if (ch < 128)
{
*(out++) = ch;
return;
}
int len = 1;
switch (ch)
{
case 0xe2:
len = 3;
break;
case 0xc2:
case 0xcb:
case 0xc4:
case 0xc6:
case 0xc3:
case 0xd0:
case 0xd1:
case 0xd2:
case 0xc5:
len = 2;
break;
}
if (len == 1) // There is no 1 length utf-8 glyph that is not 0x20 (empty space)
{
*(out++) = ch;
return;
}
if (chp == end)
return;
unsigned char ch2 = *(chp++);
unsigned char ch3 = '\0';
if (len == 3)
{
if (chp == end)
return;
ch3 = *(chp++);
}
for (int i = 128; i < 256; i++)
{
unsigned char b1 = mTranslationArray[i * 6 + 1], b2 = mTranslationArray[i * 6 + 2],
b3 = mTranslationArray[i * 6 + 3];
if (b1 == ch && b2 == ch2 && (len != 3 || b3 == ch3))
{
*(out++) = (char)i;
return;
}
}
Log(Debug::Info) << "Could not find glyph " << std::hex << (int)ch << " " << (int)ch2 << " " << (int)ch3;
*(out++) = ch; // Could not find glyph, just put whatever
}
Utf8Encoder::Utf8Encoder(FromType sourceEncoding)
: mBuffer(50 * 1024, '\0')
, mImpl(sourceEncoding)
{
}
std::string_view Utf8Encoder::getUtf8(std::string_view input)
{
return mImpl.getUtf8(input, BufferAllocationPolicy::UseGrowFactor, mBuffer);
}
std::string_view Utf8Encoder::getLegacyEnc(std::string_view input)
{
return mImpl.getLegacyEnc(input, BufferAllocationPolicy::UseGrowFactor, mBuffer);
}
ToUTF8::FromType ToUTF8::calculateEncoding(std::string_view encodingName)
{
if (encodingName == "win1250")
return ToUTF8::WINDOWS_1250;
else if (encodingName == "win1251")
return ToUTF8::WINDOWS_1251;
else if (encodingName == "win1252")
return ToUTF8::WINDOWS_1252;
else
throw std::runtime_error(
"Unknown encoding '" + std::string(encodingName) + "', see openmw --help for available options.");
}
std::string ToUTF8::encodingUsingMessage(std::string_view encodingName)
{
if (encodingName == "win1250")
return "Using Central and Eastern European font encoding.";
else if (encodingName == "win1251")
return "Using Cyrillic font encoding.";
else if (encodingName == "win1252")
return "Using default (English) font encoding.";
else
throw std::runtime_error(
"Unknown encoding '" + std::string(encodingName) + "', see openmw --help for available options.");
}
| 12,239
|
C++
|
.cpp
| 324
| 31.135802
| 110
| 0.636747
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,684
|
bulletshape.cpp
|
OpenMW_openmw/components/resource/bulletshape.cpp
|
#include "bulletshape.hpp"
#include <stdexcept>
#include <string>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <BulletCollision/CollisionShapes/btCompoundShape.h>
#include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
#include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
namespace Resource
{
namespace
{
CollisionShapePtr duplicateCollisionShape(const btCollisionShape* shape)
{
if (shape == nullptr)
return nullptr;
if (shape->isCompound())
{
const btCompoundShape* comp = static_cast<const btCompoundShape*>(shape);
std::unique_ptr<btCompoundShape, DeleteCollisionShape> newShape(new btCompoundShape);
for (int i = 0, n = comp->getNumChildShapes(); i < n; ++i)
{
auto child = duplicateCollisionShape(comp->getChildShape(i));
const btTransform& trans = comp->getChildTransform(i);
newShape->addChildShape(trans, child.release());
}
return newShape;
}
if (shape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
const btScaledBvhTriangleMeshShape* trishape = static_cast<const btScaledBvhTriangleMeshShape*>(shape);
return CollisionShapePtr(new btScaledBvhTriangleMeshShape(
const_cast<btBvhTriangleMeshShape*>(trishape->getChildShape()), trishape->getLocalScaling()));
}
if (shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
const btBvhTriangleMeshShape* trishape = static_cast<const btBvhTriangleMeshShape*>(shape);
return CollisionShapePtr(new btScaledBvhTriangleMeshShape(
const_cast<btBvhTriangleMeshShape*>(trishape), btVector3(1.f, 1.f, 1.f)));
}
if (shape->getShapeType() == BOX_SHAPE_PROXYTYPE)
{
const btBoxShape* boxshape = static_cast<const btBoxShape*>(shape);
return CollisionShapePtr(new btBoxShape(*boxshape));
}
if (shape->getShapeType() == TERRAIN_SHAPE_PROXYTYPE)
return CollisionShapePtr(
new btHeightfieldTerrainShape(static_cast<const btHeightfieldTerrainShape&>(*shape)));
throw std::logic_error(std::string("Unhandled Bullet shape duplication: ") + shape->getName());
}
void deleteShape(btCollisionShape* shape)
{
if (shape->isCompound())
{
btCompoundShape* compound = static_cast<btCompoundShape*>(shape);
for (int i = 0, n = compound->getNumChildShapes(); i < n; i++)
if (btCollisionShape* child = compound->getChildShape(i))
deleteShape(child);
}
delete shape;
}
}
void DeleteCollisionShape::operator()(btCollisionShape* shape) const
{
deleteShape(shape);
}
BulletShape::BulletShape(const BulletShape& other, const osg::CopyOp& copyOp)
: Object(other, copyOp)
, mCollisionShape(duplicateCollisionShape(other.mCollisionShape.get()))
, mAvoidCollisionShape(duplicateCollisionShape(other.mAvoidCollisionShape.get()))
, mCollisionBox(other.mCollisionBox)
, mAnimatedShapes(other.mAnimatedShapes)
, mFileName(other.mFileName)
, mFileHash(other.mFileHash)
, mVisualCollisionType(other.mVisualCollisionType)
{
}
void BulletShape::setLocalScaling(const btVector3& scale)
{
mCollisionShape->setLocalScaling(scale);
if (mAvoidCollisionShape)
mAvoidCollisionShape->setLocalScaling(scale);
}
osg::ref_ptr<BulletShapeInstance> makeInstance(osg::ref_ptr<const BulletShape> source)
{
return { new BulletShapeInstance(std::move(source)) };
}
BulletShapeInstance::BulletShapeInstance(osg::ref_ptr<const BulletShape> source)
: BulletShape(*source)
, mSource(std::move(source))
{
}
}
| 4,176
|
C++
|
.cpp
| 92
| 34.5
| 119
| 0.636006
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,685
|
scenemanager.cpp
|
OpenMW_openmw/components/resource/scenemanager.cpp
|
#include "scenemanager.hpp"
#include <cstdlib>
#include <filesystem>
#include <osg/AlphaFunc>
#include <osg/ColorMaski>
#include <osg/Group>
#include <osg/Node>
#include <osg/UserDataContainer>
#include <osgAnimation/BasicAnimationManager>
#include <osgAnimation/Bone>
#include <osgAnimation/RigGeometry>
#include <osgAnimation/UpdateBone>
#include <osgParticle/ParticleSystem>
#include <osgUtil/IncrementalCompileOperation>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include <osgDB/SharedStateManager>
#include <components/debug/debuglog.hpp>
#include <components/nifosg/controller.hpp>
#include <components/nifosg/nifloader.hpp>
#include <components/nif/niffile.hpp>
#include <components/misc/algorithm.hpp>
#include <components/misc/osguservalues.hpp>
#include <components/misc/pathhelpers.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/pathutil.hpp>
#include <components/sceneutil/clone.hpp>
#include <components/sceneutil/controller.hpp>
#include <components/sceneutil/depth.hpp>
#include <components/sceneutil/extradata.hpp>
#include <components/sceneutil/lightmanager.hpp>
#include <components/sceneutil/optimizer.hpp>
#include <components/sceneutil/riggeometryosgaextension.hpp>
#include <components/sceneutil/util.hpp>
#include <components/sceneutil/visitor.hpp>
#include <components/shader/shadermanager.hpp>
#include <components/shader/shadervisitor.hpp>
#include <components/files/conversion.hpp>
#include <components/files/hash.hpp>
#include <components/files/memorystream.hpp>
#include "bgsmfilemanager.hpp"
#include "errormarker.hpp"
#include "imagemanager.hpp"
#include "niffilemanager.hpp"
#include "objectcache.hpp"
namespace
{
class InitWorldSpaceParticlesCallback
: public SceneUtil::NodeCallback<InitWorldSpaceParticlesCallback, osgParticle::ParticleSystem*>
{
public:
void operator()(osgParticle::ParticleSystem* node, osg::NodeVisitor* nv)
{
// HACK: Ignore the InverseWorldMatrix transform the particle system is attached to
if (node->getNumParents() && node->getParent(0)->getNumParents())
transformInitialParticles(node, node->getParent(0)->getParent(0));
node->removeUpdateCallback(this);
}
void transformInitialParticles(osgParticle::ParticleSystem* partsys, osg::Node* node)
{
osg::NodePathList nodepaths = node->getParentalNodePaths();
if (nodepaths.empty())
return;
osg::Matrixf worldMat = osg::computeLocalToWorld(nodepaths[0]);
worldMat.orthoNormalize(worldMat); // scale is already applied on the particle node
for (int i = 0; i < partsys->numParticles(); ++i)
{
partsys->getParticle(i)->transformPositionVelocity(worldMat);
}
// transform initial bounds to worldspace
osg::BoundingSphere sphere(partsys->getInitialBound());
SceneUtil::transformBoundingSphere(worldMat, sphere);
osg::BoundingBox box;
box.expandBy(sphere);
partsys->setInitialBound(box);
}
};
class InitParticlesVisitor : public osg::NodeVisitor
{
public:
/// @param mask The node mask to set on ParticleSystem nodes.
InitParticlesVisitor(unsigned int mask)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mMask(mask)
{
}
bool isWorldSpaceParticleSystem(osgParticle::ParticleSystem* partsys)
{
// HACK: ParticleSystem has no getReferenceFrame()
return (partsys->getUserDataContainer() && partsys->getUserDataContainer()->getNumDescriptions() > 0
&& partsys->getUserDataContainer()->getDescriptions()[0] == "worldspace");
}
void apply(osg::Drawable& drw) override
{
if (osgParticle::ParticleSystem* partsys = dynamic_cast<osgParticle::ParticleSystem*>(&drw))
{
if (isWorldSpaceParticleSystem(partsys))
{
partsys->addUpdateCallback(new InitWorldSpaceParticlesCallback);
}
partsys->setNodeMask(mMask);
}
}
private:
unsigned int mMask;
};
}
namespace Resource
{
void TemplateMultiRef::addRef(const osg::Node* node)
{
mObjects.emplace_back(node);
}
class SharedStateManager : public osgDB::SharedStateManager
{
public:
unsigned int getNumSharedTextures() const { return _sharedTextureList.size(); }
unsigned int getNumSharedStateSets() const { return _sharedStateSetList.size(); }
void clearCache()
{
std::lock_guard<OpenThreads::Mutex> lock(_listMutex);
_sharedTextureList.clear();
_sharedStateSetList.clear();
}
};
/// Set texture filtering settings on textures contained in a FlipController.
class SetFilterSettingsControllerVisitor : public SceneUtil::ControllerVisitor
{
public:
SetFilterSettingsControllerVisitor(
osg::Texture::FilterMode minFilter, osg::Texture::FilterMode magFilter, int maxAnisotropy)
: mMinFilter(minFilter)
, mMagFilter(magFilter)
, mMaxAnisotropy(maxAnisotropy)
{
}
void visit(osg::Node& node, SceneUtil::Controller& ctrl) override
{
if (NifOsg::FlipController* flipctrl = dynamic_cast<NifOsg::FlipController*>(&ctrl))
{
for (std::vector<osg::ref_ptr<osg::Texture2D>>::iterator it = flipctrl->getTextures().begin();
it != flipctrl->getTextures().end(); ++it)
{
osg::Texture* tex = *it;
tex->setFilter(osg::Texture::MIN_FILTER, mMinFilter);
tex->setFilter(osg::Texture::MAG_FILTER, mMagFilter);
tex->setMaxAnisotropy(mMaxAnisotropy);
}
}
}
private:
osg::Texture::FilterMode mMinFilter;
osg::Texture::FilterMode mMagFilter;
int mMaxAnisotropy;
};
/// Set texture filtering settings on textures contained in StateSets.
class SetFilterSettingsVisitor : public osg::NodeVisitor
{
public:
SetFilterSettingsVisitor(
osg::Texture::FilterMode minFilter, osg::Texture::FilterMode magFilter, int maxAnisotropy)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mMinFilter(minFilter)
, mMagFilter(magFilter)
, mMaxAnisotropy(maxAnisotropy)
{
}
void apply(osg::Node& node) override
{
osg::StateSet* stateset = node.getStateSet();
if (stateset)
applyStateSet(stateset);
traverse(node);
}
void applyStateSet(osg::StateSet* stateset)
{
const osg::StateSet::TextureAttributeList& texAttributes = stateset->getTextureAttributeList();
for (unsigned int unit = 0; unit < texAttributes.size(); ++unit)
{
osg::StateAttribute* texture = stateset->getTextureAttribute(unit, osg::StateAttribute::TEXTURE);
if (texture)
applyStateAttribute(texture);
}
}
void applyStateAttribute(osg::StateAttribute* attr)
{
osg::Texture* tex = attr->asTexture();
if (tex)
{
tex->setFilter(osg::Texture::MIN_FILTER, mMinFilter);
tex->setFilter(osg::Texture::MAG_FILTER, mMagFilter);
tex->setMaxAnisotropy(mMaxAnisotropy);
}
}
private:
osg::Texture::FilterMode mMinFilter;
osg::Texture::FilterMode mMagFilter;
int mMaxAnisotropy;
};
// Check Collada extra descriptions
class ColladaDescriptionVisitor : public osg::NodeVisitor
{
public:
ColladaDescriptionVisitor()
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mSkeleton(nullptr)
{
}
osg::AlphaFunc::ComparisonFunction getTestMode(std::string mode)
{
if (mode == "ALWAYS")
return osg::AlphaFunc::ALWAYS;
if (mode == "LESS")
return osg::AlphaFunc::LESS;
if (mode == "EQUAL")
return osg::AlphaFunc::EQUAL;
if (mode == "LEQUAL")
return osg::AlphaFunc::LEQUAL;
if (mode == "GREATER")
return osg::AlphaFunc::GREATER;
if (mode == "NOTEQUAL")
return osg::AlphaFunc::NOTEQUAL;
if (mode == "GEQUAL")
return osg::AlphaFunc::GEQUAL;
if (mode == "NEVER")
return osg::AlphaFunc::NEVER;
Log(Debug::Warning) << "Unexpected alpha testing mode: " << mode;
return osg::AlphaFunc::LEQUAL;
}
void apply(osg::Node& node) override
{
if (osg::StateSet* stateset = node.getStateSet())
{
if (stateset->getRenderingHint() == osg::StateSet::TRANSPARENT_BIN)
{
osg::ref_ptr<osg::Depth> depth = new osg::Depth;
depth->setWriteMask(false);
stateset->setAttributeAndModes(depth, osg::StateAttribute::ON);
}
else if (stateset->getRenderingHint() == osg::StateSet::OPAQUE_BIN)
{
osg::ref_ptr<osg::Depth> depth = new osg::Depth;
depth->setWriteMask(true);
stateset->setAttributeAndModes(depth, osg::StateAttribute::ON);
}
}
/* Check if the <node> has <extra type="Node"> <technique profile="OpenSceneGraph"> <Descriptions>
<Description> correct format for OpenMW: <Description>alphatest mode value MaterialName</Description> e.g
<Description>alphatest GEQUAL 0.8 MyAlphaTestedMaterial</Description> */
std::vector<std::string> descriptions = node.getDescriptions();
for (const auto& description : descriptions)
{
mDescriptions.emplace_back(description);
}
// Iterate each description, and see if the current node uses the specified material for alpha testing
if (node.getStateSet())
{
for (const auto& description : mDescriptions)
{
std::vector<std::string> descriptionParts;
std::istringstream descriptionStringStream(description);
for (std::string part; std::getline(descriptionStringStream, part, ' ');)
{
descriptionParts.emplace_back(part);
}
if (descriptionParts.size() > (3) && descriptionParts.at(3) == node.getStateSet()->getName())
{
if (descriptionParts.at(0) == "alphatest")
{
osg::AlphaFunc::ComparisonFunction mode = getTestMode(descriptionParts.at(1));
osg::ref_ptr<osg::AlphaFunc> alphaFunc(new osg::AlphaFunc(
mode, Misc::StringUtils::toNumeric<float>(descriptionParts.at(2), 0.0f)));
node.getStateSet()->setAttributeAndModes(alphaFunc, osg::StateAttribute::ON);
}
}
if (descriptionParts.size() > (0) && descriptionParts.at(0) == "bodypart")
{
SceneUtil::FindByClassVisitor osgaRigFinder("RigGeometryHolder");
node.accept(osgaRigFinder);
for (osg::Node* foundRigNode : osgaRigFinder.mFoundNodes)
{
if (SceneUtil::RigGeometryHolder* rigGeometryHolder
= dynamic_cast<SceneUtil::RigGeometryHolder*>(foundRigNode))
mRigGeometryHolders.emplace_back(
osg::ref_ptr<SceneUtil::RigGeometryHolder>(rigGeometryHolder));
else
Log(Debug::Error) << "Converted RigGeometryHolder is of a wrong type.";
}
if (!mRigGeometryHolders.empty())
{
osgAnimation::RigGeometry::FindNearestParentSkeleton skeletonFinder;
mRigGeometryHolders[0]->accept(skeletonFinder);
if (skeletonFinder._root.valid())
mSkeleton = skeletonFinder._root;
}
}
}
}
traverse(node);
}
private:
std::vector<std::string> mDescriptions;
public:
osgAnimation::Skeleton* mSkeleton; // pointer is valid only if the model is a bodypart, osg::ref_ptr<Skeleton>
std::vector<osg::ref_ptr<SceneUtil::RigGeometryHolder>> mRigGeometryHolders;
};
class ReplaceAnimationUnderscoresVisitor : public osg::NodeVisitor
{
public:
ReplaceAnimationUnderscoresVisitor()
: osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
{
}
void apply(osg::Node& node) override
{
// NOTE: MUST update the animation manager names first!
if (auto* animationManager = dynamic_cast<osgAnimation::BasicAnimationManager*>(node.getUpdateCallback()))
renameAnimationChannelTargets(*animationManager);
// Then, any applicable node names
if (auto* rigGeometry = dynamic_cast<osgAnimation::RigGeometry*>(&node))
{
renameNode(*rigGeometry);
updateVertexInfluenceMap(*rigGeometry);
}
else if (auto* matrixTransform = dynamic_cast<osg::MatrixTransform*>(&node))
{
renameNode(*matrixTransform);
renameUpdateCallbacks(*matrixTransform);
}
traverse(node);
}
private:
inline void renameNode(osg::Node& node)
{
node.setName(Misc::StringUtils::underscoresToSpaces(node.getName()));
}
void renameUpdateCallbacks(osg::MatrixTransform& node)
{
osg::Callback* cb = node.getUpdateCallback();
while (cb)
{
auto* animCb = dynamic_cast<osgAnimation::AnimationUpdateCallback<osg::NodeCallback>*>(cb);
if (animCb)
{
std::string newAnimCbName = Misc::StringUtils::underscoresToSpaces(animCb->getName());
animCb->setName(newAnimCbName);
}
cb = cb->getNestedCallback();
}
}
void updateVertexInfluenceMap(osgAnimation::RigGeometry& rig)
{
osgAnimation::VertexInfluenceMap* vertexInfluenceMap = rig.getInfluenceMap();
if (!vertexInfluenceMap)
return;
std::vector<std::pair<std::string, std::string>> renameList;
for (const auto& [oldBoneName, _] : *vertexInfluenceMap)
{
const std::string newBoneName = Misc::StringUtils::underscoresToSpaces(oldBoneName);
if (newBoneName != oldBoneName)
renameList.emplace_back(oldBoneName, newBoneName);
}
for (const auto& [oldName, newName] : renameList)
{
if (vertexInfluenceMap->find(newName) == vertexInfluenceMap->end())
(*vertexInfluenceMap)[newName] = std::move((*vertexInfluenceMap)[oldName]);
vertexInfluenceMap->erase(oldName);
}
}
void renameAnimationChannelTargets(osgAnimation::BasicAnimationManager& animManager)
{
for (const osgAnimation::Animation* animation : animManager.getAnimationList())
{
if (animation)
{
const osgAnimation::ChannelList& channels = animation->getChannels();
for (osgAnimation::Channel* channel : channels)
channel->setTargetName(Misc::StringUtils::underscoresToSpaces(channel->getTargetName()));
}
}
}
};
SceneManager::SceneManager(const VFS::Manager* vfs, Resource::ImageManager* imageManager,
Resource::NifFileManager* nifFileManager, Resource::BgsmFileManager* bgsmFileManager, double expiryDelay)
: ResourceManager(vfs, expiryDelay)
, mShaderManager(new Shader::ShaderManager)
, mForceShaders(false)
, mClampLighting(true)
, mAutoUseNormalMaps(false)
, mAutoUseSpecularMaps(false)
, mApplyLightingToEnvMaps(false)
, mLightingMethod(SceneUtil::LightingMethod::FFP)
, mConvertAlphaTestToAlphaToCoverage(false)
, mAdjustCoverageForAlphaTest(false)
, mSupportsNormalsRT(false)
, mSharedStateManager(new SharedStateManager)
, mImageManager(imageManager)
, mNifFileManager(nifFileManager)
, mBgsmFileManager(bgsmFileManager)
, mMinFilter(osg::Texture::LINEAR_MIPMAP_LINEAR)
, mMagFilter(osg::Texture::LINEAR)
, mMaxAnisotropy(1)
, mUnRefImageDataAfterApply(false)
, mParticleSystemMask(~0u)
{
}
void SceneManager::setForceShaders(bool force)
{
mForceShaders = force;
}
bool SceneManager::getForceShaders() const
{
return mForceShaders;
}
void SceneManager::recreateShaders(osg::ref_ptr<osg::Node> node, const std::string& shaderPrefix,
bool forceShadersForNode, const osg::Program* programTemplate)
{
osg::ref_ptr<Shader::ShaderVisitor> shaderVisitor(createShaderVisitor(shaderPrefix));
shaderVisitor->setAllowedToModifyStateSets(false);
shaderVisitor->setProgramTemplate(programTemplate);
if (forceShadersForNode)
shaderVisitor->setForceShaders(true);
node->accept(*shaderVisitor);
}
void SceneManager::reinstateRemovedState(osg::ref_ptr<osg::Node> node)
{
osg::ref_ptr<Shader::ReinstateRemovedStateVisitor> reinstateRemovedStateVisitor
= new Shader::ReinstateRemovedStateVisitor(false);
node->accept(*reinstateRemovedStateVisitor);
}
void SceneManager::setClampLighting(bool clamp)
{
mClampLighting = clamp;
}
bool SceneManager::getClampLighting() const
{
return mClampLighting;
}
void SceneManager::setAutoUseNormalMaps(bool use)
{
mAutoUseNormalMaps = use;
}
void SceneManager::setNormalMapPattern(const std::string& pattern)
{
mNormalMapPattern = pattern;
}
void SceneManager::setNormalHeightMapPattern(const std::string& pattern)
{
mNormalHeightMapPattern = pattern;
}
void SceneManager::setAutoUseSpecularMaps(bool use)
{
mAutoUseSpecularMaps = use;
}
void SceneManager::setSpecularMapPattern(const std::string& pattern)
{
mSpecularMapPattern = pattern;
}
void SceneManager::setApplyLightingToEnvMaps(bool apply)
{
mApplyLightingToEnvMaps = apply;
}
void SceneManager::setSupportedLightingMethods(const SceneUtil::LightManager::SupportedMethods& supported)
{
mSupportedLightingMethods = supported;
}
bool SceneManager::isSupportedLightingMethod(SceneUtil::LightingMethod method) const
{
return mSupportedLightingMethods[static_cast<int>(method)];
}
void SceneManager::setLightingMethod(SceneUtil::LightingMethod method)
{
mLightingMethod = method;
if (mLightingMethod == SceneUtil::LightingMethod::SingleUBO)
{
osg::ref_ptr<osg::Program> program = new osg::Program;
program->addBindUniformBlock("LightBufferBinding", static_cast<int>(UBOBinding::LightBuffer));
mShaderManager->setProgramTemplate(program);
}
}
SceneUtil::LightingMethod SceneManager::getLightingMethod() const
{
return mLightingMethod;
}
void SceneManager::setConvertAlphaTestToAlphaToCoverage(bool convert)
{
mConvertAlphaTestToAlphaToCoverage = convert;
}
void SceneManager::setAdjustCoverageForAlphaTest(bool adjustCoverage)
{
mAdjustCoverageForAlphaTest = adjustCoverage;
}
void SceneManager::setOpaqueDepthTex(osg::ref_ptr<osg::Texture> texturePing, osg::ref_ptr<osg::Texture> texturePong)
{
mOpaqueDepthTex = { texturePing, texturePong };
}
osg::ref_ptr<osg::Texture> SceneManager::getOpaqueDepthTex(size_t frame)
{
return mOpaqueDepthTex[frame % 2];
}
SceneManager::~SceneManager()
{
// this has to be defined in the .cpp file as we can't delete incomplete types
}
Shader::ShaderManager& SceneManager::getShaderManager()
{
return *mShaderManager.get();
}
void SceneManager::setShaderPath(const std::filesystem::path& path)
{
mShaderManager->setShaderPath(path);
}
bool SceneManager::checkLoaded(VFS::Path::NormalizedView name, double timeStamp)
{
return mCache->checkInObjectCache(name, timeStamp);
}
void SceneManager::setUpNormalsRTForStateSet(osg::StateSet* stateset, bool enabled)
{
if (!getSupportsNormalsRT())
return;
stateset->setAttributeAndModes(new osg::ColorMaski(1, enabled, enabled, enabled, enabled));
}
/// @brief Callback to read image files from the VFS.
class ImageReadCallback : public osgDB::ReadFileCallback
{
public:
ImageReadCallback(Resource::ImageManager* imageMgr)
: mImageManager(imageMgr)
{
}
osgDB::ReaderWriter::ReadResult readImage(const std::string& filename, const osgDB::Options* options) override
{
auto filePath = Files::pathFromUnicodeString(filename);
if (filePath.is_absolute())
// It is a hack. Needed because either OSG or libcollada-dom tries to make an absolute path from
// our relative VFS path by adding current working directory.
filePath = std::filesystem::relative(filename, osgDB::getCurrentWorkingDirectory());
try
{
return osgDB::ReaderWriter::ReadResult(
mImageManager->getImage(VFS::Path::toNormalized(Files::pathToUnicodeString(filePath))),
osgDB::ReaderWriter::ReadResult::FILE_LOADED);
}
catch (std::exception& e)
{
return osgDB::ReaderWriter::ReadResult(e.what());
}
}
private:
Resource::ImageManager* mImageManager;
};
namespace
{
osg::ref_ptr<osg::Node> loadNonNif(
VFS::Path::NormalizedView normalizedFilename, std::istream& model, Resource::ImageManager* imageManager)
{
const std::string_view ext = Misc::getFileExtension(normalizedFilename.value());
const bool isColladaFile = ext == "dae";
osgDB::ReaderWriter* reader = osgDB::Registry::instance()->getReaderWriterForExtension(std::string(ext));
if (!reader)
{
std::stringstream errormsg;
errormsg << "Error loading " << normalizedFilename << ": no readerwriter for '" << ext << "' found"
<< std::endl;
throw std::runtime_error(errormsg.str());
}
osg::ref_ptr<osgDB::Options> options(new osgDB::Options);
// Set a ReadFileCallback so that image files referenced in the model are read from our virtual file system
// instead of the osgDB. Note, for some formats (.obj/.mtl) that reference other (non-image) files a
// findFileCallback would be necessary. but findFileCallback does not support virtual files, so we can't
// implement it.
options->setReadFileCallback(new ImageReadCallback(imageManager));
if (isColladaFile)
options->setOptionString("daeUseSequencedTextureUnits");
const std::array<std::uint64_t, 2> fileHash = Files::getHash(normalizedFilename.value(), model);
osgDB::ReaderWriter::ReadResult result = reader->readNode(model, options);
if (!result.success())
{
std::stringstream errormsg;
errormsg << "Error loading " << normalizedFilename << ": " << result.message() << " code "
<< result.status() << std::endl;
throw std::runtime_error(errormsg.str());
}
// Recognize and hide collision node
unsigned int hiddenNodeMask = 0;
SceneUtil::FindByNameVisitor nameFinder("Collision");
auto node = result.getNode();
node->accept(nameFinder);
if (nameFinder.mFoundNode)
nameFinder.mFoundNode->setNodeMask(hiddenNodeMask);
// Recognize and convert osgAnimation::RigGeometry to OpenMW-optimized type
SceneUtil::FindByClassVisitor rigFinder("RigGeometry");
node->accept(rigFinder);
// If a collada file with rigs, we should replace underscores with spaces
if (isColladaFile && !rigFinder.mFoundNodes.empty())
{
ReplaceAnimationUnderscoresVisitor renamingVisitor;
node->accept(renamingVisitor);
}
for (osg::Node* foundRigNode : rigFinder.mFoundNodes)
{
if (foundRigNode->libraryName() == std::string_view("osgAnimation"))
{
osgAnimation::RigGeometry* foundRigGeometry = static_cast<osgAnimation::RigGeometry*>(foundRigNode);
osg::ref_ptr<SceneUtil::RigGeometryHolder> newRig
= new SceneUtil::RigGeometryHolder(*foundRigGeometry, osg::CopyOp::DEEP_COPY_ALL);
if (foundRigGeometry->getStateSet())
newRig->setStateSet(foundRigGeometry->getStateSet());
if (osg::Group* parent = dynamic_cast<osg::Group*>(foundRigGeometry->getParent(0)))
{
parent->removeChild(foundRigGeometry);
parent->addChild(newRig);
}
}
}
if (isColladaFile)
{
Resource::ColladaDescriptionVisitor colladaDescriptionVisitor;
node->accept(colladaDescriptionVisitor);
if (colladaDescriptionVisitor.mSkeleton)
{
if (osg::Group* group = dynamic_cast<osg::Group*>(node))
{
group->removeChildren(0, group->getNumChildren());
for (osg::ref_ptr<SceneUtil::RigGeometryHolder> newRiggeometryHolder :
colladaDescriptionVisitor.mRigGeometryHolders)
{
osg::ref_ptr<osg::MatrixTransform> backToOriginTrans = new osg::MatrixTransform();
newRiggeometryHolder->getOrCreateUserDataContainer()->addUserObject(
new TemplateRef(newRiggeometryHolder->getGeometry(0)));
backToOriginTrans->getOrCreateUserDataContainer()->addUserObject(
new TemplateRef(newRiggeometryHolder->getGeometry(0)));
newRiggeometryHolder->setBodyPart(true);
for (int i = 0; i < 2; ++i)
{
if (newRiggeometryHolder->getGeometry(i))
newRiggeometryHolder->getGeometry(i)->setSkeleton(nullptr);
}
backToOriginTrans->addChild(newRiggeometryHolder);
group->addChild(backToOriginTrans);
node->getOrCreateUserDataContainer()->addUserObject(
new TemplateRef(newRiggeometryHolder->getGeometry(0)));
}
}
}
node->getOrCreateStateSet()->addUniform(new osg::Uniform("emissiveMult", 1.f));
node->getOrCreateStateSet()->addUniform(new osg::Uniform("specStrength", 1.f));
node->getOrCreateStateSet()->addUniform(new osg::Uniform("envMapColor", osg::Vec4f(1, 1, 1, 1)));
node->getOrCreateStateSet()->addUniform(new osg::Uniform("useFalloff", false));
node->getOrCreateStateSet()->addUniform(new osg::Uniform("distortionStrength", 0.f));
}
node->setUserValue(Misc::OsgUserValues::sFileHash,
std::string(reinterpret_cast<const char*>(fileHash.data()), fileHash.size() * sizeof(std::uint64_t)));
return node;
}
std::vector<std::string> makeSortedReservedNames()
{
static constexpr std::string_view names[] = {
"Head",
"Neck",
"Chest",
"Groin",
"Right Hand",
"Left Hand",
"Right Wrist",
"Left Wrist",
"Shield Bone",
"Right Forearm",
"Left Forearm",
"Right Upper Arm",
"Left Upper Arm",
"Right Foot",
"Left Foot",
"Right Ankle",
"Left Ankle",
"Right Knee",
"Left Knee",
"Right Upper Leg",
"Left Upper Leg",
"Right Clavicle",
"Left Clavicle",
"Weapon Bone",
"Tail",
"Bip01",
"Root Bone",
"BoneOffset",
"AttachLight",
"Arrow",
"Camera",
"Collision",
"Right_Wrist",
"Left_Wrist",
"Shield_Bone",
"Right_Forearm",
"Left_Forearm",
"Right_Upper_Arm",
"Left_Clavicle",
"Weapon_Bone",
"Root_Bone",
};
std::vector<std::string> result;
result.reserve(2 * std::size(names));
for (std::string_view name : names)
{
result.emplace_back(name);
std::string prefixedName("Tri ");
prefixedName += name;
result.push_back(std::move(prefixedName));
}
std::sort(result.begin(), result.end(), Misc::StringUtils::ciLess);
return result;
}
}
osg::ref_ptr<osg::Node> load(VFS::Path::NormalizedView normalizedFilename, const VFS::Manager* vfs,
Resource::ImageManager* imageManager, Resource::NifFileManager* nifFileManager,
Resource::BgsmFileManager* materialMgr)
{
const std::string_view ext = Misc::getFileExtension(normalizedFilename.value());
if (ext == "nif")
return NifOsg::Loader::load(*nifFileManager->get(normalizedFilename), imageManager, materialMgr);
else if (ext == "spt")
{
Log(Debug::Warning) << "Ignoring SpeedTree data file " << normalizedFilename;
return new osg::Node();
}
else
return loadNonNif(normalizedFilename, *vfs->get(normalizedFilename), imageManager);
}
class CanOptimizeCallback : public SceneUtil::Optimizer::IsOperationPermissibleForObjectCallback
{
public:
bool isReservedName(const std::string& name) const
{
if (name.empty())
return false;
static const std::vector<std::string> reservedNames = makeSortedReservedNames();
const auto it = Misc::partialBinarySearch(reservedNames.begin(), reservedNames.end(), name);
return it != reservedNames.end();
}
bool isOperationPermissibleForObjectImplementation(
const SceneUtil::Optimizer* optimizer, const osg::Drawable* node, unsigned int option) const override
{
if (option & SceneUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS)
{
if (node->asGeometry() && node->className() == std::string("Geometry"))
return true;
else
return false; // ParticleSystem would have to convert space of all the processors, RigGeometry would
// have to convert bones... theoretically possible, but very complicated
}
return (option & optimizer->getPermissibleOptimizationsForObject(node)) != 0;
}
bool isOperationPermissibleForObjectImplementation(
const SceneUtil::Optimizer* optimizer, const osg::Node* node, unsigned int option) const override
{
if (node->getNumDescriptions() > 0)
return false;
if (node->getDataVariance() == osg::Object::DYNAMIC)
return false;
if (isReservedName(node->getName()))
return false;
return (option & optimizer->getPermissibleOptimizationsForObject(node)) != 0;
}
};
static bool canOptimize(std::string_view filename)
{
const std::string_view::size_type slashpos = filename.find_last_of('/');
if (slashpos != std::string_view::npos && slashpos + 1 < filename.size())
{
const std::string_view basename = filename.substr(slashpos + 1);
// xmesh.nif can not be optimized because there are keyframes added in post
if (!basename.empty() && basename[0] == 'x')
return false;
// NPC skeleton files can not be optimized because of keyframes added in post
// (most of them are usually named like 'xbase_anim.nif' anyway, but not all of them :( )
if (basename.starts_with("base_anim") || basename.starts_with("skin"))
return false;
}
// For spell VFX, DummyXX nodes must remain intact. Not adding those to reservedNames to avoid being overly
// cautious - instead, decide on filename
if (filename.find("vfx_pattern") != std::string_view::npos)
return false;
return true;
}
unsigned int getOptimizationOptions()
{
using namespace SceneUtil;
const char* env = getenv("OPENMW_OPTIMIZE");
unsigned int options
= Optimizer::FLATTEN_STATIC_TRANSFORMS | Optimizer::REMOVE_REDUNDANT_NODES | Optimizer::MERGE_GEOMETRY;
if (env)
{
std::string str(env);
if (str.find("OFF") != std::string::npos || str.find('0') != std::string::npos)
options = 0;
if (str.find("~FLATTEN_STATIC_TRANSFORMS") != std::string::npos)
options ^= Optimizer::FLATTEN_STATIC_TRANSFORMS;
else if (str.find("FLATTEN_STATIC_TRANSFORMS") != std::string::npos)
options |= Optimizer::FLATTEN_STATIC_TRANSFORMS;
if (str.find("~REMOVE_REDUNDANT_NODES") != std::string::npos)
options ^= Optimizer::REMOVE_REDUNDANT_NODES;
else if (str.find("REMOVE_REDUNDANT_NODES") != std::string::npos)
options |= Optimizer::REMOVE_REDUNDANT_NODES;
if (str.find("~MERGE_GEOMETRY") != std::string::npos)
options ^= Optimizer::MERGE_GEOMETRY;
else if (str.find("MERGE_GEOMETRY") != std::string::npos)
options |= Optimizer::MERGE_GEOMETRY;
}
return options;
}
void SceneManager::shareState(osg::ref_ptr<osg::Node> node)
{
mSharedStateMutex.lock();
mSharedStateManager->share(node.get());
mSharedStateMutex.unlock();
}
osg::ref_ptr<osg::Node> SceneManager::loadErrorMarker()
{
try
{
VFS::Path::Normalized path("meshes/marker_error.****");
for (const auto meshType : { "nif", "osg", "osgt", "osgb", "osgx", "osg2", "dae" })
{
path.changeExtension(meshType);
if (mVFS->exists(path))
return load(path, mVFS, mImageManager, mNifFileManager, mBgsmFileManager);
}
}
catch (const std::exception& e)
{
Log(Debug::Warning) << "Failed to load error marker:" << e.what()
<< ", using embedded marker_error instead";
}
Files::IMemStream file(ErrorMarker::sValue.data(), ErrorMarker::sValue.size());
constexpr VFS::Path::NormalizedView errorMarker("error_marker.osgt");
return loadNonNif(errorMarker, file, mImageManager);
}
osg::ref_ptr<osg::Node> SceneManager::cloneErrorMarker()
{
if (!mErrorMarker)
mErrorMarker = loadErrorMarker();
return static_cast<osg::Node*>(mErrorMarker->clone(osg::CopyOp::DEEP_COPY_ALL));
}
osg::ref_ptr<const osg::Node> SceneManager::getTemplate(VFS::Path::NormalizedView path, bool compile)
{
osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(path);
if (obj)
return osg::ref_ptr<const osg::Node>(static_cast<osg::Node*>(obj.get()));
else
{
osg::ref_ptr<osg::Node> loaded;
try
{
loaded = load(path, mVFS, mImageManager, mNifFileManager, mBgsmFileManager);
SceneUtil::ProcessExtraDataVisitor extraDataVisitor(this);
loaded->accept(extraDataVisitor);
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Failed to load '" << path << "': " << e.what() << ", using marker_error instead";
loaded = cloneErrorMarker();
}
// set filtering settings
SetFilterSettingsVisitor setFilterSettingsVisitor(mMinFilter, mMagFilter, mMaxAnisotropy);
loaded->accept(setFilterSettingsVisitor);
SetFilterSettingsControllerVisitor setFilterSettingsControllerVisitor(
mMinFilter, mMagFilter, mMaxAnisotropy);
loaded->accept(setFilterSettingsControllerVisitor);
SceneUtil::ReplaceDepthVisitor replaceDepthVisitor;
loaded->accept(replaceDepthVisitor);
osg::ref_ptr<Shader::ShaderVisitor> shaderVisitor(createShaderVisitor());
loaded->accept(*shaderVisitor);
if (canOptimize(path.value()))
{
SceneUtil::Optimizer optimizer;
optimizer.setSharedStateManager(mSharedStateManager, &mSharedStateMutex);
optimizer.setIsOperationPermissibleForObjectCallback(new CanOptimizeCallback);
static const unsigned int options
= getOptimizationOptions() | SceneUtil::Optimizer::SHARE_DUPLICATE_STATE;
optimizer.optimize(loaded, options);
}
else
shareState(loaded);
if (compile && mIncrementalCompileOperation)
mIncrementalCompileOperation->add(loaded);
else
loaded->getBound();
mCache->addEntryToObjectCache(path.value(), loaded);
return loaded;
}
}
osg::ref_ptr<osg::Node> SceneManager::getInstance(VFS::Path::NormalizedView path)
{
return getInstance(getTemplate(path));
}
osg::ref_ptr<osg::Node> SceneManager::cloneNode(const osg::Node* base)
{
SceneUtil::CopyOp copyop;
if (const osg::Drawable* drawable = base->asDrawable())
{
if (drawable->asGeometry())
{
Log(Debug::Warning) << "SceneManager::cloneNode: attempting to clone osg::Geometry. For safety reasons "
"this will be expensive. Consider avoiding this call.";
copyop.setCopyFlags(
copyop.getCopyFlags() | osg::CopyOp::DEEP_COPY_ARRAYS | osg::CopyOp::DEEP_COPY_PRIMITIVES);
}
}
osg::ref_ptr<osg::Node> cloned = static_cast<osg::Node*>(base->clone(copyop));
// add a ref to the original template to help verify the safety of shallow cloning operations
// in addition, if this node is managed by a cache, we hint to the cache that it's still being used and should
// be kept in cache
cloned->getOrCreateUserDataContainer()->addUserObject(new TemplateRef(base));
return cloned;
}
osg::ref_ptr<osg::Node> SceneManager::getInstance(const osg::Node* base)
{
osg::ref_ptr<osg::Node> cloned = cloneNode(base);
// we can skip any scene graphs without update callbacks since we know that particle emitters will have an
// update callback set
if (cloned->getNumChildrenRequiringUpdateTraversal() > 0)
{
InitParticlesVisitor visitor(mParticleSystemMask);
cloned->accept(visitor);
}
return cloned;
}
osg::ref_ptr<osg::Node> SceneManager::getInstance(VFS::Path::NormalizedView path, osg::Group* parentNode)
{
osg::ref_ptr<osg::Node> cloned = getInstance(path);
attachTo(cloned, parentNode);
return cloned;
}
void SceneManager::attachTo(osg::Node* instance, osg::Group* parentNode) const
{
parentNode->addChild(instance);
}
void SceneManager::releaseGLObjects(osg::State* state)
{
mCache->releaseGLObjects(state);
mShaderManager->releaseGLObjects(state);
std::lock_guard<std::mutex> lock(mSharedStateMutex);
mSharedStateManager->releaseGLObjects(state);
}
void SceneManager::setIncrementalCompileOperation(osgUtil::IncrementalCompileOperation* ico)
{
mIncrementalCompileOperation = ico;
}
osgUtil::IncrementalCompileOperation* SceneManager::getIncrementalCompileOperation()
{
return mIncrementalCompileOperation.get();
}
Resource::ImageManager* SceneManager::getImageManager()
{
return mImageManager;
}
void SceneManager::setParticleSystemMask(unsigned int mask)
{
mParticleSystemMask = mask;
}
void SceneManager::setFilterSettings(
const std::string& magfilter, const std::string& minfilter, const std::string& mipmap, int maxAnisotropy)
{
osg::Texture::FilterMode min = osg::Texture::LINEAR;
osg::Texture::FilterMode mag = osg::Texture::LINEAR;
if (magfilter == "nearest")
mag = osg::Texture::NEAREST;
else if (magfilter != "linear")
Log(Debug::Warning) << "Warning: Invalid texture mag filter: " << magfilter;
if (minfilter == "nearest")
min = osg::Texture::NEAREST;
else if (minfilter != "linear")
Log(Debug::Warning) << "Warning: Invalid texture min filter: " << minfilter;
if (mipmap == "nearest")
{
if (min == osg::Texture::NEAREST)
min = osg::Texture::NEAREST_MIPMAP_NEAREST;
else if (min == osg::Texture::LINEAR)
min = osg::Texture::LINEAR_MIPMAP_NEAREST;
}
else if (mipmap != "none")
{
if (mipmap != "linear")
Log(Debug::Warning) << "Warning: Invalid texture mipmap: " << mipmap;
if (min == osg::Texture::NEAREST)
min = osg::Texture::NEAREST_MIPMAP_LINEAR;
else if (min == osg::Texture::LINEAR)
min = osg::Texture::LINEAR_MIPMAP_LINEAR;
}
mMinFilter = min;
mMagFilter = mag;
mMaxAnisotropy = std::max(1, maxAnisotropy);
SetFilterSettingsControllerVisitor setFilterSettingsControllerVisitor(mMinFilter, mMagFilter, mMaxAnisotropy);
SetFilterSettingsVisitor setFilterSettingsVisitor(mMinFilter, mMagFilter, mMaxAnisotropy);
mCache->accept(setFilterSettingsVisitor);
mCache->accept(setFilterSettingsControllerVisitor);
}
void SceneManager::applyFilterSettings(osg::Texture* tex)
{
tex->setFilter(osg::Texture::MIN_FILTER, mMinFilter);
tex->setFilter(osg::Texture::MAG_FILTER, mMagFilter);
tex->setMaxAnisotropy(mMaxAnisotropy);
}
void SceneManager::setUnRefImageDataAfterApply(bool unref)
{
mUnRefImageDataAfterApply = unref;
}
void SceneManager::updateCache(double referenceTime)
{
ResourceManager::updateCache(referenceTime);
mSharedStateMutex.lock();
mSharedStateManager->prune();
mSharedStateMutex.unlock();
if (mIncrementalCompileOperation)
{
std::lock_guard<OpenThreads::Mutex> lock(*mIncrementalCompileOperation->getToCompiledMutex());
osgUtil::IncrementalCompileOperation::CompileSets& sets = mIncrementalCompileOperation->getToCompile();
for (osgUtil::IncrementalCompileOperation::CompileSets::iterator it = sets.begin(); it != sets.end();)
{
int refcount = (*it)->_subgraphToCompile->referenceCount();
if ((*it)->_subgraphToCompile->asDrawable())
refcount -= 1; // ref by CompileList.
if (refcount <= 2) // ref by ObjectCache + ref by _subgraphToCompile.
{
// no other ref = not needed anymore.
it = sets.erase(it);
}
else
++it;
}
}
}
void SceneManager::clearCache()
{
ResourceManager::clearCache();
std::lock_guard<std::mutex> lock(mSharedStateMutex);
mSharedStateManager->clearCache();
}
void SceneManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
{
if (mIncrementalCompileOperation)
{
std::lock_guard<OpenThreads::Mutex> lock(*mIncrementalCompileOperation->getToCompiledMutex());
stats->setAttribute(frameNumber, "Compiling", mIncrementalCompileOperation->getToCompile().size());
}
{
std::lock_guard<std::mutex> lock(mSharedStateMutex);
stats->setAttribute(frameNumber, "Texture", mSharedStateManager->getNumSharedTextures());
stats->setAttribute(frameNumber, "StateSet", mSharedStateManager->getNumSharedStateSets());
}
Resource::reportStats("Node", frameNumber, mCache->getStats(), *stats);
}
osg::ref_ptr<Shader::ShaderVisitor> SceneManager::createShaderVisitor(const std::string& shaderPrefix)
{
osg::ref_ptr<Shader::ShaderVisitor> shaderVisitor(
new Shader::ShaderVisitor(*mShaderManager.get(), *mImageManager, shaderPrefix));
shaderVisitor->setForceShaders(mForceShaders);
shaderVisitor->setAutoUseNormalMaps(mAutoUseNormalMaps);
shaderVisitor->setNormalMapPattern(mNormalMapPattern);
shaderVisitor->setNormalHeightMapPattern(mNormalHeightMapPattern);
shaderVisitor->setAutoUseSpecularMaps(mAutoUseSpecularMaps);
shaderVisitor->setSpecularMapPattern(mSpecularMapPattern);
shaderVisitor->setApplyLightingToEnvMaps(mApplyLightingToEnvMaps);
shaderVisitor->setConvertAlphaTestToAlphaToCoverage(mConvertAlphaTestToAlphaToCoverage);
shaderVisitor->setAdjustCoverageForAlphaTest(mAdjustCoverageForAlphaTest);
shaderVisitor->setSupportsNormalsRT(mSupportsNormalsRT);
shaderVisitor->setWeatherParticleOcclusion(mWeatherParticleOcclusion);
return shaderVisitor;
}
}
| 48,236
|
C++
|
.cpp
| 1,072
| 33.151119
| 120
| 0.604367
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,686
|
bulletshapemanager.cpp
|
OpenMW_openmw/components/resource/bulletshapemanager.cpp
|
#include "bulletshapemanager.hpp"
#include <cstring>
#include <osg/Drawable>
#include <osg/NodeVisitor>
#include <osg/Transform>
#include <osg/TriangleFunctor>
#include <BulletCollision/CollisionShapes/btTriangleMesh.h>
#include <components/misc/osguservalues.hpp>
#include <components/misc/pathhelpers.hpp>
#include <components/sceneutil/visitor.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/pathutil.hpp>
#include <components/nifbullet/bulletnifloader.hpp>
#include "bulletshape.hpp"
#include "multiobjectcache.hpp"
#include "niffilemanager.hpp"
#include "objectcache.hpp"
#include "scenemanager.hpp"
namespace Resource
{
struct GetTriangleFunctor
{
GetTriangleFunctor()
: mTriMesh(nullptr)
{
}
void setTriMesh(btTriangleMesh* triMesh) { mTriMesh = triMesh; }
void setMatrix(const osg::Matrixf& matrix) { mMatrix = matrix; }
inline btVector3 toBullet(const osg::Vec3f& vec) { return btVector3(vec.x(), vec.y(), vec.z()); }
void inline operator()(const osg::Vec3& v1, const osg::Vec3& v2, const osg::Vec3& v3,
bool _temp = false) // Note: unused temp argument left here for OSG versions less than 3.5.6
{
if (mTriMesh)
mTriMesh->addTriangle(
toBullet(mMatrix.preMult(v1)), toBullet(mMatrix.preMult(v2)), toBullet(mMatrix.preMult(v3)));
}
btTriangleMesh* mTriMesh;
osg::Matrixf mMatrix;
};
/// Creates a BulletShape out of a Node hierarchy.
class NodeToShapeVisitor : public osg::NodeVisitor
{
public:
NodeToShapeVisitor()
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mTriangleMesh(nullptr)
{
}
void apply(osg::Drawable& drawable) override
{
if (!mTriangleMesh)
mTriangleMesh.reset(new btTriangleMesh);
osg::Matrixf worldMat = osg::computeLocalToWorld(getNodePath());
osg::TriangleFunctor<GetTriangleFunctor> functor;
functor.setTriMesh(mTriangleMesh.get());
functor.setMatrix(worldMat);
drawable.accept(functor);
}
osg::ref_ptr<BulletShape> getShape()
{
if (!mTriangleMesh || mTriangleMesh->getNumTriangles() == 0)
return osg::ref_ptr<BulletShape>();
osg::ref_ptr<BulletShape> shape(new BulletShape);
auto triangleMeshShape = std::make_unique<TriangleMeshShape>(mTriangleMesh.release(), true);
btVector3 aabbMin = triangleMeshShape->getLocalAabbMin();
btVector3 aabbMax = triangleMeshShape->getLocalAabbMax();
shape->mCollisionBox.mExtents[0] = (aabbMax[0] - aabbMin[0]) / 2.0f;
shape->mCollisionBox.mExtents[1] = (aabbMax[1] - aabbMin[1]) / 2.0f;
shape->mCollisionBox.mExtents[2] = (aabbMax[2] - aabbMin[2]) / 2.0f;
shape->mCollisionBox.mCenter = osg::Vec3f(
(aabbMax[0] + aabbMin[0]) / 2.0f, (aabbMax[1] + aabbMin[1]) / 2.0f, (aabbMax[2] + aabbMin[2]) / 2.0f);
shape->mCollisionShape.reset(triangleMeshShape.release());
return shape;
}
private:
std::unique_ptr<btTriangleMesh> mTriangleMesh;
};
BulletShapeManager::BulletShapeManager(
const VFS::Manager* vfs, SceneManager* sceneMgr, NifFileManager* nifFileManager, double expiryDelay)
: ResourceManager(vfs, expiryDelay)
, mInstanceCache(new MultiObjectCache)
, mSceneManager(sceneMgr)
, mNifFileManager(nifFileManager)
{
}
BulletShapeManager::~BulletShapeManager() = default;
osg::ref_ptr<const BulletShape> BulletShapeManager::getShape(VFS::Path::NormalizedView name)
{
if (osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(name))
return osg::ref_ptr<BulletShape>(static_cast<BulletShape*>(obj.get()));
osg::ref_ptr<BulletShape> shape;
if (Misc::getFileExtension(name.value()) == "nif")
{
NifBullet::BulletNifLoader loader;
shape = loader.load(*mNifFileManager->get(name));
}
else
{
// TODO: support .bullet shape files
osg::ref_ptr<const osg::Node> constNode(mSceneManager->getTemplate(name));
// const-trickery required because there is no const version of NodeVisitor
osg::ref_ptr<osg::Node> node(const_cast<osg::Node*>(constNode.get()));
// Check first if there's a custom collision node
unsigned int visitAllNodesMask = 0xffffffff;
SceneUtil::FindByNameVisitor nameFinder("Collision");
nameFinder.setTraversalMask(visitAllNodesMask);
nameFinder.setNodeMaskOverride(visitAllNodesMask);
node->accept(nameFinder);
if (nameFinder.mFoundNode)
{
NodeToShapeVisitor visitor;
visitor.setTraversalMask(visitAllNodesMask);
visitor.setNodeMaskOverride(visitAllNodesMask);
nameFinder.mFoundNode->accept(visitor);
shape = visitor.getShape();
}
// Generate a collision shape from the mesh
if (!shape)
{
NodeToShapeVisitor visitor;
node->accept(visitor);
shape = visitor.getShape();
if (!shape)
return osg::ref_ptr<BulletShape>();
}
if (shape != nullptr)
{
shape->mFileName = name;
constNode->getUserValue(Misc::OsgUserValues::sFileHash, shape->mFileHash);
}
}
mCache->addEntryToObjectCache(name.value(), shape);
return shape;
}
osg::ref_ptr<BulletShapeInstance> BulletShapeManager::cacheInstance(VFS::Path::NormalizedView name)
{
osg::ref_ptr<BulletShapeInstance> instance = createInstance(name);
if (instance != nullptr)
mInstanceCache->addEntryToObjectCache(name, instance.get());
return instance;
}
osg::ref_ptr<BulletShapeInstance> BulletShapeManager::getInstance(VFS::Path::NormalizedView name)
{
if (osg::ref_ptr<osg::Object> obj = mInstanceCache->takeFromObjectCache(name))
return static_cast<BulletShapeInstance*>(obj.get());
return createInstance(name);
}
osg::ref_ptr<BulletShapeInstance> BulletShapeManager::createInstance(VFS::Path::NormalizedView name)
{
if (osg::ref_ptr<const BulletShape> shape = getShape(name))
return makeInstance(std::move(shape));
return osg::ref_ptr<BulletShapeInstance>();
}
void BulletShapeManager::updateCache(double referenceTime)
{
ResourceManager::updateCache(referenceTime);
mInstanceCache->removeUnreferencedObjectsInCache();
}
void BulletShapeManager::clearCache()
{
ResourceManager::clearCache();
mInstanceCache->clear();
}
void BulletShapeManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
{
Resource::reportStats("Shape", frameNumber, mCache->getStats(), *stats);
Resource::reportStats("Shape Instance", frameNumber, mInstanceCache->getStats(), *stats);
}
}
| 7,333
|
C++
|
.cpp
| 169
| 33.95858
| 118
| 0.641864
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,687
|
multiobjectcache.cpp
|
OpenMW_openmw/components/resource/multiobjectcache.cpp
|
#include "multiobjectcache.hpp"
#include <vector>
#include <osg/Object>
namespace Resource
{
void MultiObjectCache::removeUnreferencedObjectsInCache()
{
std::vector<osg::ref_ptr<osg::Object>> objectsToRemove;
{
std::lock_guard<std::mutex> lock(_objectCacheMutex);
// Remove unreferenced entries from object cache
ObjectCacheMap::iterator oitr = _objectCache.begin();
while (oitr != _objectCache.end())
{
if (oitr->second->referenceCount() <= 1)
{
objectsToRemove.push_back(oitr->second);
_objectCache.erase(oitr++);
++mExpired;
}
else
{
++oitr;
}
}
}
// note, actual unref happens outside of the lock
objectsToRemove.clear();
}
void MultiObjectCache::clear()
{
std::lock_guard<std::mutex> lock(_objectCacheMutex);
_objectCache.clear();
}
void MultiObjectCache::addEntryToObjectCache(VFS::Path::NormalizedView filename, osg::Object* object)
{
if (!object)
{
OSG_ALWAYS << " trying to add NULL object to cache for " << filename << std::endl;
return;
}
std::lock_guard<std::mutex> lock(_objectCacheMutex);
_objectCache.emplace(filename, object);
}
osg::ref_ptr<osg::Object> MultiObjectCache::takeFromObjectCache(VFS::Path::NormalizedView fileName)
{
std::lock_guard<std::mutex> lock(_objectCacheMutex);
++mGet;
const auto it = _objectCache.find(fileName);
if (it != _objectCache.end())
{
osg::ref_ptr<osg::Object> object = std::move(it->second);
_objectCache.erase(it);
++mHit;
return object;
}
return nullptr;
}
void MultiObjectCache::releaseGLObjects(osg::State* state)
{
std::lock_guard<std::mutex> lock(_objectCacheMutex);
for (ObjectCacheMap::iterator itr = _objectCache.begin(); itr != _objectCache.end(); ++itr)
{
osg::Object* object = itr->second.get();
object->releaseGLObjects(state);
}
}
CacheStats MultiObjectCache::getStats() const
{
std::lock_guard<std::mutex> lock(_objectCacheMutex);
return CacheStats{
.mSize = _objectCache.size(),
.mGet = mGet,
.mHit = mHit,
.mExpired = mExpired,
};
}
}
| 2,588
|
C++
|
.cpp
| 78
| 23.397436
| 105
| 0.556668
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,688
|
niffilemanager.cpp
|
OpenMW_openmw/components/resource/niffilemanager.cpp
|
#include "niffilemanager.hpp"
#include <iostream>
#include <osg/Object>
#include <components/vfs/manager.hpp>
#include "objectcache.hpp"
namespace Resource
{
class NifFileHolder : public osg::Object
{
public:
NifFileHolder(const Nif::NIFFilePtr& file)
: mNifFile(file)
{
}
NifFileHolder(const NifFileHolder& copy, const osg::CopyOp& copyop)
: mNifFile(copy.mNifFile)
{
}
NifFileHolder() = default;
META_Object(Resource, NifFileHolder)
Nif::NIFFilePtr mNifFile;
};
NifFileManager::NifFileManager(const VFS::Manager* vfs, const ToUTF8::StatelessUtf8Encoder* encoder)
// NIF files aren't needed any more once the converted objects are cached in SceneManager / BulletShapeManager,
// so no point in using an expiry delay.
: ResourceManager(vfs, 0)
, mEncoder(encoder)
{
}
NifFileManager::~NifFileManager() = default;
Nif::NIFFilePtr NifFileManager::get(VFS::Path::NormalizedView name)
{
osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(name);
if (obj)
return static_cast<NifFileHolder*>(obj.get())->mNifFile;
else
{
auto file = std::make_shared<Nif::NIFFile>(name.value());
Nif::Reader reader(*file, mEncoder);
reader.parse(mVFS->get(name));
obj = new NifFileHolder(file);
mCache->addEntryToObjectCache(name.value(), obj);
return file;
}
}
void NifFileManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
{
Resource::reportStats("Nif", frameNumber, mCache->getStats(), *stats);
}
}
| 1,740
|
C++
|
.cpp
| 50
| 27.2
| 119
| 0.637828
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,689
|
keyframemanager.cpp
|
OpenMW_openmw/components/resource/keyframemanager.cpp
|
#include "keyframemanager.hpp"
#include <array>
#include <components/vfs/manager.hpp>
#include <osgAnimation/Animation>
#include <osgAnimation/BasicAnimationManager>
#include <osgAnimation/Channel>
#include <components/debug/debuglog.hpp>
#include <components/misc/pathhelpers.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/nifosg/nifloader.hpp>
#include <components/sceneutil/keyframe.hpp>
#include <components/sceneutil/osgacontroller.hpp>
#include <components/vfs/pathutil.hpp>
#include "animation.hpp"
#include "objectcache.hpp"
#include "scenemanager.hpp"
namespace Resource
{
namespace
{
std::string parseTextKey(const std::string& line)
{
const std::size_t spacePos = line.find_last_of(' ');
if (spacePos != std::string::npos)
return line.substr(0, spacePos);
return {};
}
double parseTimeSignature(std::string_view line)
{
const std::size_t spacePos = line.find_last_of(' ');
double time = 0.0;
if (spacePos != std::string_view::npos && spacePos + 1 < line.size())
time = Misc::StringUtils::toNumeric<double>(line.substr(spacePos + 1), time);
return time;
}
}
RetrieveAnimationsVisitor::RetrieveAnimationsVisitor(SceneUtil::KeyframeHolder& target,
osg::ref_ptr<osgAnimation::BasicAnimationManager> animationManager, VFS::Path::NormalizedView path,
const VFS::Manager& vfs)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mTarget(target)
, mAnimationManager(std::move(animationManager))
, mPath(path)
, mVFS(&vfs)
{
mPath.changeExtension("txt");
}
bool RetrieveAnimationsVisitor::belongsToLeftUpperExtremity(const std::string& name)
{
static const std::array boneNames = { "bip01 l clavicle", "left clavicle", "bip01 l upperarm", "left upper arm",
"bip01 l forearm", "bip01 l hand", "left hand", "left wrist", "shield bone", "bip01 l pinky1",
"bip01 l pinky2", "bip01 l pinky3", "bip01 l ring1", "bip01 l ring2", "bip01 l ring3", "bip01 l middle1",
"bip01 l middle2", "bip01 l middle3", "bip01 l pointer1", "bip01 l pointer2", "bip01 l pointer3",
"bip01 l thumb1", "bip01 l thumb2", "bip01 l thumb3", "left forearm" };
if (std::find(boneNames.begin(), boneNames.end(), name) != boneNames.end())
return true;
return false;
}
bool RetrieveAnimationsVisitor::belongsToRightUpperExtremity(const std::string& name)
{
static const std::array boneNames = { "bip01 r clavicle", "right clavicle", "bip01 r upperarm",
"right upper arm", "bip01 r forearm", "bip01 r hand", "right hand", "right wrist", "bip01 r thumb1",
"bip01 r thumb2", "bip01 r thumb3", "weapon bone", "bip01 r pinky1", "bip01 r pinky2", "bip01 r pinky3",
"bip01 r ring1", "bip01 r ring2", "bip01 r ring3", "bip01 r middle1", "bip01 r middle2", "bip01 r middle3",
"bip01 r pointer1", "bip01 r pointer2", "bip01 r pointer3", "right forearm" };
if (std::find(boneNames.begin(), boneNames.end(), name) != boneNames.end())
return true;
return false;
}
bool RetrieveAnimationsVisitor::belongsToTorso(const std::string& name)
{
static const std::array boneNames
= { "bip01 spine1", "bip01 spine2", "bip01 neck", "bip01 head", "head", "neck", "chest", "groin" };
if (std::find(boneNames.begin(), boneNames.end(), name) != boneNames.end())
return true;
return false;
}
void RetrieveAnimationsVisitor::addKeyframeController(const std::string& name, const osg::Node& node)
{
osg::ref_ptr<SceneUtil::OsgAnimationController> callback = new SceneUtil::OsgAnimationController();
callback->setName(name);
std::vector<SceneUtil::EmulatedAnimation> emulatedAnimations;
for (const auto& animation : mAnimationManager->getAnimationList())
{
if (animation)
{
//"Default" is osg dae plugin's default naming scheme for unnamed animations
if (animation->getName() == "Default")
{
animation->setName(std::string("idle"));
}
osg::ref_ptr<Resource::Animation> mergedAnimationTrack = new Resource::Animation;
const std::string animationName = animation->getName();
mergedAnimationTrack->setName(animationName);
const osgAnimation::ChannelList& channels = animation->getChannels();
for (const auto& channel : channels)
{
if (name == "Bip01 R Clavicle")
{
if (!belongsToRightUpperExtremity(channel->getTargetName()))
continue;
}
else if (name == "Bip01 L Clavicle")
{
if (!belongsToLeftUpperExtremity(channel->getTargetName()))
continue;
}
else if (name == "Bip01 Spine1")
{
if (!belongsToTorso(channel->getTargetName()))
continue;
}
else if (belongsToRightUpperExtremity(channel->getTargetName())
|| belongsToLeftUpperExtremity(channel->getTargetName())
|| belongsToTorso(channel->getTargetName()))
continue;
mergedAnimationTrack->addChannel(channel.get()->clone());
}
callback->addMergedAnimationTrack(std::move(mergedAnimationTrack));
float startTime = animation->getStartTime();
float stopTime = startTime + animation->getDuration();
SceneUtil::EmulatedAnimation emulatedAnimation;
emulatedAnimation.mStartTime = startTime;
emulatedAnimation.mStopTime = stopTime;
emulatedAnimation.mName = animationName;
emulatedAnimations.emplace_back(emulatedAnimation);
}
}
// mTextKeys is a nif-thing, used by OpenMW's animation system
// Format is likely "AnimationName: [Keyword_optional] [Start OR Stop]"
// AnimationNames are keywords like idle2, idle3... AiPackages and various mechanics control which
// animations are played Keywords can be stuff like Loop, Equip, Unequip, Block, InventoryHandtoHand,
// InventoryWeaponOneHand, PickProbe, Slash, Thrust, Chop... even "Slash Small Follow" osgAnimation formats
// should have a .txt file with the same name, each line holding a textkey and whitespace separated time
// value e.g. idle: start 0.0333
if (const Files::IStreamPtr textKeysFile = mVFS->find(mPath))
{
try
{
std::string line;
while (getline(*textKeysFile, line))
mTarget.mTextKeys.emplace(parseTimeSignature(line), parseTextKey(line));
}
catch (const std::exception& e)
{
Log(Debug::Warning) << "Failed to read text key file \"" << mPath << "\": " << e.what();
}
}
else
{
Log(Debug::Warning) << "Text key file is not found: " << mPath;
}
callback->setEmulatedAnimations(emulatedAnimations);
mTarget.mKeyframeControllers.emplace(name, callback);
}
void RetrieveAnimationsVisitor::apply(osg::Node& node)
{
if (node.libraryName() == std::string_view("osgAnimation") && node.className() == std::string_view("Bone")
&& Misc::StringUtils::lowerCase(node.getName()) == std::string_view("bip01"))
{
addKeyframeController("bip01", node); /* Character root */
addKeyframeController("Bip01 Spine1", node); /* Torso */
addKeyframeController("Bip01 L Clavicle", node); /* Left arm */
addKeyframeController("Bip01 R Clavicle", node); /* Right arm */
}
traverse(node);
}
KeyframeManager::KeyframeManager(const VFS::Manager* vfs, SceneManager* sceneManager, double expiryDelay,
const ToUTF8::StatelessUtf8Encoder* encoder)
: ResourceManager(vfs, expiryDelay)
, mSceneManager(sceneManager)
, mEncoder(encoder)
{
}
osg::ref_ptr<const SceneUtil::KeyframeHolder> KeyframeManager::get(const std::string& name)
{
const VFS::Path::Normalized normalized(name);
osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(normalized);
if (obj)
return osg::ref_ptr<const SceneUtil::KeyframeHolder>(static_cast<SceneUtil::KeyframeHolder*>(obj.get()));
else
{
osg::ref_ptr<SceneUtil::KeyframeHolder> loaded(new SceneUtil::KeyframeHolder);
if (Misc::getFileExtension(normalized) == "kf")
{
auto file = std::make_shared<Nif::NIFFile>(normalized);
Nif::Reader reader(*file, mEncoder);
reader.parse(mVFS->get(normalized));
NifOsg::Loader::loadKf(*file, *loaded.get());
}
else
{
osg::ref_ptr<osg::Node> scene = const_cast<osg::Node*>(mSceneManager->getTemplate(normalized).get());
osg::ref_ptr<osgAnimation::BasicAnimationManager> bam
= dynamic_cast<osgAnimation::BasicAnimationManager*>(scene->getUpdateCallback());
if (bam)
{
Resource::RetrieveAnimationsVisitor rav(*loaded.get(), std::move(bam), normalized, *mVFS);
scene->accept(rav);
}
}
mCache->addEntryToObjectCache(normalized, loaded);
return loaded;
}
}
void KeyframeManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
{
Resource::reportStats("Keyframe", frameNumber, mCache->getStats(), *stats);
}
}
| 10,300
|
C++
|
.cpp
| 211
| 37.236967
| 120
| 0.601413
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,690
|
animation.cpp
|
OpenMW_openmw/components/resource/animation.cpp
|
#include <components/resource/animation.hpp>
#include <osg/ref_ptr>
#include <osgAnimation/Channel>
namespace Resource
{
Animation::Animation(const Animation& anim, const osg::CopyOp& copyop)
: osg::Object(anim, copyop)
, mDuration(0.0f)
, mStartTime(0.0f)
{
const osgAnimation::ChannelList& channels = anim.getChannels();
for (const auto& channel : channels)
addChannel(channel.get()->clone());
}
void Animation::addChannel(osg::ref_ptr<osgAnimation::Channel> pChannel)
{
mChannels.push_back(pChannel);
}
std::vector<osg::ref_ptr<osgAnimation::Channel>>& Animation::getChannels()
{
return mChannels;
}
const std::vector<osg::ref_ptr<osgAnimation::Channel>>& Animation::getChannels() const
{
return mChannels;
}
bool Animation::update(double time)
{
for (const auto& channel : mChannels)
{
channel->update(time, 1.0f, 0);
}
return true;
}
}
| 1,027
|
C++
|
.cpp
| 35
| 23.028571
| 90
| 0.633874
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,691
|
stats.cpp
|
OpenMW_openmw/components/resource/stats.cpp
|
#include "stats.hpp"
#include <algorithm>
#include <iomanip>
#include <span>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include <osg/PolygonMode>
#include <osgText/Font>
#include <osgText/Text>
#include <osgDB/Registry>
#include <osgViewer/Renderer>
#include <osgViewer/Viewer>
#include <components/vfs/manager.hpp>
#include "cachestats.hpp"
namespace Resource
{
namespace
{
constexpr float statsWidth = 1280.0f;
constexpr float statsHeight = 1024.0f;
constexpr float characterSize = 17.0f;
constexpr float backgroundMargin = 5;
constexpr float backgroundSpacing = 3;
constexpr float maxStatsHeight = 420.0f;
constexpr std::size_t pageSize
= static_cast<std::size_t>((maxStatsHeight - 2 * backgroundMargin) / characterSize);
constexpr int statsHandlerKey = osgGA::GUIEventAdapter::KEY_F4;
const VFS::Path::Normalized fontName("Fonts/DejaVuLGCSansMono.ttf");
bool collectStatRendering = false;
bool collectStatCameraObjects = false;
bool collectStatViewerObjects = false;
bool collectStatResource = false;
bool collectStatGPU = false;
bool collectStatEvent = false;
bool collectStatFrameRate = false;
bool collectStatUpdate = false;
bool collectStatEngine = false;
std::vector<std::string> generateAllStatNames()
{
constexpr std::size_t itemsPerPage = 24;
constexpr std::string_view firstPage[] = {
"FrameNumber",
"",
"Loading",
"Compiling",
"WorkQueue",
"WorkThread",
"UnrefQueue",
"",
"Texture",
"StateSet",
"Composite",
"",
"Mechanics Actors",
"Mechanics Objects",
"",
"Physics Actors",
"Physics Objects",
"Physics Projectiles",
"Physics HeightFields",
"",
"Lua UsedMemory",
"",
"",
"",
};
static_assert(std::size(firstPage) == itemsPerPage);
constexpr std::string_view caches[] = {
"Node",
"Shape",
"Shape Instance",
"Image",
"Nif",
"Keyframe",
"BSShader Material",
"Groundcover Chunk",
"Object Chunk",
"Terrain Chunk",
"Terrain Texture",
"Land",
"Blending Rules",
};
constexpr std::string_view cellPreloader[] = {
"CellPreloader Count",
"CellPreloader Added",
"CellPreloader Evicted",
"CellPreloader Loaded",
"CellPreloader Expired",
};
constexpr std::string_view navMesh[] = {
"NavMesh Jobs",
"NavMesh Removing",
"NavMesh Updating",
"NavMesh Delayed",
"NavMesh Pushed",
"NavMesh Processing",
"NavMesh DbJobs Write",
"NavMesh DbJobs Read",
"NavMesh DbCache Get",
"NavMesh DbCache Hit",
"NavMesh CacheSize",
"NavMesh UsedTiles",
"NavMesh CachedTiles",
"NavMesh Cache Get",
"NavMesh Cache Hit",
"NavMesh Recast Tiles",
"NavMesh Recast Objects",
"NavMesh Recast Heightfields",
"NavMesh Recast Water",
};
std::vector<std::string> statNames;
for (std::string_view name : firstPage)
statNames.emplace_back(name);
for (std::size_t i = 0; i < std::size(caches); ++i)
{
Resource::addCacheStatsAttibutes(caches[i], statNames);
if ((i + 1) % 5 != 0)
statNames.emplace_back();
}
for (std::string_view name : cellPreloader)
statNames.emplace_back(name);
while (statNames.size() % itemsPerPage != 0)
statNames.emplace_back();
for (std::string_view name : navMesh)
statNames.emplace_back(name);
return statNames;
}
void setupStatCollection()
{
const char* envList = getenv("OPENMW_OSG_STATS_LIST");
if (envList == nullptr)
return;
std::string_view kwList(envList);
auto kwBegin = kwList.begin();
while (kwBegin != kwList.end())
{
auto kwEnd = std::find(kwBegin, kwList.end(), ';');
const auto kw = kwList.substr(std::distance(kwList.begin(), kwBegin), std::distance(kwBegin, kwEnd));
if (kw == "gpu")
collectStatGPU = true;
else if (kw == "event")
collectStatEvent = true;
else if (kw == "frame_rate")
collectStatFrameRate = true;
else if (kw == "update")
collectStatUpdate = true;
else if (kw == "engine")
collectStatEngine = true;
else if (kw == "rendering")
collectStatRendering = true;
else if (kw == "cameraobjects")
collectStatCameraObjects = true;
else if (kw == "viewerobjects")
collectStatViewerObjects = true;
else if (kw == "resource")
collectStatResource = true;
else if (kw == "times")
{
collectStatGPU = true;
collectStatEvent = true;
collectStatFrameRate = true;
collectStatUpdate = true;
collectStatEngine = true;
collectStatRendering = true;
}
if (kwEnd == kwList.end())
break;
kwBegin = std::next(kwEnd);
}
}
osg::ref_ptr<osg::Geometry> createBackgroundRectangle(
const osg::Vec3& pos, const float width, const float height, const osg::Vec4& color)
{
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
geometry->setUseDisplayList(false);
osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet;
geometry->setStateSet(stateSet);
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
vertices->push_back(osg::Vec3(pos.x(), pos.y(), 0));
vertices->push_back(osg::Vec3(pos.x(), pos.y() - height, 0));
vertices->push_back(osg::Vec3(pos.x() + width, pos.y() - height, 0));
vertices->push_back(osg::Vec3(pos.x() + width, pos.y(), 0));
geometry->setVertexArray(vertices);
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array;
colors->push_back(color);
geometry->setColorArray(colors, osg::Array::BIND_OVERALL);
osg::ref_ptr<osg::DrawElementsUShort> base
= new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLE_FAN, 0);
base->push_back(0);
base->push_back(1);
base->push_back(2);
base->push_back(3);
geometry->addPrimitiveSet(base);
return geometry;
}
osg::ref_ptr<osgText::Font> getMonoFont(const VFS::Manager& vfs)
{
if (osgDB::Registry::instance()->getReaderWriterForExtension("ttf") && vfs.exists(fontName))
{
const Files::IStreamPtr streamPtr = vfs.get(fontName);
return osgText::readRefFontStream(*streamPtr);
}
return nullptr;
}
class SetFontVisitor : public osg::NodeVisitor
{
public:
SetFontVisitor(osgText::Font* font)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mFont(font)
{
}
void apply(osg::Drawable& node) override
{
if (osgText::Text* text = dynamic_cast<osgText::Text*>(&node))
{
text->setFont(mFont);
}
}
private:
osgText::Font* mFont;
};
}
Profiler::Profiler(bool offlineCollect, const VFS::Manager& vfs)
: mOfflineCollect(offlineCollect)
, mTextFont(getMonoFont(vfs))
{
_characterSize = characterSize;
_font.clear();
setKeyEventTogglesOnScreenStats(osgGA::GUIEventAdapter::KEY_F3);
setupStatCollection();
}
void Profiler::setUpFonts()
{
if (mTextFont != nullptr)
{
SetFontVisitor visitor(mTextFont);
_switch->accept(visitor);
}
mInitFonts = true;
}
bool Profiler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
osgViewer::ViewerBase* viewer = nullptr;
bool handled = StatsHandler::handle(ea, aa);
if (_initialized && !mInitFonts)
setUpFonts();
auto* view = dynamic_cast<osgViewer::View*>(&aa);
if (view)
viewer = view->getViewerBase();
if (viewer != nullptr)
{
// Add/remove openmw stats to the osd as necessary
viewer->getViewerStats()->collectStats("engine", _statsType >= StatsHandler::StatsType::VIEWER_STATS);
if (mOfflineCollect)
collectStatistics(*viewer);
}
return handled;
}
StatsHandler::StatsHandler(bool offlineCollect, const VFS::Manager& vfs)
: mOfflineCollect(offlineCollect)
, mSwitch(new osg::Switch)
, mCamera(new osg::Camera)
, mTextFont(getMonoFont(vfs))
, mStatNames(generateAllStatNames())
{
osg::ref_ptr<osg::StateSet> stateset = mSwitch->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
stateset->setMode(GL_BLEND, osg::StateAttribute::ON);
stateset->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
#ifdef OSG_GL1_AVAILABLE
stateset->setAttribute(new osg::PolygonMode(), osg::StateAttribute::PROTECTED);
#endif
mCamera->getOrCreateStateSet()->setGlobalDefaults();
mCamera->setRenderer(new osgViewer::Renderer(mCamera.get()));
mCamera->setProjectionResizePolicy(osg::Camera::FIXED);
mCamera->addChild(mSwitch);
}
bool StatsHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getHandled())
return false;
switch (ea.getEventType())
{
case (osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey() == statsHandlerKey)
{
osgViewer::View* const view = dynamic_cast<osgViewer::View*>(&aa);
if (view == nullptr)
return false;
osgViewer::ViewerBase* const viewer = view->getViewerBase();
if (viewer == nullptr)
return false;
toggle(*viewer);
if (mOfflineCollect)
collectStatistics(*viewer);
aa.requestRedraw();
return true;
}
break;
}
case osgGA::GUIEventAdapter::RESIZE:
{
setWindowSize(ea.getWindowWidth(), ea.getWindowHeight());
break;
}
default:
break;
}
return false;
}
void StatsHandler::setWindowSize(int width, int height)
{
if (width <= 0 || height <= 0)
return;
mCamera->setViewport(0, 0, width, height);
if (std::abs(height * statsWidth) <= std::abs(width * statsHeight))
{
mCamera->setProjectionMatrix(
osg::Matrix::ortho2D(statsWidth - width * statsHeight / height, statsWidth, 0.0, statsHeight));
}
else
{
mCamera->setProjectionMatrix(
osg::Matrix::ortho2D(0.0, statsWidth, statsHeight - height * statsWidth / width, statsHeight));
}
}
void StatsHandler::toggle(osgViewer::ViewerBase& viewer)
{
if (!mInitialized)
{
setUpHUDCamera(viewer);
setUpScene(viewer);
mInitialized = true;
}
if (mPage == mSwitch->getNumChildren())
{
mPage = 0;
mCamera->setNodeMask(0);
mSwitch->setAllChildrenOff();
viewer.getViewerStats()->collectStats("resource", false);
}
else
{
mCamera->setNodeMask(0xffffffff);
mSwitch->setSingleChildOn(mPage);
viewer.getViewerStats()->collectStats("resource", true);
++mPage;
}
}
void StatsHandler::setUpHUDCamera(osgViewer::ViewerBase& viewer)
{
// Try GraphicsWindow first so we're likely to get the main viewer window
osg::GraphicsContext* context = dynamic_cast<osgViewer::GraphicsWindow*>(mCamera->getGraphicsContext());
if (!context)
{
osgViewer::Viewer::Windows windows;
viewer.getWindows(windows);
if (!windows.empty())
context = windows.front();
else
{
// No GraphicsWindows were found, so let's try to find a GraphicsContext
context = mCamera->getGraphicsContext();
if (!context)
{
osgViewer::Viewer::Contexts contexts;
viewer.getContexts(contexts);
if (contexts.empty())
return;
context = contexts.front();
}
}
}
mCamera->setGraphicsContext(context);
mCamera->setRenderOrder(osg::Camera::POST_RENDER, 11);
mCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
mCamera->setViewMatrix(osg::Matrix::identity());
setWindowSize(context->getTraits()->width, context->getTraits()->height);
// only clear the depth buffer
mCamera->setClearMask(0);
mCamera->setAllowEventFocus(false);
mCamera->setRenderer(new osgViewer::Renderer(mCamera.get()));
}
namespace
{
class ResourceStatsTextDrawCallback : public osg::Drawable::DrawCallback
{
public:
explicit ResourceStatsTextDrawCallback(osg::Stats* stats, std::span<const std::string> statNames)
: mStats(stats)
, mStatNames(statNames)
{
}
void drawImplementation(osg::RenderInfo& renderInfo, const osg::Drawable* drawable) const override
{
if (mStats == nullptr)
return;
osgText::Text* text = (osgText::Text*)(drawable);
std::ostringstream viewStr;
viewStr.setf(std::ios::left, std::ios::adjustfield);
viewStr.width(14);
// Used fixed formatting, as scientific will switch to "...e+.." notation for
// large numbers of vertices/drawables/etc.
viewStr.setf(std::ios::fixed);
viewStr.precision(0);
const unsigned int frameNumber = renderInfo.getState()->getFrameStamp()->getFrameNumber() - 1;
for (const std::string& statName : mStatNames)
{
if (statName.empty())
viewStr << std::endl;
else
{
double value = 0.0;
if (mStats->getAttribute(frameNumber, statName, value))
viewStr << std::setw(8) << value << std::endl;
else
viewStr << std::setw(8) << "." << std::endl;
}
}
text->setText(viewStr.str());
text->drawImplementation(renderInfo);
}
private:
osg::ref_ptr<osg::Stats> mStats;
std::span<const std::string> mStatNames;
};
}
void StatsHandler::setUpScene(osgViewer::ViewerBase& viewer)
{
const osg::Vec4 backgroundColor(0.0, 0.0, 0.0f, 0.3);
const osg::Vec4 staticTextColor(1.0, 1.0, 0.0f, 1.0);
const osg::Vec4 dynamicTextColor(1.0, 1.0, 1.0f, 1.0);
const auto longest = std::max_element(mStatNames.begin(), mStatNames.end(),
[](const std::string& lhs, const std::string& rhs) { return lhs.size() < rhs.size(); });
const std::size_t longestSize = longest->size();
const float statNamesWidth = longestSize * characterSize * 0.6 + 2 * backgroundMargin;
const float statTextWidth = 7 * characterSize + 2 * backgroundMargin;
const float statHeight = pageSize * characterSize + 2 * backgroundMargin;
const float width = statNamesWidth + backgroundSpacing + statTextWidth;
for (std::size_t offset = 0; offset < mStatNames.size(); offset += pageSize)
{
osg::ref_ptr<osg::Group> group = new osg::Group;
group->setCullingActive(false);
const std::size_t count = std::min(mStatNames.size() - offset, pageSize);
std::span<const std::string> currentStatNames(mStatNames.data() + offset, count);
osg::Vec3 pos(statsWidth - width, statHeight - characterSize, 0.0f);
group->addChild(
createBackgroundRectangle(pos + osg::Vec3(-backgroundMargin, backgroundMargin + characterSize, 0),
statNamesWidth, statHeight, backgroundColor));
osg::ref_ptr<osgText::Text> staticText = new osgText::Text;
group->addChild(staticText.get());
staticText->setColor(staticTextColor);
staticText->setCharacterSize(characterSize);
staticText->setPosition(pos);
std::ostringstream viewStr;
viewStr.clear();
viewStr.setf(std::ios::left, std::ios::adjustfield);
viewStr.width(longestSize);
for (const std::string& statName : currentStatNames)
viewStr << statName << std::endl;
staticText->setText(viewStr.str());
pos.x() += statNamesWidth + backgroundSpacing;
group->addChild(
createBackgroundRectangle(pos + osg::Vec3(-backgroundMargin, backgroundMargin + characterSize, 0),
statTextWidth, statHeight, backgroundColor));
osg::ref_ptr<osgText::Text> statsText = new osgText::Text;
group->addChild(statsText.get());
statsText->setColor(dynamicTextColor);
statsText->setCharacterSize(characterSize);
statsText->setPosition(pos);
statsText->setText("");
statsText->setDrawCallback(new ResourceStatsTextDrawCallback(viewer.getViewerStats(), currentStatNames));
if (mTextFont != nullptr)
{
staticText->setFont(mTextFont);
statsText->setFont(mTextFont);
}
mSwitch->addChild(group, false);
}
}
void StatsHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding(statsHandlerKey, "On screen resource usage stats.");
}
void collectStatistics(osgViewer::ViewerBase& viewer)
{
osgViewer::Viewer::Cameras cameras;
viewer.getCameras(cameras);
for (auto* camera : cameras)
{
if (collectStatGPU)
camera->getStats()->collectStats("gpu", true);
if (collectStatRendering)
camera->getStats()->collectStats("rendering", true);
if (collectStatCameraObjects)
camera->getStats()->collectStats("scene", true);
}
if (collectStatEvent)
viewer.getViewerStats()->collectStats("event", true);
if (collectStatFrameRate)
viewer.getViewerStats()->collectStats("frame_rate", true);
if (collectStatUpdate)
viewer.getViewerStats()->collectStats("update", true);
if (collectStatResource)
viewer.getViewerStats()->collectStats("resource", true);
if (collectStatViewerObjects)
viewer.getViewerStats()->collectStats("scene", true);
if (collectStatEngine)
viewer.getViewerStats()->collectStats("engine", true);
}
}
| 21,071
|
C++
|
.cpp
| 515
| 27.982524
| 117
| 0.543934
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,692
|
imagemanager.cpp
|
OpenMW_openmw/components/resource/imagemanager.cpp
|
#include "imagemanager.hpp"
#include <cassert>
#include <osgDB/Registry>
#include <components/debug/debuglog.hpp>
#include <components/misc/pathhelpers.hpp>
#include <components/sceneutil/glextensions.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/pathutil.hpp>
#include "objectcache.hpp"
#ifdef OSG_LIBRARY_STATIC
// This list of plugins should match with the list in the top-level CMakelists.txt.
USE_OSGPLUGIN(png)
USE_OSGPLUGIN(tga)
USE_OSGPLUGIN(dds)
USE_OSGPLUGIN(jpeg)
USE_OSGPLUGIN(bmp)
USE_OSGPLUGIN(osg)
USE_SERIALIZER_WRAPPER_LIBRARY(osg)
#endif
namespace
{
osg::ref_ptr<osg::Image> createWarningImage()
{
osg::ref_ptr<osg::Image> warningImage = new osg::Image;
int width = 8, height = 8;
warningImage->allocateImage(width, height, 1, GL_RGB, GL_UNSIGNED_BYTE);
assert(warningImage->isDataContiguous());
unsigned char* data = warningImage->data();
for (int i = 0; i < width * height; ++i)
{
data[3 * i] = (255);
data[3 * i + 1] = (0);
data[3 * i + 2] = (255);
}
return warningImage;
}
}
namespace Resource
{
ImageManager::ImageManager(const VFS::Manager* vfs, double expiryDelay)
: ResourceManager(vfs, expiryDelay)
, mWarningImage(createWarningImage())
, mOptions(new osgDB::Options("dds_flip dds_dxt1_detect_rgba ignoreTga2Fields"))
, mOptionsNoFlip(new osgDB::Options("dds_dxt1_detect_rgba ignoreTga2Fields"))
{
}
ImageManager::~ImageManager() {}
bool checkSupported(osg::Image* image)
{
switch (image->getPixelFormat())
{
case (GL_COMPRESSED_RGB_S3TC_DXT1_EXT):
case (GL_COMPRESSED_RGBA_S3TC_DXT1_EXT):
case (GL_COMPRESSED_RGBA_S3TC_DXT3_EXT):
case (GL_COMPRESSED_RGBA_S3TC_DXT5_EXT):
{
if (!SceneUtil::glExtensionsReady())
return true; // hashtag yolo (CS might not have context when loading assets)
osg::GLExtensions& exts = SceneUtil::getGLExtensions();
if (!exts.isTextureCompressionS3TCSupported
// This one works too. Should it be included in isTextureCompressionS3TCSupported()? Submitted as a
// patch to OSG.
&& !osg::isGLExtensionSupported(exts.contextID, "GL_S3_s3tc"))
{
return false;
}
break;
}
// not bothering with checks for other compression formats right now
default:
return true;
}
return true;
}
osg::ref_ptr<osg::Image> ImageManager::getImage(VFS::Path::NormalizedView path, bool disableFlip)
{
osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(path);
if (obj)
return osg::ref_ptr<osg::Image>(static_cast<osg::Image*>(obj.get()));
else
{
Files::IStreamPtr stream;
try
{
stream = mVFS->get(path);
}
catch (std::exception& e)
{
Log(Debug::Error) << "Failed to open image: " << e.what();
mCache->addEntryToObjectCache(path.value(), mWarningImage);
return mWarningImage;
}
const std::string ext(Misc::getFileExtension(path.value()));
osgDB::ReaderWriter* reader = osgDB::Registry::instance()->getReaderWriterForExtension(ext);
if (!reader)
{
Log(Debug::Error) << "Error loading " << path << ": no readerwriter for '" << ext << "' found";
mCache->addEntryToObjectCache(path.value(), mWarningImage);
return mWarningImage;
}
bool killAlpha = false;
if (reader->supportedExtensions().count("tga"))
{
// Morrowind ignores the alpha channel of 16bpp TGA files even when the header says not to
unsigned char header[18];
stream->read((char*)header, 18);
if (stream->gcount() != 18)
{
Log(Debug::Error) << "Error loading " << path << ": couldn't read TGA header";
mCache->addEntryToObjectCache(path.value(), mWarningImage);
return mWarningImage;
}
int type = header[2];
int depth;
if (type == 1 || type == 9)
depth = header[7];
else
depth = header[16];
int alphaBPP = header[17] & 0x0F;
killAlpha = depth == 16 && alphaBPP == 1;
stream->seekg(0);
}
osgDB::ReaderWriter::ReadResult result
= reader->readImage(*stream, disableFlip ? mOptionsNoFlip : mOptions);
if (!result.success())
{
Log(Debug::Error) << "Error loading " << path << ": " << result.message() << " code "
<< result.status();
mCache->addEntryToObjectCache(path.value(), mWarningImage);
return mWarningImage;
}
osg::ref_ptr<osg::Image> image = result.getImage();
image->setFileName(std::string(path.value()));
if (!checkSupported(image))
{
static bool uncompress = (getenv("OPENMW_DECOMPRESS_TEXTURES") != nullptr);
if (!uncompress)
{
Log(Debug::Error) << "Error loading " << path << ": no S3TC texture compression support installed";
mCache->addEntryToObjectCache(path.value(), mWarningImage);
return mWarningImage;
}
else
{
// decompress texture in software if not supported by GPU
// requires update to getColor() to be released with OSG 3.6
osg::ref_ptr<osg::Image> newImage = new osg::Image;
newImage->setFileName(image->getFileName());
newImage->allocateImage(image->s(), image->t(), image->r(),
image->isImageTranslucent() ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE);
for (int s = 0; s < image->s(); ++s)
for (int t = 0; t < image->t(); ++t)
for (int r = 0; r < image->r(); ++r)
newImage->setColor(image->getColor(s, t, r), s, t, r);
image = newImage;
}
}
else if (killAlpha)
{
osg::ref_ptr<osg::Image> newImage = new osg::Image;
newImage->setFileName(image->getFileName());
newImage->allocateImage(image->s(), image->t(), image->r(), GL_RGB, GL_UNSIGNED_BYTE);
// OSG just won't write the alpha as there's nowhere to put it.
for (int s = 0; s < image->s(); ++s)
for (int t = 0; t < image->t(); ++t)
for (int r = 0; r < image->r(); ++r)
newImage->setColor(image->getColor(s, t, r), s, t, r);
image = newImage;
}
mCache->addEntryToObjectCache(path.value(), image);
return image;
}
}
osg::Image* ImageManager::getWarningImage()
{
return mWarningImage;
}
void ImageManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
{
Resource::reportStats("Image", frameNumber, mCache->getStats(), *stats);
}
}
| 7,745
|
C++
|
.cpp
| 182
| 29.950549
| 119
| 0.533351
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,693
|
cachestats.cpp
|
OpenMW_openmw/components/resource/cachestats.cpp
|
#include "cachestats.hpp"
#include <osg/Stats>
namespace Resource
{
namespace
{
std::string makeAttribute(std::string_view prefix, std::string_view suffix)
{
std::string result;
result.reserve(prefix.size() + 1 + suffix.size());
result += prefix;
result += ' ';
result += suffix;
return result;
}
}
void addCacheStatsAttibutes(std::string_view prefix, std::vector<std::string>& out)
{
constexpr std::string_view suffixes[] = {
"Count",
"Get",
"Hit",
"Expired",
};
for (std::string_view suffix : suffixes)
out.push_back(makeAttribute(prefix, suffix));
}
void reportStats(std::string_view prefix, unsigned frameNumber, const CacheStats& src, osg::Stats& dst)
{
dst.setAttribute(frameNumber, makeAttribute(prefix, "Count"), static_cast<double>(src.mSize));
dst.setAttribute(frameNumber, makeAttribute(prefix, "Get"), static_cast<double>(src.mGet));
dst.setAttribute(frameNumber, makeAttribute(prefix, "Hit"), static_cast<double>(src.mHit));
dst.setAttribute(frameNumber, makeAttribute(prefix, "Expired"), static_cast<double>(src.mExpired));
}
}
| 1,295
|
C++
|
.cpp
| 35
| 28.771429
| 107
| 0.612749
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,694
|
foreachbulletobject.cpp
|
OpenMW_openmw/components/resource/foreachbulletobject.cpp
|
#include "foreachbulletobject.hpp"
#include <components/debug/debuglog.hpp>
#include <components/esm3/cellref.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/esm3/readerscache.hpp>
#include <components/esmloader/esmdata.hpp>
#include <components/esmloader/lessbyid.hpp>
#include <components/esmloader/record.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/resource/bulletshapemanager.hpp>
#include <components/vfs/manager.hpp>
#include <osg/ref_ptr>
#include <algorithm>
#include <utility>
#include <vector>
namespace Resource
{
namespace
{
struct CellRef
{
ESM::RecNameInts mType;
ESM::RefNum mRefNum;
ESM::RefId mRefId;
float mScale;
ESM::Position mPos;
CellRef(
ESM::RecNameInts type, ESM::RefNum refNum, ESM::RefId&& refId, float scale, const ESM::Position& pos)
: mType(type)
, mRefNum(refNum)
, mRefId(std::move(refId))
, mScale(scale)
, mPos(pos)
{
}
};
ESM::RecNameInts getType(const EsmLoader::EsmData& esmData, const ESM::RefId& refId)
{
const auto it = std::lower_bound(
esmData.mRefIdTypes.begin(), esmData.mRefIdTypes.end(), refId, EsmLoader::LessById{});
if (it == esmData.mRefIdTypes.end() || it->mId != refId)
return {};
return it->mType;
}
std::vector<CellRef> loadCellRefs(
const ESM::Cell& cell, const EsmLoader::EsmData& esmData, ESM::ReadersCache& readers)
{
std::vector<EsmLoader::Record<CellRef>> cellRefs;
for (std::size_t i = 0; i < cell.mContextList.size(); i++)
{
const ESM::ReadersCache::BusyItem reader
= readers.get(static_cast<std::size_t>(cell.mContextList[i].index));
cell.restore(*reader, static_cast<int>(i));
ESM::CellRef cellRef;
bool deleted = false;
while (ESM::Cell::getNextRef(*reader, cellRef, deleted))
{
const ESM::RecNameInts type = getType(esmData, cellRef.mRefID);
if (type == ESM::RecNameInts{})
continue;
cellRefs.emplace_back(
deleted, type, cellRef.mRefNum, std::move(cellRef.mRefID), cellRef.mScale, cellRef.mPos);
}
}
Log(Debug::Debug) << "Loaded " << cellRefs.size() << " cell refs";
const auto getKey = [](const EsmLoader::Record<CellRef>& v) -> ESM::RefNum { return v.mValue.mRefNum; };
std::vector<CellRef> result = prepareRecords(cellRefs, getKey);
Log(Debug::Debug) << "Prepared " << result.size() << " unique cell refs";
return result;
}
template <class F>
void forEachObject(const ESM::Cell& cell, const EsmLoader::EsmData& esmData, const VFS::Manager& vfs,
Resource::BulletShapeManager& bulletShapeManager, ESM::ReadersCache& readers, F&& f)
{
std::vector<CellRef> cellRefs = loadCellRefs(cell, esmData, readers);
Log(Debug::Debug) << "Prepared " << cellRefs.size() << " unique cell refs";
for (CellRef& cellRef : cellRefs)
{
VFS::Path::Normalized model(getModel(esmData, cellRef.mRefId, cellRef.mType));
if (model.empty())
continue;
if (cellRef.mType != ESM::REC_STAT)
model = Misc::ResourceHelpers::correctActorModelPath(model, &vfs);
osg::ref_ptr<const Resource::BulletShape> shape = [&] {
try
{
constexpr VFS::Path::NormalizedView prefix("meshes");
return bulletShapeManager.getShape(prefix / model);
}
catch (const std::exception& e)
{
Log(Debug::Warning) << "Failed to load cell ref \"" << cellRef.mRefId << "\" model \"" << model
<< "\": " << e.what();
return osg::ref_ptr<const Resource::BulletShape>();
}
}();
if (shape == nullptr)
continue;
switch (cellRef.mType)
{
case ESM::REC_ACTI:
case ESM::REC_CONT:
case ESM::REC_DOOR:
case ESM::REC_STAT:
f(BulletObject{ std::move(shape), cellRef.mPos, cellRef.mScale });
break;
default:
break;
}
}
}
}
void forEachBulletObject(ESM::ReadersCache& readers, const VFS::Manager& vfs,
Resource::BulletShapeManager& bulletShapeManager, const EsmLoader::EsmData& esmData,
std::function<void(const ESM::Cell& cell, const BulletObject& object)> callback)
{
Log(Debug::Info) << "Processing " << esmData.mCells.size() << " cells...";
for (std::size_t i = 0; i < esmData.mCells.size(); ++i)
{
const ESM::Cell& cell = esmData.mCells[i];
const bool exterior = cell.isExterior();
Log(Debug::Debug) << "Processing " << (exterior ? "exterior" : "interior") << " cell (" << (i + 1) << "/"
<< esmData.mCells.size() << ") \"" << cell.getDescription() << "\"";
std::size_t objects = 0;
forEachObject(cell, esmData, vfs, bulletShapeManager, readers, [&](const BulletObject& object) {
callback(cell, object);
++objects;
});
Log(Debug::Info) << "Processed " << (exterior ? "exterior" : "interior") << " cell (" << (i + 1) << "/"
<< esmData.mCells.size() << ") " << cell.getDescription() << " with " << objects
<< " objects";
}
}
}
| 6,283
|
C++
|
.cpp
| 136
| 32.455882
| 119
| 0.525809
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,695
|
bgsmfilemanager.cpp
|
OpenMW_openmw/components/resource/bgsmfilemanager.cpp
|
#include "bgsmfilemanager.hpp"
#include <osg/Object>
#include <components/vfs/manager.hpp>
#include "objectcache.hpp"
namespace Resource
{
class BgsmFileHolder : public osg::Object
{
public:
BgsmFileHolder(const Bgsm::MaterialFilePtr& file)
: mBgsmFile(file)
{
}
BgsmFileHolder(const BgsmFileHolder& copy, const osg::CopyOp& copyop)
: mBgsmFile(copy.mBgsmFile)
{
}
BgsmFileHolder() = default;
META_Object(Resource, BgsmFileHolder)
Bgsm::MaterialFilePtr mBgsmFile;
};
BgsmFileManager::BgsmFileManager(const VFS::Manager* vfs, double expiryDelay)
: ResourceManager(vfs, expiryDelay)
{
}
Bgsm::MaterialFilePtr BgsmFileManager::get(VFS::Path::NormalizedView name)
{
osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(name);
if (obj)
return static_cast<BgsmFileHolder*>(obj.get())->mBgsmFile;
else
{
Bgsm::MaterialFilePtr file = Bgsm::parse(mVFS->get(name));
obj = new BgsmFileHolder(file);
mCache->addEntryToObjectCache(name.value(), obj);
return file;
}
}
void BgsmFileManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
{
Resource::reportStats("BSShader Material", frameNumber, mCache->getStats(), *stats);
}
}
| 1,416
|
C++
|
.cpp
| 43
| 25.511628
| 92
| 0.644379
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,696
|
animblendrulesmanager.cpp
|
OpenMW_openmw/components/resource/animblendrulesmanager.cpp
|
#include "animblendrulesmanager.hpp"
#include <array>
#include <components/vfs/manager.hpp>
#include <osg/Stats>
#include <osgAnimation/Animation>
#include <osgAnimation/BasicAnimationManager>
#include <osgAnimation/Channel>
#include <components/debug/debuglog.hpp>
#include <components/misc/pathhelpers.hpp>
#include <components/sceneutil/osgacontroller.hpp>
#include <components/vfs/pathutil.hpp>
#include <components/resource/scenemanager.hpp>
#include "objectcache.hpp"
#include "scenemanager.hpp"
namespace Resource
{
using AnimBlendRules = SceneUtil::AnimBlendRules;
AnimBlendRulesManager::AnimBlendRulesManager(const VFS::Manager* vfs, double expiryDelay)
: ResourceManager(vfs, expiryDelay)
{
}
osg::ref_ptr<const AnimBlendRules> AnimBlendRulesManager::getRules(
const VFS::Path::NormalizedView path, const VFS::Path::NormalizedView overridePath)
{
// Note: Providing a non-existing path but an existing overridePath is not supported!
auto tmpl = loadRules(path);
if (!tmpl)
return nullptr;
// Create an instance based on template and store template reference inside so the template will not be removed
// from cache
osg::ref_ptr<SceneUtil::AnimBlendRules> blendRules(new AnimBlendRules(*tmpl, osg::CopyOp::SHALLOW_COPY));
blendRules->getOrCreateUserDataContainer()->addUserObject(new Resource::TemplateRef(tmpl));
if (!overridePath.value().empty())
{
auto blendRuleOverrides = loadRules(overridePath);
if (blendRuleOverrides)
{
blendRules->addOverrideRules(*blendRuleOverrides);
}
blendRules->getOrCreateUserDataContainer()->addUserObject(new Resource::TemplateRef(blendRuleOverrides));
}
return blendRules;
}
osg::ref_ptr<const AnimBlendRules> AnimBlendRulesManager::loadRules(VFS::Path::NormalizedView path)
{
std::optional<osg::ref_ptr<osg::Object>> obj = mCache->getRefFromObjectCacheOrNone(path);
if (obj.has_value())
{
return osg::ref_ptr<AnimBlendRules>(static_cast<AnimBlendRules*>(obj->get()));
}
osg::ref_ptr<AnimBlendRules> blendRules = AnimBlendRules::fromFile(mVFS, path);
mCache->addEntryToObjectCache(path.value(), blendRules);
return blendRules;
}
void AnimBlendRulesManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
{
Resource::reportStats("Blending Rules", frameNumber, mCache->getStats(), *stats);
}
}
| 2,589
|
C++
|
.cpp
| 59
| 37.169492
| 119
| 0.712296
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,697
|
errormarker.cpp
|
OpenMW_openmw/components/resource/errormarker.cpp
|
#include "errormarker.hpp"
namespace Resource
{
const std::string_view ErrorMarker::sValue = R"osgt(
#Ascii Scene
#Version 162
#Generator OpenSceneGraph 3.6.5
osg::Group {
UniqueID 1
Children 5 {
osg::Group {
UniqueID 2
Name "Error"
Children 1 {
osg::Geometry {
UniqueID 3
DataVariance STATIC
StateSet TRUE {
osg::StateSet {
UniqueID 4
DataVariance STATIC
ModeList 1 {
GL_BLEND ON
}
AttributeList 1 {
osg::Material {
UniqueID 5
Name "Error"
Ambient TRUE Front 1 1 1 0.5 Back 1 1 1 0.5
Diffuse TRUE Front 0.8 0.704 0.32 0.5 Back 0.8 0.704 0.32 0.5
Specular TRUE Front 0.5 0.5 0.5 0.5 Back 0.5 0.5 0.5 0.5
Emission TRUE Front 1 0.88 0.4 0.5 Back 1 0.88 0.4 0.5
Shininess TRUE Front 28.8 Back 28.8
}
Value OFF
}
RenderingHint 2
RenderBinMode USE_RENDERBIN_DETAILS
BinNumber 10
BinName "DepthSortedBin"
}
}
PrimitiveSetList 1 {
osg::DrawElementsUShort {
UniqueID 6
BufferObject TRUE {
osg::ElementBufferObject {
UniqueID 7
Target 34963
}
}
Mode TRIANGLES
vector 108 {
0 1 2 3
0 2 2 4
3 5 3 4
4 6 5 6
7 8 8 9
10 6 8 10
5 6 11 11
6 10 12 5
11 13 12 11
11 14 13 10
15 11 11 15
16 15 17 16
18 16 17 17
19 18 20 21
22 23 20 22
22 24 23 25
23 24 24 26
25 26 27 28
28 29 30 26
28 30 25 26
31 31 26 30
32 25 31 33
32 31 31 34
33 30 35 31
31 35 36 35
37 36 38 36
37 37 39 38
}
}
}
VertexArray TRUE {
osg::Vec3Array {
UniqueID 8
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 9
}
}
Binding BIND_PER_VERTEX
vector 40 {
-4.51996 -5.9634 -60.7026
2e-06 -5.96339 -61.6017
4.51996 -5.96339 -60.7026
-8.3518 -5.9634 -58.1422
8.3518 -5.96339 -58.1422
-58.1422 -5.96341 -8.3518
58.1422 -5.96339 -8.3518
60.7026 -5.96339 -4.51996
61.6017 -5.96339 0
60.7026 -5.96339 4.51996
58.1423 -5.96339 8.3518
-58.1422 -5.96341 8.3518
-60.7026 -5.96341 -4.51996
-61.6017 -5.96341 0
-60.7026 -5.96341 4.51996
8.3518 -5.9634 58.1422
-8.3518 -5.96341 58.1422
4.51997 -5.96341 60.7026
-4.51996 -5.96341 60.7026
2e-06 -5.96341 61.6017
-60.7026 5.96339 -4.51996
-61.6017 5.96339 0
-60.7026 5.96339 4.51996
-58.1423 5.96339 -8.3518
-58.1422 5.96339 8.3518
-8.3518 5.9634 -58.1422
-8.3518 5.96339 58.1422
-4.51996 5.96339 60.7026
-2e-06 5.96339 61.6017
4.51996 5.9634 60.7026
8.3518 5.9634 58.1422
8.3518 5.96341 -58.1422
-4.51997 5.96341 -60.7026
-2e-06 5.96341 -61.6017
4.51996 5.96341 -60.7026
58.1422 5.96341 8.3518
58.1422 5.96341 -8.3518
60.7026 5.96341 4.51996
60.7026 5.96341 -4.51996
61.6017 5.96341 0
}
}
}
NormalArray TRUE {
osg::Vec3Array {
UniqueID 10
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 9
}
}
Binding BIND_PER_VERTEX
vector 40 {
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
}
}
}
TexCoordArrayList 1 {
osg::Vec2Array {
UniqueID 11
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 9
}
}
Binding BIND_PER_VERTEX
vector 40 {
0.37739 0.519384
0.384197 0.509197
0.394384 0.50239
0.375 0.531401
0.406401 0.5
0.375 0.718599
0.593599 0.5
0.605616 0.50239
0.615803 0.509197
0.62261 0.519384
0.625 0.531401
0.406401 0.75
0.37739 0.730616
0.384197 0.740803
0.394384 0.74761
0.625 0.718599
0.593599 0.75
0.62261 0.730616
0.605616 0.74761
0.615803 0.740803
0.37739 0.019384
0.384197 0.009197
0.394384 0.00239
0.375 0.031401
0.406401 0
0.375 0.218599
0.593599 0
0.605616 0.00239
0.615803 0.009197
0.62261 0.019384
0.625 0.031401
0.406401 0.25
0.37739 0.230616
0.384197 0.240803
0.394384 0.24761
0.625 0.218599
0.593599 0.25
0.62261 0.230616
0.605616 0.24761
0.615803 0.240803
}
}
}
}
}
}
)osgt"
R"osgt(
osg::Group {
UniqueID 12
Name "Error"
Children 1 {
osg::Geometry {
UniqueID 13
DataVariance STATIC
StateSet TRUE {
osg::StateSet {
UniqueID 4
}
}
PrimitiveSetList 1 {
osg::DrawElementsUShort {
UniqueID 14
BufferObject TRUE {
osg::ElementBufferObject {
UniqueID 15
Target 34963
}
}
Mode TRIANGLES
vector 120 {
0 1 2 0
3 1 3 4
1 3 5 4
4 5 6 4
6 7 8 7
6 8 6 9
10 8 9 10
9 11 12 13
11 12 11 14
15 12 14 15
14 16 16 17
15 16 18 17
18 19 17 18
20 19 20 21
19 20 22 21
22 23 24 22
25 23 25 26
23 25 27 26
28 26 27 28
29 26 30 29
28 30 28 31
32 30 31 32
31 33 34 35
33 34 33 36
37 34 36 37
36 38 39 37
38 39 38 40
40 41 39 40
42 41 42 43
41 42 0 43
}
}
}
VertexArray TRUE {
osg::Vec3Array {
UniqueID 16
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 17
}
}
Binding BIND_PER_VERTEX
vector 44 {
61.6017 -5.96339 0
60.7026 5.96341 -4.51996
61.6017 5.96341 0
60.7026 -5.96339 -4.51996
58.1422 5.96341 -8.3518
58.1422 -5.96339 -8.3518
8.3518 -5.96339 -58.1422
8.3518 5.96341 -58.1422
4.51996 5.96341 -60.7026
4.51996 -5.96339 -60.7026
-2e-06 5.96341 -61.6017
2e-06 -5.96339 -61.6017
-4.51997 5.96341 -60.7026
-2e-06 5.96341 -61.6017
-4.51996 -5.9634 -60.7026
-8.3518 5.9634 -58.1422
-8.3518 -5.9634 -58.1422
-58.1423 5.96339 -8.3518
-58.1422 -5.96341 -8.3518
-60.7026 5.96339 -4.51996
-60.7026 -5.96341 -4.51996
-61.6017 5.96339 0
-61.6017 -5.96341 0
-60.7026 5.96339 4.51996
-61.6017 5.96339 0
-60.7026 -5.96341 4.51996
-58.1422 5.96339 8.3518
-58.1422 -5.96341 8.3518
-8.3518 -5.96341 58.1422
-8.3518 5.96339 58.1422
-4.51996 5.96339 60.7026
-4.51996 -5.96341 60.7026
-2e-06 5.96339 61.6017
2e-06 -5.96341 61.6017
4.51996 5.9634 60.7026
-2e-06 5.96339 61.6017
4.51997 -5.96341 60.7026
8.3518 5.9634 58.1422
8.3518 -5.9634 58.1422
58.1422 5.96341 8.3518
58.1423 -5.96339 8.3518
60.7026 5.96341 4.51996
60.7026 -5.96339 4.51996
61.6017 5.96341 0
}
}
}
NormalArray TRUE {
osg::Vec3Array {
UniqueID 18
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 17
}
}
Binding BIND_PER_VERTEX
vector 44 {
1 0 0
0.923877 0 -0.38269
0.980784 0 -0.195097
0.923877 0 -0.38269
0.773003 0 -0.634402
0.773003 0 -0.634402
0.634402 0 -0.773003
0.634402 0 -0.773003
0.38269 0 -0.923877
0.38269 0 -0.923877
0.195097 0 -0.980784
0 0 -1
-0.38269 -0 -0.923877
-0.195097 -0 -0.980784
-0.38269 -0 -0.923877
-0.634402 -0 -0.773003
-0.634402 -0 -0.773003
-0.773003 -0 -0.634402
-0.773003 -0 -0.634402
-0.923877 -0 -0.38269
-0.923877 -0 -0.38269
-0.980784 -0 -0.195097
-1 0 0
-0.923877 0 0.38269
-0.980784 0 0.195097
-0.923877 0 0.38269
-0.773003 0 0.634402
-0.773003 0 0.634402
-0.634402 0 0.773003
-0.634402 0 0.773003
-0.38269 0 0.923877
-0.38269 0 0.923877
-0.195097 0 0.980784
0 0 1
0.38269 0 0.923877
0.195097 0 0.980784
0.38269 0 0.923877
0.634402 0 0.773003
0.634402 0 0.773003
0.773003 0 0.634402
0.773003 0 0.634402
0.923877 0 0.38269
0.923877 0 0.38269
0.980784 0 0.195097
}
}
}
TexCoordArrayList 1 {
osg::Vec2Array {
UniqueID 19
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 17
}
}
Binding BIND_PER_VERTEX
vector 44 {
0.625 0.5
0.605616 0.25
0.625 0.25
0.605616 0.5
0.593599 0.25
0.593599 0.5
0.406401 0.5
0.406401 0.25
0.394384 0.25
0.394384 0.5
0.375 0.25
0.375 0.5
0.125 0.519384
0.125 0.5
0.375 0.519384
0.125 0.531401
0.375 0.531401
0.125 0.718599
0.375 0.718599
0.125 0.730616
0.375 0.730616
0.125 0.75
0.375 0.75
0.394384 1
0.375 1
0.394384 0.75
0.406401 1
0.406401 0.75
0.593599 0.75
0.593599 1
0.605616 1
0.605616 0.75
0.625 1
0.625 0.75
0.875 0.730616
0.875 0.75
0.625 0.730616
0.875 0.718599
0.625 0.718599
0.875 0.531401
0.625 0.531401
0.875 0.519384
0.625 0.519384
0.875 0.5
}
}
}
}
}
}
)osgt"
R"osgt(
osg::Group {
UniqueID 20
Name "Error"
Children 1 {
osg::Geometry {
UniqueID 21
DataVariance STATIC
StateSet TRUE {
osg::StateSet {
UniqueID 22
DataVariance STATIC
AttributeList 1 {
osg::Material {
UniqueID 23
Name "ErrorLabel"
Ambient TRUE Front 1 1 1 1 Back 1 1 1 1
Diffuse TRUE Front 0.176208 0.176208 0.176208 1 Back 0.176208 0.176208 0.176208 1
Specular TRUE Front 0.5 0.5 0.5 1 Back 0.5 0.5 0.5 1
Emission TRUE Front 0.22026 0.22026 0.22026 1 Back 0.22026 0.22026 0.22026 1
Shininess TRUE Front 28.8 Back 28.8
}
Value OFF
}
}
}
PrimitiveSetList 1 {
osg::DrawElementsUShort {
UniqueID 24
BufferObject TRUE {
osg::ElementBufferObject {
UniqueID 25
Target 34963
}
}
Mode TRIANGLES
vector 216 {
0 1 2 3
0 2 2 4
3 4 5 3
5 6 7 5
8 3 8 5
7 7 9 8
10 3 8 8
11 10 12 13
10 14 12 10
15 14 10 10
11 15 16 15
11 11 17 16
18 16 17 17
19 18 20 21
22 23 20 22
22 24 23 25
23 24 24 26
25 26 27 28
28 29 30 26
28 30 25 26
31 31 26 30
32 25 31 33
32 31 31 34
33 30 35 31
31 35 36 35
37 36 38 36
37 37 39 38
40 41 42 43
40 42 42 44
43 45 43 44
44 46 45 47
45 46 48 47
46 46 49 48
44 50 46 51
46 50 50 52
53 54 50 53
53 55 54 50
54 51 54 56
51 56 57 51
58 51 57 57
59 58 60 61
62 63 60 62
62 64 63 65
63 64 64 66
65 66 67 68
69 70 65 71
69 65 72 71
65 66 68 73
65 66 73 68
74 73 73 72
65 73 75 72
72 75 76 75
77 76 78 76
77 77 79 78
}
}
}
VertexArray TRUE {
osg::Vec3Array {
UniqueID 26
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 27
}
}
Binding BIND_PER_VERTEX
vector 80 {
-7.12646 -9.95049 -13.7349
-6.35115 -9.95049 -14.8952
-5.1908 -9.95049 -15.6705
-7.39872 -9.95049 -12.3661
-3.82208 -9.95049 -15.9428
3.82208 -9.95049 -15.9428
5.1908 -9.95049 -15.6705
6.35115 -9.95049 -14.8952
7.39872 -9.95049 -12.3661
7.12646 -9.95049 -13.7349
-7.39872 -9.95049 33.4208
7.39872 -9.95049 33.4208
-6.35115 -9.95049 35.9499
-7.12647 -9.95049 34.7895
-5.1908 -9.95049 36.7252
-3.82208 -9.95049 36.9975
3.82208 -9.95049 36.9975
7.12646 -9.95049 34.7895
5.1908 -9.95049 36.7252
6.35115 -9.95049 35.9499
-7.12646 -9.95042 -36.7346
-6.35115 -9.95042 -37.8949
-5.1908 -9.95042 -38.6702
-7.39872 -9.95042 -35.3659
-3.82208 -9.95042 -38.9425
-7.39872 -9.95042 -27.7217
3.82208 -9.95042 -38.9425
5.1908 -9.95042 -38.6702
6.35115 -9.95042 -37.8949
7.12646 -9.95042 -36.7346
7.39872 -9.95042 -35.3659
-3.82208 -9.95042 -24.1451
-7.12647 -9.95042 -26.353
-6.35115 -9.95042 -25.1926
-5.1908 -9.95042 -24.4173
7.39872 -9.95042 -27.7217
3.82208 -9.95042 -24.1451
7.12646 -9.95042 -26.353
5.1908 -9.95042 -24.4173
6.35115 -9.95042 -25.1926
-5.1908 9.95055 -15.6705
-6.35115 9.95055 -14.8952
-7.12646 9.95055 -13.7349
-3.82208 9.95055 -15.9428
-7.39872 9.95055 -12.3661
3.82208 9.95055 -15.9428
7.39872 9.95055 -12.3661
5.1908 9.95055 -15.6705
6.35115 9.95055 -14.8952
7.12646 9.95055 -13.7349
-7.39872 9.95055 33.4208
7.39872 9.95055 33.4208
-7.12646 9.95055 34.7895
-6.35115 9.95056 35.9499
-3.82208 9.95056 36.9975
-5.1908 9.95056 36.7252
3.82208 9.95055 36.9975
5.19081 9.95055 36.7252
7.12646 9.95056 34.7895
6.35115 9.95055 35.9499
-5.1908 9.95062 -38.6702
-6.35115 9.95062 -37.8949
-7.12646 9.95062 -36.7346
-3.82208 9.95062 -38.9425
-7.39872 9.95062 -35.3659
3.82208 9.95062 -38.9425
-7.39872 9.95063 -27.7217
-7.12646 9.95063 -26.353
-6.35115 9.95063 -25.1926
6.35115 9.95062 -37.8949
5.1908 9.95062 -38.6702
7.12647 9.95062 -36.7346
7.39872 9.95062 -35.3659
-3.82208 9.95063 -24.1451
-5.1908 9.95063 -24.4173
3.82208 9.95063 -24.1451
7.39872 9.95062 -27.7217
5.1908 9.95063 -24.4173
7.12646 9.95063 -26.353
6.35115 9.95063 -25.1926
}
}
}
NormalArray TRUE {
osg::Vec3Array {
UniqueID 28
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 27
}
}
Binding BIND_PER_VERTEX
vector 80 {
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 -1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
}
}
}
TexCoordArrayList 1 {
osg::Vec2Array {
UniqueID 29
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 27
}
}
Binding BIND_PER_VERTEX
vector 80 {
0.006133 0.041706
0.023598 0.006596
0.149209 0.001714
0 0.06756
0.241707 0
0.758294 0
0.850791 0.001714
0.976402 0.006596
1 0.06756
0.993867 0.041706
0 0.93244
1 0.93244
0.023598 0.993404
0.006133 0.958294
0.149209 0.998286
0.241706 1
0.758294 1
0.993867 0.958294
0.850791 0.998286
0.976402 0.993404
0.006133 0.149209
0.023598 0.023598
0.149209 0.006133
0 0.241707
0.241707 0
0 0.758294
0.758294 0
0.850791 0.006133
0.976402 0.023598
0.993867 0.149209
1 0.241707
0.241706 1
0.006133 0.850791
0.023598 0.976402
0.149209 0.993867
1 0.758293
0.758294 1
0.993867 0.850791
0.850791 0.993867
0.976402 0.976402
0.149209 0.001714
0.023598 0.006596
0.006133 0.041706
0.241706 0
0 0.06756
0.758294 0
1 0.06756
0.850791 0.001714
0.976402 0.006596
0.993867 0.041706
0 0.93244
1 0.93244
0.006133 0.958294
0.023598 0.993404
0.241707 1
0.149209 0.998286
0.758294 1
0.850791 0.998286
0.993867 0.958294
0.976402 0.993404
0.149209 0.006133
0.023598 0.023598
0.006133 0.149209
0.241706 0
0 0.241707
0.758294 0
0 0.758294
0.006133 0.850791
0.023598 0.976402
0.976402 0.023598
0.850791 0.006133
0.993867 0.149209
1 0.241706
0.241707 1
0.149209 0.993867
0.758294 1
1 0.758294
0.850791 0.993867
0.993867 0.850791
0.976402 0.976402
}
}
}
}
}
}
)osgt"
R"osgt(
osg::Group {
UniqueID 30
Name "Error"
Children 1 {
osg::Geometry {
UniqueID 31
DataVariance STATIC
StateSet TRUE {
osg::StateSet {
UniqueID 22
}
}
PrimitiveSetList 1 {
osg::DrawElementsUShort {
UniqueID 32
BufferObject TRUE {
osg::ElementBufferObject {
UniqueID 33
Target 34963
}
}
Mode TRIANGLES
vector 240 {
0 1 2 0
3 1 0 2
4 0 5 3
4 2 6 5
7 3 4 6
8 5 9 7
6 10 8 9
11 7 6 12
10 9 13 11
12 14 10 13
15 11 12 16
14 13 17 15
16 18 14 19
15 17 16 20
18 19 21 15
18 20 22 23
21 19 18 22
24 23 19 25
26 24 22 27
23 25 26 22
28 27 25 29
30 26 28 31
27 29 30 32
26 31 29 33
34 32 30 35
31 33 34 30
36 35 33 37
38 34 36 39
35 37 38 39
34 39 38 35
40 41 42 43
41 40 40 42
44 43 40 45
46 44 42 47
43 45 46 48
44 47 45 49
50 48 46 51
47 49 50 46
52 51 49 53
54 50 52 55
51 53 54 52
56 55 53 57
58 54 56 57
59 55 58 56
60 57 61 59
58 60 62 61
63 59 58 62
64 61 65 63
62 66 64 65
67 63 62 68
66 65 69 67
66 68 70 69
71 67 66 70
72 69 73 71
70 74 72 71
73 75 70 76
74 71 75 77
76 78 74 75
79 77 76 79
78 75 78 79
}
}
}
VertexArray TRUE {
osg::Vec3Array {
UniqueID 34
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 35
}
}
Binding BIND_PER_VERTEX
vector 80 {
-7.39872 9.95055 -12.3661
-7.39872 -9.95049 -12.3661
-7.39872 -9.95049 33.4208
-7.12646 -9.95049 -13.7349
-7.39872 9.95055 33.4208
-7.12646 9.95055 -13.7349
-7.12647 -9.95049 34.7895
-6.35115 -9.95049 -14.8952
-7.12646 9.95055 34.7895
-6.35115 9.95055 -14.8952
-6.35115 9.95056 35.9499
-5.1908 -9.95049 -15.6705
-6.35115 -9.95049 35.9499
-5.1908 9.95055 -15.6705
-5.1908 9.95056 36.7252
-3.82208 -9.95049 -15.9428
-5.1908 -9.95049 36.7252
-3.82208 9.95055 -15.9428
-3.82208 9.95056 36.9975
3.82208 9.95055 -15.9428
-3.82208 -9.95049 36.9975
3.82208 -9.95049 -15.9428
3.82208 -9.95049 36.9975
5.1908 -9.95049 -15.6705
3.82208 9.95055 36.9975
5.1908 9.95055 -15.6705
5.19081 9.95055 36.7252
6.35115 -9.95049 -14.8952
5.1908 -9.95049 36.7252
6.35115 9.95055 -14.8952
6.35115 -9.95049 35.9499
7.12646 -9.95049 -13.7349
6.35115 9.95055 35.9499
7.12646 9.95055 -13.7349
7.12646 9.95056 34.7895
7.39872 -9.95049 -12.3661
7.12646 -9.95049 34.7895
7.39872 9.95055 -12.3661
7.39872 -9.95049 33.4208
7.39872 9.95055 33.4208
-3.82208 9.95063 -24.1451
-3.82208 -9.95042 -24.1451
3.82208 -9.95042 -24.1451
-5.1908 -9.95042 -24.4173
3.82208 9.95063 -24.1451
-5.1908 9.95063 -24.4173
5.1908 -9.95042 -24.4173
-6.35115 -9.95042 -25.1926
5.1908 9.95063 -24.4173
-6.35115 9.95063 -25.1926
6.35115 9.95063 -25.1926
-7.12647 -9.95042 -26.353
6.35115 -9.95042 -25.1926
-7.12646 9.95063 -26.353
7.12646 9.95063 -26.353
-7.39872 -9.95042 -27.7217
7.12646 -9.95042 -26.353
-7.39872 9.95063 -27.7217
7.39872 9.95062 -27.7217
-7.39872 -9.95042 -35.3659
7.39872 -9.95042 -27.7217
-7.39872 9.95062 -35.3659
7.39872 -9.95042 -35.3659
-7.12646 -9.95042 -36.7346
7.39872 9.95062 -35.3659
-7.12646 9.95062 -36.7346
7.12647 9.95062 -36.7346
-6.35115 -9.95042 -37.8949
7.12646 -9.95042 -36.7346
-6.35115 9.95062 -37.8949
6.35115 -9.95042 -37.8949
-5.1908 -9.95042 -38.6702
6.35115 9.95062 -37.8949
-5.1908 9.95062 -38.6702
5.1908 9.95062 -38.6702
-3.82208 9.95062 -38.9425
5.1908 -9.95042 -38.6702
-3.82208 -9.95042 -38.9425
3.82208 9.95062 -38.9425
3.82208 -9.95042 -38.9425
}
}
}
NormalArray TRUE {
osg::Vec3Array {
UniqueID 36
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 35
}
}
Binding BIND_PER_VERTEX
vector 80 {
-0.995187 -0 -0.0979987
-0.995187 -0 -0.0979987
-0.995187 0 0.0979987
-0.923877 -0 -0.38269
-0.995187 0 0.0979987
-0.923877 -0 -0.38269
-0.923877 0 0.38269
-0.707107 -0 -0.707107
-0.923877 0 0.38269
-0.707107 -0 -0.707107
-0.707107 0 0.707107
-0.38269 -0 -0.923877
-0.707107 0 0.707107
-0.38269 -0 -0.923877
-0.38269 0 0.923877
-0.0979987 -0 -0.995187
-0.38269 0 0.923877
-0.0979987 -0 -0.995187
-0.0979987 0 0.995187
0.0979987 0 -0.995187
-0.0979987 0 0.995187
0.0979987 0 -0.995187
0.0979987 0 0.995187
0.38269 0 -0.923877
0.0979987 0 0.995187
0.38269 0 -0.923877
0.38269 0 0.923877
0.707107 0 -0.707107
0.38269 0 0.923877
0.707107 0 -0.707107
0.707107 0 0.707107
0.923877 0 -0.38269
0.707107 0 0.707107
0.923877 0 -0.38269
0.923877 0 0.38269
0.995187 0 -0.0979987
0.923877 0 0.38269
0.995187 0 -0.0979987
0.995187 0 0.0979987
0.995187 0 0.0979987
-0.0979987 0 0.995187
-0.0979987 0 0.995187
0.0979987 0 0.995187
-0.38269 0 0.923877
0.0979987 0 0.995187
-0.38269 0 0.923877
0.38269 0 0.923877
-0.707107 0 0.707107
0.38269 0 0.923877
-0.707107 0 0.707107
0.707107 0 0.707107
-0.923877 0 0.38269
0.707107 0 0.707107
-0.923877 0 0.38269
0.923877 0 0.38269
-0.995187 0 0.0979987
0.923877 0 0.38269
-0.995187 0 0.0979987
0.995187 0 0.0979987
-0.995187 -0 -0.0979987
0.995187 0 0.0979987
-0.995187 -0 -0.0979987
0.995187 0 -0.0979987
-0.923877 -0 -0.38269
0.995187 0 -0.0979987
-0.923877 -0 -0.38269
0.923877 0 -0.38269
-0.707107 -0 -0.707107
0.923877 0 -0.38269
-0.707107 -0 -0.707107
0.707107 0 -0.707107
-0.38269 -0 -0.923877
0.707107 0 -0.707107
-0.38269 -0 -0.923877
0.38269 0 -0.923877
-0.0979987 -0 -0.995187
0.38269 0 -0.923877
-0.0979987 -0 -0.995187
0.0979987 0 -0.995187
0.0979987 0 -0.995187
}
}
}
TexCoordArrayList 1 {
osg::Vec2Array {
UniqueID 37
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 35
}
}
Binding BIND_PER_VERTEX
vector 80 {
0 0.06756
0 0.06756
0 0.93244
0.006133 0.041706
0 0.93244
0.006133 0.041706
0.006133 0.958294
0.023598 0.006596
0.006133 0.958294
0.023598 0.006596
0.023598 0.993404
0.149209 0.001714
0.023598 0.993404
0.149209 0.001714
0.149209 0.998286
0.241706 0
0.149209 0.998286
0.241707 0
0.241706 1
0.758294 0
0.241707 1
0.758294 0
0.758294 1
0.850791 0.001714
0.758294 1
0.850791 0.001714
0.850791 0.998286
0.976402 0.006596
0.850791 0.998286
0.976402 0.006596
0.976402 0.993404
0.993867 0.041706
0.976402 0.993404
0.993867 0.041706
0.993867 0.958294
1 0.06756
0.993867 0.958294
1 0.06756
1 0.93244
1 0.93244
0.241706 1
0.241707 1
0.758294 1
0.149209 0.993867
0.758294 1
0.149209 0.993867
0.850791 0.993867
0.023598 0.976402
0.850791 0.993867
0.023598 0.976402
0.976402 0.976402
0.006133 0.850791
0.976402 0.976402
0.006133 0.850791
0.993867 0.850791
0 0.758293
0.993867 0.850791
0 0.758294
1 0.758294
0 0.241707
1 0.758294
0 0.241706
1 0.241707
0.006133 0.149209
1 0.241707
0.006133 0.149209
0.993867 0.149209
0.023598 0.023598
0.993867 0.149209
0.023598 0.023598
0.976402 0.023598
0.149209 0.006133
0.976402 0.023598
0.149209 0.006133
0.850791 0.006133
0.241707 0
0.850791 0.006133
0.241706 0
0.758294 0
0.758294 0
}
}
}
}
}
}
)osgt"
R"osgt(
osg::Group {
UniqueID 38
Name "Cube"
Children 1 {
osg::Geometry {
UniqueID 39
DataVariance STATIC
StateSet TRUE {
osg::StateSet {
UniqueID 40
DataVariance STATIC
AttributeList 1 {
osg::Material {
UniqueID 41
Name "Material"
Ambient TRUE Front 1 1 1 1 Back 1 1 1 1
Diffuse TRUE Front 0.8 0.8 0.8 1 Back 0.8 0.8 0.8 1
Specular TRUE Front 0.5 0.5 0.5 1 Back 0.5 0.5 0.5 1
Emission TRUE Front 0 0 0 1 Back 0 0 0 1
Shininess TRUE Front 41.344 Back 41.344
}
Value OFF
}
}
}
PrimitiveSetList 1 {
osg::DrawElementsUShort {
UniqueID 42
BufferObject TRUE {
osg::ElementBufferObject {
UniqueID 43
Target 34963
}
}
Mode TRIANGLES
vector 36 {
0 1 2 0
2 3 4 5
6 4 6 7
8 9 10 8
10 11 12 13
14 12 14 15
16 17 18 16
18 19 20 21
22 20 22 23
}
}
}
VertexArray TRUE {
osg::Vec3Array {
UniqueID 44
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 45
}
}
Binding BIND_PER_VERTEX
vector 24 {
1 1 1
-1 1 1
-1 -1 1
1 -1 1
1 -1 -1
1 -1 1
-1 -1 1
-1 -1 -1
-1 -1 -1
-1 -1 1
-1 1 1
-1 1 -1
-1 1 -1
1 1 -1
1 -1 -1
-1 -1 -1
1 1 -1
1 1 1
1 -1 1
1 -1 -1
-1 1 -1
-1 1 1
1 1 1
1 1 -1
}
}
}
NormalArray TRUE {
osg::Vec3Array {
UniqueID 46
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 45
}
}
Binding BIND_PER_VERTEX
vector 24 {
0 0 1
0 0 1
0 0 1
0 0 1
0 -1 0
0 -1 0
0 -1 0
0 -1 0
-1 0 0
-1 0 0
-1 0 0
-1 0 0
0 0 -1
0 0 -1
0 0 -1
0 0 -1
1 0 0
1 0 0
1 0 0
1 0 0
0 1 0
0 1 0
0 1 0
0 1 0
}
}
}
TexCoordArrayList 1 {
osg::Vec2Array {
UniqueID 47
BufferObject TRUE {
osg::VertexBufferObject {
UniqueID 45
}
}
Binding BIND_PER_VERTEX
vector 24 {
0.625 0.5
0.875 0.5
0.875 0.75
0.625 0.75
0.375 0.75
0.625 0.75
0.625 1
0.375 1
0.375 0
0.625 0
0.625 0.25
0.375 0.25
0.125 0.5
0.375 0.5
0.375 0.75
0.125 0.75
0.375 0.5
0.625 0.5
0.625 0.75
0.375 0.75
0.375 0.25
0.625 0.25
0.625 0.5
0.375 0.5
}
}
}
}
}
}
}
}
)osgt";
}
| 41,994
|
C++
|
.cpp
| 1,392
| 14.091954
| 99
| 0.360768
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,698
|
resourcesystem.cpp
|
OpenMW_openmw/components/resource/resourcesystem.cpp
|
#include "resourcesystem.hpp"
#include <algorithm>
#include "animblendrulesmanager.hpp"
#include "bgsmfilemanager.hpp"
#include "imagemanager.hpp"
#include "keyframemanager.hpp"
#include "niffilemanager.hpp"
#include "scenemanager.hpp"
namespace Resource
{
ResourceSystem::ResourceSystem(
const VFS::Manager* vfs, double expiryDelay, const ToUTF8::StatelessUtf8Encoder* encoder)
: mVFS(vfs)
{
mNifFileManager = std::make_unique<NifFileManager>(vfs, encoder);
mBgsmFileManager = std::make_unique<BgsmFileManager>(vfs, expiryDelay);
mImageManager = std::make_unique<ImageManager>(vfs, expiryDelay);
mSceneManager = std::make_unique<SceneManager>(
vfs, mImageManager.get(), mNifFileManager.get(), mBgsmFileManager.get(), expiryDelay);
mKeyframeManager = std::make_unique<KeyframeManager>(vfs, mSceneManager.get(), expiryDelay, encoder);
mAnimBlendRulesManager = std::make_unique<AnimBlendRulesManager>(vfs, expiryDelay);
addResourceManager(mNifFileManager.get());
addResourceManager(mBgsmFileManager.get());
addResourceManager(mKeyframeManager.get());
// note, scene references images so add images afterwards for correct implementation of updateCache()
addResourceManager(mSceneManager.get());
addResourceManager(mImageManager.get());
addResourceManager(mAnimBlendRulesManager.get());
}
ResourceSystem::~ResourceSystem()
{
// this has to be defined in the .cpp file as we can't delete incomplete types
mResourceManagers.clear();
}
SceneManager* ResourceSystem::getSceneManager()
{
return mSceneManager.get();
}
ImageManager* ResourceSystem::getImageManager()
{
return mImageManager.get();
}
BgsmFileManager* ResourceSystem::getBgsmFileManager()
{
return mBgsmFileManager.get();
}
NifFileManager* ResourceSystem::getNifFileManager()
{
return mNifFileManager.get();
}
KeyframeManager* ResourceSystem::getKeyframeManager()
{
return mKeyframeManager.get();
}
AnimBlendRulesManager* ResourceSystem::getAnimBlendRulesManager()
{
return mAnimBlendRulesManager.get();
}
void ResourceSystem::setExpiryDelay(double expiryDelay)
{
for (std::vector<BaseResourceManager*>::iterator it = mResourceManagers.begin(); it != mResourceManagers.end();
++it)
(*it)->setExpiryDelay(expiryDelay);
// NIF files aren't needed any more once the converted objects are cached in SceneManager / BulletShapeManager,
// so no point in using an expiry delay
mNifFileManager->setExpiryDelay(0.0);
}
void ResourceSystem::updateCache(double referenceTime)
{
for (std::vector<BaseResourceManager*>::iterator it = mResourceManagers.begin(); it != mResourceManagers.end();
++it)
(*it)->updateCache(referenceTime);
}
void ResourceSystem::clearCache()
{
for (std::vector<BaseResourceManager*>::iterator it = mResourceManagers.begin(); it != mResourceManagers.end();
++it)
(*it)->clearCache();
}
void ResourceSystem::addResourceManager(BaseResourceManager* resourceMgr)
{
mResourceManagers.push_back(resourceMgr);
}
void ResourceSystem::removeResourceManager(BaseResourceManager* resourceMgr)
{
std::vector<BaseResourceManager*>::iterator found
= std::find(mResourceManagers.begin(), mResourceManagers.end(), resourceMgr);
if (found != mResourceManagers.end())
mResourceManagers.erase(found);
}
const VFS::Manager* ResourceSystem::getVFS() const
{
return mVFS;
}
void ResourceSystem::reportStats(unsigned int frameNumber, osg::Stats* stats) const
{
for (std::vector<BaseResourceManager*>::const_iterator it = mResourceManagers.begin();
it != mResourceManagers.end(); ++it)
(*it)->reportStats(frameNumber, stats);
}
void ResourceSystem::releaseGLObjects(osg::State* state)
{
for (std::vector<BaseResourceManager*>::const_iterator it = mResourceManagers.begin();
it != mResourceManagers.end(); ++it)
(*it)->releaseGLObjects(state);
}
}
| 4,347
|
C++
|
.cpp
| 107
| 33.495327
| 119
| 0.688404
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,699
|
values.cpp
|
OpenMW_openmw/components/settings/values.cpp
|
#include "values.hpp"
#include <stdexcept>
namespace Settings
{
std::unique_ptr<Index> StaticValues::sIndex;
std::unique_ptr<Values> StaticValues::sDefaultValues;
std::unique_ptr<Values> StaticValues::sValues;
void StaticValues::initDefaults()
{
if (sDefaultValues != nullptr)
throw std::logic_error("Default settings are already initialized");
sIndex = std::make_unique<Index>();
sDefaultValues = std::make_unique<Values>(*sIndex);
}
void StaticValues::init()
{
if (sDefaultValues == nullptr)
throw std::logic_error("Default settings are not initialized");
sValues = std::make_unique<Values>(std::move(*sDefaultValues));
}
void StaticValues::clear()
{
sValues = nullptr;
sDefaultValues = nullptr;
sIndex = nullptr;
}
}
| 861
|
C++
|
.cpp
| 27
| 25.666667
| 79
| 0.6538
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,700
|
settings.cpp
|
OpenMW_openmw/components/settings/settings.cpp
|
#include "settings.hpp"
#include "parser.hpp"
#include "values.hpp"
#include <charconv>
#include <filesystem>
#include <sstream>
#include <system_error>
#if !(defined(_MSC_VER) && (_MSC_VER >= 1924)) && !(defined(__GNUC__) && __GNUC__ >= 11) || defined(__clang__) \
|| defined(__apple_build_version__)
#include <cerrno>
#include <ios>
#include <locale>
#endif
#include <components/debug/debuglog.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/conversion.hpp>
namespace Settings
{
namespace
{
template <class T>
T parseNumberFromSetting(const std::string& value, std::string_view setting, std::string_view category)
{
T number{};
const auto result = std::from_chars(value.data(), value.data() + value.size(), number);
if (result.ec != std::errc())
{
throw std::system_error(std::make_error_code(result.ec),
"Failed to parse number from setting [" + std::string(category) + "] " + std::string(setting)
+ " value \"" + value + "\"");
}
return number;
}
#if !(defined(_MSC_VER) && (_MSC_VER >= 1924)) && !(defined(__GNUC__) && __GNUC__ >= 11) || defined(__clang__) \
|| defined(__apple_build_version__)
template <>
float parseNumberFromSetting<float>(
const std::string& value, std::string_view setting, std::string_view category)
{
std::istringstream iss(value);
iss.imbue(std::locale::classic());
float floatValue = 0.0f;
if (!(iss >> floatValue))
{
throw std::system_error(errno, std::generic_category(),
"Failed to parse number from setting [" + std::string(category) + "] " + std::string(setting)
+ " value \"" + value + "\"");
}
return floatValue;
}
template <>
double parseNumberFromSetting<double>(
const std::string& value, std::string_view setting, std::string_view category)
{
std::istringstream iss(value);
iss.imbue(std::locale::classic());
double doubleValue = 0.0;
if (!(iss >> doubleValue))
{
throw std::system_error(errno, std::generic_category(),
"Failed to parse number from setting [" + std::string(category) + "] " + std::string(setting)
+ " value \"" + value + "\"");
}
return doubleValue;
}
#endif
template <class T>
std::string serialize(const T& value)
{
std::ostringstream stream;
stream << value;
return stream.str();
}
std::string toString(SceneUtil::LightingMethod value)
{
switch (value)
{
case SceneUtil::LightingMethod::FFP:
return "legacy";
case SceneUtil::LightingMethod::PerObjectUniform:
return "shaders compatibility";
case SceneUtil::LightingMethod::SingleUBO:
return "shaders";
}
throw std::invalid_argument("Invalid LightingMethod value: " + std::to_string(static_cast<int>(value)));
}
int toInt(HrtfMode value)
{
switch (value)
{
case HrtfMode::Auto:
return -1;
case HrtfMode::Disable:
return 0;
case HrtfMode::Enable:
return 1;
}
Log(Debug::Warning) << "Invalid HRTF mode value: " << static_cast<int>(value) << ", fallback to auto (-1)";
return -1;
}
}
CategorySettingValueMap Manager::mDefaultSettings = CategorySettingValueMap();
CategorySettingValueMap Manager::mUserSettings = CategorySettingValueMap();
CategorySettingVector Manager::mChangedSettings = CategorySettingVector();
std::set<std::pair<std::string_view, std::string_view>> Manager::sInitialized;
void Manager::clear()
{
sInitialized.clear();
StaticValues::clear();
mDefaultSettings.clear();
mUserSettings.clear();
mChangedSettings.clear();
}
std::filesystem::path Manager::load(const Files::ConfigurationManager& cfgMgr, bool loadEditorSettings)
{
SettingsFileParser parser;
const std::vector<std::filesystem::path>& paths = cfgMgr.getActiveConfigPaths();
if (paths.empty())
throw std::runtime_error("No config dirs! ConfigurationManager::readConfiguration must be called first.");
// Create file name strings for either the engine or the editor.
std::string defaultSettingsFile;
std::string userSettingsFile;
if (!loadEditorSettings)
{
defaultSettingsFile = "defaults.bin";
userSettingsFile = "settings.cfg";
}
else
{
defaultSettingsFile = "defaults-cs.bin";
userSettingsFile = "openmw-cs.cfg";
}
// Create the settings manager and load default settings file.
const auto defaultsBin = paths.front() / defaultSettingsFile;
if (!std::filesystem::exists(defaultsBin))
throw std::runtime_error("No default settings file found! Make sure the file \"" + defaultSettingsFile
+ "\" was properly installed.");
parser.loadSettingsFile(defaultsBin, mDefaultSettings, true, false);
const CategorySettingValueMap originalDefaultSettings = mDefaultSettings;
// Load "settings.cfg" or "openmw-cs.cfg" from every config dir except the last one as additional default
// settings.
for (int i = 0; i < static_cast<int>(paths.size()) - 1; ++i)
{
const auto additionalDefaults = paths[i] / userSettingsFile;
if (std::filesystem::exists(additionalDefaults))
parser.loadSettingsFile(additionalDefaults, mDefaultSettings, false, true);
}
if (!loadEditorSettings)
Settings::StaticValues::initDefaults();
// Load "settings.cfg" or "openmw-cs.cfg" from the last config dir as user settings. This path will be used to
// save modified settings.
auto settingspath = paths.back() / userSettingsFile;
if (std::filesystem::exists(settingspath))
parser.loadSettingsFile(settingspath, mUserSettings, false, false);
if (!loadEditorSettings)
Settings::StaticValues::init();
for (const auto& [key, value] : originalDefaultSettings)
if (!sInitialized.contains(key))
throw std::runtime_error("Default setting [" + key.first + "] " + key.second + " is not initialized");
return settingspath;
}
void Manager::saveUser(const std::filesystem::path& file)
{
SettingsFileParser parser;
parser.saveSettingsFile(file, mUserSettings);
}
const std::string& Manager::getString(std::string_view setting, std::string_view category)
{
const auto key = std::make_pair(category, setting);
CategorySettingValueMap::iterator it = mUserSettings.find(key);
if (it != mUserSettings.end())
return it->second;
it = mDefaultSettings.find(key);
if (it != mDefaultSettings.end())
return it->second;
throw std::runtime_error("Trying to retrieve a non-existing setting: [" + std::string(category) + "] "
+ std::string(setting) + ".\nMake sure the defaults.bin file was properly installed.");
}
std::vector<std::string> Manager::getStringArray(std::string_view setting, std::string_view category)
{
// TODO: it is unclear how to handle empty value -
// there is no difference between empty serialized array
// and a serialized array which has one empty value
std::vector<std::string> values;
const std::string& value = getString(setting, category);
if (value.empty())
return values;
Misc::StringUtils::split(value, values, ",");
for (auto& item : values)
Misc::StringUtils::trim(item);
return values;
}
float Manager::getFloat(std::string_view setting, std::string_view category)
{
return parseNumberFromSetting<float>(getString(setting, category), setting, category);
}
double Manager::getDouble(std::string_view setting, std::string_view category)
{
return parseNumberFromSetting<double>(getString(setting, category), setting, category);
}
int Manager::getInt(std::string_view setting, std::string_view category)
{
return parseNumberFromSetting<int>(getString(setting, category), setting, category);
}
std::uint64_t Manager::getUInt64(std::string_view setting, std::string_view category)
{
return parseNumberFromSetting<uint64_t>(getString(setting, category), setting, category);
}
std::size_t Manager::getSize(std::string_view setting, std::string_view category)
{
return parseNumberFromSetting<size_t>(getString(setting, category), setting, category);
}
unsigned Manager::getUnsigned(std::string_view setting, std::string_view category)
{
return parseNumberFromSetting<unsigned>(getString(setting, category), setting, category);
}
unsigned long Manager::getUnsignedLong(std::string_view setting, std::string_view category)
{
return parseNumberFromSetting<unsigned long>(getString(setting, category), setting, category);
}
unsigned long long Manager::getUnsignedLongLong(std::string_view setting, std::string_view category)
{
return parseNumberFromSetting<unsigned long long>(getString(setting, category), setting, category);
}
bool Manager::getBool(std::string_view setting, std::string_view category)
{
const std::string& string = getString(setting, category);
return Misc::StringUtils::ciEqual(string, "true");
}
osg::Vec2f Manager::getVector2(std::string_view setting, std::string_view category)
{
const std::string& value = getString(setting, category);
std::vector<std::string> components;
Misc::StringUtils::split(value, components);
if (components.size() == 2)
{
auto x = Misc::StringUtils::toNumeric<float>(components[0]);
auto y = Misc::StringUtils::toNumeric<float>(components[1]);
if (x && y)
{
return { x.value(), y.value() };
}
}
throw std::runtime_error(std::string("Can't parse 2d vector: " + value));
}
osg::Vec3f Manager::getVector3(std::string_view setting, std::string_view category)
{
const std::string& value = getString(setting, category);
std::vector<std::string> components;
Misc::StringUtils::split(value, components);
if (components.size() == 3)
{
auto x = Misc::StringUtils::toNumeric<float>(components[0]);
auto y = Misc::StringUtils::toNumeric<float>(components[1]);
auto z = Misc::StringUtils::toNumeric<float>(components[2]);
if (x && y && z)
{
return { x.value(), y.value(), z.value() };
}
}
throw std::runtime_error(std::string("Can't parse 3d vector: " + value));
}
void Manager::setString(std::string_view setting, std::string_view category, const std::string& value)
{
auto found = mUserSettings.find(std::make_pair(category, setting));
if (found != mUserSettings.end())
{
if (found->second == value)
return;
}
CategorySettingValueMap::key_type key(category, setting);
mUserSettings[key] = value;
mChangedSettings.insert(std::move(key));
}
void Manager::setStringArray(
std::string_view setting, std::string_view category, const std::vector<std::string>& value)
{
std::stringstream stream;
// TODO: escape delimeters, new line characters, etc.
for (size_t i = 0; i < value.size(); ++i)
{
std::string item = value[i];
Misc::StringUtils::trim(item);
stream << item;
if (i < value.size() - 1)
stream << ",";
}
setString(setting, category, stream.str());
}
void Manager::setInt(std::string_view setting, std::string_view category, const int value)
{
std::ostringstream stream;
stream << value;
setString(setting, category, stream.str());
}
void Manager::setUInt64(std::string_view setting, std::string_view category, const std::uint64_t value)
{
std::ostringstream stream;
stream << value;
setString(setting, category, stream.str());
}
void Manager::setFloat(std::string_view setting, std::string_view category, const float value)
{
std::ostringstream stream;
stream << value;
setString(setting, category, stream.str());
}
void Manager::setDouble(std::string_view setting, std::string_view category, const double value)
{
std::ostringstream stream;
stream << value;
setString(setting, category, stream.str());
}
void Manager::setBool(std::string_view setting, std::string_view category, const bool value)
{
setString(setting, category, value ? "true" : "false");
}
void Manager::setVector2(std::string_view setting, std::string_view category, const osg::Vec2f value)
{
std::ostringstream stream;
stream << value.x() << " " << value.y();
setString(setting, category, stream.str());
}
void Manager::setVector3(std::string_view setting, std::string_view category, const osg::Vec3f value)
{
std::ostringstream stream;
stream << value.x() << ' ' << value.y() << ' ' << value.z();
setString(setting, category, stream.str());
}
CategorySettingVector Manager::getPendingChanges()
{
return mChangedSettings;
}
CategorySettingVector Manager::getPendingChanges(const CategorySettingVector& filter)
{
CategorySettingVector intersection;
std::set_intersection(mChangedSettings.begin(), mChangedSettings.end(), filter.begin(), filter.end(),
std::inserter(intersection, intersection.begin()));
return intersection;
}
void Manager::resetPendingChanges()
{
mChangedSettings.clear();
}
void Manager::resetPendingChanges(const CategorySettingVector& filter)
{
for (const auto& key : filter)
{
mChangedSettings.erase(key);
}
}
void Manager::set(std::string_view setting, std::string_view category, int value)
{
setInt(setting, category, value);
}
void Manager::set(std::string_view setting, std::string_view category, unsigned value)
{
setString(setting, category, serialize(value));
}
void Manager::set(std::string_view setting, std::string_view category, unsigned long value)
{
setString(setting, category, serialize(value));
}
void Manager::set(std::string_view setting, std::string_view category, unsigned long long value)
{
setString(setting, category, serialize(value));
}
void Manager::set(std::string_view setting, std::string_view category, float value)
{
setFloat(setting, category, value);
}
void Manager::set(std::string_view setting, std::string_view category, double value)
{
setDouble(setting, category, value);
}
void Manager::set(std::string_view setting, std::string_view category, const std::string& value)
{
setString(setting, category, value);
}
void Manager::set(std::string_view setting, std::string_view category, bool value)
{
setBool(setting, category, value);
}
void Manager::set(std::string_view setting, std::string_view category, const osg::Vec2f& value)
{
setVector2(setting, category, value);
}
void Manager::set(std::string_view setting, std::string_view category, const osg::Vec3f& value)
{
setVector3(setting, category, value);
}
void Manager::set(std::string_view setting, std::string_view category, DetourNavigator::CollisionShapeType value)
{
setInt(setting, category, static_cast<int>(value));
}
void Manager::set(std::string_view setting, std::string_view category, const std::vector<std::string>& value)
{
setStringArray(setting, category, value);
}
void Manager::set(std::string_view setting, std::string_view category, const MyGUI::Colour& value)
{
setString(setting, category, value.print());
}
void Manager::set(std::string_view setting, std::string_view category, SceneUtil::LightingMethod value)
{
setString(setting, category, toString(value));
}
void Manager::set(std::string_view setting, std::string_view category, HrtfMode value)
{
setInt(setting, category, toInt(value));
}
void Manager::set(std::string_view setting, std::string_view category, WindowMode value)
{
setInt(setting, category, static_cast<int>(value));
}
void Manager::set(std::string_view setting, std::string_view category, SDLUtil::VSyncMode value)
{
setInt(setting, category, static_cast<int>(value));
}
void Manager::recordInit(std::string_view setting, std::string_view category)
{
sInitialized.emplace(category, setting);
}
GyroscopeAxis parseGyroscopeAxis(std::string_view value)
{
if (value == "x")
return GyroscopeAxis::X;
else if (value == "y")
return GyroscopeAxis::Y;
else if (value == "z")
return GyroscopeAxis::Z;
else if (value == "-x")
return GyroscopeAxis::MinusX;
else if (value == "-y")
return GyroscopeAxis::MinusY;
else if (value == "-z")
return GyroscopeAxis::MinusZ;
throw std::runtime_error("Invalid gyroscope axis: " + std::string(value));
}
NavMeshRenderMode parseNavMeshRenderMode(std::string_view value)
{
if (value == "area type")
return NavMeshRenderMode::AreaType;
if (value == "update frequency")
return NavMeshRenderMode::UpdateFrequency;
throw std::invalid_argument("Invalid navigation mesh rendering mode: " + std::string(value));
}
SceneUtil::LightingMethod parseLightingMethod(std::string_view value)
{
if (value == "legacy")
return SceneUtil::LightingMethod::FFP;
if (value == "shaders compatibility")
return SceneUtil::LightingMethod::PerObjectUniform;
if (value == "shaders")
return SceneUtil::LightingMethod::SingleUBO;
constexpr const char* fallback = "shaders compatibility";
Log(Debug::Warning) << "Unknown lighting method '" << value << "', returning fallback '" << fallback << "'";
return SceneUtil::LightingMethod::PerObjectUniform;
}
}
| 19,453
|
C++
|
.cpp
| 461
| 33.412148
| 120
| 0.622519
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,701
|
parser.cpp
|
OpenMW_openmw/components/settings/parser.cpp
|
#include "parser.hpp"
#include <sstream>
#include <components/debug/debuglog.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <filesystem>
#include <fstream>
#include <Base64.h>
void Settings::SettingsFileParser::loadSettingsFile(
const std::filesystem::path& file, CategorySettingValueMap& settings, bool base64Encoded, bool overrideExisting)
{
mFile = file;
std::ifstream fstream;
fstream.open(file);
auto stream = std::ref<std::istream>(fstream);
std::istringstream decodedStream;
if (base64Encoded)
{
std::string base64String(std::istreambuf_iterator<char>(fstream), {});
std::string decodedString;
auto result = Base64::Base64::Decode(base64String, decodedString);
if (!result.empty())
fail("Could not decode Base64 file: " + result);
// Move won't do anything until C++20, but won't hurt to do it anyway.
decodedStream.str(std::move(decodedString));
stream = std::ref<std::istream>(decodedStream);
}
Log(Debug::Info) << "Loading settings file: " << file;
std::string currentCategory;
mLine = 0;
while (!stream.get().eof() && !stream.get().fail())
{
++mLine;
std::string line;
std::getline(stream.get(), line);
size_t i = 0;
if (!skipWhiteSpace(i, line))
continue;
if (line[i] == '#') // skip comment
continue;
if (line[i] == '[')
{
size_t end = line.find(']', i);
if (end == std::string::npos)
fail("unterminated category");
currentCategory = line.substr(i + 1, end - (i + 1));
Misc::StringUtils::trim(currentCategory);
i = end + 1;
}
if (!skipWhiteSpace(i, line))
continue;
if (currentCategory.empty())
fail("empty category name");
size_t settingEnd = line.find('=', i);
if (settingEnd == std::string::npos)
fail("unterminated setting name");
std::string setting = line.substr(i, (settingEnd - i));
Misc::StringUtils::trim(setting);
size_t valueBegin = settingEnd + 1;
std::string value = line.substr(valueBegin);
Misc::StringUtils::trim(value);
if (overrideExisting)
settings[std::make_pair(currentCategory, setting)] = std::move(value);
else if (settings.insert(std::make_pair(std::make_pair(currentCategory, setting), value)).second == false)
fail(std::string("duplicate setting: [" + currentCategory + "] " + setting));
}
}
void Settings::SettingsFileParser::saveSettingsFile(
const std::filesystem::path& file, const CategorySettingValueMap& settings)
{
using CategorySettingStatusMap = std::map<CategorySetting, bool>;
// No options have been written to the file yet.
CategorySettingStatusMap written;
for (auto it = settings.begin(); it != settings.end(); ++it)
{
written[it->first] = false;
}
// Have we substantively changed the settings file?
bool changed = false;
// Were there any lines at all in the file?
bool existing = false;
// Is an entirely blank line queued to be added?
bool emptyLineQueued = false;
// The category/section we're currently in.
std::string currentCategory;
// Open the existing settings.cfg file to copy comments. This might not be the same file
// as the output file if we're copying the setting from the default settings.cfg for the
// first time. A minor change in API to pass the source file might be in order here.
std::ifstream istream;
istream.open(file);
// Create a new string stream to write the current settings to. It's likely that the
// input file and the output file are the same, so this stream serves as a temporary file
// of sorts. The setting files aren't very large so there's no performance issue.
std::stringstream ostream;
// For every line in the input file...
while (!istream.eof() && !istream.fail())
{
std::string line;
std::getline(istream, line);
// The current character position in the line.
size_t i = 0;
// An empty line was queued.
if (emptyLineQueued)
{
emptyLineQueued = false;
// We're still going through the current category, so we should copy it.
if (currentCategory.empty() || istream.eof() || line[i] != '[')
ostream << std::endl;
}
// Don't add additional newlines at the end of the file otherwise.
if (istream.eof())
continue;
// Queue entirely blank lines to add them if desired.
if (!skipWhiteSpace(i, line))
{
emptyLineQueued = true;
continue;
}
// There were at least some comments in the input file.
existing = true;
// Copy comments.
if (line[i] == '#')
{
ostream << line << std::endl;
continue;
}
// Category heading.
if (line[i] == '[')
{
size_t end = line.find(']', i);
// This should never happen unless the player edited the file while playing.
if (end == std::string::npos)
{
ostream << "# unterminated category: " << line << std::endl;
changed = true;
continue;
}
if (!currentCategory.empty())
{
// Ensure that all options in the current category have been written.
for (CategorySettingStatusMap::iterator mit = written.begin(); mit != written.end(); ++mit)
{
if (mit->second == false && mit->first.first == currentCategory)
{
Log(Debug::Verbose) << "Added new setting: [" << currentCategory << "] " << mit->first.second
<< " = " << settings.at(mit->first);
ostream << mit->first.second << " = " << settings.at(mit->first) << std::endl;
mit->second = true;
changed = true;
}
}
// Add an empty line after the last option in a category.
ostream << std::endl;
}
// Update the current category.
currentCategory = line.substr(i + 1, end - (i + 1));
Misc::StringUtils::trim(currentCategory);
// Write the (new) current category to the file.
ostream << "[" << currentCategory << "]" << std::endl;
// Log(Debug::Verbose) << "Wrote category: " << currentCategory;
// A setting can apparently follow the category on an input line. That's rather
// inconvenient, since it makes it more likely to have duplicative sections,
// which our algorithm doesn't like. Do the best we can.
i = end + 1;
}
// Truncate trailing whitespace, since we're changing the file anayway.
if (!skipWhiteSpace(i, line))
continue;
// If we've found settings before the first category, something's wrong. This
// should never happen unless the player edited the file while playing, since
// the loadSettingsFile() logic rejects it.
if (currentCategory.empty())
{
ostream << "# empty category name: " << line << std::endl;
changed = true;
continue;
}
// Which setting was at this location in the input file?
size_t settingEnd = line.find('=', i);
// This should never happen unless the player edited the file while playing.
if (settingEnd == std::string::npos)
{
ostream << "# unterminated setting name: " << line << std::endl;
changed = true;
continue;
}
std::string setting = line.substr(i, (settingEnd - i));
Misc::StringUtils::trim(setting);
// Get the existing value so we can see if we've changed it.
size_t valueBegin = settingEnd + 1;
std::string value = line.substr(valueBegin);
Misc::StringUtils::trim(value);
// Construct the setting map key to determine whether the setting has already been
// written to the file.
CategorySetting key = std::make_pair(currentCategory, setting);
CategorySettingStatusMap::iterator finder = written.find(key);
// Settings not in the written map are definitely invalid. Currently, this can only
// happen if the player edited the file while playing, because loadSettingsFile()
// will accept anything and pass it along in the map, but in the future, we might
// want to handle invalid settings more gracefully here.
if (finder == written.end())
{
ostream << "# invalid setting: " << line << std::endl;
changed = true;
continue;
}
// Write the current value of the setting to the file. The key must exist in the
// settings map because of how written was initialized and finder != end().
ostream << setting << " = " << settings.at(key) << std::endl;
// Mark that setting as written.
finder->second = true;
// Did we really change it?
if (value != settings.at(key))
{
Log(Debug::Verbose) << "Changed setting: [" << currentCategory << "] " << setting << " = "
<< settings.at(key);
changed = true;
}
// No need to write the current line, because we just emitted a replacement.
// Curiously, it appears that comments at the ends of lines with settings are not
// allowed, and the comment becomes part of the value. Was that intended?
}
// We're done with the input stream file.
istream.close();
// Ensure that all options in the current category have been written. We must complete
// the current category at the end of the file before moving on to any new categories.
for (CategorySettingStatusMap::iterator mit = written.begin(); mit != written.end(); ++mit)
{
if (mit->second == false && mit->first.first == currentCategory)
{
Log(Debug::Verbose) << "Added new setting: [" << mit->first.first << "] " << mit->first.second << " = "
<< settings.at(mit->first);
ostream << mit->first.second << " = " << settings.at(mit->first) << std::endl;
mit->second = true;
changed = true;
}
}
// If there was absolutely nothing in the file (or more likely the file didn't
// exist), start the newly created file with a helpful comment.
if (!existing)
{
const std::string filename = Files::pathToUnicodeString(file.filename());
ostream << "# This is the OpenMW user '" << filename << "' file. This file only contains" << std::endl;
ostream << "# explicitly changed settings. If you would like to revert a setting" << std::endl;
ostream << "# to its default, simply remove it from this file." << std::endl;
if (filename == "settings.cfg")
{
ostream << "# For available settings, see the file 'files/settings-default.cfg' in our source repo or the "
"documentation at:"
<< std::endl;
ostream << "#" << std::endl;
ostream << "# https://openmw.readthedocs.io/en/master/reference/modding/settings/index.html" << std::endl;
}
else if (filename == "openmw-cs.cfg")
{
ostream << "# For available settings, see the file 'apps/opencs/model/prefs/values.hpp' in our source repo."
<< std::endl;
}
}
// We still have one more thing to do before we're completely done writing the file.
// It's possible that there are entirely new categories, or that the input file had
// disappeared completely, so we need ensure that all settings are written to the file
// regardless of those issues.
for (CategorySettingStatusMap::iterator mit = written.begin(); mit != written.end(); ++mit)
{
// If the setting hasn't been written yet.
if (mit->second == false)
{
// If the catgory has changed, write a new category header.
if (mit->first.first != currentCategory)
{
currentCategory = mit->first.first;
Log(Debug::Verbose) << "Created new setting section: " << mit->first.first;
ostream << std::endl;
ostream << "[" << currentCategory << "]" << std::endl;
}
Log(Debug::Verbose) << "Added new setting: [" << mit->first.first << "] " << mit->first.second << " = "
<< settings.at(mit->first);
// Then write the setting. No need to mark it as written because we're done.
ostream << mit->first.second << " = " << settings.at(mit->first) << std::endl;
changed = true;
}
}
// Now install the newly written file in the requested place.
if (changed)
{
Log(Debug::Info) << "Updating settings file: " << file;
std::ofstream ofstream;
ofstream.open(file);
ofstream << ostream.rdbuf();
ofstream.close();
}
}
bool Settings::SettingsFileParser::skipWhiteSpace(size_t& i, std::string& str)
{
while (i < str.size() && std::isspace(str[i], std::locale::classic()))
{
++i;
}
return i < str.size();
}
[[noreturn]] void Settings::SettingsFileParser::fail(const std::string& message)
{
std::stringstream error;
error << "Error on line " << mLine << " in " << Files::pathToUnicodeString(mFile) << ":\n" << message;
throw std::runtime_error(error.str());
}
| 14,063
|
C++
|
.cpp
| 307
| 36.039088
| 120
| 0.584398
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,702
|
sanitizerimpl.cpp
|
OpenMW_openmw/components/settings/sanitizerimpl.cpp
|
#include "sanitizerimpl.hpp"
#include <osg/Vec3f>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
namespace Settings
{
namespace
{
template <class T>
struct Max final : Sanitizer<T>
{
T mMax;
explicit Max(const T& max)
: mMax(max)
{
}
T apply(const T& value) const override { return std::max(value, mMax); }
};
template <class T>
struct MaxStrict final : Sanitizer<T>
{
static_assert(std::is_floating_point_v<T>);
T mMax;
explicit MaxStrict(const T& max)
: mMax(std::nextafter(max, std::numeric_limits<T>::max()))
{
}
T apply(const T& value) const override { return std::max(value, mMax); }
};
template <>
struct MaxStrict<osg::Vec3f> final : Sanitizer<osg::Vec3f>
{
osg::Vec3f mMax;
explicit MaxStrict(const osg::Vec3f& max)
: mMax(std::nextafter(max.x(), std::numeric_limits<float>::max()),
std::nextafter(max.y(), std::numeric_limits<float>::max()),
std::nextafter(max.z(), std::numeric_limits<float>::max()))
{
}
osg::Vec3f apply(const osg::Vec3f& value) const override
{
return osg::Vec3f(
std::max(value.x(), mMax.x()), std::max(value.y(), mMax.y()), std::max(value.z(), mMax.z()));
}
};
template <class T>
struct Clamp final : Sanitizer<T>
{
T mMin;
T mMax;
explicit Clamp(const T& min, const T& max)
: mMin(min)
, mMax(max)
{
}
T apply(const T& value) const override { return std::clamp(value, mMin, mMax); }
};
template <class T>
auto getPrev(const T& value) -> std::enable_if_t<std::is_floating_point_v<T>, T>
{
assert(value > -std::numeric_limits<T>::max());
return std::nextafter(value, -std::numeric_limits<T>::max());
}
template <class T>
struct ClampStrictMax final : Sanitizer<T>
{
T mMin;
T mMax;
explicit ClampStrictMax(const T& min, const T& max)
: mMin(min)
, mMax(getPrev(max))
{
}
T apply(const T& value) const override { return std::clamp(value, mMin, mMax); }
};
template <class T>
struct Enum final : Sanitizer<T>
{
std::vector<T> mValues;
explicit Enum(std::initializer_list<T> value)
: mValues(std::make_move_iterator(value.begin()), std::make_move_iterator(value.end()))
{
}
T apply(const T& value) const override
{
if (std::find(mValues.begin(), mValues.end(), value) == mValues.end())
{
std::ostringstream message;
message << "Invalid enum value: " << value;
throw std::runtime_error(message.str());
}
return value;
}
};
template <class T>
struct EqualOrMax final : Sanitizer<T>
{
T mEqual;
T mMax;
explicit EqualOrMax(const T& equal, const T& max)
: mEqual(equal)
, mMax(max)
{
}
T apply(const T& value) const override
{
if (value == mEqual)
return value;
return std::max(value, mMax);
}
};
}
std::unique_ptr<Sanitizer<float>> makeMaxSanitizerFloat(float max)
{
return std::make_unique<Max<float>>(max);
}
std::unique_ptr<Sanitizer<int>> makeMaxSanitizerInt(int max)
{
return std::make_unique<Max<int>>(max);
}
std::unique_ptr<Sanitizer<std::size_t>> makeMaxSanitizerSize(std::size_t max)
{
return std::make_unique<Max<std::size_t>>(max);
}
std::unique_ptr<Sanitizer<std::uint64_t>> makeMaxSanitizerUInt64(std::uint64_t max)
{
return std::make_unique<Max<std::uint64_t>>(max);
}
std::unique_ptr<Sanitizer<float>> makeMaxStrictSanitizerFloat(float max)
{
return std::make_unique<MaxStrict<float>>(max);
}
std::unique_ptr<Sanitizer<osg::Vec3f>> makeMaxStrictSanitizerVec3f(const osg::Vec3f& max)
{
return std::make_unique<MaxStrict<osg::Vec3f>>(max);
}
std::unique_ptr<Sanitizer<float>> makeClampSanitizerFloat(float min, float max)
{
return std::make_unique<Clamp<float>>(min, max);
}
std::unique_ptr<Sanitizer<double>> makeClampSanitizerDouble(double min, double max)
{
return std::make_unique<Clamp<double>>(min, max);
}
std::unique_ptr<Sanitizer<int>> makeClampSanitizerInt(int min, int max)
{
return std::make_unique<Clamp<int>>(min, max);
}
std::unique_ptr<Sanitizer<float>> makeClampStrictMaxSanitizerFloat(float min, float max)
{
return std::make_unique<ClampStrictMax<float>>(min, max);
}
std::unique_ptr<Sanitizer<int>> makeEnumSanitizerInt(std::initializer_list<int> values)
{
return std::make_unique<Enum<int>>(values);
}
std::unique_ptr<Sanitizer<std::string>> makeEnumSanitizerString(std::initializer_list<std::string> values)
{
return std::make_unique<Enum<std::string>>(values);
}
std::unique_ptr<Sanitizer<float>> makeEqualOrMaxSanitizerFloat(float equal, float max)
{
return std::make_unique<EqualOrMax<float>>(equal, max);
}
}
| 5,944
|
C++
|
.cpp
| 172
| 24.593023
| 113
| 0.548134
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,703
|
launchersettings.cpp
|
OpenMW_openmw/components/config/launchersettings.cpp
|
#include "launchersettings.hpp"
#include <QDebug>
#include <QDir>
#include <QMultiMap>
#include <QRegularExpression>
#include <QString>
#include <QStringList>
#include <QTextStream>
#include <components/debug/debuglog.hpp>
#include <components/files/qtconversion.hpp>
#include "gamesettings.hpp"
namespace Config
{
namespace
{
constexpr char sSettingsSection[] = "Settings";
constexpr char sGeneralSection[] = "General";
constexpr char sProfilesSection[] = "Profiles";
constexpr char sImporterSection[] = "Importer";
constexpr char sLanguageKey[] = "language";
constexpr char sCurrentProfileKey[] = "currentprofile";
constexpr char sDataKey[] = "data";
constexpr char sArchiveKey[] = "fallback-archive";
constexpr char sContentKey[] = "content";
constexpr char sFirstRunKey[] = "firstrun";
constexpr char sImportContentSetupKey[] = "importcontentsetup";
constexpr char sImportFontSetupKey[] = "importfontsetup";
constexpr char sMainWindowWidthKey[] = "MainWindow/width";
constexpr char sMainWindowHeightKey[] = "MainWindow/height";
constexpr char sMainWindowPosXKey[] = "MainWindow/posx";
constexpr char sMainWindowPosYKey[] = "MainWindow/posy";
QString makeNewContentListName()
{
// basically, use date and time as the name e.g. YYYY-MM-DDThh:mm:ss
const std::time_t rawtime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
tm timeinfo{};
#ifdef _WIN32
(void)localtime_s(&timeinfo, &rawtime);
#else
(void)localtime_r(&rawtime, &timeinfo);
#endif
constexpr int base = 10;
QChar zeroPad('0');
return QString("%1-%2-%3T%4:%5:%6")
.arg(timeinfo.tm_year + 1900, 4)
.arg(timeinfo.tm_mon + 1, 2, base, zeroPad)
.arg(timeinfo.tm_mday, 2, base, zeroPad)
.arg(timeinfo.tm_hour, 2, base, zeroPad)
.arg(timeinfo.tm_min, 2, base, zeroPad)
.arg(timeinfo.tm_sec, 2, base, zeroPad);
}
bool parseBool(const QString& value, bool& out)
{
if (value == "false")
{
out = false;
return true;
}
if (value == "true")
{
out = true;
return true;
}
return false;
}
bool parseInt(const QString& value, int& out)
{
bool ok = false;
const int converted = value.toInt(&ok);
if (ok)
out = converted;
return ok;
}
bool parseProfilePart(
const QString& key, const QString& value, std::map<QString, LauncherSettings::Profile>& profiles)
{
const int separator = key.lastIndexOf('/');
if (separator == -1)
return false;
const QString profileName = key.mid(0, separator);
if (key.endsWith(sArchiveKey))
{
profiles[profileName].mArchives.append(value);
return true;
}
if (key.endsWith(sDataKey))
{
profiles[profileName].mData.append(value);
return true;
}
if (key.endsWith(sContentKey))
{
profiles[profileName].mContent.append(value);
return true;
}
return false;
}
bool parseSettingsSection(const QString& key, const QString& value, LauncherSettings::Settings& settings)
{
if (key == sLanguageKey)
{
settings.mLanguage = value;
return true;
}
return false;
}
bool parseProfilesSection(const QString& key, const QString& value, LauncherSettings::Profiles& profiles)
{
if (key == sCurrentProfileKey)
{
profiles.mCurrentProfile = value;
return true;
}
return parseProfilePart(key, value, profiles.mValues);
}
bool parseGeneralSection(const QString& key, const QString& value, LauncherSettings::General& general)
{
if (key == sFirstRunKey)
return parseBool(value, general.mFirstRun);
if (key == sMainWindowWidthKey)
return parseInt(value, general.mMainWindow.mWidth);
if (key == sMainWindowHeightKey)
return parseInt(value, general.mMainWindow.mHeight);
if (key == sMainWindowPosXKey)
return parseInt(value, general.mMainWindow.mPosX);
if (key == sMainWindowPosYKey)
return parseInt(value, general.mMainWindow.mPosY);
return false;
}
bool parseImporterSection(const QString& key, const QString& value, LauncherSettings::Importer& importer)
{
if (key == sImportContentSetupKey)
return parseBool(value, importer.mImportContentSetup);
if (key == sImportFontSetupKey)
return parseBool(value, importer.mImportFontSetup);
return false;
}
template <std::size_t size>
void writeSectionHeader(const char (&name)[size], QTextStream& stream)
{
stream << "\n[" << name << "]\n";
}
template <std::size_t size>
void writeKeyValue(const char (&key)[size], const QString& value, QTextStream& stream)
{
stream << key << '=' << value << '\n';
}
template <std::size_t size>
void writeKeyValue(const char (&key)[size], bool value, QTextStream& stream)
{
stream << key << '=' << (value ? "true" : "false") << '\n';
}
template <std::size_t size>
void writeKeyValue(const char (&key)[size], int value, QTextStream& stream)
{
stream << key << '=' << value << '\n';
}
template <std::size_t size>
void writeKeyValues(
const QString& prefix, const char (&suffix)[size], const QStringList& values, QTextStream& stream)
{
for (const auto& v : values)
stream << prefix << '/' << suffix << '=' << v << '\n';
}
void writeSettings(const LauncherSettings::Settings& value, QTextStream& stream)
{
writeSectionHeader(sSettingsSection, stream);
writeKeyValue(sLanguageKey, value.mLanguage, stream);
}
void writeProfiles(const LauncherSettings::Profiles& value, QTextStream& stream)
{
writeSectionHeader(sProfilesSection, stream);
writeKeyValue(sCurrentProfileKey, value.mCurrentProfile, stream);
for (auto it = value.mValues.rbegin(); it != value.mValues.rend(); ++it)
{
writeKeyValues(it->first, sArchiveKey, it->second.mArchives, stream);
writeKeyValues(it->first, sDataKey, it->second.mData, stream);
writeKeyValues(it->first, sContentKey, it->second.mContent, stream);
}
}
void writeGeneral(const LauncherSettings::General& value, QTextStream& stream)
{
writeSectionHeader(sGeneralSection, stream);
writeKeyValue(sFirstRunKey, value.mFirstRun, stream);
writeKeyValue(sMainWindowWidthKey, value.mMainWindow.mWidth, stream);
writeKeyValue(sMainWindowPosYKey, value.mMainWindow.mPosY, stream);
writeKeyValue(sMainWindowPosXKey, value.mMainWindow.mPosX, stream);
writeKeyValue(sMainWindowHeightKey, value.mMainWindow.mHeight, stream);
}
void writeImporter(const LauncherSettings::Importer& value, QTextStream& stream)
{
writeSectionHeader(sImporterSection, stream);
writeKeyValue(sImportContentSetupKey, value.mImportContentSetup, stream);
writeKeyValue(sImportFontSetupKey, value.mImportFontSetup, stream);
}
}
}
void Config::LauncherSettings::writeFile(QTextStream& stream) const
{
writeSettings(mSettings, stream);
writeProfiles(mProfiles, stream);
writeGeneral(mGeneral, stream);
writeImporter(mImporter, stream);
}
QStringList Config::LauncherSettings::getContentLists()
{
QStringList result;
result.reserve(mProfiles.mValues.size());
for (const auto& [k, v] : mProfiles.mValues)
result.push_back(k);
return result;
}
void Config::LauncherSettings::setContentList(const GameSettings& gameSettings)
{
// obtain content list from game settings (if present)
QList<SettingValue> dirs(gameSettings.getDataDirs());
dirs.erase(std::remove_if(
dirs.begin(), dirs.end(), [&](const SettingValue& dir) { return !gameSettings.isUserSetting(dir); }),
dirs.end());
// archives and content files aren't preprocessed, so we don't need to track their original form
const QList<SettingValue> archivesOriginal(gameSettings.getArchiveList());
QStringList archives;
for (const auto& archive : archivesOriginal)
{
if (gameSettings.isUserSetting(archive))
archives.push_back(archive.value);
}
const QList<SettingValue> filesOriginal(gameSettings.getContentList());
QStringList files;
for (const auto& file : filesOriginal)
{
if (gameSettings.isUserSetting(file))
files.push_back(file.value);
}
// if openmw.cfg has no content, exit so we don't create an empty content list.
if (dirs.isEmpty() || files.isEmpty())
{
return;
}
// local data directory and resources/vfs are not part of any profile
const auto resourcesVfs = gameSettings.getResourcesVfs();
const auto dataLocal = gameSettings.getDataLocal();
dirs.erase(
std::remove_if(dirs.begin(), dirs.end(), [&](const SettingValue& dir) { return dir.value == resourcesVfs; }),
dirs.end());
dirs.erase(
std::remove_if(dirs.begin(), dirs.end(), [&](const SettingValue& dir) { return dir.value == dataLocal; }),
dirs.end());
// if any existing profile in launcher matches the content list, make that profile the default
for (const QString& listName : getContentLists())
{
const auto& listDirs = getDataDirectoryList(listName);
constexpr auto compareDataDirectories = [](const SettingValue& dir, const QString& listDir) {
#ifdef Q_OS_WINDOWS
constexpr auto caseSensitivity = Qt::CaseInsensitive;
#else
constexpr auto caseSensitivity = Qt::CaseSensitive;
#endif
return dir.originalRepresentation == listDir
|| QDir::cleanPath(dir.originalRepresentation).compare(QDir::cleanPath(listDir), caseSensitivity) == 0;
};
if (!std::ranges::equal(dirs, listDirs, compareDataDirectories))
continue;
constexpr auto compareFiles
= [](const QString& a, const QString& b) { return a.compare(b, Qt::CaseInsensitive) == 0; };
if (!std::ranges::equal(files, getContentListFiles(listName), compareFiles))
continue;
if (!std::ranges::equal(archives, getArchiveList(listName), compareFiles))
continue;
setCurrentContentListName(listName);
return;
}
// otherwise, add content list
QString newContentListName(makeNewContentListName());
setCurrentContentListName(newContentListName);
QStringList newListDirs;
for (const auto& dir : dirs)
newListDirs.push_back(dir.originalRepresentation);
setContentList(newContentListName, newListDirs, archives, files);
}
void Config::LauncherSettings::setContentList(const QString& contentListName, const QStringList& dirNames,
const QStringList& archiveNames, const QStringList& fileNames)
{
Profile& profile = mProfiles.mValues[contentListName];
profile.mData = dirNames;
profile.mArchives = archiveNames;
profile.mContent = fileNames;
}
QStringList Config::LauncherSettings::getDataDirectoryList(const QString& contentListName) const
{
const Profile* profile = findProfile(contentListName);
if (profile == nullptr)
return {};
return profile->mData;
}
QStringList Config::LauncherSettings::getArchiveList(const QString& contentListName) const
{
const Profile* profile = findProfile(contentListName);
if (profile == nullptr)
return {};
return profile->mArchives;
}
QStringList Config::LauncherSettings::getContentListFiles(const QString& contentListName) const
{
const Profile* profile = findProfile(contentListName);
if (profile == nullptr)
return {};
return profile->mContent;
}
bool Config::LauncherSettings::setValue(const QString& sectionPrefix, const QString& key, const QString& value)
{
if (sectionPrefix == sSettingsSection)
return parseSettingsSection(key, value, mSettings);
if (sectionPrefix == sProfilesSection)
return parseProfilesSection(key, value, mProfiles);
if (sectionPrefix == sGeneralSection)
return parseGeneralSection(key, value, mGeneral);
if (sectionPrefix == sImporterSection)
return parseImporterSection(key, value, mImporter);
return false;
}
void Config::LauncherSettings::readFile(QTextStream& stream)
{
const QRegularExpression sectionRe("^\\[([^]]+)\\]$");
const QRegularExpression keyRe("^([^=]+)\\s*=\\s*(.+)$");
QString section;
while (!stream.atEnd())
{
const QString line = stream.readLine();
if (line.isEmpty() || line.startsWith("#"))
continue;
const QRegularExpressionMatch sectionMatch = sectionRe.match(line);
if (sectionMatch.hasMatch())
{
section = sectionMatch.captured(1);
continue;
}
if (section.isEmpty())
continue;
const QRegularExpressionMatch keyMatch = keyRe.match(line);
if (!keyMatch.hasMatch())
continue;
const QString key = keyMatch.captured(1).trimmed();
const QString value = keyMatch.captured(2).trimmed();
if (!setValue(section, key, value))
Log(Debug::Warning) << "Unsupported setting in the launcher config file: section: "
<< section.toUtf8().constData() << " key: " << key.toUtf8().constData()
<< " value: " << value.toUtf8().constData();
}
}
const Config::LauncherSettings::Profile* Config::LauncherSettings::findProfile(const QString& name) const
{
const auto it = mProfiles.mValues.find(name);
if (it == mProfiles.mValues.end())
return nullptr;
return &it->second;
}
void Config::LauncherSettings::clear()
{
mSettings = Settings{};
mGeneral = General{};
mProfiles = Profiles{};
mImporter = Importer{};
}
| 14,976
|
C++
|
.cpp
| 364
| 32.131868
| 120
| 0.629782
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,704
|
gamesettings.cpp
|
OpenMW_openmw/components/config/gamesettings.cpp
|
#include "gamesettings.hpp"
#include <QDir>
#include <QRegularExpression>
#include <components/files/configurationmanager.hpp>
#include <components/files/qtconversion.hpp>
#include <components/misc/utf8qtextstream.hpp>
const char Config::GameSettings::sArchiveKey[] = "fallback-archive";
const char Config::GameSettings::sContentKey[] = "content";
const char Config::GameSettings::sDirectoryKey[] = "data";
namespace
{
template <typename T>
QList<T> reverse(QList<T> values)
{
std::reverse(values.begin(), values.end());
return values;
}
}
Config::GameSettings::GameSettings(const Files::ConfigurationManager& cfg)
: mCfgMgr(cfg)
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
// this needs calling once so Qt can see its stream operators, which it needs when dragging and dropping
// it's automatic with Qt 6
qRegisterMetaTypeStreamOperators<SettingValue>("Config::SettingValue");
#endif
}
void Config::GameSettings::validatePaths()
{
QList<SettingValue> paths = mSettings.values(QString("data"));
mDataDirs.clear();
for (const auto& dataDir : paths)
{
if (QDir(dataDir.value).exists())
{
SettingValue copy = dataDir;
copy.value = QDir(dataDir.value).canonicalPath();
mDataDirs.append(copy);
}
}
// Do the same for data-local
const QString& local = mSettings.value(QString("data-local")).value;
if (!local.isEmpty() && QDir(local).exists())
{
mDataLocal = QDir(local).canonicalPath();
}
}
QString Config::GameSettings::getResourcesVfs() const
{
QString resources = mSettings.value(QString("resources"), { "./resources", "", "" }).value;
resources += "/vfs";
return QFileInfo(resources).canonicalFilePath();
}
QList<Config::SettingValue> Config::GameSettings::values(
const QString& key, const QList<SettingValue>& defaultValues) const
{
if (!mSettings.values(key).isEmpty())
return mSettings.values(key);
return defaultValues;
}
bool Config::GameSettings::containsValue(const QString& key, const QString& value) const
{
auto [itr, end] = mSettings.equal_range(key);
while (itr != end)
{
if (itr->value == value)
return true;
++itr;
}
return false;
}
bool Config::GameSettings::readFile(QTextStream& stream, const QString& context, bool ignoreContent)
{
if (readFile(stream, mSettings, context, ignoreContent))
{
mContexts.push_back(context);
return true;
}
return false;
}
bool Config::GameSettings::readUserFile(QTextStream& stream, const QString& context, bool ignoreContent)
{
return readFile(stream, mUserSettings, context, ignoreContent);
}
bool Config::GameSettings::readFile(
QTextStream& stream, QMultiMap<QString, SettingValue>& settings, const QString& context, bool ignoreContent)
{
QMultiMap<QString, SettingValue> cache;
QRegularExpression replaceRe("^\\s*replace\\s*=\\s*(.+)$");
QRegularExpression keyRe("^([^=]+)\\s*=\\s*(.+)$");
auto initialPos = stream.pos();
while (!stream.atEnd())
{
QString line = stream.readLine();
if (line.isEmpty() || line.startsWith("#"))
continue;
QRegularExpressionMatch match = replaceRe.match(line);
if (match.hasMatch())
{
QString key = match.captured(1).trimmed();
// Replace composing entries with a replace= line
if (key == QLatin1String("config") || key == QLatin1String("replace") || key == QLatin1String("data")
|| key == QLatin1String("fallback-archive") || key == QLatin1String("content")
|| key == QLatin1String("groundcover") || key == QLatin1String("fallback"))
settings.remove(key);
}
}
stream.seek(initialPos);
while (!stream.atEnd())
{
QString line = stream.readLine();
if (line.isEmpty() || line.startsWith("#"))
continue;
QRegularExpressionMatch match = keyRe.match(line);
if (match.hasMatch())
{
QString key = match.captured(1).trimmed();
SettingValue value{ match.captured(2).trimmed(), value.value, context };
// Don't remove composing entries
if (key != QLatin1String("config") && key != QLatin1String("replace") && key != QLatin1String("data")
&& key != QLatin1String("fallback-archive") && key != QLatin1String("content")
&& key != QLatin1String("groundcover") && key != QLatin1String("fallback"))
settings.remove(key);
if (key == QLatin1String("config") || key == QLatin1String("user-data") || key == QLatin1String("resources")
|| key == QLatin1String("data") || key == QLatin1String("data-local")
|| key == QLatin1String("load-savegame"))
{
// Path line (e.g. 'data=...'), so needs processing to deal with ampersands and quotes
// The following is based on boost::io::detail::quoted_manip.hpp, but we don't actually use
// boost::filesystem::path anymore, and use a custom class MaybeQuotedPath which uses Boost-like quoting
// rules but internally stores as a std::filesystem::path.
// Caution: This is intentional behaviour to duplicate how Boost and what we replaced it with worked,
// and we rely on that.
QChar delim = '\"';
QChar escape = '&';
if (value.value.at(0) == delim)
{
QString valueOriginal = value.value;
value.value = "";
for (QString::const_iterator it = valueOriginal.begin() + 1; it != valueOriginal.end(); ++it)
{
if (*it == escape)
++it;
else if (*it == delim)
break;
value.value += *it;
}
value.originalRepresentation = value.value;
}
value = processPathSettingValue(value);
}
if (ignoreContent && (key == QLatin1String("content") || key == QLatin1String("data")))
continue;
QList<SettingValue> values = cache.values(key);
values.append(settings.values(key));
bool exists = false;
for (const auto& existingValue : values)
{
if (existingValue.value == value.value)
{
exists = true;
break;
}
}
if (!exists)
{
cache.insert(key, value);
}
}
}
if (settings.isEmpty())
{
settings = cache; // This is the first time we read a file
validatePaths();
return true;
}
// Merge the changed keys with those which didn't
settings.unite(cache);
validatePaths();
return true;
}
bool Config::GameSettings::writeFile(QTextStream& stream)
{
// Iterate in reverse order to preserve insertion order
auto i = mUserSettings.end();
while (i != mUserSettings.begin())
{
i--;
// path lines (e.g. 'data=...') need quotes and ampersands escaping to match how boost::filesystem::path uses
// boost::io::quoted
// We don't actually use boost::filesystem::path anymore, but use a custom class MaybeQuotedPath which uses
// Boost-like quoting rules but internally stores as a std::filesystem::path.
// Caution: This is intentional behaviour to duplicate how Boost and what we replaced it with worked, and we
// rely on that.
if (i.key() == QLatin1String("config") || i.key() == QLatin1String("user-data")
|| i.key() == QLatin1String("resources") || i.key() == QLatin1String("data")
|| i.key() == QLatin1String("data-local") || i.key() == QLatin1String("load-savegame"))
{
stream << i.key() << "=";
// Equivalent to stream << std::quoted(i.value(), '"', '&'), which won't work on QStrings.
QChar delim = '\"';
QChar escape = '&';
QString string = i.value().originalRepresentation;
stream << delim;
for (auto& it : string)
{
if (it == delim || it == escape)
stream << escape;
stream << it;
}
stream << delim;
stream << '\n';
continue;
}
stream << i.key() << "=" << i.value().originalRepresentation << "\n";
}
return true;
}
bool Config::GameSettings::isOrderedLine(const QString& line)
{
return line.contains(QRegularExpression("^\\s*fallback-archive\\s*="))
|| line.contains(QRegularExpression("^\\s*fallback\\s*="))
|| line.contains(QRegularExpression("^\\s*data\\s*="))
|| line.contains(QRegularExpression("^\\s*data-local\\s*="))
|| line.contains(QRegularExpression("^\\s*resources\\s*="))
|| line.contains(QRegularExpression("^\\s*groundcover\\s*="))
|| line.contains(QRegularExpression("^\\s*content\\s*="));
}
// Policy:
//
// - Always ignore a line beginning with '#' or empty lines; added above a config
// entry.
//
// - If a line in file exists with matching key and first part of value (before ',',
// '\n', etc) also matches, then replace the line with that of mUserSettings.
// - else remove line
//
// - If there is no corresponding line in file, add at the end
//
// - Removed content items are saved as comments if the item had any comments.
// Content items prepended with '##' are considered previously removed.
//
bool Config::GameSettings::writeFileWithComments(QFile& file)
{
QTextStream stream(&file);
Misc::ensureUtf8Encoding(stream);
// slurp
std::vector<QString> fileCopy;
QString line = stream.readLine();
while (!line.isNull())
{
fileCopy.push_back(line);
line = stream.readLine();
}
stream.seek(0);
// empty file, no comments to keep
if (fileCopy.empty())
return writeFile(stream);
// start
// |
// | +----------------------------------------------------------+
// | | |
// v v |
// skip non-"ordered" lines (remove "ordered" lines) |
// | ^ |
// | | |
// | non-"ordered" line, write saved comments |
// | ^ |
// v | |
// blank or comment line, save in temp buffer <--------+ |
// | | | |
// | +------- comment line ------+ |
// v (special processing '##') |
// "ordered" line |
// | |
// v |
// save in a separate map of comments keyed by "ordered" line |
// | |
// +----------------------------------------------------------+
//
//
QRegularExpression settingRegex("^([^=]+)\\s*=\\s*([^,]+)(.*)$");
std::vector<QString> comments;
auto commentStart = fileCopy.end();
std::map<QString, std::vector<QString>> commentsMap;
for (auto iter = fileCopy.begin(); iter != fileCopy.end(); ++iter)
{
if (isOrderedLine(*iter))
{
// save in a separate map of comments keyed by "ordered" line
if (!comments.empty())
{
QRegularExpressionMatch match = settingRegex.match(*iter);
if (match.hasMatch())
{
commentsMap[match.captured(1) + "=" + match.captured(2)] = comments;
comments.clear();
commentStart = fileCopy.end();
}
// else do nothing, malformed line
}
*iter = QString(); // "ordered" lines to be removed later
}
else if ((*iter).isEmpty() || (*iter).contains(QRegularExpression("^\\s*#")))
{
// comment line, save in temp buffer
if (comments.empty())
commentStart = iter;
// special removed content processing
if ((*iter).contains(QRegularExpression("^##content\\s*=")))
{
if (!comments.empty())
{
commentsMap[*iter] = comments;
comments.clear();
commentStart = fileCopy.end();
}
}
else
comments.push_back(*iter);
*iter = QString(); // assume to be deleted later
}
else
{
QRegularExpressionMatch match = settingRegex.match(*iter);
// blank or non-"ordered" line, write saved comments
if (!comments.empty() && match.hasMatch() && settingRegex.captureCount() >= 2
&& mUserSettings.find(match.captured(1)) != mUserSettings.end())
{
if (commentStart == fileCopy.end())
throw std::runtime_error(
"Config::GameSettings: failed to parse settings - iterator is past of end of settings file");
for (const auto& comment : comments)
{
*commentStart = comment;
++commentStart;
}
comments.clear();
commentStart = fileCopy.end();
}
// keep blank lines and non-"ordered" lines other than comments
// look for a key in the line
if (!match.hasMatch() || settingRegex.captureCount() < 2)
{
// no key or first part of value found in line, replace with a null string which
// will be removed later
*iter = QString();
comments.clear();
commentStart = fileCopy.end();
continue;
}
// look for a matching key in user settings
*iter = QString(); // assume no match
QString key = match.captured(1);
QString keyVal = match.captured(1) + "=" + match.captured(2);
QMultiMap<QString, SettingValue>::const_iterator i = mUserSettings.find(key);
while (i != mUserSettings.end() && i.key() == key)
{
// todo: does this need to handle paths?
QString settingLine = i.key() + "=" + i.value().originalRepresentation;
QRegularExpressionMatch keyMatch = settingRegex.match(settingLine);
if (keyMatch.hasMatch())
{
if ((keyMatch.captured(1) + "=" + keyMatch.captured(2)) == keyVal)
{
*iter = std::move(settingLine);
break;
}
}
++i;
}
}
}
// comments at top of file
for (auto& iter : fileCopy)
{
if (iter.isNull())
continue;
// Below is based on readFile() code, if that changes corresponding change may be
// required (for example duplicates may be inserted if the rules don't match)
if (/*(*iter).isEmpty() ||*/ iter.contains(QRegularExpression("^\\s*#")))
{
stream << iter << "\n";
continue;
}
}
// Iterate in reverse order to preserve insertion order
QString settingLine;
auto it = mUserSettings.end();
while (it != mUserSettings.begin())
{
it--;
// path lines (e.g. 'data=...') need quotes and ampersands escaping to match how boost::filesystem::path uses
// boost::io::quoted
// We don't actually use boost::filesystem::path anymore, but use a custom class MaybeQuotedPath which uses
// Boost-like quoting rules but internally stores as a std::filesystem::path.
// Caution: This is intentional behaviour to duplicate how Boost and what we replaced it with worked, and we
// rely on that.
if (it.key() == QLatin1String("config") || it.key() == QLatin1String("user-data")
|| it.key() == QLatin1String("resources") || it.key() == QLatin1String("data")
|| it.key() == QLatin1String("data-local") || it.key() == QLatin1String("load-savegame"))
{
settingLine = it.key() + "=";
// Equivalent to settingLine += std::quoted(it.value(), '"', '&'), which won't work on QStrings.
QChar delim = '\"';
QChar escape = '&';
QString string = it.value().originalRepresentation;
settingLine += delim;
for (auto& iter : string)
{
if (iter == delim || iter == escape)
settingLine += escape;
settingLine += iter;
}
settingLine += delim;
}
else
settingLine = it.key() + "=" + it.value().originalRepresentation;
QRegularExpressionMatch match = settingRegex.match(settingLine);
if (match.hasMatch())
{
auto i = commentsMap.find(match.captured(1) + "=" + match.captured(2));
// check if previous removed content item with comments
if (i == commentsMap.end())
i = commentsMap.find("##" + match.captured(1) + "=" + match.captured(2));
if (i != commentsMap.end())
{
std::vector<QString> cLines = i->second;
for (const auto& cLine : cLines)
stream << cLine << "\n";
commentsMap.erase(i);
}
}
stream << settingLine << "\n";
}
// flush any removed settings
if (!commentsMap.empty())
{
auto i = commentsMap.begin();
for (; i != commentsMap.end(); ++i)
{
if (i->first.contains(QRegularExpression("^\\s*content\\s*=")))
{
std::vector<QString> cLines = i->second;
for (const auto& cLine : cLines)
stream << cLine << "\n";
// mark the content line entry for future preocessing
stream << "##" << i->first << "\n";
// commentsMap.erase(i);
}
}
}
// flush any end comments
if (!comments.empty())
{
for (const auto& comment : comments)
stream << comment << "\n";
}
file.resize(file.pos());
return true;
}
bool Config::GameSettings::hasMaster()
{
bool result = false;
QList<SettingValue> content = mSettings.values(QString(Config::GameSettings::sContentKey));
for (int i = 0; i < content.count(); ++i)
{
if (content.at(i).value.endsWith(QLatin1String(".omwgame"), Qt::CaseInsensitive)
|| content.at(i).value.endsWith(QLatin1String(".esm"), Qt::CaseInsensitive))
{
result = true;
break;
}
}
return result;
}
void Config::GameSettings::setContentList(
const QList<SettingValue>& dirNames, const QList<SettingValue>& archiveNames, const QStringList& fileNames)
{
remove(sDirectoryKey);
for (auto const& item : dirNames)
setMultiValue(sDirectoryKey, item);
remove(sArchiveKey);
for (auto const& item : archiveNames)
setMultiValue(sArchiveKey, item);
remove(sContentKey);
for (auto const& item : fileNames)
setMultiValue(sContentKey, { item });
}
QList<Config::SettingValue> Config::GameSettings::getDataDirs() const
{
return reverse(mDataDirs);
}
QList<Config::SettingValue> Config::GameSettings::getArchiveList() const
{
// QMap returns multiple rows in LIFO order, so need to reverse
return reverse(values(sArchiveKey));
}
QList<Config::SettingValue> Config::GameSettings::getContentList() const
{
// QMap returns multiple rows in LIFO order, so need to reverse
return reverse(values(sContentKey));
}
bool Config::GameSettings::isUserSetting(const SettingValue& settingValue) const
{
return settingValue.context.isEmpty() || settingValue.context == getUserContext();
}
Config::SettingValue Config::GameSettings::processPathSettingValue(const SettingValue& value)
{
std::filesystem::path path = Files::pathFromQString(value.value);
std::filesystem::path basePath = Files::pathFromQString(value.context.isEmpty() ? getUserContext() : value.context);
mCfgMgr.processPath(path, basePath);
return SettingValue{ Files::pathToQString(path), value.originalRepresentation, value.context };
}
void Config::GameSettings::clear()
{
mSettings.clear();
mContexts.clear();
mUserSettings.clear();
mDataDirs.clear();
mDataLocal.clear();
}
QDataStream& Config::operator<<(QDataStream& out, const SettingValue& settingValue)
{
out << settingValue.value;
out << settingValue.originalRepresentation;
out << settingValue.context;
return out;
}
QDataStream& Config::operator>>(QDataStream& in, SettingValue& settingValue)
{
in >> settingValue.value;
in >> settingValue.originalRepresentation;
in >> settingValue.context;
return in;
}
| 21,918
|
C++
|
.cpp
| 536
| 31.716418
| 120
| 0.549906
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,705
|
modelitem.cpp
|
OpenMW_openmw/components/contentselector/model/modelitem.cpp
|
#include "modelitem.hpp"
ContentSelectorModel::ModelItem::ModelItem(ModelItem* parent)
: mParentItem(parent)
{
}
/*
ContentSelectorModel::ModelItem::ModelItem(const ModelItem *parent)
// : mParentItem(parent)
{
}
*/
ContentSelectorModel::ModelItem::~ModelItem()
{
qDeleteAll(mChildItems);
}
ContentSelectorModel::ModelItem* ContentSelectorModel::ModelItem::parent() const
{
return mParentItem;
}
bool ContentSelectorModel::ModelItem::hasFormat(const QString& mimetype) const
{
if (mimetype == "application/omwcontent")
return true;
return QMimeData::hasFormat(mimetype);
}
int ContentSelectorModel::ModelItem::row() const
{
if (mParentItem)
return 1;
// return mParentItem->childRow(const_cast<ModelItem*>(this));
// return mParentItem->mChildItems.indexOf(const_cast<ModelItem*>(this));
return -1;
}
int ContentSelectorModel::ModelItem::childCount() const
{
return mChildItems.count();
}
int ContentSelectorModel::ModelItem::childRow(ModelItem* child) const
{
Q_ASSERT(child);
return mChildItems.indexOf(child);
}
ContentSelectorModel::ModelItem* ContentSelectorModel::ModelItem::child(int row)
{
return mChildItems.value(row);
}
void ContentSelectorModel::ModelItem::appendChild(ModelItem* item)
{
mChildItems.append(item);
}
void ContentSelectorModel::ModelItem::removeChild(int row)
{
mChildItems.removeAt(row);
}
| 1,409
|
C++
|
.cpp
| 54
| 23.407407
| 80
| 0.769173
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
34,706
|
contentmodel.cpp
|
OpenMW_openmw/components/contentselector/model/contentmodel.cpp
|
#include "contentmodel.hpp"
#include "esmfile.hpp"
#include <algorithm>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <unordered_set>
#include <QDataStream>
#include <QDebug>
#include <QDir>
#include <QFont>
#include <QIODevice>
#include <components/esm/format.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm4/reader.hpp>
#include <components/files/openfile.hpp>
#include <components/files/qtconversion.hpp>
ContentSelectorModel::ContentModel::ContentModel(
QObject* parent, QIcon& warningIcon, QIcon& errorIcon, bool showOMWScripts)
: QAbstractTableModel(parent)
, mWarningIcon(warningIcon)
, mErrorIcon(errorIcon)
, mShowOMWScripts(showOMWScripts)
, mMimeType("application/omwcontent")
, mMimeTypes(QStringList() << mMimeType)
, mColumnCount(1)
, mDropActions(Qt::MoveAction)
{
setEncoding("win1252");
uncheckAll();
}
ContentSelectorModel::ContentModel::~ContentModel()
{
qDeleteAll(mFiles);
mFiles.clear();
}
void ContentSelectorModel::ContentModel::setEncoding(const QString& encoding)
{
mEncoding = encoding;
}
int ContentSelectorModel::ContentModel::columnCount(const QModelIndex& parent) const
{
if (parent.isValid())
return 0;
return mColumnCount;
}
int ContentSelectorModel::ContentModel::rowCount(const QModelIndex& parent) const
{
if (parent.isValid())
return 0;
return mFiles.size();
}
const ContentSelectorModel::EsmFile* ContentSelectorModel::ContentModel::item(int row) const
{
if (row >= 0 && row < mFiles.size())
return mFiles.at(row);
return nullptr;
}
ContentSelectorModel::EsmFile* ContentSelectorModel::ContentModel::item(int row)
{
if (row >= 0 && row < mFiles.count())
return mFiles.at(row);
return nullptr;
}
const ContentSelectorModel::EsmFile* ContentSelectorModel::ContentModel::item(const QString& name) const
{
EsmFile::FileProperty fp = EsmFile::FileProperty_FileName;
if (name.contains('/'))
fp = EsmFile::FileProperty_FilePath;
for (const EsmFile* file : mFiles)
{
if (name.compare(file->fileProperty(fp).toString(), Qt::CaseInsensitive) == 0)
return file;
}
return nullptr;
}
QModelIndex ContentSelectorModel::ContentModel::indexFromItem(const EsmFile* item) const
{
// workaround: non-const pointer cast for calls from outside contentmodel/contentselector
EsmFile* non_const_file_ptr = const_cast<EsmFile*>(item);
if (item)
return index(mFiles.indexOf(non_const_file_ptr), 0);
return QModelIndex();
}
Qt::ItemFlags ContentSelectorModel::ContentModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return Qt::ItemIsDropEnabled;
const EsmFile* file = item(index.row());
if (!file)
return Qt::NoItemFlags;
if (file->builtIn() || file->fromAnotherConfigFile())
return Qt::ItemIsEnabled;
// game files can always be checked
if (file == mGameFile)
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
Qt::ItemFlags returnFlags;
// addon can be checked if its gamefile is
// ... special case, addon with no dependency can be used with any gamefile.
bool gamefileChecked = false;
bool noGameFiles = true;
for (const QString& fileName : file->gameFiles())
{
for (QListIterator<EsmFile*> dependencyIter(mFiles); dependencyIter.hasNext(); dependencyIter.next())
{
// compare filenames only. Multiple instances
// of the filename (with different paths) is not relevant here.
EsmFile* depFile = dependencyIter.peekNext();
if (!depFile->isGameFile() || depFile->fileName().compare(fileName, Qt::CaseInsensitive) != 0)
continue;
noGameFiles = false;
if (depFile->builtIn() || depFile->fromAnotherConfigFile() || mCheckedFiles.contains(depFile))
{
gamefileChecked = true;
break;
}
}
}
if (gamefileChecked || noGameFiles)
{
returnFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsDragEnabled;
}
return returnFlags;
}
QVariant ContentSelectorModel::ContentModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= mFiles.size())
return QVariant();
const EsmFile* file = item(index.row());
if (!file)
return QVariant();
const int column = index.column();
switch (role)
{
case Qt::DecorationRole:
{
if (file->isMissing())
return mErrorIcon;
else if (isLoadOrderError(file))
return mWarningIcon;
else
return QVariant();
}
case Qt::FontRole:
{
if (isNew(file->fileName()))
{
auto font = QFont();
font.setBold(true);
font.setItalic(true);
return font;
}
return QVariant();
}
case Qt::EditRole:
case Qt::DisplayRole:
{
if (column >= 0 && column <= EsmFile::FileProperty_GameFile)
return file->fileProperty(static_cast<EsmFile::FileProperty>(column));
return QVariant();
}
case Qt::TextAlignmentRole:
{
switch (column)
{
case 0:
case 1:
return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
case 2:
case 3:
return QVariant(Qt::AlignRight | Qt::AlignVCenter);
default:
return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
}
}
case Qt::ToolTipRole:
{
if (column != 0)
return QVariant();
return toolTip(file);
}
case Qt::CheckStateRole:
{
if (file == mGameFile)
return QVariant();
return (file->builtIn() || file->fromAnotherConfigFile() || mCheckedFiles.contains(file)) ? Qt::Checked
: Qt::Unchecked;
}
case Qt::UserRole:
{
if (file == mGameFile)
return ContentType_GameFile;
else if (flags(index))
return ContentType_Addon;
break;
}
case Qt::UserRole + 1:
return mCheckedFiles.contains(file);
}
return QVariant();
}
bool ContentSelectorModel::ContentModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
EsmFile* file = item(index.row());
QString fileName = file->fileName();
bool success = false;
switch (role)
{
case Qt::EditRole:
{
QStringList list = value.toStringList();
for (int i = 0; i < EsmFile::FileProperty_GameFile; i++)
file->setFileProperty(static_cast<EsmFile::FileProperty>(i), list.at(i));
for (int i = EsmFile::FileProperty_GameFile; i < list.size(); i++)
file->setFileProperty(EsmFile::FileProperty_GameFile, list.at(i));
emit dataChanged(index, index);
success = true;
}
break;
case Qt::UserRole + 1:
{
success = (flags(index) & Qt::ItemIsEnabled);
if (success)
{
success = setCheckState(file->filePath(), value.toBool());
emit dataChanged(index, index);
}
}
break;
case Qt::CheckStateRole:
{
int checkValue = value.toInt();
bool setState = false;
if (file->builtIn() || file->fromAnotherConfigFile())
{
setState = false;
success = false;
}
else if (checkValue == Qt::Checked && !mCheckedFiles.contains(file))
{
setState = true;
success = true;
}
else if (checkValue == Qt::Checked && mCheckedFiles.contains(file))
setState = true;
else if (checkValue == Qt::Unchecked)
setState = true;
if (setState)
{
setCheckState(file->filePath(), success);
emit dataChanged(index, index);
checkForLoadOrderErrors();
}
else
return success;
for (EsmFile* file2 : mFiles)
{
if (file2->gameFiles().contains(fileName, Qt::CaseInsensitive))
{
QModelIndex idx = indexFromItem(file2);
emit dataChanged(idx, idx);
}
}
success = true;
}
break;
}
return success;
}
bool ContentSelectorModel::ContentModel::insertRows(int position, int rows, const QModelIndex& parent)
{
return false;
}
bool ContentSelectorModel::ContentModel::removeRows(int position, int rows, const QModelIndex& parent)
{
return false;
}
Qt::DropActions ContentSelectorModel::ContentModel::supportedDropActions() const
{
return mDropActions;
}
QStringList ContentSelectorModel::ContentModel::mimeTypes() const
{
return mMimeTypes;
}
QMimeData* ContentSelectorModel::ContentModel::mimeData(const QModelIndexList& indexes) const
{
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
for (const QModelIndex& index : indexes)
{
if (!index.isValid())
continue;
stream << index.row();
}
QMimeData* mimeData = new QMimeData();
mimeData->setData(mMimeType, encodedData);
return mimeData;
}
bool ContentSelectorModel::ContentModel::dropMimeData(
const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent)
{
if (action == Qt::IgnoreAction)
return true;
if (column > 0)
return false;
if (!data->hasFormat(mMimeType))
return false;
int beginRow = rowCount();
if (row != -1)
beginRow = row;
else if (parent.isValid())
beginRow = parent.row();
int firstModifiable = 0;
while (item(firstModifiable)->builtIn() || item(firstModifiable)->fromAnotherConfigFile())
++firstModifiable;
if (beginRow < firstModifiable)
return false;
QByteArray encodedData = data->data(mMimeType);
QDataStream stream(&encodedData, QIODevice::ReadOnly);
std::vector<EsmFile*> toMove;
while (!stream.atEnd())
{
int sourceRow;
stream >> sourceRow;
toMove.emplace_back(mFiles.at(sourceRow));
}
int minRow = mFiles.size();
int maxRow = 0;
for (EsmFile* file : toMove)
{
int from = mFiles.indexOf(file);
int to = beginRow;
if (from < beginRow)
to--;
else if (from > beginRow)
beginRow++;
minRow = std::min(minRow, std::min(to, from));
maxRow = std::max(maxRow, std::max(to, from));
mFiles.move(from, to);
}
dataChanged(index(minRow, 0), index(maxRow, 0));
// at this point we know that drag and drop has finished.
checkForLoadOrderErrors();
return true;
}
void ContentSelectorModel::ContentModel::addFile(EsmFile* file)
{
beginInsertRows(QModelIndex(), mFiles.count(), mFiles.count());
mFiles.append(file);
endInsertRows();
QModelIndex idx = index(mFiles.size() - 2, 0, QModelIndex());
emit dataChanged(idx, idx);
}
void ContentSelectorModel::ContentModel::addFiles(const QString& path, bool newfiles)
{
QDir dir(path);
QStringList filters;
filters << "*.esp"
<< "*.esm"
<< "*.omwgame"
<< "*.omwaddon";
if (mShowOMWScripts)
filters << "*.omwscripts";
dir.setNameFilters(filters);
dir.setSorting(QDir::Name);
for (const QString& path2 : dir.entryList())
{
QFileInfo info(dir.absoluteFilePath(path2));
EsmFile* file = const_cast<EsmFile*>(item(info.fileName()));
bool add = file == nullptr;
std::unique_ptr<EsmFile> newFile;
if (add)
{
newFile = std::make_unique<EsmFile>(path2);
file = newFile.get();
}
else
{
// We've found the same file in a higher priority dir, update our existing entry
file->setFileName(path2);
file->setGameFiles({});
}
if (info.fileName().compare("builtin.omwscripts", Qt::CaseInsensitive) == 0)
file->setBuiltIn(true);
file->setFromAnotherConfigFile(mNonUserContent.contains(info.fileName().toLower()));
if (info.fileName().endsWith(".omwscripts", Qt::CaseInsensitive))
{
file->setDate(info.lastModified());
file->setFilePath(info.absoluteFilePath());
if (add)
addFile(newFile.release());
setNew(file->fileName(), newfiles);
continue;
}
try
{
file->setDate(info.lastModified());
file->setFilePath(info.absoluteFilePath());
std::filesystem::path filepath = Files::pathFromQString(info.absoluteFilePath());
auto stream = Files::openBinaryInputFileStream(filepath);
if (!stream->is_open())
{
qWarning() << "Failed to open addon file " << info.fileName() << ": "
<< std::generic_category().message(errno).c_str();
continue;
}
const ESM::Format format = ESM::readFormat(*stream);
stream->seekg(0);
switch (format)
{
case ESM::Format::Tes3:
{
ToUTF8::Utf8Encoder encoder(ToUTF8::calculateEncoding(mEncoding.toStdString()));
ESM::ESMReader fileReader;
fileReader.setEncoder(&encoder);
fileReader.open(std::move(stream), filepath);
file->setAuthor(QString::fromUtf8(fileReader.getAuthor().c_str()));
file->setFormat(QString::number(fileReader.esmVersionF()));
file->setDescription(QString::fromUtf8(fileReader.getDesc().c_str()));
for (const auto& master : fileReader.getGameFiles())
file->addGameFile(QString::fromUtf8(master.name.c_str()));
break;
}
case ESM::Format::Tes4:
{
ToUTF8::StatelessUtf8Encoder encoder(ToUTF8::calculateEncoding(mEncoding.toStdString()));
ESM4::Reader fileReader(std::move(stream), filepath, nullptr, &encoder, true);
file->setAuthor(QString::fromUtf8(fileReader.getAuthor().c_str()));
file->setFormat(QString::number(fileReader.esmVersionF()));
file->setDescription(QString::fromUtf8(fileReader.getDesc().c_str()));
for (const auto& master : fileReader.getGameFiles())
file->addGameFile(QString::fromUtf8(master.name.c_str()));
break;
}
default:
{
qWarning() << "Error reading addon file " << info.fileName() << ": unsupported ESM format "
<< ESM::NAME(format).toString().c_str();
continue;
}
}
// Put the file in the table
if (add)
addFile(newFile.release());
setNew(file->fileName(), newfiles);
}
catch (std::runtime_error& e)
{
// An error occurred while reading the .esp
qWarning() << "Error reading addon file: " << e.what();
}
}
}
bool ContentSelectorModel::ContentModel::containsDataFiles(const QString& path)
{
QDir dir(path);
QStringList filters;
filters << "*.esp"
<< "*.esm"
<< "*.omwgame"
<< "*.omwaddon";
dir.setNameFilters(filters);
return dir.entryList().count() != 0;
}
void ContentSelectorModel::ContentModel::clearFiles()
{
const int filesCount = mFiles.count();
if (filesCount > 0)
{
beginRemoveRows(QModelIndex(), 0, filesCount - 1);
qDeleteAll(mFiles);
mFiles.clear();
endRemoveRows();
}
}
QStringList ContentSelectorModel::ContentModel::gameFiles() const
{
QStringList gameFiles;
for (const ContentSelectorModel::EsmFile* file : mFiles)
{
if (file->isGameFile())
{
gameFiles.append(file->fileName());
}
}
return gameFiles;
}
void ContentSelectorModel::ContentModel::setCurrentGameFile(const EsmFile* file)
{
QModelIndex oldIndex = indexFromItem(mGameFile);
QModelIndex index = indexFromItem(file);
mGameFile = file;
emit dataChanged(oldIndex, oldIndex);
emit dataChanged(index, index);
}
void ContentSelectorModel::ContentModel::sortFiles()
{
emit layoutAboutToBeChanged();
// make both Qt5 (int) and Qt6 (qsizetype aka size_t) happy
using index_t = ContentFileList::size_type;
// ensure built-in are first
index_t firstModifiable = 0;
for (index_t i = 0; i < mFiles.length(); ++i)
{
if (mFiles.at(i)->builtIn())
mFiles.move(i, firstModifiable++);
}
// then non-user content
for (const auto& filename : mNonUserContent)
{
const EsmFile* file = item(filename);
int filePosition = indexFromItem(file).row();
if (filePosition >= 0)
mFiles.move(filePosition, firstModifiable++);
else
{
// the file is not in the VFS, and will be displayed with an error
auto missingFile = std::make_unique<EsmFile>(filename);
missingFile->setFromAnotherConfigFile(true);
mFiles.insert(firstModifiable++, missingFile.release());
}
}
// For the purposes of dependency sort we'll hallucinate that Bloodmoon is dependent on Tribunal
const EsmFile* tribunalFile = item("Tribunal.esm");
const EsmFile* bloodmoonFile = item("Bloodmoon.esm");
const bool sortExpansions = tribunalFile != nullptr && bloodmoonFile != nullptr;
// Dependency sort
std::unordered_set<const EsmFile*> moved;
for (int i = mFiles.size() - 1; i > firstModifiable;)
{
const auto file = mFiles.at(i);
if (moved.find(file) == moved.end())
{
int index = -1;
for (int j = firstModifiable; j < i; ++j)
{
const EsmFile* addonFile = mFiles.at(j);
const QStringList& gameFiles = addonFile->gameFiles();
// All addon files are implicitly dependent on the game file
// so that they don't accidentally become the game file
if (gameFiles.contains(file->fileName(), Qt::CaseInsensitive) || file == mGameFile
|| (sortExpansions && file == tribunalFile && addonFile == bloodmoonFile))
{
index = j;
break;
}
}
if (index >= 0)
{
mFiles.move(i, index);
moved.insert(file);
continue;
}
}
--i;
moved.clear();
}
emit layoutChanged();
}
bool ContentSelectorModel::ContentModel::isEnabled(const QModelIndex& index) const
{
return (flags(index) & Qt::ItemIsEnabled);
}
bool ContentSelectorModel::ContentModel::isNew(const QString& filepath) const
{
const auto it = mNewFiles.find(filepath);
if (it == mNewFiles.end())
return false;
return it.value();
}
void ContentSelectorModel::ContentModel::setNew(const QString& filepath, bool isNew)
{
if (filepath.isEmpty())
return;
const EsmFile* file = item(filepath);
if (!file)
return;
mNewFiles[filepath] = isNew;
}
void ContentSelectorModel::ContentModel::setNonUserContent(const QStringList& fileList)
{
mNonUserContent.clear();
for (const auto& file : fileList)
mNonUserContent.append(file.toLower());
for (auto* file : mFiles)
file->setFromAnotherConfigFile(mNonUserContent.contains(file->fileName().toLower()));
sortFiles();
}
bool ContentSelectorModel::ContentModel::isLoadOrderError(const EsmFile* file) const
{
return mPluginsWithLoadOrderError.contains(file->filePath());
}
void ContentSelectorModel::ContentModel::setContentList(const QStringList& fileList)
{
mPluginsWithLoadOrderError.clear();
int previousPosition = -1;
for (const QString& filepath : fileList)
{
if (setCheckState(filepath, true))
{
// setCheckState already gracefully handles builtIn and fromAnotherConfigFile
// as necessary, move plug-ins in visible list to match sequence of supplied filelist
const EsmFile* file = item(filepath);
int filePosition = indexFromItem(file).row();
if (filePosition < previousPosition)
{
mFiles.move(filePosition, previousPosition);
emit dataChanged(index(filePosition, 0, QModelIndex()), index(previousPosition, 0, QModelIndex()));
}
else
{
previousPosition = filePosition;
}
}
}
checkForLoadOrderErrors();
}
void ContentSelectorModel::ContentModel::checkForLoadOrderErrors()
{
for (int row = 0; row < mFiles.count(); ++row)
{
EsmFile* file = mFiles.at(row);
bool isRowInError = checkForLoadOrderErrors(file, row).count() != 0;
if (isRowInError)
{
mPluginsWithLoadOrderError.insert(file->filePath());
}
else
{
mPluginsWithLoadOrderError.remove(file->filePath());
}
}
}
QList<ContentSelectorModel::LoadOrderError> ContentSelectorModel::ContentModel::checkForLoadOrderErrors(
const EsmFile* file, int row) const
{
QList<LoadOrderError> errors = QList<LoadOrderError>();
for (const QString& dependentfileName : file->gameFiles())
{
const EsmFile* dependentFile = item(dependentfileName);
if (!dependentFile)
{
errors.append(LoadOrderError(LoadOrderError::ErrorCode_MissingDependency, dependentfileName));
}
else
{
if (!mCheckedFiles.contains(dependentFile))
{
errors.append(LoadOrderError(LoadOrderError::ErrorCode_InactiveDependency, dependentfileName));
}
if (row < indexFromItem(dependentFile).row())
{
errors.append(LoadOrderError(LoadOrderError::ErrorCode_LoadOrder, dependentfileName));
}
}
}
if (file->fileName().compare("Bloodmoon.esm", Qt::CaseInsensitive) == 0)
{
// Warn the user if Bloodmoon is loaded before Tribunal (Tribunal is not a hard dependency)
const EsmFile* tribunalFile = item("Tribunal.esm");
if (tribunalFile != nullptr && mCheckedFiles.contains(tribunalFile) && row < indexFromItem(tribunalFile).row())
errors.append(LoadOrderError(LoadOrderError::ErrorCode_LoadOrder, "Tribunal.esm"));
}
return errors;
}
QString ContentSelectorModel::ContentModel::toolTip(const EsmFile* file) const
{
if (isLoadOrderError(file))
{
QString text("<b>");
int index = indexFromItem(item(file->filePath())).row();
for (const LoadOrderError& error : checkForLoadOrderErrors(file, index))
{
assert(error.errorCode() != LoadOrderError::ErrorCode::ErrorCode_None);
text += "<p>";
text += mErrorToolTips[error.errorCode() - 1].arg(error.fileName());
text += "</p>";
}
text += ("</b>");
text += file->toolTip();
return text;
}
else
{
return file->toolTip();
}
}
void ContentSelectorModel::ContentModel::refreshModel()
{
emit dataChanged(index(0, 0), index(rowCount() - 1, 0));
}
bool ContentSelectorModel::ContentModel::setCheckState(const QString& filepath, bool checkState)
{
if (filepath.isEmpty())
return false;
const EsmFile* file = item(filepath);
if (!file || file->builtIn() || file->fromAnotherConfigFile())
return false;
if (checkState)
mCheckedFiles.insert(file);
else
mCheckedFiles.erase(file);
emit dataChanged(indexFromItem(item(filepath)), indexFromItem(item(filepath)));
if (file->isGameFile())
refreshModel();
// if we're checking an item, ensure all "upstream" files (dependencies) are checked as well.
if (checkState)
{
for (const QString& upstreamName : file->gameFiles())
{
const EsmFile* upstreamFile = item(upstreamName);
if (!upstreamFile)
continue;
mCheckedFiles.insert(upstreamFile);
emit dataChanged(indexFromItem(upstreamFile), indexFromItem(upstreamFile));
}
}
// otherwise, if we're unchecking an item (or the file is a game file) ensure all downstream files are unchecked.
else
{
for (const EsmFile* downstreamFile : mFiles)
{
QFileInfo fileInfo(filepath);
QString filename = fileInfo.fileName();
if (downstreamFile->gameFiles().contains(filename, Qt::CaseInsensitive))
{
mCheckedFiles.erase(downstreamFile);
emit dataChanged(indexFromItem(downstreamFile), indexFromItem(downstreamFile));
}
}
}
// Need to manually let Bloodmoon entry know if Tribunal is checked/unchecked
if (file->fileName().compare("Tribunal.esm", Qt::CaseInsensitive) == 0)
{
const EsmFile* bloodmoonFile = item("Bloodmoon.esm");
if (bloodmoonFile != nullptr)
{
QModelIndex bloodmoonIndex = indexFromItem(bloodmoonFile);
emit dataChanged(bloodmoonIndex, bloodmoonIndex);
}
}
return true;
}
ContentSelectorModel::ContentFileList ContentSelectorModel::ContentModel::checkedItems() const
{
ContentFileList list;
// TODO:
// First search for game files and next addons,
// so we get more or less correct game files vs addons order.
for (EsmFile* file : mFiles)
if (mCheckedFiles.contains(file))
list << file;
return list;
}
void ContentSelectorModel::ContentModel::uncheckAll()
{
emit layoutAboutToBeChanged();
mCheckedFiles.clear();
emit layoutChanged();
}
| 27,028
|
C++
|
.cpp
| 765
| 26.611765
| 119
| 0.605084
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,707
|
esmfile.cpp
|
OpenMW_openmw/components/contentselector/model/esmfile.cpp
|
#include "esmfile.hpp"
ContentSelectorModel::EsmFile::EsmFile(const QString& fileName, ModelItem* parent)
: ModelItem(parent)
, mFileName(fileName)
{
}
void ContentSelectorModel::EsmFile::setFileName(const QString& fileName)
{
mFileName = fileName;
}
void ContentSelectorModel::EsmFile::setAuthor(const QString& author)
{
mAuthor = author;
}
void ContentSelectorModel::EsmFile::setDate(const QDateTime& modified)
{
mModified = modified;
}
void ContentSelectorModel::EsmFile::setFormat(const QString& format)
{
mVersion = format;
}
void ContentSelectorModel::EsmFile::setFilePath(const QString& path)
{
mPath = path;
}
void ContentSelectorModel::EsmFile::setGameFiles(const QStringList& gamefiles)
{
mGameFiles = gamefiles;
}
void ContentSelectorModel::EsmFile::setDescription(const QString& description)
{
mDescription = description;
}
void ContentSelectorModel::EsmFile::setBuiltIn(bool builtIn)
{
mBuiltIn = builtIn;
}
void ContentSelectorModel::EsmFile::setFromAnotherConfigFile(bool fromAnotherConfigFile)
{
mFromAnotherConfigFile = fromAnotherConfigFile;
}
bool ContentSelectorModel::EsmFile::isGameFile() const
{
return (mGameFiles.size() == 0)
&& (mFileName.endsWith(QLatin1String(".esm"), Qt::CaseInsensitive)
|| mFileName.endsWith(QLatin1String(".omwgame"), Qt::CaseInsensitive));
}
QVariant ContentSelectorModel::EsmFile::fileProperty(const FileProperty prop) const
{
switch (prop)
{
case FileProperty_FileName:
return mFileName;
break;
case FileProperty_Author:
return mAuthor;
break;
case FileProperty_Format:
return mVersion;
break;
case FileProperty_DateModified:
return mModified.toString(Qt::ISODate);
break;
case FileProperty_FilePath:
return mPath;
break;
case FileProperty_Description:
return mDescription;
break;
case FileProperty_BuiltIn:
return mBuiltIn;
break;
case FileProperty_FromAnotherConfigFile:
return mFromAnotherConfigFile;
break;
case FileProperty_GameFile:
return mGameFiles;
break;
default:
break;
}
return QVariant();
}
void ContentSelectorModel::EsmFile::setFileProperty(const FileProperty prop, const QString& value)
{
switch (prop)
{
case FileProperty_FileName:
mFileName = value;
break;
case FileProperty_Author:
mAuthor = value;
break;
case FileProperty_Format:
mVersion = value;
break;
case FileProperty_DateModified:
mModified = QDateTime::fromString(value, Qt::ISODate);
break;
case FileProperty_FilePath:
mPath = value;
break;
case FileProperty_Description:
mDescription = value;
break;
// todo: check these work
case FileProperty_BuiltIn:
mBuiltIn = value == "true";
break;
case FileProperty_FromAnotherConfigFile:
mFromAnotherConfigFile = value == "true";
break;
case FileProperty_GameFile:
mGameFiles << value;
break;
default:
break;
}
}
| 3,436
|
C++
|
.cpp
| 120
| 21.383333
| 98
| 0.651248
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,708
|
combobox.cpp
|
OpenMW_openmw/components/contentselector/view/combobox.cpp
|
#include <QKeyEvent>
#include <QString>
#include <QStylePainter>
#include "combobox.hpp"
ContentSelectorView::ComboBox::ComboBox(QWidget* parent)
: QComboBox(parent)
{
mValidator
= new QRegularExpressionValidator(QRegularExpression("^[a-zA-Z0-9_]*$"), this); // Alpha-numeric + underscore
setValidator(mValidator);
setEditable(true);
setCompleter(nullptr);
setEnabled(true);
setInsertPolicy(QComboBox::NoInsert);
}
void ContentSelectorView::ComboBox::paintEvent(QPaintEvent*)
{
QStylePainter painter(this);
painter.setPen(palette().color(QPalette::Text));
// draw the combobox frame, focusrect and selected etc.
QStyleOptionComboBox opt;
initStyleOption(&opt);
painter.drawComplexControl(QStyle::CC_ComboBox, opt);
// draw the icon and text
if (!opt.editable && currentIndex() == -1) // <<< we adjust the text displayed when nothing is selected
opt.currentText = mPlaceholderText;
painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
void ContentSelectorView::ComboBox::setPlaceholderText(const QString& text)
{
mPlaceholderText = text;
}
| 1,132
|
C++
|
.cpp
| 32
| 31.5
| 117
| 0.741758
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
34,709
|
contentselector.cpp
|
OpenMW_openmw/components/contentselector/view/contentselector.cpp
|
#include "contentselector.hpp"
#include "ui_contentselector.h"
#include <components/contentselector/model/esmfile.hpp>
#include <QClipboard>
#include <QMenu>
#include <QModelIndex>
#include <QSortFilterProxyModel>
ContentSelectorView::ContentSelector::ContentSelector(QWidget* parent, bool showOMWScripts)
: QObject(parent)
, ui(std::make_unique<Ui::ContentSelector>())
{
ui->setupUi(parent);
ui->addonView->setDragDropMode(QAbstractItemView::InternalMove);
if (!showOMWScripts)
{
ui->languageComboBox->setHidden(true);
ui->refreshButton->setHidden(true);
}
buildContentModel(showOMWScripts);
buildGameFileView();
buildAddonView();
}
ContentSelectorView::ContentSelector::~ContentSelector() = default;
void ContentSelectorView::ContentSelector::buildContentModel(bool showOMWScripts)
{
QIcon warningIcon(ui->addonView->style()->standardIcon(QStyle::SP_MessageBoxWarning));
QIcon errorIcon(ui->addonView->style()->standardIcon(QStyle::SP_MessageBoxCritical));
mContentModel = new ContentSelectorModel::ContentModel(this, warningIcon, errorIcon, showOMWScripts);
}
void ContentSelectorView::ContentSelector::buildGameFileView()
{
ui->gameFileView->addItem(tr("<No game file>"));
ui->gameFileView->setVisible(true);
connect(ui->gameFileView, qOverload<int>(&ComboBox::currentIndexChanged), this,
&ContentSelector::slotCurrentGameFileIndexChanged);
ui->gameFileView->setCurrentIndex(0);
}
class AddOnProxyModel : public QSortFilterProxyModel
{
public:
explicit AddOnProxyModel(QObject* parent = nullptr)
: QSortFilterProxyModel(parent)
{
}
bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override
{
static const QString ContentTypeAddon = QString::number((int)ContentSelectorModel::ContentType_Addon);
QModelIndex nameIndex = sourceModel()->index(sourceRow, 0, sourceParent);
const QString userRole = sourceModel()->data(nameIndex, Qt::UserRole).toString();
return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent) && userRole == ContentTypeAddon;
}
};
bool ContentSelectorView::ContentSelector::isGamefileSelected() const
{
return ui->gameFileView->currentIndex() > 0;
}
QWidget* ContentSelectorView::ContentSelector::uiWidget() const
{
return ui->contentGroupBox;
}
QComboBox* ContentSelectorView::ContentSelector::languageBox() const
{
return ui->languageComboBox;
}
QToolButton* ContentSelectorView::ContentSelector::refreshButton() const
{
return ui->refreshButton;
}
QLineEdit* ContentSelectorView::ContentSelector::searchFilter() const
{
return ui->searchFilter;
}
void ContentSelectorView::ContentSelector::buildAddonView()
{
ui->addonView->setVisible(true);
mAddonProxyModel = new AddOnProxyModel(this);
mAddonProxyModel->setFilterRegularExpression(searchFilter()->text());
mAddonProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
mAddonProxyModel->setDynamicSortFilter(true);
mAddonProxyModel->setSourceModel(mContentModel);
connect(ui->searchFilter, &QLineEdit::textEdited, mAddonProxyModel, &QSortFilterProxyModel::setFilterWildcard);
connect(ui->searchFilter, &QLineEdit::textEdited, this, &ContentSelector::slotSearchFilterTextChanged);
ui->addonView->setModel(mAddonProxyModel);
connect(ui->addonView, &QTableView::activated, this, &ContentSelector::slotAddonTableItemActivated);
connect(mContentModel, &ContentSelectorModel::ContentModel::dataChanged, this,
&ContentSelector::signalAddonDataChanged);
connect(mContentModel, &ContentSelectorModel::ContentModel::dataChanged, this, &ContentSelector::slotRowsMoved);
buildContextMenu();
}
void ContentSelectorView::ContentSelector::buildContextMenu()
{
ui->addonView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->addonView, &QTableView::customContextMenuRequested, this, &ContentSelector::slotShowContextMenu);
mContextMenu = new QMenu(ui->addonView);
mContextMenu->addAction(tr("&Check Selected"), this, SLOT(slotCheckMultiSelectedItems()));
mContextMenu->addAction(tr("&Uncheck Selected"), this, SLOT(slotUncheckMultiSelectedItems()));
mContextMenu->addAction(tr("&Copy Path(s) to Clipboard"), this, SLOT(slotCopySelectedItemsPaths()));
}
void ContentSelectorView::ContentSelector::setNonUserContent(const QStringList& fileList)
{
mContentModel->setNonUserContent(fileList);
}
void ContentSelectorView::ContentSelector::setProfileContent(const QStringList& fileList)
{
clearCheckStates();
for (const QString& filepath : fileList)
{
const ContentSelectorModel::EsmFile* file = mContentModel->item(filepath);
if (file && file->isGameFile())
{
setGameFile(filepath);
break;
}
}
setContentList(fileList);
}
void ContentSelectorView::ContentSelector::setGameFile(const QString& filename)
{
int index = 0;
if (!filename.isEmpty())
{
const ContentSelectorModel::EsmFile* file = mContentModel->item(filename);
index = ui->gameFileView->findText(file->fileName());
// verify that the current index is also checked in the model
if (!mContentModel->setCheckState(filename, true))
{
// throw error in case file not found?
return;
}
}
ui->gameFileView->setCurrentIndex(index);
}
void ContentSelectorView::ContentSelector::clearCheckStates()
{
mContentModel->uncheckAll();
}
void ContentSelectorView::ContentSelector::setEncoding(const QString& encoding)
{
mContentModel->setEncoding(encoding);
}
void ContentSelectorView::ContentSelector::setContentList(const QStringList& list)
{
if (list.isEmpty())
{
slotCurrentGameFileIndexChanged(ui->gameFileView->currentIndex());
}
else
mContentModel->setContentList(list);
}
ContentSelectorModel::ContentFileList ContentSelectorView::ContentSelector::selectedFiles() const
{
if (!mContentModel)
return ContentSelectorModel::ContentFileList();
return mContentModel->checkedItems();
}
void ContentSelectorView::ContentSelector::addFiles(const QString& path, bool newfiles)
{
mContentModel->addFiles(path, newfiles);
// add any game files to the combo box
for (const QString& gameFileName : mContentModel->gameFiles())
{
if (ui->gameFileView->findText(gameFileName) == -1)
{
ui->gameFileView->addItem(gameFileName);
}
}
if (ui->gameFileView->currentIndex() != 0)
ui->gameFileView->setCurrentIndex(0);
mContentModel->uncheckAll();
mContentModel->checkForLoadOrderErrors();
}
void ContentSelectorView::ContentSelector::sortFiles()
{
mContentModel->sortFiles();
}
bool ContentSelectorView::ContentSelector::containsDataFiles(const QString& path)
{
return mContentModel->containsDataFiles(path);
}
void ContentSelectorView::ContentSelector::clearFiles()
{
mContentModel->clearFiles();
}
QString ContentSelectorView::ContentSelector::currentFile() const
{
QModelIndex currentIdx = ui->addonView->currentIndex();
if (!currentIdx.isValid() && ui->gameFileView->currentIndex() > 0)
return ui->gameFileView->currentText();
QModelIndex idx = mContentModel->index(mAddonProxyModel->mapToSource(currentIdx).row(), 0, QModelIndex());
return mContentModel->data(idx, Qt::DisplayRole).toString();
}
void ContentSelectorView::ContentSelector::slotCurrentGameFileIndexChanged(int index)
{
static int oldIndex = -1;
if (index != oldIndex)
{
if (oldIndex > -1)
{
setGameFileSelected(oldIndex, false);
}
oldIndex = index;
setGameFileSelected(index, true);
mContentModel->checkForLoadOrderErrors();
}
emit signalCurrentGamefileIndexChanged(index);
}
void ContentSelectorView::ContentSelector::setGameFileSelected(int index, bool selected)
{
QString fileName = ui->gameFileView->itemText(index);
const ContentSelectorModel::EsmFile* file = mContentModel->item(fileName);
if (file != nullptr)
{
QModelIndex index2(mContentModel->indexFromItem(file));
mContentModel->setData(index2, selected, Qt::UserRole + 1);
}
mContentModel->setCurrentGameFile(selected ? file : nullptr);
}
void ContentSelectorView::ContentSelector::slotAddonTableItemActivated(const QModelIndex& index)
{
// toggles check state when an AddOn file is double clicked or activated by keyboard
QModelIndex sourceIndex = mAddonProxyModel->mapToSource(index);
if (!mContentModel->isEnabled(sourceIndex))
return;
Qt::CheckState checkState = Qt::Unchecked;
if (mContentModel->data(sourceIndex, Qt::CheckStateRole).toInt() == Qt::Unchecked)
checkState = Qt::Checked;
mContentModel->setData(sourceIndex, checkState, Qt::CheckStateRole);
}
void ContentSelectorView::ContentSelector::slotShowContextMenu(const QPoint& pos)
{
QPoint globalPos = ui->addonView->viewport()->mapToGlobal(pos);
mContextMenu->exec(globalPos);
}
void ContentSelectorView::ContentSelector::setCheckStateForMultiSelectedItems(bool checked)
{
Qt::CheckState checkState = checked ? Qt::Checked : Qt::Unchecked;
for (const QModelIndex& index : ui->addonView->selectionModel()->selectedIndexes())
{
QModelIndex sourceIndex = mAddonProxyModel->mapToSource(index);
if (mContentModel->data(sourceIndex, Qt::CheckStateRole).toInt() != checkState)
{
mContentModel->setData(sourceIndex, checkState, Qt::CheckStateRole);
}
}
}
void ContentSelectorView::ContentSelector::slotUncheckMultiSelectedItems()
{
setCheckStateForMultiSelectedItems(false);
}
void ContentSelectorView::ContentSelector::slotCheckMultiSelectedItems()
{
setCheckStateForMultiSelectedItems(true);
}
void ContentSelectorView::ContentSelector::slotCopySelectedItemsPaths()
{
QClipboard* clipboard = QApplication::clipboard();
QString filepaths;
for (const QModelIndex& index : ui->addonView->selectionModel()->selectedIndexes())
{
int row = mAddonProxyModel->mapToSource(index).row();
const ContentSelectorModel::EsmFile* file = mContentModel->item(row);
filepaths += file->filePath() + "\n";
}
if (!filepaths.isEmpty())
{
clipboard->setText(filepaths);
}
}
void ContentSelectorView::ContentSelector::slotSearchFilterTextChanged(const QString& newText)
{
ui->addonView->setDragEnabled(newText.isEmpty());
}
void ContentSelectorView::ContentSelector::slotRowsMoved()
{
ui->addonView->selectionModel()->clearSelection();
}
| 10,713
|
C++
|
.cpp
| 276
| 34.275362
| 116
| 0.750868
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,710
|
shadermanager.cpp
|
OpenMW_openmw/components/shader/shadermanager.cpp
|
#include "shadermanager.hpp"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <components/debug/debuglog.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/misc/strings/format.hpp>
#include <components/settings/settings.hpp>
#include <filesystem>
#include <fstream>
#include <osg/Program>
#include <osgViewer/Viewer>
#include <regex>
#include <set>
#include <sstream>
#include <unordered_map>
namespace
{
osg::Shader::Type getShaderType(const std::string& templateName)
{
auto ext = std::filesystem::path(templateName).extension();
if (ext == ".vert")
return osg::Shader::VERTEX;
if (ext == ".frag")
return osg::Shader::FRAGMENT;
if (ext == ".geom")
return osg::Shader::GEOMETRY;
if (ext == ".comp")
return osg::Shader::COMPUTE;
if (ext == ".tese")
return osg::Shader::TESSEVALUATION;
if (ext == ".tesc")
return osg::Shader::TESSCONTROL;
throw std::runtime_error("unrecognized shader template name: " + templateName);
}
std::string getRootPrefix(const std::string& path)
{
if (path.starts_with("lib"))
return "lib";
else if (path.starts_with("compatibility"))
return "compatibility";
else if (path.starts_with("core"))
return "core";
else
return "";
}
}
namespace Shader
{
ShaderManager::ShaderManager()
{
mHotReloadManager = std::make_unique<HotReloadManager>();
}
ShaderManager::~ShaderManager() = default;
void ShaderManager::setShaderPath(const std::filesystem::path& path)
{
mPath = path;
}
bool addLineDirectivesAfterConditionalBlocks(std::string& source)
{
for (size_t position = 0; position < source.length();)
{
size_t foundPos = source.find("#endif", position);
foundPos = std::min(foundPos, source.find("#elif", position));
foundPos = std::min(foundPos, source.find("#else", position));
if (foundPos == std::string::npos)
break;
foundPos = source.find_first_of("\n\r", foundPos);
foundPos = source.find_first_not_of("\n\r", foundPos);
if (foundPos == std::string::npos)
break;
size_t lineDirectivePosition = source.rfind("#line", foundPos);
int lineNumber;
if (lineDirectivePosition != std::string::npos)
{
size_t lineNumberStart = lineDirectivePosition + std::string("#line ").length();
size_t lineNumberEnd = source.find_first_not_of("0123456789", lineNumberStart);
std::string lineNumberString = source.substr(lineNumberStart, lineNumberEnd - lineNumberStart);
lineNumber = Misc::StringUtils::toNumeric<int>(lineNumberString, 2) - 1;
}
else
{
lineDirectivePosition = 0;
lineNumber = 1;
}
lineNumber += std::count(source.begin() + lineDirectivePosition, source.begin() + foundPos, '\n');
source.replace(foundPos, 0, "#line " + std::to_string(lineNumber) + "\n");
position = foundPos;
}
return true;
}
// Recursively replaces include statements with the actual source of the included files.
// Adjusts #line statements accordingly and detects cyclic includes.
// cycleIncludeChecker is the set of files that include this file directly or indirectly, and is intentionally not a
// reference to allow automatic cleanup.
static bool parseIncludes(const std::filesystem::path& shaderPath, std::string& source, const std::string& fileName,
int& fileNumber, std::set<std::filesystem::path> cycleIncludeChecker,
std::set<std::filesystem::path>& includedFiles)
{
includedFiles.insert(shaderPath / fileName);
// An include is cyclic if it is being included by itself
if (cycleIncludeChecker.insert(shaderPath / fileName).second == false)
{
Log(Debug::Error) << "Shader " << fileName << " error: Detected cyclic #includes";
return false;
}
Misc::StringUtils::replaceAll(source, "\r\n", "\n");
size_t foundPos = 0;
while ((foundPos = source.find("#include")) != std::string::npos)
{
size_t start = source.find('"', foundPos);
if (start == std::string::npos || start == source.size() - 1)
{
Log(Debug::Error) << "Shader " << fileName << " error: Invalid #include";
return false;
}
size_t end = source.find('"', start + 1);
if (end == std::string::npos)
{
Log(Debug::Error) << "Shader " << fileName << " error: Invalid #include";
return false;
}
std::string includeFilename = source.substr(start + 1, end - (start + 1));
// Check if this include is a relative path
// TODO: We shouldn't be relying on soft-coded root prefixes, just check if the path exists and fallback to
// searching root if it doesn't
if (getRootPrefix(includeFilename).empty())
includeFilename
= Files::pathToUnicodeString(std::filesystem::path(fileName).parent_path() / includeFilename);
std::filesystem::path includePath = shaderPath / includeFilename;
// Determine the line number that will be used for the #line directive following the included source
size_t lineDirectivePosition = source.rfind("#line", foundPos);
int lineNumber;
if (lineDirectivePosition != std::string::npos)
{
size_t lineNumberStart = lineDirectivePosition + std::string("#line ").length();
size_t lineNumberEnd = source.find_first_not_of("0123456789", lineNumberStart);
std::string lineNumberString = source.substr(lineNumberStart, lineNumberEnd - lineNumberStart);
lineNumber = Misc::StringUtils::toNumeric<int>(lineNumberString, 2) - 1;
}
else
{
lineDirectivePosition = 0;
lineNumber = 0;
}
lineNumber += std::count(source.begin() + lineDirectivePosition, source.begin() + foundPos, '\n');
// Include the file recursively
std::ifstream includeFstream;
includeFstream.open(includePath);
if (includeFstream.fail())
{
Log(Debug::Error) << "Shader " << fileName << " error: Failed to open include " << includePath;
return false;
}
int includedFileNumber = fileNumber++;
std::stringstream buffer;
buffer << includeFstream.rdbuf();
std::string stringRepresentation = buffer.str();
if (!addLineDirectivesAfterConditionalBlocks(stringRepresentation)
|| !parseIncludes(
shaderPath, stringRepresentation, includeFilename, fileNumber, cycleIncludeChecker, includedFiles))
{
Log(Debug::Error) << "In file included from " << fileName << "." << lineNumber;
return false;
}
std::stringstream toInsert;
toInsert << "#line 0 " << includedFileNumber << "\n"
<< stringRepresentation << "\n#line " << lineNumber << " 0\n";
source.replace(foundPos, (end - foundPos + 1), toInsert.str());
}
return true;
}
bool parseForeachDirective(std::string& source, const std::string& templateName, size_t foundPos)
{
size_t iterNameStart = foundPos + strlen("$foreach") + 1;
size_t iterNameEnd = source.find_first_of(" \n\r()[].;,", iterNameStart);
if (iterNameEnd == std::string::npos)
{
Log(Debug::Error) << "Shader " << templateName << " error: Unexpected EOF";
return false;
}
std::string iteratorName = "$" + source.substr(iterNameStart, iterNameEnd - iterNameStart);
size_t listStart = iterNameEnd + 1;
size_t listEnd = source.find_first_of("\n\r", listStart);
if (listEnd == std::string::npos)
{
Log(Debug::Error) << "Shader " << templateName << " error: Unexpected EOF";
return false;
}
std::string list = source.substr(listStart, listEnd - listStart);
std::vector<std::string> listElements;
if (list != "")
Misc::StringUtils::split(list, listElements, ",");
size_t contentStart = source.find_first_not_of("\n\r", listEnd);
size_t contentEnd = source.find("$endforeach", contentStart);
if (contentEnd == std::string::npos)
{
Log(Debug::Error) << "Shader " << templateName << " error: Unexpected EOF";
return false;
}
std::string content = source.substr(contentStart, contentEnd - contentStart);
size_t overallEnd = contentEnd + std::string("$endforeach").length();
size_t lineDirectivePosition = source.rfind("#line", overallEnd);
int lineNumber;
if (lineDirectivePosition != std::string::npos)
{
size_t lineNumberStart = lineDirectivePosition + std::string("#line ").length();
size_t lineNumberEnd = source.find_first_not_of("0123456789", lineNumberStart);
std::string lineNumberString = source.substr(lineNumberStart, lineNumberEnd - lineNumberStart);
lineNumber = Misc::StringUtils::toNumeric<int>(lineNumberString, 2);
}
else
{
lineDirectivePosition = 0;
lineNumber = 2;
}
lineNumber += std::count(source.begin() + lineDirectivePosition, source.begin() + overallEnd, '\n');
std::string replacement;
for (std::vector<std::string>::const_iterator element = listElements.cbegin(); element != listElements.cend();
element++)
{
std::string contentInstance = content;
size_t foundIterator;
while ((foundIterator = contentInstance.find(iteratorName)) != std::string::npos)
contentInstance.replace(foundIterator, iteratorName.length(), *element);
replacement += contentInstance;
}
replacement += "\n#line " + std::to_string(lineNumber);
source.replace(foundPos, overallEnd - foundPos, replacement);
return true;
}
bool parseLinkDirective(
std::string& source, std::string& linkTarget, const std::string& templateName, size_t foundPos)
{
size_t endPos = foundPos + 5;
size_t lineEnd = source.find_first_of('\n', endPos);
// If lineEnd = npos, this is the last line, so no need to check
std::string linkStatement = source.substr(endPos, lineEnd - endPos);
std::regex linkRegex(R"r(\s*"([^"]+)"\s*)r" // Find any quoted string as the link name -> match[1]
R"r((if\s+)r" // Begin optional condition -> match[2]
R"r((!)?\s*)r" // Optional ! -> match[3]
R"r(([_a-zA-Z0-9]+)?)r" // The condition -> match[4]
R"r()?\s*)r" // End optional condition -> match[2]
);
std::smatch linkMatch;
bool hasCondition = false;
std::string linkConditionExpression;
if (std::regex_match(linkStatement, linkMatch, linkRegex))
{
linkTarget = linkMatch[1].str();
hasCondition = !linkMatch[2].str().empty();
linkConditionExpression = linkMatch[4].str();
}
else
{
Log(Debug::Error) << "Shader " << templateName << " error: Expected a shader filename to link";
return false;
}
if (linkTarget.empty())
{
Log(Debug::Error) << "Shader " << templateName << " error: Empty link name";
return false;
}
if (hasCondition)
{
bool condition = !(linkConditionExpression.empty() || linkConditionExpression == "0");
if (linkMatch[3].str() == "!")
condition = !condition;
if (!condition)
linkTarget.clear();
}
source.replace(foundPos, lineEnd - foundPos, "");
return true;
}
bool parseDirectives(std::string& source, std::vector<std::string>& linkedShaderTemplateNames,
const ShaderManager::DefineMap& defines, const ShaderManager::DefineMap& globalDefines,
const std::string& templateName)
{
const char escapeCharacter = '$';
size_t foundPos = 0;
while ((foundPos = source.find(escapeCharacter, foundPos)) != std::string::npos)
{
size_t endPos = source.find_first_of(" \n\r()[].;,", foundPos);
if (endPos == std::string::npos)
{
Log(Debug::Error) << "Shader " << templateName << " error: Unexpected EOF";
return false;
}
std::string directive = source.substr(foundPos + 1, endPos - (foundPos + 1));
if (directive == "foreach")
{
if (!parseForeachDirective(source, templateName, foundPos))
return false;
}
else if (directive == "link")
{
std::string linkTarget;
if (!parseLinkDirective(source, linkTarget, templateName, foundPos))
return false;
if (!linkTarget.empty() && linkTarget != templateName)
linkedShaderTemplateNames.push_back(linkTarget);
}
else
{
Log(Debug::Error) << "Shader " << templateName << " error: Unknown shader directive: $" << directive;
return false;
}
}
return true;
}
bool parseDefines(std::string& source, const ShaderManager::DefineMap& defines,
const ShaderManager::DefineMap& globalDefines, const std::string& templateName)
{
const char escapeCharacter = '@';
size_t foundPos = 0;
std::vector<std::string> forIterators;
while ((foundPos = source.find(escapeCharacter)) != std::string::npos)
{
size_t endPos = source.find_first_of(" \n\r()[].;,", foundPos);
if (endPos == std::string::npos)
{
Log(Debug::Error) << "Shader " << templateName << " error: Unexpected EOF";
return false;
}
std::string define = source.substr(foundPos + 1, endPos - (foundPos + 1));
ShaderManager::DefineMap::const_iterator defineFound = defines.find(define);
ShaderManager::DefineMap::const_iterator globalDefineFound = globalDefines.find(define);
if (define == "foreach")
{
source.replace(foundPos, 1, "$");
size_t iterNameStart = endPos + 1;
size_t iterNameEnd = source.find_first_of(" \n\r()[].;,", iterNameStart);
if (iterNameEnd == std::string::npos)
{
Log(Debug::Error) << "Shader " << templateName << " error: Unexpected EOF";
return false;
}
forIterators.push_back(source.substr(iterNameStart, iterNameEnd - iterNameStart));
}
else if (define == "endforeach")
{
source.replace(foundPos, 1, "$");
if (forIterators.empty())
{
Log(Debug::Error) << "Shader " << templateName << " error: endforeach without foreach";
return false;
}
else
forIterators.pop_back();
}
else if (define == "link")
{
source.replace(foundPos, 1, "$");
}
else if (std::find(forIterators.begin(), forIterators.end(), define) != forIterators.end())
{
source.replace(foundPos, 1, "$");
}
else if (defineFound != defines.end())
{
source.replace(foundPos, endPos - foundPos, defineFound->second);
}
else if (globalDefineFound != globalDefines.end())
{
source.replace(foundPos, endPos - foundPos, globalDefineFound->second);
}
else
{
Log(Debug::Error) << "Shader " << templateName << " error: Undefined " << define;
return false;
}
}
return true;
}
struct HotReloadManager
{
using KeysHolder = std::set<ShaderManager::MapKey>;
std::unordered_map<std::string, KeysHolder> mShaderFiles;
std::unordered_map<std::string, std::set<std::filesystem::path>> templateIncludedFiles;
std::filesystem::file_time_type mLastAutoRecompileTime;
bool mHotReloadEnabled;
bool mTriggerReload;
HotReloadManager()
{
mTriggerReload = false;
mHotReloadEnabled = false;
mLastAutoRecompileTime = std::filesystem::file_time_type::clock::now();
}
void addShaderFiles(const std::string& templateName, const ShaderManager::DefineMap& defines)
{
const std::set<std::filesystem::path>& shaderFiles = templateIncludedFiles[templateName];
for (const std::filesystem::path& file : shaderFiles)
{
mShaderFiles[Files::pathToUnicodeString(file)].insert(std::make_pair(templateName, defines));
}
}
void update(ShaderManager& Manager, osgViewer::Viewer& viewer)
{
auto timeSinceLastCheckMillis = std::chrono::duration_cast<std::chrono::milliseconds>(
std::filesystem::file_time_type::clock::now() - mLastAutoRecompileTime);
if ((mHotReloadEnabled && timeSinceLastCheckMillis.count() > 200) || mTriggerReload == true)
{
reloadTouchedShaders(Manager, viewer);
}
mTriggerReload = false;
}
void reloadTouchedShaders(ShaderManager& Manager, osgViewer::Viewer& viewer)
{
bool threadsRunningToStop = false;
for (auto& [pathShaderToTest, shaderKeys] : mShaderFiles)
{
std::filesystem::file_time_type write_time = std::filesystem::last_write_time(pathShaderToTest);
if (write_time.time_since_epoch() > mLastAutoRecompileTime.time_since_epoch())
{
if (!threadsRunningToStop)
{
threadsRunningToStop = viewer.areThreadsRunning();
if (threadsRunningToStop)
viewer.stopThreading();
}
for (const auto& [templateName, shaderDefines] : shaderKeys)
{
ShaderManager::ShaderMap::iterator shaderIt
= Manager.mShaders.find(std::make_pair(templateName, shaderDefines));
if (shaderIt == Manager.mShaders.end())
{
Log(Debug::Error) << "Failed to find shader " << templateName;
continue;
}
ShaderManager::TemplateMap::iterator templateIt = Manager.mShaderTemplates.find(
templateName); // Can't be Null, if we're here it means the template was added
assert(templateIt != Manager.mShaderTemplates.end());
std::string& shaderSource = templateIt->second;
std::set<std::filesystem::path> insertedPaths;
std::filesystem::path path = (std::filesystem::path(Manager.mPath) / templateName);
std::ifstream stream;
stream.open(path);
if (stream.fail())
{
Log(Debug::Error) << "Failed to open " << Files::pathToUnicodeString(path);
}
std::stringstream buffer;
buffer << stream.rdbuf();
// parse includes
int fileNumber = 1;
std::string source = buffer.str();
if (!addLineDirectivesAfterConditionalBlocks(source)
|| !parseIncludes(std::filesystem::path(Manager.mPath), source, templateName, fileNumber,
{}, insertedPaths))
{
break;
}
shaderSource = std::move(source);
std::vector<std::string> linkedShaderNames;
if (!Manager.createSourceFromTemplate(
shaderSource, linkedShaderNames, templateName, shaderDefines))
{
break;
}
shaderIt->second->setShaderSource(shaderSource);
}
}
}
if (threadsRunningToStop)
viewer.startThreading();
mLastAutoRecompileTime = std::filesystem::file_time_type::clock::now();
}
};
osg::ref_ptr<osg::Shader> ShaderManager::getShader(
std::string templateName, const ShaderManager::DefineMap& defines, std::optional<osg::Shader::Type> type)
{
std::unique_lock<std::mutex> lock(mMutex);
// TODO: Implement mechanism to switch to core or compatibility profile shaders.
// This logic is temporary until core support is supported.
if (getRootPrefix(templateName).empty())
templateName = "compatibility/" + templateName;
// read the template if we haven't already
TemplateMap::iterator templateIt = mShaderTemplates.find(templateName);
std::set<std::filesystem::path> insertedPaths;
if (templateIt == mShaderTemplates.end())
{
std::filesystem::path path = mPath / templateName;
std::ifstream stream;
stream.open(path);
if (stream.fail())
{
Log(Debug::Error) << "Failed to open " << path;
return nullptr;
}
std::stringstream buffer;
buffer << stream.rdbuf();
// parse includes
int fileNumber = 1;
std::string source = buffer.str();
if (!addLineDirectivesAfterConditionalBlocks(source)
|| !parseIncludes(mPath, source, templateName, fileNumber, {}, insertedPaths))
return nullptr;
mHotReloadManager->templateIncludedFiles[templateName] = std::move(insertedPaths);
templateIt = mShaderTemplates.insert(std::make_pair(templateName, source)).first;
}
ShaderMap::iterator shaderIt = mShaders.find(std::make_pair(templateName, defines));
if (shaderIt == mShaders.end())
{
std::string shaderSource = templateIt->second;
std::vector<std::string> linkedShaderNames;
if (!createSourceFromTemplate(shaderSource, linkedShaderNames, templateName, defines))
{
// Add to the cache anyway to avoid logging the same error over and over.
mShaders.insert(std::make_pair(std::make_pair(templateName, defines), nullptr));
return nullptr;
}
osg::ref_ptr<osg::Shader> shader(new osg::Shader(type ? *type : getShaderType(templateName)));
shader->setShaderSource(shaderSource);
// Assign a unique prefix to allow the SharedStateManager to compare shaders efficiently.
// Append shader source filename for debugging.
static unsigned int counter = 0;
shader->setName(Misc::StringUtils::format("%u %s", counter++, templateName));
mHotReloadManager->addShaderFiles(templateName, defines);
lock.unlock();
getLinkedShaders(shader, linkedShaderNames, defines);
lock.lock();
shaderIt = mShaders.insert(std::make_pair(std::make_pair(templateName, defines), shader)).first;
}
return shaderIt->second;
}
osg::ref_ptr<osg::Program> ShaderManager::getProgram(
const std::string& templateName, const DefineMap& defines, const osg::Program* programTemplate)
{
auto vert = getShader(templateName + ".vert", defines);
auto frag = getShader(templateName + ".frag", defines);
if (!vert || !frag)
throw std::runtime_error("failed initializing shader: " + templateName);
return getProgram(std::move(vert), std::move(frag), programTemplate);
}
osg::ref_ptr<osg::Program> ShaderManager::getProgram(osg::ref_ptr<osg::Shader> vertexShader,
osg::ref_ptr<osg::Shader> fragmentShader, const osg::Program* programTemplate)
{
std::lock_guard<std::mutex> lock(mMutex);
ProgramMap::iterator found = mPrograms.find(std::make_pair(vertexShader, fragmentShader));
if (found == mPrograms.end())
{
if (!programTemplate)
programTemplate = mProgramTemplate;
osg::ref_ptr<osg::Program> program
= programTemplate ? cloneProgram(programTemplate) : osg::ref_ptr<osg::Program>(new osg::Program);
program->addShader(vertexShader);
program->addShader(fragmentShader);
addLinkedShaders(vertexShader, program);
addLinkedShaders(fragmentShader, program);
found = mPrograms.insert(std::make_pair(std::make_pair(vertexShader, fragmentShader), program)).first;
}
return found->second;
}
osg::ref_ptr<osg::Program> ShaderManager::cloneProgram(const osg::Program* src)
{
osg::ref_ptr<osg::Program> program = static_cast<osg::Program*>(src->clone(osg::CopyOp::SHALLOW_COPY));
for (auto& [name, idx] : src->getUniformBlockBindingList())
program->addBindUniformBlock(name, idx);
return program;
}
ShaderManager::DefineMap ShaderManager::getGlobalDefines()
{
return DefineMap(mGlobalDefines);
}
void ShaderManager::setGlobalDefines(DefineMap& globalDefines)
{
mGlobalDefines = globalDefines;
for (const auto& [key, shader] : mShaders)
{
std::string templateId = key.first;
ShaderManager::DefineMap defines = key.second;
if (shader == nullptr)
// I'm not sure how to handle a shader that was already broken as there's no way to get a potential
// replacement to the nodes that need it.
continue;
std::string shaderSource = mShaderTemplates[templateId];
std::vector<std::string> linkedShaderNames;
if (!createSourceFromTemplate(shaderSource, linkedShaderNames, templateId, defines))
// We just broke the shader and there's no way to force existing objects back to fixed-function mode as
// we would when creating the shader. If we put a nullptr in the shader map, we just lose the ability to
// put a working one in later.
continue;
shader->setShaderSource(shaderSource);
getLinkedShaders(shader, linkedShaderNames, defines);
}
}
void ShaderManager::releaseGLObjects(osg::State* state)
{
std::lock_guard<std::mutex> lock(mMutex);
for (const auto& [_, shader] : mShaders)
{
if (shader != nullptr)
shader->releaseGLObjects(state);
}
for (const auto& [_, program] : mPrograms)
program->releaseGLObjects(state);
}
bool ShaderManager::createSourceFromTemplate(std::string& source,
std::vector<std::string>& linkedShaderTemplateNames, const std::string& templateName,
const ShaderManager::DefineMap& defines)
{
if (!parseDefines(source, defines, mGlobalDefines, templateName))
return false;
if (!parseDirectives(source, linkedShaderTemplateNames, defines, mGlobalDefines, templateName))
return false;
return true;
}
void ShaderManager::getLinkedShaders(
osg::ref_ptr<osg::Shader> shader, const std::vector<std::string>& linkedShaderNames, const DefineMap& defines)
{
mLinkedShaders.erase(shader);
if (linkedShaderNames.empty())
return;
for (auto& linkedShaderName : linkedShaderNames)
{
auto linkedShader = getShader(linkedShaderName, defines, shader->getType());
if (linkedShader)
mLinkedShaders[shader].emplace_back(linkedShader);
}
}
void ShaderManager::addLinkedShaders(osg::ref_ptr<osg::Shader> shader, osg::ref_ptr<osg::Program> program)
{
auto linkedIt = mLinkedShaders.find(shader);
if (linkedIt != mLinkedShaders.end())
for (const auto& linkedShader : linkedIt->second)
program->addShader(linkedShader);
}
int ShaderManager::reserveGlobalTextureUnits(Slot slot, int count)
{
// TODO: Reuse units when count increase forces reallocation
// TODO: Warn if trampling on the ~8 units needed by model textures
auto unit = mReservedTextureUnitsBySlot[static_cast<int>(slot)];
if (unit.index >= 0 && unit.count >= count)
return unit.index;
if (getAvailableTextureUnits() < count + 1)
throw std::runtime_error("Can't reserve texture unit; no available units");
mReservedTextureUnits += count;
unit.index = mMaxTextureUnits - mReservedTextureUnits;
unit.count = count;
mReservedTextureUnitsBySlot[static_cast<int>(slot)] = unit;
std::string_view slotDescr;
switch (slot)
{
case Slot::OpaqueDepthTexture:
slotDescr = "opaque depth texture";
break;
case Slot::SkyTexture:
slotDescr = "sky RTT";
break;
case Slot::ShadowMaps:
slotDescr = "shadow maps";
break;
default:
slotDescr = "UNKNOWN";
}
if (unit.count == 1)
Log(Debug::Info) << "Reserving texture unit for " << slotDescr << ": " << unit.index;
else
Log(Debug::Info) << "Reserving texture units for " << slotDescr << ": " << unit.index << ".."
<< (unit.index + count - 1);
return unit.index;
}
void ShaderManager::update(osgViewer::Viewer& viewer)
{
mHotReloadManager->update(*this, viewer);
}
void ShaderManager::setHotReloadEnabled(bool value)
{
mHotReloadManager->mHotReloadEnabled = value;
}
void ShaderManager::triggerShaderReload()
{
mHotReloadManager->mTriggerReload = true;
}
}
| 31,587
|
C++
|
.cpp
| 677
| 34.418021
| 120
| 0.57718
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.