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,266
completion_menu.hpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/completion_menu.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "../util/popup_widget.hpp" #include "../../core/sc_introspection.hpp" #include <QObject> #include <QStandardItemModel> #include <QStandardItem> #include <QListView> #include <QHBoxLayout> #include <QSortFilterProxyModel> #include <QTextBrowser> namespace ScIDE { namespace ScLanguage { struct Method; struct Class; } class CompletionTextBrowser : public QTextBrowser { // FIXME: Workaround for bug #1452 - crash when dragging/copying text from completion help window // QT seems to delete the QMimeData before it's finished with it, causing a crash. // The only way to avoid is to return no MIME data at all. QMimeData* createMimeDataFromSelection() const { return NULL; }; }; class CompletionMenu : public PopUpWidget { Q_OBJECT public: enum DataRole { CompletionRole = Qt::UserRole, MethodRole }; CompletionMenu(QWidget* parent = 0); void addItem(QStandardItem* item); void addInfo(QString info); void adapt(); void setCompletionRole(int role); QString currentText(); const ScLanguage::Method* currentMethod(); QString exec(const QRect& rect); QSortFilterProxyModel* model(); QListView* view(); protected: virtual bool eventFilter(QObject* obj, QEvent* ev); private: QListView* mListView; QStandardItemModel* mModel; QSortFilterProxyModel* mFilterModel; CompletionTextBrowser* mTextBrowser; QHBoxLayout* mLayout; int mCompletionRole; private slots: void onAnchorClicked(const QUrl url); signals: void itemChanged(int item); void infoClicked(QString info); }; } // namespace ScIDE
2,459
C++
.h
67
33.059701
101
0.754526
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,267
tokens.hpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/tokens.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QTextBlock> #include <vector> namespace ScIDE { struct Token { enum Type { Unknown = 0, WhiteSpace, Keyword, Builtin, Primitive, Name, Class, Symbol, SymbolMark, StringMark, Char, RadixFloat, ScaleDegreeFloat, Float, HexInt, EnvVar, SymbolArg, SingleLineComment, MultiLineCommentStart, MultiLineCommentEnd, OpeningBracket, ClosingBracket, Operator }; Token(Type t, int pos, int len = 0, char c = 0): type(t), positionInBlock(pos), length(len), character(c) {} Token(Token const& rhs): type(rhs.type), positionInBlock(rhs.positionInBlock), length(rhs.length), character(rhs.character) {} Type type; int positionInBlock; int length; char character; }; struct TextBlockData : public QTextBlockUserData { std::vector<Token> tokens; }; class TokenIterator { /* TokenIterator allows easy iteration over tokens in a Document (produced by the syntax highlighter). An iterator is valid as long as it refers to an existing token. An invalid iterator must not be dereferenced, incremented or decremented. Incrementing and decrementing an iterator makes it refer to the next and previous token in the document, respectively, regardless of which block the tokens reside in. If there is no next/previous token, then incrementing/decrementing an iterator will make it invalid. */ private: QTextBlock blk; int idx; TextBlockData* data; public: TokenIterator(): idx(-1) {} bool isValid() const { return idx >= 0; } const QTextBlock& block() const { return blk; } bool operator==(TokenIterator& other) const { return blk == other.blk && idx == other.idx; } const Token& operator*() { Q_ASSERT(blk.isValid()); Q_ASSERT(idx >= 0); Q_ASSERT(data); return data->tokens[idx]; } const Token* operator->() const { Q_ASSERT(blk.isValid()); Q_ASSERT(idx >= 0); Q_ASSERT(data); return &data->tokens[idx]; } // Constructs an iterator for the first token at the given block. // If there's no token in the block, the new iterator is invalid. TokenIterator(const QTextBlock& block): blk(block), idx(-1) { if (block.isValid()) { data = static_cast<TextBlockData*>(block.userData()); if (data && !data->tokens.empty()) idx = 0; } } // Constructs an iterator for the token that starts at, or contains the given position. // If there is no such token, the new iterator is invalid. TokenIterator(const QTextBlock& block, int positionInBlock): blk(block) { if (block.isValid()) { data = static_cast<TextBlockData*>(block.userData()); idx = data ? data->tokens.size() : 0; while (idx--) { const Token& token = data->tokens[idx]; if (token.positionInBlock > positionInBlock) continue; else if (token.positionInBlock == positionInBlock || token.positionInBlock + token.length > positionInBlock) break; } } else idx = -1; } // Return an iterator for the first token found left of given position, anywhere in the document. // If there is no such token, the returned iterator is invalid. static TokenIterator leftOf(const QTextBlock& block, int positionInBlock) { TokenIterator it; it.blk = block; it.idx = -1; while (it.blk.isValid()) { it.data = static_cast<TextBlockData*>(it.blk.userData()); it.idx = it.data ? it.data->tokens.size() : 0; while (it.idx--) { Token const& token = it.data->tokens[it.idx]; if (positionInBlock < 0 || token.positionInBlock < positionInBlock) return it; } positionInBlock = -1; // match on first token in next block; it.blk = it.blk.previous(); } return it; } // Return an iterator for the first token found at or right of given position, anywhere in the document. // If there is no such token, the returned iterator is invalid. static TokenIterator rightOf(const QTextBlock& block, int positionInBlock) { TokenIterator it; it.blk = block; it.idx = -1; while (it.blk.isValid()) { it.data = static_cast<TextBlockData*>(it.blk.userData()); int n = it.data ? it.data->tokens.size() : 0; while (++it.idx < n) { Token const& token = it.data->tokens[it.idx]; if (token.positionInBlock >= positionInBlock) return it; } it.idx = -1; positionInBlock = -1; // match right on first token in next block; it.blk = it.blk.next(); } return it; } // Return an iterator for the token at 'pos' or 'pos-1'. // If there is no such token, the returned iterator is invalid. static TokenIterator around(const QTextBlock& block, int positionInBlock) { TokenIterator it; it.blk = block; it.idx = -1; if (!block.isValid()) return it; it.data = static_cast<TextBlockData*>(block.userData()); if (!it.data) return it; int n = it.data->tokens.size(); for (int i = 0; i < n; ++i) { Token const& token = it.data->tokens[i]; if (token.positionInBlock > positionInBlock) { return it; } else if (token.positionInBlock == positionInBlock - 1 || token.positionInBlock == positionInBlock) { it.idx = i; break; } } return it; } TokenIterator& operator++() { if (idx < 0) return *this; do { if (idx < 0) data = static_cast<TextBlockData*>(blk.userData()); if (data) { int n = data->tokens.size(); if (++idx < n) return *this; } idx = -1; blk = blk.next(); } while (blk.isValid()); return *this; } TokenIterator& operator--() { if (idx > 0) { --idx; return *this; } else if (idx < 0) { return *this; } idx = -1; while ((blk = blk.previous()).isValid()) { data = static_cast<TextBlockData*>(blk.userData()); if (data) idx = data->tokens.size() - 1; if (idx < 0) continue; // we have a valid idx break; } return *this; } TokenIterator previous() const { TokenIterator it(*this); --it; return it; } TokenIterator next() const { TokenIterator it(*this); ++it; return it; } char character() const { return (*this)->character; } // A convenience function returning the global position in document of the token // referred to by this iterator int position() const { return (*this)->positionInBlock + blk.position(); } // A convenience function returning the type of token referred to by this iterator, // or Token::Unknown if the iterator is invalid Token::Type type() const { return isValid() ? (*this)->type : Token::Unknown; } }; } // namespace ScIDE
8,553
C++
.h
232
27.866379
114
0.587551
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,268
general_page.hpp
supercollider_supercollider/editors/sc-ide/widgets/settings/general_page.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> namespace Ui { class GeneralConfigPage; } namespace ScIDE { namespace Settings { class Manager; class GeneralPage : public QWidget { Q_OBJECT public: GeneralPage(QWidget* parent = 0); ~GeneralPage(); public slots: void load(Manager*); void store(Manager*); private slots: void onStartSessionNameChanged(const QString& text); private: Ui::GeneralConfigPage* ui; }; }} // namespace ScIDE::Settings
1,304
C++
.h
37
31.594595
81
0.753392
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,269
shortcuts_page.hpp
supercollider_supercollider/editors/sc-ide/widgets/settings/shortcuts_page.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> #include <QStandardItemModel> #include <QSortFilterProxyModel> class QTreeWidgetItem; namespace Ui { class ShortcutConfigPage; } namespace ScIDE { namespace Settings { class Manager; class ShortcutsPage : public QWidget { Q_OBJECT public: ShortcutsPage(QWidget* parent = 0); ~ShortcutsPage(); public Q_SLOTS: void load(Manager*); void store(Manager*); void filterBy(const QString&); private Q_SLOTS: void showItem(QTreeWidgetItem*, QTreeWidgetItem*); void apply(); private: enum ItemDataRole { ActionRole = Qt::UserRole, SettingsKeyRole, DefaultSequenceRole, CustomSequenceRole, EditedRole }; void addAction(QAction*, Manager*); void applyTo(QTreeWidgetItem*); void updateItem(QTreeWidgetItem*); QKeySequence activeItemSequence(QTreeWidgetItem*); bool confirmOverride(const QKeySequence& duplicateSequence, QTreeWidgetItem* duplicateItem); Ui::ShortcutConfigPage* ui; QStandardItemModel* mActionModel; QSortFilterProxyModel* mFilter; }; }} // namespace ScIDE::Settings
1,964
C++
.h
56
30.767857
96
0.751454
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,270
sclang_page.hpp
supercollider_supercollider/editors/sc-ide/widgets/settings/sclang_page.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> namespace Ui { class SclangConfigPage; } namespace ScIDE { namespace Settings { class Manager; class SclangPage : public QWidget { Q_OBJECT public: SclangPage(QWidget* parent = 0); ~SclangPage(); public Q_SLOTS: void load(Manager*); void store(Manager*); private Q_SLOTS: void addIncludePath(); void removeIncludePath(); void addExcludePath(); void removeExcludePath(); void markSclangConfigDirty() { sclangConfigDirty = true; } void changeSelectedLanguageConfig(const QString& configPath); void dialogCreateNewConfigFile(); void dialogDeleteCurrentConfigFile(); private: void readLanguageConfig(); void writeLanguageConfig(); QString languageConfigFile(); QStringList availableLanguageConfigFiles(); Ui::SclangConfigPage* ui; bool sclangConfigDirty; QString selectedLanguageConfigFile; }; }} // namespace ScIDE::Settings
1,785
C++
.h
50
31.64
81
0.756112
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,271
dialog.hpp
supercollider_supercollider/editors/sc-ide/widgets/settings/dialog.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QDialog> namespace Ui { class ConfigDialog; } namespace ScIDE { namespace Settings { class Manager; class Dialog : public QDialog { Q_OBJECT public: Dialog(Manager* settings, QWidget* parent = 0); ~Dialog(); public Q_SLOTS: virtual void accept(); virtual void reject(); virtual void reset(); void apply(); Q_SIGNALS: void storeRequest(Manager*); void loadRequest(Manager*); private: Manager* mManager; Ui::ConfigDialog* ui; }; }} // namespace ScIDE::Settings
1,375
C++
.h
41
29.731707
81
0.738438
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,272
editor_page.hpp
supercollider_supercollider/editors/sc-ide/widgets/settings/editor_page.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QTextCharFormat> #include "../../core/settings/theme.hpp" class QFontDatabase; namespace Ui { class EditorConfigPage; } namespace ScIDE { namespace Settings { class Manager; class EditorPage : public QWidget { Q_OBJECT public: EditorPage(QWidget* parent = 0); ~EditorPage(); public Q_SLOTS: void load(Manager*); void store(Manager*); private Q_SLOTS: void onCurrentTabChanged(int); void onMonospaceToggle(bool); void updateFontPreview(); void updateTextFormatEdit(); void updateTextFormatDisplay(); void updateTextFormatDisplayCommons(); void updateTheme(QString name); void dialogCopyTheme(); void deleteTheme(); private: enum TextFormatListRole { TextFormatConfigKeyRole = Qt::UserRole, TextFormatRole, DefaultTextFormatRole }; void loadThemeFormats(Theme& theme); void populateFontList(bool onlyMonospaced = false); void populateThemeList(const QString& sel = ""); QFont constructFont(); QTextCharFormat constructTextFormat(); QTreeWidgetItem* addTextFormat(const QString& name, const QString& key, const QTextCharFormat& format, const QTextCharFormat& defaultFormat = QTextCharFormat()); void updateTextFormatDisplay(QTreeWidgetItem*); QFontDatabase* fontDatabase; Ui::EditorConfigPage* ui; QStringList mFormatKeys; QTreeWidgetItem* mCommonTextFormatItem; QMap<QString, Theme*> mThemes; }; }} // namespace ScIDE::Settings
2,422
C++
.h
63
33.857143
110
0.751286
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,273
style.hpp
supercollider_supercollider/editors/sc-ide/widgets/style/style.hpp
/* SuperCollider Qt IDE Copyright (c) 2010-2012 Jakob Leben Copyright (c) 2012 Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QProxyStyle> namespace ScIDE { class Style : public QProxyStyle { public: Style(QStyle* style = 0): QProxyStyle(style) {} virtual void polish(QWidget* widget); virtual void unpolish(QWidget* widget); virtual void drawPrimitive(PrimitiveElement, const QStyleOption*, QPainter*, const QWidget* = 0) const; virtual void drawControl(ControlElement, const QStyleOption*, QPainter*, const QWidget* = 0) const; virtual void drawComplexControl(ComplexControl, const QStyleOptionComplex*, QPainter*, const QWidget* = 0) const; virtual QRect subElementRect(SubElement, const QStyleOption*, const QWidget* = 0) const; virtual QSize sizeFromContents(ContentsType, const QStyleOption*, const QSize&, const QWidget* = 0) const; virtual int pixelMetric(PixelMetric, const QStyleOption* = 0, const QWidget* = 0) const; virtual int styleHint(StyleHint, const QStyleOption* = 0, const QWidget* = 0, QStyleHintReturn* = 0) const; private: bool shouldNotHandle(const QWidget* widget) const; static constexpr float kDeselectedTabBlend = 0.3f; }; } // namespace ScIDE
1,995
C++
.h
37
49.513514
117
0.757732
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,274
SCDoc.h
supercollider_supercollider/SCDoc/SCDoc.h
#pragma once #include <stdint.h> #include <string.h> #include <string> #define SCDOC_PARSE_FULL 0 #define SCDOC_PARSE_PARTIAL 1 #define SCDOC_PARSE_METADATA 2 extern const char* NODE_TEXT; extern const char* NODE_NL; typedef struct DocNode { const char* id; char* text; int n_childs; struct DocNode** children; } DocNode; char* strmerge(char* a, char* b); DocNode* doc_node_make_take_children(const char* id, char* text, DocNode* src); DocNode* doc_node_make(const char* id, char* text, DocNode* child); DocNode* doc_node_add_child(DocNode* n, DocNode* child); DocNode* doc_node_create(const char* id); void doc_node_free_tree(DocNode* n); /** * \brief Parses a .schelp file and generates a help file parse tree * * \arg fn A UTF-8 string, the filename to be parsed * \arg mode The mode to parse, should be one of SCDOC_PARSE_FULL, PARTIAL, or METADATA * \returns A parse tree pointer, or nullptr if the file count not be opened or parsed. */ DocNode* scdoc_parse_file(const std::string& fn, int mode); /// Dumps a DocNode to stdout as a human-readable tree. void doc_node_dump(DocNode* n); extern const char* scdoc_current_file;
1,161
C++
.h
32
34.3125
87
0.741964
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,275
SCDoc.tab.hpp
supercollider_supercollider/SCDoc/SCDoc.tab.hpp
/* A Bison parser, made by GNU Bison 3.8.2. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2021 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, especially those whose name start with YY_ or yy_. They are private implementation details that can be changed or removed. */ #ifndef YY_SCDOC_SCDOC_TAB_HPP_INCLUDED # define YY_SCDOC_SCDOC_TAB_HPP_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int scdocdebug; #endif /* Token kinds. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { YYEMPTY = -2, END = 0, /* "end of file" */ YYerror = 256, /* error */ YYUNDEF = 257, /* "invalid token" */ CLASS = 258, /* CLASS */ TITLE = 259, /* TITLE */ SUMMARY = 260, /* SUMMARY */ RELATED = 261, /* RELATED */ CATEGORIES = 262, /* CATEGORIES */ REDIRECT = 263, /* REDIRECT */ CLASSTREE = 264, /* CLASSTREE */ COPYMETHOD = 265, /* COPYMETHOD */ KEYWORD = 266, /* KEYWORD */ PRIVATE = 267, /* PRIVATE */ SECTION = 268, /* SECTION */ SUBSECTION = 269, /* SUBSECTION */ SUBSUBSECTION = 270, /* SUBSUBSECTION */ METHOD = 271, /* METHOD */ ARGUMENT = 272, /* ARGUMENT */ DESCRIPTION = 273, /* DESCRIPTION */ CLASSMETHODS = 274, /* CLASSMETHODS */ INSTANCEMETHODS = 275, /* INSTANCEMETHODS */ EXAMPLES = 276, /* EXAMPLES */ RETURNS = 277, /* RETURNS */ DISCUSSION = 278, /* DISCUSSION */ LIST = 279, /* LIST */ TREE = 280, /* TREE */ NUMBEREDLIST = 281, /* NUMBEREDLIST */ DEFINITIONLIST = 282, /* DEFINITIONLIST */ TABLE = 283, /* TABLE */ FOOTNOTE = 284, /* FOOTNOTE */ NOTE = 285, /* NOTE */ WARNING = 286, /* WARNING */ CODE = 287, /* CODE */ LINK = 288, /* LINK */ ANCHOR = 289, /* ANCHOR */ SOFT = 290, /* SOFT */ IMAGE = 291, /* IMAGE */ TELETYPE = 292, /* TELETYPE */ MATH = 293, /* MATH */ STRONG = 294, /* STRONG */ EMPHASIS = 295, /* EMPHASIS */ CODEBLOCK = 296, /* "CODE block" */ TELETYPEBLOCK = 297, /* "TELETYPE block" */ MATHBLOCK = 298, /* "MATH block" */ TAGSYM = 299, /* "::" */ BARS = 300, /* "||" */ HASHES = 301, /* "##" */ TEXT = 302, /* "text" */ URL = 303, /* URL */ COMMA = 304, /* COMMA */ METHODNAME = 305, /* "method name" */ METHODARGS = 306, /* "arguments string" */ NEWLINE = 307, /* "newline" */ EMPTYLINES = 308, /* "empty lines" */ BAD_METHODNAME = 309, /* "bad method name" */ START_FULL = 310, /* START_FULL */ START_PARTIAL = 311, /* START_PARTIAL */ START_METADATA = 312 /* START_METADATA */ }; typedef enum yytokentype yytoken_kind_t; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED union YYSTYPE { #line 55 "SCDoc.y" intptr_t i; const char *id; char *str; DocNode *doc_node; #line 128 "SCDoc.tab.hpp" }; typedef union YYSTYPE YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE YYLTYPE; struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif extern YYSTYPE scdoclval; extern YYLTYPE scdoclloc; int scdocparse (void); #endif /* !YY_SCDOC_SCDOC_TAB_HPP_INCLUDED */
5,777
C++
.h
136
38.830882
80
0.552571
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,276
getopt.h
supercollider_supercollider/platform/windows/compat_stuff/getopt/getopt.h
/* Declarations for getopt. Copyright (C) 1989-1994, 1996-1999, 2001 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _GETOPT_H #ifndef __need_getopt # define _GETOPT_H 1 #endif /* If __GNU_LIBRARY__ is not already defined, either we are being used standalone, or this is the first header included in the source file. If we are being used with glibc, we need to include <features.h>, but that does not exist if we are standalone. So: if __GNU_LIBRARY__ is not defined, include <ctype.h>, which will pull in <features.h> for us if it's from glibc. (Why ctype.h? It's guaranteed to exist and it doesn't flood the namespace with stuff the way some other headers do.) */ #if !defined __GNU_LIBRARY__ # include <ctype.h> #endif #ifdef __cplusplus extern "C" { #endif /* For communication from `getopt' to the caller. When `getopt' finds an option that takes an argument, the argument value is returned here. Also, when `ordering' is RETURN_IN_ORDER, each non-option ARGV-element is returned here. */ extern char* optarg; /* Index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to `getopt'. On entry to `getopt', zero means this is the first call; initialize. When `getopt' returns -1, this is the index of the first of the non-option elements that the caller should itself scan. Otherwise, `optind' communicates from one call to the next how much of ARGV has been scanned so far. */ extern int optind; /* Callers store zero here to inhibit the error message `getopt' prints for unrecognized options. */ extern int opterr; /* Set to an option character which was unrecognized. */ extern int optopt; #ifndef __need_getopt /* Describe the long-named options requested by the application. The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector of `struct option' terminated by an element containing a name which is zero. The field `has_arg' is: no_argument (or 0) if the option does not take an argument, required_argument (or 1) if the option requires an argument, optional_argument (or 2) if the option takes an optional argument. If the field `flag' is not NULL, it points to a variable that is set to the value given in the field `val' when the option is found, but left unchanged if the option is not found. To have a long-named option do something other than set an `int' to a compiled-in constant, such as set a value from `optarg', set the option's `flag' field to zero and its `val' field to a nonzero value (the equivalent single-letter option character, if there is one). For long options that have a zero `flag' field, `getopt' returns the contents of the `val' field. */ struct option { # if (defined __STDC__ && __STDC__) || defined __cplusplus const char* name; # else char* name; # endif /* has_arg can't be an enum because some compilers complain about type mismatches in all the code that assumes it is an int. */ int has_arg; int* flag; int val; }; /* Names for the values of the `has_arg' field of `struct option'. */ # define no_argument 0 # define required_argument 1 # define optional_argument 2 #endif /* need getopt */ /* Get definitions and prototypes for functions to process the arguments in ARGV (ARGC of them, minus the program name) for options given in OPTS. Return the option character from OPTS just read. Return -1 when there are no more options. For unrecognized options, or options missing arguments, `optopt' is set to the option letter, and '?' is returned. The OPTS string is a list of characters which are recognized option letters, optionally followed by colons, specifying that that letter takes an argument, to be placed in `optarg'. If a letter in OPTS is followed by two colons, its argument is optional. This behavior is specific to the GNU `getopt'. The argument `--' causes premature termination of argument scanning, explicitly telling `getopt' that there are no more options. If OPTS begins with `--', then non-option arguments are treated as arguments to the option '\0'. This behavior is specific to the GNU `getopt'. */ #if (defined __STDC__ && __STDC__) || defined __cplusplus # ifdef __GNU_LIBRARY__ /* Many other libraries have conflicting prototypes for getopt, with differences in the consts, in stdlib.h. To avoid compilation errors, only prototype getopt for the GNU C library. */ extern int getopt(int ___argc, char* const* ___argv, const char* __shortopts); # else /* not __GNU_LIBRARY__ */ extern int getopt(); # endif /* __GNU_LIBRARY__ */ # ifndef __need_getopt extern int getopt_long(int ___argc, char* const* ___argv, const char* __shortopts, const struct option* __longopts, int* __longind); extern int getopt_long_only(int ___argc, char* const* ___argv, const char* __shortopts, const struct option* __longopts, int* __longind); /* Internal only. Users should not call this directly. */ extern int _getopt_internal(int ___argc, char* const* ___argv, const char* __shortopts, const struct option* __longopts, int* __longind, int __long_only); # endif #else /* not __STDC__ */ extern int getopt(); # ifndef __need_getopt extern int getopt_long(); extern int getopt_long_only(); extern int _getopt_internal(); # endif #endif /* __STDC__ */ #ifdef __cplusplus } #endif /* Make sure we later can get all the definitions and declarations. */ #undef __need_getopt #endif /* getopt.h */
6,524
C++
.h
137
44.065693
120
0.716131
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
34,302
multiple_exceptions.ipp
supercollider_supercollider/external_libraries/boost/boost/asio/impl/multiple_exceptions.ipp
// // impl/multiple_exceptions.ipp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #ifndef BOOST_ASIO_IMPL_MULTIPLE_EXCEPTIONS_IPP #define BOOST_ASIO_IMPL_MULTIPLE_EXCEPTIONS_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/multiple_exceptions.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { multiple_exceptions::multiple_exceptions( std::exception_ptr first) noexcept : first_(static_cast<std::exception_ptr&&>(first)) { } const char* multiple_exceptions::what() const noexcept { return "multiple exceptions"; } std::exception_ptr multiple_exceptions::first_exception() const { return first_; } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_IMPL_MULTIPLE_EXCEPTIONS_IPP
1,140
C++
.ipp
36
30.083333
79
0.734675
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,381
TimeControl.cpp
leela-zero_leela-zero/src/TimeControl.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include <algorithm> #include <cassert> #include <cstdlib> #include <memory> #include <regex> #include <sstream> #include "TimeControl.h" #include "GTP.h" #include "Timing.h" #include "Utils.h" using namespace Utils; TimeControl::TimeControl(const int maintime, const int byotime, const int byostones, const int byoperiods) : m_maintime(maintime), m_byotime(byotime), m_byostones(byostones), m_byoperiods(byoperiods) { reset_clocks(); } std::string TimeControl::stones_left_to_text_sgf(const int color) const { auto s = std::string{}; // We must be in byo-yomi before interpreting stones. if (m_inbyo[color]) { const auto c = color == FastBoard::BLACK ? "OB[" : "OW["; if (m_byostones) { s += c + std::to_string(m_stones_left[color]) + "]"; } else if (m_byoperiods) { // KGS extension. s += c + std::to_string(m_periods_left[color]) + "]"; } } return s; } std::string TimeControl::to_text_sgf() const { if (m_byotime != 0 && m_byostones == 0 && m_byoperiods == 0) { return ""; // Infinite time. } auto s = "TM[" + std::to_string(m_maintime / 100) + "]"; if (m_byotime) { if (m_byostones) { s += "OT[" + std::to_string(m_byostones) + "/"; s += std::to_string(m_byotime / 100) + " Canadian]"; } else { assert(m_byoperiods); s += "OT[" + std::to_string(m_byoperiods) + "x"; s += std::to_string(m_byotime / 100) + " byo-yomi]"; } s += stones_left_to_text_sgf(FastBoard::BLACK); s += stones_left_to_text_sgf(FastBoard::WHITE); } // Generously round up to avoid a remaining time of 0 triggering byo-yomi // to be started when the sgf is loaded. This happens because byo-yomi // stones have to be only written to the sgf when actually in byo-yomi // and this is interpreted in adjust_time() as a special case // that starts byo-yomi. const auto black_time_left = (m_remaining_time[FastBoard::BLACK] + 99) / 100; const auto white_time_left = (m_remaining_time[FastBoard::WHITE] + 99) / 100; s += "BL[" + std::to_string(black_time_left) + "]"; s += "WL[" + std::to_string(white_time_left) + "]"; return s; } std::shared_ptr<TimeControl> TimeControl::make_from_text_sgf( const std::string& maintime, const std::string& byoyomi, const std::string& black_time_left, const std::string& white_time_left, const std::string& black_moves_left, const std::string& white_moves_left) { const auto maintime_centis = std::stoi(maintime) * 100; auto byotime = 0; auto byostones = 0; auto byoperiods = 0; if (!byoyomi.empty()) { std::smatch m; const auto re_canadian = std::regex{"(\\d+)/(\\d+) Canadian"}; const auto re_byoyomi = std::regex{"(\\d+)x(\\d+) byo-yomi"}; if (std::regex_match(byoyomi, m, re_canadian)) { byostones = std::stoi(m[1]); byotime = std::stoi(m[2]) * 100; } else if (std::regex_match(byoyomi, m, re_byoyomi)) { byoperiods = std::stoi(m[1]); byotime = std::stoi(m[2]) * 100; } else { // Unrecognised byo-yomi syntax. } } const auto timecontrol_ptr = std::make_shared<TimeControl>( maintime_centis, byotime, byostones, byoperiods); if (!black_time_left.empty()) { const auto time = std::stoi(black_time_left) * 100; const auto stones = black_moves_left.empty() ? 0 : std::stoi(black_moves_left); timecontrol_ptr->adjust_time(FastBoard::BLACK, time, stones); } if (!white_time_left.empty()) { const auto time = std::stoi(white_time_left) * 100; const auto stones = white_moves_left.empty() ? 0 : std::stoi(white_moves_left); timecontrol_ptr->adjust_time(FastBoard::WHITE, time, stones); } return timecontrol_ptr; } void TimeControl::reset_clocks() { m_remaining_time = {m_maintime, m_maintime}; m_stones_left = {m_byostones, m_byostones}; m_periods_left = {m_byoperiods, m_byoperiods}; m_inbyo = {m_maintime <= 0, m_maintime <= 0}; // Now that byo-yomi status is set, add time // back to our clocks if (m_inbyo[0]) { m_remaining_time[0] = m_byotime; } if (m_inbyo[1]) { m_remaining_time[1] = m_byotime; } } void TimeControl::start(const int color) { m_times[color] = Time(); } void TimeControl::stop(const int color) { Time stop; int elapsed_centis = Time::timediff_centis(m_times[color], stop); assert(elapsed_centis >= 0); m_remaining_time[color] -= elapsed_centis; if (m_inbyo[color]) { if (m_byostones) { m_stones_left[color]--; } else if (m_byoperiods) { if (elapsed_centis > m_byotime) { m_periods_left[color]--; } } } /* time up, entering byo yomi */ if (!m_inbyo[color] && m_remaining_time[color] <= 0) { m_remaining_time[color] = m_byotime; m_stones_left[color] = m_byostones; m_periods_left[color] = m_byoperiods; m_inbyo[color] = true; } else if (m_inbyo[color] && m_byostones && m_stones_left[color] <= 0) { // reset byoyomi time and stones m_remaining_time[color] = m_byotime; m_stones_left[color] = m_byostones; } else if (m_inbyo[color] && m_byoperiods) { m_remaining_time[color] = m_byotime; } } void TimeControl::display_color_time(const int color) { auto rem = m_remaining_time[color] / 100; /* centiseconds to seconds */ auto minuteDiv = std::div(rem, 60); auto hourDiv = std::div(minuteDiv.quot, 60); auto seconds = minuteDiv.rem; auto minutes = hourDiv.rem; auto hours = hourDiv.quot; auto name = color == 0 ? "Black" : "White"; myprintf("%s time: %02d:%02d:%02d", name, hours, minutes, seconds); if (m_inbyo[color]) { if (m_byostones) { myprintf(", %d stones left", m_stones_left[color]); } else if (m_byoperiods) { myprintf(", %d period(s) of %d seconds left", m_periods_left[color], m_byotime / 100); } } myprintf("\n"); } void TimeControl::display_times() { display_color_time(FastBoard::BLACK); display_color_time(FastBoard::WHITE); myprintf("\n"); } int TimeControl::max_time_for_move(const int boardsize, const int color, const size_t movenum) const { // default: no byo yomi (absolute) auto time_remaining = m_remaining_time[color]; auto moves_remaining = get_moves_expected(boardsize, movenum); auto extra_time_per_move = 0; if (m_byotime != 0) { /* no periods or stones set means infinite time = 1 month */ if (m_byostones == 0 && m_byoperiods == 0) { return 31 * 24 * 60 * 60 * 100; } // byo yomi and in byo yomi if (m_inbyo[color]) { if (m_byostones) { moves_remaining = m_stones_left[color]; } else { assert(m_byoperiods); // Just use the byo yomi period time_remaining = 0; extra_time_per_move = m_byotime; } } else { /* byo yomi time but not in byo yomi yet */ if (m_byostones) { int byo_extra = m_byotime / m_byostones; time_remaining = m_remaining_time[color] + byo_extra; // Add back the guaranteed extra seconds extra_time_per_move = byo_extra; } else { assert(m_byoperiods); int byo_extra = m_byotime * (m_periods_left[color] - 1); time_remaining = m_remaining_time[color] + byo_extra; // Add back the guaranteed extra seconds extra_time_per_move = m_byotime; } } } // always keep a cfg_lagbugger_cs centisecond margin // for network hiccups or GUI lag auto base_time = std::max(time_remaining - cfg_lagbuffer_cs, 0) / std::max(moves_remaining, 1); auto inc_time = std::max(extra_time_per_move - cfg_lagbuffer_cs, 0); return base_time + inc_time; } void TimeControl::adjust_time(const int color, const int time, const int stones) { m_remaining_time[color] = time; // From pachi: some GTP things send 0 0 at the end of main time if (!time && !stones) { m_inbyo[color] = true; m_remaining_time[color] = m_byotime; m_stones_left[color] = m_byostones; m_periods_left[color] = m_byoperiods; } if (stones) { // stones are only given in byo-yomi m_inbyo[color] = true; } // we must be in byo-yomi before interpreting stones // the previous condition guarantees we do this if != 0 if (m_inbyo[color]) { if (m_byostones) { m_stones_left[color] = stones; } else if (m_byoperiods) { // KGS extension m_periods_left[color] = stones; } } } size_t TimeControl::opening_moves(const int boardsize) const { auto num_intersections = boardsize * boardsize; auto fast_moves = num_intersections / 6; return fast_moves; } int TimeControl::get_moves_expected(const int boardsize, const size_t movenum) const { auto board_div = 5; if (cfg_timemanage != TimeManagement::OFF) { // We will take early exits with time management on, so // it's OK to make our base time bigger. board_div = 9; } // Note this is constant as we play, so it's fair // to underestimate quite a bit. auto base_remaining = (boardsize * boardsize) / board_div; // Don't think too long in the opening. auto fast_moves = opening_moves(boardsize); if (movenum < fast_moves) { return (base_remaining + fast_moves) - movenum; } else { return base_remaining; } } // Returns true if we are in a time control where we // can save up time. If not, we should not move quickly // even if certain of our move, but plough ahead. bool TimeControl::can_accumulate_time(const int color) const { if (m_inbyo[color]) { // Cannot accumulate in Japanese byo yomi if (m_byoperiods) { return false; } // Cannot accumulate in Canadese style with // one move remaining in the period if (m_byostones && m_stones_left[color] == 1) { return false; } } else { // If there is a base time, we should expect // to be able to accumulate. This may be somewhat // of an illusion if the base time is tiny and byo // yomi time is big. } return true; }
12,257
C++
.cpp
315
31.409524
79
0.603057
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,386
SGFTree.cpp
leela-zero_leela-zero/src/SGFTree.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <cassert> #include <ctime> #include <memory> #include <sstream> #include <stdexcept> #include <type_traits> #include <utility> #include "SGFTree.h" #include "FullBoard.h" #include "GTP.h" #include "KoState.h" #include "SGFParser.h" #include "Utils.h" using namespace Utils; const int SGFTree::EOT; void SGFTree::init_state() { m_initialized = true; // Initialize with defaults. // The SGF might be missing boardsize or komi // which means we'll never initialize properly. m_state.init_game(std::min(BOARD_SIZE, 19), KOMI); } const KoState* SGFTree::get_state() const { assert(m_initialized); return &m_state; } const SGFTree* SGFTree::get_child(const size_t count) const { if (count < m_children.size()) { assert(m_initialized); return &(m_children[count]); } else { return nullptr; } } // This follows the entire line, and doesn't really need the intermediate // states, just the moves. As a consequence, states that contain more than // just moves won't have any effect. GameState SGFTree::follow_mainline_state(const unsigned int movenum) const { const auto* link = this; // This initializes a starting state from a KoState and // sets up the game history. GameState result(get_state()); if (m_timecontrol_ptr) { result.set_timecontrol(*m_timecontrol_ptr); } for (unsigned int i = 0; i <= movenum && link != nullptr; i++) { // root position has no associated move if (i != 0) { auto colored_move = link->get_colored_move(); if (colored_move.first != FastBoard::INVAL) { if (colored_move.second != FastBoard::PASS && colored_move.second != FastBoard::EMPTY && result.board.get_state(colored_move.second) != FastBoard::EMPTY) { // Fail loading return result; } result.play_move(colored_move.first, colored_move.second); } } link = link->get_child(0); } return result; } void SGFTree::load_from_string(const std::string& gamebuff) { std::istringstream pstream(gamebuff); // loads properties with moves SGFParser::parse(pstream, this); // Set up the root state to defaults init_state(); // populates the states from the moves // split this up in root node, achor (handicap), other nodes populate_states(); } // load a single game from a file void SGFTree::load_from_file(const std::string& filename, const int index) { auto gamebuff = SGFParser::chop_from_file(filename, index); // myprintf("Parsing: %s\n", gamebuff.c_str()); load_from_string(gamebuff); } void SGFTree::populate_states() { PropertyMap::iterator it; auto valid_size = false; auto has_handicap = false; // first check for go game setup in properties it = m_properties.find("GM"); if (it != end(m_properties)) { if (it->second != "1") { throw std::runtime_error("SGF Game is not a Go game"); } else { if (!m_properties.count("SZ")) { // No size, but SGF spec defines default size for Go m_properties.insert(std::make_pair("SZ", "19")); valid_size = true; } } } // board size it = m_properties.find("SZ"); if (it != end(m_properties)) { const auto size = it->second; std::istringstream strm(size); int bsize; strm >> bsize; if (bsize == BOARD_SIZE) { // Assume default komi in config.h if not specified m_state.init_game(bsize, KOMI); valid_size = true; } else { throw std::runtime_error("Board size not supported."); } } // komi it = m_properties.find("KM"); if (it != end(m_properties)) { const auto foo = it->second; std::istringstream strm(foo); float komi; strm >> komi; const auto handicap = m_state.get_handicap(); // last ditch effort: if no GM or SZ, assume 19x19 Go here auto bsize = 19; if (valid_size) { bsize = m_state.board.get_boardsize(); } if (bsize == BOARD_SIZE) { m_state.init_game(bsize, komi); m_state.set_handicap(handicap); } else { throw std::runtime_error("Board size not supported."); } } // time it = m_properties.find("TM"); if (it != end(m_properties)) { const auto maintime = it->second; it = m_properties.find("OT"); const auto byoyomi = (it != end(m_properties)) ? it->second : ""; it = m_properties.find("BL"); const auto black_time_left = (it != end(m_properties)) ? it->second : ""; it = m_properties.find("WL"); const auto white_time_left = (it != end(m_properties)) ? it->second : ""; it = m_properties.find("OB"); const auto black_moves_left = (it != end(m_properties)) ? it->second : ""; it = m_properties.find("OW"); const auto white_moves_left = (it != end(m_properties)) ? it->second : ""; m_timecontrol_ptr = TimeControl::make_from_text_sgf( maintime, byoyomi, black_time_left, white_time_left, black_moves_left, white_moves_left); } // handicap it = m_properties.find("HA"); if (it != end(m_properties)) { const auto size = it->second; std::istringstream strm(size); float handicap; strm >> handicap; has_handicap = (handicap > 0.0f); m_state.set_handicap(int(handicap)); } // result it = m_properties.find("RE"); if (it != end(m_properties)) { const auto result = it->second; if (boost::algorithm::find_first(result, "Time")) { // std::cerr << "Skipping: " << result << std::endl; m_winner = FastBoard::EMPTY; } else { if (boost::algorithm::starts_with(result, "W+")) { m_winner = FastBoard::WHITE; } else if (boost::algorithm::starts_with(result, "B+")) { m_winner = FastBoard::BLACK; } else { m_winner = FastBoard::INVAL; // std::cerr << "Could not parse game result: " << result << // std::endl; } } } else { m_winner = FastBoard::EMPTY; } // handicap stones auto prop_pair_ab = m_properties.equal_range("AB"); // Do we have a handicap specified but no handicap stones placed in // the same node? Then the SGF file is corrupt. Let's see if we can find // them in the next node, which is a common bug in some Go apps. if (has_handicap && prop_pair_ab.first == prop_pair_ab.second) { if (!m_children.empty()) { auto& successor = m_children[0]; prop_pair_ab = successor.m_properties.equal_range("AB"); } } // Loop through the stone list and apply for (auto pit = prop_pair_ab.first; pit != prop_pair_ab.second; ++pit) { const auto move = pit->second; const auto vtx = string_to_vertex(move); apply_move(FastBoard::BLACK, vtx); } // XXX: count handicap stones const auto& prop_pair_aw = m_properties.equal_range("AW"); for (auto pit = prop_pair_aw.first; pit != prop_pair_aw.second; ++pit) { const auto move = pit->second; const auto vtx = string_to_vertex(move); apply_move(FastBoard::WHITE, vtx); } it = m_properties.find("PL"); if (it != end(m_properties)) { const auto who = it->second; if (who == "W") { m_state.set_to_move(FastBoard::WHITE); } else if (who == "B") { m_state.set_to_move(FastBoard::BLACK); } } // now for all children play out the moves for (auto& child_state : m_children) { // propagate state child_state.copy_state(*this); // XXX: maybe move this to the recursive call // get move for side to move const auto colored_move = child_state.get_colored_move(); if (colored_move.first != FastBoard::INVAL) { child_state.apply_move(colored_move.first, colored_move.second); } child_state.populate_states(); } } void SGFTree::copy_state(const SGFTree& tree) { m_initialized = tree.m_initialized; m_state = tree.m_state; m_timecontrol_ptr = tree.m_timecontrol_ptr; } void SGFTree::apply_move(const int color, const int move) { if (move != FastBoard::PASS && move != FastBoard::RESIGN) { auto vtx_state = m_state.board.get_state(move); if (vtx_state == !color || vtx_state == FastBoard::INVAL) { throw std::runtime_error("Illegal move"); } // Playing on an occupied intersection is legal in SGF setup, // but we can't really handle it. So just ignore and hope that works. if (vtx_state == color) { return; } assert(vtx_state == FastBoard::EMPTY); } m_state.play_move(color, move); } void SGFTree::apply_move(const int move) { auto color = m_state.get_to_move(); apply_move(color, move); } void SGFTree::add_property(std::string property, std::string value) { m_properties.emplace(property, value); } SGFTree* SGFTree::add_child() { // first allocation is better small if (m_children.size() == 0) { m_children.reserve(1); } m_children.emplace_back(); return &(m_children.back()); } int SGFTree::string_to_vertex(const std::string& movestring) const { if (movestring.size() == 0) { return FastBoard::PASS; } if (m_state.board.get_boardsize() <= 19) { if (movestring == "tt") { return FastBoard::PASS; } } int bsize = m_state.board.get_boardsize(); if (bsize == 0) { throw std::runtime_error("Node has 0 sized board"); } char c1 = movestring[0]; char c2 = movestring[1]; int cc1; int cc2; if (c1 >= 'A' && c1 <= 'Z') { cc1 = 26 + c1 - 'A'; } else { cc1 = c1 - 'a'; } if (c2 >= 'A' && c2 <= 'Z') { cc2 = bsize - 26 - (c2 - 'A') - 1; } else { cc2 = bsize - (c2 - 'a') - 1; } // catch illegal SGF if (cc1 < 0 || cc1 >= bsize || cc2 < 0 || cc2 >= bsize) { throw std::runtime_error("Illegal SGF move"); } int vtx = m_state.board.get_vertex(cc1, cc2); return vtx; } int SGFTree::get_move(const int tomove) const { std::string colorstring; if (tomove == FastBoard::BLACK) { colorstring = "B"; } else { colorstring = "W"; } auto it = m_properties.find(colorstring); if (it != end(m_properties)) { std::string movestring = it->second; return string_to_vertex(movestring); } return SGFTree::EOT; } std::pair<int, int> SGFTree::get_colored_move() const { for (const auto& prop : m_properties) { if (prop.first == "B") { return std::make_pair(FastBoard::BLACK, string_to_vertex(prop.second)); } else if (prop.first == "W") { return std::make_pair(FastBoard::WHITE, string_to_vertex(prop.second)); } } return std::make_pair(FastBoard::INVAL, SGFTree::EOT); } FastBoard::vertex_t SGFTree::get_winner() const { return m_winner; } std::vector<int> SGFTree::get_mainline() const { std::vector<int> moves; const auto* link = this; auto tomove = link->m_state.get_to_move(); link = link->get_child(0); while (link != nullptr && link->is_initialized()) { auto move = link->get_move(tomove); if (move != SGFTree::EOT) { moves.push_back(move); } tomove = !tomove; link = link->get_child(0); } return moves; } std::string SGFTree::state_to_string(GameState& pstate, const int compcolor) { auto state = std::make_unique<GameState>(); // make a working copy *state = pstate; std::string header; std::string moves; auto komi = state->get_komi(); auto size = state->board.get_boardsize(); time_t now; time(&now); char timestr[sizeof "2017-10-16"]; strftime(timestr, sizeof timestr, "%F", localtime(&now)); header.append("(;GM[1]FF[4]RU[Chinese]"); header.append("DT[" + std::string(timestr) + "]"); header.append("SZ[" + std::to_string(size) + "]"); header.append("KM[" + str(boost::format("%.1f") % komi) + "]"); header.append(state->get_timecontrol().to_text_sgf()); auto leela_name = std::string{PROGRAM_NAME}; leela_name.append(" " + std::string(PROGRAM_VERSION)); if (!cfg_weightsfile.empty()) { auto pos = cfg_weightsfile.find_last_of("\\/"); if (std::string::npos == pos) { pos = 0; } else { ++pos; } leela_name.append(" " + cfg_weightsfile.substr(pos, 8)); } if (compcolor == FastBoard::WHITE) { header.append("PW[" + leela_name + "]"); header.append("PB[Human]"); } else { header.append("PB[" + leela_name + "]"); header.append("PW[Human]"); } state->rewind(); // check handicap here (anchor point) auto handicap = 0; std::string handicapstr; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { int vertex = state->board.get_vertex(i, j); int vtx_state = state->board.get_state(vertex); if (vtx_state == FastBoard::BLACK) { handicap++; handicapstr.append("[" + state->board.move_to_text_sgf(vertex) + "]"); } } } if (handicap > 0) { header.append("HA[" + std::to_string(handicap) + "]"); moves.append("AB" + handicapstr); } moves.append("\n"); int counter = 0; while (state->forward_move()) { int move = state->get_last_move(); assert(move != FastBoard::RESIGN); std::string movestr = state->board.move_to_text_sgf(move); if (state->board.black_to_move()) { moves.append(";W[" + movestr + "]"); } else { moves.append(";B[" + movestr + "]"); } if (++counter % 10 == 0) { moves.append("\n"); } } if (!state->has_resigned()) { float score = state->final_score(); if (score > 0.0f) { header.append("RE[B+" + str(boost::format("%.1f") % score) + "]"); } else if (score < 0.0f) { header.append("RE[W+" + str(boost::format("%.1f") % -score) + "]"); } else { header.append("RE[0]"); } } else { if (state->who_resigned() == FastBoard::WHITE) { header.append("RE[B+Resign]"); } else { header.append("RE[W+Resign]"); } } header.append("\nC[" + std::string{PROGRAM_NAME} + " options:" + cfg_options_str + "]"); std::string result(header); result.append("\n"); result.append(moves); result.append(")\n"); return result; }
16,706
C++
.cpp
463
28.650108
79
0.581028
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,388
CPUPipe.cpp
leela-zero_leela-zero/src/CPUPipe.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #ifdef __APPLE__ #include <Accelerate/Accelerate.h> #endif #ifdef USE_MKL #include <mkl.h> #endif #ifdef USE_OPENBLAS #include <cblas.h> #endif #ifndef USE_BLAS #include <Eigen/Dense> #endif #include "CPUPipe.h" #include "Im2Col.h" #include "Network.h" #ifndef USE_BLAS // Eigen helpers template <typename T> using EigenMatrixMap = Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>; template <typename T> using ConstEigenMatrixMap = Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>; #endif void CPUPipe::initialize(int channels) { m_input_channels = channels; } void CPUPipe::winograd_transform_in(const std::vector<float>& in, std::vector<float>& V, const int C) { constexpr auto W = BOARD_SIZE; constexpr auto H = BOARD_SIZE; constexpr auto WTILES = WINOGRAD_WTILES; constexpr auto P = WINOGRAD_P; constexpr auto Wpad = 2 + WINOGRAD_M * WTILES; constexpr auto buffersize = 32; std::array<std::array<float, Wpad>, Wpad> in_pad{{{0.0f}}}; std::array<float, buffersize * WINOGRAD_ALPHA * WINOGRAD_ALPHA> buffer; auto buffer_offset = 0; auto buffer_entries = 0; // multiple vector [i0..i5] by Bt and produce [o0..o5] // const auto Bt = std::array<float, WINOGRAD_TILE>{ // 1.0f, 0.0f, -5.0f / 2.0f, 0.0f, 1.0f, 0.0f, // 0.0f, -SQ2, -2.0f, SQ2 / 2.0f, 1.0f, 0.0f, // 0.0f, SQ2, -2.0f, -SQ2 / 2.0f, 1.0f, 0.0f, // 0.0f, -SQ2 / 2.0f, -1.0f / 2.0f, SQ2, 1.0f, 0.0f, // 0.0f, SQ2 / 2.0f, -1.0f / 2.0f, -SQ2, 1.0f, 0.0f, // 0.0f, 1.0f, 0.0f, -5.0f / 2.0f, 0.0f, 1.0f}; const auto multiply_bt = [](float& o0, float& o1, float& o2, float& o3, float& o4, float& o5, const float i0, const float i1, const float i2, const float i3, const float i4, const float i5) { auto i3m1 = i1 * -SQ2 + i3 * (SQ2 / 2.0f); auto i4m2 = i2 * -2.0f + i4 * 1.0f; o0 = i0 + i2 * (-5.0f / 2.0f) + i4; o1 = i3m1 + i4m2; o2 = -i3m1 + i4m2; auto i3m1_2 = i3 * (SQ2) + i1 * (-SQ2 / 2.0f); auto i4m2_2 = i2 * (-1.0f / 2.0f) + i4; o3 = i3m1_2 + i4m2_2; o4 = -i3m1_2 + i4m2_2; o5 = i1 + i3 * (-5.0f / 2.0f) + i5; }; for (auto ch = 0; ch < C; ch++) { for (auto yin = 0; yin < H; yin++) { for (auto xin = 0; xin < W; xin++) { in_pad[yin + 1][xin + 1] = in[ch * (W * H) + yin * W + xin]; } } for (auto block_y = 0; block_y < WTILES; block_y++) { // Tiles overlap by 2 const auto yin = WINOGRAD_M * block_y; for (auto block_x = 0; block_x < WTILES; block_x++) { const auto xin = WINOGRAD_M * block_x; #define DECL_T1(XX) \ float T1_##XX##_0, T1_##XX##_1, T1_##XX##_2, T1_##XX##_3, T1_##XX##_4, \ T1_##XX##_5; DECL_T1(0) DECL_T1(1) DECL_T1(2) DECL_T1(3) DECL_T1(4) DECL_T1(5) // Calculates transpose(B).x.B #define MULTIPLY_BT(XX) \ multiply_bt(T1_0_##XX, T1_1_##XX, T1_2_##XX, T1_3_##XX, T1_4_##XX, \ T1_5_##XX, \ in_pad[yin + 0][xin + XX], \ in_pad[yin + 1][xin + XX], \ in_pad[yin + 2][xin + XX], \ in_pad[yin + 3][xin + XX], \ in_pad[yin + 4][xin + XX], \ in_pad[yin + 5][xin + XX]); MULTIPLY_BT(0) MULTIPLY_BT(1) MULTIPLY_BT(2) MULTIPLY_BT(3) MULTIPLY_BT(4) MULTIPLY_BT(5) #define MULTIPLY_B(XX) \ multiply_bt( \ buffer[buffersize * (XX * WINOGRAD_ALPHA + 0) + buffer_entries], \ buffer[buffersize * (XX * WINOGRAD_ALPHA + 1) + buffer_entries], \ buffer[buffersize * (XX * WINOGRAD_ALPHA + 2) + buffer_entries], \ buffer[buffersize * (XX * WINOGRAD_ALPHA + 3) + buffer_entries], \ buffer[buffersize * (XX * WINOGRAD_ALPHA + 4) + buffer_entries], \ buffer[buffersize * (XX * WINOGRAD_ALPHA + 5) + buffer_entries], \ T1_##XX##_0, T1_##XX##_1, T1_##XX##_2, T1_##XX##_3, T1_##XX##_4, \ T1_##XX##_5); MULTIPLY_B(0) MULTIPLY_B(1) MULTIPLY_B(2) MULTIPLY_B(3) MULTIPLY_B(4) MULTIPLY_B(5) if (buffer_entries == 0) { buffer_offset = ch * P + block_y * WTILES + block_x; } buffer_entries++; if (buffer_entries >= buffersize || (ch == C - 1 && block_x == WTILES - 1 && block_y == WTILES - 1)) { for (auto i = 0; i < WINOGRAD_ALPHA * WINOGRAD_ALPHA; i++) { for (auto entry = 0; entry < buffer_entries; entry++) { V[i * C * P + buffer_offset + entry] = buffer[i * buffersize + entry]; } } buffer_entries = 0; } } } } } void CPUPipe::winograd_sgemm(const std::vector<float>& U, const std::vector<float>& V, std::vector<float>& M, const int C, const int K) { constexpr auto P = WINOGRAD_P; for (auto b = 0; b < WINOGRAD_TILE; b++) { const auto offset_u = b * K * C; const auto offset_v = b * C * P; const auto offset_m = b * K * P; #ifdef USE_BLAS cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, K, P, C, 1.0f, &U[offset_u], K, &V[offset_v], P, 0.0f, &M[offset_m], P); #else auto C_mat = EigenMatrixMap<float>(M.data() + offset_m, P, K); C_mat.noalias() = ConstEigenMatrixMap<float>(V.data() + offset_v, P, C) * ConstEigenMatrixMap<float>(U.data() + offset_u, K, C).transpose(); #endif } } void CPUPipe::winograd_transform_out(const std::vector<float>& M, std::vector<float>& Y, const int K) { constexpr auto W = BOARD_SIZE; constexpr auto H = BOARD_SIZE; constexpr auto WTILES = WINOGRAD_WTILES; constexpr auto P = WINOGRAD_P; // multiple vector [i0..i5] by At and produce [o0..o3] // const auto At = std::array<float, WINOGRAD_ALPHA * WINOGRAD_M>{ // 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // 0.0f, SQ2 / 2.0f, -SQ2 / 2.0f, SQ2, -SQ2, 0.0f, // 0.0f, 1.0f / 2.0f, 1.0f / 2.0f, 2.0f, 2.0f, 0.0f, // 0.0f, SQ2 / 4.0f, -SQ2 / 4.0f, 2.0f * SQ2, -2.0f * SQ2, 1.0f}; const auto multiply_at = [](float& o0, float& o1, float& o2, float& o3, const float i0, const float i1, const float i2, const float i3, const float i4, const float i5) { auto t1p2 = (i1 + i2) * (1.0f / 2.0f); auto t1m2 = (i1 - i2) * (SQ2 / 4.0f); auto t3p4 = i3 + i4; auto t3m4 = (i3 - i4) * (SQ2); o0 = i0 + t1p2 + t1p2 + t3p4; o1 = t1m2 + t1m2 + t3m4; o2 = t1p2 + t3p4 + t3p4; o3 = t1m2 + t3m4 + t3m4 + i5; }; for (auto k = 0; k < K; k++) { for (auto block_x = 0; block_x < WTILES; block_x++) { const auto x = WINOGRAD_M * block_x; for (auto block_y = 0; block_y < WTILES; block_y++) { const auto y = WINOGRAD_M * block_y; const auto b = block_y * WTILES + block_x; using WinogradTile = std::array<std::array<float, WINOGRAD_ALPHA>, WINOGRAD_ALPHA>; WinogradTile temp_m; for (auto xi = 0; xi < WINOGRAD_ALPHA; xi++) { for (auto nu = 0; nu < WINOGRAD_ALPHA; nu++) { temp_m[xi][nu] = M[(xi * WINOGRAD_ALPHA + nu) * K * P + k * P + b]; } } std::array<std::array<float, WINOGRAD_ALPHA>, WINOGRAD_M> temp; std::array<std::array<float, WINOGRAD_M>, WINOGRAD_M> o; // Calculates transpose(A).temp_m.A for (auto j = 0; j < WINOGRAD_ALPHA; j++) { multiply_at(temp[0][j], temp[1][j], temp[2][j], temp[3][j], temp_m[0][j], temp_m[1][j], temp_m[2][j], temp_m[3][j], temp_m[4][j], temp_m[5][j]); } for (auto i = 0; i < WINOGRAD_M; i++) { multiply_at(o[i][0], o[i][1], o[i][2], o[i][3], temp[i][0], temp[i][1], temp[i][2], temp[i][3], temp[i][4], temp[i][5]); } const auto y_ind = k * H * W + y * W + x; for (auto i = 0; i < WINOGRAD_M; i++) { for (auto j = 0; j < WINOGRAD_M; j++) { if (y + i < H && x + j < W) { Y[y_ind + i * W + j] = o[i][j]; } } } } } } } void CPUPipe::winograd_convolve3(const int outputs, const std::vector<float>& input, const std::vector<float>& U, std::vector<float>& V, std::vector<float>& M, std::vector<float>& output) { constexpr unsigned int filter_len = WINOGRAD_ALPHA * WINOGRAD_ALPHA; const auto input_channels = U.size() / (outputs * filter_len); winograd_transform_in(input, V, input_channels); winograd_sgemm(U, V, M, input_channels, outputs); winograd_transform_out(M, output, outputs); } template <unsigned int filter_size> void convolve(const size_t outputs, const std::vector<float>& input, const std::vector<float>& weights, const std::vector<float>& biases, std::vector<float>& output) { // The size of the board is defined at compile time constexpr unsigned int width = BOARD_SIZE; constexpr unsigned int height = BOARD_SIZE; constexpr auto num_intersections = width * height; constexpr auto filter_len = filter_size * filter_size; const auto input_channels = weights.size() / (biases.size() * filter_len); const auto filter_dim = filter_len * input_channels; assert(outputs * num_intersections == output.size()); std::vector<float> col(filter_dim * width * height); im2col<filter_size>(input_channels, input, col); // Weight shape (output, input, filter_size, filter_size) // 96 18 3 3 // C←αAB + βC // outputs[96,19x19] = weights[96,18x3x3] x col[18x3x3,19x19] // M Number of rows in matrices A and C. // N Number of columns in matrices B and C. // K Number of columns in matrix A; number of rows in matrix B. // lda The size of the first dimention of matrix A; if you are // passing a matrix A[m][n], the value should be m. // cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B, // ldb, beta, C, N); #ifdef USE_BLAS cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, // M N K outputs, num_intersections, filter_dim, 1.0f, &weights[0], filter_dim, &col[0], num_intersections, 0.0f, &output[0], num_intersections); #else auto C_mat = EigenMatrixMap<float>(output.data(), num_intersections, outputs); C_mat.noalias() = ConstEigenMatrixMap<float>(col.data(), num_intersections, filter_dim) * ConstEigenMatrixMap<float>(weights.data(), filter_dim, outputs); #endif for (unsigned int o = 0; o < outputs; o++) { for (unsigned int b = 0; b < num_intersections; b++) { output[(o * num_intersections) + b] += biases[o]; } } } template <size_t spatial_size> void batchnorm(const size_t channels, std::vector<float>& data, const float* const means, const float* const stddevs, const float* const eltwise = nullptr) { for (auto c = size_t{0}; c < channels; ++c) { const auto mean = means[c]; const auto scale_stddev = stddevs[c]; const auto arr = &data[c * spatial_size]; if (eltwise == nullptr) { // Classical BN for (auto b = size_t{0}; b < spatial_size; b++) { arr[b] = std::max(0.0f, scale_stddev * (arr[b] - mean)); } } else { // BN + residual add const auto res = &eltwise[c * spatial_size]; for (auto b = size_t{0}; b < spatial_size; b++) { arr[b] = std::max(0.0f, (scale_stddev * (arr[b] - mean)) + res[b]); } } } } void CPUPipe::forward(const std::vector<float>& input, std::vector<float>& output_pol, std::vector<float>& output_val) { // Input convolution constexpr auto P = WINOGRAD_P; // Calculate output channels const auto output_channels = m_input_channels; // input_channels is the maximum number of input channels of any // convolution. Residual blocks are identical, but the first convolution // might be bigger when the network has very few filters const auto input_channels = std::max(static_cast<size_t>(output_channels), static_cast<size_t>(Network::INPUT_CHANNELS)); auto conv_out = std::vector<float>(output_channels * NUM_INTERSECTIONS); auto V = std::vector<float>(WINOGRAD_TILE * input_channels * P); auto M = std::vector<float>(WINOGRAD_TILE * output_channels * P); winograd_convolve3(output_channels, input, m_weights->m_conv_weights[0], V, M, conv_out); batchnorm<NUM_INTERSECTIONS>(output_channels, conv_out, m_weights->m_batchnorm_means[0].data(), m_weights->m_batchnorm_stddevs[0].data()); // Residual tower auto conv_in = std::vector<float>(output_channels * NUM_INTERSECTIONS); auto res = std::vector<float>(output_channels * NUM_INTERSECTIONS); for (auto i = size_t{1}; i < m_weights->m_conv_weights.size(); i += 2) { auto output_channels = m_input_channels; std::swap(conv_out, conv_in); winograd_convolve3(output_channels, conv_in, m_weights->m_conv_weights[i], V, M, conv_out); batchnorm<NUM_INTERSECTIONS>(output_channels, conv_out, m_weights->m_batchnorm_means[i].data(), m_weights->m_batchnorm_stddevs[i].data()); std::swap(conv_in, res); std::swap(conv_out, conv_in); winograd_convolve3(output_channels, conv_in, m_weights->m_conv_weights[i + 1], V, M, conv_out); batchnorm<NUM_INTERSECTIONS>( output_channels, conv_out, m_weights->m_batchnorm_means[i + 1].data(), m_weights->m_batchnorm_stddevs[i + 1].data(), res.data()); } convolve<1>(Network::OUTPUTS_POLICY, conv_out, m_conv_pol_w, m_conv_pol_b, output_pol); convolve<1>(Network::OUTPUTS_VALUE, conv_out, m_conv_val_w, m_conv_val_b, output_val); } void CPUPipe::push_weights(const unsigned int /*filter_size*/, const unsigned int /*channels*/, const unsigned int outputs, std::shared_ptr<const ForwardPipeWeights> weights) { m_weights = weights; // Output head convolutions m_conv_pol_w = weights->m_conv_pol_w; m_conv_pol_b.resize(m_conv_pol_w.size() / outputs, 0.0f); m_conv_val_w = weights->m_conv_val_w; m_conv_val_b.resize(m_conv_val_w.size() / outputs, 0.0f); }
18,317
C++
.cpp
389
35.773779
81
0.506127
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
34,390
UCTNodeRoot.cpp
leela-zero_leela-zero/src/UCTNodeRoot.cpp
/* This file is part of Leela Zero. Copyright (C) 2018-2019 Gian-Carlo Pascutto Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <algorithm> #include <cassert> #include <iterator> #include <numeric> #include <random> #include <utility> #include <vector> #include "FastBoard.h" #include "FastState.h" #include "GTP.h" #include "KoState.h" #include "Random.h" #include "UCTNode.h" #include "Utils.h" /* * These functions belong to UCTNode but should only be called on the root node * of UCTSearch and have been seperated to increase code clarity. */ UCTNode* UCTNode::get_first_child() const { if (m_children.empty()) { return nullptr; } return m_children.front().get(); } void UCTNode::kill_superkos(const GameState& state) { UCTNodePointer* pass_child = nullptr; size_t valid_count = 0; for (auto& child : m_children) { auto move = child->get_move(); if (move != FastBoard::PASS) { KoState mystate = state; mystate.play_move(move); if (mystate.superko()) { // Don't delete nodes for now, just mark them invalid. child->invalidate(); } } else { pass_child = &child; } if (child->valid()) { valid_count++; } } if (valid_count > 1 && pass_child && !state.is_move_legal(state.get_to_move(), FastBoard::PASS)) { // Remove the PASS node according to "avoid" -- but only if there are // other valid nodes left. (*pass_child)->invalidate(); } // Now do the actual deletion. m_children.erase( std::remove_if(begin(m_children), end(m_children), [](const auto& child) { return !child->valid(); }), end(m_children)); } void UCTNode::dirichlet_noise(const float epsilon, const float alpha) { auto child_cnt = m_children.size(); auto dirichlet_vector = std::vector<float>{}; std::gamma_distribution<float> gamma(alpha, 1.0f); for (size_t i = 0; i < child_cnt; i++) { dirichlet_vector.emplace_back(gamma(Random::get_Rng())); } auto sample_sum = std::accumulate(begin(dirichlet_vector), end(dirichlet_vector), 0.0f); // If the noise vector sums to 0 or a denormal, then don't try to // normalize. if (sample_sum < std::numeric_limits<float>::min()) { return; } for (auto& v : dirichlet_vector) { v /= sample_sum; } child_cnt = 0; for (auto& child : m_children) { auto policy = child->get_policy(); auto eta_a = dirichlet_vector[child_cnt++]; policy = policy * (1 - epsilon) + epsilon * eta_a; child->set_policy(policy); } } void UCTNode::randomize_first_proportionally() { auto accum = 0.0; auto norm_factor = 0.0; auto accum_vector = std::vector<double>{}; for (const auto& child : m_children) { auto visits = child->get_visits(); if (norm_factor == 0.0) { norm_factor = visits; // Nonsensical options? End of game? if (visits <= cfg_random_min_visits) { return; } } if (visits > cfg_random_min_visits) { accum += std::pow(visits / norm_factor, 1.0 / cfg_random_temp); accum_vector.emplace_back(accum); } } auto distribution = std::uniform_real_distribution<double>{0.0, accum}; auto pick = distribution(Random::get_Rng()); auto index = size_t{0}; for (size_t i = 0; i < accum_vector.size(); i++) { if (pick < accum_vector[i]) { index = i; break; } } // Take the early out if (index == 0) { return; } assert(m_children.size() > index); // Now swap the child at index with the first child std::iter_swap(begin(m_children), begin(m_children) + index); } UCTNode* UCTNode::get_nopass_child(FastState& state) const { for (const auto& child : m_children) { /* If we prevent the engine from passing, we must bail out when we only have unreasonable moves to pick, like filling eyes. Note that this knowledge isn't required by the engine, we require it because we're overruling its moves. */ if (child->m_move != FastBoard::PASS && !state.board.is_eye(state.get_to_move(), child->m_move)) { return child.get(); } } return nullptr; } // Used to find new root in UCTSearch. std::unique_ptr<UCTNode> UCTNode::find_child(const int move) { for (auto& child : m_children) { if (child.get_move() == move) { // no guarantee that this is a non-inflated node child.inflate(); return std::unique_ptr<UCTNode>(child.release()); } } // Can happen if we resigned or children are not expanded return nullptr; } void UCTNode::inflate_all_children() { for (const auto& node : get_children()) { node.inflate(); } } void UCTNode::prepare_root_node(Network& network, const int color, std::atomic<int>& nodes, GameState& root_state) { float root_eval; const auto had_children = has_children(); if (expandable()) { create_children(network, nodes, root_state, root_eval); } if (had_children) { root_eval = get_net_eval(color); } else { root_eval = (color == FastBoard::BLACK ? root_eval : 1.0f - root_eval); } Utils::myprintf("NN eval=%f\n", root_eval); // There are a lot of special cases where code assumes // all children of the root are inflated, so do that. inflate_all_children(); // Remove illegal moves, so the root move list is correct. // This also removes a lot of special cases. kill_superkos(root_state); if (cfg_noise) { // Adjust the Dirichlet noise's alpha constant to the board size auto alpha = 0.03f * 361.0f / NUM_INTERSECTIONS; dirichlet_noise(0.25f, alpha); } }
7,244
C++
.cpp
195
30.430769
79
0.626551
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,391
UCTNodePointer.cpp
leela-zero_leela-zero/src/UCTNodePointer.cpp
/* This file is part of Leela Zero. Copyright (C) 2018-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <atomic> #include <cassert> #include <cstring> #include <memory> #include "UCTNode.h" std::atomic<size_t> UCTNodePointer::m_tree_size = {0}; size_t UCTNodePointer::get_tree_size() { return m_tree_size.load(); } void UCTNodePointer::increment_tree_size(const size_t sz) { m_tree_size += sz; } void UCTNodePointer::decrement_tree_size(const size_t sz) { assert(UCTNodePointer::m_tree_size >= sz); m_tree_size -= sz; } UCTNodePointer::~UCTNodePointer() { auto sz = sizeof(UCTNodePointer); auto v = m_data.load(); if (is_inflated(v)) { delete read_ptr(v); sz += sizeof(UCTNode); } decrement_tree_size(sz); } UCTNodePointer::UCTNodePointer(UCTNodePointer&& n) { auto nv = std::atomic_exchange(&n.m_data, INVALID); auto v = std::atomic_exchange(&m_data, nv); #ifdef NDEBUG (void)v; #else assert(v == INVALID); #endif increment_tree_size(sizeof(UCTNodePointer)); } UCTNodePointer::UCTNodePointer(const std::int16_t vertex, const float policy) { std::uint32_t i_policy; auto i_vertex = static_cast<std::uint16_t>(vertex); std::memcpy(&i_policy, &policy, sizeof(i_policy)); m_data = (static_cast<std::uint64_t>(i_policy) << 32) | (static_cast<std::uint64_t>(i_vertex) << 16); increment_tree_size(sizeof(UCTNodePointer)); } UCTNodePointer& UCTNodePointer::operator=(UCTNodePointer&& n) { auto nv = std::atomic_exchange(&n.m_data, INVALID); auto v = std::atomic_exchange(&m_data, nv); if (is_inflated(v)) { decrement_tree_size(sizeof(UCTNode)); delete read_ptr(v); } return *this; } UCTNode* UCTNodePointer::release() { auto v = std::atomic_exchange(&m_data, INVALID); decrement_tree_size(sizeof(UCTNode)); return read_ptr(v); } void UCTNodePointer::inflate() const { while (true) { auto v = m_data.load(); if (is_inflated(v)) return; auto v2 = reinterpret_cast<std::uint64_t>( new UCTNode(read_vertex(v), read_policy(v))); assert((v2 & 3ULL) == 0); v2 |= POINTER; bool success = m_data.compare_exchange_strong(v, v2); if (success) { increment_tree_size(sizeof(UCTNode)); return; } else { // this means that somebody else also modified this instance. // Try again next time delete read_ptr(v2); } } } bool UCTNodePointer::valid() const { auto v = m_data.load(); if (is_inflated(v)) return read_ptr(v)->valid(); return true; } int UCTNodePointer::get_visits() const { auto v = m_data.load(); if (is_inflated(v)) return read_ptr(v)->get_visits(); return 0; } float UCTNodePointer::get_policy() const { auto v = m_data.load(); if (is_inflated(v)) return read_ptr(v)->get_policy(); return read_policy(v); } float UCTNodePointer::get_eval_lcb(const int color) const { auto v = m_data.load(); assert(is_inflated(v)); return read_ptr(v)->get_eval_lcb(color); } bool UCTNodePointer::active() const { auto v = m_data.load(); if (is_inflated(v)) return read_ptr(v)->active(); return true; } float UCTNodePointer::get_eval(const int tomove) const { // this can only be called if it is an inflated pointer auto v = m_data.load(); assert(is_inflated(v)); return read_ptr(v)->get_eval(tomove); } int UCTNodePointer::get_move() const { auto v = m_data.load(); if (is_inflated(v)) return read_ptr(v)->get_move(); return read_vertex(v); }
4,851
C++
.cpp
136
30.970588
79
0.676979
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,392
NNCache.cpp
leela-zero_leela-zero/src/NNCache.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Michael O and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <functional> #include <memory> #include "NNCache.h" #include "GTP.h" #include "UCTSearch.h" #include "Utils.h" const int NNCache::MAX_CACHE_COUNT; const int NNCache::MIN_CACHE_COUNT; const size_t NNCache::ENTRY_SIZE; NNCache::NNCache(const int size) : m_size(size) {} bool NNCache::lookup(const std::uint64_t hash, Netresult& result) { std::lock_guard<std::mutex> lock(m_mutex); ++m_lookups; auto iter = m_cache.find(hash); if (iter == m_cache.end()) { return false; // Not found. } const auto& entry = iter->second; // Found it. ++m_hits; result = entry->result; return true; } void NNCache::insert(const std::uint64_t hash, const Netresult& result) { std::lock_guard<std::mutex> lock(m_mutex); if (m_cache.find(hash) != m_cache.end()) { return; // Already in the cache. } m_cache.emplace(hash, std::make_unique<Entry>(result)); m_order.push_back(hash); ++m_inserts; // If the cache is too large, remove the oldest entry. if (m_order.size() > m_size) { m_cache.erase(m_order.front()); m_order.pop_front(); } } void NNCache::resize(const int size) { m_size = size; while (m_order.size() > m_size) { m_cache.erase(m_order.front()); m_order.pop_front(); } } void NNCache::clear() { m_cache.clear(); m_order.clear(); } void NNCache::set_size_from_playouts(const int max_playouts) { // cache hits are generally from last several moves so setting cache // size based on playouts increases the hit rate while balancing memory // usage for low playout instances. 150'000 cache entries is ~208 MiB constexpr auto num_cache_moves = 3; auto max_playouts_per_move = std::min(max_playouts, UCTSearch::UNLIMITED_PLAYOUTS / num_cache_moves); auto max_size = num_cache_moves * max_playouts_per_move; max_size = std::min(MAX_CACHE_COUNT, std::max(MIN_CACHE_COUNT, max_size)); resize(max_size); } void NNCache::dump_stats() { Utils::myprintf( "NNCache: %d/%d hits/lookups = %.1f%% hitrate, %d inserts, %u size\n", m_hits, m_lookups, 100. * m_hits / (m_lookups + 1), m_inserts, m_cache.size()); } size_t NNCache::get_estimated_size() { return m_order.size() * NNCache::ENTRY_SIZE; }
3,616
C++
.cpp
92
34.782609
80
0.692571
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
34,393
FullBoard.cpp
leela-zero_leela-zero/src/FullBoard.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <array> #include <cassert> #include "FullBoard.h" #include "Network.h" #include "Utils.h" #include "Zobrist.h" using namespace Utils; int FullBoard::remove_string(const int i) { int pos = i; int removed = 0; int color = m_state[i]; do { m_hash ^= Zobrist::zobrist[m_state[pos]][pos]; m_ko_hash ^= Zobrist::zobrist[m_state[pos]][pos]; m_state[pos] = EMPTY; m_parent[pos] = NUM_VERTICES; remove_neighbour(pos, color); m_empty_idx[pos] = m_empty_cnt; m_empty[m_empty_cnt] = pos; m_empty_cnt++; m_hash ^= Zobrist::zobrist[m_state[pos]][pos]; m_ko_hash ^= Zobrist::zobrist[m_state[pos]][pos]; removed++; pos = m_next[pos]; } while (pos != i); return removed; } std::uint64_t FullBoard::calc_ko_hash() const { auto res = Zobrist::zobrist_empty; for (auto i = 0; i < m_numvertices; i++) { if (m_state[i] != INVAL) { res ^= Zobrist::zobrist[m_state[i]][i]; } } /* Tromp-Taylor has positional superko */ return res; } template <class Function> std::uint64_t FullBoard::calc_hash(const int komove, Function transform) const { auto res = Zobrist::zobrist_empty; for (auto i = 0; i < m_numvertices; i++) { if (m_state[i] != INVAL) { res ^= Zobrist::zobrist[m_state[i]][transform(i)]; } } /* prisoner hashing is rule set dependent */ res ^= Zobrist::zobrist_pris[0][m_prisoners[0]]; res ^= Zobrist::zobrist_pris[1][m_prisoners[1]]; if (m_tomove == BLACK) { res ^= Zobrist::zobrist_blacktomove; } res ^= Zobrist::zobrist_ko[transform(komove)]; return res; } std::uint64_t FullBoard::calc_hash(const int komove) const { return calc_hash(komove, [](const auto vertex) { return vertex; }); } std::uint64_t FullBoard::calc_symmetry_hash(const int komove, const int symmetry) const { return calc_hash(komove, [this, symmetry](const auto vertex) { if (vertex == NO_VERTEX) { return NO_VERTEX; } else { const auto newvtx = Network::get_symmetry(get_xy(vertex), symmetry, m_boardsize); return get_vertex(newvtx.first, newvtx.second); } }); } std::uint64_t FullBoard::get_hash() const { return m_hash; } std::uint64_t FullBoard::get_ko_hash() const { return m_ko_hash; } void FullBoard::set_to_move(const int tomove) { if (m_tomove != tomove) { m_hash ^= Zobrist::zobrist_blacktomove; } FastBoard::set_to_move(tomove); } int FullBoard::update_board(const int color, const int i) { assert(i != FastBoard::PASS); assert(m_state[i] == EMPTY); m_hash ^= Zobrist::zobrist[m_state[i]][i]; m_ko_hash ^= Zobrist::zobrist[m_state[i]][i]; m_state[i] = vertex_t(color); m_next[i] = i; m_parent[i] = i; m_libs[i] = count_pliberties(i); m_stones[i] = 1; m_hash ^= Zobrist::zobrist[m_state[i]][i]; m_ko_hash ^= Zobrist::zobrist[m_state[i]][i]; /* update neighbor liberties (they all lose 1) */ add_neighbour(i, color); /* did we play into an opponent eye? */ auto eyeplay = (m_neighbours[i] & s_eyemask[!color]); auto captured_stones = 0; int captured_vtx; for (int k = 0; k < 4; k++) { int ai = i + m_dirs[k]; if (m_state[ai] == !color) { if (m_libs[m_parent[ai]] <= 0) { int this_captured = remove_string(ai); captured_vtx = ai; captured_stones += this_captured; } } else if (m_state[ai] == color) { int ip = m_parent[i]; int aip = m_parent[ai]; if (ip != aip) { if (m_stones[ip] >= m_stones[aip]) { merge_strings(ip, aip); } else { merge_strings(aip, ip); } } } } m_hash ^= Zobrist::zobrist_pris[color][m_prisoners[color]]; m_prisoners[color] += captured_stones; m_hash ^= Zobrist::zobrist_pris[color][m_prisoners[color]]; /* move last vertex in list to our position */ auto lastvertex = m_empty[--m_empty_cnt]; m_empty_idx[lastvertex] = m_empty_idx[i]; m_empty[m_empty_idx[i]] = lastvertex; /* check whether we still live (i.e. detect suicide) */ if (m_libs[m_parent[i]] == 0) { assert(captured_stones == 0); remove_string(i); } /* check for possible simple ko */ if (captured_stones == 1 && eyeplay) { assert(get_state(captured_vtx) == FastBoard::EMPTY && !is_suicide(captured_vtx, !color)); return captured_vtx; } // No ko return NO_VERTEX; } void FullBoard::display_board(const int lastmove) { FastBoard::display_board(lastmove); myprintf("Hash: %llX Ko-Hash: %llX\n\n", get_hash(), get_ko_hash()); } void FullBoard::reset_board(const int size) { FastBoard::reset_board(size); m_hash = calc_hash(); m_ko_hash = calc_ko_hash(); }
6,424
C++
.cpp
173
30.456647
80
0.614194
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,396
Random.cpp
leela-zero_leela-zero/src/Random.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <climits> #include <cstdint> #include <random> #include <thread> #include "Random.h" #include "GTP.h" #include "Utils.h" Random& Random::get_Rng() { static thread_local Random s_rng{0}; return s_rng; } Random::Random(const std::uint64_t seed) { if (seed == 0) { size_t thread_id = std::hash<std::thread::id>()(std::this_thread::get_id()); seedrandom(cfg_rng_seed ^ std::uint64_t(thread_id)); } else { seedrandom(seed); } } // This is xoroshiro128+. // Note that the last bit isn't entirely random, so don't use it, // if possible. std::uint64_t Random::gen() { const std::uint64_t s0 = m_s[0]; std::uint64_t s1 = m_s[1]; const std::uint64_t result = s0 + s1; s1 ^= s0; m_s[0] = Utils::rotl(s0, 55) ^ s1 ^ (s1 << 14); m_s[1] = Utils::rotl(s1, 36); return result; } std::uint64_t Random::randuint64(const uint64_t max) { const uint64_t inclusive_max = max - 1; return std::uniform_int_distribution<uint64_t>{0, inclusive_max}(*this); } std::uint64_t Random::randuint64() { return gen(); } static std::uint64_t splitmix64(std::uint64_t z) { z += 0x9e3779b97f4a7c15; z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >> 27)) * 0x94d049bb133111eb; return z ^ (z >> 31); } void Random::seedrandom(const std::uint64_t seed) { // Initialize state of xoroshiro128+ by transforming the seed // with the splitmix64 algorithm. // As suggested by http://xoroshiro.di.unimi.it/xoroshiro128plus.c m_s[0] = splitmix64(seed); m_s[1] = splitmix64(m_s[0]); }
2,915
C++
.cpp
76
34.276316
76
0.693017
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
34,397
GameState.cpp
leela-zero_leela-zero/src/GameState.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include <algorithm> #include <array> #include <cassert> #include <iterator> #include <memory> #include <string> #include "GameState.h" #include "FastBoard.h" #include "FastState.h" #include "FullBoard.h" #include "KoState.h" #include "Network.h" #include "UCTSearch.h" void GameState::init_game(const int size, const float komi) { KoState::init_game(size, komi); m_game_history.clear(); m_game_history.emplace_back(std::make_shared<KoState>(*this)); m_timecontrol.reset_clocks(); m_resigned = FastBoard::EMPTY; } void GameState::reset_game() { KoState::reset_game(); m_game_history.clear(); m_game_history.emplace_back(std::make_shared<KoState>(*this)); m_timecontrol.reset_clocks(); m_resigned = FastBoard::EMPTY; } bool GameState::forward_move() { if (m_game_history.size() > m_movenum + 1) { m_movenum++; *(static_cast<KoState*>(this)) = *m_game_history[m_movenum]; return true; } else { return false; } } bool GameState::undo_move() { if (m_movenum > 0) { m_movenum--; // this is not so nice, but it should work *(static_cast<KoState*>(this)) = *m_game_history[m_movenum]; // This also restores hashes as they're part of state return true; } else { return false; } } void GameState::rewind() { *(static_cast<KoState*>(this)) = *m_game_history[0]; m_movenum = 0; } void GameState::play_move(const int vertex) { play_move(get_to_move(), vertex); } void GameState::play_move(const int color, const int vertex) { if (vertex == FastBoard::RESIGN) { m_resigned = color; } else { KoState::play_move(color, vertex); } // cut off any leftover moves from navigating m_game_history.resize(m_movenum); m_game_history.emplace_back(std::make_shared<KoState>(*this)); } bool GameState::play_textmove(std::string color, const std::string& vertex) { int who; transform(cbegin(color), cend(color), begin(color), tolower); if (color == "w" || color == "white") { who = FullBoard::WHITE; } else if (color == "b" || color == "black") { who = FullBoard::BLACK; } else { return false; } const auto move = board.text_to_move(vertex); if (move == FastBoard::NO_VERTEX || (move != FastBoard::PASS && move != FastBoard::RESIGN && board.get_state(move) != FastBoard::EMPTY)) { return false; } set_to_move(who); play_move(move); return true; } void GameState::stop_clock(const int color) { m_timecontrol.stop(color); } void GameState::start_clock(const int color) { m_timecontrol.start(color); } void GameState::display_state() { FastState::display_state(); m_timecontrol.display_times(); } int GameState::who_resigned() const { return m_resigned; } bool GameState::has_resigned() const { return m_resigned != FastBoard::EMPTY; } const TimeControl& GameState::get_timecontrol() const { return m_timecontrol; } void GameState::set_timecontrol(const TimeControl& timecontrol) { m_timecontrol = timecontrol; } void GameState::set_timecontrol(const int maintime, const int byotime, const int byostones, const int byoperiods) { TimeControl timecontrol(maintime, byotime, byostones, byoperiods); m_timecontrol = timecontrol; } void GameState::adjust_time(const int color, const int time, const int stones) { m_timecontrol.adjust_time(color, time, stones); } void GameState::anchor_game_history() { // handicap moves don't count in game history m_movenum = 0; m_game_history.clear(); m_game_history.emplace_back(std::make_shared<KoState>(*this)); } bool GameState::set_fixed_handicap(const int handicap) { if (!valid_handicap(handicap)) { return false; } int board_size = board.get_boardsize(); int high = board_size >= 13 ? 3 : 2; int mid = board_size / 2; int low = board_size - 1 - high; if (handicap >= 2) { play_move(FastBoard::BLACK, board.get_vertex(low, low)); play_move(FastBoard::BLACK, board.get_vertex(high, high)); } if (handicap >= 3) { play_move(FastBoard::BLACK, board.get_vertex(high, low)); } if (handicap >= 4) { play_move(FastBoard::BLACK, board.get_vertex(low, high)); } if (handicap >= 5 && handicap % 2 == 1) { play_move(FastBoard::BLACK, board.get_vertex(mid, mid)); } if (handicap >= 6) { play_move(FastBoard::BLACK, board.get_vertex(low, mid)); play_move(FastBoard::BLACK, board.get_vertex(high, mid)); } if (handicap >= 8) { play_move(FastBoard::BLACK, board.get_vertex(mid, low)); play_move(FastBoard::BLACK, board.get_vertex(mid, high)); } board.set_to_move(FastBoard::WHITE); anchor_game_history(); set_handicap(handicap); return true; } int GameState::set_fixed_handicap_2(const int handicap) { int board_size = board.get_boardsize(); int low = board_size >= 13 ? 3 : 2; int mid = board_size / 2; int high = board_size - 1 - low; int interval = (high - mid) / 2; int placed = 0; while (interval >= 3) { for (int i = low; i <= high; i += interval) { for (int j = low; j <= high; j += interval) { if (placed >= handicap) return placed; if (board.get_state(i - 1, j - 1) != FastBoard::EMPTY) continue; if (board.get_state(i - 1, j) != FastBoard::EMPTY) continue; if (board.get_state(i - 1, j + 1) != FastBoard::EMPTY) continue; if (board.get_state(i, j - 1) != FastBoard::EMPTY) continue; if (board.get_state(i, j) != FastBoard::EMPTY) continue; if (board.get_state(i, j + 1) != FastBoard::EMPTY) continue; if (board.get_state(i + 1, j - 1) != FastBoard::EMPTY) continue; if (board.get_state(i + 1, j) != FastBoard::EMPTY) continue; if (board.get_state(i + 1, j + 1) != FastBoard::EMPTY) continue; play_move(FastBoard::BLACK, board.get_vertex(i, j)); placed++; } } interval = interval / 2; } return placed; } bool GameState::valid_handicap(const int handicap) { int board_size = board.get_boardsize(); if (handicap < 2 || handicap > 9) { return false; } if (board_size % 2 == 0 && handicap > 4) { return false; } if (board_size == 7 && handicap > 4) { return false; } if (board_size < 7 && handicap > 0) { return false; } return true; } void GameState::place_free_handicap(int stones, Network& network) { int limit = board.get_boardsize() * board.get_boardsize(); if (stones > limit / 2) { stones = limit / 2; } int orgstones = stones; int fixplace = std::min(9, stones); set_fixed_handicap(fixplace); stones -= fixplace; stones -= set_fixed_handicap_2(stones); for (int i = 0; i < stones; i++) { auto search = std::make_unique<UCTSearch>(*this, network); auto move = search->think(FastBoard::BLACK, UCTSearch::NOPASS); play_move(FastBoard::BLACK, move); } if (orgstones) { board.set_to_move(FastBoard::WHITE); } else { board.set_to_move(FastBoard::BLACK); } anchor_game_history(); set_handicap(orgstones); } const FullBoard& GameState::get_past_board(const int moves_ago) const { assert(moves_ago >= 0 && (unsigned)moves_ago <= m_movenum); assert(m_movenum + 1 <= m_game_history.size()); return m_game_history[m_movenum - moves_ago]->board; } const std::vector<std::shared_ptr<const KoState>>& GameState::get_game_history() const { return m_game_history; }
9,145
C++
.cpp
253
30.474308
80
0.641124
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,398
Training.cpp
leela-zero_leela-zero/src/Training.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include <algorithm> #include <bitset> #include <cassert> #include <fstream> #include <iostream> #include <iterator> #include <memory> #include <sstream> #include <stdexcept> #include <utility> #include "Training.h" #include "FastBoard.h" #include "FullBoard.h" #include "GTP.h" #include "GameState.h" #include "Random.h" #include "SGFParser.h" #include "SGFTree.h" #include "Timing.h" #include "UCTNode.h" #include "Utils.h" #include "string.h" #include "zlib.h" std::vector<TimeStep> Training::m_data{}; std::ostream& operator<<(std::ostream& stream, const TimeStep& timestep) { stream << timestep.planes.size() << ' '; for (const auto plane : timestep.planes) { stream << plane << ' '; } stream << timestep.probabilities.size() << ' '; for (const auto prob : timestep.probabilities) { stream << prob << ' '; } stream << timestep.to_move << ' '; stream << timestep.net_winrate << ' '; stream << timestep.root_uct_winrate << ' '; stream << timestep.child_uct_winrate << ' '; stream << timestep.bestmove_visits << std::endl; return stream; } std::istream& operator>>(std::istream& stream, TimeStep& timestep) { int planes_size; stream >> planes_size; for (auto i = 0; i < planes_size; ++i) { TimeStep::BoardPlane plane; stream >> plane; timestep.planes.push_back(plane); } int prob_size; stream >> prob_size; for (auto i = 0; i < prob_size; ++i) { float prob; stream >> prob; timestep.probabilities.push_back(prob); } stream >> timestep.to_move; stream >> timestep.net_winrate; stream >> timestep.root_uct_winrate; stream >> timestep.child_uct_winrate; stream >> timestep.bestmove_visits; return stream; } std::string OutputChunker::gen_chunk_name() const { auto base = std::string{m_basename}; base.append("." + std::to_string(m_chunk_count) + ".gz"); return base; } OutputChunker::OutputChunker(const std::string& basename, bool compress) : m_basename(basename), m_compress(compress) {} OutputChunker::~OutputChunker() { flush_chunks(); } void OutputChunker::append(const std::string& str) { m_buffer.append(str); m_game_count++; if (m_game_count >= CHUNK_SIZE) { flush_chunks(); } } void OutputChunker::flush_chunks() { if (m_compress) { auto chunk_name = gen_chunk_name(); auto out = gzopen(chunk_name.c_str(), "wb9"); auto in_buff_size = m_buffer.size(); auto in_buff = std::make_unique<char[]>(in_buff_size); memcpy(in_buff.get(), m_buffer.data(), in_buff_size); auto comp_size = gzwrite(out, in_buff.get(), in_buff_size); if (!comp_size) { throw std::runtime_error("Error in gzip output"); } Utils::myprintf("Writing chunk %d\n", m_chunk_count); gzclose(out); } else { auto chunk_name = m_basename; auto flags = std::ofstream::out | std::ofstream::app; auto out = std::ofstream{chunk_name, flags}; out << m_buffer; out.close(); } m_buffer.clear(); m_chunk_count++; m_game_count = 0; } void Training::clear_training() { Training::m_data.clear(); } TimeStep::NNPlanes Training::get_planes(const GameState* const state) { const auto input_data = Network::gather_features(state, 0); auto planes = TimeStep::NNPlanes{}; planes.resize(Network::INPUT_CHANNELS); for (auto c = size_t{0}; c < Network::INPUT_CHANNELS; c++) { for (auto idx = 0; idx < NUM_INTERSECTIONS; idx++) { planes[c][idx] = bool(input_data[c * NUM_INTERSECTIONS + idx]); } } return planes; } void Training::record(Network& network, const GameState& state, const UCTNode& root) { auto step = TimeStep{}; step.to_move = state.board.get_to_move(); step.planes = get_planes(&state); const auto result = network.get_output(&state, Network::Ensemble::DIRECT, Network::IDENTITY_SYMMETRY); step.net_winrate = result.winrate; const auto& best_node = root.get_best_root_child(step.to_move); step.root_uct_winrate = root.get_eval(step.to_move); step.child_uct_winrate = best_node.get_eval(step.to_move); step.bestmove_visits = best_node.get_visits(); step.probabilities.resize(POTENTIAL_MOVES); // Get total visit amount. We count rather // than trust the root to avoid ttable issues. auto sum_visits = 0.0; for (const auto& child : root.get_children()) { sum_visits += child->get_visits(); } // In a terminal position (with 2 passes), we can have children, but we // will not able to accumulate search results on them because every attempt // to evaluate will bail immediately. So in this case there will be 0 total // visits, and we should not construct the (non-existent) probabilities. if (sum_visits <= 0.0) { return; } for (const auto& child : root.get_children()) { auto prob = static_cast<float>(child->get_visits() / sum_visits); auto move = child->get_move(); if (move != FastBoard::PASS) { auto xy = state.board.get_xy(move); step.probabilities[xy.second * BOARD_SIZE + xy.first] = prob; } else { step.probabilities[NUM_INTERSECTIONS] = prob; } } m_data.emplace_back(step); } void Training::dump_training(const int winner_color, const std::string& filename) { auto chunker = OutputChunker{filename, true}; dump_training(winner_color, chunker); } void Training::save_training(const std::string& filename) { auto flags = std::ofstream::out; auto out = std::ofstream{filename, flags}; save_training(out); } void Training::load_training(const std::string& filename) { auto flags = std::ifstream::in; auto in = std::ifstream{filename, flags}; load_training(in); } void Training::save_training(std::ofstream& out) { out << m_data.size() << ' '; for (const auto& step : m_data) { out << step; } } void Training::load_training(std::ifstream& in) { int steps; in >> steps; for (auto i = 0; i < steps; ++i) { TimeStep step; in >> step; m_data.push_back(step); } } void Training::dump_training(const int winner_color, OutputChunker& outchunk) { auto training_str = std::string{}; for (const auto& step : m_data) { auto out = std::stringstream{}; // First output 16 times an input feature plane for (auto p = size_t{0}; p < 16; p++) { const auto& plane = step.planes[p]; // Write it out as a string of hex characters for (auto bit = size_t{0}; bit + 3 < plane.size(); bit += 4) { auto hexbyte = plane[bit] << 3 | plane[bit + 1] << 2 | plane[bit + 2] << 1 | plane[bit + 3] << 0; out << std::hex << hexbyte; } // NUM_INTERSECTIONS % 4 = 1 so the last bit goes by itself // for odd sizes assert(plane.size() % 4 == 1); out << plane[plane.size() - 1]; out << std::dec << std::endl; } // The side to move planes can be compactly encoded into a single // bit, 0 = black to move. out << (step.to_move == FastBoard::BLACK ? "0" : "1") << std::endl; // Then a POTENTIAL_MOVES long array of float probabilities for (auto it = begin(step.probabilities); it != end(step.probabilities); ++it) { out << *it; if (next(it) != end(step.probabilities)) { out << " "; } } out << std::endl; // And the game result for the side to move if (step.to_move == winner_color) { out << "1"; } else { out << "-1"; } out << std::endl; training_str.append(out.str()); } outchunk.append(training_str); } void Training::dump_debug(const std::string& filename) { auto chunker = OutputChunker{filename, true}; dump_debug(chunker); } void Training::dump_debug(OutputChunker& outchunk) { auto debug_str = std::string{}; { auto out = std::stringstream{}; out << "2" << std::endl; // File format version out << cfg_resignpct << " " << cfg_weightsfile << std::endl; debug_str.append(out.str()); } for (const auto& step : m_data) { auto out = std::stringstream{}; out << step.net_winrate << " " << step.root_uct_winrate << " " << step.child_uct_winrate << " " << step.bestmove_visits << std::endl; debug_str.append(out.str()); } outchunk.append(debug_str); } void Training::process_game(GameState& state, size_t& train_pos, const int who_won, const std::vector<int>& tree_moves, OutputChunker& outchunker) { clear_training(); auto counter = size_t{0}; state.rewind(); do { auto to_move = state.get_to_move(); auto move_vertex = tree_moves[counter]; auto move_idx = size_t{0}; // Detect if this SGF seems to be corrupted if (!state.is_move_legal(to_move, move_vertex)) { std::cout << "Mainline move not found: " << move_vertex << std::endl; return; } if (move_vertex != FastBoard::PASS) { // get x y coords for actual move auto xy = state.board.get_xy(move_vertex); move_idx = (xy.second * BOARD_SIZE) + xy.first; } else { move_idx = NUM_INTERSECTIONS; // PASS } auto step = TimeStep{}; step.to_move = to_move; step.planes = get_planes(&state); step.probabilities.resize(POTENTIAL_MOVES); step.probabilities[move_idx] = 1.0f; train_pos++; m_data.emplace_back(step); counter++; } while (state.forward_move() && counter < tree_moves.size()); dump_training(who_won, outchunker); } void Training::dump_supervised(const std::string& sgf_name, const std::string& out_filename) { auto outchunker = OutputChunker{out_filename, true}; auto games = SGFParser::chop_all(sgf_name); auto gametotal = games.size(); auto train_pos = size_t{0}; std::cout << "Total games in file: " << gametotal << std::endl; // Shuffle games around std::cout << "Shuffling..."; std::shuffle(begin(games), end(games), Random::get_Rng()); std::cout << "done." << std::endl; Time start; for (auto gamecount = size_t{0}; gamecount < gametotal; gamecount++) { auto sgftree = std::make_unique<SGFTree>(); try { sgftree->load_from_string(games[gamecount]); } catch (...) { continue; }; if (gamecount > 0 && gamecount % 1000 == 0) { Time elapsed; auto elapsed_s = Time::timediff_seconds(start, elapsed); Utils::myprintf( "Game %5d, %5d positions in %5.2f seconds -> %d pos/s\n", gamecount, train_pos, elapsed_s, int(train_pos / elapsed_s)); } auto tree_moves = sgftree->get_mainline(); // Empty game or couldn't be parsed? if (tree_moves.size() == 0) { continue; } auto who_won = sgftree->get_winner(); // Accept all komis and handicaps, but reject no usable result if (who_won != FastBoard::BLACK && who_won != FastBoard::WHITE) { continue; } auto state = std::make_unique<GameState>(sgftree->follow_mainline_state()); // Our board size is hardcoded in several places if (state->board.get_boardsize() != BOARD_SIZE) { continue; } process_game(*state, train_pos, who_won, tree_moves, outchunker); } std::cout << "Dumped " << train_pos << " training positions." << std::endl; }
13,507
C++
.cpp
355
30.729577
80
0.600412
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,399
KoState.cpp
leela-zero_leela-zero/src/KoState.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <algorithm> #include <cassert> #include <iterator> #include "KoState.h" #include "FastBoard.h" #include "FastState.h" #include "FullBoard.h" void KoState::init_game(const int size, const float komi) { assert(size <= BOARD_SIZE); FastState::init_game(size, komi); m_ko_hash_history.clear(); m_ko_hash_history.emplace_back(board.get_ko_hash()); } bool KoState::superko() const { auto first = crbegin(m_ko_hash_history); auto last = crend(m_ko_hash_history); auto res = std::find(++first, last, board.get_ko_hash()); return (res != last); } void KoState::reset_game() { FastState::reset_game(); m_ko_hash_history.clear(); m_ko_hash_history.push_back(board.get_ko_hash()); } void KoState::play_move(const int vertex) { play_move(board.get_to_move(), vertex); } void KoState::play_move(const int color, const int vertex) { if (vertex != FastBoard::RESIGN) { FastState::play_move(color, vertex); } m_ko_hash_history.push_back(board.get_ko_hash()); }
2,352
C++
.cpp
57
37.263158
72
0.72935
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,400
FastBoard.cpp
leela-zero_leela-zero/src/FastBoard.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <algorithm> #include <array> #include <cassert> #include <cctype> #include <iostream> #include <queue> #include <sstream> #include <string> #include "FastBoard.h" #include "Utils.h" using namespace Utils; const int FastBoard::NBR_SHIFT; const int FastBoard::NUM_VERTICES; const int FastBoard::NO_VERTEX; const int FastBoard::PASS; const int FastBoard::RESIGN; const std::array<int, 2> FastBoard::s_eyemask = { 4 * (1 << (NBR_SHIFT * BLACK)), 4 * (1 << (NBR_SHIFT * WHITE)) }; const std::array<FastBoard::vertex_t, 4> FastBoard::s_cinvert = { WHITE, BLACK, EMPTY, INVAL }; int FastBoard::get_boardsize() const { return m_boardsize; } int FastBoard::get_vertex(const int x, const int y) const { assert(x >= 0 && x < BOARD_SIZE); assert(y >= 0 && y < BOARD_SIZE); assert(x >= 0 && x < m_boardsize); assert(y >= 0 && y < m_boardsize); int vertex = ((y + 1) * m_sidevertices) + (x + 1); assert(vertex >= 0 && vertex < m_numvertices); return vertex; } std::pair<int, int> FastBoard::get_xy(const int vertex) const { // int vertex = ((y + 1) * (get_boardsize() + 2)) + (x + 1); int x = (vertex % m_sidevertices) - 1; int y = (vertex / m_sidevertices) - 1; assert(x >= 0 && x < m_boardsize); assert(y >= 0 && y < m_boardsize); assert(get_vertex(x, y) == vertex); return std::make_pair(x, y); } FastBoard::vertex_t FastBoard::get_state(const int vertex) const { assert(vertex >= 0 && vertex < NUM_VERTICES); assert(vertex >= 0 && vertex < m_numvertices); return m_state[vertex]; } void FastBoard::set_state(const int vertex, const FastBoard::vertex_t content) { assert(vertex >= 0 && vertex < NUM_VERTICES); assert(vertex >= 0 && vertex < m_numvertices); assert(content >= BLACK && content <= INVAL); m_state[vertex] = content; } FastBoard::vertex_t FastBoard::get_state(const int x, const int y) const { return get_state(get_vertex(x, y)); } void FastBoard::set_state(const int x, const int y, const FastBoard::vertex_t content) { set_state(get_vertex(x, y), content); } void FastBoard::reset_board(const int size) { m_boardsize = size; m_sidevertices = size + 2; m_numvertices = m_sidevertices * m_sidevertices; m_tomove = BLACK; m_prisoners[BLACK] = 0; m_prisoners[WHITE] = 0; m_empty_cnt = 0; m_dirs[0] = -m_sidevertices; m_dirs[1] = +1; m_dirs[2] = +m_sidevertices; m_dirs[3] = -1; for (int i = 0; i < m_numvertices; i++) { m_state[i] = INVAL; m_neighbours[i] = 0; m_parent[i] = NUM_VERTICES; } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { int vertex = get_vertex(i, j); m_state[vertex] = EMPTY; m_empty_idx[vertex] = m_empty_cnt; m_empty[m_empty_cnt++] = vertex; if (i == 0 || i == size - 1) { m_neighbours[vertex] += (1 << (NBR_SHIFT * BLACK)) | (1 << (NBR_SHIFT * WHITE)); m_neighbours[vertex] += 1 << (NBR_SHIFT * EMPTY); } else { m_neighbours[vertex] += 2 << (NBR_SHIFT * EMPTY); } if (j == 0 || j == size - 1) { m_neighbours[vertex] += (1 << (NBR_SHIFT * BLACK)) | (1 << (NBR_SHIFT * WHITE)); m_neighbours[vertex] += 1 << (NBR_SHIFT * EMPTY); } else { m_neighbours[vertex] += 2 << (NBR_SHIFT * EMPTY); } } } m_parent[NUM_VERTICES] = NUM_VERTICES; m_libs[NUM_VERTICES] = 16384; /* we will subtract from this */ m_next[NUM_VERTICES] = NUM_VERTICES; assert(m_state[NO_VERTEX] == INVAL); } bool FastBoard::is_suicide(const int i, const int color) const { // If there are liberties next to us, it is never suicide if (count_pliberties(i)) { return false; } // If we get here, we played in a "hole" surrounded by stones for (auto k = 0; k < 4; k++) { auto ai = i + m_dirs[k]; auto libs = m_libs[m_parent[ai]]; if (get_state(ai) == color) { if (libs > 1) { // connecting to live group = not suicide return false; } } else if (get_state(ai) == !color) { if (libs <= 1) { // killing neighbour = not suicide return false; } } } // We played in a hole, friendlies had one liberty at most and // we did not kill anything. So we killed ourselves. return true; } int FastBoard::count_pliberties(const int i) const { return count_neighbours(EMPTY, i); } // count neighbours of color c at vertex v // the border of the board has fake neighours of both colors int FastBoard::count_neighbours(const int c, const int v) const { assert(c == WHITE || c == BLACK || c == EMPTY); return (m_neighbours[v] >> (NBR_SHIFT * c)) & NBR_MASK; } void FastBoard::add_neighbour(const int vtx, const int color) { assert(color == WHITE || color == BLACK || color == EMPTY); std::array<int, 4> nbr_pars; int nbr_par_cnt = 0; for (int k = 0; k < 4; k++) { int ai = vtx + m_dirs[k]; m_neighbours[ai] += (1 << (NBR_SHIFT * color)) - (1 << (NBR_SHIFT * EMPTY)); bool found = false; for (int i = 0; i < nbr_par_cnt; i++) { if (nbr_pars[i] == m_parent[ai]) { found = true; break; } } if (!found) { m_libs[m_parent[ai]]--; nbr_pars[nbr_par_cnt++] = m_parent[ai]; } } } void FastBoard::remove_neighbour(const int vtx, const int color) { assert(color == WHITE || color == BLACK || color == EMPTY); std::array<int, 4> nbr_pars; int nbr_par_cnt = 0; for (int k = 0; k < 4; k++) { int ai = vtx + m_dirs[k]; m_neighbours[ai] += (1 << (NBR_SHIFT * EMPTY)) - (1 << (NBR_SHIFT * color)); bool found = false; for (int i = 0; i < nbr_par_cnt; i++) { if (nbr_pars[i] == m_parent[ai]) { found = true; break; } } if (!found) { m_libs[m_parent[ai]]++; nbr_pars[nbr_par_cnt++] = m_parent[ai]; } } } int FastBoard::calc_reach_color(const int color) const { auto reachable = 0; auto bd = std::vector<bool>(m_numvertices, false); auto open = std::queue<int>(); for (auto i = 0; i < m_boardsize; i++) { for (auto j = 0; j < m_boardsize; j++) { auto vertex = get_vertex(i, j); if (m_state[vertex] == color) { reachable++; bd[vertex] = true; open.push(vertex); } } } while (!open.empty()) { /* colored field, spread */ auto vertex = open.front(); open.pop(); for (auto k = 0; k < 4; k++) { auto neighbor = vertex + m_dirs[k]; if (!bd[neighbor] && m_state[neighbor] == EMPTY) { reachable++; bd[neighbor] = true; open.push(neighbor); } } } return reachable; } // Needed for scoring passed out games not in MC playouts float FastBoard::area_score(const float komi) const { auto white = calc_reach_color(WHITE); auto black = calc_reach_color(BLACK); return black - white - komi; } void FastBoard::display_board(const int lastmove) { int boardsize = get_boardsize(); myprintf("\n "); print_columns(); for (int j = boardsize - 1; j >= 0; j--) { myprintf("%2d", j + 1); if (lastmove == get_vertex(0, j)) myprintf("("); else myprintf(" "); for (int i = 0; i < boardsize; i++) { if (get_state(i, j) == WHITE) { myprintf("O"); } else if (get_state(i, j) == BLACK) { myprintf("X"); } else if (starpoint(boardsize, i, j)) { myprintf("+"); } else { myprintf("."); } if (lastmove == get_vertex(i, j)) { myprintf(")"); } else if (i != boardsize - 1 && lastmove == get_vertex(i, j) + 1) { myprintf("("); } else { myprintf(" "); } } myprintf("%2d\n", j + 1); } myprintf(" "); print_columns(); myprintf("\n"); } void FastBoard::print_columns() { for (int i = 0; i < get_boardsize(); i++) { if (i < 25) { myprintf("%c ", (('a' + i < 'i') ? 'a' + i : 'a' + i + 1)); } else { myprintf("%c ", (('A' + (i - 25) < 'I') ? 'A' + (i - 25) : 'A' + (i - 25) + 1)); } } myprintf("\n"); } void FastBoard::merge_strings(const int ip, const int aip) { assert(ip != NUM_VERTICES && aip != NUM_VERTICES); /* merge stones */ m_stones[ip] += m_stones[aip]; /* loop over stones, update parents */ int newpos = aip; do { // check if this stone has a liberty for (int k = 0; k < 4; k++) { int ai = newpos + m_dirs[k]; // for each liberty, check if it is not shared if (m_state[ai] == EMPTY) { // find liberty neighbors bool found = false; for (int kk = 0; kk < 4; kk++) { int aai = ai + m_dirs[kk]; // friendly string shouldn't be ip // ip can also be an aip that has been marked if (m_parent[aai] == ip) { found = true; break; } } if (!found) { m_libs[ip]++; } } } m_parent[newpos] = ip; newpos = m_next[newpos]; } while (newpos != aip); /* merge stings */ std::swap(m_next[aip], m_next[ip]); } bool FastBoard::is_eye(const int color, const int i) const { /* check for 4 neighbors of the same color */ int ownsurrounded = (m_neighbours[i] & s_eyemask[color]); // if not, it can't be an eye // this takes advantage of borders being colored // both ways if (!ownsurrounded) { return false; } // 2 or more diagonals taken // 1 for side groups int colorcount[4]; colorcount[BLACK] = 0; colorcount[WHITE] = 0; colorcount[INVAL] = 0; colorcount[m_state[i - 1 - m_sidevertices]]++; colorcount[m_state[i + 1 - m_sidevertices]]++; colorcount[m_state[i - 1 + m_sidevertices]]++; colorcount[m_state[i + 1 + m_sidevertices]]++; if (colorcount[INVAL] == 0) { if (colorcount[!color] > 1) { return false; } } else { if (colorcount[!color]) { return false; } } return true; } std::string FastBoard::move_to_text(const int move) const { std::ostringstream result; int column = move % m_sidevertices; int row = move / m_sidevertices; column--; row--; assert(move == FastBoard::PASS || move == FastBoard::RESIGN || (row >= 0 && row < m_boardsize)); assert(move == FastBoard::PASS || move == FastBoard::RESIGN || (column >= 0 && column < m_boardsize)); if (move >= 0 && move <= m_numvertices) { result << static_cast<char>(column < 8 ? 'A' + column : 'A' + column + 1); result << (row + 1); } else if (move == FastBoard::PASS) { result << "pass"; } else if (move == FastBoard::RESIGN) { result << "resign"; } else { result << "error"; } return result.str(); } int FastBoard::text_to_move(std::string move) const { transform(cbegin(move), cend(move), begin(move), tolower); if (move == "pass") { return PASS; } else if (move == "resign") { return RESIGN; } else if (move.size() < 2 || !std::isalpha(move[0]) || !std::isdigit(move[1]) || move[0] == 'i') { return NO_VERTEX; } auto column = move[0] - 'a'; if (move[0] > 'i') { --column; } int row; std::istringstream parsestream(move.substr(1)); parsestream >> row; --row; if (row >= m_boardsize || column >= m_boardsize) { return NO_VERTEX; } return get_vertex(column, row); } std::string FastBoard::move_to_text_sgf(const int move) const { std::ostringstream result; int column = move % m_sidevertices; int row = move / m_sidevertices; column--; row--; assert(move == FastBoard::PASS || move == FastBoard::RESIGN || (row >= 0 && row < m_boardsize)); assert(move == FastBoard::PASS || move == FastBoard::RESIGN || (column >= 0 && column < m_boardsize)); // SGF inverts rows row = m_boardsize - row - 1; if (move >= 0 && move <= m_numvertices) { if (column <= 25) { result << static_cast<char>('a' + column); } else { result << static_cast<char>('A' + column - 26); } if (row <= 25) { result << static_cast<char>('a' + row); } else { result << static_cast<char>('A' + row - 26); } } else if (move == FastBoard::PASS) { result << "tt"; } else if (move == FastBoard::RESIGN) { result << "tt"; } else { result << "error"; } return result.str(); } bool FastBoard::starpoint(const int size, const int point) { int stars[3]; int points[2]; int hits = 0; if (size % 2 == 0 || size < 9) { return false; } stars[0] = size >= 13 ? 3 : 2; stars[1] = size / 2; stars[2] = size - 1 - stars[0]; points[0] = point / size; points[1] = point % size; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { if (points[i] == stars[j]) { hits++; } } } return hits >= 2; } bool FastBoard::starpoint(const int size, const int x, const int y) { return starpoint(size, y * size + x); } int FastBoard::get_prisoners(const int side) const { assert(side == WHITE || side == BLACK); return m_prisoners[side]; } int FastBoard::get_to_move() const { return m_tomove; } bool FastBoard::black_to_move() const { return m_tomove == BLACK; } bool FastBoard::white_to_move() const { return m_tomove == WHITE; } void FastBoard::set_to_move(const int tomove) { m_tomove = tomove; } std::string FastBoard::get_string(const int vertex) const { std::string result; int start = m_parent[vertex]; int newpos = start; do { result += move_to_text(newpos) + " "; newpos = m_next[newpos]; } while (newpos != start); // eat last space assert(result.size() > 0); result.resize(result.size() - 1); return result; } std::string FastBoard::get_stone_list() const { std::string result; for (int i = 0; i < m_boardsize; i++) { for (int j = 0; j < m_boardsize; j++) { int vertex = get_vertex(i, j); if (get_state(vertex) != EMPTY) { result += move_to_text(vertex) + " "; } } } // eat final space, if any. if (result.size() > 0) { result.resize(result.size() - 1); } return result; }
16,953
C++
.cpp
497
26.410463
80
0.536164
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,404
Tuner.cpp
leela-zero_leela-zero/src/Tuner.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #ifdef USE_OPENCL #include <array> #include <cassert> #include <cmath> #include <fstream> #include <iostream> #include <map> #include <random> #include <sstream> #include <string> #ifndef USE_BLAS #include <Eigen/Dense> #endif #include "GTP.h" #include "OpenCL.h" #include "Random.h" #include "Tuner.h" #include "Utils.h" const auto TUNER_FILE_LOCAL = std::string("leelaz_opencl_tuning"); template <typename net_t> std::vector<std::string> Tuner<net_t>::tuned_devices; #ifndef USE_BLAS // Eigen helpers template <typename T> using EigenMatrixMap = Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>; template <typename T> using ConstEigenMatrixMap = Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>; #endif template <typename net_t> static std::string getTunerKernel(); template <typename net_t> static float getTunerMaxError(); template <> std::string getTunerKernel<float>() { return std::string("XgemmBatched"); } template <> float getTunerMaxError<float>() { return 1e-4f; } #ifdef USE_HALF template <> std::string getTunerKernel<half_float::half>() { return std::string("XgemmBatchedHalf"); } template <> float getTunerMaxError<half_float::half>() { return 1e-1f; } #endif using namespace Utils; template <typename net_t> static void sgemmBatched_ref(const std::vector<net_t>& a, const std::vector<net_t>& b, std::vector<net_t>& c, const int m, const int n, const int k, const int batch_size) { std::vector<float> ar(a.size()); std::vector<float> br(b.size()); std::vector<float> cr(c.size()); std::copy(begin(a), end(a), begin(ar)); std::copy(begin(b), end(b), begin(br)); for (auto batch = 0; batch < batch_size; batch++) { auto offset_u = batch * m * k; auto offset_v = batch * n * k; auto offset_m = batch * m * n; #ifdef USE_BLAS // Calculates C = transpose(tranpose(A) * B) in row major, or // C = A * transpose(B) in column major. for (auto i = 0; i < m; i++) { for (auto j = 0; j < n; j++) { auto acc = 0.0f; for (auto l = 0; l < k; l++) { acc += ar[l * m + i + offset_u] * br[l * n + j + offset_v]; } cr[j * m + i + offset_m] = acc; } } #else auto C = EigenMatrixMap<float>(cr.data() + offset_m, m, n); auto A = ConstEigenMatrixMap<float>(ar.data() + offset_u, m, k); auto B = ConstEigenMatrixMap<float>(br.data() + offset_v, n, k); C.noalias() = (A * B.transpose()); #endif } std::copy(begin(cr), end(cr), begin(c)); } static bool IsMultiple(const size_t a, const size_t b) { return (a % b == 0); } template <typename net_t> bool Tuner<net_t>::valid_config_sgemm(Parameters p, const bool exhaustive) { if (p["TCE"] == 0) { if (!IsMultiple(p["MWG"], p["MDIMC"] * p["VWM"])) { return false; } if (!IsMultiple(p["NWG"], p["NDIMC"] * p["VWN"])) { return false; } if (!IsMultiple(p["MWG"], p["MDIMA"] * p["VWM"])) { return false; } if (!IsMultiple(p["NWG"], p["NDIMB"] * p["VWN"])) { return false; } if (!IsMultiple(p["KWG"], p["MDIMC"] * p["NDIMC"] / p["MDIMA"])) { return false; } if (!IsMultiple(p["KWG"], p["MDIMC"] * p["NDIMC"] / p["NDIMB"])) { return false; } // Extra restrictions for a fast tuning run if (!exhaustive) { if (p["MDIMC"] != p["MDIMA"]) { return false; } if (p["NDIMC"] != p["NDIMB"]) { return false; } if (p["SA"] != p["SB"]) { return false; } } } else { if (!m_use_tensorcore) { return false; } // In Tensor Core implementations, MDIMA and NDIMB represents the // wmmv multiplication dimensions, that is, // m16n16k16 / m32n8k16 / m8n32k16. Thus m * n is fixed to 256. if (p["MDIMA"] * p["NDIMB"] != 256) { return false; } if (p["MWG"] < p["MDIMC"]) { return false; } if (p["NWG"] < p["NDIMC"]) { return false; } if (p["MDIMC"] < p["MDIMA"]) { return false; } if (p["NDIMC"] < p["NDIMB"]) { return false; } if (p["MWG"] < 32) { return false; } if (p["NWG"] < 32) { return false; } if (p["KWG"] < 32) { return false; } // VWM / VWN has no meaning if we don't do SA / SB. // Only test VWM / VWN == 2 if (p["SA"] == 0 && p["VWM"] != 2) { return false; } if (p["SB"] == 0 && p["VWN"] != 2) { return false; } } return true; } template <typename net_t> Parameters Tuner<net_t>::get_parameters_by_int( const std::vector<Configurations>& opts, const int n) { Parameters param; std::vector<size_t> choices(opts.size()); auto cfgs = 1; for (auto c = size_t{0}; c < opts.size(); c++) { choices[c] = opts[c].second.size(); cfgs *= choices[c]; } auto j = n; for (auto c = size_t{0}; c < opts.size(); c++) { auto o = opts[c]; auto s = o.first; auto v = o.second[j % choices[c]]; j /= choices[c]; param[s] = v; } return param; } template <typename net_t> std::string Tuner<net_t>::parameters_to_defines(const Parameters& p) { std::string s; for (auto const& x : p) { s += " -D" + x.first + "=" + std::to_string(x.second); } return s; } template <typename net_t> std::string Tuner<net_t>::parameters_to_string(const Parameters& p) { std::string s; for (auto const& x : p) { s += x.first + "=" + std::to_string(x.second) + " "; } if (s.size() > 0) { s.resize(s.size() - 1); } return s; } static size_t next_power_of_two(const size_t x) { return 2 << size_t(std::ceil(std::log2(x)) - 1); } template <typename net_t> static void sgemm_generate_data(std::vector<net_t>& x, const int m, const int n, const int batch_size, const int m_ceil, const int n_ceil) { for (auto batch = 0; batch < batch_size; batch++) { for (auto i = 0; i < n_ceil; i++) { if (i < n) { for (auto j = 0; j < m; j++) { x[batch * n_ceil * m_ceil + i * m_ceil + j] = (((i ^ j) + batch - 128) % 256) / 256.0f; } for (auto j = m; j < m_ceil; j++) { x[batch * n_ceil * m_ceil + i * m_ceil + j] = 0.0f; } } else { for (auto j = 0; j < m_ceil; j++) { x[batch * n_ceil * m_ceil + i * m_ceil + j] = 0.0f; } } } } } template <typename net_t> static float compare_ref(std::vector<net_t>& x, std::vector<net_t>& ref, const int m, const int n, const int batch_size, const int m_ceil, const int n_ceil) { auto sum = 0.0f; for (auto batch = 0; batch < batch_size; batch++) { for (auto j = 0; j < m; j++) { for (auto i = 0; i < n; i++) { auto r = ref[batch * n * m + j * n + i]; auto y = x[batch * n_ceil * m_ceil + j * n_ceil + i]; sum += (r - y) * (r - y); } } } return sum / (m * n * batch_size); } template <typename net_t> std::vector<Parameters> Tuner<net_t>::build_valid_params() { auto opts = std::vector<Configurations>(); if (cfg_sgemm_exhaustive) { opts = { {"MWG", {16, 32, 64}}, {"NWG", {16, 32, 64}}, {"KWG", {16, 32}}, {"MDIMC", {8, 16, 32}}, {"NDIMC", {8, 16, 32}}, {"MDIMA", {8, 16, 32}}, {"NDIMB", {8, 16, 32}}, {"KWI", {2, 8}}, {"VWM", {1, 2, 4, 8}}, {"VWN", {1, 2, 4, 8}}, {"STRM", {0, 1}}, {"STRN", {0, 1}}, {"SA", {0, 1}}, {"SB", {0, 1}}, }; } else { opts = { {"MWG", {16, 32, 64}}, {"NWG", {16, 32, 64}}, {"KWG", {16, 32}}, {"MDIMC", {8, 16, 32}}, {"NDIMC", {8, 16, 32}}, {"MDIMA", {8, 16, 32}}, {"NDIMB", {8, 16, 32}}, {"KWI", {2, 8}}, {"VWM", {2, 4}}, {"VWN", {2, 4}}, {"STRM", {0}}, {"STRN", {0}}, {"SA", {1}}, {"SB", {1}}, }; } // Tensor Core options auto topts = std::vector<Configurations>(); if (cfg_sgemm_exhaustive) { topts = { {"MWG", {32, 64, 128, 256}}, {"NWG", {8, 16, 32, 64, 128, 256}}, {"KWG", {16, 32, 64, 128, 256}}, {"MDIMC", {8, 16, 32, 64}}, {"NDIMC", {8, 16, 32, 64}}, {"MDIMA", {8, 16, 32}}, {"NDIMB", {8, 16, 32}}, {"KWI", {2}}, {"VWM", {2, 4, 8}}, {"VWN", {2, 4, 8}}, {"STRM", {0}}, {"STRN", {0}}, {"SA", {0, 1}}, {"SB", {0, 1}}, }; } else { topts = { {"MWG", {32, 64, 128}}, {"NWG", {16, 32, 64, 128}}, {"KWG", {16, 32, 64, 128}}, {"MDIMC", {8, 16, 32}}, {"NDIMC", {8, 16, 32}}, {"MDIMA", {8, 16, 32}}, {"NDIMB", {8, 16, 32}}, {"KWI", {2}}, {"VWM", {2}}, {"VWN", {2}}, {"STRM", {0}}, {"STRN", {0}}, {"SA", {0}}, {"SB", {0}}, }; } auto valid_params = std::vector<Parameters>{}; auto build_from = [this, &valid_params](std::vector<Configurations>& opts, int tce) { auto cfgs = 1; for (auto c = size_t{0}; c < opts.size(); c++) { cfgs *= opts[c].second.size(); } for (auto i = 0; i < cfgs; i++) { Parameters param = get_parameters_by_int(opts, i); param["TCE"] = tce; if (valid_config_sgemm(param, cfg_sgemm_exhaustive)) { valid_params.push_back(param); } } }; build_from(opts, 0); build_from(topts, 1); // Don't use thread RNG or determinism will depend on whether tuner ran. auto rng = Random{0}; std::shuffle(begin(valid_params), end(valid_params), rng); if (cfg_sgemm_exhaustive) { // Likely too many valid params, cut out some of them valid_params.resize(valid_params.size() / 16); } return valid_params; } template <typename net_t> std::string Tuner<net_t>::tune_sgemm(const int m, const int n, const int k, const int batch_size, const int runs) { // This needs to be at minimum the maximum (MNK/WG) values above. auto m_max = std::max(256, m); auto n_max = std::max(256, n); auto k_max = std::max(256, k); auto at_size = batch_size * next_power_of_two(k_max) * next_power_of_two(m_max); auto b_size = batch_size * next_power_of_two(k_max) * next_power_of_two(n_max); auto c_size = batch_size * next_power_of_two(m_max) * next_power_of_two(n_max); auto total_flops = batch_size * 2.0 * m * n * k; auto at = std::vector<net_t>(at_size); auto b = std::vector<net_t>(b_size); auto c = std::vector<net_t>(c_size); auto c_ref = std::vector<net_t>(c_size); sgemm_generate_data(at, k, m, batch_size, k, m); sgemm_generate_data(b, n, k, batch_size, n, k); sgemmBatched_ref(at, b, c_ref, m, n, k, batch_size); auto aBuffer = cl::Buffer(m_context, CL_MEM_READ_WRITE, sizeof(net_t) * at_size, nullptr, nullptr); auto bBuffer = cl::Buffer(m_context, CL_MEM_READ_WRITE, sizeof(net_t) * b_size, nullptr, nullptr); auto cBuffer = cl::Buffer(m_context, CL_MEM_READ_WRITE, sizeof(net_t) * c_size, nullptr, nullptr); myprintf("\nStarted OpenCL SGEMM tuner.\n"); auto valid_params = build_valid_params(); myprintf("Will try %zu valid configurations.\n", valid_params.size()); std::string best_params; auto best_time = unsigned{0}; auto queue = cl::CommandQueue(m_context, m_device, CL_QUEUE_PROFILING_ENABLE); auto event = cl::Event(); auto program = cl::Program(m_context, sourceCode_common + sourceCode_sgemm); auto m_ceil_prev = 0; auto n_ceil_prev = 0; auto k_ceil_prev = 0; auto param_counter = size_t{0}; auto min_error = 100.0f; auto failed_compile = 0; auto failed_enqueue = 0; auto failed_error = 0; for (auto& p : valid_params) { param_counter++; auto defines = parameters_to_defines(p); try { auto args = m_opencl.m_cl_args + " " + defines; program.build(args.c_str()); } catch (const cl::Error&) { // Failed to compile, get next parameter failed_compile++; continue; } auto sgemm_kernel = cl::Kernel(program, "XgemmBatched"); auto m_ceil = int(ceilMultiple(ceilMultiple(m, p["MWG"]), p["VWM"])); auto n_ceil = int(ceilMultiple(ceilMultiple(n, p["NWG"]), p["VWN"])); auto k_ceil = int(ceilMultiple(ceilMultiple(k, p["KWG"]), p["VWM"])); if (m_ceil != m_ceil_prev || n_ceil != n_ceil_prev || k_ceil != k_ceil_prev) { m_ceil_prev = m_ceil; n_ceil_prev = n_ceil; k_ceil_prev = k_ceil; sgemm_generate_data(at, k, m, batch_size, k_ceil, m_ceil); sgemm_generate_data(b, n, k, batch_size, n_ceil, k_ceil); queue.enqueueWriteBuffer(aBuffer, CL_FALSE, 0, at_size * sizeof(net_t), at.data()); queue.enqueueWriteBuffer(bBuffer, CL_FALSE, 0, b_size * sizeof(net_t), b.data()); queue.finish(); } sgemm_kernel.setArg(0, m_ceil); sgemm_kernel.setArg(1, n_ceil); sgemm_kernel.setArg(2, k_ceil); sgemm_kernel.setArg(3, aBuffer); sgemm_kernel.setArg(4, bBuffer); sgemm_kernel.setArg(5, cBuffer); cl::NDRange local_sgemm = {p["MDIMC"], p["NDIMC"], 1}; cl::NDRange size_sgemm = {(m_ceil * p["MDIMC"]) / p["MWG"], (n_ceil * p["NDIMC"]) / p["NWG"], size_t(batch_size)}; // Tensor Core implementation uses a different dimension. if (p["TCE"]) { local_sgemm = {32 * p["MDIMC"] / p["MDIMA"], p["NDIMC"] / p["NDIMB"], 1}; size_sgemm = {32 * m_ceil / p["MDIMA"] * p["MDIMC"] / p["MWG"], n_ceil / p["NDIMB"] * p["NDIMC"] / p["NWG"], size_t(batch_size)}; } auto sum = 0.0f; auto error = 0.0f; for (auto r = 0; r < runs; r++) { try { queue.enqueueNDRangeKernel(sgemm_kernel, cl::NullRange, size_sgemm, local_sgemm, nullptr, &event); queue.finish(); event.wait(); queue.enqueueReadBuffer(cBuffer, CL_FALSE, 0, c_size * sizeof(net_t), c.data()); queue.finish(); auto this_error = compare_ref(c, c_ref, n, m, batch_size, n_ceil, m_ceil); error = std::max(error, this_error); auto elapsed = event.getProfilingInfo<CL_PROFILING_COMMAND_END>() - event.getProfilingInfo<CL_PROFILING_COMMAND_START>(); sum += elapsed; } catch (const cl::Error&) { // Failed to enqueue kernel. Set error to some big number. failed_enqueue++; error = std::numeric_limits<float>::max(); // This failure will be counted to be failed due to error, // so preemptively subtract one from that count. failed_error--; break; } } min_error = std::min(min_error, error); if (error >= getTunerMaxError<net_t>()) { failed_error++; } if (error < getTunerMaxError<net_t>() && (best_time == 0 || sum < best_time)) { auto param_str = parameters_to_string(p); auto kernel_ms = 1e-6f * (sum / runs); // Timing is in nanoseconds (10^-9), Giga = 10^9, so this works out auto kernel_gflops = total_flops / (sum / runs); myprintf("(%u/%u) %s %.4f ms (%.1f GFLOPS)\n", param_counter, valid_params.size(), param_str.c_str(), kernel_ms, kernel_gflops); best_time = sum; best_params = defines; } } if (best_time == 0) { if (failed_compile > 0) { myprintf_error("Failed to compile: %d kernels.\n", failed_compile); } if (failed_enqueue > 0) { myprintf_error("Failed to enqueue: %d kernels\n", failed_enqueue); } if (failed_error > 0) { myprintf_error("Too high error: %d kernels\n", failed_error); } myprintf_error("Failed to find a working configuration.\n" "Check your OpenCL drivers.\n"); myprintf_error("Minimum error: %f. Error bound: %f\n", min_error, getTunerMaxError<net_t>()); throw std::runtime_error("Tuner failed to find working configuration."); } return best_params; } template <typename net_t> void Tuner<net_t>::store_sgemm_tuners(const int m, const int n, const int k, const int batch_size, std::string tuners) { auto tuner_file = leelaz_file(TUNER_FILE_LOCAL); auto file_contents = std::vector<std::string>(); { // Read the previous contents to string auto file = std::ifstream{tuner_file}; if (file.good()) { auto line = std::string{}; while (std::getline(file, line)) { file_contents.emplace_back(line); } } } auto file = std::ofstream{tuner_file}; auto device_name = m_opencl.get_device_name(); auto tuning_params = std::stringstream{}; tuning_params << m << ";" << n << ";" << k << ";" << batch_size; auto tuning_line_prefix = std::to_string(TUNER_VERSION) + ";" + getTunerKernel<net_t>() + ";" + tuning_params.str() + ";"; auto tuning_line = tuning_line_prefix + tuners + ";" + device_name; // Write back previous data as long as it's not the device and // tuning we just tuned for (const auto& line : file_contents) { if (line.find(tuning_line_prefix) == std::string::npos || line.find(device_name) == std::string::npos) { file << line << std::endl; } } // Write new tuning file << tuning_line << std::endl; if (file.fail()) { myprintf("Could not save the tuning result.\n"); myprintf("Do I have write permissions on %s?\n", tuner_file.c_str()); } } template <typename net_t> std::string Tuner<net_t>::sgemm_tuners_from_line(std::string line, const int m, const int n, const int k, const int batch_size) { auto s = std::vector<std::string>{}; auto ss = std::stringstream{line}; auto item = std::string{}; while (std::getline(ss, item, ';')) { s.emplace_back(item); } if (s.size() != 8) { return ""; } if (s[0] != std::to_string(TUNER_VERSION)) { return ""; } if (s[1] != getTunerKernel<net_t>()) { return ""; } if (s[2] != std::to_string(m)) { return ""; } if (s[3] != std::to_string(n)) { return ""; } if (s[4] != std::to_string(k)) { return ""; } if (s[5] != std::to_string(batch_size)) { return ""; } if (s[7] != m_opencl.get_device_name()) { return ""; } return s[6]; } template <typename net_t> std::string Tuner<net_t>::load_sgemm_tuners(const int m, const int n, const int k, const int batch_size) { auto tuner_file = leelaz_file(TUNER_FILE_LOCAL); auto file = std::ifstream{tuner_file}; auto try_prior_tuning = file.good(); // If we want full tuning, don't reuse previously tuned results // except if the tuning was created from this run from a different // GPU instance with the same name. This prevents the tuner running // for multiple times if the system has multiple same GPUs. if (try_prior_tuning && cfg_sgemm_exhaustive) { auto dev = m_opencl.get_device_name(); try_prior_tuning = std::any_of(begin(tuned_devices), end(tuned_devices), [&dev](const std::string& x) { return dev == x; }); } tuned_devices.emplace_back(m_opencl.get_device_name()); if (try_prior_tuning) { auto line = std::string{}; while (std::getline(file, line)) { auto tuners = sgemm_tuners_from_line(line, m, n, k, batch_size); if (tuners.size() != 0) { myprintf("Loaded existing SGEMM tuning.\n"); return tuners; } } } auto tuners = tune_sgemm(m, n, k, batch_size); store_sgemm_tuners(m, n, k, batch_size, tuners); return tuners; } template <typename net_t> void Tuner<net_t>::enable_tensorcore() {} template <> void Tuner<half_float::half>::enable_tensorcore() { m_use_tensorcore = true; } template class Tuner<float>; #ifdef USE_HALF template class Tuner<half_float::half>; #endif #endif
23,847
C++
.cpp
638
27.819749
80
0.511575
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
34,406
Timing.cpp
leela-zero_leela-zero/src/Timing.cpp
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include <chrono> #include "Timing.h" int Time::timediff_centis(const Time start, const Time end) { return std::chrono::duration_cast<std::chrono::milliseconds> (end.m_time - start.m_time).count() / 10; } double Time::timediff_seconds(const Time start, const Time end) { return std::chrono::duration<double>(end.m_time - start.m_time).count(); } Time::Time() { m_time = std::chrono::steady_clock::now(); }
1,728
C++
.cpp
35
45.114286
76
0.746881
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,407
utils_unittest.cpp
leela-zero_leela-zero/src/tests/utils_unittest.cpp
/* This file is part of Leela Zero. Copyright (C) 2018-2019 Seth Troisi and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include <boost/math/distributions/chi_squared.hpp> #include <cstddef> #include <gtest/gtest.h> #include <limits> #include <vector> #include "Random.h" #include "Utils.h" // Test should fail about this often from distribution not looking uniform. // Increasing this allows better detection of bad RNG but increase the chance // of test failure with acceptable RNG implemantation. On my system RNG seems // to be a tiny bit not random and test fail about twice as often as predicted. constexpr auto ALPHA = 0.0001; using namespace Utils; TEST(UtilsTest, CeilMultiple) { // Equal to a multiple EXPECT_EQ(ceilMultiple(0, 1), (size_t)0); EXPECT_EQ(ceilMultiple(0, 3), (size_t)0); EXPECT_EQ(ceilMultiple(6, 1), (size_t)6); EXPECT_EQ(ceilMultiple(23, 1), (size_t)23); EXPECT_EQ(ceilMultiple(2, 2), (size_t)2); EXPECT_EQ(ceilMultiple(4, 2), (size_t)4); EXPECT_EQ(ceilMultiple(6, 2), (size_t)6); EXPECT_EQ(ceilMultiple(0, 3), (size_t)0); EXPECT_EQ(ceilMultiple(3, 3), (size_t)3); EXPECT_EQ(ceilMultiple(9, 3), (size_t)9); // Requires rounding up EXPECT_EQ(ceilMultiple(3, 5), (size_t)5); EXPECT_EQ(ceilMultiple(6, 5), (size_t)10); EXPECT_EQ(ceilMultiple(9, 5), (size_t)10); EXPECT_EQ(ceilMultiple(23, 5), (size_t)25); EXPECT_EQ(ceilMultiple(99, 100), (size_t)100); } double randomlyDistributedProbability(const std::vector<short>& values, const double expected) { auto count = values.size(); // h0: each number had a (1 / count) chance // Chi-square test that each bucket is a randomly distributed count // Variance of getting <v> at each iteration is Var[Bernoulli(1/count)] auto varIter = 1.0 / count - 1.0 / (count * count); // All rng are supposedly independant auto variance = count * expected * varIter; auto x = 0.0; for (const auto& observed : values) { auto error = observed - expected; auto t = (error * error) / variance; x += t; } auto degrees_of_freedom = count - 1; // test statistic of cdf(chi_squared_distribution(count - 1), q); return boost::math::gamma_p(degrees_of_freedom / 2.0, x / 2.0); } bool rngBucketsLookRandom(const double p, const double alpha) { return p >= (alpha / 2) && p <= (1 - alpha / 2); } TEST(UtilsTest, RandFix) { // Using seed = 0 results in pseudo-random seed. auto rng = std::make_unique<Random>(0); auto expected = size_t{40}; auto max = std::uint16_t{200}; auto count = std::vector<short>(max, 0); for (auto i = size_t{0}; i < expected * max; i++) { count[rng->randfix<200>()]++; } auto p = randomlyDistributedProbability(count, expected); EXPECT_PRED2(rngBucketsLookRandom, p, ALPHA); } TEST(UtilsTest, Randuint64_lastEightBits) { // Using seed = 0 results in pseudo-random seed. auto rng = std::make_unique<Random>(0); auto expected = size_t{40}; // Verify last 8 bits are random. auto max = std::uint16_t{128}; auto count = std::vector<short>(max, 0); for (auto i = size_t{0}; i < expected * max; i++) { count[rng->randuint64() & 127]++; } auto p = randomlyDistributedProbability(count, expected); EXPECT_PRED2(rngBucketsLookRandom, p, ALPHA); } TEST(UtilsTest, Randuint64_max) { // Using seed = 0 results in pseudo-random seed. auto rng = std::make_unique<Random>(0); auto expected = size_t{40}; auto max = std::uint64_t{100}; auto count = std::vector<short>(max, 0); for (auto i = size_t{0}; i < expected * max; i++) { count[rng->randuint64(max)]++; } auto p = randomlyDistributedProbability(count, expected); EXPECT_PRED2(rngBucketsLookRandom, p, ALPHA); }
5,034
C++
.cpp
114
39.350877
79
0.6852
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,408
gtests.cpp
leela-zero_leela-zero/src/tests/gtests.cpp
/* This file is part of Leela Zero. Copyright (C) 2018-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #include "config.h" #include <algorithm> #include <cstdint> #include <gtest/gtest.h> #include <iostream> #include <memory> #include <regex> #include <string> #include <vector> #include "GTP.h" #include "GameState.h" #include "NNCache.h" #include "Random.h" #include "ThreadPool.h" #include "Utils.h" #include "Zobrist.h" using namespace Utils; void expect_regex(const std::string& s, const std::string& re, const bool positive = true) { auto m = std::regex_search(s, std::regex(re)); if (positive && !m) { FAIL() << "Output:" << std::endl << s << "Does not contain:" << std::endl << re << std::endl; } else if (!positive && m) { FAIL() << "output:" << std::endl << s << "Should not contain:" << std::endl << re << std::endl; } } class LeelaEnv : public ::testing::Environment { public: ~LeelaEnv() {} void SetUp() { GTP::setup_default_parameters(); cfg_gtp_mode = true; // Setup global objects after command line has been parsed thread_pool.initialize(cfg_num_threads); // Use deterministic random numbers for hashing auto rng = std::make_unique<Random>(5489); Zobrist::init_zobrist(*rng); // Initialize the main thread RNG. // Doing this here avoids mixing in the thread_id, which // improves reproducibility across platforms. Random::get_Rng().seedrandom(cfg_rng_seed); cfg_weightsfile = "../src/tests/0k.txt"; auto playouts = std::min(cfg_max_playouts, cfg_max_visits); auto network = std::make_unique<Network>(); network->initialize(playouts, cfg_weightsfile); GTP::initialize(std::move(network)); } void TearDown() {} }; ::testing::Environment* const leela_env = ::testing::AddGlobalTestEnvironment(new LeelaEnv); class LeelaTest : public ::testing::Test { public: LeelaTest() { // Reset engine parameters GTP::setup_default_parameters(); cfg_max_playouts = 1; cfg_gtp_mode = true; m_gamestate = std::make_unique<GameState>(); m_gamestate->init_game(19, 7.5f); } GameState& get_gamestate() { return *m_gamestate; } std::pair<std::string, std::string> gtp_execute(const std::string& cmd) { testing::internal::CaptureStdout(); testing::internal::CaptureStderr(); GTP::execute(get_gamestate(), cmd); return std::make_pair(testing::internal::GetCapturedStdout(), testing::internal::GetCapturedStderr()); } void test_analyze_cmd(const std::string& cmd, bool valid, int who, int interval, int avoidlen, int avoidcolor, int avoiduntil); private: std::unique_ptr<GameState> m_gamestate; }; TEST_F(LeelaTest, Startup) { auto maingame = get_gamestate(); } TEST_F(LeelaTest, DefaultHash) { auto maingame = get_gamestate(); auto hash = maingame.board.get_hash(); auto ko_hash = maingame.board.get_ko_hash(); EXPECT_EQ(hash, 0x9A930BE1616C538E); EXPECT_EQ(ko_hash, 0xA14C933E7669946D); } TEST_F(LeelaTest, Transposition) { auto maingame = get_gamestate(); testing::internal::CaptureStdout(); GTP::execute(maingame, "play b Q16"); GTP::execute(maingame, "play w D16"); GTP::execute(maingame, "play b D4"); auto hash = maingame.board.get_hash(); auto ko_hash = maingame.board.get_ko_hash(); GTP::execute(maingame, "clear_board"); GTP::execute(maingame, "play b D4"); GTP::execute(maingame, "play w D16"); GTP::execute(maingame, "play b Q16"); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(hash, maingame.board.get_hash()); EXPECT_EQ(ko_hash, maingame.board.get_ko_hash()); } TEST_F(LeelaTest, KoPntNotSame) { auto maingame = get_gamestate(); testing::internal::CaptureStdout(); GTP::execute(maingame, "play b E6"); GTP::execute(maingame, "play w F6"); GTP::execute(maingame, "play b E5"); GTP::execute(maingame, "play w F5"); GTP::execute(maingame, "play b D4"); GTP::execute(maingame, "play w E4"); GTP::execute(maingame, "play b E3"); GTP::execute(maingame, "play w G4"); GTP::execute(maingame, "play b F4"); // capture GTP::execute(maingame, "play w F3"); GTP::execute(maingame, "play b D3"); auto hash = maingame.board.get_hash(); auto ko_hash = maingame.board.get_ko_hash(); GTP::execute(maingame, "clear_board"); GTP::execute(maingame, "play b E6"); GTP::execute(maingame, "play w F6"); GTP::execute(maingame, "play b E5"); GTP::execute(maingame, "play w F5"); GTP::execute(maingame, "play b D4"); GTP::execute(maingame, "play w E4"); GTP::execute(maingame, "play b E3"); GTP::execute(maingame, "play w G4"); GTP::execute(maingame, "play b D3"); GTP::execute(maingame, "play w F3"); GTP::execute(maingame, "play b F4"); // capture std::string output = testing::internal::GetCapturedStdout(); // Board position is the same EXPECT_EQ(ko_hash, maingame.board.get_ko_hash()); // But ko (intersection) is not EXPECT_NE(hash, maingame.board.get_hash()); } TEST_F(LeelaTest, MoveOnOccupiedPnt) { auto maingame = get_gamestate(); std::string output; { testing::internal::CaptureStdout(); GTP::execute(maingame, "play b D4"); GTP::execute(maingame, "play b D4"); output = testing::internal::GetCapturedStdout(); } // Find this error in the output EXPECT_NE(output.find("illegal move"), std::string::npos); { testing::internal::CaptureStdout(); GTP::execute(maingame, "play w Q16"); GTP::execute(maingame, "play b Q16"); output = testing::internal::GetCapturedStdout(); } // Find this error in the output EXPECT_NE(output.find("illegal move"), std::string::npos); } // Basic TimeControl test TEST_F(LeelaTest, TimeControl) { std::pair<std::string, std::string> result; // clear_board to force GTP to make a new UCTSearch. // This will pickup our new cfg_* settings. result = gtp_execute("clear_board"); result = gtp_execute("kgs-time_settings canadian 0 120 25"); result = gtp_execute("showboard"); expect_regex(result.second, "Black time: 00:02:00, 25 stones left"); expect_regex(result.second, "White time: 00:02:00, 25 stones left"); result = gtp_execute("go"); result = gtp_execute("showboard"); expect_regex(result.second, "Black time: \\S*, 24 stones left"); expect_regex(result.second, "White time: \\S*, 25 stones left"); result = gtp_execute("go"); result = gtp_execute("showboard"); expect_regex(result.second, "Black time: \\S*, 24 stones left"); expect_regex(result.second, "White time: \\S*, 24 stones left"); } // Test changing TimeControl during game TEST_F(LeelaTest, TimeControl2) { std::pair<std::string, std::string> result; // clear_board to force GTP to make a new UCTSearch. // This will pickup our new cfg_* settings. result = gtp_execute("clear_board"); result = gtp_execute("kgs-time_settings byoyomi 0 100 1"); result = gtp_execute("go"); result = gtp_execute("showboard"); expect_regex(result.second, "Black time: 00:01:40, 1 period\\(s\\) of 100 seconds left"); expect_regex(result.second, "White time: 00:01:40, 1 period\\(s\\) of 100 seconds left"); result = gtp_execute("kgs-time_settings byoyomi 0 120 1"); result = gtp_execute("go"); result = gtp_execute("showboard"); expect_regex(result.second, "Black time: 00:02:00, 1 period\\(s\\) of 120 seconds left"); expect_regex(result.second, "White time: 00:02:00, 1 period\\(s\\) of 120 seconds left"); } void LeelaTest::test_analyze_cmd(const std::string& cmd, const bool valid, const int who, const int interval, const int avoidlen, const int avoidcolor, const int avoiduntil) { // std::cout << "testing " << cmd << std::endl; // avoid_until checks against the absolute game move number, indexed from 0 std::istringstream cmdstream(cmd); auto maingame = get_gamestate(); AnalyzeTags result{cmdstream, maingame}; EXPECT_EQ(result.m_invalid, !valid); if (!valid) return; EXPECT_EQ(result.m_who, who); EXPECT_EQ(result.m_interval_centis, interval); EXPECT_EQ(result.m_moves_to_avoid.size(), avoidlen); if (avoidlen) { EXPECT_EQ(result.m_moves_to_avoid[0].color, avoidcolor); EXPECT_EQ(result.m_moves_to_avoid[0].until_move, avoiduntil); } } // Test parsing the lz-analyze command line TEST_F(LeelaTest, AnalyzeParse) { gtp_execute("clear_board"); test_analyze_cmd("b 50", true, FastBoard::BLACK, 50, 0, -1, -1); test_analyze_cmd("50 b", true, FastBoard::BLACK, 50, 0, -1, -1); test_analyze_cmd("b interval 50", true, FastBoard::BLACK, 50, 0, -1, -1); test_analyze_cmd("interval 50 b", true, FastBoard::BLACK, 50, 0, -1, -1); test_analyze_cmd("b interval", false, -1, -1, -1, -1, -1); test_analyze_cmd("42 w", true, FastBoard::WHITE, 42, 0, -1, -1); test_analyze_cmd("1234", true, FastBoard::BLACK, 1234, 0, -1, -1); gtp_execute("play b q16"); test_analyze_cmd("1234", true, FastBoard::WHITE, 1234, 0, -1, -1); test_analyze_cmd("b 100 avoid b k10 1", true, FastBoard::BLACK, 100, 1, FastBoard::BLACK, 1); test_analyze_cmd("b 100 avoid b k10 1 avoid b a1 1", true, FastBoard::BLACK, 100, 2, FastBoard::BLACK, 1); test_analyze_cmd("b 100 avoid w k10 8", true, FastBoard::BLACK, 100, 1, FastBoard::WHITE, 8); gtp_execute("play w q4"); test_analyze_cmd("b 100 avoid b k10 8", true, FastBoard::BLACK, 100, 1, FastBoard::BLACK, 9); test_analyze_cmd("100 b avoid b k10 8", true, FastBoard::BLACK, 100, 1, FastBoard::BLACK, 9); test_analyze_cmd("b avoid b k10 8 100", true, FastBoard::BLACK, 100, 1, FastBoard::BLACK, 9); test_analyze_cmd("avoid b k10 8 100 b", true, FastBoard::BLACK, 100, 1, FastBoard::BLACK, 9); test_analyze_cmd("avoid b k10 8 100 w", true, FastBoard::WHITE, 100, 1, FastBoard::BLACK, 9); test_analyze_cmd("avoid b z10 8 100 w", false, -1, -1, -1, -1, -1); test_analyze_cmd("avoid b k10 8 100 w bogus", false, -1, -1, -1, -1, -1); test_analyze_cmd("avoid b k10 8 100 w avoid b pass 17", true, FastBoard::WHITE, 100, 2, FastBoard::BLACK, 9); test_analyze_cmd("avoid b k10 8 w avoid b pass 17", true, FastBoard::WHITE, 0, 2, FastBoard::BLACK, 9); gtp_execute("clear_board"); test_analyze_cmd("b avoid b a1 10 allow b t1 1", false, -1, -1, -1, -1, -1); test_analyze_cmd("b avoid w a1 10 allow b t1 1", true, FastBoard::BLACK, 0, 1, FastBoard::WHITE, 9); test_analyze_cmd("b avoid b pass 10 allow b t1 1", true, FastBoard::BLACK, 0, 1, FastBoard::BLACK, 9); test_analyze_cmd("b avoid b resign 10 allow b t1 1", true, FastBoard::BLACK, 0, 1, FastBoard::BLACK, 9); test_analyze_cmd("b avoid w c3,c4,d3,d4 2 avoid b pass 50", true, FastBoard::BLACK, 0, 5, FastBoard::WHITE, 1); test_analyze_cmd("b avoid w c3,c4,d3,d4, 2 avoid b pass 50", false, -1, -1, -1, -1, -1); gtp_execute("clear_board"); test_analyze_cmd("b avoid b q16 1", true, FastBoard::BLACK, 0, 1, FastBoard::BLACK, 0); test_analyze_cmd("b avoid b : 1", false, -1, -1, -1, -1, -1); test_analyze_cmd("b avoid b d4: 1", false, -1, -1, -1, -1, -1); test_analyze_cmd("b avoid b d14: 1", false, -1, -1, -1, -1, -1); test_analyze_cmd("b avoid b :e3 1", false, -1, -1, -1, -1, -1); test_analyze_cmd("b avoid b d:e3 1", false, -1, -1, -1, -1, -1); test_analyze_cmd("b avoid b q16:q16 20", true, FastBoard::BLACK, 0, 1, FastBoard::BLACK, 19); test_analyze_cmd("b avoid b q16:t19 1", true, FastBoard::BLACK, 0, 16, FastBoard::BLACK, 0); test_analyze_cmd("b avoid b t19:q16 1", true, FastBoard::BLACK, 0, 16, FastBoard::BLACK, 0); test_analyze_cmd("b avoid b t16:q19 1", true, FastBoard::BLACK, 0, 16, FastBoard::BLACK, 0); test_analyze_cmd("b avoid b q19:t16 1", true, FastBoard::BLACK, 0, 16, FastBoard::BLACK, 0); test_analyze_cmd("b avoid b a1:t19 1", true, FastBoard::BLACK, 0, 361, FastBoard::BLACK, 0); test_analyze_cmd("b avoid b a1:t19 1 avoid w pass 1 avoid w resign 1", true, FastBoard::BLACK, 0, 363, FastBoard::BLACK, 0); test_analyze_cmd("b avoid b a1:t19,pass,resign 1", true, FastBoard::BLACK, 0, 363, FastBoard::BLACK, 0); } TEST_F(LeelaTest, AnalyzeParseMinmoves) { gtp_execute("clear_board"); gtp_execute("lz-setoption name pondering value false"); gtp_execute("lz-setoption name playouts value 1"); auto result = gtp_execute("lz-analyze b interval 1 minmoves 5"); // Expect to see at least 5 move priors expect_regex(result.first, "info.*?(prior\\s+\\d+\\s+.*?){5,}.*"); }
14,817
C++
.cpp
323
38.773994
80
0.627606
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,419
FullBoard.h
leela-zero_leela-zero/src/FullBoard.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef FULLBOARD_H_INCLUDED #define FULLBOARD_H_INCLUDED #include "config.h" #include <cstdint> #include "FastBoard.h" class FullBoard : public FastBoard { public: int remove_string(int i); int update_board(int color, int i); std::uint64_t get_hash() const; std::uint64_t get_ko_hash() const; void set_to_move(int tomove); void reset_board(int size); void display_board(int lastmove = -1); std::uint64_t calc_hash(int komove = NO_VERTEX) const; std::uint64_t calc_symmetry_hash(int komove, int symmetry) const; std::uint64_t calc_ko_hash() const; std::uint64_t m_hash; std::uint64_t m_ko_hash; private: template <class Function> std::uint64_t calc_hash(int komove, Function transform) const; }; #endif
2,067
C++
.h
47
39.659574
72
0.744012
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,422
CPUPipe.h
leela-zero_leela-zero/src/CPUPipe.h
/* This file is part of Leela Zero. Copyright (C) 2018-2019 Junhee Yoo and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef CPUPIPE_H_INCLUDED #define CPUPIPE_H_INCLUDED #include "config.h" #include <cassert> #include <vector> #include "ForwardPipe.h" class CPUPipe : public ForwardPipe { public: virtual void initialize(int channels); virtual void forward(const std::vector<float>& input, std::vector<float>& output_pol, std::vector<float>& output_val); virtual void push_weights( unsigned int filter_size, unsigned int channels, unsigned int outputs, std::shared_ptr<const ForwardPipeWeights> weights); private: void winograd_transform_in(const std::vector<float>& in, std::vector<float>& V, int C); void winograd_sgemm(const std::vector<float>& U, const std::vector<float>& V, std::vector<float>& M, int C, int K); void winograd_transform_out(const std::vector<float>& M, std::vector<float>& Y, int K); void winograd_convolve3(int outputs, const std::vector<float>& input, const std::vector<float>& U, std::vector<float>& V, std::vector<float>& M, std::vector<float>& output); int m_input_channels; // Input + residual block tower std::shared_ptr<const ForwardPipeWeights> m_weights; std::vector<float> m_conv_pol_w; std::vector<float> m_conv_val_w; std::vector<float> m_conv_pol_b; std::vector<float> m_conv_val_b; }; #endif
2,886
C++
.h
61
38.540984
78
0.663105
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,423
TimeControl.h
leela-zero_leela-zero/src/TimeControl.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef TIMECONTROL_H_INCLUDED #define TIMECONTROL_H_INCLUDED #include "config.h" #include <array> #include <memory> #include "Timing.h" class TimeControl { public: /* Initialize time control. Timing info is per GTP and in centiseconds */ TimeControl(int maintime = 60 * 60 * 100, int byotime = 0, int byostones = 0, int byoperiods = 0); void start(int color); void stop(int color); int max_time_for_move(int boardsize, int color, size_t movenum) const; void adjust_time(int color, int time, int stones); void display_times(); void reset_clocks(); bool can_accumulate_time(int color) const; size_t opening_moves(int boardsize) const; std::string to_text_sgf() const; static std::shared_ptr<TimeControl> make_from_text_sgf( const std::string& maintime, const std::string& byoyomi, const std::string& black_time_left, const std::string& white_time_left, const std::string& black_moves_left, const std::string& white_moves_left); private: std::string stones_left_to_text_sgf(int color) const; void display_color_time(int color); int get_moves_expected(int boardsize, size_t movenum) const; int m_maintime; int m_byotime; int m_byostones; int m_byoperiods; std::array<int, 2> m_remaining_time; /* main time per player */ std::array<int, 2> m_stones_left; /* stones to play in byo period */ std::array<int, 2> m_periods_left; /* byo periods */ std::array<bool, 2> m_inbyo; /* player is in byo yomi */ std::array<Time, 2> m_times; /* storage for player times */ }; #endif
2,956
C++
.h
65
40.538462
79
0.710609
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,426
SGFTree.h
leela-zero_leela-zero/src/SGFTree.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef SGFTREE_H_INCLUDED #define SGFTREE_H_INCLUDED #include <cstddef> #include <map> #include <sstream> #include <string> #include <vector> #include "FastBoard.h" #include "GameState.h" #include "KoState.h" #include "TimeControl.h" class SGFTree { public: static constexpr auto EOT = 0; // End-Of-Tree marker SGFTree() = default; void init_state(); const KoState* get_state() const; GameState follow_mainline_state(unsigned int movenum = 999) const; std::vector<int> get_mainline() const; void load_from_file(const std::string& filename, int index = 0); void load_from_string(const std::string& gamebuff); void add_property(std::string property, std::string value); SGFTree* add_child(); const SGFTree* get_child(size_t count) const; int get_move(int tomove) const; std::pair<int, int> get_colored_move() const; bool is_initialized() const { return m_initialized; } FastBoard::vertex_t get_winner() const; static std::string state_to_string(GameState& state, int compcolor); private: void populate_states(); void apply_move(int color, int move); void apply_move(int move); void copy_state(const SGFTree& state); int string_to_vertex(const std::string& move) const; using PropertyMap = std::multimap<std::string, std::string>; bool m_initialized{false}; KoState m_state; std::shared_ptr<TimeControl> m_timecontrol_ptr; FastBoard::vertex_t m_winner{FastBoard::INVAL}; std::vector<SGFTree> m_children; PropertyMap m_properties; }; #endif
2,872
C++
.h
69
37.347826
72
0.735727
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,427
Timing.h
leela-zero_leela-zero/src/Timing.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef TIMING_H_INCLUDED #define TIMING_H_INCLUDED #include <chrono> class Time { public: /* sets to current time */ Time(); /* time difference in centiseconds */ static int timediff_centis(Time start, Time end); /* time difference in seconds */ static double timediff_seconds(Time start, Time end); private: std::chrono::steady_clock::time_point m_time; }; #endif
1,698
C++
.h
38
40.421053
72
0.753034
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,432
UCTNodePointer.h
leela-zero_leela-zero/src/UCTNodePointer.h
/* This file is part of Leela Zero. Copyright (C) 2018-2019 Gian-Carlo Pascutto Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef UCTNODEPOINTER_H_INCLUDED #define UCTNODEPOINTER_H_INCLUDED #include "config.h" #include <atomic> #include <cassert> #include <cstring> #include <memory> #include "SMP.h" class UCTNode; // 'lazy-initializable' version of std::unique_ptr<UCTNode>. // When a UCTNodePointer is constructed, the constructor arguments // are stored instead of constructing the actual UCTNode instance. // Later when the UCTNode is needed, the external code calls inflate() // which actually constructs the UCTNode. Basically, this is a 'tagged union' // of: // - std::unique_ptr<UCTNode> pointer; // - std::pair<float, std::int16_t> args; // All methods should be thread-safe except destructor and when // the instanced is 'moved from'. class UCTNodePointer { private: static constexpr std::uint64_t INVALID = 2; static constexpr std::uint64_t POINTER = 1; static constexpr std::uint64_t UNINFLATED = 0; static std::atomic<size_t> m_tree_size; static void increment_tree_size(size_t sz); static void decrement_tree_size(size_t sz); // the raw storage used here. // if bit [1:0] is 1, m_data is the actual pointer. // if bit [1:0] is 0, bit [31:16] is the vertex value, bit [63:32] is the policy // if bit [1:0] is other values, it should assert-fail // (C-style bit fields and unions are not portable) mutable std::atomic<std::uint64_t> m_data{INVALID}; UCTNode* read_ptr(const uint64_t v) const { assert((v & 3ULL) == POINTER); return reinterpret_cast<UCTNode*>(v & ~(0x3ULL)); } std::int16_t read_vertex(const uint64_t v) const { assert((v & 3ULL) == UNINFLATED); return static_cast<std::int16_t>(v >> 16); } float read_policy(const uint64_t v) const { static_assert(sizeof(float) == 4, "This code assumes floats are 32-bit"); assert((v & 3ULL) == UNINFLATED); auto x = static_cast<std::uint32_t>(v >> 32); float ret; std::memcpy(&ret, &x, sizeof(ret)); return ret; } bool is_inflated(const uint64_t v) const { return (v & 3ULL) == POINTER; } public: static size_t get_tree_size(); ~UCTNodePointer(); UCTNodePointer(UCTNodePointer&& n); UCTNodePointer(std::int16_t vertex, float policy); UCTNodePointer(const UCTNodePointer&) = delete; bool is_inflated() const { return is_inflated(m_data.load()); } // methods from std::unique_ptr<UCTNode> typename std::add_lvalue_reference<UCTNode>::type operator*() const { return *read_ptr(m_data.load()); } UCTNode* operator->() const { return read_ptr(m_data.load()); } UCTNode* get() const { return read_ptr(m_data.load()); } UCTNodePointer& operator=(UCTNodePointer&& n); UCTNode* release(); // construct UCTNode instance from the vertex/policy pair void inflate() const; // proxy of UCTNode methods which can be called without // constructing UCTNode bool valid() const; int get_visits() const; float get_policy() const; bool active() const; int get_move() const; // these can only be called if it is an inflated pointer float get_eval(int tomove) const; float get_eval_lcb(int color) const; }; #endif
4,572
C++
.h
111
36.18018
84
0.69373
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,434
KoState.h
leela-zero_leela-zero/src/KoState.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef KOSTATE_H_INCLUDED #define KOSTATE_H_INCLUDED #include "config.h" #include <vector> #include "FastState.h" #include "FullBoard.h" class KoState : public FastState { public: void init_game(int size, float komi); bool superko() const; void reset_game(); void play_move(int color, int vertex); void play_move(int vertex); private: std::vector<std::uint64_t> m_ko_hash_history; }; #endif
1,721
C++
.h
40
39
72
0.755995
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,435
Random.h
leela-zero_leela-zero/src/Random.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef RANDOM_H_INCLUDED #define RANDOM_H_INCLUDED #include "config.h" #include <cstdint> #include <limits> /* Random number generator xoroshiro128+ */ class Random { public: Random() = delete; Random(std::uint64_t seed = 0); void seedrandom(std::uint64_t s); // Random numbers from [0, max - 1] template <int MAX> std::uint32_t randfix() { static_assert(0 < MAX && MAX < std::numeric_limits<std::uint32_t>::max(), "randfix out of range"); // Last bit isn't random, so don't use it in isolation. We specialize // this case. static_assert(MAX != 2, "don't isolate the LSB with xoroshiro128+"); return gen() % MAX; } std::uint64_t randuint64(); // Random number from [0, max - 1] std::uint64_t randuint64(std::uint64_t max); // return the thread local RNG static Random& get_Rng(); // UniformRandomBitGenerator interface using result_type = std::uint64_t; constexpr static result_type min() { return std::numeric_limits<result_type>::min(); } constexpr static result_type max() { return std::numeric_limits<result_type>::max(); } result_type operator()() { return gen(); } private: std::uint64_t gen(); std::uint64_t m_s[2]; }; // Specialization for last bit: use sign test template <> inline std::uint32_t Random::randfix<2>() { return (gen() > (std::numeric_limits<std::uint64_t>::max() / 2)); } #endif
2,821
C++
.h
73
33.410959
77
0.687294
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,438
Tuner.h
leela-zero_leela-zero/src/Tuner.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef SGEMM_TUNER_H_INCLUDED #define SGEMM_TUNER_H_INCLUDED #include "config.h" #include <map> #include <string> #include <vector> using Configurations = std::pair<std::string, std::vector<size_t>>; using Parameters = std::map<std::string, size_t>; template <typename net_t> class OpenCL; template <typename net_t> class Tuner { OpenCL<net_t>& m_opencl; cl::Context m_context; cl::Device m_device; bool m_use_tensorcore = false; public: std::string tune_sgemm(int m, int n, int k, int batch_size, int runs = 4); std::string load_sgemm_tuners(int m, int n, int k, int batch_size); // list of device types that was tuned in this run. // This is to prevent the same device from being tuned multiple times. static std::vector<std::string> tuned_devices; // version 0 : Initial release // version 1 : Tuner with additional tensor cores (parameter TCE) static constexpr auto TUNER_VERSION = 1; Tuner(OpenCL<net_t>& opencl, cl::Context context, cl::Device device) : m_opencl(opencl), m_context(context), m_device(device) {} void enable_tensorcore(); private: void store_sgemm_tuners(int m, int n, int k, int batch_size, std::string tuners); bool valid_config_sgemm(Parameters p, bool exhaustive); std::string parameters_to_defines(const Parameters& p); std::string parameters_to_string(const Parameters& p); Parameters get_parameters_by_int(const std::vector<Configurations>& opts, int n); std::string sgemm_tuners_from_line(std::string line, int m, int n, int k, int batch_size); std::vector<Parameters> build_valid_params(); }; #endif
3,038
C++
.h
63
42.492063
78
0.711532
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,444
NNCache.h
leela-zero_leela-zero/src/NNCache.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Michael O and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef NNCACHE_H_INCLUDED #define NNCACHE_H_INCLUDED #include "config.h" #include <array> #include <deque> #include <memory> #include <mutex> #include <unordered_map> class NNCache { public: // Maximum size of the cache in number of items. static constexpr int MAX_CACHE_COUNT = 150'000; // Minimum size of the cache in number of items. static constexpr int MIN_CACHE_COUNT = 6'000; struct Netresult { // 19x19 board positions std::array<float, NUM_INTERSECTIONS> policy; // pass float policy_pass; // winrate float winrate; Netresult() : policy_pass(0.0f), winrate(0.0f) { policy.fill(0.0f); } }; static constexpr size_t ENTRY_SIZE = sizeof(Netresult) + sizeof(std::uint64_t) + sizeof(std::unique_ptr<Netresult>); NNCache(int size = MAX_CACHE_COUNT); // ~ 208MiB // Set a reasonable size gives max number of playouts void set_size_from_playouts(int max_playouts); // Resize NNCache void resize(int size); void clear(); // Try and find an existing entry. bool lookup(std::uint64_t hash, Netresult& result); // Insert a new entry. void insert(std::uint64_t hash, const Netresult& result); // Return the hit rate ratio. std::pair<int, int> hit_rate() const { return {m_hits, m_lookups}; } void dump_stats(); // Return the estimated memory consumption of the cache. size_t get_estimated_size(); private: std::mutex m_mutex; size_t m_size; // Statistics int m_hits{0}; int m_lookups{0}; int m_inserts{0}; struct Entry { Entry(const Netresult& r) : result(r) {} Netresult result; // ~ 1.4KiB }; // Map from hash to {features, result} std::unordered_map<std::uint64_t, std::unique_ptr<const Entry>> m_cache; // Order entries were added to the map. std::deque<size_t> m_order; }; #endif
3,314
C++
.h
85
32.870588
78
0.67875
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,445
FastBoard.h
leela-zero_leela-zero/src/FastBoard.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef FASTBOARD_H_INCLUDED #define FASTBOARD_H_INCLUDED #include "config.h" #include <array> #include <queue> #include <string> #include <utility> #include <vector> class FastBoard { friend class FastState; public: /* neighbor counts are up to 4, so 3 bits is ok, but a power of 2 makes things a bit faster */ static constexpr int NBR_SHIFT = 4; static constexpr int NBR_MASK = (1 << NBR_SHIFT) - 1; /* number of vertices in a "letterboxed" board representation */ static constexpr int NUM_VERTICES = ((BOARD_SIZE + 2) * (BOARD_SIZE + 2)); /* no applicable vertex */ static constexpr int NO_VERTEX = 0; /* vertex of a pass */ static constexpr int PASS = -1; /* vertex of a "resign move" */ static constexpr int RESIGN = -2; /* possible contents of a vertex */ enum vertex_t : char { BLACK = 0, WHITE = 1, EMPTY = 2, INVAL = 3 }; int get_boardsize() const; vertex_t get_state(int x, int y) const; vertex_t get_state(int vertex) const; int get_vertex(int x, int y) const; void set_state(int x, int y, vertex_t content); void set_state(int vertex, vertex_t content); std::pair<int, int> get_xy(int vertex) const; bool is_suicide(int i, int color) const; int count_pliberties(int i) const; bool is_eye(int color, int vtx) const; float area_score(float komi) const; int get_prisoners(int side) const; bool black_to_move() const; bool white_to_move() const; int get_to_move() const; void set_to_move(int color); std::string move_to_text(int move) const; int text_to_move(std::string move) const; std::string move_to_text_sgf(int move) const; std::string get_stone_list() const; std::string get_string(int vertex) const; void reset_board(int size); void display_board(int lastmove = -1); static bool starpoint(int size, int point); static bool starpoint(int size, int x, int y); protected: /* bit masks to detect eyes on neighbors */ static const std::array<int, 2> s_eyemask; static const std::array<vertex_t, 4> s_cinvert; /* color inversion */ std::array<vertex_t, NUM_VERTICES> m_state; /* board contents */ std::array<unsigned short, NUM_VERTICES + 1> m_next; /* next stone in string */ std::array<unsigned short, NUM_VERTICES + 1> m_parent; /* parent node of string */ std::array<unsigned short, NUM_VERTICES + 1> m_libs; /* liberties per string parent */ std::array<unsigned short, NUM_VERTICES + 1> m_stones; /* stones per string parent */ std::array<unsigned short, NUM_VERTICES> m_neighbours; /* counts of neighboring stones */ std::array<int, 4> m_dirs; /* movement directions 4 way */ std::array<int, 2> m_prisoners; /* prisoners per color */ std::array<unsigned short, NUM_VERTICES> m_empty; /* empty intersections */ std::array<unsigned short, NUM_VERTICES> m_empty_idx; /* intersection indices */ int m_empty_cnt; /* count of empties */ int m_tomove; int m_numvertices; int m_boardsize; int m_sidevertices; int calc_reach_color(int color) const; int count_neighbours(int color, int i) const; void merge_strings(int ip, int aip); void add_neighbour(int i, int color); void remove_neighbour(int i, int color); void print_columns(); }; #endif
4,884
C++
.h
116
37.077586
97
0.666315
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,446
config.h
leela-zero_leela-zero/src/config.h
/* This file is part of Leela Zero. Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors Leela Zero is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Zero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Leela Zero. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with NVIDIA Corporation's libraries from the NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural Network library and/or the NVIDIA TensorRT inference library (or a modified version of those libraries), containing parts covered by the terms of the respective license agreement, the licensors of this Program grant you additional permission to convey the resulting work. */ #ifndef CONFIG_H_INCLUDED #define CONFIG_H_INCLUDED /* * We need to check for input while we are thinking. * That code isn't portable, so select something appropriate for the system. */ #ifdef _WIN32 #undef HAVE_SELECT #define NOMINMAX #else #define HAVE_SELECT #endif /* * BOARD_SIZE: Define size of the board to compile Leela with, must be an odd number due to winograd tiles */ static constexpr auto BOARD_SIZE = 19; static_assert(BOARD_SIZE % 2 == 1, "Code assumes odd board size, remove at your own risk!"); static constexpr auto NUM_INTERSECTIONS = BOARD_SIZE * BOARD_SIZE; static constexpr auto POTENTIAL_MOVES = NUM_INTERSECTIONS + 1; // including pass /* * KOMI: Define the default komi to use when training. */ static constexpr auto KOMI = 7.5f; /* * Features * * USE_BLAS: Optionally use a basic linear algebra library. * This is may perform faster than the included Eigen library, * and some BLAS libraries can target multiple CPU models. * Not all operations are performed on the GPU - * some operations won't get any speedup from it. * Also used for OpenCL self-checks. */ //#define USE_BLAS /* * We use OpenBLAS by default, except on macOS, which has a fast BLAS * built-in. (Accelerate) */ #if !defined(__APPLE__) && !defined(__MACOSX) #if defined(USE_BLAS) #define USE_OPENBLAS #endif #endif /* * USE_MKL: Optionally allows using Intel Math Kernel library as * BLAS implementation. Note that MKL's license is not compatible with the GPL, * so do not redistribute the resulting binaries. It is fine to use it on your * own system. */ //#define USE_MKL /* * USE_OPENCL: Use OpenCL acceleration for GPUs. This makes the program a lot * faster if you have a recent GPU. Don't use it on CPUs even if they have * OpenCL drivers - the BLAS version is much faster for those. */ #ifndef USE_CPU_ONLY #define USE_OPENCL /* * USE_HALF: Include the half-precision OpenCL implementation when building. * The current implementation autodetects whether half-precision is better * or single-precision is better (half precision is chosen if it's 5% faster) * Half-precision OpenCL gains performance on some GPUs while losing some * accuracy on the calculation, but generally it is worth using half precision * if it is at least 5% faster. */ #define USE_HALF #endif /* * USE_TUNER: Expose some extra command line parameters that allow tuning the * search algorithm. */ //#define USE_TUNER static constexpr auto PROGRAM_NAME = "Leela Zero"; static constexpr auto PROGRAM_VERSION = "0.17"; /* * OpenBLAS limitation: the default configuration on some Linuxes * is limited to 64 cores. */ #if defined(USE_BLAS) && defined(USE_OPENBLAS) static constexpr auto MAX_CPUS = 64; #else static constexpr auto MAX_CPUS = 256; #endif #ifdef USE_HALF #include "half/half.hpp" #endif #ifdef USE_OPENCL // If OpenCL are fully usable, then check the OpenCL against CPU // implementation with some probability. #define USE_OPENCL_SELFCHECK static constexpr auto SELFCHECK_PROBABILITY = 2000; #endif #if (_MSC_VER >= 1400) /* VC8+ Disable all deprecation warnings */ #pragma warning(disable : 4996) #endif /* VC8+ */ #endif
4,476
C++
.h
121
34.636364
80
0.759289
leela-zero/leela-zero
5,332
1,013
373
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,448
stereomanager.cpp
OpenMW_openmw/components/stereo/stereomanager.cpp
#include "stereomanager.hpp" #include "frustum.hpp" #include "multiview.hpp" #include <osg/DisplaySettings> #include <osg/Texture2D> #include <osg/Texture2DArray> #include <osg/Texture2DMultisample> #include <osg/io_utils> #include <osgUtil/CullVisitor> #include <osgUtil/RenderStage> #include <osgViewer/Renderer> #include <osgViewer/Viewer> #include <map> #include <string> #include <components/misc/constants.hpp> #include <components/sceneutil/color.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/statesetupdater.hpp> #include <components/settings/values.hpp> namespace Stereo { // Update stereo view/projection during update class StereoUpdateCallback final : public osg::Callback { public: StereoUpdateCallback(Manager* stereoView) : stereoView(stereoView) { } bool run(osg::Object* object, osg::Object* data) override { auto b = traverse(object, data); stereoView->update(); return b; } Manager* stereoView; }; // Update states during cull class BruteForceStereoStatesetUpdateCallback final : public SceneUtil::StateSetUpdater { public: BruteForceStereoStatesetUpdateCallback(Manager* manager) : mManager(manager) { } protected: virtual void setDefaults(osg::StateSet* stateset) override { stateset->addUniform(new osg::Uniform("projectionMatrix", osg::Matrixf{})); } virtual void apply(osg::StateSet* stateset, osg::NodeVisitor* /*nv*/) override {} void applyLeft(osg::StateSet* stateset, osgUtil::CullVisitor* nv) override { auto* uProjectionMatrix = stateset->getUniform("projectionMatrix"); if (uProjectionMatrix) uProjectionMatrix->set(mManager->computeEyeProjection(0, SceneUtil::AutoDepth::isReversed())); } void applyRight(osg::StateSet* stateset, osgUtil::CullVisitor* nv) override { auto* uProjectionMatrix = stateset->getUniform("projectionMatrix"); if (uProjectionMatrix) uProjectionMatrix->set(mManager->computeEyeProjection(1, SceneUtil::AutoDepth::isReversed())); } private: Manager* mManager; }; // Update states during cull class MultiviewStereoStatesetUpdateCallback : public SceneUtil::StateSetUpdater { public: MultiviewStereoStatesetUpdateCallback(Manager* manager) : mManager(manager) { } protected: virtual void setDefaults(osg::StateSet* stateset) { stateset->addUniform(new osg::Uniform(osg::Uniform::FLOAT_MAT4, "invProjectionMatrixMultiView", 2)); } virtual void apply(osg::StateSet* stateset, osg::NodeVisitor* /*nv*/) { mManager->updateMultiviewStateset(stateset); } private: Manager* mManager; }; static bool sStereoEnabled = false; static Manager* sInstance = nullptr; Manager& Manager::instance() { return *sInstance; } Manager::Manager(osgViewer::Viewer* viewer, bool enableStereo, double near, double far) : mViewer(viewer) , mMainCamera(mViewer->getCamera()) , mUpdateCallback(new StereoUpdateCallback(this)) , mMasterProjectionMatrix(osg::Matrixd::identity()) , mEyeResolutionOverriden(false) , mEyeResolutionOverride(0, 0) , mNear(near) , mFar(far) , mFrustumManager(nullptr) , mUpdateViewCallback(nullptr) { if (sInstance) throw std::logic_error("Double instance of Stereo::Manager"); sInstance = this; sStereoEnabled = enableStereo; } Manager::~Manager() {} void Manager::initializeStereo(osg::GraphicsContext* gc, bool enableMultiview, bool sharedShadowMaps) { auto ci = gc->getState()->getContextID(); configureExtensions(ci, enableMultiview); mMainCamera->addUpdateCallback(mUpdateCallback); mFrustumManager = std::make_unique<StereoFrustumManager>(sharedShadowMaps, mViewer->getCamera()); if (getMultiview()) setupOVRMultiView2Technique(); else setupBruteForceTechnique(); updateStereoFramebuffer(); } void shaderStereoDefines(Shader::ShaderManager::DefineMap& defines) { if (getMultiview()) { defines["useOVR_multiview"] = "1"; defines["numViews"] = "2"; } else { defines["useOVR_multiview"] = "0"; defines["numViews"] = "1"; } } void Manager::overrideEyeResolution(const osg::Vec2i& eyeResolution) { mEyeResolutionOverride = eyeResolution; mEyeResolutionOverriden = true; // if (mMultiviewFramebuffer) // updateStereoFramebuffer(); } void Manager::screenResolutionChanged() { updateStereoFramebuffer(); } osg::Vec2i Manager::eyeResolution() { if (mEyeResolutionOverriden) return mEyeResolutionOverride; auto width = mMainCamera->getViewport()->width() / 2; auto height = mMainCamera->getViewport()->height(); return osg::Vec2i(width, height); } void Manager::disableStereoForNode(osg::Node* node) { // Re-apply the main camera's full viewport to return to full screen rendering. node->getOrCreateStateSet()->setAttribute(mMainCamera->getViewport()); } void Manager::setShadowTechnique(SceneUtil::MWShadowTechnique* shadowTechnique) { if (mFrustumManager) mFrustumManager->setShadowTechnique(shadowTechnique); } void Manager::setupBruteForceTechnique() { auto* ds = osg::DisplaySettings::instance().get(); ds->setStereo(true); ds->setStereoMode(osg::DisplaySettings::StereoMode::HORIZONTAL_SPLIT); ds->setUseSceneViewForStereoHint(true); mMainCamera->addCullCallback(new BruteForceStereoStatesetUpdateCallback(this)); struct ComputeStereoMatricesCallback : public osgUtil::SceneView::ComputeStereoMatricesCallback { ComputeStereoMatricesCallback(Manager* sv) : mManager(sv) { } osg::Matrixd computeLeftEyeProjection(const osg::Matrixd& projection) const override { (void)projection; return mManager->computeEyeProjection(0, false); } osg::Matrixd computeLeftEyeView(const osg::Matrixd& view) const override { return view * mManager->computeEyeViewOffset(0); } osg::Matrixd computeRightEyeProjection(const osg::Matrixd& projection) const override { (void)projection; return mManager->computeEyeProjection(1, false); } osg::Matrixd computeRightEyeView(const osg::Matrixd& view) const override { return view * mManager->computeEyeViewOffset(1); } Manager* mManager; }; auto* renderer = static_cast<osgViewer::Renderer*>(mMainCamera->getRenderer()); for (auto* sceneView : { renderer->getSceneView(0), renderer->getSceneView(1) }) { sceneView->setComputeStereoMatricesCallback(new ComputeStereoMatricesCallback(this)); auto* cvMain = sceneView->getCullVisitor(); auto* cvLeft = sceneView->getCullVisitorLeft(); auto* cvRight = sceneView->getCullVisitorRight(); if (!cvMain) sceneView->setCullVisitor(cvMain = new osgUtil::CullVisitor()); if (!cvLeft) sceneView->setCullVisitor(cvLeft = cvMain->clone()); if (!cvRight) sceneView->setCullVisitor(cvRight = cvMain->clone()); // Osg by default gives cullVisitorLeft and cullVisitor the same identifier. // So we make our own to avoid confusion cvMain->setIdentifier(mIdentifierMain); cvLeft->setIdentifier(mIdentifierLeft); cvRight->setIdentifier(mIdentifierRight); } } void Manager::setupOVRMultiView2Technique() { auto* ds = osg::DisplaySettings::instance().get(); ds->setStereo(false); mMainCamera->addCullCallback(new MultiviewStereoStatesetUpdateCallback(this)); } void Manager::updateStereoFramebuffer() { // VR-TODO: in VR, still need to have this framebuffer attached before the postprocessor is created // auto samples = /*do not use Settings here*/; // auto eyeRes = eyeResolution(); // if (mMultiviewFramebuffer) // mMultiviewFramebuffer->detachFrom(mMainCamera); // mMultiviewFramebuffer = std::make_shared<MultiviewFramebuffer>(static_cast<int>(eyeRes.x()), // static_cast<int>(eyeRes.y()), samples); // mMultiviewFramebuffer->attachColorComponent(SceneUtil::Color::colorSourceFormat(), // SceneUtil::Color::colorSourceType(), SceneUtil::Color::colorInternalFormat()); // mMultiviewFramebuffer->attachDepthComponent(SceneUtil::AutoDepth::depthSourceFormat(), // SceneUtil::AutoDepth::depthSourceType(), SceneUtil::AutoDepth::depthInternalFormat()); // mMultiviewFramebuffer->attachTo(mMainCamera); } void Manager::update() { if (mUpdateViewCallback) { mUpdateViewCallback->updateView(mView[0], mView[1]); mViewOffsetMatrix[0] = mView[0].viewMatrix(true); mViewOffsetMatrix[1] = mView[1].viewMatrix(true); mProjectionMatrix[0] = mView[0].perspectiveMatrix(mNear, mFar, false); mProjectionMatrix[1] = mView[1].perspectiveMatrix(mNear, mFar, false); if (SceneUtil::AutoDepth::isReversed()) { mProjectionMatrixReverseZ[0] = mView[0].perspectiveMatrix(mNear, mFar, true); mProjectionMatrixReverseZ[1] = mView[1].perspectiveMatrix(mNear, mFar, true); } View masterView; masterView.fov.angleDown = std::min(mView[0].fov.angleDown, mView[1].fov.angleDown); masterView.fov.angleUp = std::max(mView[0].fov.angleUp, mView[1].fov.angleUp); masterView.fov.angleLeft = std::min(mView[0].fov.angleLeft, mView[1].fov.angleLeft); masterView.fov.angleRight = std::max(mView[0].fov.angleRight, mView[1].fov.angleRight); auto projectionMatrix = masterView.perspectiveMatrix(mNear, mFar, false); mMainCamera->setProjectionMatrix(projectionMatrix); } else { auto* ds = osg::DisplaySettings::instance().get(); const auto& projectionMatrix = mMainCamera->getProjectionMatrix(); auto s = ds->getEyeSeparation() * Constants::UnitsPerMeter; mViewOffsetMatrix[0] = osg::Matrixd(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, s, 0.0, 0.0, 1.0); mViewOffsetMatrix[1] = osg::Matrixd(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -s, 0.0, 0.0, 1.0); mProjectionMatrix[0] = ds->computeLeftEyeProjectionImplementation(projectionMatrix); mProjectionMatrix[1] = ds->computeRightEyeProjectionImplementation(projectionMatrix); if (SceneUtil::AutoDepth::isReversed()) { mProjectionMatrixReverseZ[0] = ds->computeLeftEyeProjectionImplementation(mMasterProjectionMatrix); mProjectionMatrixReverseZ[1] = ds->computeRightEyeProjectionImplementation(mMasterProjectionMatrix); } } mFrustumManager->update({ mProjectionMatrix[0], mProjectionMatrix[1] }); } void Manager::updateMultiviewStateset(osg::StateSet* stateset) { std::array<osg::Matrix, 2> projectionMatrices; for (int view : { 0, 1 }) projectionMatrices[view] = computeEyeViewOffset(view) * computeEyeProjection(view, SceneUtil::AutoDepth::isReversed()); Stereo::setMultiviewMatrices(stateset, projectionMatrices, true); } void Manager::setUpdateViewCallback(std::shared_ptr<UpdateViewCallback> cb) { mUpdateViewCallback = std::move(cb); } void Manager::setCullCallback(osg::ref_ptr<osg::NodeCallback> cb) { mMainCamera->setCullCallback(cb); } osg::Matrixd Manager::computeEyeProjection(int view, bool reverseZ) const { return reverseZ ? mProjectionMatrixReverseZ[view] : mProjectionMatrix[view]; } osg::Matrixd Manager::computeEyeViewOffset(int view) const { return mViewOffsetMatrix[view]; } Eye Manager::getEye(const osgUtil::CullVisitor* cv) const { if (cv->getIdentifier() == mIdentifierMain) return Eye::Center; if (cv->getIdentifier() == mIdentifierLeft) return Eye::Left; if (cv->getIdentifier() == mIdentifierRight) return Eye::Right; return Eye::Center; } bool getStereo() { return sStereoEnabled; } Manager::CustomViewCallback::CustomViewCallback(View& left, View& right) : mLeft(left) , mRight(right) { } void Manager::CustomViewCallback::updateView(View& left, View& right) { left = mLeft; right = mRight; } InitializeStereoOperation::InitializeStereoOperation(const Settings& settings) : GraphicsOperation("InitializeStereoOperation", false) , mMultiview(settings.mMultiview) , mSharedShadowMaps(settings.mSharedShadowMaps) , mCustomView(settings.mCustomView) , mEyeResolution(settings.mEyeResolution) { // Ideally, this would have belonged to the operator(). But the vertex buffer // hint has to be set before realize is called on the osg viewer, and so has to // be done here instead. Stereo::setVertexBufferHint(settings.mMultiview, settings.mAllowDisplayListsForMultiview); } void InitializeStereoOperation::operator()(osg::GraphicsContext* graphicsContext) { auto& sm = Stereo::Manager::instance(); if (mCustomView.has_value()) sm.setUpdateViewCallback( std::make_shared<Stereo::Manager::CustomViewCallback>(mCustomView->mLeft, mCustomView->mRight)); if (mEyeResolution.has_value()) sm.overrideEyeResolution(*mEyeResolution); sm.initializeStereo(graphicsContext, mMultiview, mSharedShadowMaps); } }
14,707
C++
.cpp
350
33.011429
116
0.649867
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,449
frustum.cpp
OpenMW_openmw/components/stereo/frustum.cpp
#include "multiview.hpp" #include <osg/DisplaySettings> #include <osg/Texture2D> #include <osg/Texture2DArray> #include <osg/Texture2DMultisample> #include <osg/io_utils> #include <osgUtil/CullVisitor> #include <osgUtil/RenderStage> #include <osgViewer/Renderer> #include <osgViewer/Viewer> #include <map> #include <string> #include <components/sceneutil/color.hpp> #include <components/sceneutil/mwshadowtechnique.hpp> #include <components/settings/settings.hpp> #include "frustum.hpp" namespace Stereo { struct MultiviewFrustumCallback final : public Stereo::InitialFrustumCallback { MultiviewFrustumCallback(StereoFrustumManager* sfm, osg::Camera* camera) : Stereo::InitialFrustumCallback(camera) , mSfm(sfm) { } void setInitialFrustum( osg::CullStack& cullStack, osg::BoundingBoxd& bb, bool& nearCulling, bool& farCulling) const override { auto cm = cullStack.getCullingMode(); nearCulling = !!(cm & osg::CullSettings::NEAR_PLANE_CULLING); farCulling = !!(cm & osg::CullSettings::FAR_PLANE_CULLING); bb = mSfm->boundingBox(); } StereoFrustumManager* mSfm; }; struct ShadowFrustumCallback final : public SceneUtil::MWShadowTechnique::CustomFrustumCallback { ShadowFrustumCallback(StereoFrustumManager* parent) : mParent(parent) { } void operator()(osgUtil::CullVisitor& cv, osg::BoundingBoxd& customClipSpace, osgUtil::CullVisitor*& sharedFrustumHint) override { mParent->customFrustumCallback(cv, customClipSpace, sharedFrustumHint); } StereoFrustumManager* mParent; }; void joinBoundingBoxes( const osg::Matrix& masterProjection, const osg::Matrix& slaveProjection, osg::BoundingBoxd& bb) { static const std::array<osg::Vec3d, 8> clipCorners = { { { -1.0, -1.0, -1.0 }, { 1.0, -1.0, -1.0 }, { 1.0, -1.0, 1.0 }, { -1.0, -1.0, 1.0 }, { -1.0, 1.0, -1.0 }, { 1.0, 1.0, -1.0 }, { 1.0, 1.0, 1.0 }, { -1.0, 1.0, 1.0 }, } }; osg::Matrix slaveClipToView; slaveClipToView.invert(slaveProjection); for (const auto& clipCorner : clipCorners) { auto masterViewVertice = clipCorner * slaveClipToView; auto masterClipVertice = masterViewVertice * masterProjection; bb.expandBy(masterClipVertice); } } StereoFrustumManager::StereoFrustumManager(bool sharedShadowMaps, osg::Camera* camera) : mCamera(camera) , mShadowTechnique(nullptr) , mShadowFrustumCallback(nullptr) { if (Stereo::getMultiview()) { mMultiviewFrustumCallback = std::make_unique<MultiviewFrustumCallback>(this, camera); } if (sharedShadowMaps) { mShadowFrustumCallback = new ShadowFrustumCallback(this); auto* renderer = static_cast<osgViewer::Renderer*>(mCamera->getRenderer()); for (auto* sceneView : { renderer->getSceneView(0), renderer->getSceneView(1) }) { mSharedFrustums[sceneView->getCullVisitorRight()] = sceneView->getCullVisitorLeft(); } } } StereoFrustumManager::~StereoFrustumManager() { if (mShadowTechnique) mShadowTechnique->setCustomFrustumCallback(nullptr); } void StereoFrustumManager::setShadowTechnique(SceneUtil::MWShadowTechnique* shadowTechnique) { if (mShadowTechnique) mShadowTechnique->setCustomFrustumCallback(nullptr); mShadowTechnique = shadowTechnique; if (mShadowTechnique) mShadowTechnique->setCustomFrustumCallback(mShadowFrustumCallback); } void StereoFrustumManager::customFrustumCallback( osgUtil::CullVisitor& cv, osg::BoundingBoxd& customClipSpace, osgUtil::CullVisitor*& sharedFrustumHint) { auto it = mSharedFrustums.find(&cv); if (it != mSharedFrustums.end()) { sharedFrustumHint = it->second; } customClipSpace = mBoundingBox; } void StereoFrustumManager::update(std::array<osg::Matrix, 2> projections) { mBoundingBox.init(); for (auto& projection : projections) joinBoundingBoxes(mCamera->getProjectionMatrix(), projection, mBoundingBox); } }
4,507
C++
.cpp
119
29.621849
113
0.646277
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,450
types.cpp
OpenMW_openmw/components/stereo/types.cpp
#include "types.hpp" #include <osg/io_utils> namespace Stereo { Pose Pose::operator+(const Pose& rhs) { Pose pose = *this; pose.position += this->orientation * rhs.position; pose.orientation = rhs.orientation * this->orientation; return pose; } const Pose& Pose::operator+=(const Pose& rhs) { *this = *this + rhs; return *this; } Pose Pose::operator*(float scalar) { Pose pose = *this; pose.position *= scalar; return pose; } const Pose& Pose::operator*=(float scalar) { *this = *this * scalar; return *this; } Pose Pose::operator/(float scalar) { Pose pose = *this; pose.position /= scalar; return pose; } const Pose& Pose::operator/=(float scalar) { *this = *this / scalar; return *this; } bool Pose::operator==(const Pose& rhs) const { return position == rhs.position && orientation == rhs.orientation; } osg::Matrix View::viewMatrix(bool useGLConventions) { auto position = pose.position; auto orientation = pose.orientation; if (useGLConventions) { // When applied as an offset to an existing view matrix, // that view matrix will already convert points to a camera space // with opengl conventions. So we need to convert offsets to opengl // conventions. float y = position.y(); float z = position.z(); position.y() = z; position.z() = -y; y = orientation.y(); z = orientation.z(); orientation.y() = z; orientation.z() = -y; osg::Matrix viewMatrix; viewMatrix.setTrans(-position); viewMatrix.postMultRotate(orientation.conj()); return viewMatrix; } else { osg::Vec3d forward = orientation * osg::Vec3d(0, 1, 0); osg::Vec3d up = orientation * osg::Vec3d(0, 0, 1); osg::Matrix viewMatrix; viewMatrix.makeLookAt(position, position + forward, up); return viewMatrix; } } osg::Matrix View::perspectiveMatrix(float near, float far, bool reverseZ) { const float tanLeft = tanf(fov.angleLeft); const float tanRight = tanf(fov.angleRight); const float tanDown = tanf(fov.angleDown); const float tanUp = tanf(fov.angleUp); const float tanWidth = tanRight - tanLeft; const float tanHeight = tanUp - tanDown; float matrix[16] = {}; matrix[0] = 2 / tanWidth; matrix[4] = 0; matrix[8] = (tanRight + tanLeft) / tanWidth; matrix[12] = 0; matrix[1] = 0; matrix[5] = 2 / tanHeight; matrix[9] = (tanUp + tanDown) / tanHeight; matrix[13] = 0; if (reverseZ) { matrix[2] = 0; matrix[6] = 0; matrix[10] = (2.f * near) / (far - near); matrix[14] = ((2.f * near) * far) / (far - near); } else { matrix[2] = 0; matrix[6] = 0; matrix[10] = -(far + near) / (far - near); matrix[14] = -(far * (2.f * near)) / (far - near); } matrix[3] = 0; matrix[7] = 0; matrix[11] = -1; matrix[15] = 0; return osg::Matrix(matrix); } bool FieldOfView::operator==(const FieldOfView& rhs) const { return angleDown == rhs.angleDown && angleUp == rhs.angleUp && angleLeft == rhs.angleLeft && angleRight == rhs.angleRight; } bool View::operator==(const View& rhs) const { return pose == rhs.pose && fov == rhs.fov; } std::ostream& operator<<(std::ostream& os, const Pose& pose) { os << "position=" << pose.position << ", orientation=" << pose.orientation; return os; } std::ostream& operator<<(std::ostream& os, const FieldOfView& fov) { os << "left=" << fov.angleLeft << ", right=" << fov.angleRight << ", down=" << fov.angleDown << ", up=" << fov.angleUp; return os; } std::ostream& operator<<(std::ostream& os, const View& view) { os << "pose=< " << view.pose << " >, fov=< " << view.fov << " >"; return os; } }
4,408
C++
.cpp
137
23.605839
100
0.533098
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,451
multiview.cpp
OpenMW_openmw/components/stereo/multiview.cpp
#include "multiview.hpp" #include <osg/FrameBufferObject> #include <osg/GLExtensions> #include <osg/Texture2D> #include <osg/Texture2DArray> #include <osg/Texture2DMultisample> #include <osgUtil/CullVisitor> #include <osgUtil/RenderStage> #ifdef OSG_HAS_MULTIVIEW #include <osg/Texture2DMultisampleArray> #endif #include <components/debug/debuglog.hpp> #include <components/sceneutil/nodecallback.hpp> #include <components/settings/settings.hpp> #include <components/stereo/stereomanager.hpp> #include <algorithm> namespace Stereo { namespace { bool getMultiviewSupportedImpl(unsigned int contextID) { #ifdef OSG_HAS_MULTIVIEW if (!osg::isGLExtensionSupported(contextID, "GL_OVR_multiview")) { Log(Debug::Verbose) << "Disabling Multiview (opengl extension \"GL_OVR_multiview\" not supported)"; return false; } if (!osg::isGLExtensionSupported(contextID, "GL_OVR_multiview2")) { Log(Debug::Verbose) << "Disabling Multiview (opengl extension \"GL_OVR_multiview2\" not supported)"; return false; } return true; #else Log(Debug::Verbose) << "Disabling Multiview (OSG does not support multiview)"; return false; #endif } bool getMultiviewSupported(unsigned int contextID) { static bool supported = getMultiviewSupportedImpl(contextID); return supported; } bool getTextureViewSupportedImpl(unsigned int contextID) { if (!osg::isGLExtensionOrVersionSupported(contextID, "ARB_texture_view", 4.3)) { Log(Debug::Verbose) << "Disabling texture views (opengl extension \"ARB_texture_view\" not supported)"; return false; } return true; } bool getTextureViewSupported(unsigned int contextID) { static bool supported = getTextureViewSupportedImpl(contextID); return supported; } bool getMultiviewImpl(unsigned int contextID) { if (!Stereo::getStereo()) { Log(Debug::Verbose) << "Disabling Multiview (disabled by config)"; return false; } if (!getMultiviewSupported(contextID)) { return false; } if (!getTextureViewSupported(contextID)) { Log(Debug::Verbose) << "Disabling Multiview (texture views not supported)"; return false; } Log(Debug::Verbose) << "Enabling Multiview"; return true; } static bool sMultiview = false; bool getMultiview(unsigned int contextID) { static bool multiView = getMultiviewImpl(contextID); return multiView; } } bool getTextureViewSupported() { return getTextureViewSupported(0); } bool getMultiview() { return getMultiview(0); } void configureExtensions(unsigned int contextID, bool enableMultiview) { getTextureViewSupported(contextID); getMultiviewSupported(contextID); if (enableMultiview) { sMultiview = getMultiview(contextID); } else { Log(Debug::Verbose) << "Disabling Multiview (disabled by config)"; sMultiview = false; } } void setVertexBufferHint(bool enableMultiview, bool allowDisplayListsForMultiview) { if (getStereo() && enableMultiview) { auto* ds = osg::DisplaySettings::instance().get(); if (!allowDisplayListsForMultiview && ds->getVertexBufferHint() == osg::DisplaySettings::VertexBufferHint::NO_PREFERENCE) { // Note that this only works if this code is executed before realize() is called on the viewer. // The hint is read by the state object only once, before the user realize operations are run. // Therefore we have to set this hint without access to a graphics context to let us determine // if multiview will actually be supported or not. So if the user has requested multiview, we // will just have to set it regardless. ds->setVertexBufferHint(osg::DisplaySettings::VertexBufferHint::VERTEX_BUFFER_OBJECT); Log(Debug::Verbose) << "Disabling display lists"; } } } class Texture2DViewSubloadCallback : public osg::Texture2D::SubloadCallback { public: Texture2DViewSubloadCallback(osg::Texture2DArray* textureArray, int layer); void load(const osg::Texture2D& texture, osg::State& state) const override; void subload(const osg::Texture2D& texture, osg::State& state) const override; private: osg::ref_ptr<osg::Texture2DArray> mTextureArray; int mLayer; }; Texture2DViewSubloadCallback::Texture2DViewSubloadCallback(osg::Texture2DArray* textureArray, int layer) : mTextureArray(textureArray) , mLayer(layer) { } void Texture2DViewSubloadCallback::load(const osg::Texture2D& texture, osg::State& state) const { state.checkGLErrors("before Texture2DViewSubloadCallback::load()"); auto contextId = state.getContextID(); auto* gl = osg::GLExtensions::Get(contextId, false); mTextureArray->apply(state); auto sourceTextureObject = mTextureArray->getTextureObject(contextId); if (!sourceTextureObject) { Log(Debug::Error) << "Texture2DViewSubloadCallback: Texture2DArray did not have a texture object"; return; } osg::Texture::TextureObject* const targetTextureObject = texture.getTextureObject(contextId); if (targetTextureObject == nullptr) { Log(Debug::Error) << "Texture2DViewSubloadCallback: Texture2D did not have a texture object"; return; } // OSG already bound this texture ID, giving it a target. // Delete it and make a new texture ID. glBindTexture(GL_TEXTURE_2D, 0); glDeleteTextures(1, &targetTextureObject->_id); glGenTextures(1, &targetTextureObject->_id); auto sourceId = sourceTextureObject->_id; auto targetId = targetTextureObject->_id; auto internalFormat = sourceTextureObject->_profile._internalFormat; auto levels = std::max(1, sourceTextureObject->_profile._numMipmapLevels); { ////// OSG BUG // Texture views require immutable storage. // OSG should always give immutable storage to sized internal formats, but does not do so for depth formats. // Fortunately, we can just call glTexStorage3D here to make it immutable. This probably discards depth info // for that frame, but whatever. #ifndef GL_TEXTURE_IMMUTABLE_FORMAT #define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F #endif // Store any current binding and re-apply it after so i don't mess with state. GLint oldBinding = 0; glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY, &oldBinding); // Bind the source texture and check if it's immutable. glBindTexture(GL_TEXTURE_2D_ARRAY, sourceId); GLint immutable = 0; glGetTexParameteriv(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_IMMUTABLE_FORMAT, &immutable); if (!immutable) { // It wasn't immutable, so make it immutable. gl->glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, internalFormat, sourceTextureObject->_profile._width, sourceTextureObject->_profile._height, 2); state.checkGLErrors("after Texture2DViewSubloadCallback::load()::glTexStorage3D"); } glBindTexture(GL_TEXTURE_2D_ARRAY, oldBinding); } gl->glTextureView(targetId, GL_TEXTURE_2D, sourceId, internalFormat, 0, levels, mLayer, 1); state.checkGLErrors("after Texture2DViewSubloadCallback::load()::glTextureView"); glBindTexture(GL_TEXTURE_2D, targetId); } void Texture2DViewSubloadCallback::subload(const osg::Texture2D& texture, osg::State& state) const { // Nothing to do } osg::ref_ptr<osg::Texture2D> createTextureView_Texture2DFromTexture2DArray( osg::Texture2DArray* textureArray, int layer) { if (!getTextureViewSupported()) { Log(Debug::Error) << "createTextureView_Texture2DFromTexture2DArray: Tried to use a texture view but " "glTextureView is not supported"; return nullptr; } osg::ref_ptr<osg::Texture2D> texture2d = new osg::Texture2D; texture2d->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); texture2d->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); texture2d->setSubloadCallback(new Texture2DViewSubloadCallback(textureArray, layer)); texture2d->setTextureSize(textureArray->getTextureWidth(), textureArray->getTextureHeight()); texture2d->setBorderColor(textureArray->getBorderColor()); texture2d->setBorderWidth(textureArray->getBorderWidth()); texture2d->setLODBias(textureArray->getLODBias()); texture2d->setFilter(osg::Texture::FilterParameter::MAG_FILTER, textureArray->getFilter(osg::Texture::FilterParameter::MAG_FILTER)); texture2d->setFilter(osg::Texture::FilterParameter::MIN_FILTER, textureArray->getFilter(osg::Texture::FilterParameter::MIN_FILTER)); texture2d->setInternalFormat(textureArray->getInternalFormat()); texture2d->setNumMipmapLevels(textureArray->getNumMipmapLevels()); return texture2d; } #ifdef OSG_HAS_MULTIVIEW //! Draw callback that, if set on a RenderStage, resolves MSAA after draw. Needed when using custom fbo/resolve fbos //! on renderstages in combination with multiview. struct MultiviewMSAAResolveCallback : public osgUtil::RenderBin::DrawCallback { void drawImplementation( osgUtil::RenderBin* bin, osg::RenderInfo& renderInfo, osgUtil::RenderLeaf*& previous) override { osgUtil::RenderStage* stage = static_cast<osgUtil::RenderStage*>(bin); auto msaaFbo = stage->getFrameBufferObject(); auto resolveFbo = stage->getMultisampleResolveFramebufferObject(); if (msaaFbo != mMsaaFbo) { mMsaaFbo = msaaFbo; setupMsaaLayers(); } if (resolveFbo != mFbo) { mFbo = resolveFbo; setupLayers(); } // Null the resolve framebuffer to keep osg from doing redundant work. stage->setMultisampleResolveFramebufferObject(nullptr); // Do the actual render work bin->drawImplementation(renderInfo, previous); // Blit layers osg::State& state = *renderInfo.getState(); osg::GLExtensions* ext = state.get<osg::GLExtensions>(); for (int i = 0; i < 2; i++) { mLayers[i]->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); mMsaaLayers[i]->apply(state, osg::FrameBufferObject::READ_FRAMEBUFFER); ext->glBlitFramebuffer(0, 0, mWidth, mHeight, 0, 0, mWidth, mHeight, GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, GL_NEAREST); } msaaFbo->apply(state, osg::FrameBufferObject::READ_DRAW_FRAMEBUFFER); } void setupLayers() { const auto& attachments = mFbo->getAttachmentMap(); for (int i = 0; i < 2; i++) { mLayers[i] = new osg::FrameBufferObject; // Intentionally not using ref& so attachment can be non-const for (auto [component, attachment] : attachments) { osg::Texture2DArray* texture = static_cast<osg::Texture2DArray*>(attachment.getTexture()); mLayers[i]->setAttachment(component, osg::FrameBufferAttachment(texture, i)); mWidth = texture->getTextureWidth(); mHeight = texture->getTextureHeight(); } } } void setupMsaaLayers() { const auto& attachments = mMsaaFbo->getAttachmentMap(); for (int i = 0; i < 2; i++) { mMsaaLayers[i] = new osg::FrameBufferObject; // Intentionally not using ref& so attachment can be non-const for (auto [component, attachment] : attachments) { osg::Texture2DMultisampleArray* texture = static_cast<osg::Texture2DMultisampleArray*>(attachment.getTexture()); mMsaaLayers[i]->setAttachment(component, osg::FrameBufferAttachment(texture, i)); mWidth = texture->getTextureWidth(); mHeight = texture->getTextureHeight(); } } } osg::ref_ptr<osg::FrameBufferObject> mFbo; osg::ref_ptr<osg::FrameBufferObject> mMsaaFbo; osg::ref_ptr<osg::FrameBufferObject> mLayers[2]; osg::ref_ptr<osg::FrameBufferObject> mMsaaLayers[2]; int mWidth; int mHeight; }; #endif void setMultiviewMSAAResolveCallback(osgUtil::RenderStage* renderStage) { #ifdef OSG_HAS_MULTIVIEW if (Stereo::getMultiview()) { renderStage->setDrawCallback(new MultiviewMSAAResolveCallback); } #endif } void setMultiviewMatrices( osg::StateSet* stateset, const std::array<osg::Matrix, 2>& projection, bool createInverseMatrices) { auto* projUniform = stateset->getUniform("projectionMatrixMultiView"); if (!projUniform) { projUniform = new osg::Uniform(osg::Uniform::FLOAT_MAT4, "projectionMatrixMultiView", 2); stateset->addUniform(projUniform, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } projUniform->setElement(0, projection[0]); projUniform->setElement(1, projection[1]); if (createInverseMatrices) { auto* invUniform = stateset->getUniform("invProjectionMatrixMultiView"); if (!invUniform) { invUniform = new osg::Uniform(osg::Uniform::FLOAT_MAT4, "invProjectionMatrixMultiView", 2); stateset->addUniform(invUniform, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } invUniform->setElement(0, osg::Matrix::inverse(projection[0])); invUniform->setElement(1, osg::Matrix::inverse(projection[1])); } } void setMultiviewCompatibleTextureSize(osg::Texture* tex, int w, int h) { switch (tex->getTextureTarget()) { case GL_TEXTURE_2D: static_cast<osg::Texture2D*>(tex)->setTextureSize(w, h); break; case GL_TEXTURE_2D_ARRAY: static_cast<osg::Texture2DArray*>(tex)->setTextureSize(w, h, 2); break; case GL_TEXTURE_2D_MULTISAMPLE: static_cast<osg::Texture2DMultisample*>(tex)->setTextureSize(w, h); break; #ifdef OSG_HAS_MULTIVIEW case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: static_cast<osg::Texture2DMultisampleArray*>(tex)->setTextureSize(w, h, 2); break; #endif default: throw std::logic_error("Invalid texture type received"); } } osg::ref_ptr<osg::Texture> createMultiviewCompatibleTexture(int width, int height, int samples) { #ifdef OSG_HAS_MULTIVIEW if (Stereo::getMultiview()) { if (samples > 1) { auto tex = new osg::Texture2DMultisampleArray(); tex->setTextureSize(width, height, 2); tex->setNumSamples(samples); return tex; } else { auto tex = new osg::Texture2DArray(); tex->setTextureSize(width, height, 2); return tex; } } else #endif { if (samples > 1) { auto tex = new osg::Texture2DMultisample(); tex->setTextureSize(width, height); tex->setNumSamples(samples); tex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); tex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); return tex; } else { auto tex = new osg::Texture2D(); tex->setTextureSize(width, height); tex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); tex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); return tex; } } } osg::FrameBufferAttachment createMultiviewCompatibleAttachment(osg::Texture* tex) { switch (tex->getTextureTarget()) { case GL_TEXTURE_2D: { auto* tex2d = static_cast<osg::Texture2D*>(tex); return osg::FrameBufferAttachment(tex2d); } case GL_TEXTURE_2D_MULTISAMPLE: { auto* tex2dMsaa = static_cast<osg::Texture2DMultisample*>(tex); return osg::FrameBufferAttachment(tex2dMsaa); } #ifdef OSG_HAS_MULTIVIEW case GL_TEXTURE_2D_ARRAY: { auto* tex2dArray = static_cast<osg::Texture2DArray*>(tex); return osg::FrameBufferAttachment(tex2dArray, osg::Camera::FACE_CONTROLLED_BY_MULTIVIEW_SHADER, 0); } case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: { auto* tex2dMsaaArray = static_cast<osg::Texture2DMultisampleArray*>(tex); return osg::FrameBufferAttachment(tex2dMsaaArray, osg::Camera::FACE_CONTROLLED_BY_MULTIVIEW_SHADER, 0); } #endif default: throw std::logic_error("Invalid texture type received"); } } unsigned int osgFaceControlledByMultiviewShader() { #ifdef OSG_HAS_MULTIVIEW return osg::Camera::FACE_CONTROLLED_BY_MULTIVIEW_SHADER; #else return 0; #endif } class UpdateRenderStagesCallback : public SceneUtil::NodeCallback<UpdateRenderStagesCallback, osg::Node*, osgUtil::CullVisitor*> { public: UpdateRenderStagesCallback(Stereo::MultiviewFramebuffer* multiviewFramebuffer) : mMultiviewFramebuffer(multiviewFramebuffer) { mViewport = new osg::Viewport(0, 0, multiviewFramebuffer->width(), multiviewFramebuffer->height()); mViewportStateset = new osg::StateSet(); mViewportStateset->setAttribute(mViewport.get()); } void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { osgUtil::RenderStage* renderStage = cv->getCurrentRenderStage(); bool msaa = mMultiviewFramebuffer->samples() > 1; if (!Stereo::getMultiview()) { auto eye = static_cast<int>(Stereo::Manager::instance().getEye(cv)); if (msaa) { renderStage->setFrameBufferObject(mMultiviewFramebuffer->layerMsaaFbo(eye)); renderStage->setMultisampleResolveFramebufferObject(mMultiviewFramebuffer->layerFbo(eye)); } else { renderStage->setFrameBufferObject(mMultiviewFramebuffer->layerFbo(eye)); } } // OSG tries to do a horizontal split, but we want to render to separate framebuffers instead. renderStage->setViewport(mViewport); cv->pushStateSet(mViewportStateset.get()); traverse(node, cv); cv->popStateSet(); } private: Stereo::MultiviewFramebuffer* mMultiviewFramebuffer; osg::ref_ptr<osg::Viewport> mViewport; osg::ref_ptr<osg::StateSet> mViewportStateset; }; MultiviewFramebuffer::MultiviewFramebuffer(int width, int height, int samples) : mWidth(width) , mHeight(height) , mSamples(samples) , mMultiview(getMultiview()) , mMultiviewFbo{ new osg::FrameBufferObject } , mLayerFbo{ new osg::FrameBufferObject, new osg::FrameBufferObject } , mLayerMsaaFbo{ new osg::FrameBufferObject, new osg::FrameBufferObject } { } MultiviewFramebuffer::~MultiviewFramebuffer() {} void MultiviewFramebuffer::attachColorComponent(GLint sourceFormat, GLint sourceType, GLint internalFormat) { if (mMultiview) { #ifdef OSG_HAS_MULTIVIEW mMultiviewColorTexture = createTextureArray(sourceFormat, sourceType, internalFormat); mMultiviewFbo->setAttachment(osg::Camera::COLOR_BUFFER, osg::FrameBufferAttachment( mMultiviewColorTexture, osg::Camera::FACE_CONTROLLED_BY_MULTIVIEW_SHADER, 0)); for (unsigned i = 0; i < 2; i++) { mColorTexture[i] = createTextureView_Texture2DFromTexture2DArray(mMultiviewColorTexture.get(), i); mLayerFbo[i]->setAttachment(osg::Camera::COLOR_BUFFER, osg::FrameBufferAttachment(mColorTexture[i])); } #endif } else { for (unsigned i = 0; i < 2; i++) { if (mSamples > 1) mLayerMsaaFbo[i]->setAttachment(osg::Camera::COLOR_BUFFER, osg::FrameBufferAttachment(new osg::RenderBuffer(mWidth, mHeight, internalFormat, mSamples))); mColorTexture[i] = createTexture(sourceFormat, sourceType, internalFormat); mLayerFbo[i]->setAttachment(osg::Camera::COLOR_BUFFER, osg::FrameBufferAttachment(mColorTexture[i])); } } } void MultiviewFramebuffer::attachDepthComponent(GLint sourceFormat, GLint sourceType, GLint internalFormat) { if (mMultiview) { #ifdef OSG_HAS_MULTIVIEW mMultiviewDepthTexture = createTextureArray(sourceFormat, sourceType, internalFormat); mMultiviewFbo->setAttachment(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER, osg::FrameBufferAttachment( mMultiviewDepthTexture, osg::Camera::FACE_CONTROLLED_BY_MULTIVIEW_SHADER, 0)); for (unsigned i = 0; i < 2; i++) { mDepthTexture[i] = createTextureView_Texture2DFromTexture2DArray(mMultiviewDepthTexture.get(), i); mLayerFbo[i]->setAttachment( osg::Camera::PACKED_DEPTH_STENCIL_BUFFER, osg::FrameBufferAttachment(mDepthTexture[i])); } #endif } else { for (unsigned i = 0; i < 2; i++) { if (mSamples > 1) mLayerMsaaFbo[i]->setAttachment(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER, osg::FrameBufferAttachment(new osg::RenderBuffer(mWidth, mHeight, internalFormat, mSamples))); mDepthTexture[i] = createTexture(sourceFormat, sourceType, internalFormat); mLayerFbo[i]->setAttachment( osg::Camera::PACKED_DEPTH_STENCIL_BUFFER, osg::FrameBufferAttachment(mDepthTexture[i])); } } } osg::FrameBufferObject* MultiviewFramebuffer::multiviewFbo() { return mMultiviewFbo; } osg::FrameBufferObject* MultiviewFramebuffer::layerFbo(int i) { return mLayerFbo[i]; } osg::FrameBufferObject* MultiviewFramebuffer::layerMsaaFbo(int i) { return mLayerMsaaFbo[i]; } osg::Texture2DArray* MultiviewFramebuffer::multiviewColorBuffer() { return mMultiviewColorTexture; } osg::Texture2DArray* MultiviewFramebuffer::multiviewDepthBuffer() { return mMultiviewDepthTexture; } osg::Texture2D* MultiviewFramebuffer::layerColorBuffer(int i) { return mColorTexture[i]; } osg::Texture2D* MultiviewFramebuffer::layerDepthBuffer(int i) { return mDepthTexture[i]; } void MultiviewFramebuffer::attachTo(osg::Camera* camera) { #ifdef OSG_HAS_MULTIVIEW if (mMultiview) { if (mMultiviewColorTexture) { camera->attach(osg::Camera::COLOR_BUFFER, mMultiviewColorTexture, 0, osg::Camera::FACE_CONTROLLED_BY_MULTIVIEW_SHADER, false, mSamples); camera->getBufferAttachmentMap()[osg::Camera::COLOR_BUFFER]._internalFormat = mMultiviewColorTexture->getInternalFormat(); camera->getBufferAttachmentMap()[osg::Camera::COLOR_BUFFER]._mipMapGeneration = false; } if (mMultiviewDepthTexture) { camera->attach(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER, mMultiviewDepthTexture, 0, osg::Camera::FACE_CONTROLLED_BY_MULTIVIEW_SHADER, false, mSamples); camera->getBufferAttachmentMap()[osg::Camera::PACKED_DEPTH_STENCIL_BUFFER]._internalFormat = mMultiviewDepthTexture->getInternalFormat(); camera->getBufferAttachmentMap()[osg::Camera::PACKED_DEPTH_STENCIL_BUFFER]._mipMapGeneration = false; } } #endif camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); if (!mCullCallback) mCullCallback = new UpdateRenderStagesCallback(this); camera->addCullCallback(mCullCallback); } void MultiviewFramebuffer::detachFrom(osg::Camera* camera) { #ifdef OSG_HAS_MULTIVIEW if (mMultiview) { if (mMultiviewColorTexture) { camera->detach(osg::Camera::COLOR_BUFFER); } if (mMultiviewDepthTexture) { camera->detach(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER); } } #endif camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER); if (mCullCallback) camera->removeCullCallback(mCullCallback); } osg::Texture2D* MultiviewFramebuffer::createTexture(GLint sourceFormat, GLint sourceType, GLint internalFormat) { osg::Texture2D* texture = new osg::Texture2D; texture->setTextureSize(mWidth, mHeight); texture->setSourceFormat(sourceFormat); texture->setSourceType(sourceType); texture->setInternalFormat(internalFormat); texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE); return texture; } osg::Texture2DArray* MultiviewFramebuffer::createTextureArray( GLint sourceFormat, GLint sourceType, GLint internalFormat) { osg::Texture2DArray* textureArray = new osg::Texture2DArray; textureArray->setTextureSize(mWidth, mHeight, 2); textureArray->setSourceFormat(sourceFormat); textureArray->setSourceType(sourceType); textureArray->setInternalFormat(internalFormat); textureArray->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); textureArray->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); textureArray->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); textureArray->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); textureArray->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE); return textureArray; } osg::FrameBufferAttachment makeSingleLayerAttachmentFromMultilayerAttachment( osg::FrameBufferAttachment attachment, int layer) { osg::Texture* tex = attachment.getTexture(); if (tex->getTextureTarget() == GL_TEXTURE_2D_ARRAY) return osg::FrameBufferAttachment(static_cast<osg::Texture2DArray*>(tex), layer, 0); #ifdef OSG_HAS_MULTIVIEW if (tex->getTextureTarget() == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) return osg::FrameBufferAttachment(static_cast<osg::Texture2DMultisampleArray*>(tex), layer, 0); #endif Log(Debug::Error) << "Attempted to extract a layer from an unlayered texture"; return osg::FrameBufferAttachment(); } MultiviewFramebufferResolve::MultiviewFramebufferResolve( osg::FrameBufferObject* msaaFbo, osg::FrameBufferObject* resolveFbo, GLbitfield blitMask) : mResolveFbo(resolveFbo) , mMsaaFbo(msaaFbo) , mBlitMask(blitMask) { } void MultiviewFramebufferResolve::setResolveFbo(osg::FrameBufferObject* resolveFbo) { if (resolveFbo != mResolveFbo) dirty(); mResolveFbo = resolveFbo; } void MultiviewFramebufferResolve::setMsaaFbo(osg::FrameBufferObject* msaaFbo) { if (msaaFbo != mMsaaFbo) dirty(); mMsaaFbo = msaaFbo; } void MultiviewFramebufferResolve::resolveImplementation(osg::State& state) { if (mDirtyLayers) setupLayers(); osg::GLExtensions* ext = state.get<osg::GLExtensions>(); for (int view : { 0, 1 }) { mResolveLayers[view]->apply(state, osg::FrameBufferObject::BindTarget::DRAW_FRAMEBUFFER); mMsaaLayers[view]->apply(state, osg::FrameBufferObject::BindTarget::READ_FRAMEBUFFER); ext->glBlitFramebuffer(0, 0, mWidth, mHeight, 0, 0, mWidth, mHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); } } void MultiviewFramebufferResolve::setupLayers() { mDirtyLayers = false; std::vector<osg::FrameBufferObject::BufferComponent> components; if (mBlitMask & GL_DEPTH_BUFFER_BIT) components.push_back(osg::FrameBufferObject::BufferComponent::PACKED_DEPTH_STENCIL_BUFFER); if (mBlitMask & GL_COLOR_BUFFER_BIT) components.push_back(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER); mMsaaLayers = { new osg::FrameBufferObject, new osg::FrameBufferObject }; mResolveLayers = { new osg::FrameBufferObject, new osg::FrameBufferObject }; for (auto component : components) { const auto& msaaAttachment = mMsaaFbo->getAttachment(component); mMsaaLayers[0]->setAttachment( component, makeSingleLayerAttachmentFromMultilayerAttachment(msaaAttachment, 0)); mMsaaLayers[1]->setAttachment( component, makeSingleLayerAttachmentFromMultilayerAttachment(msaaAttachment, 1)); const auto& resolveAttachment = mResolveFbo->getAttachment(component); mResolveLayers[0]->setAttachment( component, makeSingleLayerAttachmentFromMultilayerAttachment(resolveAttachment, 0)); mResolveLayers[1]->setAttachment( component, makeSingleLayerAttachmentFromMultilayerAttachment(resolveAttachment, 1)); mWidth = msaaAttachment.getTexture()->getTextureWidth(); mHeight = msaaAttachment.getTexture()->getTextureHeight(); } } #ifdef OSG_HAS_MULTIVIEW namespace { struct MultiviewFrustumCallback final : public osg::CullSettings::InitialFrustumCallback { MultiviewFrustumCallback(Stereo::InitialFrustumCallback* ifc) : mIfc(ifc) { } void setInitialFrustum(osg::CullStack& cullStack, osg::Polytope& frustum) const override { bool nearCulling = false; bool farCulling = false; osg::BoundingBoxd bb; mIfc->setInitialFrustum(cullStack, bb, nearCulling, farCulling); frustum.setToBoundingBox(bb, nearCulling, farCulling); } Stereo::InitialFrustumCallback* mIfc; }; } #endif InitialFrustumCallback::InitialFrustumCallback(osg::Camera* camera) : mCamera(camera) { #ifdef OSG_HAS_MULTIVIEW camera->setInitialFrustumCallback(new MultiviewFrustumCallback(this)); #endif } InitialFrustumCallback::~InitialFrustumCallback() { #ifdef OSG_HAS_MULTIVIEW osg::ref_ptr<osg::Camera> camera; if (mCamera.lock(camera)) camera->setInitialFrustumCallback(nullptr); #endif } }
32,948
C++
.cpp
754
33.108753
120
0.626896
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,452
serialization.cpp
OpenMW_openmw/components/detournavigator/serialization.cpp
#include "serialization.hpp" #include "agentbounds.hpp" #include "dbrefgeometryobject.hpp" #include "preparednavmeshdata.hpp" #include "recast.hpp" #include "recastmesh.hpp" #include "settings.hpp" #include "tilebounds.hpp" #include <components/serialization/binaryreader.hpp> #include <components/serialization/binarywriter.hpp> #include <components/serialization/format.hpp> #include <components/serialization/sizeaccumulator.hpp> #include <cstddef> #include <cstring> #include <type_traits> #include <vector> namespace DetourNavigator { namespace { template <Serialization::Mode mode> struct Format : Serialization::Format<mode, Format<mode>> { using Serialization::Format<mode, Format<mode>>::operator(); template <class Visitor> void operator()(Visitor&& visitor, const osg::Vec2i& value) const { visitor(*this, value.ptr(), 2); } template <class Visitor> void operator()(Visitor&& visitor, const osg::Vec2f& value) const { visitor(*this, value.ptr(), 2); } template <class Visitor> void operator()(Visitor&& visitor, const osg::Vec3f& value) const { visitor(*this, value.ptr(), 3); } template <class Visitor> void operator()(Visitor&& visitor, const Water& value) const { visitor(*this, value.mCellSize); visitor(*this, value.mLevel); } template <class Visitor> void operator()(Visitor&& visitor, const CellWater& value) const { visitor(*this, value.mCellPosition); visitor(*this, value.mWater); } template <class Visitor> void operator()(Visitor&& visitor, const RecastSettings& value) const { visitor(*this, value.mCellHeight); visitor(*this, value.mCellSize); visitor(*this, value.mDetailSampleDist); visitor(*this, value.mDetailSampleMaxError); visitor(*this, value.mMaxClimb); visitor(*this, value.mMaxSimplificationError); visitor(*this, value.mMaxSlope); visitor(*this, value.mRecastScaleFactor); visitor(*this, value.mSwimHeightScale); visitor(*this, value.mBorderSize); visitor(*this, value.mMaxEdgeLen); visitor(*this, value.mMaxVertsPerPoly); visitor(*this, value.mRegionMergeArea); visitor(*this, value.mRegionMinArea); visitor(*this, value.mTileSize); } template <class Visitor> void operator()(Visitor&& visitor, const TileBounds& value) const { visitor(*this, value.mMin); visitor(*this, value.mMax); } template <class Visitor> void operator()(Visitor&& visitor, const Heightfield& value) const { visitor(*this, value.mCellPosition); visitor(*this, value.mCellSize); visitor(*this, value.mLength); visitor(*this, value.mMinHeight); visitor(*this, value.mMaxHeight); visitor(*this, value.mHeights); visitor(*this, value.mOriginalSize); visitor(*this, value.mMinX); visitor(*this, value.mMinY); } template <class Visitor> void operator()(Visitor&& visitor, const FlatHeightfield& value) const { visitor(*this, value.mCellPosition); visitor(*this, value.mCellSize); visitor(*this, value.mHeight); } template <class Visitor> void operator()(Visitor&& visitor, const RecastMesh& value) const { visitor(*this, value.getWater()); visitor(*this, value.getHeightfields()); visitor(*this, value.getFlatHeightfields()); } template <class Visitor> void operator()(Visitor&& visitor, const ESM::Position& value) const { visitor(*this, value.pos); visitor(*this, value.rot); } template <class Visitor> void operator()(Visitor&& visitor, const ObjectTransform& value) const { visitor(*this, value.mPosition); visitor(*this, value.mScale); } template <class Visitor> void operator()(Visitor&& visitor, const DbRefGeometryObject& value) const { visitor(*this, value.mShapeId); visitor(*this, value.mObjectTransform); } template <class Visitor> void operator()(Visitor&& visitor, const RecastSettings& settings, const AgentBounds& agentBounds, const RecastMesh& recastMesh, const std::vector<DbRefGeometryObject>& dbRefGeometryObjects) const { visitor(*this, DetourNavigator::recastMeshMagic); visitor(*this, DetourNavigator::recastMeshVersion); visitor(*this, settings); visitor(*this, agentBounds); visitor(*this, recastMesh); visitor(*this, dbRefGeometryObjects); } template <class Visitor, class T> auto operator()(Visitor&& visitor, T& value) const -> std::enable_if_t<std::is_same_v<std::decay_t<T>, rcPolyMesh>> { visitor(*this, value.nverts); visitor(*this, value.npolys); visitor(*this, value.maxpolys); visitor(*this, value.nvp); visitor(*this, value.bmin); visitor(*this, value.bmax); visitor(*this, value.cs); visitor(*this, value.ch); visitor(*this, value.borderSize); visitor(*this, value.maxEdgeError); if constexpr (mode == Serialization::Mode::Read) { if (value.verts == nullptr) permRecastAlloc(value.verts, getVertsLength(value)); if (value.polys == nullptr) permRecastAlloc(value.polys, getPolysLength(value)); if (value.regs == nullptr) permRecastAlloc(value.regs, getRegsLength(value)); if (value.flags == nullptr) permRecastAlloc(value.flags, getFlagsLength(value)); if (value.areas == nullptr) permRecastAlloc(value.areas, getAreasLength(value)); } visitor(*this, value.verts, getVertsLength(value)); visitor(*this, value.polys, getPolysLength(value)); visitor(*this, value.regs, getRegsLength(value)); visitor(*this, value.flags, getFlagsLength(value)); visitor(*this, value.areas, getAreasLength(value)); } template <class Visitor, class T> auto operator()(Visitor&& visitor, T& value) const -> std::enable_if_t<std::is_same_v<std::decay_t<T>, rcPolyMeshDetail>> { visitor(*this, value.nmeshes); if constexpr (mode == Serialization::Mode::Read) if (value.meshes == nullptr) permRecastAlloc(value.meshes, getMeshesLength(value)); visitor(*this, value.meshes, getMeshesLength(value)); visitor(*this, value.nverts); if constexpr (mode == Serialization::Mode::Read) if (value.verts == nullptr) permRecastAlloc(value.verts, getVertsLength(value)); visitor(*this, value.verts, getVertsLength(value)); visitor(*this, value.ntris); if constexpr (mode == Serialization::Mode::Read) if (value.tris == nullptr) permRecastAlloc(value.tris, getTrisLength(value)); visitor(*this, value.tris, getTrisLength(value)); } template <class Visitor, class T> auto operator()(Visitor&& visitor, T& value) const -> std::enable_if_t<std::is_same_v<std::decay_t<T>, PreparedNavMeshData>> { if constexpr (mode == Serialization::Mode::Write) { visitor(*this, DetourNavigator::preparedNavMeshDataMagic); visitor(*this, DetourNavigator::preparedNavMeshDataVersion); } else { static_assert(mode == Serialization::Mode::Read); char magic[std::size(DetourNavigator::preparedNavMeshDataMagic)]; visitor(*this, magic); if (std::memcmp(magic, DetourNavigator::preparedNavMeshDataMagic, sizeof(magic)) != 0) throw std::runtime_error("Bad PreparedNavMeshData magic"); std::uint32_t version = 0; visitor(*this, version); if (version != DetourNavigator::preparedNavMeshDataVersion) throw std::runtime_error("Bad PreparedNavMeshData version"); } visitor(*this, value.mUserId); visitor(*this, value.mCellSize); visitor(*this, value.mCellHeight); visitor(*this, value.mPolyMesh); visitor(*this, value.mPolyMeshDetail); } template <class Visitor> void operator()(Visitor&& visitor, const AgentBounds& value) const { visitor(*this, value.mShapeType); visitor(*this, value.mHalfExtents); } }; } } // namespace DetourNavigator namespace DetourNavigator { std::vector<std::byte> serialize(const RecastSettings& settings, const AgentBounds& agentBounds, const RecastMesh& recastMesh, const std::vector<DbRefGeometryObject>& dbRefGeometryObjects) { constexpr Format<Serialization::Mode::Write> format; Serialization::SizeAccumulator sizeAccumulator; format(sizeAccumulator, settings, agentBounds, recastMesh, dbRefGeometryObjects); std::vector<std::byte> result(sizeAccumulator.value()); format(Serialization::BinaryWriter(result.data(), result.data() + result.size()), settings, agentBounds, recastMesh, dbRefGeometryObjects); return result; } std::vector<std::byte> serialize(const PreparedNavMeshData& value) { constexpr Format<Serialization::Mode::Write> format; Serialization::SizeAccumulator sizeAccumulator; format(sizeAccumulator, value); std::vector<std::byte> result(sizeAccumulator.value()); format(Serialization::BinaryWriter(result.data(), result.data() + result.size()), value); return result; } bool deserialize(const std::vector<std::byte>& data, PreparedNavMeshData& value) { try { constexpr Format<Serialization::Mode::Read> format; format(Serialization::BinaryReader(data.data(), data.data() + data.size()), value); return true; } catch (const std::exception&) { return false; } } }
11,674
C++
.cpp
257
31.610895
113
0.561447
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,453
recastmeshobject.cpp
OpenMW_openmw/components/detournavigator/recastmeshobject.cpp
#include "recastmeshobject.hpp" #include <BulletCollision/CollisionShapes/btCompoundShape.h> #include <cassert> namespace DetourNavigator { namespace { bool updateCompoundObject( const btCompoundShape& shape, const AreaType areaType, std::vector<ChildRecastMeshObject>& children) { assert(static_cast<std::size_t>(shape.getNumChildShapes()) == children.size()); bool result = false; for (int i = 0, num = shape.getNumChildShapes(); i < num; ++i) { assert(shape.getChildShape(i) == std::addressof(children[static_cast<std::size_t>(i)].getShape())); result = children[static_cast<std::size_t>(i)].update(shape.getChildTransform(i), areaType) || result; } return result; } std::vector<ChildRecastMeshObject> makeChildrenObjects(const btCompoundShape& shape, const AreaType areaType) { std::vector<ChildRecastMeshObject> result; for (int i = 0, num = shape.getNumChildShapes(); i < num; ++i) result.emplace_back(*shape.getChildShape(i), shape.getChildTransform(i), areaType); return result; } std::vector<ChildRecastMeshObject> makeChildrenObjects(const btCollisionShape& shape, const AreaType areaType) { if (shape.isCompound()) return makeChildrenObjects(static_cast<const btCompoundShape&>(shape), areaType); return {}; } } ChildRecastMeshObject::ChildRecastMeshObject( const btCollisionShape& shape, const btTransform& transform, const AreaType areaType) : mShape(shape) , mTransform(transform) , mAreaType(areaType) , mLocalScaling(shape.getLocalScaling()) , mChildren(makeChildrenObjects(shape, mAreaType)) { } bool ChildRecastMeshObject::update(const btTransform& transform, const AreaType areaType) { bool result = false; if (!(mTransform == transform)) { mTransform = transform; result = true; } if (mAreaType != areaType) { mAreaType = areaType; result = true; } if (!(mLocalScaling == mShape.get().getLocalScaling())) { mLocalScaling = mShape.get().getLocalScaling(); result = true; } if (mShape.get().isCompound()) result = updateCompoundObject(static_cast<const btCompoundShape&>(mShape.get()), mAreaType, mChildren) || result; return result; } RecastMeshObject::RecastMeshObject( const CollisionShape& shape, const btTransform& transform, const AreaType areaType) : mInstance(shape.getInstance()) , mObjectTransform(shape.getObjectTransform()) , mImpl(shape.getShape(), transform, areaType) { } }
2,919
C++
.cpp
73
30.60274
118
0.624736
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,454
makenavmesh.cpp
OpenMW_openmw/components/detournavigator/makenavmesh.cpp
#include "makenavmesh.hpp" #include "debug.hpp" #include "exceptions.hpp" #include "flags.hpp" #include "navmeshdata.hpp" #include "navmeshdb.hpp" #include "navmeshtilescache.hpp" #include "offmeshconnection.hpp" #include "preparednavmeshdata.hpp" #include "recastcontext.hpp" #include "recastmesh.hpp" #include "recastmeshbuilder.hpp" #include "recastparams.hpp" #include "settings.hpp" #include "settingsutils.hpp" #include "components/debug/debuglog.hpp" #include <DetourNavMesh.h> #include <DetourNavMeshBuilder.h> #include <Recast.h> #include <algorithm> #include <array> #include <iomanip> #include <limits> namespace DetourNavigator { namespace { constexpr int walkableRadiusUpperLimit = 255; struct Rectangle { TileBounds mBounds; float mHeight; }; std::vector<float> getOffMeshVerts(const std::vector<OffMeshConnection>& connections) { std::vector<float> result; result.reserve(connections.size() * 6); const auto add = [&](const osg::Vec3f& v) { result.push_back(v.x()); result.push_back(v.y()); result.push_back(v.z()); }; for (const auto& v : connections) { add(v.mStart); add(v.mEnd); } return result; } Flag getFlag(AreaType areaType) { switch (areaType) { case AreaType_null: return Flag_none; case AreaType_ground: return Flag_walk; case AreaType_water: return Flag_swim; case AreaType_door: return Flag_openDoor; case AreaType_pathgrid: return Flag_usePathgrid; } return Flag_none; } std::vector<unsigned char> getOffMeshConAreas(const std::vector<OffMeshConnection>& connections) { std::vector<unsigned char> result; result.reserve(connections.size()); std::transform(connections.begin(), connections.end(), std::back_inserter(result), [](const OffMeshConnection& v) { return v.mAreaType; }); return result; } std::vector<unsigned short> getOffMeshFlags(const std::vector<OffMeshConnection>& connections) { std::vector<unsigned short> result; result.reserve(connections.size()); std::transform(connections.begin(), connections.end(), std::back_inserter(result), [](const OffMeshConnection& v) { return getFlag(v.mAreaType); }); return result; } float getHeight(const RecastSettings& settings, const AgentBounds& agentBounds) { return getAgentHeight(agentBounds) * settings.mRecastScaleFactor; } float getMaxClimb(const RecastSettings& settings) { return settings.mMaxClimb * settings.mRecastScaleFactor; } float getRadius(const RecastSettings& settings, const AgentBounds& agentBounds) { return getAgentRadius(agentBounds) * settings.mRecastScaleFactor; } float getSwimLevel(const RecastSettings& settings, const float waterLevel, const float agentHalfExtentsZ) { return waterLevel - settings.mSwimHeightScale * agentHalfExtentsZ - agentHalfExtentsZ; } int getWalkableHeight(const RecastSettings& settings, const AgentBounds& agentBounds) { return static_cast<int>(std::ceil(getHeight(settings, agentBounds) / settings.mCellHeight)); } int getWalkableRadius(const RecastSettings& settings, const AgentBounds& agentBounds) { return static_cast<int>(std::ceil(getRadius(settings, agentBounds) / settings.mCellSize)); } struct RecastParams { float mSampleDist = 0; float mSampleMaxError = 0; int mMaxEdgeLen = 0; int mWalkableClimb = 0; int mWalkableHeight = 0; int mWalkableRadius = 0; }; RecastParams makeRecastParams(const RecastSettings& settings, const AgentBounds& agentBounds) { RecastParams result; result.mWalkableHeight = getWalkableHeight(settings, agentBounds); result.mWalkableClimb = static_cast<int>(std::floor(getMaxClimb(settings) / settings.mCellHeight)); result.mWalkableRadius = getWalkableRadius(settings, agentBounds); result.mMaxEdgeLen = static_cast<int>(std::round(static_cast<float>(settings.mMaxEdgeLen) / settings.mCellSize)); result.mSampleDist = settings.mDetailSampleDist < 0.9f ? 0 : settings.mCellSize * settings.mDetailSampleDist; result.mSampleMaxError = settings.mCellHeight * settings.mDetailSampleMaxError; return result; } [[nodiscard]] bool initHeightfield(RecastContext& context, const TilePosition& tilePosition, float minZ, float maxZ, const RecastSettings& settings, rcHeightfield& solid) { const int size = settings.mTileSize + settings.mBorderSize * 2; const int width = size; const int height = size; const float halfBoundsSize = size * settings.mCellSize * 0.5f; const osg::Vec2f shift = osg::Vec2f(tilePosition.x() + 0.5f, tilePosition.y() + 0.5f) * getTileSize(settings); const osg::Vec3f bmin(shift.x() - halfBoundsSize, minZ, shift.y() - halfBoundsSize); const osg::Vec3f bmax(shift.x() + halfBoundsSize, maxZ, shift.y() + halfBoundsSize); if (size < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid size to init heightfield: " << size; return false; } if (settings.mCellHeight <= 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid cell height to init heightfield: " << settings.mCellHeight; return false; } if (settings.mCellSize <= 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid cell size to init heightfield: " << settings.mCellSize; return false; } return rcCreateHeightfield( &context, solid, width, height, bmin.ptr(), bmax.ptr(), settings.mCellSize, settings.mCellHeight); } bool isSupportedCoordinate(float value) { constexpr float maxVertexCoordinate = static_cast<float>(1 << 22); return -maxVertexCoordinate < value && value < maxVertexCoordinate; } template <class Iterator> bool isSupportedCoordinates(Iterator begin, Iterator end) { return std::all_of(begin, end, isSupportedCoordinate); } [[nodiscard]] bool rasterizeTriangles(RecastContext& context, const Mesh& mesh, const RecastSettings& settings, const RecastParams& params, rcHeightfield& solid) { std::vector<unsigned char> areas(mesh.getAreaTypes().begin(), mesh.getAreaTypes().end()); std::vector<float> vertices = mesh.getVertices(); constexpr std::size_t verticesPerTriangle = 3; for (std::size_t i = 0; i < vertices.size(); i += verticesPerTriangle) { for (std::size_t j = 0; j < verticesPerTriangle; ++j) { const float coordinate = toNavMeshCoordinates(settings, vertices[i + j]); if (!isSupportedCoordinate(coordinate)) return false; vertices[i + j] = coordinate; } std::swap(vertices[i + 1], vertices[i + 2]); } rcClearUnwalkableTriangles(&context, settings.mMaxSlope, vertices.data(), static_cast<int>(mesh.getVerticesCount()), mesh.getIndices().data(), static_cast<int>(areas.size()), areas.data()); return rcRasterizeTriangles(&context, vertices.data(), static_cast<int>(mesh.getVerticesCount()), mesh.getIndices().data(), areas.data(), static_cast<int>(areas.size()), solid, params.mWalkableClimb); } [[nodiscard]] bool rasterizeTriangles(RecastContext& context, const Rectangle& rectangle, AreaType areaType, const RecastParams& params, rcHeightfield& solid) { const std::array vertices{ rectangle.mBounds.mMin.x(), rectangle.mHeight, rectangle.mBounds.mMin.y(), // vertex 0 rectangle.mBounds.mMin.x(), rectangle.mHeight, rectangle.mBounds.mMax.y(), // vertex 1 rectangle.mBounds.mMax.x(), rectangle.mHeight, rectangle.mBounds.mMax.y(), // vertex 2 rectangle.mBounds.mMax.x(), rectangle.mHeight, rectangle.mBounds.mMin.y(), // vertex 3 }; if (!isSupportedCoordinates(vertices.begin(), vertices.end())) return false; const std::array indices{ 0, 1, 2, // triangle 0 0, 2, 3, // triangle 1 }; const std::array<unsigned char, 2> areas{ areaType, areaType }; return rcRasterizeTriangles(&context, vertices.data(), static_cast<int>(vertices.size() / 3), indices.data(), areas.data(), static_cast<int>(areas.size()), solid, params.mWalkableClimb); } [[nodiscard]] bool rasterizeTriangles(RecastContext& context, float agentHalfExtentsZ, const std::vector<CellWater>& water, const RecastSettings& settings, const RecastParams& params, const TileBounds& realTileBounds, rcHeightfield& solid) { for (const CellWater& cellWater : water) { const TileBounds cellTileBounds = maxCellTileBounds(cellWater.mCellPosition, cellWater.mWater.mCellSize); if (auto intersection = getIntersection(realTileBounds, cellTileBounds)) { const Rectangle rectangle{ toNavMeshCoordinates(settings, *intersection), toNavMeshCoordinates( settings, getSwimLevel(settings, cellWater.mWater.mLevel, agentHalfExtentsZ)) }; if (!rasterizeTriangles(context, rectangle, AreaType_water, params, solid)) return false; } } return true; } [[nodiscard]] bool rasterizeTriangles(RecastContext& context, const TileBounds& realTileBounds, const std::vector<FlatHeightfield>& heightfields, const RecastSettings& settings, const RecastParams& params, rcHeightfield& solid) { for (const FlatHeightfield& heightfield : heightfields) { const TileBounds cellTileBounds = maxCellTileBounds(heightfield.mCellPosition, heightfield.mCellSize); if (auto intersection = getIntersection(realTileBounds, cellTileBounds)) { const Rectangle rectangle{ toNavMeshCoordinates(settings, *intersection), toNavMeshCoordinates(settings, heightfield.mHeight) }; if (!rasterizeTriangles(context, rectangle, AreaType_ground, params, solid)) return false; } } return true; } [[nodiscard]] bool rasterizeTriangles(RecastContext& context, const std::vector<Heightfield>& heightfields, const RecastSettings& settings, const RecastParams& params, rcHeightfield& solid) { for (const Heightfield& heightfield : heightfields) { const Mesh mesh = makeMesh(heightfield); if (!rasterizeTriangles(context, mesh, settings, params, solid)) return false; } return true; } [[nodiscard]] bool rasterizeTriangles(RecastContext& context, const TilePosition& tilePosition, float agentHalfExtentsZ, const RecastMesh& recastMesh, const RecastSettings& settings, const RecastParams& params, rcHeightfield& solid) { const TileBounds realTileBounds = makeRealTileBoundsWithBorder(settings, tilePosition); return rasterizeTriangles(context, recastMesh.getMesh(), settings, params, solid) && rasterizeTriangles( context, agentHalfExtentsZ, recastMesh.getWater(), settings, params, realTileBounds, solid) && rasterizeTriangles(context, recastMesh.getHeightfields(), settings, params, solid) && rasterizeTriangles( context, realTileBounds, recastMesh.getFlatHeightfields(), settings, params, solid); } bool isValidWalkableHeight(int value) { return value >= 3; } [[nodiscard]] bool buildCompactHeightfield(RecastContext& context, const int walkableHeight, const int walkableClimb, rcHeightfield& solid, rcCompactHeightfield& compact) { if (!isValidWalkableHeight(walkableHeight)) { Log(Debug::Warning) << context.getPrefix() << "Invalid walkableHeight to build compact heightfield: " << walkableHeight; return false; } if (walkableClimb < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid walkableClimb to build compact heightfield: " << walkableClimb; return false; } return rcBuildCompactHeightfield(&context, walkableHeight, walkableClimb, solid, compact); } bool isValidWalkableRadius(int value) { return 0 < value && value < walkableRadiusUpperLimit; } [[nodiscard]] bool erodeWalkableArea(RecastContext& context, int walkableRadius, rcCompactHeightfield& compact) { if (!isValidWalkableRadius(walkableRadius)) { Log(Debug::Warning) << context.getPrefix() << "Invalid walkableRadius to erode walkable area: " << walkableRadius; return false; } return rcErodeWalkableArea(&context, walkableRadius, compact); } [[nodiscard]] bool buildDistanceField(RecastContext& context, rcCompactHeightfield& compact) { return rcBuildDistanceField(&context, compact); } [[nodiscard]] bool buildRegions(RecastContext& context, rcCompactHeightfield& compact, const int borderSize, const int minRegionArea, const int mergeRegionArea) { if (borderSize < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid borderSize to build regions: " << borderSize; return false; } if (minRegionArea < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid minRegionArea to build regions: " << minRegionArea; return false; } if (mergeRegionArea < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid mergeRegionArea to build regions: " << mergeRegionArea; return false; } return rcBuildRegions(&context, compact, borderSize, minRegionArea, mergeRegionArea); } [[nodiscard]] bool buildContours(RecastContext& context, rcCompactHeightfield& compact, const float maxError, const int maxEdgeLen, rcContourSet& contourSet, const int buildFlags = RC_CONTOUR_TESS_WALL_EDGES) { if (maxError < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid maxError to build contours: " << maxError; return false; } if (maxEdgeLen < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid maxEdgeLen to build contours: " << maxEdgeLen; return false; } return rcBuildContours(&context, compact, maxError, maxEdgeLen, contourSet, buildFlags); } [[nodiscard]] bool buildPolyMesh( RecastContext& context, rcContourSet& contourSet, const int maxVertsPerPoly, rcPolyMesh& polyMesh) { if (maxVertsPerPoly < 3) { Log(Debug::Warning) << context.getPrefix() << "Invalid maxVertsPerPoly to build poly mesh: " << maxVertsPerPoly; return false; } return rcBuildPolyMesh(&context, contourSet, maxVertsPerPoly, polyMesh); } [[nodiscard]] bool buildPolyMeshDetail(RecastContext& context, const rcPolyMesh& polyMesh, const rcCompactHeightfield& compact, const float sampleDist, const float sampleMaxError, rcPolyMeshDetail& polyMeshDetail) { if (sampleDist < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid sampleDist to build poly mesh detail: " << sampleDist; return false; } if (sampleMaxError < 0) { Log(Debug::Warning) << context.getPrefix() << "Invalid sampleMaxError to build poly mesh detail: " << sampleMaxError; return false; } return rcBuildPolyMeshDetail(&context, polyMesh, compact, sampleDist, sampleMaxError, polyMeshDetail); } void setPolyMeshFlags(rcPolyMesh& polyMesh) { for (int i = 0; i < polyMesh.npolys; ++i) polyMesh.flags[i] = getFlag(static_cast<AreaType>(polyMesh.areas[i])); } [[nodiscard]] bool fillPolyMesh(RecastContext& context, const RecastSettings& settings, const RecastParams& params, rcHeightfield& solid, rcPolyMesh& polyMesh, rcPolyMeshDetail& polyMeshDetail) { rcCompactHeightfield compact; if (!buildCompactHeightfield(context, params.mWalkableHeight, params.mWalkableClimb, solid, compact)) return false; if (!erodeWalkableArea(context, params.mWalkableRadius, compact)) return false; if (!buildDistanceField(context, compact)) return false; if (!buildRegions( context, compact, settings.mBorderSize, settings.mRegionMinArea, settings.mRegionMergeArea)) return false; rcContourSet contourSet; if (!buildContours(context, compact, settings.mMaxSimplificationError, params.mMaxEdgeLen, contourSet)) return false; if (contourSet.nconts == 0) return false; if (!buildPolyMesh(context, contourSet, settings.mMaxVertsPerPoly, polyMesh)) return false; if (!buildPolyMeshDetail( context, polyMesh, compact, params.mSampleDist, params.mSampleMaxError, polyMeshDetail)) return false; setPolyMeshFlags(polyMesh); return true; } std::pair<float, float> getBoundsByZ( const RecastMesh& recastMesh, float agentHalfExtentsZ, const RecastSettings& settings) { float minZ = 0; float maxZ = 0; const std::vector<float>& vertices = recastMesh.getMesh().getVertices(); for (std::size_t i = 0, n = vertices.size(); i < n; i += 3) { minZ = std::min(minZ, vertices[i + 2]); maxZ = std::max(maxZ, vertices[i + 2]); } for (const CellWater& water : recastMesh.getWater()) { const float swimLevel = getSwimLevel(settings, water.mWater.mLevel, agentHalfExtentsZ); minZ = std::min(minZ, swimLevel); maxZ = std::max(maxZ, swimLevel); } for (const Heightfield& heightfield : recastMesh.getHeightfields()) { if (heightfield.mHeights.empty()) continue; const auto [minHeight, maxHeight] = std::minmax_element(heightfield.mHeights.begin(), heightfield.mHeights.end()); minZ = std::min(minZ, *minHeight); maxZ = std::max(maxZ, *maxHeight); } for (const FlatHeightfield& heightfield : recastMesh.getFlatHeightfields()) { minZ = std::min(minZ, heightfield.mHeight); maxZ = std::max(maxZ, heightfield.mHeight); } return { minZ, maxZ }; } } std::unique_ptr<PreparedNavMeshData> prepareNavMeshTileData(const RecastMesh& recastMesh, ESM::RefId worldspace, const TilePosition& tilePosition, const AgentBounds& agentBounds, const RecastSettings& settings) { RecastContext context(worldspace, tilePosition, agentBounds); const auto [minZ, maxZ] = getBoundsByZ(recastMesh, agentBounds.mHalfExtents.z(), settings); rcHeightfield solid; if (!initHeightfield(context, tilePosition, toNavMeshCoordinates(settings, minZ), toNavMeshCoordinates(settings, maxZ), settings, solid)) return nullptr; const RecastParams params = makeRecastParams(settings, agentBounds); if (!rasterizeTriangles( context, tilePosition, agentBounds.mHalfExtents.z(), recastMesh, settings, params, solid)) return nullptr; rcFilterLowHangingWalkableObstacles(&context, params.mWalkableClimb, solid); rcFilterLedgeSpans(&context, params.mWalkableHeight, params.mWalkableClimb, solid); rcFilterWalkableLowHeightSpans(&context, params.mWalkableHeight, solid); std::unique_ptr<PreparedNavMeshData> result = std::make_unique<PreparedNavMeshData>(); if (!fillPolyMesh(context, settings, params, solid, result->mPolyMesh, result->mPolyMeshDetail)) return nullptr; result->mCellSize = settings.mCellSize; result->mCellHeight = settings.mCellHeight; return result; } NavMeshData makeNavMeshTileData(const PreparedNavMeshData& data, const std::vector<OffMeshConnection>& offMeshConnections, const AgentBounds& agentBounds, const TilePosition& tile, const RecastSettings& settings) { const auto offMeshConVerts = getOffMeshVerts(offMeshConnections); const std::vector<float> offMeshConRad(offMeshConnections.size(), getRadius(settings, agentBounds)); const std::vector<unsigned char> offMeshConDir(offMeshConnections.size(), 0); const std::vector<unsigned char> offMeshConAreas = getOffMeshConAreas(offMeshConnections); const std::vector<unsigned short> offMeshConFlags = getOffMeshFlags(offMeshConnections); dtNavMeshCreateParams params; params.verts = data.mPolyMesh.verts; params.vertCount = data.mPolyMesh.nverts; params.polys = data.mPolyMesh.polys; params.polyAreas = data.mPolyMesh.areas; params.polyFlags = data.mPolyMesh.flags; params.polyCount = data.mPolyMesh.npolys; params.nvp = data.mPolyMesh.nvp; params.detailMeshes = data.mPolyMeshDetail.meshes; params.detailVerts = data.mPolyMeshDetail.verts; params.detailVertsCount = data.mPolyMeshDetail.nverts; params.detailTris = data.mPolyMeshDetail.tris; params.detailTriCount = data.mPolyMeshDetail.ntris; params.offMeshConVerts = offMeshConVerts.data(); params.offMeshConRad = offMeshConRad.data(); params.offMeshConDir = offMeshConDir.data(); params.offMeshConAreas = offMeshConAreas.data(); params.offMeshConFlags = offMeshConFlags.data(); params.offMeshConUserID = nullptr; params.offMeshConCount = static_cast<int>(offMeshConnections.size()); params.walkableHeight = getHeight(settings, agentBounds); params.walkableRadius = getRadius(settings, agentBounds); params.walkableClimb = getMaxClimb(settings); rcVcopy(params.bmin, data.mPolyMesh.bmin); rcVcopy(params.bmax, data.mPolyMesh.bmax); params.cs = data.mCellSize; params.ch = data.mCellHeight; params.buildBvTree = true; params.userId = data.mUserId; params.tileX = tile.x(); params.tileY = tile.y(); params.tileLayer = 0; unsigned char* navMeshData; int navMeshDataSize; const auto navMeshDataCreated = dtCreateNavMeshData(&params, &navMeshData, &navMeshDataSize); if (!navMeshDataCreated) throw NavigatorException("Failed to create navmesh tile data"); return NavMeshData(navMeshData, navMeshDataSize); } void initEmptyNavMesh(const Settings& settings, dtNavMesh& navMesh) { dtNavMeshParams params; std::fill_n(params.orig, 3, 0.0f); params.tileWidth = settings.mRecast.mTileSize * settings.mRecast.mCellSize; params.tileHeight = settings.mRecast.mTileSize * settings.mRecast.mCellSize; params.maxTiles = settings.mMaxTilesNumber; params.maxPolys = settings.mDetour.mMaxPolys; const auto status = navMesh.init(&params); if (!dtStatusSucceed(status)) throw NavigatorException("Failed to init navmesh"); } bool isSupportedAgentBounds(const RecastSettings& settings, const AgentBounds& agentBounds) { return isValidWalkableHeight(getWalkableHeight(settings, agentBounds)) && isValidWalkableRadius(getWalkableRadius(settings, agentBounds)); } }
26,266
C++
.cpp
529
36.969754
119
0.612942
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,455
navigatorutils.cpp
OpenMW_openmw/components/detournavigator/navigatorutils.cpp
#include "navigatorutils.hpp" #include "debug.hpp" #include "findrandompointaroundcircle.hpp" #include "navigator.hpp" #include "raycast.hpp" #include <components/debug/debuglog.hpp> namespace DetourNavigator { std::optional<osg::Vec3f> findRandomPointAroundCircle(const Navigator& navigator, const AgentBounds& agentBounds, const osg::Vec3f& start, const float maxRadius, const Flags includeFlags, float (*prng)()) { const auto navMesh = navigator.getNavMesh(agentBounds); if (!navMesh) return std::nullopt; const Settings& settings = navigator.getSettings(); const auto locked = navMesh->lock(); const auto result = DetourNavigator::findRandomPointAroundCircle(locked->getQuery(), toNavMeshCoordinates(settings.mRecast, agentBounds.mHalfExtents), toNavMeshCoordinates(settings.mRecast, start), toNavMeshCoordinates(settings.mRecast, maxRadius), includeFlags, prng); if (!result) return std::nullopt; return std::optional<osg::Vec3f>(fromNavMeshCoordinates(settings.mRecast, *result)); } std::optional<osg::Vec3f> raycast(const Navigator& navigator, const AgentBounds& agentBounds, const osg::Vec3f& start, const osg::Vec3f& end, const Flags includeFlags) { const auto navMesh = navigator.getNavMesh(agentBounds); if (navMesh == nullptr) return std::nullopt; const Settings& settings = navigator.getSettings(); const auto locked = navMesh->lock(); const auto result = DetourNavigator::raycast(locked->getQuery(), toNavMeshCoordinates(settings.mRecast, agentBounds.mHalfExtents), toNavMeshCoordinates(settings.mRecast, start), toNavMeshCoordinates(settings.mRecast, end), includeFlags); if (!result) return std::nullopt; return fromNavMeshCoordinates(settings.mRecast, *result); } std::optional<osg::Vec3f> findNearestNavMeshPosition(const Navigator& navigator, const AgentBounds& agentBounds, const osg::Vec3f& position, const osg::Vec3f& searchAreaHalfExtents, const Flags includeFlags) { const auto navMesh = navigator.getNavMesh(agentBounds); if (navMesh == nullptr) return std::nullopt; const auto& settings = navigator.getSettings(); const osg::Vec3f navMeshPosition = toNavMeshCoordinates(settings.mRecast, position); const auto lockedNavMesh = navMesh->lockConst(); dtNavMeshQuery navMeshQuery; if (const dtStatus status = navMeshQuery.init(&lockedNavMesh->getImpl(), settings.mDetour.mMaxNavMeshQueryNodes); dtStatusFailed(status)) { Log(Debug::Error) << "Failed to init dtNavMeshQuery for findNearestNavMeshPosition: " << WriteDtStatus{ status }; return std::nullopt; } dtQueryFilter queryFilter; queryFilter.setIncludeFlags(includeFlags); osg::Vec3f nearestNavMeshPos; const osg::Vec3f endPolyHalfExtents = toNavMeshCoordinates(settings.mRecast, searchAreaHalfExtents); dtPolyRef polyRef; if (const dtStatus status = navMeshQuery.findNearestPoly( navMeshPosition.ptr(), endPolyHalfExtents.ptr(), &queryFilter, &polyRef, nearestNavMeshPos.ptr()); dtStatusFailed(status) || polyRef == 0) { return std::nullopt; } return fromNavMeshCoordinates(settings.mRecast, nearestNavMeshPos); } }
3,557
C++
.cpp
71
41.169014
118
0.689675
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,456
collisionshapetype.cpp
OpenMW_openmw/components/detournavigator/collisionshapetype.cpp
#include "collisionshapetype.hpp" #include <stdexcept> #include <string> namespace DetourNavigator { CollisionShapeType toCollisionShapeType(int value) { switch (static_cast<CollisionShapeType>(value)) { case CollisionShapeType::Aabb: case CollisionShapeType::RotatingBox: case CollisionShapeType::Cylinder: return static_cast<CollisionShapeType>(value); } std::string error("Invalid CollisionShapeType value: \""); error += std::to_string(value); error += '"'; throw std::invalid_argument(error); } }
624
C++
.cpp
20
24.1
66
0.651163
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,457
recast.cpp
OpenMW_openmw/components/detournavigator/recast.cpp
#include "recast.hpp" #include <Recast.h> #include <RecastAlloc.h> #include <cstring> #include <new> namespace DetourNavigator { void* permRecastAlloc(std::size_t size) { void* const result = rcAlloc(size, RC_ALLOC_PERM); if (result == nullptr) throw std::bad_alloc(); return result; } void permRecastAlloc(rcPolyMesh& value) { permRecastAlloc(value.verts, getVertsLength(value)); permRecastAlloc(value.polys, getPolysLength(value)); permRecastAlloc(value.regs, getRegsLength(value)); permRecastAlloc(value.flags, getFlagsLength(value)); permRecastAlloc(value.areas, getAreasLength(value)); } void permRecastAlloc(rcPolyMeshDetail& value) { try { permRecastAlloc(value.meshes, getMeshesLength(value)); permRecastAlloc(value.verts, getVertsLength(value)); permRecastAlloc(value.tris, getTrisLength(value)); } catch (...) { freePolyMeshDetail(value); throw; } } void freePolyMeshDetail(rcPolyMeshDetail& value) noexcept { rcFree(value.meshes); value.meshes = nullptr; rcFree(value.verts); value.verts = nullptr; rcFree(value.tris); value.tris = nullptr; } void copyPolyMesh(const rcPolyMesh& src, rcPolyMesh& dst) { dst.nverts = src.nverts; dst.npolys = src.npolys; dst.maxpolys = src.maxpolys; dst.nvp = src.nvp; rcVcopy(dst.bmin, src.bmin); rcVcopy(dst.bmax, src.bmax); dst.cs = src.cs; dst.ch = src.ch; dst.borderSize = src.borderSize; dst.maxEdgeError = src.maxEdgeError; permRecastAlloc(dst); std::memcpy(dst.verts, src.verts, getVertsLength(src) * sizeof(*dst.verts)); std::memcpy(dst.polys, src.polys, getPolysLength(src) * sizeof(*dst.polys)); std::memcpy(dst.regs, src.regs, getRegsLength(src) * sizeof(*dst.regs)); std::memcpy(dst.flags, src.flags, getFlagsLength(src) * sizeof(*dst.flags)); std::memcpy(dst.areas, src.areas, getAreasLength(src) * sizeof(*dst.areas)); } void copyPolyMeshDetail(const rcPolyMeshDetail& src, rcPolyMeshDetail& dst) { dst.nmeshes = src.nmeshes; dst.nverts = src.nverts; dst.ntris = src.ntris; permRecastAlloc(dst); std::memcpy(dst.meshes, src.meshes, getMeshesLength(src) * sizeof(*dst.meshes)); std::memcpy(dst.verts, src.verts, getVertsLength(src) * sizeof(*dst.verts)); std::memcpy(dst.tris, src.tris, getTrisLength(src) * sizeof(*dst.tris)); } }
2,685
C++
.cpp
75
28.186667
88
0.634896
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,458
navmeshmanager.cpp
OpenMW_openmw/components/detournavigator/navmeshmanager.cpp
#include "navmeshmanager.hpp" #include "debug.hpp" #include "gettilespositions.hpp" #include "makenavmesh.hpp" #include "navmeshcacheitem.hpp" #include "settings.hpp" #include "settingsutils.hpp" #include "waitconditiontype.hpp" #include <components/debug/debuglog.hpp> #include <components/esm/util.hpp> #include <osg/io_utils> #include <DetourNavMesh.h> namespace { /// Safely reset shared_ptr with definite underlying object destrutor call. /// Assuming there is another thread holding copy of this shared_ptr or weak_ptr to this shared_ptr. template <class T> bool resetIfUnique(std::shared_ptr<T>& ptr) { const std::weak_ptr<T> weak(ptr); ptr.reset(); if (auto shared = weak.lock()) { ptr = std::move(shared); return false; } return true; } } namespace DetourNavigator { namespace { int getMaxRadius(int maxTiles) { return static_cast<int>(std::ceil(std::sqrt(static_cast<float>(maxTiles) / osg::PIf) + 1)); } TilesPositionsRange makeRange(const TilePosition& center, int radius) { return TilesPositionsRange{ .mBegin = center - TilePosition(radius, radius), .mEnd = center + TilePosition(radius + 1, radius + 1), }; } osg::Vec2f getMinCellGridPosition(const osg::Vec2i& center, int offset, float cellSize) { const osg::Vec2i cell = center + osg::Vec2i(offset, offset); return osg::Vec2f(static_cast<float>(cell.x()) * cellSize, static_cast<float>(cell.y()) * cellSize); } TilesPositionsRange makeCellGridRange( const RecastSettings& settings, ESM::RefId worldspace, const CellGridBounds& bounds) { const float floatCellSize = static_cast<float>(ESM::getCellSize(worldspace)); const osg::Vec2f min = getMinCellGridPosition(bounds.mCenter, -bounds.mHalfSize, floatCellSize); const osg::Vec2f max = getMinCellGridPosition(bounds.mCenter, bounds.mHalfSize + 1, floatCellSize); return TilesPositionsRange{ .mBegin = getTilePosition(settings, toNavMeshCoordinates(settings, min)), .mEnd = getTilePosition(settings, toNavMeshCoordinates(settings, max)), }; } TilesPositionsRange makeRange(const Settings& settings, ESM::RefId worldspace, const std::optional<CellGridBounds>& bounds, int radius, const TilePosition& center) { TilesPositionsRange result = makeRange(center, radius); if (bounds.has_value()) result = getIntersection(result, makeCellGridRange(settings.mRecast, worldspace, *bounds)); return result; } TilePosition toNavMeshTilePosition(const RecastSettings& settings, const osg::Vec3f& position) { return getTilePosition(settings, toNavMeshCoordinates(settings, position)); } } NavMeshManager::NavMeshManager(const Settings& settings, std::unique_ptr<NavMeshDb>&& db) : mSettings(settings) , mMaxRadius(getMaxRadius(settings.mMaxTilesNumber)) , mRecastMeshManager(settings.mRecast) , mOffMeshConnectionsManager(settings.mRecast) , mAsyncNavMeshUpdater(settings, mRecastMeshManager, mOffMeshConnectionsManager, std::move(db)) { } void NavMeshManager::updateBounds(ESM::RefId worldspace, const std::optional<CellGridBounds>& cellGridBounds, const osg::Vec3f& playerPosition, const UpdateGuard* guard) { if (worldspace != mWorldspace) { mRecastMeshManager.setWorldspace(worldspace, guard); for (auto& [agent, cache] : mCache) cache = std::make_shared<GuardedNavMeshCacheItem>(++mGenerationCounter, mSettings); mWorldspace = worldspace; } const TilePosition playerTile = toNavMeshTilePosition(mSettings.mRecast, playerPosition); mRecastMeshManager.setRange(makeRange(mSettings, worldspace, cellGridBounds, mMaxRadius, playerTile), guard); mCellGridBounds = cellGridBounds; } bool NavMeshManager::addObject(const ObjectId id, const CollisionShape& shape, const btTransform& transform, const AreaType areaType, const UpdateGuard* guard) { return mRecastMeshManager.addObject(id, shape, transform, areaType, guard); } bool NavMeshManager::updateObject( const ObjectId id, const btTransform& transform, const AreaType areaType, const UpdateGuard* guard) { return mRecastMeshManager.updateObject(id, transform, areaType, guard); } void NavMeshManager::removeObject(const ObjectId id, const UpdateGuard* guard) { mRecastMeshManager.removeObject(id, guard); } void NavMeshManager::addWater(const osg::Vec2i& cellPosition, int cellSize, float level, const UpdateGuard* guard) { mRecastMeshManager.addWater(cellPosition, cellSize, level, guard); } void NavMeshManager::removeWater(const osg::Vec2i& cellPosition, const UpdateGuard* guard) { mRecastMeshManager.removeWater(cellPosition, guard); } void NavMeshManager::addHeightfield( const osg::Vec2i& cellPosition, int cellSize, const HeightfieldShape& shape, const UpdateGuard* guard) { mRecastMeshManager.addHeightfield(cellPosition, cellSize, shape, guard); } void NavMeshManager::removeHeightfield(const osg::Vec2i& cellPosition, const UpdateGuard* guard) { mRecastMeshManager.removeHeightfield(cellPosition, guard); } void NavMeshManager::addAgent(const AgentBounds& agentBounds) { auto cached = mCache.find(agentBounds); if (cached != mCache.end()) return; mCache.emplace(agentBounds, std::make_shared<GuardedNavMeshCacheItem>(++mGenerationCounter, mSettings)); mPlayerTile.reset(); Log(Debug::Debug) << "cache add for agent=" << agentBounds; } bool NavMeshManager::reset(const AgentBounds& agentBounds) { const auto it = mCache.find(agentBounds); if (it == mCache.end()) return true; if (!resetIfUnique(it->second)) return false; mCache.erase(agentBounds); mPlayerTile.reset(); return true; } void NavMeshManager::addOffMeshConnection( const ObjectId id, const osg::Vec3f& start, const osg::Vec3f& end, const AreaType areaType) { mOffMeshConnectionsManager.add(id, OffMeshConnection{ start, end, areaType }); const auto startTilePosition = getTilePosition(mSettings.mRecast, start); const auto endTilePosition = getTilePosition(mSettings.mRecast, end); mRecastMeshManager.addChangedTile(startTilePosition, ChangeType::add); if (startTilePosition != endTilePosition) mRecastMeshManager.addChangedTile(endTilePosition, ChangeType::add); } void NavMeshManager::removeOffMeshConnections(const ObjectId id) { const auto changedTiles = mOffMeshConnectionsManager.remove(id); for (const auto& tile : changedTiles) mRecastMeshManager.addChangedTile(tile, ChangeType::update); } void NavMeshManager::update(const osg::Vec3f& playerPosition, const UpdateGuard* guard) { const TilePosition playerTile = toNavMeshTilePosition(mSettings.mRecast, playerPosition); if (mLastRecastMeshManagerRevision == mRecastMeshManager.getRevision() && mPlayerTile.has_value() && *mPlayerTile == playerTile) return; mLastRecastMeshManagerRevision = mRecastMeshManager.getRevision(); mPlayerTile = playerTile; mRecastMeshManager.setRange(makeRange(mSettings, mWorldspace, mCellGridBounds, mMaxRadius, playerTile), guard); const auto changedTiles = mRecastMeshManager.takeChangedTiles(guard); const TilesPositionsRange range = mRecastMeshManager.getLimitedObjectsRange(); for (const auto& [agentBounds, cached] : mCache) update(agentBounds, playerTile, range, cached, changedTiles); } void NavMeshManager::update(const AgentBounds& agentBounds, const TilePosition& playerTile, const TilesPositionsRange& range, const SharedNavMeshCacheItem& cached, const std::map<osg::Vec2i, ChangeType>& changedTiles) { std::map<osg::Vec2i, ChangeType> tilesToPost = changedTiles; { const int maxTiles = mSettings.mMaxTilesNumber; const auto locked = cached->lockConst(); const auto& navMesh = locked->getImpl(); getTilesPositions(range, [&](const TilePosition& tile) { if (changedTiles.find(tile) != changedTiles.end()) return; const bool shouldAdd = shouldAddTile(tile, playerTile, maxTiles); const bool presentInNavMesh = navMesh.getTileAt(tile.x(), tile.y(), 0) != nullptr; if (shouldAdd && !presentInNavMesh) tilesToPost.emplace(tile, locked->isEmptyTile(tile) ? ChangeType::update : ChangeType::add); else if (!shouldAdd && presentInNavMesh) tilesToPost.emplace(tile, ChangeType::remove); }); locked->forEachTilePosition([&](const TilePosition& tile) { if (!shouldAddTile(tile, playerTile, maxTiles)) tilesToPost.emplace(tile, ChangeType::remove); }); } mAsyncNavMeshUpdater.post(agentBounds, cached, playerTile, mWorldspace, tilesToPost); Log(Debug::Debug) << "Cache update posted for agent=" << agentBounds << " playerTile=" << playerTile << " recastMeshManagerRevision=" << mLastRecastMeshManagerRevision; } void NavMeshManager::wait(WaitConditionType waitConditionType, Loading::Listener* listener) { mAsyncNavMeshUpdater.wait(waitConditionType, listener); } SharedNavMeshCacheItem NavMeshManager::getNavMesh(const AgentBounds& agentBounds) const { return getCached(agentBounds); } std::map<AgentBounds, SharedNavMeshCacheItem> NavMeshManager::getNavMeshes() const { return mCache; } Stats NavMeshManager::getStats() const { return Stats{ .mUpdater = mAsyncNavMeshUpdater.getStats(), .mRecast = mRecastMeshManager.getStats(), }; } RecastMeshTiles NavMeshManager::getRecastMeshTiles() const { RecastMeshTiles result; getTilesPositions(mRecastMeshManager.getLimitedObjectsRange(), [&](const TilePosition& v) { if (auto mesh = mRecastMeshManager.getCachedMesh(mWorldspace, v)) result.emplace(v, std::move(mesh)); }); return result; } SharedNavMeshCacheItem NavMeshManager::getCached(const AgentBounds& agentBounds) const { const auto cached = mCache.find(agentBounds); if (cached != mCache.end()) return cached->second; return SharedNavMeshCacheItem(); } }
11,129
C++
.cpp
240
37.641667
119
0.678124
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,459
recastmeshbuilder.cpp
OpenMW_openmw/components/detournavigator/recastmeshbuilder.cpp
#include "recastmeshbuilder.hpp" #include "exceptions.hpp" #include <components/bullethelpers/heightfield.hpp> #include <components/bullethelpers/processtrianglecallback.hpp> #include <components/bullethelpers/transformboundingbox.hpp> #include <components/misc/convert.hpp> #include <BulletCollision/CollisionShapes/btBoxShape.h> #include <BulletCollision/CollisionShapes/btCompoundShape.h> #include <BulletCollision/CollisionShapes/btConcaveShape.h> #include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h> #include <LinearMath/btAabbUtil2.h> #include <LinearMath/btTransform.h> #include <algorithm> #include <array> #include <cassert> #include <cmath> #include <sstream> #include <vector> namespace DetourNavigator { using BulletHelpers::makeProcessTriangleCallback; namespace { RecastMeshTriangle makeRecastMeshTriangle(const btVector3* vertices, const AreaType areaType) { RecastMeshTriangle result; result.mAreaType = areaType; for (std::size_t i = 0; i < 3; ++i) result.mVertices[i] = Misc::Convert::toOsg(vertices[i]); return result; } float getHeightfieldScale(int cellSize, std::size_t dataSize) { return static_cast<float>(cellSize) / (dataSize - 1); } bool isNan(const RecastMeshTriangle& triangle) { for (std::size_t i = 0; i < 3; ++i) if (std::isnan(triangle.mVertices[i].x()) || std::isnan(triangle.mVertices[i].y()) || std::isnan(triangle.mVertices[i].z())) return true; return false; } } Mesh makeMesh(std::vector<RecastMeshTriangle>&& triangles, const osg::Vec3f& shift) { std::vector<osg::Vec3f> uniqueVertices; uniqueVertices.reserve(3 * triangles.size()); for (const RecastMeshTriangle& triangle : triangles) for (const osg::Vec3f& vertex : triangle.mVertices) uniqueVertices.push_back(vertex); std::sort(uniqueVertices.begin(), uniqueVertices.end()); uniqueVertices.erase(std::unique(uniqueVertices.begin(), uniqueVertices.end()), uniqueVertices.end()); std::vector<int> indices; indices.reserve(3 * triangles.size()); std::vector<AreaType> areaTypes; areaTypes.reserve(triangles.size()); for (const RecastMeshTriangle& triangle : triangles) { areaTypes.push_back(triangle.mAreaType); for (const osg::Vec3f& vertex : triangle.mVertices) { const auto it = std::lower_bound(uniqueVertices.begin(), uniqueVertices.end(), vertex); assert(it != uniqueVertices.end()); assert(*it == vertex); indices.push_back(static_cast<int>(it - uniqueVertices.begin())); } } triangles.clear(); std::vector<float> vertices; vertices.reserve(3 * uniqueVertices.size()); for (const osg::Vec3f& vertex : uniqueVertices) { vertices.push_back(vertex.x() + shift.x()); vertices.push_back(vertex.y() + shift.y()); vertices.push_back(vertex.z() + shift.z()); } return Mesh(std::move(indices), std::move(vertices), std::move(areaTypes)); } Mesh makeMesh(const Heightfield& heightfield) { using BulletHelpers::makeProcessTriangleCallback; using Misc::Convert::toOsg; constexpr int upAxis = 2; constexpr bool flipQuadEdges = false; #if BT_BULLET_VERSION < 310 std::vector<btScalar> heights(heightfield.mHeights.begin(), heightfield.mHeights.end()); btHeightfieldTerrainShape shape(static_cast<int>(heightfield.mHeights.size() / heightfield.mLength), static_cast<int>(heightfield.mLength), heights.data(), 1, heightfield.mMinHeight, heightfield.mMaxHeight, upAxis, PHY_FLOAT, flipQuadEdges); #else btHeightfieldTerrainShape shape(static_cast<int>(heightfield.mHeights.size() / heightfield.mLength), static_cast<int>(heightfield.mLength), heightfield.mHeights.data(), heightfield.mMinHeight, heightfield.mMaxHeight, upAxis, flipQuadEdges); #endif const float scale = getHeightfieldScale(heightfield.mCellSize, heightfield.mOriginalSize); shape.setLocalScaling(btVector3(scale, scale, 1)); btVector3 aabbMin; btVector3 aabbMax; shape.getAabb(btTransform::getIdentity(), aabbMin, aabbMax); std::vector<RecastMeshTriangle> triangles; auto callback = makeProcessTriangleCallback([&](btVector3* vertices, int, int) { triangles.emplace_back(makeRecastMeshTriangle(vertices, AreaType_ground)); }); shape.processAllTriangles(&callback, aabbMin, aabbMax); const osg::Vec2f aabbShift = (osg::Vec2f(aabbMax.x(), aabbMax.y()) - osg::Vec2f(aabbMin.x(), aabbMin.y())) * 0.5; const osg::Vec2f tileShift = osg::Vec2f(heightfield.mMinX, heightfield.mMinY) * scale; const osg::Vec2f localShift = aabbShift + tileShift; const float cellSize = static_cast<float>(heightfield.mCellSize); const osg::Vec3f cellShift(heightfield.mCellPosition.x() * cellSize, heightfield.mCellPosition.y() * cellSize, (heightfield.mMinHeight + heightfield.mMaxHeight) * 0.5f); return makeMesh(std::move(triangles), cellShift + osg::Vec3f(localShift.x(), localShift.y(), 0)); } RecastMeshBuilder::RecastMeshBuilder(const TileBounds& bounds) noexcept : mBounds(bounds) { } void RecastMeshBuilder::addObject(const btCollisionShape& shape, const btTransform& transform, const AreaType areaType, osg::ref_ptr<const Resource::BulletShape> source, const ObjectTransform& objectTransform) { addObject(shape, transform, areaType); mSources.push_back(MeshSource{ std::move(source), objectTransform, areaType }); } void RecastMeshBuilder::addObject( const btCollisionShape& shape, const btTransform& transform, const AreaType areaType) { if (shape.isCompound()) return addObject(static_cast<const btCompoundShape&>(shape), transform, areaType); else if (shape.getShapeType() == TERRAIN_SHAPE_PROXYTYPE) return addObject(static_cast<const btHeightfieldTerrainShape&>(shape), transform, areaType); else if (shape.isConcave()) return addObject(static_cast<const btConcaveShape&>(shape), transform, areaType); else if (shape.getShapeType() == BOX_SHAPE_PROXYTYPE) return addObject(static_cast<const btBoxShape&>(shape), transform, areaType); std::ostringstream message; message << "Unsupported shape type: " << BroadphaseNativeTypes(shape.getShapeType()); throw InvalidArgument(message.str()); } void RecastMeshBuilder::addObject( const btCompoundShape& shape, const btTransform& transform, const AreaType areaType) { for (int i = 0, num = shape.getNumChildShapes(); i < num; ++i) addObject(*shape.getChildShape(i), transform * shape.getChildTransform(i), areaType); } void RecastMeshBuilder::addObject( const btConcaveShape& shape, const btTransform& transform, const AreaType areaType) { return addObject(shape, transform, makeProcessTriangleCallback([&](btVector3* vertices, int, int) { RecastMeshTriangle triangle = makeRecastMeshTriangle(vertices, areaType); std::reverse(triangle.mVertices.begin(), triangle.mVertices.end()); mTriangles.emplace_back(triangle); })); } void RecastMeshBuilder::addObject( const btHeightfieldTerrainShape& shape, const btTransform& transform, const AreaType areaType) { addObject(shape, transform, makeProcessTriangleCallback([&](btVector3* vertices, int, int) { mTriangles.emplace_back(makeRecastMeshTriangle(vertices, areaType)); })); } void RecastMeshBuilder::addObject(const btBoxShape& shape, const btTransform& transform, const AreaType areaType) { constexpr std::array<int, 36> indices{ { 0, 2, 3, // triangle 0 3, 1, 0, // triangle 1 0, 4, 6, // triangle 2 6, 2, 0, // triangle 3 0, 1, 5, // triangle 4 5, 4, 0, // triangle 5 7, 5, 1, // triangle 6 1, 3, 7, // triangle 7 7, 3, 2, // triangle 8 2, 6, 7, // triangle 9 7, 6, 4, // triangle 10 4, 5, 7, // triangle 11 } }; for (std::size_t i = 0; i < indices.size(); i += 3) { std::array<btVector3, 3> vertices; for (std::size_t j = 0; j < 3; ++j) { btVector3 position; shape.getVertex(indices[i + j], position); vertices[j] = transform(position); } mTriangles.emplace_back(makeRecastMeshTriangle(vertices.data(), areaType)); } } void RecastMeshBuilder::addWater(const osg::Vec2i& cellPosition, const Water& water) { mWater.push_back(CellWater{ cellPosition, water }); } void RecastMeshBuilder::addHeightfield(const osg::Vec2i& cellPosition, int cellSize, float height) { if (const auto intersection = getIntersection(mBounds, maxCellTileBounds(cellPosition, cellSize))) mFlatHeightfields.emplace_back(FlatHeightfield{ cellPosition, cellSize, height }); } void RecastMeshBuilder::addHeightfield(const osg::Vec2i& cellPosition, int cellSize, const float* heights, std::size_t size, float minHeight, float maxHeight) { const auto intersection = getIntersection(mBounds, maxCellTileBounds(cellPosition, cellSize)); if (!intersection.has_value()) return; const osg::Vec3f shift = Misc::Convert::toOsg( BulletHelpers::getHeightfieldShift(cellPosition.x(), cellPosition.y(), cellSize, minHeight, maxHeight)); const float stepSize = getHeightfieldScale(cellSize, size); const int halfCellSize = cellSize / 2; const auto local = [&](float v, float shift) { return (v - shift + halfCellSize) / stepSize; }; const auto index = [&](float v, int add) { return std::clamp<int>(static_cast<int>(v) + add, 0, size); }; const std::size_t minX = index(std::round(local(intersection->mMin.x(), shift.x())), -1); const std::size_t minY = index(std::round(local(intersection->mMin.y(), shift.y())), -1); const std::size_t maxX = index(std::round(local(intersection->mMax.x(), shift.x())), 1); const std::size_t maxY = index(std::round(local(intersection->mMax.y(), shift.y())), 1); const std::size_t endX = std::min(maxX + 1, size); const std::size_t endY = std::min(maxY + 1, size); const std::size_t sliceSize = (endX - minX) * (endY - minY); if (sliceSize == 0) return; std::vector<float> tileHeights; tileHeights.reserve(sliceSize); for (std::size_t y = minY; y < endY; ++y) for (std::size_t x = minX; x < endX; ++x) tileHeights.push_back(heights[x + y * size]); Heightfield heightfield; heightfield.mCellPosition = cellPosition; heightfield.mCellSize = cellSize; heightfield.mLength = static_cast<std::uint8_t>(endY - minY); heightfield.mMinHeight = minHeight; heightfield.mMaxHeight = maxHeight; heightfield.mHeights = std::move(tileHeights); heightfield.mOriginalSize = size; heightfield.mMinX = static_cast<std::uint8_t>(minX); heightfield.mMinY = static_cast<std::uint8_t>(minY); mHeightfields.push_back(std::move(heightfield)); } std::shared_ptr<RecastMesh> RecastMeshBuilder::create(const Version& version) && { mTriangles.erase(std::remove_if(mTriangles.begin(), mTriangles.end(), isNan), mTriangles.end()); std::sort(mTriangles.begin(), mTriangles.end()); std::sort(mWater.begin(), mWater.end()); std::sort(mHeightfields.begin(), mHeightfields.end()); std::sort(mFlatHeightfields.begin(), mFlatHeightfields.end()); Mesh mesh = makeMesh(std::move(mTriangles)); return std::make_shared<RecastMesh>(version, std::move(mesh), std::move(mWater), std::move(mHeightfields), std::move(mFlatHeightfields), std::move(mSources)); } void RecastMeshBuilder::addObject( const btConcaveShape& shape, const btTransform& transform, btTriangleCallback&& callback) { btVector3 aabbMin; btVector3 aabbMax; shape.getAabb(btTransform::getIdentity(), aabbMin, aabbMax); const btVector3 boundsMin(mBounds.mMin.x(), mBounds.mMin.y(), -std::numeric_limits<btScalar>::max() * std::numeric_limits<btScalar>::epsilon()); const btVector3 boundsMax(mBounds.mMax.x(), mBounds.mMax.y(), std::numeric_limits<btScalar>::max() * std::numeric_limits<btScalar>::epsilon()); auto wrapper = makeProcessTriangleCallback([&](btVector3* triangle, int partId, int triangleIndex) { std::array<btVector3, 3> transformed; for (std::size_t i = 0; i < 3; ++i) transformed[i] = transform(triangle[i]); if (TestTriangleAgainstAabb2(transformed.data(), boundsMin, boundsMax)) callback.processTriangle(transformed.data(), partId, triangleIndex); }); shape.processAllTriangles(&wrapper, aabbMin, aabbMax); } void RecastMeshBuilder::addObject( const btHeightfieldTerrainShape& shape, const btTransform& transform, btTriangleCallback&& callback) { using BulletHelpers::transformBoundingBox; btVector3 aabbMin; btVector3 aabbMax; shape.getAabb(btTransform::getIdentity(), aabbMin, aabbMax); transformBoundingBox(transform, aabbMin, aabbMax); aabbMin.setX(std::max(static_cast<btScalar>(mBounds.mMin.x()), aabbMin.x())); aabbMin.setX(std::min(static_cast<btScalar>(mBounds.mMax.x()), aabbMin.x())); aabbMin.setY(std::max(static_cast<btScalar>(mBounds.mMin.y()), aabbMin.y())); aabbMin.setY(std::min(static_cast<btScalar>(mBounds.mMax.y()), aabbMin.y())); aabbMax.setX(std::max(static_cast<btScalar>(mBounds.mMin.x()), aabbMax.x())); aabbMax.setX(std::min(static_cast<btScalar>(mBounds.mMax.x()), aabbMax.x())); aabbMax.setY(std::max(static_cast<btScalar>(mBounds.mMin.y()), aabbMax.y())); aabbMax.setY(std::min(static_cast<btScalar>(mBounds.mMax.y()), aabbMax.y())); transformBoundingBox(transform.inverse(), aabbMin, aabbMax); auto wrapper = makeProcessTriangleCallback([&](btVector3* triangle, int partId, int triangleIndex) { std::array<btVector3, 3> transformed; for (std::size_t i = 0; i < 3; ++i) transformed[i] = transform(triangle[i]); callback.processTriangle(transformed.data(), partId, triangleIndex); }); shape.processAllTriangles(&wrapper, aabbMin, aabbMax); } }
15,236
C++
.cpp
293
42.860068
118
0.653175
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,460
raycast.cpp
OpenMW_openmw/components/detournavigator/raycast.cpp
#include "raycast.hpp" #include <DetourNavMesh.h> #include <DetourNavMeshQuery.h> #include <array> namespace DetourNavigator { std::optional<osg::Vec3f> raycast(const dtNavMeshQuery& navMeshQuery, const osg::Vec3f& halfExtents, const osg::Vec3f& start, const osg::Vec3f& end, const Flags includeFlags) { dtQueryFilter queryFilter; queryFilter.setIncludeFlags(includeFlags); dtPolyRef ref = 0; if (dtStatus status = navMeshQuery.findNearestPoly(start.ptr(), halfExtents.ptr(), &queryFilter, &ref, nullptr); dtStatusFailed(status) || ref == 0) return {}; const unsigned options = 0; std::array<dtPolyRef, 16> path; dtRaycastHit hit; hit.path = path.data(); hit.maxPath = path.size(); if (dtStatus status = navMeshQuery.raycast(ref, start.ptr(), end.ptr(), &queryFilter, options, &hit); dtStatusFailed(status) || hit.pathCount == 0) return {}; osg::Vec3f hitPosition; if (dtStatus status = navMeshQuery.closestPointOnPoly(path[hit.pathCount - 1], end.ptr(), hitPosition.ptr(), nullptr); dtStatusFailed(status)) return {}; return hitPosition; } }
1,258
C++
.cpp
31
32.645161
120
0.642623
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,461
settings.cpp
OpenMW_openmw/components/detournavigator/settings.cpp
#include "settings.hpp" #include <components/misc/constants.hpp> #include <components/settings/values.hpp> #include <algorithm> #include <stdexcept> #include <string> namespace DetourNavigator { namespace { struct NavMeshLimits { int mMaxTiles; int mMaxPolys; }; template <class T> unsigned long getMinValuableBitsNumber(const T value) { unsigned long power = 0; while (power < sizeof(T) * 8 && (static_cast<T>(1) << power) < value) ++power; return power; } NavMeshLimits getNavMeshTileLimits(const DetourSettings& settings) { // Max tiles and max polys affect how the tile IDs are caculated. // There are 22 bits available for identifying a tile and a polygon. constexpr int polysAndTilesBits = 22; const unsigned long polysBits = getMinValuableBitsNumber(settings.mMaxPolys); if (polysBits >= polysAndTilesBits) throw std::invalid_argument("Too many polygons per tile: " + std::to_string(settings.mMaxPolys)); const unsigned long tilesBits = polysAndTilesBits - polysBits; return NavMeshLimits{ .mMaxTiles = static_cast<int>(1 << tilesBits), .mMaxPolys = static_cast<int>(1 << polysBits), }; } RecastSettings makeRecastSettingsFromSettingsManager() { RecastSettings result; result.mBorderSize = ::Settings::navigator().mBorderSize; result.mCellHeight = ::Settings::navigator().mCellHeight; result.mCellSize = ::Settings::navigator().mCellSize; result.mDetailSampleDist = ::Settings::navigator().mDetailSampleDist; result.mDetailSampleMaxError = ::Settings::navigator().mDetailSampleMaxError; result.mMaxClimb = Constants::sStepSizeUp; result.mMaxSimplificationError = ::Settings::navigator().mMaxSimplificationError; result.mMaxSlope = Constants::sMaxSlope; result.mRecastScaleFactor = ::Settings::navigator().mRecastScaleFactor; result.mSwimHeightScale = 0; result.mMaxEdgeLen = ::Settings::navigator().mMaxEdgeLen; result.mMaxVertsPerPoly = ::Settings::navigator().mMaxVertsPerPoly; result.mRegionMergeArea = ::Settings::navigator().mRegionMergeArea; result.mRegionMinArea = ::Settings::navigator().mRegionMinArea; result.mTileSize = ::Settings::navigator().mTileSize; return result; } DetourSettings makeDetourSettingsFromSettingsManager() { DetourSettings result; result.mMaxNavMeshQueryNodes = ::Settings::navigator().mMaxNavMeshQueryNodes; result.mMaxPolys = ::Settings::navigator().mMaxPolygonsPerTile; result.mMaxPolygonPathSize = ::Settings::navigator().mMaxPolygonPathSize; result.mMaxSmoothPathSize = ::Settings::navigator().mMaxSmoothPathSize; return result; } } Settings makeSettingsFromSettingsManager() { Settings result; result.mRecast = makeRecastSettingsFromSettingsManager(); result.mDetour = makeDetourSettingsFromSettingsManager(); const NavMeshLimits limits = getNavMeshTileLimits(result.mDetour); result.mDetour.mMaxPolys = limits.mMaxPolys; result.mMaxTilesNumber = std::min(limits.mMaxTiles, ::Settings::navigator().mMaxTilesNumber.get()); result.mWaitUntilMinDistanceToPlayer = ::Settings::navigator().mWaitUntilMinDistanceToPlayer; result.mAsyncNavMeshUpdaterThreads = ::Settings::navigator().mAsyncNavMeshUpdaterThreads; result.mMaxNavMeshTilesCacheSize = ::Settings::navigator().mMaxNavMeshTilesCacheSize; result.mEnableWriteRecastMeshToFile = ::Settings::navigator().mEnableWriteRecastMeshToFile; result.mEnableWriteNavMeshToFile = ::Settings::navigator().mEnableWriteNavMeshToFile; result.mRecastMeshPathPrefix = ::Settings::navigator().mRecastMeshPathPrefix; result.mNavMeshPathPrefix = ::Settings::navigator().mNavMeshPathPrefix; result.mEnableRecastMeshFileNameRevision = ::Settings::navigator().mEnableRecastMeshFileNameRevision; result.mEnableNavMeshFileNameRevision = ::Settings::navigator().mEnableNavMeshFileNameRevision; result.mMinUpdateInterval = std::chrono::milliseconds(::Settings::navigator().mMinUpdateIntervalMs); result.mEnableNavMeshDiskCache = ::Settings::navigator().mEnableNavMeshDiskCache; result.mWriteToNavMeshDb = ::Settings::navigator().mWriteToNavmeshdb; result.mMaxDbFileSize = ::Settings::navigator().mMaxNavmeshdbFileSize; return result; } }
4,834
C++
.cpp
91
43.021978
113
0.686005
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,462
tilecachedrecastmeshmanager.cpp
OpenMW_openmw/components/detournavigator/tilecachedrecastmeshmanager.cpp
#include "tilecachedrecastmeshmanager.hpp" #include "changetype.hpp" #include "gettilespositions.hpp" #include "recastmeshbuilder.hpp" #include "settingsutils.hpp" #include "stats.hpp" #include "updateguard.hpp" #include <components/bullethelpers/aabb.hpp> #include <components/misc/convert.hpp> #include <boost/geometry/geometry.hpp> #include <limits> namespace DetourNavigator { namespace { const TilesPositionsRange infiniteRange{ .mBegin = TilePosition(std::numeric_limits<int>::min(), std::numeric_limits<int>::min()), .mEnd = TilePosition(std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), }; struct AddHeightfield { osg::Vec2i mCellPosition; int mCellSize; RecastMeshBuilder& mBuilder; void operator()(const HeightfieldSurface& v) { mBuilder.addHeightfield(mCellPosition, mCellSize, v.mHeights, v.mSize, v.mMinHeight, v.mMaxHeight); } void operator()(HeightfieldPlane v) { mBuilder.addHeightfield(mCellPosition, mCellSize, v.mHeight); } }; TilePosition makeTilePosition(const boost::geometry::model::point<int, 2, boost::geometry::cs::cartesian>& v) { return TilePosition(v.get<0>(), v.get<1>()); } template <class Mutex> class MaybeLockGuard { public: explicit MaybeLockGuard(Mutex& mutex, const UpdateGuard* guard) : mImpl(guard == nullptr ? std::optional<std::unique_lock<Mutex>>(mutex) : std::nullopt) { } private: const std::optional<std::unique_lock<Mutex>> mImpl; }; TilesPositionsRange getIndexRange(const auto& index) { const auto bounds = index.bounds(); return TilesPositionsRange{ .mBegin = makeTilePosition(bounds.min_corner()), .mEnd = makeTilePosition(bounds.max_corner()) + TilePosition(1, 1), }; } } TileCachedRecastMeshManager::TileCachedRecastMeshManager(const RecastSettings& settings) : mSettings(settings) , mRange(infiniteRange) { } void TileCachedRecastMeshManager::setRange(const TilesPositionsRange& range, const UpdateGuard* guard) { if (mRange == range) return; bool changed = false; if (mRange != infiniteRange) { for (const auto& [id, data] : mObjects) { const TilesPositionsRange objectRange = makeTilesPositionsRange(data->mObject.getShape(), data->mObject.getTransform(), mSettings); getTilesPositions(getIntersection(mRange, objectRange), [&](const TilePosition& v) { if (!isInTilesPositionsRange(range, v)) { addChangedTile(v, ChangeType::remove); changed = true; } }); getTilesPositions(getIntersection(range, objectRange), [&](const TilePosition& v) { if (!isInTilesPositionsRange(mRange, v)) { addChangedTile(v, ChangeType::add); changed = true; } }); } getTilesPositions(mRange, [&](const TilePosition& v) { if (!isInTilesPositionsRange(range, v)) mCache.erase(v); }); } const MaybeLockGuard lock(mMutex, guard); if (changed) ++mRevision; mRange = range; } TilesPositionsRange TileCachedRecastMeshManager::getLimitedObjectsRange() const { std::optional<TilesPositionsRange> result; if (!mWater.empty()) result = getIndexRange(mWaterIndex); if (!mHeightfields.empty()) { const TilesPositionsRange range = getIndexRange(mHeightfieldIndex); if (result.has_value()) result = getUnion(*result, range); else result = range; } if (!mObjects.empty()) { const TilesPositionsRange range = getIndexRange(mObjectIndex); if (result.has_value()) result = getUnion(*result, range); else result = range; } if (result.has_value()) return getIntersection(mRange, *result); return {}; } void TileCachedRecastMeshManager::setWorldspace(ESM::RefId worldspace, const UpdateGuard* guard) { const MaybeLockGuard lock(mMutex, guard); if (mWorldspace == worldspace) return; mWorldspace = worldspace; ++mGeneration; ++mRevision; mObjectIndex.clear(); mObjects.clear(); mWater.clear(); mHeightfields.clear(); mCache.clear(); } bool TileCachedRecastMeshManager::addObject(ObjectId id, const CollisionShape& shape, const btTransform& transform, const AreaType areaType, const UpdateGuard* guard) { const TilesPositionsRange range = makeTilesPositionsRange(shape.getShape(), transform, mSettings); { const MaybeLockGuard lock(mMutex, guard); const auto it = mObjects.find(id); if (it != mObjects.end()) return false; const std::size_t revision = mRevision + 1; ObjectData* const dataPtr = mObjects .emplace_hint(it, id, std::unique_ptr<ObjectData>(new ObjectData{ .mObject = RecastMeshObject(shape, transform, areaType), .mRange = range, .mAabb = CommulativeAabb(revision, BulletHelpers::getAabb(shape.getShape(), transform)), .mGeneration = mGeneration, .mRevision = revision, .mLastNavMeshReportedChange = {}, .mLastNavMeshReport = {}, })) ->second.get(); assert(range.mBegin != range.mEnd); mObjectIndex.insert(makeObjectIndexValue(range, dataPtr)); mRevision = revision; } getTilesPositions( getIntersection(range, mRange), [&](const TilePosition& v) { addChangedTile(v, ChangeType::add); }); return true; } bool TileCachedRecastMeshManager::updateObject( ObjectId id, const btTransform& transform, const AreaType areaType, const UpdateGuard* guard) { TilesPositionsRange newRange; TilesPositionsRange oldRange; { const MaybeLockGuard lock(mMutex, guard); const auto it = mObjects.find(id); if (it == mObjects.end()) return false; if (!it->second->mObject.update(transform, areaType)) return false; const std::size_t lastChangeRevision = it->second->mLastNavMeshReportedChange.has_value() ? it->second->mLastNavMeshReportedChange->mRevision : mRevision; const btCollisionShape& shape = it->second->mObject.getShape(); if (!it->second->mAabb.update(lastChangeRevision, BulletHelpers::getAabb(shape, transform))) return false; newRange = makeTilesPositionsRange(shape, transform, mSettings); oldRange = it->second->mRange; if (newRange != oldRange) { mObjectIndex.remove(makeObjectIndexValue(oldRange, it->second.get())); mObjectIndex.insert(makeObjectIndexValue(newRange, it->second.get())); it->second->mRange = newRange; } ++mRevision; it->second->mRevision = mRevision; } if (newRange == oldRange) { getTilesPositions(getIntersection(newRange, mRange), [&](const TilePosition& v) { addChangedTile(v, ChangeType::update); }); } else { getTilesPositions(getIntersection(newRange, mRange), [&](const TilePosition& v) { const ChangeType changeType = isInTilesPositionsRange(oldRange, v) ? ChangeType::update : ChangeType::add; addChangedTile(v, changeType); }); getTilesPositions(getIntersection(oldRange, mRange), [&](const TilePosition& v) { if (!isInTilesPositionsRange(newRange, v)) addChangedTile(v, ChangeType::remove); }); } return true; } void TileCachedRecastMeshManager::removeObject(ObjectId id, const UpdateGuard* guard) { TilesPositionsRange range; { const MaybeLockGuard lock(mMutex, guard); const auto it = mObjects.find(id); if (it == mObjects.end()) return; range = it->second->mRange; mObjectIndex.remove(makeObjectIndexValue(range, it->second.get())); mObjects.erase(it); ++mRevision; } getTilesPositions( getIntersection(range, mRange), [&](const TilePosition& v) { addChangedTile(v, ChangeType::remove); }); } void TileCachedRecastMeshManager::addWater( const osg::Vec2i& cellPosition, const int cellSize, const float level, const UpdateGuard* guard) { const btVector3 shift = Misc::Convert::toBullet(getWaterShift3d(cellPosition, cellSize, level)); const std::optional<TilesPositionsRange> range = cellSize == std::numeric_limits<int>::max() ? std::optional<TilesPositionsRange>() : makeTilesPositionsRange(cellSize, shift, mSettings); { const MaybeLockGuard lock(mMutex, guard); auto it = mWater.find(cellPosition); if (it != mWater.end()) return; const std::size_t revision = mRevision + 1; it = mWater.emplace_hint(it, cellPosition, WaterData{ .mWater = Water{ .mCellSize = cellSize, .mLevel = level }, .mRange = range, .mRevision = revision, }); if (range.has_value()) mWaterIndex.insert(makeWaterIndexValue(*range, it)); else mInfiniteWater = it; mRevision = revision; } addChangedTiles(range, ChangeType::add); } void TileCachedRecastMeshManager::removeWater(const osg::Vec2i& cellPosition, const UpdateGuard* guard) { std::optional<TilesPositionsRange> range; { const MaybeLockGuard lock(mMutex, guard); const auto it = mWater.find(cellPosition); if (it == mWater.end()) return; range = it->second.mRange; if (range.has_value()) mWaterIndex.remove(makeWaterIndexValue(*range, it)); else mInfiniteWater = mWater.end(); mWater.erase(it); ++mRevision; } addChangedTiles(range, ChangeType::remove); } void TileCachedRecastMeshManager::addHeightfield( const osg::Vec2i& cellPosition, const int cellSize, const HeightfieldShape& shape, const UpdateGuard* guard) { const btVector3 shift = getHeightfieldShift(shape, cellPosition, cellSize); const std::optional<TilesPositionsRange> range = cellSize == std::numeric_limits<int>::max() ? std::optional<TilesPositionsRange>() : makeTilesPositionsRange(cellSize, shift, mSettings); { const MaybeLockGuard lock(mMutex, guard); auto it = mHeightfields.find(cellPosition); if (it != mHeightfields.end()) return; const std::size_t revision = mRevision + 1; it = mHeightfields.emplace_hint(it, cellPosition, HeightfieldData{ .mCellSize = cellSize, .mShape = shape, .mRange = range, .mRevision = revision, }); if (range.has_value()) mHeightfieldIndex.insert(makeHeightfieldIndexValue(*range, it)); else mInfiniteHeightfield = it; mRevision = revision; } addChangedTiles(range, ChangeType::add); } void TileCachedRecastMeshManager::removeHeightfield(const osg::Vec2i& cellPosition, const UpdateGuard* guard) { std::optional<TilesPositionsRange> range; { const MaybeLockGuard lock(mMutex, guard); const auto it = mHeightfields.find(cellPosition); if (it == mHeightfields.end()) return; range = it->second.mRange; if (range.has_value()) mHeightfieldIndex.remove(makeHeightfieldIndexValue(*range, it)); else mInfiniteHeightfield = mHeightfields.end(); mHeightfields.erase(it); ++mRevision; } addChangedTiles(range, ChangeType::remove); } std::shared_ptr<RecastMesh> TileCachedRecastMeshManager::getMesh( ESM::RefId worldspace, const TilePosition& tilePosition) { { const std::lock_guard lock(mMutex); if (mWorldspace != worldspace) return nullptr; if (!isInTilesPositionsRange(mRange, tilePosition)) return nullptr; const auto it = mCache.find(tilePosition); if (it != mCache.end() && it->second.mRecastMesh->getVersion() == it->second.mVersion) return it->second.mRecastMesh; } auto result = makeMesh(tilePosition); if (result != nullptr) { const std::lock_guard lock(mMutex); mCache.insert_or_assign(tilePosition, CachedTile{ .mVersion = result->getVersion(), .mRecastMesh = result, }); } return result; } std::shared_ptr<RecastMesh> TileCachedRecastMeshManager::getCachedMesh( ESM::RefId worldspace, const TilePosition& tilePosition) const { const std::lock_guard lock(mMutex); if (mWorldspace != worldspace) return nullptr; if (!isInTilesPositionsRange(mRange, tilePosition)) return nullptr; const auto it = mCache.find(tilePosition); if (it == mCache.end()) return nullptr; return it->second.mRecastMesh; } std::shared_ptr<RecastMesh> TileCachedRecastMeshManager::getNewMesh( ESM::RefId worldspace, const TilePosition& tilePosition) const { { const std::lock_guard lock(mMutex); if (mWorldspace != worldspace) return nullptr; } return makeMesh(tilePosition); } void TileCachedRecastMeshManager::reportNavMeshChange( const TilePosition& tilePosition, Version recastMeshVersion, Version navMeshVersion) { const std::lock_guard lock(mMutex); for (auto it = mObjectIndex.qbegin(makeIndexQuery(tilePosition)); it != mObjectIndex.qend(); ++it) { ObjectData& object = *it->second; if (recastMeshVersion.mGeneration != object.mGeneration) continue; if (object.mLastNavMeshReport.has_value() && navMeshVersion < object.mLastNavMeshReport->mNavMeshVersion) continue; object.mLastNavMeshReport = { recastMeshVersion.mRevision, navMeshVersion }; if (!object.mLastNavMeshReportedChange.has_value() || object.mLastNavMeshReportedChange->mNavMeshVersion < object.mLastNavMeshReport->mNavMeshVersion) object.mLastNavMeshReportedChange = object.mLastNavMeshReport; } } void TileCachedRecastMeshManager::addChangedTile(const TilePosition& tilePosition, const ChangeType changeType) { auto tile = mChangedTiles.find(tilePosition); if (tile == mChangedTiles.end()) mChangedTiles.emplace(tilePosition, changeType); else tile->second = changeType == ChangeType::remove ? changeType : tile->second; } std::map<osg::Vec2i, ChangeType> TileCachedRecastMeshManager::takeChangedTiles(const UpdateGuard* guard) { { const MaybeLockGuard lock(mMutex, guard); for (const auto& [tilePosition, changeType] : mChangedTiles) if (const auto it = mCache.find(tilePosition); it != mCache.end()) ++it->second.mVersion.mRevision; } return std::move(mChangedTiles); } TileCachedRecastMeshManagerStats TileCachedRecastMeshManager::getStats() const { const std::lock_guard lock(mMutex); return TileCachedRecastMeshManagerStats{ .mTiles = mCache.size(), .mObjects = mObjects.size(), .mHeightfields = mHeightfields.size(), .mWater = mWater.size(), }; } TileCachedRecastMeshManager::IndexPoint TileCachedRecastMeshManager::makeIndexPoint( const TilePosition& tilePosition) { return IndexPoint(tilePosition.x(), tilePosition.y()); } TileCachedRecastMeshManager::IndexBox TileCachedRecastMeshManager::makeIndexBox(const TilesPositionsRange& range) { assert(range.mBegin != range.mEnd); return IndexBox(makeIndexPoint(range.mBegin), makeIndexPoint(range.mEnd - TilePosition(1, 1))); } TileCachedRecastMeshManager::ObjectIndexValue TileCachedRecastMeshManager::makeObjectIndexValue( const TilesPositionsRange& range, ObjectData* id) { return { makeIndexBox(range), id }; } TileCachedRecastMeshManager::WaterIndexValue TileCachedRecastMeshManager::makeWaterIndexValue( const TilesPositionsRange& range, std::map<osg::Vec2i, WaterData>::const_iterator it) { return { makeIndexBox(range), it }; } TileCachedRecastMeshManager::HeightfieldIndexValue TileCachedRecastMeshManager::makeHeightfieldIndexValue( const TilesPositionsRange& range, std::map<osg::Vec2i, HeightfieldData>::const_iterator it) { return { makeIndexBox(range), it }; } auto TileCachedRecastMeshManager::makeIndexQuery(const TilePosition& tilePosition) -> decltype(boost::geometry::index::intersects(IndexBox())) { const IndexPoint point = makeIndexPoint(tilePosition); return boost::geometry::index::intersects(IndexBox(point, point)); } std::shared_ptr<RecastMesh> TileCachedRecastMeshManager::makeMesh(const TilePosition& tilePosition) const { RecastMeshBuilder builder(makeRealTileBoundsWithBorder(mSettings, tilePosition)); using Object = std::tuple<osg::ref_ptr<const Resource::BulletShapeInstance>, ObjectTransform, std::reference_wrapper<const btCollisionShape>, btTransform, AreaType>; std::vector<Object> objects; Version version; bool hasInput = false; { const std::lock_guard lock(mMutex); for (auto it = mWaterIndex.qbegin(makeIndexQuery(tilePosition)); it != mWaterIndex.qend(); ++it) { const auto& [cellPosition, data] = *it->second; builder.addWater(cellPosition, data.mWater); hasInput = true; } for (auto it = mHeightfieldIndex.qbegin(makeIndexQuery(tilePosition)); it != mHeightfieldIndex.qend(); ++it) { const auto& [cellPosition, data] = *it->second; std::visit(AddHeightfield{ cellPosition, data.mCellSize, builder }, data.mShape); hasInput = true; } objects.reserve(mObjects.size()); for (auto it = mObjectIndex.qbegin(makeIndexQuery(tilePosition)); it != mObjectIndex.qend(); ++it) { const auto& object = it->second->mObject; objects.emplace_back(object.getInstance(), object.getObjectTransform(), object.getShape(), object.getTransform(), object.getAreaType()); hasInput = true; } if (hasInput) { if (mInfiniteWater != mWater.end()) builder.addWater(mInfiniteWater->first, mInfiniteWater->second.mWater); if (mInfiniteHeightfield != mHeightfields.end()) std::visit( AddHeightfield{ mInfiniteHeightfield->first, mInfiniteHeightfield->second.mCellSize, builder }, mInfiniteHeightfield->second.mShape); version.mGeneration = mGeneration; version.mRevision = mRevision; } } if (!hasInput) return nullptr; for (const auto& [instance, objectTransform, shape, transform, areaType] : objects) builder.addObject(shape, transform, areaType, instance->getSource(), objectTransform); return std::move(builder).create(version); } void TileCachedRecastMeshManager::addChangedTiles( const std::optional<TilesPositionsRange>& range, ChangeType changeType) { if (range.has_value()) getTilesPositions(*range, [&](const TilePosition& v) { addChangedTile(v, changeType); }); } }
21,628
C++
.cpp
499
31.651303
120
0.599222
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,463
navmeshtileview.cpp
OpenMW_openmw/components/detournavigator/navmeshtileview.cpp
#include "navmeshtileview.hpp" #include "ref.hpp" #include <DetourCommon.h> #include <DetourNavMesh.h> #include <algorithm> #include <cassert> #include <stdexcept> #include <tuple> inline bool operator==(const dtMeshHeader& lhs, const dtMeshHeader& rhs) noexcept { const auto makeTuple = [](const dtMeshHeader& v) { using DetourNavigator::ArrayRef; return std::tuple(v.x, v.y, v.layer, v.userId, v.polyCount, v.vertCount, v.maxLinkCount, v.detailMeshCount, v.detailVertCount, v.detailTriCount, v.bvNodeCount, v.offMeshConCount, v.offMeshBase, v.walkableHeight, v.walkableRadius, v.walkableClimb, v.detailVertCount, ArrayRef(v.bmin), ArrayRef(v.bmax), v.bvQuantFactor); }; return makeTuple(lhs) == makeTuple(rhs); } inline bool operator==(const dtPoly& lhs, const dtPoly& rhs) noexcept { const auto makeTuple = [](const dtPoly& v) { using DetourNavigator::ArrayRef; return std::tuple(ArrayRef(v.verts), ArrayRef(v.neis), v.flags, v.vertCount, v.areaAndtype); }; return makeTuple(lhs) == makeTuple(rhs); } inline bool operator==(const dtPolyDetail& lhs, const dtPolyDetail& rhs) noexcept { const auto makeTuple = [](const dtPolyDetail& v) { return std::tuple(v.vertBase, v.triBase, v.vertCount, v.triCount); }; return makeTuple(lhs) == makeTuple(rhs); } inline bool operator==(const dtBVNode& lhs, const dtBVNode& rhs) noexcept { const auto makeTuple = [](const dtBVNode& v) { using DetourNavigator::ArrayRef; return std::tuple(ArrayRef(v.bmin), ArrayRef(v.bmax), v.i); }; return makeTuple(lhs) == makeTuple(rhs); } inline bool operator==(const dtOffMeshConnection& lhs, const dtOffMeshConnection& rhs) noexcept { const auto makeTuple = [](const dtOffMeshConnection& v) { using DetourNavigator::ArrayRef; return std::tuple(ArrayRef(v.pos), v.rad, v.poly, v.flags, v.side, v.userId); }; return makeTuple(lhs) == makeTuple(rhs); } namespace DetourNavigator { NavMeshTileConstView asNavMeshTileConstView(const unsigned char* data) { const dtMeshHeader* header = reinterpret_cast<const dtMeshHeader*>(data); if (header->magic != DT_NAVMESH_MAGIC) throw std::logic_error("Invalid navmesh magic"); if (header->version != DT_NAVMESH_VERSION) throw std::logic_error("Invalid navmesh version"); // Similar code to // https://github.com/recastnavigation/recastnavigation/blob/c5cbd53024c8a9d8d097a4371215e3342d2fdc87/Detour/Source/DetourNavMesh.cpp#L978-L996 const int headerSize = dtAlign4(sizeof(dtMeshHeader)); const int vertsSize = dtAlign4(sizeof(float) * 3 * header->vertCount); const int polysSize = dtAlign4(sizeof(dtPoly) * header->polyCount); const int linksSize = dtAlign4(sizeof(dtLink) * (header->maxLinkCount)); const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail) * header->detailMeshCount); const int detailVertsSize = dtAlign4(sizeof(float) * 3 * header->detailVertCount); const int detailTrisSize = dtAlign4(sizeof(unsigned char) * 4 * header->detailTriCount); const int bvtreeSize = dtAlign4(sizeof(dtBVNode) * header->bvNodeCount); const int offMeshLinksSize = dtAlign4(sizeof(dtOffMeshConnection) * header->offMeshConCount); const unsigned char* ptr = data + headerSize; NavMeshTileConstView view; view.mHeader = header; view.mVerts = dtGetThenAdvanceBufferPointer<const float>(ptr, vertsSize); view.mPolys = dtGetThenAdvanceBufferPointer<const dtPoly>(ptr, polysSize); ptr += linksSize; view.mDetailMeshes = dtGetThenAdvanceBufferPointer<const dtPolyDetail>(ptr, detailMeshesSize); view.mDetailVerts = dtGetThenAdvanceBufferPointer<const float>(ptr, detailVertsSize); view.mDetailTris = dtGetThenAdvanceBufferPointer<const unsigned char>(ptr, detailTrisSize); view.mBvTree = dtGetThenAdvanceBufferPointer<const dtBVNode>(ptr, bvtreeSize); view.mOffMeshCons = dtGetThenAdvanceBufferPointer<const dtOffMeshConnection>(ptr, offMeshLinksSize); return view; } NavMeshTileConstView asNavMeshTileConstView(const dtMeshTile& tile) { NavMeshTileConstView view; view.mHeader = tile.header; view.mPolys = tile.polys; view.mVerts = tile.verts; view.mDetailMeshes = tile.detailMeshes; view.mDetailVerts = tile.detailVerts; view.mDetailTris = tile.detailTris; view.mBvTree = tile.bvTree; view.mOffMeshCons = tile.offMeshCons; return view; } bool operator==(const NavMeshTileConstView& lhs, const NavMeshTileConstView& rhs) noexcept { using DetourNavigator::Ref; using DetourNavigator::Span; const auto makeTuple = [](const DetourNavigator::NavMeshTileConstView& v) { return std::tuple(Ref(*v.mHeader), Span(v.mPolys, v.mHeader->polyCount), Span(v.mVerts, v.mHeader->vertCount), Span(v.mDetailMeshes, v.mHeader->detailMeshCount), Span(v.mDetailVerts, v.mHeader->detailVertCount), Span(v.mDetailTris, v.mHeader->detailTriCount), Span(v.mBvTree, v.mHeader->bvNodeCount), Span(v.mOffMeshCons, v.mHeader->offMeshConCount)); }; return makeTuple(lhs) == makeTuple(rhs); } }
5,388
C++
.cpp
107
43.570093
151
0.706005
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,464
stats.cpp
OpenMW_openmw/components/detournavigator/stats.cpp
#include "stats.hpp" #include <osg/Stats> namespace DetourNavigator { namespace { void reportStats(const AsyncNavMeshUpdaterStats& stats, unsigned int frameNumber, osg::Stats& out) { out.setAttribute(frameNumber, "NavMesh Jobs", static_cast<double>(stats.mJobs)); out.setAttribute(frameNumber, "NavMesh Removing", static_cast<double>(stats.mWaiting.mRemoving)); out.setAttribute(frameNumber, "NavMesh Updating", static_cast<double>(stats.mWaiting.mUpdating)); out.setAttribute(frameNumber, "NavMesh Delayed", static_cast<double>(stats.mWaiting.mDelayed)); out.setAttribute(frameNumber, "NavMesh Pushed", static_cast<double>(stats.mPushed)); out.setAttribute(frameNumber, "NavMesh Processing", static_cast<double>(stats.mProcessing)); if (stats.mDb.has_value()) { out.setAttribute( frameNumber, "NavMesh DbJobs Read", static_cast<double>(stats.mDb->mJobs.mReadingJobs)); out.setAttribute( frameNumber, "NavMesh DbJobs Write", static_cast<double>(stats.mDb->mJobs.mWritingJobs)); out.setAttribute(frameNumber, "NavMesh DbCache Get", static_cast<double>(stats.mDb->mGetTileCount)); out.setAttribute(frameNumber, "NavMesh DbCache Hit", static_cast<double>(stats.mDbGetTileHits)); } out.setAttribute(frameNumber, "NavMesh CacheSize", static_cast<double>(stats.mCache.mNavMeshCacheSize)); out.setAttribute(frameNumber, "NavMesh UsedTiles", static_cast<double>(stats.mCache.mUsedNavMeshTiles)); out.setAttribute(frameNumber, "NavMesh CachedTiles", static_cast<double>(stats.mCache.mCachedNavMeshTiles)); out.setAttribute(frameNumber, "NavMesh Cache Get", static_cast<double>(stats.mCache.mGetCount)); out.setAttribute(frameNumber, "NavMesh Cache Hit", static_cast<double>(stats.mCache.mHitCount)); } void reportStats(const TileCachedRecastMeshManagerStats& stats, unsigned int frameNumber, osg::Stats& out) { out.setAttribute(frameNumber, "NavMesh Recast Tiles", static_cast<double>(stats.mTiles)); out.setAttribute(frameNumber, "NavMesh Recast Objects", static_cast<double>(stats.mObjects)); out.setAttribute(frameNumber, "NavMesh Recast Heightfields", static_cast<double>(stats.mHeightfields)); out.setAttribute(frameNumber, "NavMesh Recast Water", static_cast<double>(stats.mWater)); } } void reportStats(const Stats& stats, unsigned int frameNumber, osg::Stats& out) { reportStats(stats.mUpdater, frameNumber, out); reportStats(stats.mRecast, frameNumber, out); } }
2,778
C++
.cpp
43
53.953488
120
0.687683
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,465
navmeshcacheitem.cpp
OpenMW_openmw/components/detournavigator/navmeshcacheitem.cpp
#include "navmeshcacheitem.hpp" #include "debug.hpp" #include "makenavmesh.hpp" #include "navmeshdata.hpp" #include "navmeshtilescache.hpp" #include "navmeshtileview.hpp" #include "settings.hpp" #include "tileposition.hpp" #include <DetourNavMesh.h> #include <ostream> #include <sstream> namespace { using DetourNavigator::TilePosition; bool removeTile(dtNavMesh& navMesh, const TilePosition& position) { const int layer = 0; const auto tileRef = navMesh.getTileRefAt(position.x(), position.y(), layer); if (tileRef == 0) return false; unsigned char** const data = nullptr; int* const dataSize = nullptr; return dtStatusSucceed(navMesh.removeTile(tileRef, data, dataSize)); } dtStatus addTile(dtNavMesh& navMesh, unsigned char* data, int size) { const int doNotTransferOwnership = 0; const dtTileRef lastRef = 0; dtTileRef* const result = nullptr; return navMesh.addTile(data, size, doNotTransferOwnership, lastRef, result); } } namespace DetourNavigator { std::ostream& operator<<(std::ostream& stream, UpdateNavMeshStatus value) { switch (value) { case UpdateNavMeshStatus::ignored: return stream << "ignore"; case UpdateNavMeshStatus::removed: return stream << "removed"; case UpdateNavMeshStatus::added: return stream << "add"; case UpdateNavMeshStatus::replaced: return stream << "replaced"; case UpdateNavMeshStatus::failed: return stream << "failed"; case UpdateNavMeshStatus::lost: return stream << "lost"; case UpdateNavMeshStatus::cached: return stream << "cached"; case UpdateNavMeshStatus::unchanged: return stream << "unchanged"; case UpdateNavMeshStatus::restored: return stream << "restored"; } return stream << "unknown(" << static_cast<unsigned>(value) << ")"; } const dtMeshTile* getTile(const dtNavMesh& navMesh, const TilePosition& position) { const int layer = 0; return navMesh.getTileAt(position.x(), position.y(), layer); } NavMeshCacheItem::NavMeshCacheItem(std::size_t generation, const Settings& settings) : mVersion{ generation, 0 } { initEmptyNavMesh(settings, mImpl); if (const dtStatus status = mQuery.init(&mImpl, settings.mDetour.mMaxNavMeshQueryNodes); !dtStatusSucceed(status)) { std::ostringstream error; error << "Failed to init navmesh query: " << WriteDtStatus{ status }; throw std::runtime_error(error.str()); } } UpdateNavMeshStatus NavMeshCacheItem::updateTile( const TilePosition& position, NavMeshTilesCache::Value&& cached, NavMeshData&& navMeshData) { const dtMeshTile* currentTile = getTile(mImpl, position); if (currentTile != nullptr && asNavMeshTileConstView(*currentTile) == asNavMeshTileConstView(navMeshData.mValue.get())) { return UpdateNavMeshStatus::ignored; } bool removed = ::removeTile(mImpl, position); removed = mEmptyTiles.erase(position) > 0 || removed; const auto addStatus = addTile(mImpl, navMeshData.mValue.get(), navMeshData.mSize); if (dtStatusSucceed(addStatus)) { auto tile = mUsedTiles.find(position); if (tile == mUsedTiles.end()) { mUsedTiles.emplace_hint(tile, position, Tile{ Version{ mVersion.mRevision, 1 }, std::move(cached), std::move(navMeshData) }); } else { ++tile->second.mVersion.mRevision; tile->second.mCached = std::move(cached); tile->second.mData = std::move(navMeshData); } ++mVersion.mRevision; return UpdateNavMeshStatusBuilder().added(true).removed(removed).getResult(); } else { if (removed) { mUsedTiles.erase(position); ++mVersion.mRevision; } return UpdateNavMeshStatusBuilder() .removed(removed) .failed((addStatus & DT_OUT_OF_MEMORY) != 0) .getResult(); } } UpdateNavMeshStatus NavMeshCacheItem::removeTile(const TilePosition& position) { bool removed = ::removeTile(mImpl, position); removed = mEmptyTiles.erase(position) > 0 || removed; if (removed) { mUsedTiles.erase(position); ++mVersion.mRevision; } return UpdateNavMeshStatusBuilder().removed(removed).getResult(); } UpdateNavMeshStatus NavMeshCacheItem::markAsEmpty(const TilePosition& position) { bool removed = ::removeTile(mImpl, position); removed = mEmptyTiles.insert(position).second || removed; if (removed) { mUsedTiles.erase(position); ++mVersion.mRevision; } return UpdateNavMeshStatusBuilder().removed(removed).getResult(); } bool NavMeshCacheItem::isEmptyTile(const TilePosition& position) const { return mEmptyTiles.find(position) != mEmptyTiles.end(); } }
5,441
C++
.cpp
145
28.158621
105
0.612909
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,466
navmeshdbutils.cpp
OpenMW_openmw/components/detournavigator/navmeshdbutils.cpp
#include "navmeshdbutils.hpp" #include "navmeshdb.hpp" #include "recastmesh.hpp" #include "components/debug/debuglog.hpp" #include "components/misc/strings/conversion.hpp" #include <cassert> #include <optional> #include <string_view> namespace DetourNavigator { namespace { std::optional<ShapeId> findShapeId( NavMeshDb& db, std::string_view name, ShapeType type, const std::string& hash) { const Sqlite3::ConstBlob hashData{ hash.data(), static_cast<int>(hash.size()) }; return db.findShapeId(name, type, hashData); } ShapeId getShapeId( NavMeshDb& db, std::string_view name, ShapeType type, const std::string& hash, ShapeId& nextShapeId) { const Sqlite3::ConstBlob hashData{ hash.data(), static_cast<int>(hash.size()) }; if (const auto existingShapeId = db.findShapeId(name, type, hashData)) return *existingShapeId; const ShapeId newShapeId = nextShapeId; db.insertShape(newShapeId, name, type, hashData); Log(Debug::Verbose) << "Added " << name << " " << Misc::StringUtils::toHex(hash) << " " << type << " shape to navmeshdb with id " << newShapeId; ++nextShapeId; return newShapeId; } } ShapeId resolveMeshSource(NavMeshDb& db, const MeshSource& source, ShapeId& nextShapeId) { switch (source.mAreaType) { case AreaType_null: return getShapeId( db, source.mShape->mFileName, ShapeType::Avoid, source.mShape->mFileHash, nextShapeId); case AreaType_ground: return getShapeId( db, source.mShape->mFileName, ShapeType::Collision, source.mShape->mFileHash, nextShapeId); default: Log(Debug::Warning) << "Trying to resolve recast mesh source with unsupported area type: " << source.mAreaType; assert(false); return ShapeId(0); } } std::optional<ShapeId> resolveMeshSource(NavMeshDb& db, const MeshSource& source) { switch (source.mAreaType) { case AreaType_null: return findShapeId(db, source.mShape->mFileName, ShapeType::Avoid, source.mShape->mFileHash); case AreaType_ground: return findShapeId(db, source.mShape->mFileName, ShapeType::Collision, source.mShape->mFileHash); default: Log(Debug::Warning) << "Trying to resolve recast mesh source with unsupported area type: " << source.mAreaType; return std::nullopt; } } }
2,770
C++
.cpp
64
32.1875
113
0.596296
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,467
recastmesh.cpp
OpenMW_openmw/components/detournavigator/recastmesh.cpp
#include "recastmesh.hpp" #include "exceptions.hpp" namespace DetourNavigator { Mesh::Mesh(std::vector<int>&& indices, std::vector<float>&& vertices, std::vector<AreaType>&& areaTypes) { if (indices.size() / 3 != areaTypes.size()) throw InvalidArgument("Number of flags doesn't match number of triangles: triangles=" + std::to_string(indices.size() / 3) + ", areaTypes=" + std::to_string(areaTypes.size())); indices.shrink_to_fit(); vertices.shrink_to_fit(); areaTypes.shrink_to_fit(); mIndices = std::move(indices); mVertices = std::move(vertices); mAreaTypes = std::move(areaTypes); } RecastMesh::RecastMesh(const Version& version, Mesh mesh, std::vector<CellWater> water, std::vector<Heightfield> heightfields, std::vector<FlatHeightfield> flatHeightfields, std::vector<MeshSource> meshSources) : mVersion(version) , mMesh(std::move(mesh)) , mWater(std::move(water)) , mHeightfields(std::move(heightfields)) , mFlatHeightfields(std::move(flatHeightfields)) , mMeshSources(std::move(meshSources)) { mWater.shrink_to_fit(); mHeightfields.shrink_to_fit(); for (Heightfield& v : mHeightfields) v.mHeights.shrink_to_fit(); } }
1,335
C++
.cpp
32
34.15625
108
0.640277
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,468
navigatorimpl.cpp
OpenMW_openmw/components/detournavigator/navigatorimpl.cpp
#include "navigatorimpl.hpp" #include "makenavmesh.hpp" #include "settingsutils.hpp" #include "stats.hpp" #include <components/esm3/loadpgrd.hpp> #include <components/misc/convert.hpp> #include <components/misc/coordinateconverter.hpp> namespace DetourNavigator { NavigatorImpl::NavigatorImpl(const Settings& settings, std::unique_ptr<NavMeshDb>&& db) : mSettings(settings) , mNavMeshManager(mSettings, std::move(db)) { } bool NavigatorImpl::addAgent(const AgentBounds& agentBounds) { if (!isSupportedAgentBounds(mSettings.mRecast, agentBounds)) return false; ++mAgents[agentBounds]; mNavMeshManager.addAgent(agentBounds); return true; } void NavigatorImpl::removeAgent(const AgentBounds& agentBounds) { const auto it = mAgents.find(agentBounds); if (it == mAgents.end()) return; if (it->second > 0) --it->second; } void NavigatorImpl::updateBounds(ESM::RefId worldspace, const std::optional<CellGridBounds>& cellGridBounds, const osg::Vec3f& playerPosition, const UpdateGuard* guard) { mNavMeshManager.updateBounds(worldspace, cellGridBounds, playerPosition, guard); } void NavigatorImpl::addObject( const ObjectId id, const ObjectShapes& shapes, const btTransform& transform, const UpdateGuard* guard) { addObjectImpl(id, shapes, transform, guard); } bool NavigatorImpl::addObjectImpl( const ObjectId id, const ObjectShapes& shapes, const btTransform& transform, const UpdateGuard* guard) { const CollisionShape collisionShape( shapes.mShapeInstance, *shapes.mShapeInstance->mCollisionShape, shapes.mTransform); bool result = mNavMeshManager.addObject(id, collisionShape, transform, AreaType_ground, guard); if (const btCollisionShape* const avoidShape = shapes.mShapeInstance->mAvoidCollisionShape.get()) { const ObjectId avoidId(avoidShape); const CollisionShape avoidCollisionShape(shapes.mShapeInstance, *avoidShape, shapes.mTransform); if (mNavMeshManager.addObject(avoidId, avoidCollisionShape, transform, AreaType_null, guard)) { updateAvoidShapeId(id, avoidId, guard); result = true; } } return result; } void NavigatorImpl::addObject( const ObjectId id, const DoorShapes& shapes, const btTransform& transform, const UpdateGuard* guard) { if (addObjectImpl(id, static_cast<const ObjectShapes&>(shapes), transform, guard)) { const osg::Vec3f start = toNavMeshCoordinates(mSettings.mRecast, shapes.mConnectionStart); const osg::Vec3f end = toNavMeshCoordinates(mSettings.mRecast, shapes.mConnectionEnd); mNavMeshManager.addOffMeshConnection(id, start, end, AreaType_door); mNavMeshManager.addOffMeshConnection(id, end, start, AreaType_door); } } void NavigatorImpl::updateObject( const ObjectId id, const ObjectShapes& shapes, const btTransform& transform, const UpdateGuard* guard) { mNavMeshManager.updateObject(id, transform, AreaType_ground, guard); if (const btCollisionShape* const avoidShape = shapes.mShapeInstance->mAvoidCollisionShape.get()) { const ObjectId avoidId(avoidShape); if (mNavMeshManager.updateObject(avoidId, transform, AreaType_null, guard)) updateAvoidShapeId(id, avoidId, guard); } } void NavigatorImpl::updateObject( const ObjectId id, const DoorShapes& shapes, const btTransform& transform, const UpdateGuard* guard) { return updateObject(id, static_cast<const ObjectShapes&>(shapes), transform, guard); } void NavigatorImpl::removeObject(const ObjectId id, const UpdateGuard* guard) { mNavMeshManager.removeObject(id, guard); const auto avoid = mAvoidIds.find(id); if (avoid != mAvoidIds.end()) mNavMeshManager.removeObject(avoid->second, guard); const auto water = mWaterIds.find(id); if (water != mWaterIds.end()) mNavMeshManager.removeObject(water->second, guard); mNavMeshManager.removeOffMeshConnections(id); } void NavigatorImpl::addWater(const osg::Vec2i& cellPosition, int cellSize, float level, const UpdateGuard* guard) { mNavMeshManager.addWater(cellPosition, cellSize, level, guard); } void NavigatorImpl::removeWater(const osg::Vec2i& cellPosition, const UpdateGuard* guard) { mNavMeshManager.removeWater(cellPosition, guard); } void NavigatorImpl::addHeightfield( const osg::Vec2i& cellPosition, int cellSize, const HeightfieldShape& shape, const UpdateGuard* guard) { mNavMeshManager.addHeightfield(cellPosition, cellSize, shape, guard); } void NavigatorImpl::removeHeightfield(const osg::Vec2i& cellPosition, const UpdateGuard* guard) { mNavMeshManager.removeHeightfield(cellPosition, guard); } void NavigatorImpl::addPathgrid(const ESM::Cell& cell, const ESM::Pathgrid& pathgrid) { const Misc::CoordinateConverter converter = Misc::makeCoordinateConverter(cell); for (const auto& edge : pathgrid.mEdges) { const auto src = Misc::Convert::makeOsgVec3f(converter.toWorldPoint(pathgrid.mPoints[edge.mV0])); const auto dst = Misc::Convert::makeOsgVec3f(converter.toWorldPoint(pathgrid.mPoints[edge.mV1])); mNavMeshManager.addOffMeshConnection(ObjectId(&pathgrid), toNavMeshCoordinates(mSettings.mRecast, src), toNavMeshCoordinates(mSettings.mRecast, dst), AreaType_pathgrid); } } void NavigatorImpl::removePathgrid(const ESM::Pathgrid& pathgrid) { mNavMeshManager.removeOffMeshConnections(ObjectId(&pathgrid)); } void NavigatorImpl::update(const osg::Vec3f& playerPosition, const UpdateGuard* guard) { removeUnusedNavMeshes(); mNavMeshManager.update(playerPosition, guard); } void NavigatorImpl::wait(WaitConditionType waitConditionType, Loading::Listener* listener) { mNavMeshManager.wait(waitConditionType, listener); } SharedNavMeshCacheItem NavigatorImpl::getNavMesh(const AgentBounds& agentBounds) const { return mNavMeshManager.getNavMesh(agentBounds); } std::map<AgentBounds, SharedNavMeshCacheItem> NavigatorImpl::getNavMeshes() const { return mNavMeshManager.getNavMeshes(); } const Settings& NavigatorImpl::getSettings() const { return mSettings; } Stats NavigatorImpl::getStats() const { return mNavMeshManager.getStats(); } RecastMeshTiles NavigatorImpl::getRecastMeshTiles() const { return mNavMeshManager.getRecastMeshTiles(); } void NavigatorImpl::updateAvoidShapeId(const ObjectId id, const ObjectId avoidId, const UpdateGuard* guard) { updateId(id, avoidId, mWaterIds, guard); } void NavigatorImpl::updateId(const ObjectId id, const ObjectId updateId, std::unordered_map<ObjectId, ObjectId>& ids, const UpdateGuard* guard) { auto inserted = ids.insert(std::make_pair(id, updateId)); if (!inserted.second) { mNavMeshManager.removeObject(inserted.first->second, guard); inserted.first->second = updateId; } } void NavigatorImpl::removeUnusedNavMeshes() { for (auto it = mAgents.begin(); it != mAgents.end();) { if (it->second == 0 && mNavMeshManager.reset(it->first)) it = mAgents.erase(it); else ++it; } } float NavigatorImpl::getMaxNavmeshAreaRealRadius() const { const auto& settings = getSettings(); return getRealTileSize(settings.mRecast) * getMaxNavmeshAreaRadius(settings); } }
8,015
C++
.cpp
187
35.101604
117
0.691538
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,469
gettilespositions.cpp
OpenMW_openmw/components/detournavigator/gettilespositions.cpp
#include "gettilespositions.hpp" #include "settings.hpp" #include "settingsutils.hpp" #include "tilebounds.hpp" #include "tileposition.hpp" #include <components/misc/convert.hpp> #include <BulletCollision/CollisionShapes/btCollisionShape.h> namespace DetourNavigator { TilesPositionsRange makeTilesPositionsRange( const osg::Vec2f& aabbMin, const osg::Vec2f& aabbMax, const RecastSettings& settings) { osg::Vec2f min = toNavMeshCoordinates(settings, aabbMin); osg::Vec2f max = toNavMeshCoordinates(settings, aabbMax); const float border = getBorderSize(settings); min -= osg::Vec2f(border, border); max += osg::Vec2f(border, border); TilePosition minTile = getTilePosition(settings, min); TilePosition maxTile = getTilePosition(settings, max); if (minTile.x() > maxTile.x()) std::swap(minTile.x(), maxTile.x()); if (minTile.y() > maxTile.y()) std::swap(minTile.y(), maxTile.y()); return { minTile, maxTile + osg::Vec2i(1, 1) }; } TilesPositionsRange makeTilesPositionsRange( const btCollisionShape& shape, const btTransform& transform, const RecastSettings& settings) { const TileBounds bounds = makeObjectTileBounds(shape, transform); return makeTilesPositionsRange(bounds.mMin, bounds.mMax, settings); } TilesPositionsRange makeTilesPositionsRange(const btCollisionShape& shape, const btTransform& transform, const TileBounds& bounds, const RecastSettings& settings) { if (const auto intersection = getIntersection(bounds, makeObjectTileBounds(shape, transform))) return makeTilesPositionsRange(intersection->mMin, intersection->mMax, settings); return {}; } TilesPositionsRange makeTilesPositionsRange( const int cellSize, const btVector3& shift, const RecastSettings& settings) { const int halfCellSize = cellSize / 2; const btTransform transform(btMatrix3x3::getIdentity(), shift); btVector3 aabbMin = transform(btVector3(-halfCellSize, -halfCellSize, 0)); btVector3 aabbMax = transform(btVector3(halfCellSize, halfCellSize, 0)); aabbMin.setX(std::min(aabbMin.x(), aabbMax.x())); aabbMin.setY(std::min(aabbMin.y(), aabbMax.y())); aabbMax.setX(std::max(aabbMin.x(), aabbMax.x())); aabbMax.setY(std::max(aabbMin.y(), aabbMax.y())); return makeTilesPositionsRange(Misc::Convert::toOsgXY(aabbMin), Misc::Convert::toOsgXY(aabbMax), settings); } TilesPositionsRange getIntersection(const TilesPositionsRange& a, const TilesPositionsRange& b) noexcept { const int beginX = std::max(a.mBegin.x(), b.mBegin.x()); const int endX = std::min(a.mEnd.x(), b.mEnd.x()); if (beginX > endX) return {}; const int beginY = std::max(a.mBegin.y(), b.mBegin.y()); const int endY = std::min(a.mEnd.y(), b.mEnd.y()); if (beginY > endY) return {}; return TilesPositionsRange{ TilePosition(beginX, beginY), TilePosition(endX, endY) }; } TilesPositionsRange getUnion(const TilesPositionsRange& a, const TilesPositionsRange& b) noexcept { const int beginX = std::min(a.mBegin.x(), b.mBegin.x()); const int endX = std::max(a.mEnd.x(), b.mEnd.x()); const int beginY = std::min(a.mBegin.y(), b.mBegin.y()); const int endY = std::max(a.mEnd.y(), b.mEnd.y()); return TilesPositionsRange{ .mBegin = TilePosition(beginX, beginY), .mEnd = TilePosition(endX, endY) }; } }
3,600
C++
.cpp
72
42.611111
115
0.677107
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,470
preparednavmeshdata.cpp
OpenMW_openmw/components/detournavigator/preparednavmeshdata.cpp
#include "preparednavmeshdata.hpp" #include "preparednavmeshdatatuple.hpp" #include "recast.hpp" #include <Recast.h> #include <cstring> namespace { void initPolyMeshDetail(rcPolyMeshDetail& value) noexcept { value.meshes = nullptr; value.verts = nullptr; value.tris = nullptr; value.nmeshes = 0; value.nverts = 0; value.ntris = 0; } } namespace DetourNavigator { PreparedNavMeshData::PreparedNavMeshData() noexcept { initPolyMeshDetail(mPolyMeshDetail); } PreparedNavMeshData::PreparedNavMeshData(const PreparedNavMeshData& other) : mUserId(other.mUserId) , mCellSize(other.mCellSize) , mCellHeight(other.mCellHeight) { copyPolyMesh(other.mPolyMesh, mPolyMesh); copyPolyMeshDetail(other.mPolyMeshDetail, mPolyMeshDetail); } PreparedNavMeshData::~PreparedNavMeshData() noexcept { freePolyMeshDetail(mPolyMeshDetail); } bool operator==(const PreparedNavMeshData& lhs, const PreparedNavMeshData& rhs) noexcept { return makeTuple(lhs) == makeTuple(rhs); } }
1,133
C++
.cpp
40
22.85
92
0.703499
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,471
navmeshtilescache.cpp
OpenMW_openmw/components/detournavigator/navmeshtilescache.cpp
#include "navmeshtilescache.hpp" #include "stats.hpp" #include <cstring> namespace DetourNavigator { NavMeshTilesCache::NavMeshTilesCache(const std::size_t maxNavMeshDataSize) : mMaxNavMeshDataSize(maxNavMeshDataSize) , mUsedNavMeshDataSize(0) , mFreeNavMeshDataSize(0) , mHitCount(0) , mGetCount(0) { } NavMeshTilesCache::Value NavMeshTilesCache::get( const AgentBounds& agentBounds, const TilePosition& changedTile, const RecastMesh& recastMesh) { const std::lock_guard<std::mutex> lock(mMutex); ++mGetCount; const auto tile = mValues.find(std::tie(agentBounds, changedTile, recastMesh)); if (tile == mValues.end()) return Value(); acquireItemUnsafe(tile->second); ++mHitCount; return Value(*this, tile->second); } NavMeshTilesCache::Value NavMeshTilesCache::set(const AgentBounds& agentBounds, const TilePosition& changedTile, const RecastMesh& recastMesh, std::unique_ptr<PreparedNavMeshData>&& value) { const auto itemSize = sizeof(RecastMesh) + getSize(recastMesh) + (value == nullptr ? 0 : sizeof(PreparedNavMeshData) + getSize(*value)); const std::lock_guard<std::mutex> lock(mMutex); if (itemSize > mFreeNavMeshDataSize + (mMaxNavMeshDataSize - mUsedNavMeshDataSize)) return Value(); while (!mFreeItems.empty() && mUsedNavMeshDataSize + itemSize > mMaxNavMeshDataSize) removeLeastRecentlyUsed(); RecastMeshData key{ recastMesh.getMesh(), recastMesh.getWater(), recastMesh.getHeightfields(), recastMesh.getFlatHeightfields() }; const auto iterator = mFreeItems.emplace(mFreeItems.end(), agentBounds, changedTile, std::move(key), itemSize); const auto emplaced = mValues.emplace( std::make_tuple(agentBounds, changedTile, std::cref(iterator->mRecastMeshData)), iterator); if (!emplaced.second) { mFreeItems.erase(iterator); acquireItemUnsafe(emplaced.first->second); ++mGetCount; ++mHitCount; return Value(*this, emplaced.first->second); } iterator->mPreparedNavMeshData = std::move(value); ++iterator->mUseCount; mUsedNavMeshDataSize += itemSize; mBusyItems.splice(mBusyItems.end(), mFreeItems, iterator); return Value(*this, iterator); } NavMeshTilesCacheStats NavMeshTilesCache::getStats() const { NavMeshTilesCacheStats result; { const std::lock_guard<std::mutex> lock(mMutex); result.mNavMeshCacheSize = mUsedNavMeshDataSize; result.mUsedNavMeshTiles = mBusyItems.size(); result.mCachedNavMeshTiles = mFreeItems.size(); result.mHitCount = mHitCount; result.mGetCount = mGetCount; } return result; } void NavMeshTilesCache::removeLeastRecentlyUsed() { const auto& item = mFreeItems.back(); const auto value = mValues.find(std::tie(item.mAgentBounds, item.mChangedTile, item.mRecastMeshData)); if (value == mValues.end()) return; mUsedNavMeshDataSize -= item.mSize; mFreeNavMeshDataSize -= item.mSize; mValues.erase(value); mFreeItems.pop_back(); } void NavMeshTilesCache::acquireItemUnsafe(ItemIterator iterator) { if (++iterator->mUseCount > 1) return; mBusyItems.splice(mBusyItems.end(), mFreeItems, iterator); mFreeNavMeshDataSize -= iterator->mSize; } void NavMeshTilesCache::releaseItem(ItemIterator iterator) { if (--iterator->mUseCount > 0) return; const std::lock_guard<std::mutex> lock(mMutex); mFreeItems.splice(mFreeItems.begin(), mBusyItems, iterator); mFreeNavMeshDataSize += iterator->mSize; } }
3,948
C++
.cpp
94
33.265957
119
0.659002
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,472
recastcontext.cpp
OpenMW_openmw/components/detournavigator/recastcontext.cpp
#include "recastcontext.hpp" #include "debug.hpp" #include "components/debug/debuglog.hpp" #include <sstream> namespace DetourNavigator { namespace { Debug::Level getLogLevel(rcLogCategory category) { switch (category) { case RC_LOG_PROGRESS: return Debug::Verbose; case RC_LOG_WARNING: return Debug::Warning; case RC_LOG_ERROR: return Debug::Error; } return Debug::Debug; } std::string formatPrefix( ESM::RefId worldspace, const TilePosition& tilePosition, const AgentBounds& agentBounds) { std::ostringstream stream; stream << "Worldspace: " << worldspace << "; tile position: " << tilePosition.x() << ", " << tilePosition.y() << "; agent bounds: " << agentBounds << "; "; return stream.str(); } } RecastContext::RecastContext( ESM::RefId worldspace, const TilePosition& tilePosition, const AgentBounds& agentBounds) : mPrefix(formatPrefix(worldspace, tilePosition, agentBounds)) { } void RecastContext::doLog(const rcLogCategory category, const char* msg, const int len) { if (len > 0) Log(getLogLevel(category)) << mPrefix << std::string_view(msg, static_cast<std::size_t>(len)); } }
1,437
C++
.cpp
41
25.536585
106
0.576978
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,473
findrandompointaroundcircle.cpp
OpenMW_openmw/components/detournavigator/findrandompointaroundcircle.cpp
#include "findrandompointaroundcircle.hpp" #include <DetourNavMesh.h> #include <DetourNavMeshQuery.h> namespace DetourNavigator { std::optional<osg::Vec3f> findRandomPointAroundCircle(const dtNavMeshQuery& navMeshQuery, const osg::Vec3f& halfExtents, const osg::Vec3f& start, const float maxRadius, const Flags includeFlags, float (*prng)()) { dtQueryFilter queryFilter; queryFilter.setIncludeFlags(includeFlags); dtPolyRef startRef = 0; const dtStatus status = navMeshQuery.findNearestPoly(start.ptr(), halfExtents.ptr(), &queryFilter, &startRef, nullptr); if (dtStatusFailed(status)) return std::nullopt; dtPolyRef resultRef = 0; osg::Vec3f resultPosition; navMeshQuery.findRandomPointAroundCircle( startRef, start.ptr(), maxRadius, &queryFilter, prng, &resultRef, resultPosition.ptr()); if (resultRef == 0) return std::optional<osg::Vec3f>(); return std::optional<osg::Vec3f>(resultPosition); } }
1,063
C++
.cpp
25
35
112
0.689622
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,474
offmeshconnectionsmanager.cpp
OpenMW_openmw/components/detournavigator/offmeshconnectionsmanager.cpp
#include "offmeshconnectionsmanager.hpp" #include "objectid.hpp" #include "offmeshconnection.hpp" #include "settings.hpp" #include "settingsutils.hpp" #include "tileposition.hpp" #include <algorithm> #include <set> #include <vector> namespace DetourNavigator { OffMeshConnectionsManager::OffMeshConnectionsManager(const RecastSettings& settings) : mSettings(settings) { } void OffMeshConnectionsManager::add(const ObjectId id, const OffMeshConnection& value) { const auto values = mValues.lock(); values->mById.insert(std::make_pair(id, value)); const auto startTilePosition = getTilePosition(mSettings, value.mStart); const auto endTilePosition = getTilePosition(mSettings, value.mEnd); values->mByTilePosition[startTilePosition].insert(id); if (startTilePosition != endTilePosition) values->mByTilePosition[endTilePosition].insert(id); } std::set<TilePosition> OffMeshConnectionsManager::remove(const ObjectId id) { const auto values = mValues.lock(); const auto byId = values->mById.equal_range(id); if (byId.first == byId.second) return {}; std::set<TilePosition> removed; std::for_each(byId.first, byId.second, [&](const auto& v) { const auto startTilePosition = getTilePosition(mSettings, v.second.mStart); const auto endTilePosition = getTilePosition(mSettings, v.second.mEnd); removed.emplace(startTilePosition); if (startTilePosition != endTilePosition) removed.emplace(endTilePosition); }); for (const TilePosition& tilePosition : removed) { const auto it = values->mByTilePosition.find(tilePosition); if (it == values->mByTilePosition.end()) continue; it->second.erase(id); if (it->second.empty()) values->mByTilePosition.erase(it); } values->mById.erase(byId.first, byId.second); return removed; } std::vector<OffMeshConnection> OffMeshConnectionsManager::get(const TilePosition& tilePosition) const { std::vector<OffMeshConnection> result; const auto values = mValues.lockConst(); const auto itByTilePosition = values->mByTilePosition.find(tilePosition); if (itByTilePosition == values->mByTilePosition.end()) return result; std::for_each(itByTilePosition->second.begin(), itByTilePosition->second.end(), [&](const ObjectId v) { const auto byId = values->mById.equal_range(v); std::for_each(byId.first, byId.second, [&](const auto& v) { if (getTilePosition(mSettings, v.second.mStart) == tilePosition || getTilePosition(mSettings, v.second.mEnd) == tilePosition) result.push_back(v.second); }); }); std::sort(result.begin(), result.end()); return result; } }
3,023
C++
.cpp
70
34.314286
111
0.653242
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,475
generatenavmeshtile.cpp
OpenMW_openmw/components/detournavigator/generatenavmeshtile.cpp
#include "generatenavmeshtile.hpp" #include "dbrefgeometryobject.hpp" #include "makenavmesh.hpp" #include "preparednavmeshdata.hpp" #include "serialization.hpp" #include "settings.hpp" #include <components/debug/debuglog.hpp> #include <osg/io_utils> #include <functional> #include <memory> #include <optional> #include <stdexcept> #include <vector> namespace DetourNavigator { namespace { struct Ignore { ESM::RefId mWorldspace; const TilePosition& mTilePosition; std::shared_ptr<NavMeshTileConsumer> mConsumer; ~Ignore() noexcept { if (mConsumer != nullptr) mConsumer->ignore(mWorldspace, mTilePosition); } }; } GenerateNavMeshTile::GenerateNavMeshTile(ESM::RefId worldspace, const TilePosition& tilePosition, RecastMeshProvider recastMeshProvider, const AgentBounds& agentBounds, const DetourNavigator::Settings& settings, std::weak_ptr<NavMeshTileConsumer> consumer) : mWorldspace(worldspace) , mTilePosition(tilePosition) , mRecastMeshProvider(recastMeshProvider) , mAgentBounds(agentBounds) , mSettings(settings) , mConsumer(std::move(consumer)) { } void GenerateNavMeshTile::doWork() { impl(); } void GenerateNavMeshTile::impl() noexcept { const auto consumer = mConsumer.lock(); if (consumer == nullptr) return; try { Ignore ignore{ mWorldspace, mTilePosition, consumer }; const std::shared_ptr<RecastMesh> recastMesh = mRecastMeshProvider.getMesh(mWorldspace, mTilePosition); if (recastMesh == nullptr || isEmpty(*recastMesh)) return; const std::vector<DbRefGeometryObject> objects = makeDbRefGeometryObjects( recastMesh->getMeshSources(), [&](const MeshSource& v) { return consumer->resolveMeshSource(v); }); std::vector<std::byte> input = serialize(mSettings.mRecast, mAgentBounds, *recastMesh, objects); const std::optional<NavMeshTileInfo> info = consumer->find(mWorldspace, mTilePosition, input); if (info.has_value() && info->mVersion == navMeshFormatVersion) { consumer->identity(mWorldspace, mTilePosition, info->mTileId); ignore.mConsumer = nullptr; return; } const auto data = prepareNavMeshTileData(*recastMesh, mWorldspace, mTilePosition, mAgentBounds, mSettings.mRecast); if (data == nullptr) return; if (info.has_value()) consumer->update(mWorldspace, mTilePosition, info->mTileId, navMeshFormatVersion, *data); else consumer->insert(mWorldspace, mTilePosition, navMeshFormatVersion, input, *data); ignore.mConsumer = nullptr; } catch (const std::exception& e) { Log(Debug::Warning) << "Failed to generate navmesh for worldspace \"" << mWorldspace << "\" tile " << mTilePosition << ": " << e.what(); consumer->cancel(e.what()); } } }
3,271
C++
.cpp
83
29.795181
115
0.623856
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,476
asyncnavmeshupdater.cpp
OpenMW_openmw/components/detournavigator/asyncnavmeshupdater.cpp
#include "asyncnavmeshupdater.hpp" #include "dbrefgeometryobject.hpp" #include "debug.hpp" #include "makenavmesh.hpp" #include "navmeshdbutils.hpp" #include "serialization.hpp" #include "settings.hpp" #include "version.hpp" #include <components/debug/debuglog.hpp> #include <components/loadinglistener/loadinglistener.hpp> #include <components/misc/strings/conversion.hpp> #include <components/misc/thread.hpp> #include <DetourNavMesh.h> #include <osg/io_utils> #include <boost/geometry.hpp> #include <algorithm> #include <optional> #include <set> #include <tuple> #include <type_traits> namespace DetourNavigator { namespace { int getManhattanDistance(const TilePosition& lhs, const TilePosition& rhs) { return std::abs(lhs.x() - rhs.x()) + std::abs(lhs.y() - rhs.y()); } bool isAbsentTileTooClose(const TilePosition& position, int distance, const std::set<std::tuple<AgentBounds, TilePosition>>& pushedTiles, const std::set<std::tuple<AgentBounds, TilePosition>>& presentTiles, const Misc::ScopeGuarded<std::set<std::tuple<AgentBounds, TilePosition>>>& processingTiles) { const auto isAbsentAndCloserThan = [&](const std::tuple<AgentBounds, TilePosition>& v) { return presentTiles.find(v) == presentTiles.end() && getManhattanDistance(position, std::get<1>(v)) < distance; }; if (std::any_of(pushedTiles.begin(), pushedTiles.end(), isAbsentAndCloserThan)) return true; if (const auto locked = processingTiles.lockConst(); std::any_of(locked->begin(), locked->end(), isAbsentAndCloserThan)) return true; return false; } auto getAgentAndTile(const Job& job) noexcept { return std::make_tuple(job.mAgentBounds, job.mChangedTile); } std::unique_ptr<DbWorker> makeDbWorker( AsyncNavMeshUpdater& updater, std::unique_ptr<NavMeshDb>&& db, const Settings& settings) { if (db == nullptr) return nullptr; return std::make_unique<DbWorker>(updater, std::move(db), TileVersion(navMeshFormatVersion), settings.mRecast, settings.mWriteToNavMeshDb); } std::size_t getNextJobId() { static std::atomic_size_t nextJobId{ 1 }; return nextJobId.fetch_add(1); } bool isWritingDbJob(const Job& job) { return job.mGeneratedNavMeshData != nullptr; } } std::ostream& operator<<(std::ostream& stream, JobStatus value) { switch (value) { case JobStatus::Done: return stream << "JobStatus::Done"; case JobStatus::Fail: return stream << "JobStatus::Fail"; case JobStatus::MemoryCacheMiss: return stream << "JobStatus::MemoryCacheMiss"; } return stream << "JobStatus::" << static_cast<std::underlying_type_t<JobStatus>>(value); } Job::Job(const AgentBounds& agentBounds, std::weak_ptr<GuardedNavMeshCacheItem> navMeshCacheItem, ESM::RefId worldspace, const TilePosition& changedTile, ChangeType changeType, std::chrono::steady_clock::time_point processTime) : mId(getNextJobId()) , mAgentBounds(agentBounds) , mNavMeshCacheItem(std::move(navMeshCacheItem)) , mWorldspace(worldspace) , mChangedTile(changedTile) , mProcessTime(processTime) , mChangeType(changeType) { } void SpatialJobQueue::clear() { mValues.clear(); mIndex.clear(); mSize = 0; } void SpatialJobQueue::push(JobIt job) { auto it = mValues.find(job->mChangedTile); if (it == mValues.end()) { it = mValues.emplace_hint(it, job->mChangedTile, std::deque<JobIt>()); mIndex.insert(IndexValue(IndexPoint(job->mChangedTile.x(), job->mChangedTile.y()), it)); } it->second.push_back(job); ++mSize; } std::optional<JobIt> SpatialJobQueue::pop(TilePosition playerTile) { const IndexPoint point(playerTile.x(), playerTile.y()); const auto it = mIndex.qbegin(boost::geometry::index::nearest(point, 1)); if (it == mIndex.qend()) return std::nullopt; const UpdatingMap::iterator mapIt = it->second; std::deque<JobIt>& tileJobs = mapIt->second; JobIt result = tileJobs.front(); tileJobs.pop_front(); --mSize; if (tileJobs.empty()) { mValues.erase(mapIt); mIndex.remove(*it); } return result; } void SpatialJobQueue::update(TilePosition playerTile, int maxTiles, std::vector<JobIt>& removing) { for (auto it = mValues.begin(); it != mValues.end();) { if (shouldAddTile(it->first, playerTile, maxTiles)) { ++it; continue; } for (JobIt job : it->second) { job->mChangeType = ChangeType::remove; removing.push_back(job); } mSize -= it->second.size(); mIndex.remove(IndexValue(IndexPoint(it->first.x(), it->first.y()), it)); it = mValues.erase(it); } } bool JobQueue::hasJob(std::chrono::steady_clock::time_point now) const { return !mRemoving.empty() || mUpdating.size() > 0 || (!mDelayed.empty() && mDelayed.front()->mProcessTime <= now); } void JobQueue::clear() { mRemoving.clear(); mDelayed.clear(); mUpdating.clear(); } void JobQueue::push(JobIt job, std::chrono::steady_clock::time_point now) { if (job->mProcessTime > now) { mDelayed.push_back(job); return; } if (job->mChangeType == ChangeType::remove) { mRemoving.push_back(job); return; } mUpdating.push(job); } std::optional<JobIt> JobQueue::pop(TilePosition playerTile, std::chrono::steady_clock::time_point now) { if (!mRemoving.empty()) { const JobIt result = mRemoving.back(); mRemoving.pop_back(); return result; } if (const std::optional<JobIt> result = mUpdating.pop(playerTile)) return result; if (mDelayed.empty() || mDelayed.front()->mProcessTime > now) return std::nullopt; const JobIt result = mDelayed.front(); mDelayed.pop_front(); return result; } void JobQueue::update(TilePosition playerTile, int maxTiles, std::chrono::steady_clock::time_point now) { mUpdating.update(playerTile, maxTiles, mRemoving); while (!mDelayed.empty() && mDelayed.front()->mProcessTime <= now) { const JobIt job = mDelayed.front(); mDelayed.pop_front(); if (shouldAddTile(job->mChangedTile, playerTile, maxTiles)) { mUpdating.push(job); } else { job->mChangeType = ChangeType::remove; mRemoving.push_back(job); } } } AsyncNavMeshUpdater::AsyncNavMeshUpdater(const Settings& settings, TileCachedRecastMeshManager& recastMeshManager, OffMeshConnectionsManager& offMeshConnectionsManager, std::unique_ptr<NavMeshDb>&& db) : mSettings(settings) , mRecastMeshManager(recastMeshManager) , mOffMeshConnectionsManager(offMeshConnectionsManager) , mShouldStop() , mNavMeshTilesCache(settings.mMaxNavMeshTilesCacheSize) , mDbWorker(makeDbWorker(*this, std::move(db), mSettings)) { for (std::size_t i = 0; i < mSettings.get().mAsyncNavMeshUpdaterThreads; ++i) mThreads.emplace_back([&] { process(); }); } AsyncNavMeshUpdater::~AsyncNavMeshUpdater() { stop(); } void AsyncNavMeshUpdater::post(const AgentBounds& agentBounds, const SharedNavMeshCacheItem& navMeshCacheItem, const TilePosition& playerTile, ESM::RefId worldspace, const std::map<TilePosition, ChangeType>& changedTiles) { bool playerTileChanged = false; { auto locked = mPlayerTile.lock(); playerTileChanged = *locked != playerTile; *locked = playerTile; } if (!playerTileChanged && changedTiles.empty()) return; std::unique_lock lock(mMutex); if (playerTileChanged) { Log(Debug::Debug) << "Player tile has been changed to " << playerTile; mWaiting.update(playerTile, mSettings.get().mMaxTilesNumber); } for (const auto& [changedTile, changeType] : changedTiles) { if (mPushed.emplace(agentBounds, changedTile).second) { const auto processTime = [&, changedTile = changedTile, changeType = changeType] { if (changeType != ChangeType::update) return std::chrono::steady_clock::time_point(); const auto lastUpdate = mLastUpdates.find(std::tie(agentBounds, changedTile)); if (lastUpdate == mLastUpdates.end()) return std::chrono::steady_clock::time_point(); return lastUpdate->second + mSettings.get().mMinUpdateInterval; }(); const JobIt it = mJobs.emplace( mJobs.end(), agentBounds, navMeshCacheItem, worldspace, changedTile, changeType, processTime); Log(Debug::Debug) << "Post job " << it->mId << " for agent=(" << it->mAgentBounds << ")" << " changedTile=(" << it->mChangedTile << ")" << " changeType=" << it->mChangeType; mWaiting.push(it); } } Log(Debug::Debug) << "Posted " << mJobs.size() << " navigator jobs"; if (mWaiting.hasJob()) mHasJob.notify_all(); lock.unlock(); if (playerTileChanged && mDbWorker != nullptr) mDbWorker->update(playerTile); } void AsyncNavMeshUpdater::wait(WaitConditionType waitConditionType, Loading::Listener* listener) { switch (waitConditionType) { case WaitConditionType::requiredTilesPresent: waitUntilJobsDoneForNotPresentTiles(listener); break; case WaitConditionType::allJobsDone: waitUntilAllJobsDone(); break; } } void AsyncNavMeshUpdater::stop() { mShouldStop = true; if (mDbWorker != nullptr) mDbWorker->stop(); std::unique_lock<std::mutex> lock(mMutex); mWaiting.clear(); mHasJob.notify_all(); lock.unlock(); for (auto& thread : mThreads) if (thread.joinable()) thread.join(); } void AsyncNavMeshUpdater::waitUntilJobsDoneForNotPresentTiles(Loading::Listener* listener) { const int maxDistanceToPlayer = mSettings.get().mWaitUntilMinDistanceToPlayer; if (maxDistanceToPlayer <= 0) return; const std::size_t initialJobsLeft = getTotalJobs(); std::size_t maxProgress = initialJobsLeft; std::size_t prevJobsLeft = initialJobsLeft; std::size_t jobsDone = 0; std::size_t jobsLeft = 0; const TilePosition playerPosition = *mPlayerTile.lockConst(); const auto isDone = [&] { jobsLeft = mJobs.size(); if (jobsLeft == 0) return true; return !isAbsentTileTooClose(playerPosition, maxDistanceToPlayer, mPushed, mPresentTiles, mProcessingTiles); }; std::unique_lock<std::mutex> lock(mMutex); if (!isAbsentTileTooClose(playerPosition, maxDistanceToPlayer, mPushed, mPresentTiles, mProcessingTiles) || mJobs.empty()) return; const Loading::ScopedLoad load(listener); if (listener != nullptr) { listener->setLabel("#{OMWEngine:BuildingNavigationMesh}"); listener->setProgressRange(maxProgress); } while (!mDone.wait_for(lock, std::chrono::milliseconds(20), isDone)) { if (listener == nullptr) continue; if (maxProgress < jobsLeft) { maxProgress = jobsLeft; listener->setProgressRange(maxProgress); listener->setProgress(jobsDone); } else if (jobsLeft < prevJobsLeft) { const std::size_t newJobsDone = prevJobsLeft - jobsLeft; jobsDone += newJobsDone; prevJobsLeft = jobsLeft; listener->increaseProgress(newJobsDone); } } } void AsyncNavMeshUpdater::waitUntilAllJobsDone() { { std::unique_lock<std::mutex> lock(mMutex); mDone.wait(lock, [this] { return mJobs.empty(); }); } mProcessingTiles.wait(mProcessed, [](const auto& v) { return v.empty(); }); } AsyncNavMeshUpdaterStats AsyncNavMeshUpdater::getStats() const { AsyncNavMeshUpdaterStats result; { const std::lock_guard<std::mutex> lock(mMutex); result.mJobs = mJobs.size(); result.mWaiting = mWaiting.getStats(); result.mPushed = mPushed.size(); } result.mProcessing = mProcessingTiles.lockConst()->size(); if (mDbWorker != nullptr) result.mDb = mDbWorker->getStats(); result.mCache = mNavMeshTilesCache.getStats(); result.mDbGetTileHits = mDbGetTileHits.load(std::memory_order_relaxed); return result; } void AsyncNavMeshUpdater::process() noexcept { Log(Debug::Debug) << "Start process navigator jobs by thread=" << std::this_thread::get_id(); Misc::setCurrentThreadIdlePriority(); while (!mShouldStop) { try { if (JobIt job = getNextJob(); job != mJobs.end()) { const JobStatus status = processJob(*job); Log(Debug::Debug) << "Processed job " << job->mId << " with status=" << status << " changeType=" << job->mChangeType; switch (status) { case JobStatus::Done: unlockTile(job->mId, job->mAgentBounds, job->mChangedTile); if (job->mGeneratedNavMeshData != nullptr) mDbWorker->enqueueJob(job); else removeJob(job); break; case JobStatus::Fail: unlockTile(job->mId, job->mAgentBounds, job->mChangedTile); removeJob(job); break; case JobStatus::MemoryCacheMiss: { mDbWorker->enqueueJob(job); break; } } } else cleanupLastUpdates(); } catch (const std::exception& e) { Log(Debug::Error) << "AsyncNavMeshUpdater::process exception: " << e.what(); } } Log(Debug::Debug) << "Stop navigator jobs processing by thread=" << std::this_thread::get_id(); } JobStatus AsyncNavMeshUpdater::processJob(Job& job) { Log(Debug::Debug) << "Processing job " << job.mId << " for agent=(" << job.mAgentBounds << ")" << " changedTile=(" << job.mChangedTile << ")" << " changeType=" << job.mChangeType << " by thread=" << std::this_thread::get_id(); const auto navMeshCacheItem = job.mNavMeshCacheItem.lock(); if (!navMeshCacheItem) return JobStatus::Done; const auto playerTile = *mPlayerTile.lockConst(); if (!shouldAddTile(job.mChangedTile, playerTile, mSettings.get().mMaxTilesNumber)) { Log(Debug::Debug) << "Ignore add tile by job " << job.mId << ": too far from player"; job.mChangeType = ChangeType::remove; navMeshCacheItem->lock()->removeTile(job.mChangedTile); return JobStatus::Done; } switch (job.mState) { case JobState::Initial: return processInitialJob(job, *navMeshCacheItem); case JobState::WithDbResult: return processJobWithDbResult(job, *navMeshCacheItem); } return JobStatus::Done; } JobStatus AsyncNavMeshUpdater::processInitialJob(Job& job, GuardedNavMeshCacheItem& navMeshCacheItem) { Log(Debug::Debug) << "Processing initial job " << job.mId; std::shared_ptr<RecastMesh> recastMesh = mRecastMeshManager.get().getMesh(job.mWorldspace, job.mChangedTile); if (recastMesh == nullptr) { Log(Debug::Debug) << "Null recast mesh for job " << job.mId; navMeshCacheItem.lock()->markAsEmpty(job.mChangedTile); return JobStatus::Done; } if (isEmpty(*recastMesh)) { Log(Debug::Debug) << "Empty bounds for job " << job.mId; navMeshCacheItem.lock()->markAsEmpty(job.mChangedTile); return JobStatus::Done; } NavMeshTilesCache::Value cachedNavMeshData = mNavMeshTilesCache.get(job.mAgentBounds, job.mChangedTile, *recastMesh); std::unique_ptr<PreparedNavMeshData> preparedNavMeshData; const PreparedNavMeshData* preparedNavMeshDataPtr = nullptr; if (cachedNavMeshData) { preparedNavMeshDataPtr = &cachedNavMeshData.get(); } else { if (job.mChangeType != ChangeType::update && mDbWorker != nullptr) { job.mRecastMesh = std::move(recastMesh); return JobStatus::MemoryCacheMiss; } preparedNavMeshData = prepareNavMeshTileData( *recastMesh, job.mWorldspace, job.mChangedTile, job.mAgentBounds, mSettings.get().mRecast); if (preparedNavMeshData == nullptr) { Log(Debug::Debug) << "Null navmesh data for job " << job.mId; navMeshCacheItem.lock()->markAsEmpty(job.mChangedTile); return JobStatus::Done; } if (job.mChangeType == ChangeType::update) { preparedNavMeshDataPtr = preparedNavMeshData.get(); } else { cachedNavMeshData = mNavMeshTilesCache.set( job.mAgentBounds, job.mChangedTile, *recastMesh, std::move(preparedNavMeshData)); preparedNavMeshDataPtr = cachedNavMeshData ? &cachedNavMeshData.get() : preparedNavMeshData.get(); } } const auto offMeshConnections = mOffMeshConnectionsManager.get().get(job.mChangedTile); assert(preparedNavMeshDataPtr != nullptr); const UpdateNavMeshStatus status = navMeshCacheItem.lock()->updateTile(job.mChangedTile, std::move(cachedNavMeshData), makeNavMeshTileData(*preparedNavMeshDataPtr, offMeshConnections, job.mAgentBounds, job.mChangedTile, mSettings.get().mRecast)); return handleUpdateNavMeshStatus(status, job, navMeshCacheItem, *recastMesh); } JobStatus AsyncNavMeshUpdater::processJobWithDbResult(Job& job, GuardedNavMeshCacheItem& navMeshCacheItem) { Log(Debug::Debug) << "Processing job with db result " << job.mId; std::unique_ptr<PreparedNavMeshData> preparedNavMeshData; bool generatedNavMeshData = false; if (job.mCachedTileData.has_value() && job.mCachedTileData->mVersion == navMeshFormatVersion) { preparedNavMeshData = std::make_unique<PreparedNavMeshData>(); if (deserialize(job.mCachedTileData->mData, *preparedNavMeshData)) ++mDbGetTileHits; else preparedNavMeshData = nullptr; } if (preparedNavMeshData == nullptr) { preparedNavMeshData = prepareNavMeshTileData( *job.mRecastMesh, job.mWorldspace, job.mChangedTile, job.mAgentBounds, mSettings.get().mRecast); generatedNavMeshData = true; } if (preparedNavMeshData == nullptr) { Log(Debug::Debug) << "Null navmesh data for job " << job.mId; navMeshCacheItem.lock()->markAsEmpty(job.mChangedTile); return JobStatus::Done; } auto cachedNavMeshData = mNavMeshTilesCache.set( job.mAgentBounds, job.mChangedTile, *job.mRecastMesh, std::move(preparedNavMeshData)); const auto offMeshConnections = mOffMeshConnectionsManager.get().get(job.mChangedTile); const PreparedNavMeshData* preparedNavMeshDataPtr = cachedNavMeshData ? &cachedNavMeshData.get() : preparedNavMeshData.get(); assert(preparedNavMeshDataPtr != nullptr); const UpdateNavMeshStatus status = navMeshCacheItem.lock()->updateTile(job.mChangedTile, std::move(cachedNavMeshData), makeNavMeshTileData(*preparedNavMeshDataPtr, offMeshConnections, job.mAgentBounds, job.mChangedTile, mSettings.get().mRecast)); const JobStatus result = handleUpdateNavMeshStatus(status, job, navMeshCacheItem, *job.mRecastMesh); if (result == JobStatus::Done && job.mChangeType != ChangeType::update && mDbWorker != nullptr && mSettings.get().mWriteToNavMeshDb && generatedNavMeshData) job.mGeneratedNavMeshData = std::make_unique<PreparedNavMeshData>(*preparedNavMeshDataPtr); return result; } JobStatus AsyncNavMeshUpdater::handleUpdateNavMeshStatus(UpdateNavMeshStatus status, const Job& job, const GuardedNavMeshCacheItem& navMeshCacheItem, const RecastMesh& recastMesh) { const Version navMeshVersion = navMeshCacheItem.lockConst()->getVersion(); mRecastMeshManager.get().reportNavMeshChange(job.mChangedTile, recastMesh.getVersion(), navMeshVersion); if (status == UpdateNavMeshStatus::removed || status == UpdateNavMeshStatus::lost) { const std::scoped_lock lock(mMutex); mPresentTiles.erase(std::make_tuple(job.mAgentBounds, job.mChangedTile)); } else if (isSuccess(status) && status != UpdateNavMeshStatus::ignored) { const std::scoped_lock lock(mMutex); mPresentTiles.insert(std::make_tuple(job.mAgentBounds, job.mChangedTile)); } writeDebugFiles(job, &recastMesh); return isSuccess(status) ? JobStatus::Done : JobStatus::Fail; } JobIt AsyncNavMeshUpdater::getNextJob() { std::unique_lock<std::mutex> lock(mMutex); bool shouldStop = false; const auto hasJob = [&] { shouldStop = mShouldStop.load(); return shouldStop || mWaiting.hasJob(); }; if (!mHasJob.wait_for(lock, std::chrono::milliseconds(10), hasJob)) { if (mJobs.empty()) mDone.notify_all(); return mJobs.end(); } if (shouldStop) return mJobs.end(); const TilePosition playerTile = *mPlayerTile.lockConst(); JobIt job = mJobs.end(); if (const std::optional<JobIt> nextJob = mWaiting.pop(playerTile)) job = *nextJob; if (job == mJobs.end()) return job; Log(Debug::Debug) << "Pop job " << job->mId << " by thread=" << std::this_thread::get_id(); if (job->mRecastMesh != nullptr) return job; if (!lockTile(job->mId, job->mAgentBounds, job->mChangedTile)) { Log(Debug::Debug) << "Failed to lock tile by job " << job->mId; job->mProcessTime = std::chrono::steady_clock::now() + mSettings.get().mMinUpdateInterval; mWaiting.push(job); return mJobs.end(); } if (job->mChangeType == ChangeType::update) mLastUpdates[getAgentAndTile(*job)] = std::chrono::steady_clock::now(); mPushed.erase(getAgentAndTile(*job)); return job; } void AsyncNavMeshUpdater::writeDebugFiles(const Job& job, const RecastMesh* recastMesh) const { std::string revision; std::string recastMeshRevision; std::string navMeshRevision; if ((mSettings.get().mEnableWriteNavMeshToFile || mSettings.get().mEnableWriteRecastMeshToFile) && (mSettings.get().mEnableRecastMeshFileNameRevision || mSettings.get().mEnableNavMeshFileNameRevision)) { revision = "." + std::to_string((std::chrono::steady_clock::now() - std::chrono::steady_clock::time_point()).count()); if (mSettings.get().mEnableRecastMeshFileNameRevision) recastMeshRevision = revision; if (mSettings.get().mEnableNavMeshFileNameRevision) navMeshRevision = std::move(revision); } if (recastMesh && mSettings.get().mEnableWriteRecastMeshToFile) writeToFile(*recastMesh, mSettings.get().mRecastMeshPathPrefix + std::to_string(job.mChangedTile.x()) + "_" + std::to_string(job.mChangedTile.y()) + "_", recastMeshRevision, mSettings.get().mRecast); if (mSettings.get().mEnableWriteNavMeshToFile) if (const auto shared = job.mNavMeshCacheItem.lock()) writeToFile(shared->lockConst()->getImpl(), mSettings.get().mNavMeshPathPrefix, navMeshRevision); } bool AsyncNavMeshUpdater::lockTile( std::size_t jobId, const AgentBounds& agentBounds, const TilePosition& changedTile) { Log(Debug::Debug) << "Locking tile by job " << jobId << " agent=" << agentBounds << " changedTile=(" << changedTile << ")"; return mProcessingTiles.lock()->emplace(agentBounds, changedTile).second; } void AsyncNavMeshUpdater::unlockTile( std::size_t jobId, const AgentBounds& agentBounds, const TilePosition& changedTile) { auto locked = mProcessingTiles.lock(); locked->erase(std::tie(agentBounds, changedTile)); Log(Debug::Debug) << "Unlocked tile by job " << jobId << " agent=" << agentBounds << " changedTile=(" << changedTile << ")"; if (locked->empty()) mProcessed.notify_all(); } std::size_t AsyncNavMeshUpdater::getTotalJobs() const { const std::scoped_lock lock(mMutex); return mJobs.size(); } void AsyncNavMeshUpdater::cleanupLastUpdates() { const auto now = std::chrono::steady_clock::now(); const std::lock_guard<std::mutex> lock(mMutex); for (auto it = mLastUpdates.begin(); it != mLastUpdates.end();) { if (now - it->second > mSettings.get().mMinUpdateInterval) it = mLastUpdates.erase(it); else ++it; } } void AsyncNavMeshUpdater::enqueueJob(JobIt job) { Log(Debug::Debug) << "Enqueueing job " << job->mId << " by thread=" << std::this_thread::get_id(); const std::lock_guard lock(mMutex); mWaiting.push(job); mHasJob.notify_all(); } void AsyncNavMeshUpdater::removeJob(JobIt job) { Log(Debug::Debug) << "Removing job " << job->mId << " by thread=" << std::this_thread::get_id(); const std::lock_guard lock(mMutex); mJobs.erase(job); } void DbJobQueue::push(JobIt job) { const std::lock_guard lock(mMutex); if (isWritingDbJob(*job)) mWriting.push_back(job); else mReading.push(job); mHasJob.notify_all(); } std::optional<JobIt> DbJobQueue::pop() { std::unique_lock lock(mMutex); const auto hasJob = [&] { return mShouldStop || mReading.size() > 0 || mWriting.size() > 0; }; mHasJob.wait(lock, hasJob); if (mShouldStop) return std::nullopt; if (const std::optional<JobIt> job = mReading.pop(mPlayerTile)) return job; if (mWriting.empty()) return std::nullopt; const JobIt job = mWriting.front(); mWriting.pop_front(); return job; } void DbJobQueue::update(TilePosition playerTile) { const std::lock_guard lock(mMutex); mPlayerTile = playerTile; } void DbJobQueue::stop() { const std::lock_guard lock(mMutex); mReading.clear(); mWriting.clear(); mShouldStop = true; mHasJob.notify_all(); } DbJobQueueStats DbJobQueue::getStats() const { const std::lock_guard lock(mMutex); return DbJobQueueStats{ .mReadingJobs = mReading.size(), .mWritingJobs = mWriting.size(), }; } DbWorker::DbWorker(AsyncNavMeshUpdater& updater, std::unique_ptr<NavMeshDb>&& db, TileVersion version, const RecastSettings& recastSettings, bool writeToDb) : mUpdater(updater) , mRecastSettings(recastSettings) , mDb(std::move(db)) , mVersion(version) , mWriteToDb(writeToDb) , mNextTileId(mDb->getMaxTileId() + 1) , mNextShapeId(mDb->getMaxShapeId() + 1) , mThread([this] { run(); }) { } DbWorker::~DbWorker() { stop(); } void DbWorker::enqueueJob(JobIt job) { Log(Debug::Debug) << "Enqueueing db job " << job->mId << " by thread=" << std::this_thread::get_id(); mQueue.push(job); } DbWorkerStats DbWorker::getStats() const { return DbWorkerStats{ .mJobs = mQueue.getStats(), .mGetTileCount = mGetTileCount.load(std::memory_order_relaxed), }; } void DbWorker::stop() { mShouldStop = true; mQueue.stop(); if (mThread.joinable()) mThread.join(); } void DbWorker::run() noexcept { while (!mShouldStop) { try { if (const auto job = mQueue.pop()) processJob(*job); } catch (const std::exception& e) { Log(Debug::Error) << "DbWorker exception: " << e.what(); } } } void DbWorker::processJob(JobIt job) { const auto process = [&](auto f) { try { f(job); } catch (const std::exception& e) { Log(Debug::Error) << "DbWorker exception while processing job " << job->mId << ": " << e.what(); if (mWriteToDb) { const std::string_view message(e.what()); if (message.find("database or disk is full") != std::string_view::npos) { mWriteToDb = false; Log(Debug::Warning) << "Writes to navmeshdb are disabled because file size limit is reached or disk is full"; } else if (message.find("database is locked") != std::string_view::npos) { mWriteToDb = false; Log(Debug::Warning) << "Writes to navmeshdb are disabled to avoid concurrent writes from multiple processes"; } else if (message.find("UNIQUE constraint failed: tiles.tile_id") != std::string_view::npos) { Log(Debug::Warning) << "Found duplicate navmeshdb tile_id, please report the " "issue to https://gitlab.com/OpenMW/openmw/-/issues, attach openmw.log: " << mNextTileId; try { mNextTileId = TileId(mDb->getMaxTileId() + 1); Log(Debug::Info) << "Updated navmeshdb tile_id to: " << mNextTileId; } catch (const std::exception& e) { mWriteToDb = false; Log(Debug::Warning) << "Failed to update next tile_id, writes to navmeshdb are disabled: " << e.what(); } } } } }; if (isWritingDbJob(*job)) { process([&](JobIt job) { processWritingJob(job); }); mUpdater.removeJob(job); return; } process([&](JobIt job) { processReadingJob(job); }); job->mState = JobState::WithDbResult; mUpdater.enqueueJob(job); } void DbWorker::processReadingJob(JobIt job) { ++mGetTileCount; Log(Debug::Debug) << "Processing db read job " << job->mId; if (job->mInput.empty()) { Log(Debug::Debug) << "Serializing input for job " << job->mId; if (mWriteToDb) { const auto objects = makeDbRefGeometryObjects(job->mRecastMesh->getMeshSources(), [&](const MeshSource& v) { return resolveMeshSource(*mDb, v, mNextShapeId); }); job->mInput = serialize(mRecastSettings, job->mAgentBounds, *job->mRecastMesh, objects); } else { struct HandleResult { const RecastSettings& mRecastSettings; Job& mJob; bool operator()(const std::vector<DbRefGeometryObject>& objects) const { mJob.mInput = serialize(mRecastSettings, mJob.mAgentBounds, *mJob.mRecastMesh, objects); return true; } bool operator()(const MeshSource& meshSource) const { Log(Debug::Debug) << "No object for mesh source (fileName=\"" << meshSource.mShape->mFileName << "\", areaType=" << meshSource.mAreaType << ", fileHash=" << Misc::StringUtils::toHex(meshSource.mShape->mFileHash) << ") for job " << mJob.mId; return false; } }; const auto result = makeDbRefGeometryObjects(job->mRecastMesh->getMeshSources(), [&](const MeshSource& v) { return resolveMeshSource(*mDb, v); }); if (!std::visit(HandleResult{ mRecastSettings, *job }, result)) return; } } job->mCachedTileData = mDb->getTileData(job->mWorldspace, job->mChangedTile, job->mInput); } void DbWorker::processWritingJob(JobIt job) { if (!mWriteToDb) { Log(Debug::Debug) << "Ignored db write job " << job->mId; return; } Log(Debug::Debug) << "Processing db write job " << job->mId; if (job->mInput.empty()) { Log(Debug::Debug) << "Serializing input for job " << job->mId; const std::vector<DbRefGeometryObject> objects = makeDbRefGeometryObjects(job->mRecastMesh->getMeshSources(), [&](const MeshSource& v) { return resolveMeshSource(*mDb, v, mNextShapeId); }); job->mInput = serialize(mRecastSettings, job->mAgentBounds, *job->mRecastMesh, objects); } if (const auto& cachedTileData = job->mCachedTileData) { Log(Debug::Debug) << "Update db tile by job " << job->mId; job->mGeneratedNavMeshData->mUserId = cachedTileData->mTileId; mDb->updateTile(cachedTileData->mTileId, mVersion, serialize(*job->mGeneratedNavMeshData)); return; } const auto cached = mDb->findTile(job->mWorldspace, job->mChangedTile, job->mInput); if (cached.has_value() && cached->mVersion == mVersion) { Log(Debug::Debug) << "Ignore existing db tile by job " << job->mId; return; } job->mGeneratedNavMeshData->mUserId = mNextTileId; Log(Debug::Debug) << "Insert db tile by job " << job->mId; mDb->insertTile(mNextTileId, job->mWorldspace, job->mChangedTile, mVersion, job->mInput, serialize(*job->mGeneratedNavMeshData)); ++mNextTileId; } }
37,246
C++
.cpp
879
30.649602
120
0.572233
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,477
navigator.cpp
OpenMW_openmw/components/detournavigator/navigator.cpp
#include "navigator.hpp" #include "navigatorimpl.hpp" #include "navigatorstub.hpp" #include "recastglobalallocator.hpp" #include <components/debug/debuglog.hpp> #include <components/files/conversion.hpp> namespace DetourNavigator { std::unique_ptr<Navigator> makeNavigator(const Settings& settings, const std::filesystem::path& userDataPath) { DetourNavigator::RecastGlobalAllocator::init(); std::unique_ptr<NavMeshDb> db; if (settings.mEnableNavMeshDiskCache) { const std::string path = Files::pathToUnicodeString(userDataPath / "navmesh.db"); Log(Debug::Info) << "Using " << path << " to store navigation mesh cache"; try { db = std::make_unique<NavMeshDb>(path, settings.mMaxDbFileSize); } catch (const std::exception& e) { Log(Debug::Error) << e.what() << ", navigation mesh disk cache will be disabled"; } } return std::make_unique<NavigatorImpl>(settings, std::move(db)); } std::unique_ptr<Navigator> makeNavigatorStub() { return std::make_unique<NavigatorStub>(); } }
1,188
C++
.cpp
32
29.46875
113
0.636838
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,478
commulativeaabb.cpp
OpenMW_openmw/components/detournavigator/commulativeaabb.cpp
#include "commulativeaabb.hpp" #include <components/bullethelpers/aabb.hpp> namespace DetourNavigator { CommulativeAabb::CommulativeAabb(std::size_t lastChangeRevision, const btAABB& aabb) : mLastChangeRevision(lastChangeRevision) , mAabb(aabb) { } bool CommulativeAabb::update(std::size_t lastChangeRevision, const btAABB& aabb) { if (mLastChangeRevision != lastChangeRevision) { mLastChangeRevision = lastChangeRevision; // btAABB doesn't have copy-assignment operator mAabb.m_min = aabb.m_min; mAabb.m_max = aabb.m_max; return true; } const btAABB currentAabb = mAabb; mAabb.merge(aabb); return currentAabb != mAabb; } }
775
C++
.cpp
24
25
88
0.65508
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,479
navmeshdb.cpp
OpenMW_openmw/components/detournavigator/navmeshdb.cpp
#include "navmeshdb.hpp" #include <components/debug/debuglog.hpp> #include <components/misc/compression.hpp> #include <components/misc/strings/format.hpp> #include <components/sqlite3/db.hpp> #include <components/sqlite3/request.hpp> #include <DetourAlloc.h> #include <sqlite3.h> #include <cstddef> #include <string_view> #include <vector> namespace DetourNavigator { namespace { constexpr const char schema[] = R"( BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS tiles ( tile_id INTEGER PRIMARY KEY, revision INTEGER NOT NULL DEFAULT 1, worldspace TEXT NOT NULL, tile_position_x INTEGER NOT NULL, tile_position_y INTEGER NOT NULL, version INTEGER NOT NULL, input BLOB, data BLOB ); CREATE UNIQUE INDEX IF NOT EXISTS index_unique_tiles_by_worldspace_and_tile_position_and_input ON tiles (worldspace, tile_position_x, tile_position_y, input); CREATE INDEX IF NOT EXISTS index_tiles_by_worldspace_and_tile_position ON tiles (worldspace, tile_position_x, tile_position_y); CREATE TABLE IF NOT EXISTS shapes ( shape_id INTEGER PRIMARY KEY, name TEXT NOT NULL, type INTEGER NOT NULL, hash BLOB NOT NULL ); CREATE UNIQUE INDEX IF NOT EXISTS index_unique_shapes_by_name_and_type_and_hash ON shapes (name, type, hash); COMMIT; )"; constexpr std::string_view getMaxTileIdQuery = R"( SELECT max(tile_id) FROM tiles )"; constexpr std::string_view findTileQuery = R"( SELECT tile_id, version FROM tiles WHERE worldspace = :worldspace AND tile_position_x = :tile_position_x AND tile_position_y = :tile_position_y AND input = :input )"; constexpr std::string_view getTileDataQuery = R"( SELECT tile_id, version, data FROM tiles WHERE worldspace = :worldspace AND tile_position_x = :tile_position_x AND tile_position_y = :tile_position_y AND input = :input )"; constexpr std::string_view insertTileQuery = R"( INSERT INTO tiles ( tile_id, worldspace, version, tile_position_x, tile_position_y, input, data) VALUES (:tile_id, :worldspace, :version, :tile_position_x, :tile_position_y, :input, :data) )"; constexpr std::string_view updateTileQuery = R"( UPDATE tiles SET version = :version, data = :data, revision = revision + 1 WHERE tile_id = :tile_id )"; constexpr std::string_view deleteTilesAtQuery = R"( DELETE FROM tiles WHERE worldspace = :worldspace AND tile_position_x = :tile_position_x AND tile_position_y = :tile_position_y )"; constexpr std::string_view deleteTilesAtExceptQuery = R"( DELETE FROM tiles WHERE worldspace = :worldspace AND tile_position_x = :tile_position_x AND tile_position_y = :tile_position_y AND tile_id != :exclude_tile_id )"; constexpr std::string_view deleteTilesOutsideRangeQuery = R"( DELETE FROM tiles WHERE worldspace = :worldspace AND ( tile_position_x < :begin_tile_position_x OR tile_position_y < :begin_tile_position_y OR tile_position_x >= :end_tile_position_x OR tile_position_y >= :end_tile_position_y ) )"; constexpr std::string_view getMaxShapeIdQuery = R"( SELECT max(shape_id) FROM shapes )"; constexpr std::string_view findShapeIdQuery = R"( SELECT shape_id FROM shapes WHERE name = :name AND type = :type AND hash = :hash )"; constexpr std::string_view insertShapeQuery = R"( INSERT INTO shapes ( shape_id, name, type, hash) VALUES (:shape_id, :name, :type, :hash) )"; constexpr std::string_view vacuumQuery = R"( VACUUM; )"; struct GetPageSize { static std::string_view text() noexcept { return "pragma page_size;"; } static void bind(sqlite3&, sqlite3_stmt&) {} }; std::uint64_t getPageSize(sqlite3& db) { Sqlite3::Statement<GetPageSize> statement(db); std::uint64_t value = 0; request(db, statement, &value, 1); return value; } void setMaxPageCount(sqlite3& db, std::uint64_t value) { const auto query = Misc::StringUtils::format("pragma max_page_count = %lu;", value); if (const int ec = sqlite3_exec(&db, query.c_str(), nullptr, nullptr, nullptr); ec != SQLITE_OK) throw std::runtime_error("Failed set max page count: " + std::string(sqlite3_errmsg(&db))); } } std::ostream& operator<<(std::ostream& stream, ShapeType value) { switch (value) { case ShapeType::Collision: return stream << "collision"; case ShapeType::Avoid: return stream << "avoid"; } return stream << "unknown shape type (" << static_cast<std::underlying_type_t<ShapeType>>(value) << ")"; } NavMeshDb::NavMeshDb(std::string_view path, std::uint64_t maxFileSize) : mDb(Sqlite3::makeDb(path, schema)) , mGetMaxTileId(*mDb, DbQueries::GetMaxTileId{}) , mFindTile(*mDb, DbQueries::FindTile{}) , mGetTileData(*mDb, DbQueries::GetTileData{}) , mInsertTile(*mDb, DbQueries::InsertTile{}) , mUpdateTile(*mDb, DbQueries::UpdateTile{}) , mDeleteTilesAt(*mDb, DbQueries::DeleteTilesAt{}) , mDeleteTilesAtExcept(*mDb, DbQueries::DeleteTilesAtExcept{}) , mDeleteTilesOutsideRange(*mDb, DbQueries::DeleteTilesOutsideRange{}) , mGetMaxShapeId(*mDb, DbQueries::GetMaxShapeId{}) , mFindShapeId(*mDb, DbQueries::FindShapeId{}) , mInsertShape(*mDb, DbQueries::InsertShape{}) , mVacuum(*mDb, DbQueries::Vacuum{}) { const std::uint64_t dbPageSize = getPageSize(*mDb); if (dbPageSize == 0) throw std::runtime_error("NavMeshDb page size is zero"); setMaxPageCount(*mDb, maxFileSize / dbPageSize + static_cast<std::uint64_t>((maxFileSize % dbPageSize) != 0)); } Sqlite3::Transaction NavMeshDb::startTransaction(Sqlite3::TransactionMode mode) { return Sqlite3::Transaction(*mDb, mode); } TileId NavMeshDb::getMaxTileId() { TileId tileId{ 0 }; request(*mDb, mGetMaxTileId, &tileId, 1); return tileId; } std::optional<Tile> NavMeshDb::findTile( ESM::RefId worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input) { Tile result; auto row = std::tie(result.mTileId, result.mVersion); const std::vector<std::byte> compressedInput = Misc::compress(input); if (&row == request(*mDb, mFindTile, &row, 1, worldspace.serializeText(), tilePosition, compressedInput)) return {}; return result; } std::optional<TileData> NavMeshDb::getTileData( ESM::RefId worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input) { TileData result; auto row = std::tie(result.mTileId, result.mVersion, result.mData); const std::vector<std::byte> compressedInput = Misc::compress(input); if (&row == request(*mDb, mGetTileData, &row, 1, worldspace.serializeText(), tilePosition, compressedInput)) return {}; result.mData = Misc::decompress(result.mData); return result; } int NavMeshDb::insertTile(TileId tileId, ESM::RefId worldspace, const TilePosition& tilePosition, TileVersion version, const std::vector<std::byte>& input, const std::vector<std::byte>& data) { const std::vector<std::byte> compressedInput = Misc::compress(input); const std::vector<std::byte> compressedData = Misc::compress(data); return execute(*mDb, mInsertTile, tileId, worldspace.serializeText(), tilePosition, version, compressedInput, compressedData); } int NavMeshDb::updateTile(TileId tileId, TileVersion version, const std::vector<std::byte>& data) { const std::vector<std::byte> compressedData = Misc::compress(data); return execute(*mDb, mUpdateTile, tileId, version, compressedData); } int NavMeshDb::deleteTilesAt(ESM::RefId worldspace, const TilePosition& tilePosition) { return execute(*mDb, mDeleteTilesAt, worldspace.serializeText(), tilePosition); } int NavMeshDb::deleteTilesAtExcept(ESM::RefId worldspace, const TilePosition& tilePosition, TileId excludeTileId) { return execute(*mDb, mDeleteTilesAtExcept, worldspace.serializeText(), tilePosition, excludeTileId); } int NavMeshDb::deleteTilesOutsideRange(ESM::RefId worldspace, const TilesPositionsRange& range) { return execute(*mDb, mDeleteTilesOutsideRange, worldspace.serializeText(), range); } ShapeId NavMeshDb::getMaxShapeId() { ShapeId shapeId{ 0 }; request(*mDb, mGetMaxShapeId, &shapeId, 1); return shapeId; } std::optional<ShapeId> NavMeshDb::findShapeId(std::string_view name, ShapeType type, const Sqlite3::ConstBlob& hash) { ShapeId shapeId; if (&shapeId == request(*mDb, mFindShapeId, &shapeId, 1, name, type, hash)) return {}; return shapeId; } int NavMeshDb::insertShape(ShapeId shapeId, std::string_view name, ShapeType type, const Sqlite3::ConstBlob& hash) { return execute(*mDb, mInsertShape, shapeId, name, type, hash); } void NavMeshDb::vacuum() { execute(*mDb, mVacuum); } namespace DbQueries { std::string_view GetMaxTileId::text() noexcept { return getMaxTileIdQuery; } std::string_view FindTile::text() noexcept { return findTileQuery; } void FindTile::bind(sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input) { Sqlite3::bindParameter(db, statement, ":worldspace", worldspace); Sqlite3::bindParameter(db, statement, ":tile_position_x", tilePosition.x()); Sqlite3::bindParameter(db, statement, ":tile_position_y", tilePosition.y()); Sqlite3::bindParameter(db, statement, ":input", input); } std::string_view GetTileData::text() noexcept { return getTileDataQuery; } void GetTileData::bind(sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input) { Sqlite3::bindParameter(db, statement, ":worldspace", worldspace); Sqlite3::bindParameter(db, statement, ":tile_position_x", tilePosition.x()); Sqlite3::bindParameter(db, statement, ":tile_position_y", tilePosition.y()); Sqlite3::bindParameter(db, statement, ":input", input); } std::string_view InsertTile::text() noexcept { return insertTileQuery; } void InsertTile::bind(sqlite3& db, sqlite3_stmt& statement, TileId tileId, std::string_view worldspace, const TilePosition& tilePosition, TileVersion version, const std::vector<std::byte>& input, const std::vector<std::byte>& data) { Sqlite3::bindParameter(db, statement, ":tile_id", tileId); Sqlite3::bindParameter(db, statement, ":worldspace", worldspace); Sqlite3::bindParameter(db, statement, ":tile_position_x", tilePosition.x()); Sqlite3::bindParameter(db, statement, ":tile_position_y", tilePosition.y()); Sqlite3::bindParameter(db, statement, ":version", version); Sqlite3::bindParameter(db, statement, ":input", input); Sqlite3::bindParameter(db, statement, ":data", data); } std::string_view UpdateTile::text() noexcept { return updateTileQuery; } void UpdateTile::bind(sqlite3& db, sqlite3_stmt& statement, TileId tileId, TileVersion version, const std::vector<std::byte>& data) { Sqlite3::bindParameter(db, statement, ":tile_id", tileId); Sqlite3::bindParameter(db, statement, ":version", version); Sqlite3::bindParameter(db, statement, ":data", data); } std::string_view DeleteTilesAt::text() noexcept { return deleteTilesAtQuery; } void DeleteTilesAt::bind( sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilePosition& tilePosition) { Sqlite3::bindParameter(db, statement, ":worldspace", worldspace); Sqlite3::bindParameter(db, statement, ":tile_position_x", tilePosition.x()); Sqlite3::bindParameter(db, statement, ":tile_position_y", tilePosition.y()); } std::string_view DeleteTilesAtExcept::text() noexcept { return deleteTilesAtExceptQuery; } void DeleteTilesAtExcept::bind(sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilePosition& tilePosition, TileId excludeTileId) { Sqlite3::bindParameter(db, statement, ":worldspace", worldspace); Sqlite3::bindParameter(db, statement, ":tile_position_x", tilePosition.x()); Sqlite3::bindParameter(db, statement, ":tile_position_y", tilePosition.y()); Sqlite3::bindParameter(db, statement, ":exclude_tile_id", excludeTileId); } std::string_view DeleteTilesOutsideRange::text() noexcept { return deleteTilesOutsideRangeQuery; } void DeleteTilesOutsideRange::bind( sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilesPositionsRange& range) { Sqlite3::bindParameter(db, statement, ":worldspace", worldspace); Sqlite3::bindParameter(db, statement, ":begin_tile_position_x", range.mBegin.x()); Sqlite3::bindParameter(db, statement, ":begin_tile_position_y", range.mBegin.y()); Sqlite3::bindParameter(db, statement, ":end_tile_position_x", range.mEnd.x()); Sqlite3::bindParameter(db, statement, ":end_tile_position_y", range.mEnd.y()); } std::string_view GetMaxShapeId::text() noexcept { return getMaxShapeIdQuery; } std::string_view FindShapeId::text() noexcept { return findShapeIdQuery; } void FindShapeId::bind( sqlite3& db, sqlite3_stmt& statement, std::string_view name, ShapeType type, const Sqlite3::ConstBlob& hash) { Sqlite3::bindParameter(db, statement, ":name", name); Sqlite3::bindParameter(db, statement, ":type", static_cast<int>(type)); Sqlite3::bindParameter(db, statement, ":hash", hash); } std::string_view InsertShape::text() noexcept { return insertShapeQuery; } void InsertShape::bind(sqlite3& db, sqlite3_stmt& statement, ShapeId shapeId, std::string_view name, ShapeType type, const Sqlite3::ConstBlob& hash) { Sqlite3::bindParameter(db, statement, ":shape_id", shapeId); Sqlite3::bindParameter(db, statement, ":name", name); Sqlite3::bindParameter(db, statement, ":type", static_cast<int>(type)); Sqlite3::bindParameter(db, statement, ":hash", hash); } std::string_view Vacuum::text() noexcept { return vacuumQuery; } } }
16,461
C++
.cpp
363
34.917355
120
0.611686
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,480
debug.cpp
OpenMW_openmw/components/detournavigator/debug.cpp
#include "debug.hpp" #include "exceptions.hpp" #include "recastmesh.hpp" #include "settings.hpp" #include "settingsutils.hpp" #include "tilespositionsrange.hpp" #include "version.hpp" #include <components/debug/writeflags.hpp> #include <DetourNavMesh.h> #include <DetourStatus.h> #include <osg/io_utils> #include <array> #include <filesystem> #include <fstream> #include <ostream> #include <string_view> namespace DetourNavigator { std::ostream& operator<<(std::ostream& stream, const TileBounds& value) { return stream << "TileBounds {" << value.mMin << ", " << value.mMax << "}"; } std::ostream& operator<<(std::ostream& stream, Status value) { #define OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(name) \ case Status::name: \ return stream << "DetourNavigator::Status::" #name; switch (value) { OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(Success) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(PartialPath) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(NavMeshNotFound) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(StartPolygonNotFound) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(EndPolygonNotFound) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(TargetPolygonNotFound) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(MoveAlongSurfaceFailed) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(FindPathOverPolygonsFailed) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(InitNavMeshQueryFailed) OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE(FindStraightPathFailed) } #undef OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_STATUS_MESSAGE return stream << "DetourNavigator::Error::" << static_cast<int>(value); } std::ostream& operator<<(std::ostream& s, const Water& v) { return s << "Water {" << v.mCellSize << ", " << v.mLevel << "}"; } std::ostream& operator<<(std::ostream& s, const CellWater& v) { return s << "CellWater {" << v.mCellPosition << ", " << v.mWater << "}"; } std::ostream& operator<<(std::ostream& s, const FlatHeightfield& v) { return s << "FlatHeightfield {" << v.mCellPosition << ", " << v.mCellSize << ", " << v.mHeight << "}"; } std::ostream& operator<<(std::ostream& s, const Heightfield& v) { s << "Heightfield {.mCellPosition=" << v.mCellPosition << ", .mCellSize=" << v.mCellSize << ", .mLength=" << static_cast<int>(v.mLength) << ", .mMinHeight=" << v.mMinHeight << ", .mMaxHeight=" << v.mMaxHeight << ", .mHeights={"; for (float h : v.mHeights) s << h << ", "; s << "}"; return s << ", .mOriginalSize=" << v.mOriginalSize << "}"; } std::ostream& operator<<(std::ostream& s, CollisionShapeType v) { switch (v) { case CollisionShapeType::Aabb: return s << "CollisionShapeType::Aabb"; case CollisionShapeType::RotatingBox: return s << "CollisionShapeType::RotatingBox"; case CollisionShapeType::Cylinder: return s << "CollisionShapeType::Cylinder"; } return s << "CollisionShapeType::" << static_cast<std::underlying_type_t<CollisionShapeType>>(v); } std::ostream& operator<<(std::ostream& s, const AgentBounds& v) { return s << "AgentBounds {" << v.mShapeType << ", {" << v.mHalfExtents.x() << ", " << v.mHalfExtents.y() << ", " << v.mHalfExtents.z() << "}}"; } namespace { using StatusString = Debug::FlagString<unsigned int>; constexpr std::array dtStatuses{ StatusString{ DT_FAILURE, "DT_FAILURE" }, StatusString{ DT_SUCCESS, "DT_SUCCESS" }, StatusString{ DT_IN_PROGRESS, "DT_IN_PROGRESS" }, StatusString{ DT_WRONG_MAGIC, "DT_WRONG_MAGIC" }, StatusString{ DT_WRONG_VERSION, "DT_WRONG_VERSION" }, StatusString{ DT_OUT_OF_MEMORY, "DT_OUT_OF_MEMORY" }, StatusString{ DT_INVALID_PARAM, "DT_INVALID_PARAM" }, StatusString{ DT_BUFFER_TOO_SMALL, "DT_BUFFER_TOO_SMALL" }, StatusString{ DT_OUT_OF_NODES, "DT_OUT_OF_NODES" }, StatusString{ DT_PARTIAL_RESULT, "DT_PARTIAL_RESULT" }, }; } std::ostream& operator<<(std::ostream& stream, const WriteDtStatus& value) { return Debug::writeFlags(stream, value.mStatus, dtStatuses); } std::ostream& operator<<(std::ostream& stream, const Flag value) { switch (value) { case Flag_none: return stream << "none"; case Flag_walk: return stream << "walk"; case Flag_swim: return stream << "swim"; case Flag_openDoor: return stream << "openDoor"; case Flag_usePathgrid: return stream << "usePathgrid"; } return stream; } std::ostream& operator<<(std::ostream& stream, const WriteFlags& value) { if (value.mValue == Flag_none) { return stream << Flag_none; } else { bool first = true; for (const auto flag : { Flag_walk, Flag_swim, Flag_openDoor, Flag_usePathgrid }) { if (value.mValue & flag) { if (!first) stream << " | "; first = false; stream << flag; } } return stream; } } std::ostream& operator<<(std::ostream& stream, AreaType value) { switch (value) { case AreaType_null: return stream << "null"; case AreaType_water: return stream << "water"; case AreaType_door: return stream << "door"; case AreaType_pathgrid: return stream << "pathgrid"; case AreaType_ground: return stream << "ground"; } return stream << "unknown area type (" << static_cast<std::underlying_type_t<AreaType>>(value) << ")"; } std::ostream& operator<<(std::ostream& stream, ChangeType value) { switch (value) { case ChangeType::remove: return stream << "ChangeType::remove"; case ChangeType::add: return stream << "ChangeType::add"; case ChangeType::update: return stream << "ChangeType::update"; } return stream << "ChangeType::" << static_cast<int>(value); } std::ostream& operator<<(std::ostream& stream, const Version& value) { return stream << "Version {" << value.mGeneration << ", " << value.mRevision << "}"; } std::ostream& operator<<(std::ostream& stream, const TilesPositionsRange& value) { return stream << "TilesPositionsRange {" << value.mBegin << ", " << value.mEnd << "}"; } std::ostream& operator<<(std::ostream& stream, const AreaCosts& value) { return stream << "AreaCosts {" << ".mWater = " << value.mWater << ", .mDoor = " << value.mDoor << ", .mPathgrid = " << value.mPathgrid << ", .mGround = " << value.mGround << "}"; } std::ostream& operator<<(std::ostream& stream, const DetourSettings& value) { return stream << "DetourSettings {" << ".mMaxPolys = " << value.mMaxPolys << ", .mMaxNavMeshQueryNodes = " << value.mMaxNavMeshQueryNodes << ", .mMaxPolygonPathSize = " << value.mMaxPolygonPathSize << ", .mMaxSmoothPathSize = " << value.mMaxSmoothPathSize << "}"; } void writeToFile(const RecastMesh& recastMesh, const std::string& pathPrefix, const std::string& revision, const RecastSettings& settings) { const auto path = pathPrefix + "recastmesh" + revision + ".obj"; std::ofstream file(std::filesystem::path(path), std::ios::out); if (!file.is_open()) throw NavigatorException("Open file failed: " + path); file.exceptions(std::ios::failbit | std::ios::badbit); file.precision(std::numeric_limits<float>::max_exponent10); std::vector<float> vertices = recastMesh.getMesh().getVertices(); for (std::size_t i = 0; i < vertices.size(); i += 3) { file << "v " << toNavMeshCoordinates(settings, vertices[i]) << ' ' << toNavMeshCoordinates(settings, vertices[i + 2]) << ' ' << toNavMeshCoordinates(settings, vertices[i + 1]) << '\n'; } std::size_t count = 0; for (int v : recastMesh.getMesh().getIndices()) { if (count % 3 == 0) { if (count != 0) file << '\n'; file << 'f'; } file << ' ' << (v + 1); ++count; } file << '\n'; } void writeToFile(const dtNavMesh& navMesh, const std::string& pathPrefix, const std::string& revision) { const int navMeshSetMagic = 'M' << 24 | 'S' << 16 | 'E' << 8 | 'T'; //'MSET'; const int navMeshSetVersion = 1; struct NavMeshSetHeader { int magic; int version; int numTiles; dtNavMeshParams params; }; struct NavMeshTileHeader { dtTileRef tileRef; int dataSize; }; const auto path = pathPrefix + "all_tiles_navmesh" + revision + ".bin"; std::ofstream file(std::filesystem::path(path), std::ios::out | std::ios::binary); if (!file.is_open()) throw NavigatorException("Open file failed: " + path); file.exceptions(std::ios::failbit | std::ios::badbit); NavMeshSetHeader header; header.magic = navMeshSetMagic; header.version = navMeshSetVersion; header.numTiles = 0; for (int i = 0; i < navMesh.getMaxTiles(); ++i) { const auto tile = navMesh.getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; header.numTiles++; } header.params = *navMesh.getParams(); using const_char_ptr = const char*; file.write(const_char_ptr(&header), sizeof(header)); for (int i = 0; i < navMesh.getMaxTiles(); ++i) { const auto tile = navMesh.getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; NavMeshTileHeader tileHeader; tileHeader.tileRef = navMesh.getTileRef(tile); tileHeader.dataSize = tile->dataSize; file.write(const_char_ptr(&tileHeader), sizeof(tileHeader)); file.write(const_char_ptr(tile->data), tile->dataSize); } } }
11,295
C++
.cpp
272
31.591912
120
0.556425
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,481
cellborder.cpp
OpenMW_openmw/components/terrain/cellborder.cpp
#include "cellborder.hpp" #include <osg/Geometry> #include <osg/Material> #include <osg/PolygonMode> #include "world.hpp" #include <components/esm/util.hpp> #include <components/esm3/loadland.hpp> #include <components/resource/scenemanager.hpp> #include <components/terrain/storage.hpp> namespace Terrain { CellBorder::CellBorder( Terrain::World* world, osg::Group* root, int borderMask, Resource::SceneManager* sceneManager) : mWorld(world) , mSceneManager(sceneManager) , mRoot(root) , mBorderMask(borderMask) { } osg::ref_ptr<osg::Group> CellBorder::createBorderGeometry(float x, float y, float size, Terrain::Storage* terrain, Resource::SceneManager* sceneManager, int mask, ESM::RefId worldspace, float offset, osg::Vec4f color) { const int cellSize = ESM::getCellSize(worldspace); const int borderSegments = 40; osg::Vec3 cellCorner = osg::Vec3(x * cellSize, y * cellSize, 0); size *= cellSize; osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array; osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array; osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array; normals->push_back(osg::Vec3(0.0f, -1.0f, 0.0f)); float borderStep = size / ((float)borderSegments); for (int i = 0; i <= 2 * borderSegments; ++i) { osg::Vec3f pos = i < borderSegments ? osg::Vec3(i * borderStep, 0.0f, 0.0f) : osg::Vec3(size, (i - borderSegments) * borderStep, 0.0f); pos += cellCorner; pos += osg::Vec3f(0, 0, terrain->getHeightAt(pos, worldspace) + offset); vertices->push_back(pos); osg::Vec4f col = i % 2 == 0 ? osg::Vec4f(0, 0, 0, 1) : color; colors->push_back(col); } osg::ref_ptr<osg::Geometry> border = new osg::Geometry; border->setVertexArray(vertices.get()); border->setNormalArray(normals.get()); border->setNormalBinding(osg::Geometry::BIND_OVERALL); border->setColorArray(colors.get()); border->setColorBinding(osg::Geometry::BIND_PER_VERTEX); border->addPrimitiveSet(new osg::DrawArrays(GL_LINE_STRIP, 0, vertices->size())); osg::ref_ptr<osg::Group> borderGroup = new osg::Group; borderGroup->addChild(border.get()); osg::StateSet* stateSet = borderGroup->getOrCreateStateSet(); osg::ref_ptr<osg::Material> material(new osg::Material); material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE); stateSet->setAttribute(material); osg::PolygonMode* polygonmode = new osg::PolygonMode; polygonmode->setMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE); stateSet->setAttributeAndModes(polygonmode, osg::StateAttribute::ON); sceneManager->recreateShaders(borderGroup, "debug"); borderGroup->setNodeMask(mask); return borderGroup; } void CellBorder::createCellBorderGeometry(int x, int y) { auto borderGroup = createBorderGeometry( x, y, 1.f, mWorld->getStorage(), mSceneManager, mBorderMask, mWorld->getWorldspace()); mRoot->addChild(borderGroup); mCellBorderNodes[std::make_pair(x, y)] = borderGroup; } void CellBorder::destroyCellBorderGeometry(int x, int y) { CellGrid::iterator it = mCellBorderNodes.find(std::make_pair(x, y)); if (it == mCellBorderNodes.end()) return; osg::ref_ptr<osg::Node> borderNode = it->second; mRoot->removeChild(borderNode); mCellBorderNodes.erase(it); } void CellBorder::destroyCellBorderGeometry() { for (const auto& v : mCellBorderNodes) mRoot->removeChild(v.second); mCellBorderNodes.clear(); } }
3,872
C++
.cpp
84
37.690476
118
0.644758
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,482
quadtreenode.cpp
OpenMW_openmw/components/terrain/quadtreenode.cpp
#include "quadtreenode.hpp" #include <cassert> #include <osgUtil/CullVisitor> #include "defs.hpp" #include "viewdata.hpp" namespace Terrain { float distance(const osg::BoundingBox& box, const osg::Vec3f& v) { if (box.contains(v)) return 0; else { osg::Vec3f maxDist(0, 0, 0); if (v.x() < box.xMin()) maxDist.x() = box.xMin() - v.x(); else if (v.x() > box.xMax()) maxDist.x() = v.x() - box.xMax(); if (v.y() < box.yMin()) maxDist.y() = box.yMin() - v.y(); else if (v.y() > box.yMax()) maxDist.y() = v.y() - box.yMax(); if (v.z() < box.zMin()) maxDist.z() = box.zMin() - v.z(); else if (v.z() > box.zMax()) maxDist.z() = v.z() - box.zMax(); return maxDist.length(); } } ChildDirection reflect(ChildDirection dir, Direction dir2) { assert(dir != Root); const int lookupTable[4][4] = { // NW NE SW SE { SW, SE, NW, NE }, // N { NE, NW, SE, SW }, // E { SW, SE, NW, NE }, // S { NE, NW, SE, SW } // W }; return (ChildDirection)lookupTable[dir2][dir]; } bool adjacent(ChildDirection dir, Direction dir2) { assert(dir != Root); const bool lookupTable[4][4] = { // NW NE SW SE { true, true, false, false }, // N { false, true, false, true }, // E { false, false, true, true }, // S { true, false, true, false } // W }; return lookupTable[dir2][dir]; } QuadTreeNode* searchNeighbour(QuadTreeNode* currentNode, Direction dir) { if (currentNode->getDirection() == Root) return nullptr; // Arrived at root node, the root node does not have neighbours QuadTreeNode* nextNode; if (adjacent(currentNode->getDirection(), dir)) nextNode = searchNeighbour(currentNode->getParent(), dir); else nextNode = currentNode->getParent(); if (nextNode && nextNode->getNumChildren()) return nextNode->getChild(reflect(currentNode->getDirection(), dir)); else return nullptr; } QuadTreeNode::QuadTreeNode(QuadTreeNode* parent, ChildDirection direction, float size, const osg::Vec2f& center) : mParent(parent) , mDirection(direction) , mValidBounds(false) , mSize(size) , mCenter(center) { for (unsigned int i = 0; i < 4; ++i) mNeighbours[i] = nullptr; } QuadTreeNode::~QuadTreeNode() {} QuadTreeNode* QuadTreeNode::getNeighbour(Direction dir) { return mNeighbours[dir]; } float QuadTreeNode::distance(const osg::Vec3f& v) const { const osg::BoundingBox& box = getBoundingBox(); return Terrain::distance(box, v); } void QuadTreeNode::initNeighbours() { for (int i = 0; i < 4; ++i) mNeighbours[i] = searchNeighbour(this, (Direction)i); for (unsigned int i = 0; i < getNumChildren(); ++i) getChild(i)->initNeighbours(); } void QuadTreeNode::traverseNodes(ViewData* vd, const osg::Vec3f& viewPoint, LodCallback* lodCallback) { if (!hasValidBounds()) return; LodCallback::ReturnValue lodResult = lodCallback->isSufficientDetail(this, distance(viewPoint)); if (lodResult == LodCallback::StopTraversal) return; else if (lodResult == LodCallback::Deeper && getNumChildren()) { for (unsigned int i = 0; i < getNumChildren(); ++i) getChild(i)->traverseNodes(vd, viewPoint, lodCallback); } else vd->add(this); } void QuadTreeNode::setBoundingBox(const osg::BoundingBox& boundingBox) { mBoundingBox = boundingBox; mValidBounds = boundingBox.valid(); } const osg::BoundingBox& QuadTreeNode::getBoundingBox() const { return mBoundingBox; } float QuadTreeNode::getSize() const { return mSize; } const osg::Vec2f& QuadTreeNode::getCenter() const { return mCenter; } }
4,330
C++
.cpp
127
25.267717
116
0.552978
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,483
viewdata.cpp
OpenMW_openmw/components/terrain/viewdata.cpp
#include "viewdata.hpp" #include "quadtreenode.hpp" #include <algorithm> namespace Terrain { ViewData::ViewData() : mNumEntries(0) , mLastUsageTimeStamp(0.0) , mChanged(false) , mHasViewPoint(false) , mWorldUpdateRevision(0) { } ViewData::~ViewData() {} void ViewData::copyFrom(const ViewData& other) { mNumEntries = other.mNumEntries; mEntries = other.mEntries; mChanged = other.mChanged; mHasViewPoint = other.mHasViewPoint; mViewPoint = other.mViewPoint; mActiveGrid = other.mActiveGrid; mWorldUpdateRevision = other.mWorldUpdateRevision; mNodes = other.mNodes; } void ViewData::add(QuadTreeNode* node) { unsigned int index = mNumEntries++; if (index + 1 > mEntries.size()) mEntries.resize(index + 1); ViewDataEntry& entry = mEntries[index]; if (entry.set(node)) { mChanged = true; mNodes.clear(); } } void ViewData::setViewPoint(const osg::Vec3f& viewPoint) { mViewPoint = viewPoint; mHasViewPoint = true; } // NOTE: As a performance optimisation, we cache mRenderingNodes from previous frames here. // If this cache becomes invalid (e.g. through mWorldUpdateRevision), we need to use clear() instead of reset(). void ViewData::reset() { // clear any unused entries for (unsigned int i = mNumEntries; i < mEntries.size(); ++i) mEntries[i].set(nullptr); // reset index for next frame mNumEntries = 0; mChanged = false; mNodes.clear(); } void ViewData::clear() { for (unsigned int i = 0; i < mEntries.size(); ++i) mEntries[i].set(nullptr); mNumEntries = 0; mLastUsageTimeStamp = 0; mChanged = false; mHasViewPoint = false; mNodes.clear(); } bool ViewData::suitableToUse(const osg::Vec4i& activeGrid) const { return hasViewPoint() && activeGrid == mActiveGrid && getNumEntries(); } bool ViewData::contains(const QuadTreeNode* node) const { return std::binary_search(mNodes.begin(), mNodes.end(), node); } void ViewData::buildNodeIndex() { if (!mNodes.empty()) return; mNodes.reserve(mNumEntries); for (std::size_t i = 0; i < mNumEntries; ++i) if (const QuadTreeNode* node = mEntries[i].mNode) mNodes.push_back(node); std::sort(mNodes.begin(), mNodes.end()); } void ViewData::removeNodeFromIndex(const QuadTreeNode* node) { const auto it = std::lower_bound(mNodes.begin(), mNodes.end(), node); if (it == mNodes.end() || *it != node) return; mNodes.erase(it); } ViewDataEntry::ViewDataEntry() : mNode(nullptr) , mLodFlags(0) { } bool ViewDataEntry::set(QuadTreeNode* node) { if (node == mNode) return false; else { mNode = node; // clear cached data mRenderingNode = nullptr; return true; } } ViewData* ViewDataMap::getViewData( osg::Object* viewer, const osg::Vec3f& viewPoint, const osg::Vec4i& activeGrid, bool& needsUpdate) { ViewerMap::const_iterator found = mViewers.find(viewer); ViewData* vd = nullptr; if (found == mViewers.end()) { vd = createOrReuseView(); mViewers[viewer] = vd; } else vd = found->second; needsUpdate = false; if (!(vd->suitableToUse(activeGrid) && (vd->getViewPoint() - viewPoint).length2() < mReuseDistance * mReuseDistance && vd->getWorldUpdateRevision() >= mWorldUpdateRevision)) { float shortestDist = viewer ? mReuseDistance * mReuseDistance : std::numeric_limits<float>::max(); const ViewData* mostSuitableView = nullptr; for (const ViewData* other : mUsedViews) { if (other->suitableToUse(activeGrid) && other->getWorldUpdateRevision() >= mWorldUpdateRevision) { float dist = (viewPoint - other->getViewPoint()).length2(); if (dist < shortestDist) { shortestDist = dist; mostSuitableView = other; } } } if (mostSuitableView && mostSuitableView != vd) { vd->copyFrom(*mostSuitableView); return vd; } else if (!mostSuitableView) { if (vd->getWorldUpdateRevision() != mWorldUpdateRevision) { vd->setWorldUpdateRevision(mWorldUpdateRevision); vd->clear(); } vd->setViewPoint(viewPoint); vd->setActiveGrid(activeGrid); needsUpdate = true; } } return vd; } ViewData* ViewDataMap::createOrReuseView() { ViewData* vd = nullptr; if (mUnusedViews.size()) { vd = mUnusedViews.front(); mUnusedViews.pop_front(); } else { mViewVector.emplace_back(); vd = &mViewVector.back(); } mUsedViews.push_back(vd); vd->setWorldUpdateRevision(mWorldUpdateRevision); return vd; } ViewData* ViewDataMap::createIndependentView() const { ViewData* vd = new ViewData; vd->setWorldUpdateRevision(mWorldUpdateRevision); return vd; } void ViewDataMap::clearUnusedViews(double referenceTime) { for (ViewerMap::iterator it = mViewers.begin(); it != mViewers.end();) { if (it->second->getLastUsageTimeStamp() + mExpiryDelay < referenceTime) mViewers.erase(it++); else ++it; } for (std::deque<ViewData*>::iterator it = mUsedViews.begin(); it != mUsedViews.end();) { if ((*it)->getLastUsageTimeStamp() + mExpiryDelay < referenceTime) { (*it)->clear(); mUnusedViews.push_back(*it); it = mUsedViews.erase(it); } else ++it; } } void ViewDataMap::rebuildViews() { ++mWorldUpdateRevision; } }
6,602
C++
.cpp
205
22.346341
116
0.550165
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,484
chunkmanager.cpp
OpenMW_openmw/components/terrain/chunkmanager.cpp
#include "chunkmanager.hpp" #include <osg/Material> #include <osg/Texture2D> #include <osgUtil/IncrementalCompileOperation> #include <components/resource/objectcache.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/lightmanager.hpp> #include "compositemaprenderer.hpp" #include "material.hpp" #include "storage.hpp" #include "terraindrawable.hpp" #include "texturemanager.hpp" namespace Terrain { ChunkManager::ChunkManager(Storage* storage, Resource::SceneManager* sceneMgr, TextureManager* textureManager, CompositeMapRenderer* renderer, ESM::RefId worldspace, double expiryDelay) : GenericResourceManager<ChunkKey>(nullptr, expiryDelay) , QuadTreeWorld::ChunkManager(worldspace) , mStorage(storage) , mSceneManager(sceneMgr) , mTextureManager(textureManager) , mCompositeMapRenderer(renderer) , mNodeMask(0) , mCompositeMapSize(512) , mCompositeMapLevel(1.f) , mMaxCompGeometrySize(1.f) { mMultiPassRoot = new osg::StateSet; mMultiPassRoot->setRenderingHint(osg::StateSet::OPAQUE_BIN); osg::ref_ptr<osg::Material> material(new osg::Material); material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE); mMultiPassRoot->setAttributeAndModes(material, osg::StateAttribute::ON); } osg::ref_ptr<osg::Node> ChunkManager::getChunk(float size, const osg::Vec2f& center, unsigned char lod, unsigned int lodFlags, bool activeGrid, const osg::Vec3f& viewPoint, bool compile) { // Override lod with the vertexLodMod adjusted value. // TODO: maybe we can refactor this code by moving all vertexLodMod code into this class. lod = static_cast<unsigned char>(lodFlags >> (4 * 4)); const ChunkKey key{ .mCenter = center, .mLod = lod, .mLodFlags = lodFlags }; if (osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(key)) return static_cast<osg::Node*>(obj.get()); const TerrainDrawable* templateGeometry = nullptr; const TemplateKey templateKey{ .mCenter = center, .mLod = lod }; const auto pair = mCache->lowerBound(templateKey); if (pair.has_value() && templateKey == TemplateKey{ .mCenter = pair->first.mCenter, .mLod = pair->first.mLod }) templateGeometry = static_cast<const TerrainDrawable*>(pair->second.get()); osg::ref_ptr<osg::Node> node = createChunk(size, center, lod, lodFlags, compile, templateGeometry); mCache->addEntryToObjectCache(key, node.get()); return node; } void ChunkManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const { Resource::reportStats("Terrain Chunk", frameNumber, mCache->getStats(), *stats); } void ChunkManager::clearCache() { GenericResourceManager<ChunkKey>::clearCache(); mBufferCache.clearCache(); } void ChunkManager::releaseGLObjects(osg::State* state) { GenericResourceManager<ChunkKey>::releaseGLObjects(state); mBufferCache.releaseGLObjects(state); } osg::ref_ptr<osg::Texture2D> ChunkManager::createCompositeMapRTT() { osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setTextureWidth(mCompositeMapSize); texture->setTextureHeight(mCompositeMapSize); texture->setInternalFormat(GL_RGB); texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); return texture; } void ChunkManager::createCompositeMapGeometry( float chunkSize, const osg::Vec2f& chunkCenter, const osg::Vec4f& texCoords, CompositeMap& compositeMap) { if (chunkSize > mMaxCompGeometrySize) { createCompositeMapGeometry(chunkSize / 2.f, chunkCenter + osg::Vec2f(chunkSize / 4.f, chunkSize / 4.f), osg::Vec4f( texCoords.x() + texCoords.z() / 2.f, texCoords.y(), texCoords.z() / 2.f, texCoords.w() / 2.f), compositeMap); createCompositeMapGeometry(chunkSize / 2.f, chunkCenter + osg::Vec2f(-chunkSize / 4.f, chunkSize / 4.f), osg::Vec4f(texCoords.x(), texCoords.y(), texCoords.z() / 2.f, texCoords.w() / 2.f), compositeMap); createCompositeMapGeometry(chunkSize / 2.f, chunkCenter + osg::Vec2f(chunkSize / 4.f, -chunkSize / 4.f), osg::Vec4f(texCoords.x() + texCoords.z() / 2.f, texCoords.y() + texCoords.w() / 2.f, texCoords.z() / 2.f, texCoords.w() / 2.f), compositeMap); createCompositeMapGeometry(chunkSize / 2.f, chunkCenter + osg::Vec2f(-chunkSize / 4.f, -chunkSize / 4.f), osg::Vec4f( texCoords.x(), texCoords.y() + texCoords.w() / 2.f, texCoords.z() / 2.f, texCoords.w() / 2.f), compositeMap); } else { float left = texCoords.x() * 2.f - 1; float top = texCoords.y() * 2.f - 1; float width = texCoords.z() * 2.f; float height = texCoords.w() * 2.f; std::vector<osg::ref_ptr<osg::StateSet>> passes = createPasses(chunkSize, chunkCenter, true); for (std::vector<osg::ref_ptr<osg::StateSet>>::iterator it = passes.begin(); it != passes.end(); ++it) { osg::ref_ptr<osg::Geometry> geom = osg::createTexturedQuadGeometry( osg::Vec3(left, top, 0), osg::Vec3(width, 0, 0), osg::Vec3(0, height, 0)); geom->setUseDisplayList( false); // don't bother making a display list for an object that is just rendered once. geom->setUseVertexBufferObjects(false); geom->setTexCoordArray(1, geom->getTexCoordArray(0), osg::Array::BIND_PER_VERTEX); geom->setStateSet(*it); compositeMap.mDrawables.emplace_back(geom); } } } std::vector<osg::ref_ptr<osg::StateSet>> ChunkManager::createPasses( float chunkSize, const osg::Vec2f& chunkCenter, bool forCompositeMap) { std::vector<LayerInfo> layerList; std::vector<osg::ref_ptr<osg::Image>> blendmaps; mStorage->getBlendmaps(chunkSize, chunkCenter, blendmaps, layerList, mWorldspace); bool useShaders = mSceneManager->getForceShaders(); if (!mSceneManager->getClampLighting()) useShaders = true; // always use shaders when lighting is unclamped, this is to avoid lighting seams between // a terrain chunk with normal maps and one without normal maps std::vector<TextureLayer> layers; { for (std::vector<LayerInfo>::const_iterator it = layerList.begin(); it != layerList.end(); ++it) { TextureLayer textureLayer; textureLayer.mParallax = it->mParallax; textureLayer.mSpecular = it->mSpecular; textureLayer.mDiffuseMap = mTextureManager->getTexture(it->mDiffuseMap); if (!forCompositeMap && !it->mNormalMap.empty()) textureLayer.mNormalMap = mTextureManager->getTexture(it->mNormalMap); if (it->requiresShaders()) useShaders = true; layers.push_back(textureLayer); } } if (forCompositeMap) useShaders = false; std::vector<osg::ref_ptr<osg::Texture2D>> blendmapTextures; for (std::vector<osg::ref_ptr<osg::Image>>::const_iterator it = blendmaps.begin(); it != blendmaps.end(); ++it) { osg::ref_ptr<osg::Texture2D> texture(new osg::Texture2D); texture->setImage(*it); texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); texture->setResizeNonPowerOfTwoHint(false); blendmapTextures.push_back(texture); } float blendmapScale = mStorage->getBlendmapScale(chunkSize); return ::Terrain::createPasses( useShaders, mSceneManager, layers, blendmapTextures, blendmapScale, blendmapScale); } osg::ref_ptr<osg::Node> ChunkManager::createChunk(float chunkSize, const osg::Vec2f& chunkCenter, unsigned char lod, unsigned int lodFlags, bool compile, const TerrainDrawable* templateGeometry) { osg::ref_ptr<TerrainDrawable> geometry(new TerrainDrawable); if (!templateGeometry) { osg::ref_ptr<osg::Vec3Array> positions(new osg::Vec3Array); osg::ref_ptr<osg::Vec3Array> normals(new osg::Vec3Array); osg::ref_ptr<osg::Vec4ubArray> colors(new osg::Vec4ubArray); colors->setNormalize(true); mStorage->fillVertexBuffers(lod, chunkSize, chunkCenter, mWorldspace, *positions, *normals, *colors); osg::ref_ptr<osg::VertexBufferObject> vbo(new osg::VertexBufferObject); positions->setVertexBufferObject(vbo); normals->setVertexBufferObject(vbo); colors->setVertexBufferObject(vbo); geometry->setVertexArray(positions); geometry->setNormalArray(normals, osg::Array::BIND_PER_VERTEX); geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX); } else { // Unfortunately we need to copy vertex data because of poor coupling with VertexBufferObject. osg::ref_ptr<osg::Array> positions = static_cast<osg::Array*>(templateGeometry->getVertexArray()->clone(osg::CopyOp::DEEP_COPY_ALL)); osg::ref_ptr<osg::Array> normals = static_cast<osg::Array*>(templateGeometry->getNormalArray()->clone(osg::CopyOp::DEEP_COPY_ALL)); osg::ref_ptr<osg::Array> colors = static_cast<osg::Array*>(templateGeometry->getColorArray()->clone(osg::CopyOp::DEEP_COPY_ALL)); osg::ref_ptr<osg::VertexBufferObject> vbo(new osg::VertexBufferObject); positions->setVertexBufferObject(vbo); normals->setVertexBufferObject(vbo); colors->setVertexBufferObject(vbo); geometry->setVertexArray(positions); geometry->setNormalArray(normals, osg::Array::BIND_PER_VERTEX); geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX); } geometry->setUseDisplayList(false); geometry->setUseVertexBufferObjects(true); if (chunkSize <= 1.f) geometry->setLightListCallback(new SceneUtil::LightListCallback); unsigned int numVerts = (mStorage->getCellVertices(mWorldspace) - 1) * chunkSize / (1 << lod) + 1; geometry->addPrimitiveSet(mBufferCache.getIndexBuffer(numVerts, lodFlags)); bool useCompositeMap = chunkSize >= mCompositeMapLevel; unsigned int numUvSets = useCompositeMap ? 1 : 2; geometry->setTexCoordArrayList(osg::Geometry::ArrayList(numUvSets, mBufferCache.getUVBuffer(numVerts))); geometry->createClusterCullingCallback(); geometry->setStateSet(mMultiPassRoot); if (templateGeometry) { if (templateGeometry->getCompositeMap()) { geometry->setCompositeMap(templateGeometry->getCompositeMap()); geometry->setCompositeMapRenderer(mCompositeMapRenderer); } geometry->setPasses(templateGeometry->getPasses()); } else { if (useCompositeMap) { osg::ref_ptr<CompositeMap> compositeMap = new CompositeMap; compositeMap->mTexture = createCompositeMapRTT(); createCompositeMapGeometry(chunkSize, chunkCenter, osg::Vec4f(0, 0, 1, 1), *compositeMap); mCompositeMapRenderer->addCompositeMap(compositeMap.get(), false); geometry->setCompositeMap(compositeMap); geometry->setCompositeMapRenderer(mCompositeMapRenderer); TextureLayer layer; layer.mDiffuseMap = compositeMap->mTexture; layer.mParallax = false; layer.mSpecular = false; geometry->setPasses(::Terrain::createPasses( mSceneManager->getForceShaders() || !mSceneManager->getClampLighting(), mSceneManager, std::vector<TextureLayer>(1, layer), std::vector<osg::ref_ptr<osg::Texture2D>>(), 1.f, 1.f)); } else { geometry->setPasses(createPasses(chunkSize, chunkCenter, false)); } } geometry->setupWaterBoundingBox(-1, chunkSize * mStorage->getCellWorldSize(mWorldspace) / numVerts); if (!templateGeometry && compile && mSceneManager->getIncrementalCompileOperation()) { mSceneManager->getIncrementalCompileOperation()->add(geometry); } geometry->setNodeMask(mNodeMask); return geometry; } }
13,247
C++
.cpp
246
42.821138
120
0.638393
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,485
texturemanager.cpp
OpenMW_openmw/components/terrain/texturemanager.cpp
#include "texturemanager.hpp" #include <osg/Texture2D> #include <components/resource/imagemanager.hpp> #include <components/resource/objectcache.hpp> #include <components/resource/scenemanager.hpp> namespace Terrain { TextureManager::TextureManager(Resource::SceneManager* sceneMgr, double expiryDelay) : ResourceManager(sceneMgr->getVFS(), expiryDelay) , mSceneManager(sceneMgr) { } struct UpdateTextureFilteringFunctor { UpdateTextureFilteringFunctor(Resource::SceneManager* sceneMgr) : mSceneManager(sceneMgr) { } Resource::SceneManager* mSceneManager; void operator()(std::string, osg::Object* obj) { mSceneManager->applyFilterSettings(static_cast<osg::Texture2D*>(obj)); } }; void TextureManager::updateTextureFiltering() { UpdateTextureFilteringFunctor f(mSceneManager); mCache->call(f); } osg::ref_ptr<osg::Texture2D> TextureManager::getTexture(VFS::Path::NormalizedView name) { // don't bother with case folding, since there is only one way of referring to terrain textures we can assume // the case is always the same osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(name); if (obj != nullptr) return static_cast<osg::Texture2D*>(obj.get()); osg::ref_ptr<osg::Texture2D> texture(new osg::Texture2D(mSceneManager->getImageManager()->getImage(name))); texture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); texture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT); mSceneManager->applyFilterSettings(texture); mCache->addEntryToObjectCache(name.value(), texture.get()); return texture; } void TextureManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const { Resource::reportStats("Terrain Texture", frameNumber, mCache->getStats(), *stats); } }
1,976
C++
.cpp
48
34.25
117
0.689457
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,486
world.cpp
OpenMW_openmw/components/terrain/world.cpp
#include "world.hpp" #include <osg/Camera> #include <osg/Group> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/settings/values.hpp> #include "chunkmanager.hpp" #include "compositemaprenderer.hpp" #include "heightcull.hpp" #include "storage.hpp" #include "texturemanager.hpp" namespace Terrain { World::World(osg::Group* parent, osg::Group* compileRoot, Resource::ResourceSystem* resourceSystem, Storage* storage, unsigned int nodeMask, unsigned int preCompileMask, unsigned int borderMask, ESM::RefId worldspace, double expiryDelay) : mStorage(storage) , mParent(parent) , mResourceSystem(resourceSystem) , mBorderVisible(false) , mWorldspace(worldspace) { mTerrainRoot = new osg::Group; mTerrainRoot->setNodeMask(nodeMask); mTerrainRoot->setName("Terrain Root"); osg::ref_ptr<osg::Camera> compositeCam = new osg::Camera; compositeCam->setRenderOrder(osg::Camera::PRE_RENDER, -1); compositeCam->setProjectionMatrix(osg::Matrix::identity()); compositeCam->setViewMatrix(osg::Matrix::identity()); compositeCam->setReferenceFrame(osg::Camera::ABSOLUTE_RF); compositeCam->setClearMask(0); compositeCam->setNodeMask(preCompileMask); mCompositeMapCamera = compositeCam; compileRoot->addChild(compositeCam); mCompositeMapRenderer = new CompositeMapRenderer; compositeCam->addChild(mCompositeMapRenderer); mParent->addChild(mTerrainRoot); mTextureManager = std::make_unique<TextureManager>(mResourceSystem->getSceneManager(), expiryDelay); mChunkManager = std::make_unique<ChunkManager>(mStorage, mResourceSystem->getSceneManager(), mTextureManager.get(), mCompositeMapRenderer, mWorldspace, expiryDelay); mChunkManager->setNodeMask(nodeMask); mCellBorder = std::make_unique<CellBorder>(this, mTerrainRoot.get(), borderMask, mResourceSystem->getSceneManager()); mResourceSystem->addResourceManager(mChunkManager.get()); mResourceSystem->addResourceManager(mTextureManager.get()); } World::World(osg::Group* parent, Storage* storage, unsigned int nodeMask, ESM::RefId worldspace) : mStorage(storage) , mParent(parent) , mCompositeMapCamera(nullptr) , mCompositeMapRenderer(nullptr) , mResourceSystem(nullptr) , mTextureManager(nullptr) , mChunkManager(nullptr) , mCellBorder(nullptr) , mBorderVisible(false) , mWorldspace(worldspace) { mTerrainRoot = new osg::Group; mTerrainRoot->setNodeMask(nodeMask); mParent->addChild(mTerrainRoot); } World::~World() { if (mResourceSystem && mChunkManager) mResourceSystem->removeResourceManager(mChunkManager.get()); if (mResourceSystem && mTextureManager) mResourceSystem->removeResourceManager(mTextureManager.get()); mParent->removeChild(mTerrainRoot); if (mCompositeMapCamera && mCompositeMapRenderer) { mCompositeMapCamera->removeChild(mCompositeMapRenderer); mCompositeMapCamera->getParent(0)->removeChild(mCompositeMapCamera); } } void World::setBordersVisible(bool visible) { mBorderVisible = visible; if (visible) { for (std::set<std::pair<int, int>>::iterator it = mLoadedCells.begin(); it != mLoadedCells.end(); ++it) mCellBorder->createCellBorderGeometry(it->first, it->second); } else mCellBorder->destroyCellBorderGeometry(); } void World::loadCell(int x, int y) { if (mBorderVisible) mCellBorder->createCellBorderGeometry(x, y); mLoadedCells.insert(std::pair<int, int>(x, y)); } void World::unloadCell(int x, int y) { if (mBorderVisible) mCellBorder->destroyCellBorderGeometry(x, y); mLoadedCells.erase(std::pair<int, int>(x, y)); } void World::setTargetFrameRate(float rate) { mCompositeMapRenderer->setTargetFrameRate(rate); } float World::getHeightAt(const osg::Vec3f& worldPos) { return mStorage->getHeightAt(worldPos, mWorldspace); } void World::updateTextureFiltering() { if (mTextureManager) mTextureManager->updateTextureFiltering(); } void World::clearAssociatedCaches() { if (mChunkManager) mChunkManager->clearCache(); } void World::enableHeightCullCallback(bool enable) { if (enable) mHeightCullCallback = new HeightCullCallback; else mHeightCullCallback = nullptr; } osg::Callback* World::getHeightCullCallback(float highz, unsigned int mask) { if (!mHeightCullCallback || mTerrainRoot->getNumChildren() == 0) return nullptr; mHeightCullCallback->setHighZ(highz); mHeightCullCallback->setCullMask(mask); return mHeightCullCallback; } }
5,164
C++
.cpp
132
31.318182
117
0.678329
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,487
quadtreeworld.cpp
OpenMW_openmw/components/terrain/quadtreeworld.cpp
#include "quadtreeworld.hpp" #include <osg/Material> #include <osg/PolygonMode> #include <osg/ShapeDrawable> #include <osgUtil/CullVisitor> #include <limits> #include <components/esm/util.hpp> #include <components/loadinglistener/reporter.hpp> #include <components/misc/constants.hpp> #include <components/misc/mathutil.hpp> #include <components/resource/resourcesystem.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include "chunkmanager.hpp" #include "compositemaprenderer.hpp" #include "heightcull.hpp" #include "quadtreenode.hpp" #include "storage.hpp" #include "terraindrawable.hpp" #include "viewdata.hpp" namespace { unsigned int Log2(unsigned int n) { unsigned int targetlevel = 0; while (n >>= 1) ++targetlevel; return targetlevel; } } namespace Terrain { class DefaultLodCallback : public LodCallback { public: DefaultLodCallback(float factor, float minSize, float viewDistance, const osg::Vec4i& grid, int cellSizeInUnits, float distanceModifier = 0.f) : mFactor(factor) , mMinSize(minSize) , mViewDistance(viewDistance) , mActiveGrid(grid) , mDistanceModifier(distanceModifier) , mCellSizeInUnits(cellSizeInUnits) { } ReturnValue isSufficientDetail(QuadTreeNode* node, float dist) override { const osg::Vec2f& center = node->getCenter(); bool activeGrid = (center.x() > mActiveGrid.x() && center.y() > mActiveGrid.y() && center.x() < mActiveGrid.z() && center.y() < mActiveGrid.w()); if (node->getSize() > 1) { float halfSize = node->getSize() / 2; osg::Vec4i nodeBounds(static_cast<int>(center.x() - halfSize), static_cast<int>(center.y() - halfSize), static_cast<int>(center.x() + halfSize), static_cast<int>(center.y() + halfSize)); bool intersects = (std::max(nodeBounds.x(), mActiveGrid.x()) < std::min(nodeBounds.z(), mActiveGrid.z()) && std::max(nodeBounds.y(), mActiveGrid.y()) < std::min(nodeBounds.w(), mActiveGrid.w())); // to prevent making chunks who will cross the activegrid border if (intersects) return Deeper; } dist = std::max(0.f, dist + mDistanceModifier); if (dist > mViewDistance && !activeGrid) // for Scene<->ObjectPaging sync the activegrid must remain loaded return StopTraversal; return getNativeLodLevel(node, mMinSize) <= convertDistanceToLodLevel(dist, mMinSize, mFactor, mCellSizeInUnits) ? StopTraversalAndUse : Deeper; } static unsigned int getNativeLodLevel(const QuadTreeNode* node, float minSize) { return Log2(static_cast<unsigned int>(node->getSize() / minSize)); } static unsigned int convertDistanceToLodLevel(float dist, float minSize, float factor, int cellSize) { return Log2(static_cast<unsigned int>(dist / (cellSize * minSize * factor))); } private: float mFactor; float mMinSize; float mViewDistance; osg::Vec4i mActiveGrid; float mDistanceModifier; int mCellSizeInUnits; }; class RootNode : public QuadTreeNode { public: RootNode(float size, const osg::Vec2f& center) : QuadTreeNode(nullptr, Root, size, center) , mWorld(nullptr) { } void setWorld(QuadTreeWorld* world) { mWorld = world; } void accept(osg::NodeVisitor& nv) override { if (!nv.validNodeMask(*this)) return; nv.pushOntoNodePath(this); mWorld->accept(nv); nv.popFromNodePath(); } private: QuadTreeWorld* mWorld; }; class QuadTreeBuilder { public: QuadTreeBuilder(Terrain::Storage* storage, float minSize, ESM::RefId worldspace) : mStorage(storage) , mMinX(0.f) , mMaxX(0.f) , mMinY(0.f) , mMaxY(0.f) , mMinSize(minSize) , mWorldspace(worldspace) { } void build() { mStorage->getBounds(mMinX, mMaxX, mMinY, mMaxY, mWorldspace); int origSizeX = static_cast<int>(mMaxX - mMinX); int origSizeY = static_cast<int>(mMaxY - mMinY); // Dividing a quad tree only works well for powers of two, so round up to the nearest one int size = Misc::nextPowerOfTwo(std::max(origSizeX, origSizeY)); float centerX = (mMinX + mMaxX) / 2.f + (size - origSizeX) / 2.f; float centerY = (mMinY + mMaxY) / 2.f + (size - origSizeY) / 2.f; mRootNode = new RootNode(size, osg::Vec2f(centerX, centerY)); addChildren(mRootNode); mRootNode->initNeighbours(); float cellWorldSize = mStorage->getCellWorldSize(mWorldspace); mRootNode->setInitialBound( osg::BoundingSphere(osg::BoundingBox(osg::Vec3(mMinX * cellWorldSize, mMinY * cellWorldSize, 0), osg::Vec3(mMaxX * cellWorldSize, mMaxY * cellWorldSize, 0)))); } void addChildren(QuadTreeNode* parent) { float halfSize = parent->getSize() / 2.f; osg::BoundingBox boundingBox; for (unsigned int i = 0; i < 4; ++i) { osg::ref_ptr<QuadTreeNode> child = addChild(parent, static_cast<ChildDirection>(i), halfSize); if (child) { boundingBox.expandBy(child->getBoundingBox()); parent->addChildNode(child); } } if (!boundingBox.valid()) parent->removeChildren(0, 4); else parent->setBoundingBox(boundingBox); } osg::ref_ptr<QuadTreeNode> addChild(QuadTreeNode* parent, ChildDirection direction, float size) { float halfSize = size / 2.f; osg::Vec2f center; switch (direction) { case SW: center = parent->getCenter() + osg::Vec2f(-halfSize, -halfSize); break; case SE: center = parent->getCenter() + osg::Vec2f(halfSize, -halfSize); break; case NW: center = parent->getCenter() + osg::Vec2f(-halfSize, halfSize); break; case NE: center = parent->getCenter() + osg::Vec2f(halfSize, halfSize); break; default: break; } osg::ref_ptr<QuadTreeNode> node = new QuadTreeNode(parent, direction, size, center); if (center.x() - halfSize > mMaxX || center.x() + halfSize < mMinX || center.y() - halfSize > mMaxY || center.y() + halfSize < mMinY) // Out of bounds of the actual terrain - this will happen because // we rounded the size up to the next power of two { // Still create and return an empty node so as to not break the assumption that each QuadTreeNode has // either 4 or 0 children. return node; } // Do not add child nodes for default cells without data. // size = 1 means that the single shape covers the whole cell. if (node->getSize() == 1 && !mStorage->hasData(ESM::ExteriorCellLocation(center.x() - 0.5, center.y() - 0.5, mWorldspace))) return node; if (node->getSize() <= mMinSize) { // We arrived at a leaf. // Since the tree is used for LOD level selection instead of culling, we do not need to load the actual // height data here. constexpr float minZ = -std::numeric_limits<float>::max(); constexpr float maxZ = std::numeric_limits<float>::max(); float cellWorldSize = mStorage->getCellWorldSize(mWorldspace); osg::BoundingBox boundingBox( osg::Vec3f((center.x() - halfSize) * cellWorldSize, (center.y() - halfSize) * cellWorldSize, minZ), osg::Vec3f((center.x() + halfSize) * cellWorldSize, (center.y() + halfSize) * cellWorldSize, maxZ)); node->setBoundingBox(boundingBox); return node; } else { addChildren(node); return node; } } osg::ref_ptr<RootNode> getRootNode() { return mRootNode; } private: Terrain::Storage* mStorage; float mMinX, mMaxX, mMinY, mMaxY; float mMinSize; osg::ref_ptr<RootNode> mRootNode; ESM::RefId mWorldspace; }; class DebugChunkManager : public QuadTreeWorld::ChunkManager { public: DebugChunkManager( Resource::SceneManager* sceneManager, Storage* storage, unsigned int nodeMask, ESM::RefId worldspace) : QuadTreeWorld::ChunkManager(worldspace) , mSceneManager(sceneManager) , mStorage(storage) , mNodeMask(nodeMask) { } osg::ref_ptr<osg::Node> getChunk(float size, const osg::Vec2f& chunkCenter, unsigned char lod, unsigned int lodFlags, bool activeGrid, const osg::Vec3f& viewPoint, bool compile) { osg::Vec3f center = { chunkCenter.x(), chunkCenter.y(), 0 }; auto chunkBorder = CellBorder::createBorderGeometry(center.x() - size / 2.f, center.y() - size / 2.f, size, mStorage, mSceneManager, mNodeMask, mWorldspace, 5.f, { 1, 0, 0, 0 }); osg::ref_ptr<SceneUtil::PositionAttitudeTransform> pat = new SceneUtil::PositionAttitudeTransform; pat->setPosition(-center * ESM::getCellSize(mWorldspace)); pat->addChild(chunkBorder); return pat; } unsigned int getNodeMask() { return mNodeMask; } private: Resource::SceneManager* mSceneManager; Storage* mStorage; unsigned int mNodeMask; }; QuadTreeWorld::QuadTreeWorld(osg::Group* parent, osg::Group* compileRoot, Resource::ResourceSystem* resourceSystem, Storage* storage, unsigned int nodeMask, unsigned int preCompileMask, unsigned int borderMask, int compMapResolution, float compMapLevel, float lodFactor, int vertexLodMod, float maxCompGeometrySize, bool debugChunks, ESM::RefId worldspace, double expiryDelay) : TerrainGrid( parent, compileRoot, resourceSystem, storage, nodeMask, worldspace, expiryDelay, preCompileMask, borderMask) , mViewDataMap(new ViewDataMap) , mQuadTreeBuilt(false) , mLodFactor(lodFactor) , mVertexLodMod(vertexLodMod) , mViewDistance(std::numeric_limits<float>::max()) , mMinSize(ESM::isEsm4Ext(worldspace) ? 1 / 4.f : 1 / 8.f) , mDebugTerrainChunks(debugChunks) { mChunkManager->setCompositeMapSize(compMapResolution); mChunkManager->setCompositeMapLevel(compMapLevel); mChunkManager->setMaxCompositeGeometrySize(maxCompGeometrySize); mChunkManagers.push_back(mChunkManager.get()); if (mDebugTerrainChunks) { mDebugChunkManager = std::make_unique<DebugChunkManager>( mResourceSystem->getSceneManager(), mStorage, borderMask, mWorldspace); addChunkManager(mDebugChunkManager.get()); } } QuadTreeWorld::~QuadTreeWorld() {} /// get the level of vertex detail to render this node at, expressed relative to the native resolution of the vertex /// data set, NOT relative to mMinSize as is the case with node LODs. unsigned int getVertexLod(QuadTreeNode* node, int vertexLodMod) { unsigned int vertexLod = DefaultLodCallback::getNativeLodLevel(node, 1); if (vertexLodMod > 0) { vertexLod = static_cast<unsigned int>(std::max(0, static_cast<int>(vertexLod) - vertexLodMod)); } else if (vertexLodMod < 0) { float size = node->getSize(); // Stop to simplify at this level since with size = 1 the node already covers the whole cell and has // getCellVertices() vertices. while (size < 1) { size *= 2; vertexLodMod = std::min(0, vertexLodMod + 1); } vertexLod += std::abs(vertexLodMod); } return vertexLod; } /// get the flags to use for stitching in the index buffer so that chunks of different LOD connect seamlessly unsigned int getLodFlags(QuadTreeNode* node, unsigned int ourVertexLod, int vertexLodMod, const ViewData* vd) { unsigned int lodFlags = 0; for (unsigned int i = 0; i < 4; ++i) { QuadTreeNode* neighbour = node->getNeighbour(static_cast<Direction>(i)); // If the neighbour isn't currently rendering itself, // go up until we find one. NOTE: We don't need to go down, // because in that case neighbour's detail would be higher than // our detail and the neighbour would handle stitching by itself. while (neighbour && !vd->contains(neighbour)) neighbour = neighbour->getParent(); unsigned int lod = 0; if (neighbour) lod = getVertexLod(neighbour, vertexLodMod); if (lod <= ourVertexLod) // We only need to worry about neighbours less detailed than we are - lod = 0; // neighbours with more detail will do the stitching themselves // Use 4 bits for each LOD delta if (lod > 0) { lodFlags |= (lod - ourVertexLod) << (4 * i); } } // Use the remaining bits for our vertex LOD lodFlags |= (ourVertexLod << (4 * 4)); return lodFlags; } void QuadTreeWorld::loadRenderingNode( ViewDataEntry& entry, ViewData* vd, float cellWorldSize, const osg::Vec4i& gridbounds, bool compile) { if (!vd->hasChanged() && entry.mRenderingNode) return; if (vd->hasChanged()) { vd->buildNodeIndex(); unsigned int ourVertexLod = getVertexLod(entry.mNode, mVertexLodMod); // have to recompute the lodFlags in case a neighbour has changed LOD. unsigned int lodFlags = getLodFlags(entry.mNode, ourVertexLod, mVertexLodMod, vd); if (lodFlags != entry.mLodFlags) { entry.mRenderingNode = nullptr; entry.mLodFlags = lodFlags; } } if (!entry.mRenderingNode) { osg::ref_ptr<SceneUtil::PositionAttitudeTransform> pat = new SceneUtil::PositionAttitudeTransform; pat->setPosition(osg::Vec3f( entry.mNode->getCenter().x() * cellWorldSize, entry.mNode->getCenter().y() * cellWorldSize, 0.f)); const osg::Vec2f& center = entry.mNode->getCenter(); bool activeGrid = (center.x() > gridbounds.x() && center.y() > gridbounds.y() && center.x() < gridbounds.z() && center.y() < gridbounds.w()); for (QuadTreeWorld::ChunkManager* m : mChunkManagers) { osg::ref_ptr<osg::Node> n = m->getChunk(entry.mNode->getSize(), entry.mNode->getCenter(), DefaultLodCallback::getNativeLodLevel(entry.mNode, mMinSize), entry.mLodFlags, activeGrid, vd->getViewPoint(), compile); if (n) pat->addChild(n); } entry.mRenderingNode = pat; } } namespace { osg::ref_ptr<osg::StateSet> makeStateSet() { osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet; stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF); stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); stateSet->setAttributeAndModes( new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE), osg::StateAttribute::ON); osg::ref_ptr<osg::Material> material = new osg::Material; material->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 1, 1)); material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, 1)); material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, 1)); stateSet->setAttributeAndModes(material, osg::StateAttribute::ON); stateSet->setRenderBinDetails(100, "RenderBin"); return stateSet; } void updateWaterCullingView( HeightCullCallback* callback, ViewData* vd, osgUtil::CullVisitor* cv, float cellworldsize, bool outofworld) { if (!(cv->getTraversalMask() & callback->getCullMask())) return; float lowZ = std::numeric_limits<float>::max(); float highZ = callback->getHighZ(); if (cv->getEyePoint().z() <= highZ || outofworld) { callback->setLowZ(-std::numeric_limits<float>::max()); return; } cv->pushCurrentMask(); static bool debug = getenv("OPENMW_WATER_CULLING_DEBUG") != nullptr; for (unsigned int i = 0; i < vd->getNumEntries(); ++i) { ViewDataEntry& entry = vd->getEntry(i); osg::BoundingBox bb = static_cast<TerrainDrawable*>(entry.mRenderingNode->asGroup()->getChild(0)) ->getWaterBoundingBox(); if (!bb.valid()) continue; osg::Vec3f ofs( entry.mNode->getCenter().x() * cellworldsize, entry.mNode->getCenter().y() * cellworldsize, 0.f); bb._min += ofs; bb._max += ofs; bb._min.z() = highZ; bb._max.z() = highZ; if (cv->isCulled(bb)) continue; lowZ = bb._min.z(); if (!debug) break; osg::Box* b = new osg::Box; b->set(bb.center(), bb._max - bb.center()); osg::ShapeDrawable* drw = new osg::ShapeDrawable(b); static const osg::ref_ptr<osg::StateSet> stateset = makeStateSet(); drw->setStateSet(stateset); drw->accept(*cv); } callback->setLowZ(lowZ); cv->popCurrentMask(); } } void QuadTreeWorld::accept(osg::NodeVisitor& nv) { bool isCullVisitor = nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR; if (!isCullVisitor && nv.getVisitorType() != osg::NodeVisitor::INTERSECTION_VISITOR) return; osg::Object* viewer = isCullVisitor ? static_cast<osgUtil::CullVisitor*>(&nv)->getCurrentCamera() : nullptr; bool needsUpdate = true; osg::Vec3f viewPoint = viewer ? nv.getViewPoint() : nv.getEyePoint(); ViewData* vd = mViewDataMap->getViewData(viewer, viewPoint, mActiveGrid, needsUpdate); if (needsUpdate) { vd->reset(); DefaultLodCallback lodCallback( mLodFactor, mMinSize, mViewDistance, mActiveGrid, ESM::getCellSize(mWorldspace)); mRootNode->traverseNodes(vd, viewPoint, &lodCallback); } const float cellWorldSize = ESM::getCellSize(mWorldspace); for (unsigned int i = 0; i < vd->getNumEntries(); ++i) { ViewDataEntry& entry = vd->getEntry(i); loadRenderingNode(entry, vd, cellWorldSize, mActiveGrid, false); entry.mRenderingNode->accept(nv); } if (mHeightCullCallback && isCullVisitor) updateWaterCullingView(mHeightCullCallback, vd, static_cast<osgUtil::CullVisitor*>(&nv), mStorage->getCellWorldSize(mWorldspace), !isGridEmpty()); vd->resetChanged(); double referenceTime = nv.getFrameStamp() ? nv.getFrameStamp()->getReferenceTime() : 0.0; if (referenceTime != 0.0) { vd->setLastUsageTimeStamp(referenceTime); mViewDataMap->clearUnusedViews(referenceTime); } } void QuadTreeWorld::ensureQuadTreeBuilt() { std::lock_guard<std::mutex> lock(mQuadTreeMutex); if (mQuadTreeBuilt) return; QuadTreeBuilder builder(mStorage, mMinSize, mWorldspace); builder.build(); mRootNode = builder.getRootNode(); mRootNode->setWorld(this); mQuadTreeBuilt = true; } void QuadTreeWorld::enable(bool enabled) { if (enabled) { ensureQuadTreeBuilt(); if (!mRootNode->getNumParents()) mTerrainRoot->addChild(mRootNode); } else if (mRootNode) mTerrainRoot->removeChild(mRootNode); } View* QuadTreeWorld::createView() { return mViewDataMap->createIndependentView(); } void QuadTreeWorld::preload(View* view, const osg::Vec3f& viewPoint, const osg::Vec4i& grid, std::atomic<bool>& abort, Loading::Reporter& reporter) { ensureQuadTreeBuilt(); const float cellWorldSize = mStorage->getCellWorldSize(mWorldspace); ViewData* vd = static_cast<ViewData*>(view); vd->setViewPoint(viewPoint); vd->setActiveGrid(grid); DefaultLodCallback lodCallback(mLodFactor, mMinSize, mViewDistance, grid, cellWorldSize); mRootNode->traverseNodes(vd, viewPoint, &lodCallback); reporter.addTotal(vd->getNumEntries()); for (unsigned int i = 0, n = vd->getNumEntries(); i < n && !abort; ++i) { ViewDataEntry& entry = vd->getEntry(i); loadRenderingNode(entry, vd, cellWorldSize, grid, true); reporter.addProgress(1); } } void QuadTreeWorld::reportStats(unsigned int frameNumber, osg::Stats* stats) { if (mCompositeMapRenderer) stats->setAttribute(frameNumber, "Composite", mCompositeMapRenderer->getCompileSetSize()); } void QuadTreeWorld::loadCell(int x, int y) { // fallback behavior only for undefined cells (every other is already handled in quadtree) float dummy; if (mChunkManager && !mStorage->getMinMaxHeights(1, osg::Vec2f(x + 0.5, y + 0.5), mWorldspace, dummy, dummy)) TerrainGrid::loadCell(x, y); else World::loadCell(x, y); } void QuadTreeWorld::unloadCell(int x, int y) { // fallback behavior only for undefined cells (every other is already handled in quadtree) float dummy; if (mChunkManager && !mStorage->getMinMaxHeights(1, osg::Vec2f(x + 0.5, y + 0.5), mWorldspace, dummy, dummy)) TerrainGrid::unloadCell(x, y); else World::unloadCell(x, y); } void QuadTreeWorld::addChunkManager(QuadTreeWorld::ChunkManager* m) { mChunkManagers.push_back(m); mTerrainRoot->setNodeMask(mTerrainRoot->getNodeMask() | m->getNodeMask()); if (m->getViewDistance()) m->setMaxLodLevel( DefaultLodCallback::convertDistanceToLodLevel(m->getViewDistance() + mViewDataMap->getReuseDistance(), mMinSize, ESM::getCellSize(mWorldspace), mLodFactor)); } void QuadTreeWorld::rebuildViews() { mViewDataMap->rebuildViews(); } void QuadTreeWorld::setViewDistance(float viewDistance) { if (mViewDistance == viewDistance) return; mViewDistance = viewDistance; mViewDataMap->rebuildViews(); } }
24,151
C++
.cpp
540
33.431481
120
0.590695
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,488
material.cpp
OpenMW_openmw/components/terrain/material.cpp
#include "material.hpp" #include <osg/BlendFunc> #include <osg/Capability> #include <osg/Depth> #include <osg/Fog> #include <osg/TexEnvCombine> #include <osg/TexMat> #include <osg/Texture2D> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/util.hpp> #include <components/shader/shadermanager.hpp> #include <components/stereo/stereomanager.hpp> #include <mutex> namespace { class BlendmapTexMat { public: static const osg::ref_ptr<osg::TexMat>& value(const int blendmapScale) { static BlendmapTexMat instance; return instance.get(blendmapScale); } const osg::ref_ptr<osg::TexMat>& get(const int blendmapScale) { const std::lock_guard<std::mutex> lock(mMutex); auto texMat = mTexMatMap.find(blendmapScale); if (texMat == mTexMatMap.end()) { osg::Matrixf matrix; float scale = (blendmapScale / (static_cast<float>(blendmapScale) + 1.f)); matrix.preMultTranslate(osg::Vec3f(0.5f, 0.5f, 0.f)); matrix.preMultScale(osg::Vec3f(scale, scale, 1.f)); matrix.preMultTranslate(osg::Vec3f(-0.5f, -0.5f, 0.f)); // We need to nudge the blendmap to look like vanilla. // This causes visible seams unless the blendmap's resolution is doubled, but Vanilla also doubles the // blendmap, apparently. matrix.preMultTranslate(osg::Vec3f(1.0f / blendmapScale / 4.0f, 1.0f / blendmapScale / 4.0f, 0.f)); texMat = mTexMatMap.insert(std::make_pair(blendmapScale, new osg::TexMat(matrix))).first; } return texMat->second; } private: std::mutex mMutex; std::map<float, osg::ref_ptr<osg::TexMat>> mTexMatMap; }; class LayerTexMat { public: static const osg::ref_ptr<osg::TexMat>& value(const float layerTileSize) { static LayerTexMat instance; return instance.get(layerTileSize); } const osg::ref_ptr<osg::TexMat>& get(const float layerTileSize) { const std::lock_guard<std::mutex> lock(mMutex); auto texMat = mTexMatMap.find(layerTileSize); if (texMat == mTexMatMap.end()) { texMat = mTexMatMap .insert(std::make_pair(layerTileSize, new osg::TexMat(osg::Matrix::scale(osg::Vec3f(layerTileSize, layerTileSize, 1.f))))) .first; } return texMat->second; } private: std::mutex mMutex; std::map<float, osg::ref_ptr<osg::TexMat>> mTexMatMap; }; class EqualDepth { public: static const osg::ref_ptr<osg::Depth>& value() { static EqualDepth instance; return instance.mValue; } private: osg::ref_ptr<osg::Depth> mValue; EqualDepth() : mValue(new SceneUtil::AutoDepth) { mValue->setFunction(osg::Depth::EQUAL); } }; class LequalDepth { public: static const osg::ref_ptr<osg::Depth>& value() { static LequalDepth instance; return instance.mValue; } private: osg::ref_ptr<osg::Depth> mValue; LequalDepth() : mValue(new SceneUtil::AutoDepth(osg::Depth::LEQUAL)) { } }; class BlendFuncFirst { public: static const osg::ref_ptr<osg::BlendFunc>& value() { static BlendFuncFirst instance; return instance.mValue; } private: osg::ref_ptr<osg::BlendFunc> mValue; BlendFuncFirst() : mValue(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ZERO)) { } }; class BlendFunc { public: static const osg::ref_ptr<osg::BlendFunc>& value() { static BlendFunc instance; return instance.mValue; } private: osg::ref_ptr<osg::BlendFunc> mValue; BlendFunc() : mValue(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE)) { } }; class TexEnvCombine { public: static const osg::ref_ptr<osg::TexEnvCombine>& value() { static TexEnvCombine instance; return instance.mValue; } private: osg::ref_ptr<osg::TexEnvCombine> mValue; TexEnvCombine() : mValue(new osg::TexEnvCombine) { mValue->setCombine_RGB(osg::TexEnvCombine::REPLACE); mValue->setSource0_RGB(osg::TexEnvCombine::PREVIOUS); } }; class DiscardAlphaCombine { public: static const osg::ref_ptr<osg::TexEnvCombine>& value() { static DiscardAlphaCombine instance; return instance.mValue; } private: osg::ref_ptr<osg::TexEnvCombine> mValue; DiscardAlphaCombine() : mValue(new osg::TexEnvCombine) { mValue->setCombine_Alpha(osg::TexEnvCombine::REPLACE); mValue->setSource0_Alpha(osg::TexEnvCombine::CONSTANT); mValue->setConstantColor(osg::Vec4(0.0, 0.0, 0.0, 1.0)); } }; class UniformCollection { public: static const UniformCollection& value() { static UniformCollection instance; return instance; } osg::ref_ptr<osg::Uniform> mDiffuseMap; osg::ref_ptr<osg::Uniform> mBlendMap; osg::ref_ptr<osg::Uniform> mNormalMap; osg::ref_ptr<osg::Uniform> mColorMode; UniformCollection() : mDiffuseMap(new osg::Uniform("diffuseMap", 0)) , mBlendMap(new osg::Uniform("blendMap", 1)) , mNormalMap(new osg::Uniform("normalMap", 2)) , mColorMode(new osg::Uniform("colorMode", 2)) { } }; } namespace Terrain { std::vector<osg::ref_ptr<osg::StateSet>> createPasses(bool useShaders, Resource::SceneManager* sceneManager, const std::vector<TextureLayer>& layers, const std::vector<osg::ref_ptr<osg::Texture2D>>& blendmaps, int blendmapScale, float layerTileSize) { auto& shaderManager = sceneManager->getShaderManager(); std::vector<osg::ref_ptr<osg::StateSet>> passes; unsigned int blendmapIndex = 0; for (std::vector<TextureLayer>::const_iterator it = layers.begin(); it != layers.end(); ++it) { bool firstLayer = (it == layers.begin()); osg::ref_ptr<osg::StateSet> stateset(new osg::StateSet); if (!blendmaps.empty()) { stateset->setMode(GL_BLEND, osg::StateAttribute::ON); if (sceneManager->getSupportsNormalsRT()) stateset->setAttribute(new osg::Disablei(GL_BLEND, 1)); stateset->setRenderBinDetails(firstLayer ? 0 : 1, "RenderBin"); if (!firstLayer) { stateset->setAttributeAndModes(BlendFunc::value(), osg::StateAttribute::ON); stateset->setAttributeAndModes(EqualDepth::value(), osg::StateAttribute::ON); } else { stateset->setAttributeAndModes(BlendFuncFirst::value(), osg::StateAttribute::ON); stateset->setAttributeAndModes(LequalDepth::value(), osg::StateAttribute::ON); } } if (useShaders) { stateset->setTextureAttributeAndModes(0, it->mDiffuseMap); if (layerTileSize != 1.f) stateset->setTextureAttributeAndModes( 0, LayerTexMat::value(layerTileSize), osg::StateAttribute::ON); stateset->addUniform(UniformCollection::value().mDiffuseMap); if (!blendmaps.empty()) { osg::ref_ptr<osg::Texture2D> blendmap = blendmaps.at(blendmapIndex++); stateset->setTextureAttributeAndModes(1, blendmap.get()); stateset->setTextureAttributeAndModes(1, BlendmapTexMat::value(blendmapScale)); stateset->addUniform(UniformCollection::value().mBlendMap); } bool parallax = it->mNormalMap && it->mParallax; bool reconstructNormalZ = false; if (it->mNormalMap) { stateset->setTextureAttributeAndModes(2, it->mNormalMap); stateset->addUniform(UniformCollection::value().mNormalMap); // Special handling for red-green normal maps (e.g. BC5 or R8G8). const osg::Image* image = it->mNormalMap->getImage(0); if (image) { switch (SceneUtil::computeUnsizedPixelFormat(image->getPixelFormat())) { case GL_RG: case GL_RG_INTEGER: { reconstructNormalZ = true; parallax = false; } } } } Shader::ShaderManager::DefineMap defineMap; defineMap["normalMap"] = (it->mNormalMap) ? "1" : "0"; defineMap["blendMap"] = (!blendmaps.empty()) ? "1" : "0"; defineMap["specularMap"] = it->mSpecular ? "1" : "0"; defineMap["parallax"] = parallax ? "1" : "0"; defineMap["writeNormals"] = (it == layers.end() - 1) ? "1" : "0"; defineMap["reconstructNormalZ"] = reconstructNormalZ ? "1" : "0"; Stereo::shaderStereoDefines(defineMap); stateset->setAttributeAndModes(shaderManager.getProgram("terrain", defineMap)); stateset->addUniform(UniformCollection::value().mColorMode); } else { // Add the actual layer texture osg::ref_ptr<osg::Texture2D> tex = it->mDiffuseMap; stateset->setTextureAttributeAndModes(0, tex.get()); if (layerTileSize != 1.f) stateset->setTextureAttributeAndModes( 0, LayerTexMat::value(layerTileSize), osg::StateAttribute::ON); stateset->setTextureAttributeAndModes(0, DiscardAlphaCombine::value(), osg::StateAttribute::ON); // Multiply by the alpha map if (!blendmaps.empty()) { osg::ref_ptr<osg::Texture2D> blendmap = blendmaps.at(blendmapIndex++); stateset->setTextureAttributeAndModes(1, blendmap.get()); // This is to map corner vertices directly to the center of a blendmap texel. stateset->setTextureAttributeAndModes(1, BlendmapTexMat::value(blendmapScale)); stateset->setTextureAttributeAndModes(1, TexEnvCombine::value(), osg::StateAttribute::ON); } } passes.push_back(stateset); } return passes; } }
11,463
C++
.cpp
289
27.595156
118
0.556195
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,489
compositemaprenderer.cpp
OpenMW_openmw/components/terrain/compositemaprenderer.cpp
#include "compositemaprenderer.hpp" #include <osg/FrameBufferObject> #include <osg/RenderInfo> #include <osg/Texture2D> #include <algorithm> namespace Terrain { CompositeMapRenderer::CompositeMapRenderer() : mTargetFrameRate(120) , mMinimumTimeAvailable(0.0025) { setSupportsDisplayList(false); setCullingActive(false); mFBO = new osg::FrameBufferObject; getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); } CompositeMapRenderer::~CompositeMapRenderer() {} void CompositeMapRenderer::drawImplementation(osg::RenderInfo& renderInfo) const { double dt = mTimer.time_s(); dt = std::min(dt, 0.2); mTimer.setStartTick(); double targetFrameTime = 1.0 / static_cast<double>(mTargetFrameRate); double conservativeTimeRatio(0.75); double availableTime = std::max((targetFrameTime - dt) * conservativeTimeRatio, mMinimumTimeAvailable); std::lock_guard<std::mutex> lock(mMutex); if (mImmediateCompileSet.empty() && mCompileSet.empty()) return; while (!mImmediateCompileSet.empty()) { osg::ref_ptr<CompositeMap> node = *mImmediateCompileSet.begin(); mImmediateCompileSet.erase(node); mMutex.unlock(); compile(*node, renderInfo); mMutex.lock(); } const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration<double>(availableTime); while (!mCompileSet.empty() && std::chrono::steady_clock::now() < deadline) { osg::ref_ptr<CompositeMap> node = *mCompileSet.begin(); mCompileSet.erase(node); mMutex.unlock(); compile(*node, renderInfo); mMutex.lock(); if (node->mCompiled < node->mDrawables.size()) { // We did not compile the map fully. // Place it back to queue to continue work in the next time. mCompileSet.insert(node); } } mTimer.setStartTick(); } void CompositeMapRenderer::compile(CompositeMap& compositeMap, osg::RenderInfo& renderInfo) const { // if there are no more external references we can assume the texture is no longer required if (compositeMap.mTexture->referenceCount() <= 1) { compositeMap.mCompiled = compositeMap.mDrawables.size(); return; } osg::Timer timer; osg::State& state = *renderInfo.getState(); osg::GLExtensions* ext = state.get<osg::GLExtensions>(); if (!mFBO) return; if (!ext->isFrameBufferObjectSupported) return; osg::FrameBufferAttachment attach(compositeMap.mTexture); mFBO->setAttachment(osg::Camera::COLOR_BUFFER, attach); mFBO->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); GLenum status = ext->glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { GLuint fboId = state.getGraphicsContext() ? state.getGraphicsContext()->getDefaultFboId() : 0; ext->glBindFramebuffer(GL_FRAMEBUFFER_EXT, fboId); OSG_ALWAYS << "Error attaching FBO" << std::endl; return; } // inform State that Texture attribute has changed due to compiling of FBO texture // should OSG be doing this on its own? state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), osg::StateAttribute::TEXTURE); for (unsigned int i = compositeMap.mCompiled; i < compositeMap.mDrawables.size(); ++i) { osg::Drawable* drw = compositeMap.mDrawables[i]; osg::StateSet* stateset = drw->getStateSet(); if (stateset) renderInfo.getState()->pushStateSet(stateset); renderInfo.getState()->apply(); glViewport(0, 0, compositeMap.mTexture->getTextureWidth(), compositeMap.mTexture->getTextureHeight()); drw->drawImplementation(renderInfo); if (stateset) renderInfo.getState()->popStateSet(); ++compositeMap.mCompiled; compositeMap.mDrawables[i] = nullptr; } if (compositeMap.mCompiled == compositeMap.mDrawables.size()) compositeMap.mDrawables = std::vector<osg::ref_ptr<osg::Drawable>>(); state.haveAppliedAttribute(osg::StateAttribute::VIEWPORT); GLuint fboId = state.getGraphicsContext() ? state.getGraphicsContext()->getDefaultFboId() : 0; ext->glBindFramebuffer(GL_FRAMEBUFFER_EXT, fboId); } void CompositeMapRenderer::setMinimumTimeAvailableForCompile(double time) { mMinimumTimeAvailable = time; } void CompositeMapRenderer::setTargetFrameRate(float framerate) { mTargetFrameRate = framerate; } void CompositeMapRenderer::addCompositeMap(CompositeMap* compositeMap, bool immediate) { std::lock_guard<std::mutex> lock(mMutex); if (immediate) mImmediateCompileSet.insert(compositeMap); else mCompileSet.insert(compositeMap); } void CompositeMapRenderer::setImmediate(CompositeMap* compositeMap) { std::lock_guard<std::mutex> lock(mMutex); CompileSet::iterator found = mCompileSet.find(compositeMap); if (found == mCompileSet.end()) return; else { mImmediateCompileSet.insert(compositeMap); mCompileSet.erase(found); } } unsigned int CompositeMapRenderer::getCompileSetSize() const { std::lock_guard<std::mutex> lock(mMutex); return mCompileSet.size(); } CompositeMap::CompositeMap() : mCompiled(0) { } CompositeMap::~CompositeMap() {} }
5,882
C++
.cpp
141
32.375887
114
0.639186
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,490
buffercache.cpp
OpenMW_openmw/components/terrain/buffercache.cpp
#include "buffercache.hpp" #include <cassert> #include <osg/PrimitiveSet> #include "defs.hpp" namespace { template <typename IndexArrayType> osg::ref_ptr<IndexArrayType> createIndexBuffer(unsigned int flags, unsigned int verts) { // LOD level n means every 2^n-th vertex is kept, but we currently handle LOD elsewhere. size_t lodLevel = 0; //(flags >> (4*4)); size_t lodDeltas[4]; for (int i = 0; i < 4; ++i) lodDeltas[i] = (flags >> (4 * i)) & (0xf); bool anyDeltas = (lodDeltas[Terrain::North] || lodDeltas[Terrain::South] || lodDeltas[Terrain::West] || lodDeltas[Terrain::East]); size_t increment = static_cast<size_t>(1) << lodLevel; assert(increment < verts); osg::ref_ptr<IndexArrayType> indices(new IndexArrayType(osg::PrimitiveSet::TRIANGLES)); indices->reserve((verts - 1) * (verts - 1) * 2 * 3 / increment); size_t rowStart = 0, colStart = 0, rowEnd = verts - 1, colEnd = verts - 1; // If any edge needs stitching we'll skip all edges at this point, // mainly because stitching one edge would have an effect on corners and on the adjacent edges if (anyDeltas) { colStart += increment; colEnd -= increment; rowEnd -= increment; rowStart += increment; } for (size_t row = rowStart; row < rowEnd; row += increment) { for (size_t col = colStart; col < colEnd; col += increment) { // diamond pattern if ((row + col % 2) % 2 == 1) { indices->push_back(verts * (col + increment) + row); indices->push_back(verts * (col + increment) + row + increment); indices->push_back(verts * col + row + increment); indices->push_back(verts * col + row); indices->push_back(verts * (col + increment) + row); indices->push_back(verts * (col) + row + increment); } else { indices->push_back(verts * col + row); indices->push_back(verts * (col + increment) + row + increment); indices->push_back(verts * col + row + increment); indices->push_back(verts * col + row); indices->push_back(verts * (col + increment) + row); indices->push_back(verts * (col + increment) + row + increment); } } } size_t innerStep = increment; if (anyDeltas) { // Now configure LOD transitions at the edges - this is pretty tedious, // and some very long and boring code, but it works great // South size_t row = 0; size_t outerStep = static_cast<size_t>(1) << (lodDeltas[Terrain::South] + lodLevel); for (size_t col = 0; col < verts - 1; col += outerStep) { indices->push_back(verts * col + row); indices->push_back(verts * (col + outerStep) + row); // Make sure not to touch the right edge if (col + outerStep == verts - 1) indices->push_back(verts * (col + outerStep - innerStep) + row + innerStep); else indices->push_back(verts * (col + outerStep) + row + innerStep); for (size_t i = 0; i < outerStep; i += innerStep) { // Make sure not to touch the left or right edges if (col + i == 0 || col + i == verts - 1 - innerStep) continue; indices->push_back(verts * (col) + row); indices->push_back(verts * (col + i + innerStep) + row + innerStep); indices->push_back(verts * (col + i) + row + innerStep); } } // North row = verts - 1; outerStep = size_t(1) << (lodDeltas[Terrain::North] + lodLevel); for (size_t col = 0; col < verts - 1; col += outerStep) { indices->push_back(verts * (col + outerStep) + row); indices->push_back(verts * col + row); // Make sure not to touch the left edge if (col == 0) indices->push_back(verts * (col + innerStep) + row - innerStep); else indices->push_back(verts * col + row - innerStep); for (size_t i = 0; i < outerStep; i += innerStep) { // Make sure not to touch the left or right edges if (col + i == 0 || col + i == verts - 1 - innerStep) continue; indices->push_back(verts * (col + i) + row - innerStep); indices->push_back(verts * (col + i + innerStep) + row - innerStep); indices->push_back(verts * (col + outerStep) + row); } } // West size_t col = 0; outerStep = size_t(1) << (lodDeltas[Terrain::West] + lodLevel); for (row = 0; row < verts - 1; row += outerStep) { indices->push_back(verts * col + row + outerStep); indices->push_back(verts * col + row); // Make sure not to touch the top edge if (row + outerStep == verts - 1) indices->push_back(verts * (col + innerStep) + row + outerStep - innerStep); else indices->push_back(verts * (col + innerStep) + row + outerStep); for (size_t i = 0; i < outerStep; i += innerStep) { // Make sure not to touch the top or bottom edges if (row + i == 0 || row + i == verts - 1 - innerStep) continue; indices->push_back(verts * col + row); indices->push_back(verts * (col + innerStep) + row + i); indices->push_back(verts * (col + innerStep) + row + i + innerStep); } } // East col = verts - 1; outerStep = size_t(1) << (lodDeltas[Terrain::East] + lodLevel); for (row = 0; row < verts - 1; row += outerStep) { indices->push_back(verts * col + row); indices->push_back(verts * col + row + outerStep); // Make sure not to touch the bottom edge if (row == 0) indices->push_back(verts * (col - innerStep) + row + innerStep); else indices->push_back(verts * (col - innerStep) + row); for (size_t i = 0; i < outerStep; i += innerStep) { // Make sure not to touch the top or bottom edges if (row + i == 0 || row + i == verts - 1 - innerStep) continue; indices->push_back(verts * col + row + outerStep); indices->push_back(verts * (col - innerStep) + row + i + innerStep); indices->push_back(verts * (col - innerStep) + row + i); } } } return indices; } } namespace Terrain { osg::ref_ptr<osg::Vec2Array> BufferCache::getUVBuffer(unsigned int numVerts) { std::lock_guard<std::mutex> lock(mUvBufferMutex); if (mUvBufferMap.find(numVerts) != mUvBufferMap.end()) { return mUvBufferMap[numVerts]; } int vertexCount = numVerts * numVerts; osg::ref_ptr<osg::Vec2Array> uvs(new osg::Vec2Array(osg::Array::BIND_PER_VERTEX)); uvs->reserve(vertexCount); for (unsigned int col = 0; col < numVerts; ++col) { for (unsigned int row = 0; row < numVerts; ++row) { uvs->push_back(osg::Vec2f( col / static_cast<float>(numVerts - 1), ((numVerts - 1) - row) / static_cast<float>(numVerts - 1))); } } // Assign a VBO here to enable state sharing between different Geometries. uvs->setVertexBufferObject(new osg::VertexBufferObject); mUvBufferMap[numVerts] = uvs; return uvs; } osg::ref_ptr<osg::DrawElements> BufferCache::getIndexBuffer(unsigned int numVerts, unsigned int flags) { std::pair<int, int> id = std::make_pair(numVerts, flags); std::lock_guard<std::mutex> lock(mIndexBufferMutex); if (mIndexBufferMap.find(id) != mIndexBufferMap.end()) { return mIndexBufferMap[id]; } osg::ref_ptr<osg::DrawElements> buffer; if (numVerts * numVerts <= (0xffffu)) buffer = createIndexBuffer<osg::DrawElementsUShort>(flags, numVerts); else buffer = createIndexBuffer<osg::DrawElementsUInt>(flags, numVerts); // Assign a EBO here to enable state sharing between different Geometries. buffer->setElementBufferObject(new osg::ElementBufferObject); mIndexBufferMap[id] = buffer; return buffer; } void BufferCache::clearCache() { { std::lock_guard<std::mutex> lock(mIndexBufferMutex); mIndexBufferMap.clear(); } { std::lock_guard<std::mutex> lock(mUvBufferMutex); mUvBufferMap.clear(); } } void BufferCache::releaseGLObjects(osg::State* state) { { std::lock_guard<std::mutex> lock(mIndexBufferMutex); for (const auto& [_, indexbuffer] : mIndexBufferMap) indexbuffer->releaseGLObjects(state); } { std::lock_guard<std::mutex> lock(mUvBufferMutex); for (const auto& [_, uvbuffer] : mUvBufferMap) uvbuffer->releaseGLObjects(state); } } }
10,093
C++
.cpp
220
32.390909
120
0.51027
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,491
terraindrawable.cpp
OpenMW_openmw/components/terrain/terraindrawable.cpp
#include "terraindrawable.hpp" #include <osg/ClusterCullingCallback> #include <osgUtil/CullVisitor> #include <components/sceneutil/lightmanager.hpp> #include "compositemaprenderer.hpp" namespace Terrain { TerrainDrawable::TerrainDrawable() {} TerrainDrawable::~TerrainDrawable() {} TerrainDrawable::TerrainDrawable(const TerrainDrawable& copy, const osg::CopyOp& copyop) : osg::Geometry(copy, copyop) , mPasses(copy.mPasses) , mLightListCallback(copy.mLightListCallback) { } void TerrainDrawable::accept(osg::NodeVisitor& nv) { if (nv.getVisitorType() != osg::NodeVisitor::CULL_VISITOR) { osg::Geometry::accept(nv); } else if (nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); cull(static_cast<osgUtil::CullVisitor*>(&nv)); nv.popFromNodePath(); } } inline float distance(const osg::Vec3& coord, const osg::Matrix& matrix) { return -((float)coord[0] * (float)matrix(0, 2) + (float)coord[1] * (float)matrix(1, 2) + (float)coord[2] * (float)matrix(2, 2) + matrix(3, 2)); } // canot use ClusterCullingCallback::cull: viewpoint != eyepoint // !osgfixpotential! bool clusterCull(osg::ClusterCullingCallback* cb, const osg::Vec3f& eyePoint, bool shadowcam) { float _deviation = cb->getDeviation(); const osg::Vec3& _controlPoint = cb->getControlPoint(); osg::Vec3 _normal = cb->getNormal(); if (shadowcam) _normal = _normal * -1; // inverting for shadowcam frontfaceculing float _radius = cb->getRadius(); if (_deviation <= -1.0f) return false; osg::Vec3 eye_cp = eyePoint - _controlPoint; float radius = eye_cp.length(); if (radius < _radius) return false; float deviation = (eye_cp * _normal) / radius; return deviation < _deviation; } void TerrainDrawable::cull(osgUtil::CullVisitor* cv) { const osg::BoundingBox& bb = getBoundingBox(); if (_cullingActive && cv->isCulled(getBoundingBox())) return; bool shadowcam = cv->getCurrentCamera()->getName() == "ShadowCamera"; if (cv->getCullingMode() & osg::CullStack::CLUSTER_CULLING && clusterCull(mClusterCullingCallback, cv->getEyePoint(), shadowcam)) return; osg::RefMatrix& matrix = *cv->getModelViewMatrix(); if (cv->getComputeNearFarMode() != osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR && bb.valid()) { if (!cv->updateCalculatedNearFar(matrix, *this, false)) return; } float depth = bb.valid() ? distance(bb.center(), matrix) : 0.0f; if (osg::isNaN(depth)) return; if (shadowcam) { cv->addDrawableAndDepth(this, &matrix, depth); return; } if (mCompositeMap && mCompositeMapRenderer) { mCompositeMapRenderer->setImmediate(mCompositeMap); mCompositeMapRenderer = nullptr; } bool pushedLight = mLightListCallback && mLightListCallback->pushLightState(this, cv); osg::StateSet* stateset = getStateSet(); if (stateset) cv->pushStateSet(stateset); for (PassVector::const_iterator it = mPasses.begin(); it != mPasses.end(); ++it) { cv->pushStateSet(*it); cv->addDrawableAndDepth(this, &matrix, depth); cv->popStateSet(); } if (stateset) cv->popStateSet(); if (pushedLight) cv->popStateSet(); } void TerrainDrawable::createClusterCullingCallback() { mClusterCullingCallback = new osg::ClusterCullingCallback(this); } void TerrainDrawable::setPasses(const TerrainDrawable::PassVector& passes) { mPasses = passes; } void TerrainDrawable::setLightListCallback(SceneUtil::LightListCallback* lightListCallback) { mLightListCallback = lightListCallback; } void TerrainDrawable::setupWaterBoundingBox(float waterheight, float margin) { osg::Vec3Array* vertices = static_cast<osg::Vec3Array*>(getVertexArray()); for (unsigned int i = 0; i < vertices->size(); ++i) { const osg::Vec3f& vertex = (*vertices)[i]; if (vertex.z() <= waterheight) mWaterBoundingBox.expandBy(vertex); } if (mWaterBoundingBox.valid()) { const osg::BoundingBox& bb = getBoundingBox(); mWaterBoundingBox.xMin() = std::max(bb.xMin(), mWaterBoundingBox.xMin() - margin); mWaterBoundingBox.yMin() = std::max(bb.yMin(), mWaterBoundingBox.yMin() - margin); mWaterBoundingBox.xMax() = std::min(bb.xMax(), mWaterBoundingBox.xMax() + margin); mWaterBoundingBox.xMax() = std::min(bb.xMax(), mWaterBoundingBox.xMax() + margin); } } void TerrainDrawable::compileGLObjects(osg::RenderInfo& renderInfo) const { for (PassVector::const_iterator it = mPasses.begin(); it != mPasses.end(); ++it) { osg::StateSet* stateset = *it; stateset->compileGLObjects(*renderInfo.getState()); } osg::Geometry::compileGLObjects(renderInfo); } }
5,378
C++
.cpp
135
31.02963
100
0.614425
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,492
terraingrid.cpp
OpenMW_openmw/components/terrain/terraingrid.cpp
#include "terraingrid.hpp" #include <memory> #include <osg/ComputeBoundsVisitor> #include <osg/Group> #include "chunkmanager.hpp" #include "heightcull.hpp" #include "storage.hpp" #include "view.hpp" #include <components/sceneutil/positionattitudetransform.hpp> namespace Terrain { class MyView : public View { public: osg::ref_ptr<osg::Node> mLoaded; void reset() override {} }; TerrainGrid::TerrainGrid(osg::Group* parent, osg::Group* compileRoot, Resource::ResourceSystem* resourceSystem, Storage* storage, unsigned int nodeMask, ESM::RefId worldspace, double expiryDelay, unsigned int preCompileMask, unsigned int borderMask) : Terrain::World( parent, compileRoot, resourceSystem, storage, nodeMask, preCompileMask, borderMask, worldspace, expiryDelay) , mNumSplits(4) { } TerrainGrid::TerrainGrid(osg::Group* parent, Storage* storage, ESM::RefId worldspace, unsigned int nodeMask) : Terrain::World(parent, storage, nodeMask, worldspace) , mNumSplits(4) { } TerrainGrid::~TerrainGrid() { while (!mGrid.empty()) { TerrainGrid::unloadCell(mGrid.begin()->first.first, mGrid.begin()->first.second); } } void TerrainGrid::cacheCell(View* view, int x, int y) { osg::Vec2f center(x + 0.5f, y + 0.5f); static_cast<MyView*>(view)->mLoaded = buildTerrain(nullptr, 1.f, center); } osg::ref_ptr<osg::Node> TerrainGrid::buildTerrain( osg::Group* parent, float chunkSize, const osg::Vec2f& chunkCenter) { if (chunkSize * mNumSplits > 1.f) { // keep splitting osg::ref_ptr<osg::Group> group(new osg::Group); if (parent) parent->addChild(group); float newChunkSize = chunkSize / 2.f; buildTerrain(group, newChunkSize, chunkCenter + osg::Vec2f(newChunkSize / 2.f, newChunkSize / 2.f)); buildTerrain(group, newChunkSize, chunkCenter + osg::Vec2f(newChunkSize / 2.f, -newChunkSize / 2.f)); buildTerrain(group, newChunkSize, chunkCenter + osg::Vec2f(-newChunkSize / 2.f, newChunkSize / 2.f)); buildTerrain(group, newChunkSize, chunkCenter + osg::Vec2f(-newChunkSize / 2.f, -newChunkSize / 2.f)); return group; } else { osg::ref_ptr<osg::Node> node = mChunkManager->getChunk(chunkSize, chunkCenter, 0, 0, false, osg::Vec3f(), true); if (!node) return nullptr; const float cellWorldSize = mStorage->getCellWorldSize(mWorldspace); osg::ref_ptr<SceneUtil::PositionAttitudeTransform> pat = new SceneUtil::PositionAttitudeTransform; pat->setPosition(osg::Vec3f(chunkCenter.x() * cellWorldSize, chunkCenter.y() * cellWorldSize, 0.f)); pat->addChild(node); if (parent) parent->addChild(pat); return pat; } } void TerrainGrid::loadCell(int x, int y) { if (mGrid.find(std::make_pair(x, y)) != mGrid.end()) return; // already loaded osg::Vec2f center(x + 0.5f, y + 0.5f); osg::ref_ptr<osg::Node> terrainNode = buildTerrain(nullptr, 1.f, center); if (!terrainNode) return; // no terrain defined TerrainGrid::World::loadCell(x, y); mTerrainRoot->addChild(terrainNode); mGrid[std::make_pair(x, y)] = terrainNode; updateWaterCulling(); } void TerrainGrid::unloadCell(int x, int y) { CellBorder::CellGrid::iterator it = mGrid.find(std::make_pair(x, y)); if (it == mGrid.end()) return; Terrain::World::unloadCell(x, y); osg::ref_ptr<osg::Node> terrainNode = it->second; mTerrainRoot->removeChild(terrainNode); mGrid.erase(it); updateWaterCulling(); } void TerrainGrid::updateWaterCulling() { if (!mHeightCullCallback) return; osg::ComputeBoundsVisitor computeBoundsVisitor; mTerrainRoot->accept(computeBoundsVisitor); float lowZ = computeBoundsVisitor.getBoundingBox()._min.z(); mHeightCullCallback->setLowZ(lowZ); } View* TerrainGrid::createView() { return new MyView; } }
4,358
C++
.cpp
111
30.891892
120
0.625444
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,493
storage.cpp
OpenMW_openmw/components/esmterrain/storage.cpp
#include "storage.hpp" #include <algorithm> #include <optional> #include <stdexcept> #include <osg/Image> #include <osg/Plane> #include <components/debug/debuglog.hpp> #include <components/esm/esmterrain.hpp> #include <components/esm/util.hpp> #include <components/esm3/loadland.hpp> #include <components/esm4/loadland.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/misc/strings/algorithm.hpp> #include <components/vfs/manager.hpp> #include "gridsampling.hpp" namespace ESMTerrain { namespace { UniqueTextureId getTextureIdAt(const LandObject* land, std::size_t x, std::size_t y) { assert(x < ESM::Land::LAND_TEXTURE_SIZE); assert(y < ESM::Land::LAND_TEXTURE_SIZE); if (land == nullptr) return { 0, 0 }; const ESM::LandData* data = land->getData(ESM::Land::DATA_VTEX); if (data == nullptr) return { 0, 0 }; const std::uint16_t tex = data->getTextures()[y * ESM::Land::LAND_TEXTURE_SIZE + x]; if (tex == 0) return { 0, 0 }; // vtex 0 is always the base texture, regardless of plugin return { tex, land->getPlugin() }; } } class LandCache { public: explicit LandCache(int offsetX, int offsetY, std::size_t size) : mOffsetX(offsetX) , mOffsetY(offsetY) , mSize(size) , mValues(size * size) { } std::optional<const LandObject*> find(int x, int y) const { const std::size_t index = getIndex(x, y); if (const auto& value = mValues[index]) return value->get(); return std::nullopt; } void insert(int x, int y, osg::ref_ptr<const LandObject>&& value) { const std::size_t index = getIndex(x, y); mValues[index] = std::move(value); } private: int mOffsetX; int mOffsetY; std::size_t mSize; std::vector<std::optional<osg::ref_ptr<const LandObject>>> mValues; std::size_t getIndex(int x, int y) const { return normalizeCoordinate(x, mOffsetX) * mSize + normalizeCoordinate(y, mOffsetY); } std::size_t normalizeCoordinate(int value, int offset) const { assert(value >= offset); assert(value < offset + static_cast<int>(mSize)); return static_cast<std::size_t>(value - offset); } }; LandObject::LandObject(const ESM4::Land& land, int loadFlags) : mData(land, loadFlags) { } LandObject::LandObject(const ESM::Land& land, int loadFlags) : mData(land, loadFlags) { } LandObject::LandObject(const LandObject& /*copy*/, const osg::CopyOp& /*copyOp*/) { throw std::logic_error("LandObject copy constructor is not implemented"); } const float defaultHeight = ESM::Land::DEFAULT_HEIGHT; Storage::Storage(const VFS::Manager* vfs, std::string_view normalMapPattern, std::string_view normalHeightMapPattern, bool autoUseNormalMaps, std::string_view specularMapPattern, bool autoUseSpecularMaps) : mVFS(vfs) , mNormalMapPattern(normalMapPattern) , mNormalHeightMapPattern(normalHeightMapPattern) , mAutoUseNormalMaps(autoUseNormalMaps) , mSpecularMapPattern(specularMapPattern) , mAutoUseSpecularMaps(autoUseSpecularMaps) { } bool Storage::getMinMaxHeights(float size, const osg::Vec2f& center, ESM::RefId worldspace, float& min, float& max) { assert(size <= 1 && "Storage::getMinMaxHeights, chunk size should be <= 1 cell"); osg::Vec2f origin = center - osg::Vec2f(size / 2.f, size / 2.f); int cellX = static_cast<int>(std::floor(origin.x())); int cellY = static_cast<int>(std::floor(origin.y())); osg::ref_ptr<const LandObject> land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace)); const ESM::LandData* data = land ? land->getData(ESM::Land::DATA_VHGT) : nullptr; const int landSize = ESM::getLandSize(worldspace); int startRow = (origin.x() - cellX) * landSize; int startColumn = (origin.y() - cellY) * landSize; int endRow = startRow + size * (landSize - 1) + 1; int endColumn = startColumn + size * (landSize - 1) + 1; if (data) { min = std::numeric_limits<float>::max(); max = -std::numeric_limits<float>::max(); for (int row = startRow; row < endRow; ++row) { for (int col = startColumn; col < endColumn; ++col) { float h = data->getHeights()[col * landSize + row]; if (h > max) max = h; if (h < min) min = h; } } return true; } min = defaultHeight; max = defaultHeight; return false; } void Storage::fixNormal( osg::Vec3f& normal, ESM::ExteriorCellLocation cellLocation, int col, int row, LandCache& cache) { const int landSize = ESM::getLandSize(cellLocation.mWorldspace); while (col >= landSize - 1) { ++cellLocation.mY; col -= landSize - 1; } while (row >= landSize - 1) { ++cellLocation.mX; row -= landSize - 1; } while (col < 0) { --cellLocation.mY; col += landSize - 1; } while (row < 0) { --cellLocation.mX; row += landSize - 1; } const LandObject* land = getLand(cellLocation, cache); const ESM::LandData* data = land ? land->getData(ESM::Land::DATA_VNML) : nullptr; if (data) { normal.x() = data->getNormals()[col * landSize * 3 + row * 3]; normal.y() = data->getNormals()[col * landSize * 3 + row * 3 + 1]; normal.z() = data->getNormals()[col * landSize * 3 + row * 3 + 2]; normal.normalize(); } else normal = osg::Vec3f(0, 0, 1); } void Storage::averageNormal( osg::Vec3f& normal, ESM::ExteriorCellLocation cellLocation, int col, int row, LandCache& cache) { osg::Vec3f n1, n2, n3, n4; fixNormal(n1, cellLocation, col + 1, row, cache); fixNormal(n2, cellLocation, col - 1, row, cache); fixNormal(n3, cellLocation, col, row + 1, cache); fixNormal(n4, cellLocation, col, row - 1, cache); normal = (n1 + n2 + n3 + n4); normal.normalize(); } void Storage::fixColour( osg::Vec4ub& color, ESM::ExteriorCellLocation cellLocation, int col, int row, LandCache& cache) { const int landSize = ESM::getLandSize(cellLocation.mWorldspace); if (col == landSize - 1) { ++cellLocation.mY; col = 0; } if (row == landSize - 1) { ++cellLocation.mX; row = 0; } const LandObject* land = getLand(cellLocation, cache); const ESM::LandData* data = land ? land->getData(ESM::Land::DATA_VCLR) : nullptr; if (data) { color.r() = data->getColors()[col * landSize * 3 + row * 3]; color.g() = data->getColors()[col * landSize * 3 + row * 3 + 1]; color.b() = data->getColors()[col * landSize * 3 + row * 3 + 2]; } else { color.r() = 255; color.g() = 255; color.b() = 255; } } void Storage::fillVertexBuffers(int lodLevel, float size, const osg::Vec2f& center, ESM::RefId worldspace, osg::Vec3Array& positions, osg::Vec3Array& normals, osg::Vec4ubArray& colours) { if (lodLevel < 0 || 63 < lodLevel) throw std::invalid_argument("Invalid terrain lod level: " + std::to_string(lodLevel)); if (size <= 0) throw std::invalid_argument("Invalid terrain size: " + std::to_string(size)); // LOD level n means every 2^n-th vertex is kept const std::size_t sampleSize = std::size_t{ 1 } << lodLevel; const std::size_t cellSize = static_cast<std::size_t>(ESM::getLandSize(worldspace)); const std::size_t numVerts = static_cast<std::size_t>(size * (cellSize - 1) / sampleSize) + 1; positions.resize(numVerts * numVerts); normals.resize(numVerts * numVerts); colours.resize(numVerts * numVerts); const bool alteration = useAlteration(); const int landSizeInUnits = ESM::getCellSize(worldspace); const osg::Vec2f origin = center - osg::Vec2f(size, size) * 0.5f; const int startCellX = static_cast<int>(std::floor(origin.x())); const int startCellY = static_cast<int>(std::floor(origin.y())); LandCache cache(startCellX - 1, startCellY - 1, static_cast<std::size_t>(std::ceil(size)) + 2); std::pair lastCell{ startCellX, startCellY }; const LandObject* land = getLand(ESM::ExteriorCellLocation(startCellX, startCellY, worldspace), cache); const ESM::LandData* heightData = nullptr; const ESM::LandData* normalData = nullptr; const ESM::LandData* colourData = nullptr; bool validHeightDataExists = false; if (land != nullptr) { heightData = land->getData(ESM::Land::DATA_VHGT); normalData = land->getData(ESM::Land::DATA_VNML); colourData = land->getData(ESM::Land::DATA_VCLR); validHeightDataExists = true; } const auto handleSample = [&](std::size_t cellShiftX, std::size_t cellShiftY, std::size_t row, std::size_t col, std::size_t vertX, std::size_t vertY) { const int cellX = startCellX + cellShiftX; const int cellY = startCellY + cellShiftY; const std::pair cell{ cellX, cellY }; const ESM::ExteriorCellLocation cellLocation(cellX, cellY, worldspace); if (lastCell != cell) { land = getLand(cellLocation, cache); heightData = nullptr; normalData = nullptr; colourData = nullptr; if (land != nullptr) { heightData = land->getData(ESM::Land::DATA_VHGT); normalData = land->getData(ESM::Land::DATA_VNML); colourData = land->getData(ESM::Land::DATA_VCLR); validHeightDataExists = true; } lastCell = cell; } float height = defaultHeight; if (heightData != nullptr) height = heightData->getHeights()[col * cellSize + row]; if (alteration) height += getAlteredHeight(col, row); const std::size_t vertIndex = vertX * numVerts + vertY; positions[vertIndex] = osg::Vec3f((vertX / static_cast<float>(numVerts - 1) - 0.5f) * size * landSizeInUnits, (vertY / static_cast<float>(numVerts - 1) - 0.5f) * size * landSizeInUnits, height); const std::size_t srcArrayIndex = col * cellSize * 3 + row * 3; osg::Vec3f normal(0, 0, 1); if (normalData != nullptr) { for (std::size_t i = 0; i < 3; ++i) normal[i] = normalData->getNormals()[srcArrayIndex + i]; normal.normalize(); } // Normals apparently don't connect seamlessly between cells if (col == cellSize - 1 || row == cellSize - 1) fixNormal(normal, cellLocation, col, row, cache); // some corner normals appear to be complete garbage (z < 0) if ((row == 0 || row == cellSize - 1) && (col == 0 || col == cellSize - 1)) averageNormal(normal, cellLocation, col, row, cache); assert(normal.z() > 0); normals[vertIndex] = normal; osg::Vec4ub color(255, 255, 255, 255); if (colourData != nullptr) for (std::size_t i = 0; i < 3; ++i) color[i] = colourData->getColors()[srcArrayIndex + i]; // Does nothing by default, override in OpenMW-CS if (alteration) adjustColor(col, row, heightData, color); // Unlike normals, colors mostly connect seamlessly between cells, but not always... if (col == cellSize - 1 || row == cellSize - 1) fixColour(color, cellLocation, col, row, cache); colours[vertIndex] = color; }; const std::size_t beginX = static_cast<std::size_t>((origin.x() - startCellX) * cellSize); const std::size_t beginY = static_cast<std::size_t>((origin.y() - startCellY) * cellSize); const std::size_t distance = static_cast<std::size_t>(size * (cellSize - 1)) + 1; sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, handleSample); if (!validHeightDataExists && ESM::isEsm4Ext(worldspace)) std::fill(positions.begin(), positions.end(), osg::Vec3f()); } std::string Storage::getTextureName(UniqueTextureId id) { std::string_view texture = "_land_default.dds"; if (id.first != 0) { // NB: All vtex ids are +1 compared to the ltex ids const std::string* ltex = getLandTexture(id.first - 1, id.second); if (ltex) texture = *ltex; else { Log(Debug::Warning) << "Warning: Unable to find land texture index " << id.first - 1 << " in plugin " << id.second << ", using default texture instead"; } } // this is needed due to MWs messed up texture handling return Misc::ResourceHelpers::correctTexturePath(texture, mVFS); } void Storage::getBlendmaps(float chunkSize, const osg::Vec2f& chunkCenter, ImageVector& blendmaps, std::vector<Terrain::LayerInfo>& layerList, ESM::RefId worldspace) { const osg::Vec2f origin = chunkCenter - osg::Vec2f(chunkSize, chunkSize) * 0.5f; const int startCellX = static_cast<int>(std::floor(origin.x())); const int startCellY = static_cast<int>(std::floor(origin.y())); const std::size_t blendmapSize = getBlendmapSize(chunkSize, ESM::Land::LAND_TEXTURE_SIZE); // We need to upscale the blendmap 2x with nearest neighbor sampling to look like Vanilla constexpr std::size_t imageScaleFactor = 2; const std::size_t blendmapImageSize = blendmapSize * imageScaleFactor; std::vector<UniqueTextureId> textureIds(blendmapSize * blendmapSize); LandCache cache(startCellX - 1, startCellY - 1, static_cast<std::size_t>(std::ceil(chunkSize)) + 2); std::pair lastCell{ startCellX, startCellY }; const LandObject* land = getLand(ESM::ExteriorCellLocation(startCellX, startCellY, worldspace), cache); const auto handleSample = [&](const CellSample& sample) { const std::pair cell{ sample.mCellX, sample.mCellY }; if (lastCell != cell) { land = getLand(ESM::ExteriorCellLocation(sample.mCellX, sample.mCellY, worldspace), cache); lastCell = cell; } textureIds[sample.mDstCol * blendmapSize + sample.mDstRow] = getTextureIdAt(land, sample.mSrcRow, sample.mSrcCol); }; sampleBlendmaps(chunkSize, origin.x(), origin.y(), ESM::Land::LAND_TEXTURE_SIZE, handleSample); std::map<UniqueTextureId, std::size_t> textureIndicesMap; for (std::size_t y = 0; y < blendmapSize; ++y) { for (std::size_t x = 0; x < blendmapSize; ++x) { const UniqueTextureId id = textureIds[y * blendmapSize + x]; auto found = textureIndicesMap.find(id); if (found == textureIndicesMap.end()) { std::size_t layerIndex = layerList.size(); Terrain::LayerInfo info = getLayerInfo(getTextureName(id)); // look for existing diffuse map, which may be present when several plugins use the same texture for (std::size_t i = 0; i < layerList.size(); ++i) { if (layerList[i].mDiffuseMap == info.mDiffuseMap) { layerIndex = i; break; } } found = textureIndicesMap.emplace(id, layerIndex).first; if (layerIndex >= layerList.size()) { osg::ref_ptr<osg::Image> image(new osg::Image); image->allocateImage(static_cast<int>(blendmapImageSize), static_cast<int>(blendmapImageSize), 1, GL_ALPHA, GL_UNSIGNED_BYTE); std::memset(image->data(), 0, image->getTotalDataSize()); blendmaps.push_back(std::move(image)); layerList.push_back(std::move(info)); } } const std::size_t layerIndex = found->second; unsigned char* const data = blendmaps[layerIndex]->data(); const std::size_t realY = (blendmapSize - y - 1) * imageScaleFactor; const std::size_t realX = x * imageScaleFactor; data[((realY + 0) * blendmapImageSize + realX + 0)] = 255; data[((realY + 1) * blendmapImageSize + realX + 0)] = 255; data[((realY + 0) * blendmapImageSize + realX + 1)] = 255; data[((realY + 1) * blendmapImageSize + realX + 1)] = 255; } } if (blendmaps.size() == 1) blendmaps.clear(); // If a single texture fills the whole terrain, there is no need to blend } float Storage::getHeightAt(const osg::Vec3f& worldPos, ESM::RefId worldspace) { const float cellSize = ESM::getCellSize(worldspace); int cellX = static_cast<int>(std::floor(worldPos.x() / cellSize)); int cellY = static_cast<int>(std::floor(worldPos.y() / cellSize)); osg::ref_ptr<const LandObject> land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace)); if (!land) return ESM::isEsm4Ext(worldspace) ? std::numeric_limits<float>::lowest() : defaultHeight; const ESM::LandData* data = land->getData(ESM::Land::DATA_VHGT); if (!data) return defaultHeight; const int landSize = data->getLandSize(); // Mostly lifted from Ogre::Terrain::getHeightAtTerrainPosition // Normalized position in the cell float nX = (worldPos.x() - (cellX * cellSize)) / cellSize; float nY = (worldPos.y() - (cellY * cellSize)) / cellSize; // get left / bottom points (rounded down) float factor = landSize - 1.0f; float invFactor = 1.0f / factor; int startX = static_cast<int>(nX * factor); int startY = static_cast<int>(nY * factor); int endX = startX + 1; int endY = startY + 1; endX = std::min(endX, landSize - 1); endY = std::min(endY, landSize - 1); // now get points in terrain space (effectively rounding them to boundaries) float startXTS = startX * invFactor; float startYTS = startY * invFactor; float endXTS = endX * invFactor; float endYTS = endY * invFactor; // get parametric from start coord to next point float xParam = (nX - startXTS) * factor; float yParam = (nY - startYTS) * factor; /* For even / odd tri strip rows, triangles are this shape: even odd 3---2 3---2 | / | | \ | 0---1 0---1 */ // Build all 4 positions in normalized cell space, using point-sampled height osg::Vec3f v0(startXTS, startYTS, getVertexHeight(data, startX, startY) / cellSize); osg::Vec3f v1(endXTS, startYTS, getVertexHeight(data, endX, startY) / cellSize); osg::Vec3f v2(endXTS, endYTS, getVertexHeight(data, endX, endY) / cellSize); osg::Vec3f v3(startXTS, endYTS, getVertexHeight(data, startX, endY) / cellSize); // define this plane in terrain space osg::Plane plane; // FIXME: deal with differing triangle alignment if (true) { // odd row bool secondTri = ((1.0 - yParam) > xParam); if (secondTri) plane = osg::Plane(v0, v1, v3); else plane = osg::Plane(v1, v2, v3); } /* else { // even row bool secondTri = (yParam > xParam); if (secondTri) plane.redefine(v0, v2, v3); else plane.redefine(v0, v1, v2); } */ // Solve plane equation for z return (-plane.getNormal().x() * nX - plane.getNormal().y() * nY - plane[3]) / plane.getNormal().z() * cellSize; } const LandObject* Storage::getLand(ESM::ExteriorCellLocation cellLocation, LandCache& cache) { if (const auto land = cache.find(cellLocation.mX, cellLocation.mY)) return *land; osg::ref_ptr<const LandObject> land = getLand(cellLocation); const LandObject* result = land.get(); cache.insert(cellLocation.mX, cellLocation.mY, std::move(land)); return result; } void Storage::adjustColor(int col, int row, const ESM::LandData* heightData, osg::Vec4ub& color) const {} float Storage::getAlteredHeight(int col, int row) const { return 0; } Terrain::LayerInfo Storage::getLayerInfo(const std::string& texture) { std::lock_guard<std::mutex> lock(mLayerInfoMutex); // Already have this cached? std::map<std::string, Terrain::LayerInfo>::iterator found = mLayerInfoMap.find(texture); if (found != mLayerInfoMap.end()) return found->second; Terrain::LayerInfo info; info.mParallax = false; info.mSpecular = false; info.mDiffuseMap = texture; if (mAutoUseNormalMaps) { std::string texture_ = texture; Misc::StringUtils::replaceLast(texture_, ".", mNormalHeightMapPattern + "."); if (mVFS->exists(texture_)) { info.mNormalMap = std::move(texture_); info.mParallax = true; } else { texture_ = texture; Misc::StringUtils::replaceLast(texture_, ".", mNormalMapPattern + "."); if (mVFS->exists(texture_)) info.mNormalMap = std::move(texture_); } } if (mAutoUseSpecularMaps) { std::string texture_ = texture; Misc::StringUtils::replaceLast(texture_, ".", mSpecularMapPattern + "."); if (mVFS->exists(texture_)) { info.mDiffuseMap = std::move(texture_); info.mSpecular = true; } } mLayerInfoMap[texture] = info; return info; } float Storage::getCellWorldSize(ESM::RefId worldspace) { return static_cast<float>(ESM::getCellSize(worldspace)); } int Storage::getCellVertices(ESM::RefId worldspace) { return ESM::getLandSize(worldspace); } int Storage::getBlendmapScale(float chunkSize) { return ESM::Land::LAND_TEXTURE_SIZE * chunkSize; } }
23,908
C++
.cpp
529
33.979206
120
0.566525
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,494
sdlcursormanager.cpp
OpenMW_openmw/components/sdlutil/sdlcursormanager.cpp
#include "sdlcursormanager.hpp" #include <stdexcept> #include <SDL_endian.h> #include <SDL_hints.h> #include <SDL_mouse.h> #include <SDL_render.h> #include <osg/Geometry> #include <osg/GraphicsContext> #include <osg/TexMat> #include <osg/Texture2D> #include <osg/Version> #include <osgViewer/GraphicsWindow> #include <components/debug/debuglog.hpp> #include "imagetosurface.hpp" #if defined(OSG_LIBRARY_STATIC) && (!defined(ANDROID) || OSG_VERSION_GREATER_THAN(3, 6, 5)) // Sets the default windowing system interface according to the OS. // Necessary for OpenSceneGraph to do some things, like decompression. USE_GRAPHICSWINDOW() #endif namespace SDLUtil { SDLCursorManager::SDLCursorManager() : mEnabled(false) , mInitialized(false) { } SDLCursorManager::~SDLCursorManager() { CursorMap::const_iterator curs_iter = mCursorMap.begin(); while (curs_iter != mCursorMap.end()) { SDL_FreeCursor(curs_iter->second); ++curs_iter; } mCursorMap.clear(); } void SDLCursorManager::setEnabled(bool enabled) { if (mInitialized && enabled == mEnabled) return; mInitialized = true; mEnabled = enabled; // turn on hardware cursors if (enabled) { _setGUICursor(mCurrentCursor); } // turn off hardware cursors else { SDL_ShowCursor(SDL_FALSE); } } void SDLCursorManager::cursorChanged(std::string_view name) { mCurrentCursor = name; _setGUICursor(mCurrentCursor); } void SDLCursorManager::_setGUICursor(std::string_view name) { auto it = mCursorMap.find(name); if (it != mCursorMap.end()) SDL_SetCursor(it->second); } void SDLCursorManager::createCursor(std::string_view name, int rotDegrees, osg::Image* image, Uint8 hotspot_x, Uint8 hotspot_y, int cursorWidth, int cursorHeight) { #ifndef ANDROID _createCursorFromResource(name, rotDegrees, image, hotspot_x, hotspot_y, cursorWidth, cursorHeight); #endif } SDLUtil::SurfaceUniquePtr decompress( osg::ref_ptr<osg::Image> source, float rotDegrees, int cursorWidth, int cursorHeight) { int width = source->s(); int height = source->t(); bool useAlpha = source->isImageTranslucent(); osg::ref_ptr<osg::Image> decompressedImage = new osg::Image; decompressedImage->setFileName(source->getFileName()); decompressedImage->allocateImage(width, height, 1, useAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE); for (int s = 0; s < width; ++s) for (int t = 0; t < height; ++t) decompressedImage->setColor(source->getColor(s, t, 0), s, t, 0); Uint32 redMask = 0x000000ff; Uint32 greenMask = 0x0000ff00; Uint32 blueMask = 0x00ff0000; Uint32 alphaMask = useAlpha ? 0xff000000 : 0; SDL_Surface* cursorSurface = SDL_CreateRGBSurfaceFrom(decompressedImage->data(), width, height, decompressedImage->getPixelSizeInBits(), decompressedImage->getRowSizeInBytes(), redMask, greenMask, blueMask, alphaMask); SDL_Surface* targetSurface = SDL_CreateRGBSurface(0, cursorWidth, cursorHeight, 32, redMask, greenMask, blueMask, alphaMask); SDL_Renderer* renderer = SDL_CreateSoftwareRenderer(targetSurface); SDL_RenderClear(renderer); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"); SDL_Texture* cursorTexture = SDL_CreateTextureFromSurface(renderer, cursorSurface); SDL_RenderCopyEx(renderer, cursorTexture, nullptr, nullptr, -rotDegrees, nullptr, SDL_FLIP_VERTICAL); SDL_DestroyTexture(cursorTexture); SDL_FreeSurface(cursorSurface); SDL_DestroyRenderer(renderer); return SDLUtil::SurfaceUniquePtr(targetSurface, SDL_FreeSurface); } void SDLCursorManager::_createCursorFromResource(std::string_view name, int rotDegrees, osg::Image* image, Uint8 hotspot_x, Uint8 hotspot_y, int cursorWidth, int cursorHeight) { if (mCursorMap.find(name) != mCursorMap.end()) return; try { auto surface = decompress(image, static_cast<float>(rotDegrees), cursorWidth, cursorHeight); // set the cursor and store it for later SDL_Cursor* curs = SDL_CreateColorCursor(surface.get(), hotspot_x, hotspot_y); mCursorMap.emplace(name, curs); } catch (std::exception& e) { Log(Debug::Warning) << e.what(); Log(Debug::Warning) << "Using default cursor."; return; } } }
4,747
C++
.cpp
122
31.352459
114
0.655781
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,495
sdlmappings.cpp
OpenMW_openmw/components/sdlutil/sdlmappings.cpp
#include "sdlmappings.hpp" #include <map> #include <MyGUI_MouseButton.h> #include <SDL_gamecontroller.h> #include <SDL_mouse.h> namespace SDLUtil { std::string sdlControllerButtonToString(int button) { switch (button) { case SDL_CONTROLLER_BUTTON_A: return "A Button"; case SDL_CONTROLLER_BUTTON_B: return "B Button"; case SDL_CONTROLLER_BUTTON_BACK: return "Back Button"; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: return "DPad Down"; case SDL_CONTROLLER_BUTTON_DPAD_LEFT: return "DPad Left"; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return "DPad Right"; case SDL_CONTROLLER_BUTTON_DPAD_UP: return "DPad Up"; case SDL_CONTROLLER_BUTTON_GUIDE: return "Guide Button"; case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: return "Left Shoulder"; case SDL_CONTROLLER_BUTTON_LEFTSTICK: return "Left Stick Button"; case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: return "Right Shoulder"; case SDL_CONTROLLER_BUTTON_RIGHTSTICK: return "Right Stick Button"; case SDL_CONTROLLER_BUTTON_START: return "Start Button"; case SDL_CONTROLLER_BUTTON_X: return "X Button"; case SDL_CONTROLLER_BUTTON_Y: return "Y Button"; default: return "Button " + std::to_string(button); } } std::string sdlControllerAxisToString(int axis) { switch (axis) { case SDL_CONTROLLER_AXIS_LEFTX: return "Left Stick X"; case SDL_CONTROLLER_AXIS_LEFTY: return "Left Stick Y"; case SDL_CONTROLLER_AXIS_RIGHTX: return "Right Stick X"; case SDL_CONTROLLER_AXIS_RIGHTY: return "Right Stick Y"; case SDL_CONTROLLER_AXIS_TRIGGERLEFT: return "Left Trigger"; case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: return "Right Trigger"; default: return "Axis " + std::to_string(axis); } } MyGUI::MouseButton sdlMouseButtonToMyGui(Uint8 button) { // The right button is the second button, according to MyGUI if (button == SDL_BUTTON_RIGHT) button = SDL_BUTTON_MIDDLE; else if (button == SDL_BUTTON_MIDDLE) button = SDL_BUTTON_RIGHT; // MyGUI's buttons are 0 indexed return MyGUI::MouseButton::Enum(button - 1); } Uint8 myGuiMouseButtonToSdl(MyGUI::MouseButton button) { Uint8 value = static_cast<Uint8>(button.getValue() + 1); if (value == SDL_BUTTON_RIGHT) value = SDL_BUTTON_MIDDLE; else if (value == SDL_BUTTON_MIDDLE) value = SDL_BUTTON_RIGHT; return value; } namespace { std::map<SDL_Keycode, MyGUI::KeyCode> initKeyMap() { std::map<SDL_Keycode, MyGUI::KeyCode> keyMap; keyMap[SDLK_UNKNOWN] = MyGUI::KeyCode::None; keyMap[SDLK_ESCAPE] = MyGUI::KeyCode::Escape; keyMap[SDLK_1] = MyGUI::KeyCode::One; keyMap[SDLK_2] = MyGUI::KeyCode::Two; keyMap[SDLK_3] = MyGUI::KeyCode::Three; keyMap[SDLK_4] = MyGUI::KeyCode::Four; keyMap[SDLK_5] = MyGUI::KeyCode::Five; keyMap[SDLK_6] = MyGUI::KeyCode::Six; keyMap[SDLK_7] = MyGUI::KeyCode::Seven; keyMap[SDLK_8] = MyGUI::KeyCode::Eight; keyMap[SDLK_9] = MyGUI::KeyCode::Nine; keyMap[SDLK_0] = MyGUI::KeyCode::Zero; keyMap[SDLK_MINUS] = MyGUI::KeyCode::Minus; keyMap[SDLK_EQUALS] = MyGUI::KeyCode::Equals; keyMap[SDLK_BACKSPACE] = MyGUI::KeyCode::Backspace; keyMap[SDLK_TAB] = MyGUI::KeyCode::Tab; keyMap[SDLK_q] = MyGUI::KeyCode::Q; keyMap[SDLK_w] = MyGUI::KeyCode::W; keyMap[SDLK_e] = MyGUI::KeyCode::E; keyMap[SDLK_r] = MyGUI::KeyCode::R; keyMap[SDLK_t] = MyGUI::KeyCode::T; keyMap[SDLK_y] = MyGUI::KeyCode::Y; keyMap[SDLK_u] = MyGUI::KeyCode::U; keyMap[SDLK_i] = MyGUI::KeyCode::I; keyMap[SDLK_o] = MyGUI::KeyCode::O; keyMap[SDLK_p] = MyGUI::KeyCode::P; keyMap[SDLK_RETURN] = MyGUI::KeyCode::Return; keyMap[SDLK_a] = MyGUI::KeyCode::A; keyMap[SDLK_s] = MyGUI::KeyCode::S; keyMap[SDLK_d] = MyGUI::KeyCode::D; keyMap[SDLK_f] = MyGUI::KeyCode::F; keyMap[SDLK_g] = MyGUI::KeyCode::G; keyMap[SDLK_h] = MyGUI::KeyCode::H; keyMap[SDLK_j] = MyGUI::KeyCode::J; keyMap[SDLK_k] = MyGUI::KeyCode::K; keyMap[SDLK_l] = MyGUI::KeyCode::L; keyMap[SDLK_SEMICOLON] = MyGUI::KeyCode::Semicolon; keyMap[SDLK_QUOTE] = MyGUI::KeyCode::Apostrophe; keyMap[SDLK_BACKQUOTE] = MyGUI::KeyCode::Grave; keyMap[SDLK_LSHIFT] = MyGUI::KeyCode::LeftShift; keyMap[SDLK_BACKSLASH] = MyGUI::KeyCode::Backslash; keyMap[SDLK_z] = MyGUI::KeyCode::Z; keyMap[SDLK_x] = MyGUI::KeyCode::X; keyMap[SDLK_c] = MyGUI::KeyCode::C; keyMap[SDLK_v] = MyGUI::KeyCode::V; keyMap[SDLK_b] = MyGUI::KeyCode::B; keyMap[SDLK_n] = MyGUI::KeyCode::N; keyMap[SDLK_m] = MyGUI::KeyCode::M; keyMap[SDLK_COMMA] = MyGUI::KeyCode::Comma; keyMap[SDLK_PERIOD] = MyGUI::KeyCode::Period; keyMap[SDLK_SLASH] = MyGUI::KeyCode::Slash; keyMap[SDLK_RSHIFT] = MyGUI::KeyCode::RightShift; keyMap[SDLK_KP_MULTIPLY] = MyGUI::KeyCode::Multiply; keyMap[SDLK_LALT] = MyGUI::KeyCode::LeftAlt; keyMap[SDLK_SPACE] = MyGUI::KeyCode::Space; keyMap[SDLK_CAPSLOCK] = MyGUI::KeyCode::Capital; keyMap[SDLK_F1] = MyGUI::KeyCode::F1; keyMap[SDLK_F2] = MyGUI::KeyCode::F2; keyMap[SDLK_F3] = MyGUI::KeyCode::F3; keyMap[SDLK_F4] = MyGUI::KeyCode::F4; keyMap[SDLK_F5] = MyGUI::KeyCode::F5; keyMap[SDLK_F6] = MyGUI::KeyCode::F6; keyMap[SDLK_F7] = MyGUI::KeyCode::F7; keyMap[SDLK_F8] = MyGUI::KeyCode::F8; keyMap[SDLK_F9] = MyGUI::KeyCode::F9; keyMap[SDLK_F10] = MyGUI::KeyCode::F10; keyMap[SDLK_NUMLOCKCLEAR] = MyGUI::KeyCode::NumLock; keyMap[SDLK_SCROLLLOCK] = MyGUI::KeyCode::ScrollLock; keyMap[SDLK_KP_7] = MyGUI::KeyCode::Numpad7; keyMap[SDLK_KP_8] = MyGUI::KeyCode::Numpad8; keyMap[SDLK_KP_9] = MyGUI::KeyCode::Numpad9; keyMap[SDLK_KP_MINUS] = MyGUI::KeyCode::Subtract; keyMap[SDLK_KP_4] = MyGUI::KeyCode::Numpad4; keyMap[SDLK_KP_5] = MyGUI::KeyCode::Numpad5; keyMap[SDLK_KP_6] = MyGUI::KeyCode::Numpad6; keyMap[SDLK_KP_PLUS] = MyGUI::KeyCode::Add; keyMap[SDLK_KP_1] = MyGUI::KeyCode::Numpad1; keyMap[SDLK_KP_2] = MyGUI::KeyCode::Numpad2; keyMap[SDLK_KP_3] = MyGUI::KeyCode::Numpad3; keyMap[SDLK_KP_0] = MyGUI::KeyCode::Numpad0; keyMap[SDLK_KP_PERIOD] = MyGUI::KeyCode::Decimal; keyMap[SDLK_F11] = MyGUI::KeyCode::F11; keyMap[SDLK_F12] = MyGUI::KeyCode::F12; keyMap[SDLK_F13] = MyGUI::KeyCode::F13; keyMap[SDLK_F14] = MyGUI::KeyCode::F14; keyMap[SDLK_F15] = MyGUI::KeyCode::F15; keyMap[SDLK_KP_EQUALS] = MyGUI::KeyCode::NumpadEquals; keyMap[SDLK_COLON] = MyGUI::KeyCode::Colon; keyMap[SDLK_KP_ENTER] = MyGUI::KeyCode::NumpadEnter; keyMap[SDLK_KP_DIVIDE] = MyGUI::KeyCode::Divide; keyMap[SDLK_SYSREQ] = MyGUI::KeyCode::SysRq; keyMap[SDLK_RALT] = MyGUI::KeyCode::RightAlt; keyMap[SDLK_HOME] = MyGUI::KeyCode::Home; keyMap[SDLK_UP] = MyGUI::KeyCode::ArrowUp; keyMap[SDLK_PAGEUP] = MyGUI::KeyCode::PageUp; keyMap[SDLK_LEFT] = MyGUI::KeyCode::ArrowLeft; keyMap[SDLK_RIGHT] = MyGUI::KeyCode::ArrowRight; keyMap[SDLK_END] = MyGUI::KeyCode::End; keyMap[SDLK_DOWN] = MyGUI::KeyCode::ArrowDown; keyMap[SDLK_PAGEDOWN] = MyGUI::KeyCode::PageDown; keyMap[SDLK_INSERT] = MyGUI::KeyCode::Insert; keyMap[SDLK_DELETE] = MyGUI::KeyCode::Delete; keyMap[SDLK_APPLICATION] = MyGUI::KeyCode::AppMenu; keyMap[SDLK_LGUI] = MyGUI::KeyCode::LeftWindows; keyMap[SDLK_RGUI] = MyGUI::KeyCode::RightWindows; keyMap[SDLK_LCTRL] = MyGUI::KeyCode::LeftControl; keyMap[SDLK_RCTRL] = MyGUI::KeyCode::RightControl; return keyMap; } std::map<MyGUI::KeyCode, SDL_Keycode> reverseKeyMap(const std::map<SDL_Keycode, MyGUI::KeyCode>& map) { std::map<MyGUI::KeyCode, SDL_Keycode> result; for (auto& [sdl, mygui] : map) result[mygui] = sdl; return result; } } MyGUI::KeyCode sdlKeyToMyGUI(SDL_Keycode code) { static std::map<SDL_Keycode, MyGUI::KeyCode> keyMap = initKeyMap(); MyGUI::KeyCode kc = MyGUI::KeyCode::None; auto foundKey = keyMap.find(code); if (foundKey != keyMap.end()) kc = foundKey->second; return kc; } SDL_Keycode myGuiKeyToSdl(MyGUI::KeyCode button) { static auto keyMap = reverseKeyMap(initKeyMap()); SDL_Keycode kc = 0; auto foundKey = keyMap.find(button); if (foundKey != keyMap.end()) kc = foundKey->second; return kc; } }
9,989
C++
.cpp
225
32.622222
109
0.565654
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,496
sdlvideowrapper.cpp
OpenMW_openmw/components/sdlutil/sdlvideowrapper.cpp
#include "sdlvideowrapper.hpp" #include <components/debug/debuglog.hpp> #include <components/sdlutil/sdlgraphicswindow.hpp> #include <components/settings/settings.hpp> #include <osgViewer/Viewer> #include <SDL_video.h> namespace SDLUtil { VideoWrapper::VideoWrapper(SDL_Window* window, osg::ref_ptr<osgViewer::Viewer> viewer) : mWindow(window) , mViewer(std::move(viewer)) , mGamma(1.f) , mContrast(1.f) , mHasSetGammaContrast(false) { SDL_GetWindowGammaRamp(mWindow, mOldSystemGammaRamp, &mOldSystemGammaRamp[256], &mOldSystemGammaRamp[512]); } VideoWrapper::~VideoWrapper() { SDL_SetWindowFullscreen(mWindow, 0); // If user hasn't touched the defaults no need to restore if (mHasSetGammaContrast) SDL_SetWindowGammaRamp(mWindow, mOldSystemGammaRamp, &mOldSystemGammaRamp[256], &mOldSystemGammaRamp[512]); } void VideoWrapper::setSyncToVBlank(VSyncMode vsyncMode) { osgViewer::Viewer::Windows windows; mViewer->getWindows(windows); mViewer->stopThreading(); for (osgViewer::Viewer::Windows::iterator it = windows.begin(); it != windows.end(); ++it) { osgViewer::GraphicsWindow* win = *it; if (GraphicsWindowSDL2* sdl2win = dynamic_cast<GraphicsWindowSDL2*>(win)) sdl2win->setSyncToVBlank(vsyncMode); else win->setSyncToVBlank(vsyncMode != VSyncMode::Disabled); } mViewer->startThreading(); } void VideoWrapper::setGammaContrast(float gamma, float contrast) { if (gamma == mGamma && contrast == mContrast) return; mGamma = gamma; mContrast = contrast; mHasSetGammaContrast = true; Uint16 red[256], green[256], blue[256]; for (int i = 0; i < 256; i++) { float k = i / 256.0f; k = (k - 0.5f) * contrast + 0.5f; k = pow(k, 1.f / gamma); k *= 256; float value = k * 256; if (value > 65535) value = 65535; else if (value < 0) value = 0; red[i] = green[i] = blue[i] = static_cast<Uint16>(value); } if (SDL_SetWindowGammaRamp(mWindow, red, green, blue) < 0) Log(Debug::Warning) << "Couldn't set gamma: " << SDL_GetError(); } void VideoWrapper::setVideoMode(int width, int height, Settings::WindowMode windowMode, bool windowBorder) { SDL_SetWindowFullscreen(mWindow, 0); if (SDL_GetWindowFlags(mWindow) & SDL_WINDOW_MAXIMIZED) SDL_RestoreWindow(mWindow); int w, h; SDL_GetWindowSize(mWindow, &w, &h); int dw, dh; SDL_GL_GetDrawableSize(mWindow, &dw, &dh); if (windowMode == Settings::WindowMode::Fullscreen || windowMode == Settings::WindowMode::WindowedFullscreen) { SDL_DisplayMode mode; SDL_GetWindowDisplayMode(mWindow, &mode); mode.w = width / (dw / w); mode.h = height / (dh / h); SDL_SetWindowDisplayMode(mWindow, &mode); SDL_SetWindowFullscreen(mWindow, windowMode == Settings::WindowMode::Fullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_FULLSCREEN_DESKTOP); } else { SDL_SetWindowSize(mWindow, width / (dw / w), height / (dh / h)); SDL_SetWindowBordered(mWindow, windowBorder ? SDL_TRUE : SDL_FALSE); centerWindow(); } } void VideoWrapper::centerWindow() { // Resize breaks the sdl window in some cases; see issue: #5539 SDL_Rect rect{}; int x = 0; int y = 0; int w = 0; int h = 0; auto index = SDL_GetWindowDisplayIndex(mWindow); SDL_GetDisplayBounds(index, &rect); SDL_GetWindowSize(mWindow, &w, &h); x = rect.x; y = rect.y; // Center dimensions that do not fill the screen if (w < rect.w) { x = rect.x + rect.w / 2 - w / 2; } if (h < rect.h) { y = rect.y + rect.h / 2 - h / 2; } SDL_SetWindowPosition(mWindow, x, y); } }
4,261
C++
.cpp
114
28.175439
120
0.583899
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,497
imagetosurface.cpp
OpenMW_openmw/components/sdlutil/imagetosurface.cpp
#include "imagetosurface.hpp" #include <SDL_surface.h> #include <osg/Image> namespace SDLUtil { SurfaceUniquePtr imageToSurface(osg::Image* image, bool flip) { int width = image->s(); int height = image->t(); SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); for (int x = 0; x < width; ++x) for (int y = 0; y < height; ++y) { osg::Vec4f clr = image->getColor(x, flip ? ((height - 1) - y) : y); int bpp = surface->format->BytesPerPixel; Uint8* p = (Uint8*)surface->pixels + y * surface->pitch + x * bpp; *(Uint32*)(p) = SDL_MapRGBA(surface->format, static_cast<Uint8>(clr.r() * 255), static_cast<Uint8>(clr.g() * 255), static_cast<Uint8>(clr.b() * 255), static_cast<Uint8>(clr.a() * 255)); } return SurfaceUniquePtr(surface, SDL_FreeSurface); } }
1,025
C++
.cpp
24
32.791667
120
0.548744
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,498
sdlgraphicswindow.cpp
OpenMW_openmw/components/sdlutil/sdlgraphicswindow.cpp
#include "sdlgraphicswindow.hpp" #include <SDL_video.h> #ifdef OPENMW_GL4ES_MANUAL_INIT #include "gl4es_init.h" #endif namespace SDLUtil { GraphicsWindowSDL2::~GraphicsWindowSDL2() { close(true); } GraphicsWindowSDL2::GraphicsWindowSDL2(osg::GraphicsContext::Traits* traits, VSyncMode vsyncMode) : mWindow(nullptr) , mContext(nullptr) , mValid(false) , mRealized(false) , mOwnsWindow(false) , mVSyncMode(vsyncMode) { _traits = traits; init(); if (GraphicsWindowSDL2::valid()) { setState(new osg::State); getState()->setGraphicsContext(this); if (_traits.valid() && _traits->sharedContext.valid()) { getState()->setContextID(_traits->sharedContext->getState()->getContextID()); incrementContextIDUsageCount(getState()->getContextID()); } else { getState()->setContextID(osg::GraphicsContext::createNewContextID()); } } } bool GraphicsWindowSDL2::setWindowDecorationImplementation(bool flag) { if (!mWindow) return false; SDL_SetWindowBordered(mWindow, flag ? SDL_TRUE : SDL_FALSE); return true; } bool GraphicsWindowSDL2::setWindowRectangleImplementation(int x, int y, int width, int height) { if (!mWindow) return false; int w, h; SDL_GetWindowSize(mWindow, &w, &h); int dw, dh; SDL_GL_GetDrawableSize(mWindow, &dw, &dh); SDL_SetWindowPosition(mWindow, x, y); SDL_SetWindowSize(mWindow, width / (dw / w), height / (dh / h)); return true; } void GraphicsWindowSDL2::setWindowName(const std::string& name) { if (!mWindow) return; SDL_SetWindowTitle(mWindow, name.c_str()); _traits->windowName = name; } void GraphicsWindowSDL2::setCursor(MouseCursor mouseCursor) { _traits->useCursor = false; } void GraphicsWindowSDL2::init() { if (mValid) return; if (!_traits.valid()) return; WindowData* inheritedWindowData = dynamic_cast<WindowData*>(_traits->inheritedWindowData.get()); mWindow = inheritedWindowData ? inheritedWindowData->mWindow : nullptr; mOwnsWindow = (mWindow == nullptr); if (mOwnsWindow) { OSG_FATAL << "Error: No SDL window provided." << std::endl; return; } // SDL will change the current context when it creates a new one, so we // have to get the current one to be able to restore it afterward. SDL_Window* oldWin = SDL_GL_GetCurrentWindow(); SDL_GLContext oldCtx = SDL_GL_GetCurrentContext(); #if defined(ANDROID) || defined(OPENMW_GL4ES_MANUAL_INIT) int major = 1; int minor = 1; char* ver = getenv("OPENMW_GLES_VERSION"); if (ver && strcmp(ver, "2") == 0) { major = 2; minor = 0; } else if (ver && strcmp(ver, "3") == 0) { major = 3; minor = 2; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor); #endif mContext = SDL_GL_CreateContext(mWindow); if (!mContext) { OSG_FATAL << "Error: Unable to create OpenGL graphics context: " << SDL_GetError() << std::endl; return; } #ifdef OPENMW_GL4ES_MANUAL_INIT openmw_gl4es_init(mWindow); #endif setSwapInterval(mVSyncMode); // Update traits with what we've actually been given // Use intermediate to avoid signed/unsigned mismatch int intermediateLocation; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &intermediateLocation); _traits->red = intermediateLocation; SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &intermediateLocation); _traits->green = intermediateLocation; SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &intermediateLocation); _traits->blue = intermediateLocation; SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &intermediateLocation); _traits->alpha = intermediateLocation; SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &intermediateLocation); _traits->depth = intermediateLocation; SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &intermediateLocation); _traits->stencil = intermediateLocation; SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &intermediateLocation); _traits->doubleBuffer = intermediateLocation; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &intermediateLocation); _traits->sampleBuffers = intermediateLocation; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &intermediateLocation); _traits->samples = intermediateLocation; SDL_GL_MakeCurrent(oldWin, oldCtx); mValid = true; getEventQueue()->syncWindowRectangleWithGraphicsContext(); } bool GraphicsWindowSDL2::realizeImplementation() { if (mRealized) { OSG_NOTICE << "GraphicsWindowSDL2::realizeImplementation() Already realized" << std::endl; return true; } if (!mValid) init(); if (!mValid) return false; SDL_ShowWindow(mWindow); getEventQueue()->syncWindowRectangleWithGraphicsContext(); mRealized = true; return true; } bool GraphicsWindowSDL2::makeCurrentImplementation() { if (!mRealized) { OSG_WARN << "Warning: GraphicsWindow not realized, cannot do makeCurrent." << std::endl; return false; } return SDL_GL_MakeCurrent(mWindow, mContext) == 0; } bool GraphicsWindowSDL2::releaseContextImplementation() { if (!mRealized) { OSG_WARN << "Warning: GraphicsWindow not realized, cannot do releaseContext." << std::endl; return false; } return SDL_GL_MakeCurrent(nullptr, nullptr) == 0; } void GraphicsWindowSDL2::closeImplementation() { if (mContext) SDL_GL_DeleteContext(mContext); mContext = nullptr; if (mWindow && mOwnsWindow) SDL_DestroyWindow(mWindow); mWindow = nullptr; mValid = false; mRealized = false; } void GraphicsWindowSDL2::swapBuffersImplementation() { if (!mRealized) return; SDL_GL_SwapWindow(mWindow); } void GraphicsWindowSDL2::setSyncToVBlank(bool on) { throw std::runtime_error( "setSyncToVBlank with bool argument is not supported. Use the VSyncMode argument instead."); } void GraphicsWindowSDL2::setSyncToVBlank(VSyncMode mode) { SDL_Window* oldWin = SDL_GL_GetCurrentWindow(); SDL_GLContext oldCtx = SDL_GL_GetCurrentContext(); SDL_GL_MakeCurrent(mWindow, mContext); setSwapInterval(mode); SDL_GL_MakeCurrent(oldWin, oldCtx); } void GraphicsWindowSDL2::setSwapInterval(VSyncMode mode) { mVSyncMode = mode; if (mode == VSyncMode::Adaptive) { if (SDL_GL_SetSwapInterval(-1) == -1) { OSG_NOTICE << "Adaptive vsync unsupported" << std::endl; setSwapInterval(VSyncMode::Enabled); } } else if (mode == VSyncMode::Enabled) { if (SDL_GL_SetSwapInterval(1) == -1) { OSG_NOTICE << "Vertical synchronization unsupported, disabling" << std::endl; setSwapInterval(VSyncMode::Disabled); } } else { SDL_GL_SetSwapInterval(0); } } void GraphicsWindowSDL2::raiseWindow() { SDL_RaiseWindow(mWindow); } }
8,077
C++
.cpp
230
26.191304
108
0.608573
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,499
gl4es_init.cpp
OpenMW_openmw/components/sdlutil/gl4es_init.cpp
// EGL does not work reliably for feature detection. // Instead, we initialize gl4es manually. #ifdef OPENMW_GL4ES_MANUAL_INIT #include "gl4es_init.h" // For glHint #include <GL/gl.h> extern "C" { #include <gl4es/gl4eshint.h> #include <gl4es/gl4esinit.h> static SDL_Window* gWindow; void openmw_gl4es_GetMainFBSize(int* width, int* height) { SDL_GetWindowSize(gWindow, width, height); } void openmw_gl4es_init(SDL_Window* window) { gWindow = window; set_getprocaddress(SDL_GL_GetProcAddress); set_getmainfbsize(openmw_gl4es_GetMainFBSize); initialize_gl4es(); // merge glBegin/glEnd in beams and console glHint(GL_BEGINEND_HINT_GL4ES, 1); // dxt unpacked to 16-bit looks ugly glHint(GL_AVOID16BITS_HINT_GL4ES, 1); } } // extern "C" #endif // OPENMW_GL4ES_MANUAL_INIT
876
C++
.cpp
28
26.392857
60
0.686532
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,500
sdlinputwrapper.cpp
OpenMW_openmw/components/sdlutil/sdlinputwrapper.cpp
#include "sdlinputwrapper.hpp" #include <components/debug/debuglog.hpp> #include <components/settings/values.hpp> #include <osgViewer/Viewer> namespace SDLUtil { InputWrapper::InputWrapper(SDL_Window* window, osg::ref_ptr<osgViewer::Viewer> viewer, bool grab) : mSDLWindow(window) , mViewer(std::move(viewer)) , mMouseListener(nullptr) , mSensorListener(nullptr) , mKeyboardListener(nullptr) , mWindowListener(nullptr) , mConListener(nullptr) , mWarpX(0) , mWarpY(0) , mWarpCompensate(false) , mWrapPointer(false) , mAllowGrab(grab) , mWantMouseVisible(false) , mWantGrab(false) , mWantRelative(false) , mGrabPointer(false) , mMouseRelative(false) , mFirstMouseMove(true) , mMouseZ(0) , mMouseX(0) , mMouseY(0) , mWindowHasFocus(true) , mMouseInWindow(true) { Uint32 flags = SDL_GetWindowFlags(mSDLWindow); mWindowHasFocus = (flags & SDL_WINDOW_INPUT_FOCUS); mMouseInWindow = (flags & SDL_WINDOW_MOUSE_FOCUS); _setWindowScale(); } InputWrapper::~InputWrapper() {} void InputWrapper::_setWindowScale() { int w, h; SDL_GetWindowSize(mSDLWindow, &w, &h); int dw, dh; SDL_GL_GetDrawableSize(mSDLWindow, &dw, &dh); mScaleX = dw / w; mScaleY = dh / h; } void InputWrapper::capture(bool windowEventsOnly) { mViewer->getEventQueue()->frame(0.f); SDL_PumpEvents(); SDL_Event evt; if (windowEventsOnly) { // During loading, handle window events, discard button presses and mouse movement and keep others for later while (SDL_PeepEvents(&evt, 1, SDL_GETEVENT, SDL_WINDOWEVENT, SDL_WINDOWEVENT) > 0) handleWindowEvent(evt); SDL_FlushEvent(SDL_KEYDOWN); SDL_FlushEvent(SDL_CONTROLLERBUTTONDOWN); SDL_FlushEvent(SDL_MOUSEBUTTONDOWN); SDL_FlushEvent(SDL_MOUSEMOTION); SDL_FlushEvent(SDL_MOUSEWHEEL); return; } while (SDL_PollEvent(&evt)) { switch (evt.type) { case SDL_MOUSEMOTION: // Ignore this if it happened due to a warp if (!_handleWarpMotion(evt.motion)) { // If in relative mode, don't trigger events unless window has focus if (!mWantRelative || mWindowHasFocus) mMouseListener->mouseMoved(_packageMouseMotion(evt)); // Try to keep the mouse inside the window if (mWindowHasFocus) _wrapMousePointer(evt.motion); } break; case SDL_MOUSEWHEEL: mMouseListener->mouseMoved(_packageMouseMotion(evt)); mMouseListener->mouseWheelMoved(evt.wheel); break; case SDL_SENSORUPDATE: mSensorListener->sensorUpdated(evt.sensor); break; case SDL_MOUSEBUTTONDOWN: mMouseListener->mousePressed(evt.button, evt.button.button); break; case SDL_MOUSEBUTTONUP: mMouseListener->mouseReleased(evt.button, evt.button.button); break; case SDL_KEYDOWN: mKeyboardListener->keyPressed(evt.key); if (!isModifierHeld(KMOD_ALT) && evt.key.keysym.sym >= SDLK_F1 && evt.key.keysym.sym <= SDLK_F12) { mViewer->getEventQueue()->keyPress( osgGA::GUIEventAdapter::KEY_F1 + (evt.key.keysym.sym - SDLK_F1)); } break; case SDL_KEYUP: if (!evt.key.repeat) { mKeyboardListener->keyReleased(evt.key); if (!isModifierHeld(KMOD_ALT) && evt.key.keysym.sym >= SDLK_F1 && evt.key.keysym.sym <= SDLK_F12) mViewer->getEventQueue()->keyRelease( osgGA::GUIEventAdapter::KEY_F1 + (evt.key.keysym.sym - SDLK_F1)); } break; case SDL_TEXTEDITING: break; case SDL_TEXTINPUT: mKeyboardListener->textInput(evt.text); break; case SDL_KEYMAPCHANGED: break; case SDL_JOYHATMOTION: // As we manage everything with GameController, don't even bother with these. case SDL_JOYAXISMOTION: case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED: break; case SDL_CONTROLLERDEVICEADDED: if (mConListener) mConListener->controllerAdded( 1, evt.cdevice); // We only support one joystick, so give everything a generic deviceID break; case SDL_CONTROLLERDEVICEREMOVED: if (mConListener) mConListener->controllerRemoved(evt.cdevice); break; case SDL_CONTROLLERBUTTONDOWN: if (mConListener) mConListener->buttonPressed(1, evt.cbutton); break; case SDL_CONTROLLERBUTTONUP: if (mConListener) mConListener->buttonReleased(1, evt.cbutton); break; case SDL_CONTROLLERAXISMOTION: if (mConListener) mConListener->axisMoved(1, evt.caxis); break; #if SDL_VERSION_ATLEAST(2, 0, 14) case SDL_CONTROLLERSENSORUPDATE: // controller sensor data is received on demand break; case SDL_CONTROLLERTOUCHPADDOWN: mConListener->touchpadPressed(1, TouchEvent(evt.ctouchpad)); break; case SDL_CONTROLLERTOUCHPADMOTION: mConListener->touchpadMoved(1, TouchEvent(evt.ctouchpad)); break; case SDL_CONTROLLERTOUCHPADUP: mConListener->touchpadReleased(1, TouchEvent(evt.ctouchpad)); break; #endif case SDL_WINDOWEVENT: handleWindowEvent(evt); break; case SDL_QUIT: if (mWindowListener) mWindowListener->windowClosed(); break; case SDL_DISPLAYEVENT: switch (evt.display.event) { case SDL_DISPLAYEVENT_ORIENTATION: if (mSensorListener && evt.display.display == static_cast<Uint32>(Settings::video().mScreen)) { mSensorListener->displayOrientationChanged(); } break; default: break; } break; case SDL_CLIPBOARDUPDATE: break; // We don't need this event, clipboard is retrieved on demand case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: case SDL_DOLLARGESTURE: case SDL_DOLLARRECORD: case SDL_MULTIGESTURE: // No use for touch & gesture events break; case SDL_APP_WILLENTERBACKGROUND: case SDL_APP_WILLENTERFOREGROUND: case SDL_APP_DIDENTERBACKGROUND: case SDL_APP_DIDENTERFOREGROUND: // We do not need background/foreground switch event for mobile devices so far break; case SDL_APP_TERMINATING: // There is nothing we can do here. break; case SDL_APP_LOWMEMORY: Log(Debug::Warning) << "System reports that free RAM on device is running low. You may encounter " "an unexpected behaviour."; break; default: Log(Debug::Info) << "Unhandled SDL event of type 0x" << std::hex << evt.type; break; } } } void InputWrapper::handleWindowEvent(const SDL_Event& evt) { switch (evt.window.event) { case SDL_WINDOWEVENT_ENTER: mMouseInWindow = true; updateMouseSettings(); break; case SDL_WINDOWEVENT_LEAVE: mMouseInWindow = false; updateMouseSettings(); break; case SDL_WINDOWEVENT_MOVED: // I'm not sure what OSG is using the window position for, but I don't think it's needed, // so we ignore window moved events (improves window movement performance) break; case SDL_WINDOWEVENT_SIZE_CHANGED: int w, h; SDL_GL_GetDrawableSize(mSDLWindow, &w, &h); int x, y; SDL_GetWindowPosition(mSDLWindow, &x, &y); // Happens when you Alt-Tab out of game if (w == 0 && h == 0) return; mViewer->getCamera()->getGraphicsContext()->resized(x, y, w, h); mViewer->getEventQueue()->windowResize(x, y, w, h); if (mWindowListener) mWindowListener->windowResized(w, h); _setWindowScale(); break; case SDL_WINDOWEVENT_RESIZED: // This should also fire SIZE_CHANGED, so no need to handle break; case SDL_WINDOWEVENT_FOCUS_GAINED: mWindowHasFocus = true; updateMouseSettings(); break; case SDL_WINDOWEVENT_FOCUS_LOST: mWindowHasFocus = false; updateMouseSettings(); break; case SDL_WINDOWEVENT_CLOSE: break; case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_RESTORED: if (mWindowListener) mWindowListener->windowVisibilityChange(true); break; case SDL_WINDOWEVENT_HIDDEN: case SDL_WINDOWEVENT_MINIMIZED: if (mWindowListener) mWindowListener->windowVisibilityChange(false); break; } } bool InputWrapper::isModifierHeld(int mod) { return (SDL_GetModState() & mod) != 0; } bool InputWrapper::isKeyDown(SDL_Scancode key) { return (SDL_GetKeyboardState(nullptr)[key]) != 0; } /// \brief Moves the mouse to the specified point within the viewport void InputWrapper::warpMouse(int x, int y) { SDL_WarpMouseInWindow(mSDLWindow, x, y); mWarpCompensate = true; mWarpX = x; mWarpY = y; } /// \brief Locks the pointer to the window void InputWrapper::setGrabPointer(bool grab) { mWantGrab = grab; updateMouseSettings(); } /// \brief Set the mouse to relative positioning. Doesn't move the cursor /// and disables mouse acceleration. void InputWrapper::setMouseRelative(bool relative) { mWantRelative = relative; updateMouseSettings(); } void InputWrapper::setMouseVisible(bool visible) { mWantMouseVisible = visible; updateMouseSettings(); } void InputWrapper::updateMouseSettings() { mGrabPointer = mWantGrab && mMouseInWindow && mWindowHasFocus; SDL_SetWindowGrab(mSDLWindow, mGrabPointer && mAllowGrab ? SDL_TRUE : SDL_FALSE); SDL_ShowCursor(mWantMouseVisible || !mWindowHasFocus); bool relative = mWantRelative && mMouseInWindow && mWindowHasFocus; if (mMouseRelative == relative) return; mMouseRelative = relative; mWrapPointer = false; // eep, wrap the pointer manually if the input driver doesn't support // relative positioning natively // also use wrapping if no-grab was specified in options (SDL_SetRelativeMouseMode // appears to eat the mouse cursor when pausing in a debugger) bool success = mAllowGrab && SDL_SetRelativeMouseMode(relative ? SDL_TRUE : SDL_FALSE) == 0; if (relative && !success) mWrapPointer = true; // now remove all mouse events using the old setting from the queue SDL_PumpEvents(); SDL_FlushEvent(SDL_MOUSEMOTION); } /// \brief Internal method for ignoring relative motions as a side effect /// of warpMouse() bool InputWrapper::_handleWarpMotion(const SDL_MouseMotionEvent& evt) { if (!mWarpCompensate) return false; // this was a warp event, signal the caller to eat it. if (evt.x == mWarpX && evt.y == mWarpY) { mWarpCompensate = false; return true; } return false; } /// \brief Wrap the mouse to the viewport void InputWrapper::_wrapMousePointer(const SDL_MouseMotionEvent& evt) { // don't wrap if we don't want relative movements, support relative // movements natively, or aren't grabbing anyways if (!mMouseRelative || !mWrapPointer || !mGrabPointer) return; int width = 0; int height = 0; SDL_GetWindowSize(mSDLWindow, &width, &height); const int FUDGE_FACTOR_X = width / 4; const int FUDGE_FACTOR_Y = height / 4; // warp the mouse if it's about to go outside the window if (evt.x - FUDGE_FACTOR_X < 0 || evt.x + FUDGE_FACTOR_X > width || evt.y - FUDGE_FACTOR_Y < 0 || evt.y + FUDGE_FACTOR_Y > height) { warpMouse(width / 2, height / 2); } } /// \brief Package mouse and mousewheel motions into a single event MouseMotionEvent InputWrapper::_packageMouseMotion(const SDL_Event& evt) { MouseMotionEvent pack_evt = {}; pack_evt.x = mMouseX * mScaleX; pack_evt.y = mMouseY * mScaleY; pack_evt.z = mMouseZ; if (evt.type == SDL_MOUSEMOTION) { pack_evt.x = mMouseX = evt.motion.x * mScaleX; pack_evt.y = mMouseY = evt.motion.y * mScaleY; pack_evt.xrel = evt.motion.xrel * mScaleX; pack_evt.yrel = evt.motion.yrel * mScaleY; pack_evt.type = SDL_MOUSEMOTION; if (mFirstMouseMove) { // first event should be treated as non-relative, since there's no point of reference // SDL then (incorrectly) uses (0,0) as point of reference, on Linux at least... pack_evt.xrel = pack_evt.yrel = 0; mFirstMouseMove = false; } } else if (evt.type == SDL_MOUSEWHEEL) { mMouseZ += pack_evt.zrel = (evt.wheel.y * 120); pack_evt.z = mMouseZ; pack_evt.type = SDL_MOUSEWHEEL; } else { throw std::runtime_error("Tried to package non-motion event!"); } return pack_evt; } }
15,974
C++
.cpp
387
27.142119
120
0.53332
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,502
ba2dx10file.cpp
OpenMW_openmw/components/bsa/ba2dx10file.cpp
#include "ba2dx10file.hpp" #include <cassert> #include <filesystem> #include <fstream> #include <lz4frame.h> #if defined(_MSC_VER) // why is this necessary? These are included with /external:I #pragma warning(push) #pragma warning(disable : 4706) #pragma warning(disable : 4702) #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filtering_streambuf.hpp> #pragma warning(pop) #else #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filtering_streambuf.hpp> #endif #include <boost/iostreams/device/array.hpp> #include <components/bsa/ba2file.hpp> #include <components/bsa/memorystream.hpp> #include <components/esm/fourcc.hpp> #include <components/files/constrainedfilestream.hpp> #include <components/files/conversion.hpp> #include <components/misc/strings/lower.hpp> namespace Bsa { BA2DX10File::BA2DX10File() {} BA2DX10File::~BA2DX10File() = default; void BA2DX10File::loadFiles(uint32_t fileCount, std::istream& in) { mFiles.clear(); mFiles.reserve(fileCount); for (uint32_t i = 0; i < fileCount; ++i) { uint32_t nameHash, extHash, dirHash; in.read(reinterpret_cast<char*>(&nameHash), sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&extHash), sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&dirHash), sizeof(uint32_t)); FileRecord file; uint8_t unknown; in.read(reinterpret_cast<char*>(&unknown), sizeof(uint8_t)); uint8_t nbChunks; in.read(reinterpret_cast<char*>(&nbChunks), sizeof(uint8_t)); file.texturesChunks.resize(nbChunks); uint16_t chunkHeaderSize; in.read(reinterpret_cast<char*>(&chunkHeaderSize), sizeof(uint16_t)); if (chunkHeaderSize != 24) fail("Corrupted BSA"); in.read(reinterpret_cast<char*>(&file.height), sizeof(uint16_t)); in.read(reinterpret_cast<char*>(&file.width), sizeof(uint16_t)); in.read(reinterpret_cast<char*>(&file.numMips), sizeof(uint8_t)); in.read(reinterpret_cast<char*>(&file.DXGIFormat), sizeof(uint8_t)); in.read(reinterpret_cast<char*>(&file.cubeMaps), sizeof(uint16_t)); for (auto& texture : file.texturesChunks) { in.read(reinterpret_cast<char*>(&texture.offset), sizeof(int64_t)); in.read(reinterpret_cast<char*>(&texture.packedSize), sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&texture.size), sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&texture.startMip), sizeof(uint16_t)); in.read(reinterpret_cast<char*>(&texture.endMip), sizeof(uint16_t)); uint32_t baadfood; in.read(reinterpret_cast<char*>(&baadfood), sizeof(uint32_t)); if (baadfood != 0xBAADF00D) fail("Corrupted BSA"); } mFolders[dirHash][{ nameHash, extHash }] = std::move(file); FileStruct fileStruct{}; mFiles.push_back(fileStruct); } } /// Read header information from the input source void BA2DX10File::readHeader() { assert(!mIsLoaded); std::ifstream input(mFilepath, std::ios_base::binary); // Total archive size std::streamoff fsize = 0; if (input.seekg(0, std::ios_base::end)) { fsize = input.tellg(); input.seekg(0); } if (fsize < 24) // header is 24 bytes fail("File too small to be a valid BSA archive"); // Get essential header numbers uint32_t type, fileCount; uint64_t fileTableOffset; { uint32_t header[4]; input.read(reinterpret_cast<char*>(header), 16); input.read(reinterpret_cast<char*>(&fileTableOffset), 8); if (header[0] != ESM::fourCC("BTDX")) fail("Unrecognized BA2 signature"); mVersion = header[1]; switch (static_cast<BA2Version>(mVersion)) { case BA2Version::Fallout4: case BA2Version::Fallout4NextGen_v7: case BA2Version::Fallout4NextGen_v8: break; case BA2Version::StarfieldDDS: uint64_t dummy; input.read(reinterpret_cast<char*>(&dummy), 8); uint32_t compressionMethod; input.read(reinterpret_cast<char*>(&compressionMethod), 4); if (compressionMethod == 3) fail("Unsupported LZ4-compressed DDS BA2"); break; default: fail("Unrecognized DDS BA2 version"); } type = header[2]; fileCount = header[3]; } if (type == ESM::fourCC("DX10")) loadFiles(fileCount, input); else fail("Unrecognized ba2 version type"); // Read the string table input.seekg(fileTableOffset); for (uint32_t i = 0; i < fileCount; ++i) { std::vector<char> fileName; uint16_t fileNameSize; input.read(reinterpret_cast<char*>(&fileNameSize), sizeof(uint16_t)); fileName.resize(fileNameSize); input.read(fileName.data(), fileName.size()); fileName.push_back('\0'); mFileNames.push_back(fileName); mFiles[i].setNameInfos(0, &mFileNames.back()); } mIsLoaded = true; } std::optional<BA2DX10File::FileRecord> BA2DX10File::getFileRecord(const std::string& str) const { for (const auto c : str) { if (((static_cast<unsigned>(c) >> 7U) & 1U) != 0U) { fail("File record " + str + " contains unicode characters, refusing to load."); } } #ifdef _WIN32 const auto& path = str; #else // Force-convert the path into something UNIX can handle first // to make sure std::filesystem::path doesn't think the entire path is the filename on Linux // and subsequently purge it to determine the file folder. std::string path = str; std::replace(path.begin(), path.end(), '\\', '/'); #endif const auto p = std::filesystem::path{ path }; // Purposefully damage Unicode strings. const auto fileName = Misc::StringUtils::lowerCase(p.stem().string()); const auto ext = Misc::StringUtils::lowerCase(p.extension().string()); // Purposefully damage Unicode strings. const auto folder = Misc::StringUtils::lowerCase(p.parent_path().string()); uint32_t folderHash = generateHash(folder); auto it = mFolders.find(folderHash); if (it == mFolders.end()) return std::nullopt; // folder not found uint32_t fileHash = generateHash(fileName); uint32_t extHash = generateExtensionHash(ext); auto iter = it->second.find({ fileHash, extHash }); if (iter == it->second.end()) return std::nullopt; // file not found return iter->second; } #pragma pack(push) #pragma pack(1) struct DDSHeader { uint32_t size = 0; uint32_t flags = 0; uint32_t height = 0; uint32_t width = 0; uint32_t pitchOrLinearSize = 0; uint32_t depth = 0; uint32_t mipMapCount = 0; uint32_t reserved1[11] = {}; struct { uint32_t size = 0; uint32_t flags = 0; uint32_t fourCC = 0; uint32_t RGBBitCount = 0; uint32_t RBitMask = 0; uint32_t GBitMask = 0; uint32_t BBitMask = 0; uint32_t ABitMask = 0; } ddspf; uint32_t caps = 0; uint32_t caps2 = 0; uint32_t caps3 = 0; uint32_t caps4 = 0; uint32_t reserved2 = 0; }; struct DDSHeaderDX10 : DDSHeader { int32_t dxgiFormat = 0; uint32_t resourceDimension = 0; uint32_t miscFlags = 0; uint32_t arraySize = 0; uint32_t miscFlags2 = 0; }; #pragma pack(pop) Files::IStreamPtr BA2DX10File::getFile(const FileStruct* file) { if (auto fileRec = getFileRecord(file->name()); fileRec) return getFile(*fileRec); fail("File not found: " + std::string(file->name())); } void BA2DX10File::addFile(const std::string& filename, std::istream& file) { assert(false); // not implemented yet fail("Add file is not implemented for compressed BSA: " + filename); } Files::IStreamPtr BA2DX10File::getFile(const char* file) { if (auto fileRec = getFileRecord(file); fileRec) return getFile(*fileRec); fail("File not found: " + std::string(file)); } constexpr const uint32_t DDSD_CAPS = 0x00000001; constexpr const uint32_t DDSD_HEIGHT = 0x00000002; constexpr const uint32_t DDSD_WIDTH = 0x00000004; constexpr const uint32_t DDSD_PITCH = 0x00000008; constexpr const uint32_t DDSD_PIXELFORMAT = 0x00001000; constexpr const uint32_t DDSD_MIPMAPCOUNT = 0x00020000; constexpr const uint32_t DDSD_LINEARSIZE = 0x00080000; constexpr const uint32_t DDSCAPS_COMPLEX = 0x00000008; constexpr const uint32_t DDSCAPS_TEXTURE = 0x00001000; constexpr const uint32_t DDSCAPS_MIPMAP = 0x00400000; constexpr const uint32_t DDSCAPS2_CUBEMAP = 0x00000200; constexpr const uint32_t DDSCAPS2_POSITIVEX = 0x00000400; constexpr const uint32_t DDSCAPS2_NEGATIVEX = 0x00000800; constexpr const uint32_t DDSCAPS2_POSITIVEY = 0x00001000; constexpr const uint32_t DDSCAPS2_NEGATIVEY = 0x00002000; constexpr const uint32_t DDSCAPS2_POSITIVEZ = 0x00004000; constexpr const uint32_t DDSCAPS2_NEGATIVEZ = 0x00008000; constexpr const uint32_t DDPF_ALPHAPIXELS = 0x00000001; constexpr const uint32_t DDPF_ALPHA = 0x00000002; constexpr const uint32_t DDPF_FOURCC = 0x00000004; constexpr const uint32_t DDPF_RGB = 0x00000040; constexpr const uint32_t DDPF_LUMINANCE = 0x00020000; constexpr const uint32_t DDS_DIMENSION_TEXTURE2D = 0x00000003; constexpr const uint32_t DDS_RESOURCE_MISC_TEXTURECUBE = 0x00000004; enum DXGI : uint8_t { DXGI_FORMAT_UNKNOWN = 0, DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32A32_UINT, DXGI_FORMAT_R32G32B32A32_SINT, DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_UNORM, DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_R16G16B16A16_SINT, DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32_SINT, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UINT, DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_SNORM, DXGI_FORMAT_R8G8B8A8_SINT, DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_SINT, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_SINT, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8_UINT, DXGI_FORMAT_R8G8_SNORM, DXGI_FORMAT_R8G8_SINT, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R16_SNORM, DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R8_SNORM, DXGI_FORMAT_R8_SINT, DXGI_FORMAT_A8_UNORM, DXGI_FORMAT_R1_UNORM, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R8G8_B8G8_UNORM, DXGI_FORMAT_G8R8_G8B8_UNORM, DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC1_UNORM_SRGB, DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC2_UNORM_SRGB, DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC3_UNORM_SRGB, DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_UNORM, DXGI_FORMAT_BC4_SNORM, DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC5_SNORM, DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM, DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8X8_TYPELESS, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_UF16, DXGI_FORMAT_BC6H_SF16, DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM, DXGI_FORMAT_BC7_UNORM_SRGB, DXGI_FORMAT_AYUV, DXGI_FORMAT_Y410, DXGI_FORMAT_Y416, DXGI_FORMAT_NV12, DXGI_FORMAT_P010, DXGI_FORMAT_P016, DXGI_FORMAT_420_OPAQUE, DXGI_FORMAT_YUY2, DXGI_FORMAT_Y210, DXGI_FORMAT_Y216, DXGI_FORMAT_NV11, DXGI_FORMAT_AI44, DXGI_FORMAT_IA44, DXGI_FORMAT_P8, DXGI_FORMAT_A8P8, DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_P208, DXGI_FORMAT_V208, DXGI_FORMAT_V408 }; Files::IStreamPtr BA2DX10File::getFile(const FileRecord& fileRecord) { DDSHeaderDX10 header; header.size = sizeof(DDSHeader); header.width = fileRecord.width; header.height = fileRecord.height; header.flags = DDSD_CAPS | DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT | DDSD_MIPMAPCOUNT; header.caps = DDSCAPS_TEXTURE; header.mipMapCount = fileRecord.numMips; if (header.mipMapCount > 1) header.caps = header.caps | DDSCAPS_MIPMAP | DDSCAPS_COMPLEX; header.depth = 0; header.resourceDimension = DDS_DIMENSION_TEXTURE2D; header.arraySize = 1; if (fileRecord.cubeMaps == 2049) { header.caps = header.caps | DDSCAPS_COMPLEX; header.caps2 = DDSCAPS2_CUBEMAP | DDSCAPS2_POSITIVEX | DDSCAPS2_NEGATIVEX | DDSCAPS2_POSITIVEY | DDSCAPS2_NEGATIVEY | DDSCAPS2_POSITIVEZ | DDSCAPS2_NEGATIVEZ; header.miscFlags = DDS_RESOURCE_MISC_TEXTURECUBE; } header.ddspf.size = sizeof(header.ddspf); switch (DXGI(fileRecord.DXGIFormat)) { case DXGI_FORMAT_BC1_UNORM: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("DXT1"); header.pitchOrLinearSize = fileRecord.width * fileRecord.height / 2; break; } case DXGI_FORMAT_BC2_UNORM: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("DXT3"); header.pitchOrLinearSize = fileRecord.width * fileRecord.height; break; } case DXGI_FORMAT_BC3_UNORM: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("DXT5"); header.pitchOrLinearSize = fileRecord.width * fileRecord.height; break; } case DXGI_FORMAT_BC4_SNORM: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("BC4S"); header.pitchOrLinearSize = fileRecord.width * fileRecord.height / 2; break; } case DXGI_FORMAT_BC4_UNORM: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("BC4U"); header.pitchOrLinearSize = fileRecord.width * fileRecord.height / 2; break; } case DXGI_FORMAT_BC5_SNORM: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("BC5S"); header.pitchOrLinearSize = fileRecord.width * fileRecord.height; break; } case DXGI_FORMAT_BC5_UNORM: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("BC5U"); header.pitchOrLinearSize = fileRecord.width * fileRecord.height; break; } case DXGI_FORMAT_BC1_UNORM_SRGB: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("DX10"); header.dxgiFormat = int32_t(fileRecord.DXGIFormat); header.pitchOrLinearSize = fileRecord.width * fileRecord.height / 2; break; } case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_UNORM_SRGB: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: { header.flags = header.flags | DDSD_LINEARSIZE; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("DX10"); header.dxgiFormat = int32_t(fileRecord.DXGIFormat); header.pitchOrLinearSize = fileRecord.width * fileRecord.height; break; } case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: case DXGI_FORMAT_R8G8B8A8_SINT: case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("DX10"); header.dxgiFormat = int32_t(fileRecord.DXGIFormat); header.pitchOrLinearSize = fileRecord.width * 4; break; } case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R8G8_UINT: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("DX10"); header.dxgiFormat = int32_t(fileRecord.DXGIFormat); header.pitchOrLinearSize = fileRecord.width * 2; break; } case DXGI_FORMAT_R8_SINT: case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_R8_UINT: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_FOURCC; header.ddspf.fourCC = ESM::fourCC("DX10"); header.dxgiFormat = int32_t(fileRecord.DXGIFormat); header.pitchOrLinearSize = fileRecord.width; break; } case DXGI_FORMAT_R8G8B8A8_UNORM: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_RGB | DDPF_ALPHAPIXELS; header.ddspf.RGBBitCount = 32; header.ddspf.RBitMask = 0x000000FF; header.ddspf.GBitMask = 0x0000FF00; header.ddspf.BBitMask = 0x00FF0000; header.ddspf.ABitMask = 0xFF000000; header.pitchOrLinearSize = fileRecord.width * 4; break; } case DXGI_FORMAT_B8G8R8A8_UNORM: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_RGB | DDPF_ALPHAPIXELS; header.ddspf.RGBBitCount = 32; header.ddspf.RBitMask = 0x00FF0000; header.ddspf.GBitMask = 0x0000FF00; header.ddspf.BBitMask = 0x000000FF; header.ddspf.ABitMask = 0xFF000000; header.pitchOrLinearSize = fileRecord.width * 4; break; } case DXGI_FORMAT_B8G8R8X8_UNORM: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_RGB; header.ddspf.RGBBitCount = 32; header.ddspf.RBitMask = 0x00FF0000; header.ddspf.GBitMask = 0x0000FF00; header.ddspf.BBitMask = 0x000000FF; header.pitchOrLinearSize = fileRecord.width * 4; break; } case DXGI_FORMAT_B5G6R5_UNORM: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_RGB; header.ddspf.RGBBitCount = 16; header.ddspf.RBitMask = 0x0000F800; header.ddspf.GBitMask = 0x000007E0; header.ddspf.BBitMask = 0x0000001F; header.pitchOrLinearSize = fileRecord.width * 2; break; } case DXGI_FORMAT_B5G5R5A1_UNORM: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_RGB | DDPF_ALPHAPIXELS; header.ddspf.RGBBitCount = 16; header.ddspf.RBitMask = 0x00007C00; header.ddspf.GBitMask = 0x000003E0; header.ddspf.BBitMask = 0x0000001F; header.ddspf.ABitMask = 0x00008000; header.pitchOrLinearSize = fileRecord.width * 2; break; } case DXGI_FORMAT_R8G8_UNORM: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_LUMINANCE | DDPF_ALPHAPIXELS; header.ddspf.RGBBitCount = 16; header.ddspf.RBitMask = 0x000000FF; header.ddspf.ABitMask = 0x0000FF00; header.pitchOrLinearSize = fileRecord.width * 2; break; } case DXGI_FORMAT_A8_UNORM: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_ALPHA; header.ddspf.RGBBitCount = 8; header.ddspf.ABitMask = 0x000000FF; header.pitchOrLinearSize = fileRecord.width; break; } case DXGI_FORMAT_R8_UNORM: { header.flags = header.flags | DDSD_PITCH; header.ddspf.flags = DDPF_LUMINANCE; header.ddspf.RGBBitCount = 8; header.ddspf.RBitMask = 0x000000FF; header.pitchOrLinearSize = fileRecord.width; break; } default: break; } size_t headerSize = (header.ddspf.fourCC == ESM::fourCC("DX10") ? sizeof(DDSHeaderDX10) : sizeof(DDSHeader)); size_t textureSize = sizeof(uint32_t) + headerSize; //"DDS " + header for (const auto& textureChunk : fileRecord.texturesChunks) textureSize += textureChunk.size; auto memoryStreamPtr = std::make_unique<MemoryInputStream>(textureSize); char* buff = memoryStreamPtr->getRawData(); uint32_t dds = ESM::fourCC("DDS "); buff = (char*)std::memcpy(buff, &dds, sizeof(uint32_t)) + sizeof(uint32_t); std::memcpy(buff, &header, headerSize); size_t offset = sizeof(uint32_t) + headerSize; // append chunks for (const auto& c : fileRecord.texturesChunks) { if (c.packedSize != 0) { Files::IStreamPtr streamPtr = Files::openConstrainedFileStream(mFilepath, c.offset, c.packedSize); std::istream* fileStream = streamPtr.get(); boost::iostreams::filtering_streambuf<boost::iostreams::input> inputStreamBuf; inputStreamBuf.push(boost::iostreams::zlib_decompressor()); inputStreamBuf.push(*fileStream); boost::iostreams::basic_array_sink<char> sr(memoryStreamPtr->getRawData() + offset, c.size); boost::iostreams::copy(inputStreamBuf, sr); } // uncompressed chunk else { Files::IStreamPtr streamPtr = Files::openConstrainedFileStream(mFilepath, c.offset, c.size); std::istream* fileStream = streamPtr.get(); fileStream->read(memoryStreamPtr->getRawData() + offset, c.size); } offset += c.size; } return std::make_unique<Files::StreamWithBuffer<MemoryInputStream>>(std::move(memoryStreamPtr)); } } // namespace Bsa
26,314
C++
.cpp
632
30.286392
118
0.58863
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,503
bsa_file.cpp
OpenMW_openmw/components/bsa/bsa_file.cpp
/* OpenMW - The completely unofficial reimplementation of Morrowind Copyright (C) 2008-2010 Nicolay Korslund Email: < korslund@gmail.com > WWW: https://openmw.org/ This file (bsa_file.cpp) is part of the OpenMW package. OpenMW is distributed as free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License version 3 along with this program. If not, see https://www.gnu.org/licenses/ . */ #include "bsa_file.hpp" #include <components/esm/fourcc.hpp> #include <components/files/constrainedfilestream.hpp> #include <algorithm> #include <cassert> #include <cstring> #include <filesystem> #include <fstream> using namespace Bsa; /// Error handling [[noreturn]] void BSAFile::fail(const std::string& msg) const { throw std::runtime_error("BSA Error: " + msg + "\nArchive: " + Files::pathToUnicodeString(mFilepath)); } // the getHash code is from bsapack from ghostwheel // the code is also the same as in // https://github.com/arviceblot/bsatool_rs/commit/67cb59ec3aaeedc0849222ea387f031c33e48c81 BSAFile::Hash getHash(const std::string& name) { BSAFile::Hash hash; unsigned l = (static_cast<unsigned>(name.size()) >> 1); unsigned sum, off, temp, i, n; for (sum = off = i = 0; i < l; i++) { sum ^= (((unsigned)(name[i])) << (off & 0x1F)); off += 8; } hash.low = sum; for (sum = off = 0; i < name.size(); i++) { temp = (((unsigned)(name[i])) << (off & 0x1F)); sum ^= temp; n = temp & 0x1F; sum = (sum << (32 - n)) | (sum >> n); // binary "rotate right" off += 8; } hash.high = sum; return hash; } /// Read header information from the input source void BSAFile::readHeader() { /* * The layout of a BSA archive is as follows: * * - 12 bytes header, contains 3 ints: * id number - equal to 0x100 * dirsize - size of the directory block (see below) * numfiles - number of files * * ---------- start of directory block ----------- * * - 8 bytes*numfiles, each record contains: * fileSize * offset into data buffer (see below) * * - 4 bytes*numfiles, each record is an offset into the following name buffer * * - name buffer, indexed by the previous table, each string is * null-terminated. Size is (dirsize - 12*numfiles). * * ---------- end of directory block ------------- * * - 8*filenum - hash table block, we currently ignore this * * ----------- start of data buffer -------------- * * - The rest of the archive is file data, indexed by the * offsets in the directory block. The offsets start at 0 at * the beginning of this buffer. * */ assert(!mIsLoaded); std::ifstream input(mFilepath, std::ios_base::binary); // Total archive size std::streamoff fsize = 0; if (input.seekg(0, std::ios_base::end)) { fsize = input.tellg(); input.seekg(0); } if (fsize < 12) fail("File too small to be a valid BSA archive"); // Get essential header numbers size_t dirsize, filenum; { // First 12 bytes uint32_t head[3]; input.read(reinterpret_cast<char*>(head), 12); if (head[0] != 0x100) fail("Unrecognized BSA header"); // Total number of bytes used in size/offset-table + filename // sections. dirsize = head[1]; // Number of files filenum = head[2]; } // Each file must take up at least 21 bytes of data in the bsa. So // if files*21 overflows the file size then we are guaranteed that // the archive is corrupt. if ((filenum * 21 > unsigned(fsize - 12)) || (dirsize + 8 * filenum > unsigned(fsize - 12))) fail("Directory information larger than entire archive"); // Read the offset info into a temporary buffer std::vector<uint32_t> offsets(3 * filenum); input.read(reinterpret_cast<char*>(offsets.data()), 12 * filenum); // Read the string table mStringBuf.resize(dirsize - 12 * filenum); input.read(mStringBuf.data(), mStringBuf.size()); // Check our position assert(input.tellg() == std::streampos(12 + dirsize)); std::vector<Hash> hashes(filenum); static_assert(sizeof(Hash) == 8); input.read(reinterpret_cast<char*>(hashes.data()), 8 * filenum); // Calculate the offset of the data buffer. All file offsets are // relative to this. 12 header bytes + directory + hash table // (skipped) size_t fileDataOffset = 12 + dirsize + 8 * filenum; // Set up the the FileStruct table mFiles.resize(filenum); size_t endOfNameBuffer = 0; for (size_t i = 0; i < filenum; i++) { FileStruct& fs = mFiles[i]; fs.fileSize = offsets[i * 2]; fs.offset = static_cast<uint32_t>(offsets[i * 2 + 1] + fileDataOffset); auto namesOffset = offsets[2 * filenum + i]; fs.setNameInfos(namesOffset, &mStringBuf); fs.hash = hashes[i]; if (namesOffset >= mStringBuf.size()) { fail("Archive contains names offset outside itself"); } const void* end = std::memchr(fs.name(), '\0', mStringBuf.size() - namesOffset); if (!end) { fail("Archive contains non-zero terminated string"); } endOfNameBuffer = std::max(endOfNameBuffer, namesOffset + std::strlen(fs.name()) + 1); assert(endOfNameBuffer <= mStringBuf.size()); if (fs.offset + fs.fileSize > fsize) fail("Archive contains offsets outside itself"); } mStringBuf.resize(endOfNameBuffer); std::sort(mFiles.begin(), mFiles.end(), [](const FileStruct& left, const FileStruct& right) { return left.offset < right.offset; }); mIsLoaded = true; } /// Write header information to the output sink void Bsa::BSAFile::writeHeader() { std::fstream output(mFilepath, std::ios::binary | std::ios::in | std::ios::out); uint32_t head[3]; head[0] = 0x100; auto fileDataOffset = mFiles.empty() ? 12 : mFiles.front().offset; head[1] = static_cast<uint32_t>(fileDataOffset - 12 - 8 * mFiles.size()); output.seekp(0, std::ios_base::end); head[2] = static_cast<uint32_t>(mFiles.size()); output.seekp(0); output.write(reinterpret_cast<char*>(head), 12); std::sort(mFiles.begin(), mFiles.end(), [](const FileStruct& left, const FileStruct& right) { return std::make_pair(left.hash.low, left.hash.high) < std::make_pair(right.hash.low, right.hash.high); }); size_t filenum = mFiles.size(); std::vector<uint32_t> offsets(3 * filenum); std::vector<Hash> hashes(filenum); for (size_t i = 0; i < filenum; i++) { auto& f = mFiles[i]; offsets[i * 2] = f.fileSize; offsets[i * 2 + 1] = f.offset - fileDataOffset; offsets[2 * filenum + i] = f.namesOffset; hashes[i] = f.hash; } output.write(reinterpret_cast<char*>(offsets.data()), sizeof(uint32_t) * offsets.size()); output.write(reinterpret_cast<char*>(mStringBuf.data()), mStringBuf.size()); output.seekp(fileDataOffset - 8 * mFiles.size(), std::ios_base::beg); output.write(reinterpret_cast<char*>(hashes.data()), sizeof(Hash) * hashes.size()); } /// Open an archive file. void BSAFile::open(const std::filesystem::path& file) { if (mIsLoaded) close(); mFilepath = file; if (std::filesystem::exists(file)) readHeader(); else { { std::fstream(mFilepath, std::ios::binary | std::ios::out); } writeHeader(); mIsLoaded = true; } } /// Close the archive, write the updated headers to the file void Bsa::BSAFile::close() { if (mHasChanged) writeHeader(); mFiles.clear(); mStringBuf.clear(); mIsLoaded = false; } Files::IStreamPtr Bsa::BSAFile::getFile(const FileStruct* file) { return Files::openConstrainedFileStream(mFilepath, file->offset, file->fileSize); } void Bsa::BSAFile::addFile(const std::string& filename, std::istream& file) { if (!mIsLoaded) fail("Unable to add file " + filename + " the archive is not opened"); auto newStartOfDataBuffer = 12 + (12 + 8) * (mFiles.size() + 1) + mStringBuf.size() + filename.size() + 1; if (mFiles.empty()) std::filesystem::resize_file(mFilepath, newStartOfDataBuffer); std::fstream stream(mFilepath, std::ios::binary | std::ios::in | std::ios::out); FileStruct newFile; file.seekg(0, std::ios::end); newFile.fileSize = static_cast<uint32_t>(file.tellg()); newFile.setNameInfos(mStringBuf.size(), &mStringBuf); newFile.hash = getHash(filename); if (mFiles.empty()) newFile.offset = static_cast<uint32_t>(newStartOfDataBuffer); else { std::vector<char> buffer; while (mFiles.front().offset < newStartOfDataBuffer) { FileStruct& firstFile = mFiles.front(); buffer.resize(firstFile.fileSize); stream.seekg(firstFile.offset, std::ios::beg); stream.read(buffer.data(), firstFile.fileSize); stream.seekp(0, std::ios::end); firstFile.offset = static_cast<uint32_t>(stream.tellp()); stream.write(buffer.data(), firstFile.fileSize); // ensure sort order is preserved std::rotate(mFiles.begin(), mFiles.begin() + 1, mFiles.end()); } stream.seekp(0, std::ios::end); newFile.offset = static_cast<uint32_t>(stream.tellp()); } mStringBuf.insert(mStringBuf.end(), filename.begin(), filename.end()); mStringBuf.push_back('\0'); mFiles.push_back(newFile); mHasChanged = true; stream.seekp(0, std::ios::end); file.seekg(0, std::ios::beg); stream << file.rdbuf(); } BsaVersion Bsa::BSAFile::detectVersion(const std::filesystem::path& filePath) { std::ifstream input(filePath, std::ios_base::binary); // Get essential header numbers // First 12 bytes uint32_t head[3]; input.read(reinterpret_cast<char*>(head), sizeof(head)); if (input.gcount() != sizeof(head)) return BsaVersion::Unknown; if (head[0] == static_cast<uint32_t>(BsaVersion::Uncompressed)) { return BsaVersion::Uncompressed; } if (head[0] == static_cast<uint32_t>(BsaVersion::Compressed)) { return BsaVersion::Compressed; } if (head[0] == ESM::fourCC("BTDX")) { if (head[2] == ESM::fourCC("GNRL")) return BsaVersion::BA2GNRL; if (head[2] == ESM::fourCC("DX10")) return BsaVersion::BA2DX10; } return BsaVersion::Unknown; }
11,116
C++
.cpp
292
32.160959
111
0.6311
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,504
ba2gnrlfile.cpp
OpenMW_openmw/components/bsa/ba2gnrlfile.cpp
#include "ba2gnrlfile.hpp" #include <cassert> #include <filesystem> #include <fstream> #include <lz4frame.h> #if defined(_MSC_VER) // why is this necessary? These are included with /external:I #pragma warning(push) #pragma warning(disable : 4706) #pragma warning(disable : 4702) #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/iostreams/filtering_streambuf.hpp> #pragma warning(pop) #else #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/iostreams/filtering_streambuf.hpp> #endif #include <boost/iostreams/device/array.hpp> #include <components/bsa/ba2file.hpp> #include <components/bsa/memorystream.hpp> #include <components/esm/fourcc.hpp> #include <components/files/constrainedfilestream.hpp> #include <components/files/conversion.hpp> #include <components/misc/strings/lower.hpp> namespace Bsa { // special marker for invalid records, const uint32_t sInvalidOffset = std::numeric_limits<uint32_t>::max(); BA2GNRLFile::FileRecord::FileRecord() : size(0) , offset(sInvalidOffset) { } bool BA2GNRLFile::FileRecord::isValid() const { return offset != sInvalidOffset; } BA2GNRLFile::BA2GNRLFile() {} BA2GNRLFile::~BA2GNRLFile() = default; void BA2GNRLFile::loadFiles(uint32_t fileCount, std::istream& in) { mFiles.clear(); mFiles.reserve(fileCount); for (uint32_t i = 0; i < fileCount; ++i) { uint32_t nameHash, extHash, dirHash; in.read(reinterpret_cast<char*>(&nameHash), sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&extHash), sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&dirHash), sizeof(uint32_t)); FileRecord file; uint32_t unknown; in.read(reinterpret_cast<char*>(&unknown), sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&file.offset), sizeof(int64_t)); in.read(reinterpret_cast<char*>(&file.packedSize), sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&file.size), sizeof(uint32_t)); uint32_t baadfood; in.read(reinterpret_cast<char*>(&baadfood), sizeof(uint32_t)); if (baadfood != 0xBAADF00D) fail("Corrupted BSA"); mFolders[dirHash][{ nameHash, extHash }] = file; FileStruct fileStruct{}; fileStruct.fileSize = file.size; fileStruct.offset = file.offset; mFiles.push_back(fileStruct); } } /// Read header information from the input source void BA2GNRLFile::readHeader() { assert(!mIsLoaded); std::ifstream input(mFilepath, std::ios_base::binary); // Total archive size std::streamoff fsize = 0; if (input.seekg(0, std::ios_base::end)) { fsize = input.tellg(); input.seekg(0); } if (fsize < 24) // header is 24 bytes fail("File too small to be a valid BSA archive"); // Get essential header numbers uint32_t type, fileCount; uint64_t fileTableOffset; { uint32_t header[4]; input.read(reinterpret_cast<char*>(header), 16); input.read(reinterpret_cast<char*>(&fileTableOffset), 8); if (header[0] != ESM::fourCC("BTDX")) fail("Unrecognized BA2 signature"); mVersion = header[1]; switch (static_cast<BA2Version>(mVersion)) { case BA2Version::Fallout4: case BA2Version::Fallout4NextGen_v7: case BA2Version::Fallout4NextGen_v8: break; case BA2Version::StarfieldGeneral: uint64_t dummy; input.read(reinterpret_cast<char*>(&dummy), 8); break; default: fail("Unrecognized general BA2 version"); } type = header[2]; fileCount = header[3]; } if (type == ESM::fourCC("GNRL")) loadFiles(fileCount, input); else fail("Unrecognized ba2 version type"); // Read the string table input.seekg(fileTableOffset); for (uint32_t i = 0; i < fileCount; ++i) { std::vector<char> fileName; uint16_t fileNameSize; input.read(reinterpret_cast<char*>(&fileNameSize), sizeof(uint16_t)); fileName.resize(fileNameSize); input.read(fileName.data(), fileName.size()); fileName.push_back('\0'); mFileNames.push_back(fileName); mFiles[i].setNameInfos(0, &mFileNames.back()); } mIsLoaded = true; } BA2GNRLFile::FileRecord BA2GNRLFile::getFileRecord(const std::string& str) const { for (const auto c : str) { if (((static_cast<unsigned>(c) >> 7U) & 1U) != 0U) { fail("File record " + str + " contains unicode characters, refusing to load."); } } #ifdef _WIN32 const auto& path = str; #else // Force-convert the path into something UNIX can handle first // to make sure std::filesystem::path doesn't think the entire path is the filename on Linux // and subsequently purge it to determine the file folder. std::string path = str; std::replace(path.begin(), path.end(), '\\', '/'); #endif const auto p = std::filesystem::path{ path }; // Purposefully damage Unicode strings. const auto fileName = Misc::StringUtils::lowerCase(p.stem().string()); const auto ext = Misc::StringUtils::lowerCase(p.extension().string()); // Purposefully damage Unicode strings. const auto folder = Misc::StringUtils::lowerCase(p.parent_path().string()); uint32_t folderHash = generateHash(folder); auto it = mFolders.find(folderHash); if (it == mFolders.end()) return FileRecord(); // folder not found, return default which has offset of sInvalidOffset uint32_t fileHash = generateHash(fileName); uint32_t extHash = generateExtensionHash(ext); auto iter = it->second.find({ fileHash, extHash }); if (iter == it->second.end()) return FileRecord(); // file not found, return default which has offset of sInvalidOffset return iter->second; } Files::IStreamPtr BA2GNRLFile::getFile(const FileStruct* file) { FileRecord fileRec = getFileRecord(file->name()); if (!fileRec.isValid()) { fail("File not found: " + std::string(file->name())); } return getFile(fileRec); } void BA2GNRLFile::addFile(const std::string& filename, std::istream& file) { assert(false); // not implemented yet fail("Add file is not implemented for compressed BSA: " + filename); } Files::IStreamPtr BA2GNRLFile::getFile(const char* file) { FileRecord fileRec = getFileRecord(file); if (!fileRec.isValid()) { fail("File not found: " + std::string(file)); } return getFile(fileRec); } Files::IStreamPtr BA2GNRLFile::getFile(const FileRecord& fileRecord) { const uint32_t inputSize = fileRecord.packedSize ? fileRecord.packedSize : fileRecord.size; Files::IStreamPtr streamPtr = Files::openConstrainedFileStream(mFilepath, fileRecord.offset, inputSize); auto memoryStreamPtr = std::make_unique<MemoryInputStream>(fileRecord.size); if (fileRecord.packedSize) { boost::iostreams::filtering_streambuf<boost::iostreams::input> inputStreamBuf; inputStreamBuf.push(boost::iostreams::zlib_decompressor()); inputStreamBuf.push(*streamPtr); boost::iostreams::basic_array_sink<char> sr(memoryStreamPtr->getRawData(), fileRecord.size); boost::iostreams::copy(inputStreamBuf, sr); } else { streamPtr->read(memoryStreamPtr->getRawData(), fileRecord.size); } return std::make_unique<Files::StreamWithBuffer<MemoryInputStream>>(std::move(memoryStreamPtr)); } } // namespace Bsa
8,303
C++
.cpp
203
31.945813
118
0.618227
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,505
compressedbsafile.cpp
OpenMW_openmw/components/bsa/compressedbsafile.cpp
/* OpenMW - The completely unofficial reimplementation of Morrowind Copyright (C) 2008-2010 Nicolay Korslund Email: < korslund@gmail.com > WWW: http://openmw.sourceforge.net/ This file (compressedbsafile.cpp) is part of the OpenMW package. OpenMW is distributed as free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License version 3 along with this program. If not, see http://www.gnu.org/licenses/ . Compressed BSA stuff added by cc9cii 2018 */ #include "compressedbsafile.hpp" #include <cassert> #include <filesystem> #include <fstream> #include <lz4frame.h> #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4706) #pragma warning(disable : 4702) #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/iostreams/filtering_streambuf.hpp> #pragma warning(pop) #else #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/iostreams/filtering_streambuf.hpp> #endif #include <boost/iostreams/device/array.hpp> #include <components/bsa/memorystream.hpp> #include <components/files/constrainedfilestream.hpp> #include <components/files/conversion.hpp> #include <components/misc/strings/lower.hpp> namespace Bsa { /// Read header information from the input source void CompressedBSAFile::readHeader() { assert(!mIsLoaded); std::ifstream input(mFilepath, std::ios_base::binary); // Total archive size std::streamoff fsize = 0; if (input.seekg(0, std::ios_base::end)) { fsize = input.tellg(); input.seekg(0); } if (fsize < 36) // Header is 36 bytes fail("File too small to be a valid BSA archive"); input.read(reinterpret_cast<char*>(&mHeader), sizeof(mHeader)); if (mHeader.mFormat != static_cast<std::uint32_t>(BsaVersion::Compressed)) // BSA fail("Unrecognized compressed BSA format"); if (mHeader.mVersion != Version_TES4 && mHeader.mVersion != Version_FO3 && mHeader.mVersion != Version_SSE) fail("Unrecognized compressed BSA version"); if (mHeader.mVersion == Version_TES4) mHeader.mFlags &= (~ArchiveFlag_EmbeddedNames); input.seekg(mHeader.mFoldersOffset); if (input.bad()) fail("Invalid compressed BSA folder record offset"); struct FlatFolderRecord { std::uint64_t mHash; std::string mName; std::uint32_t mCount; std::int64_t mOffset; }; std::vector<std::pair<FlatFolderRecord, std::vector<FileRecord>>> folders; folders.resize(mHeader.mFolderCount); for (auto& [folder, filelist] : folders) { input.read(reinterpret_cast<char*>(&folder.mHash), 8); input.read(reinterpret_cast<char*>(&folder.mCount), 4); if (mHeader.mVersion == Version_SSE) // SSE { std::uint32_t unknown = 0; input.read(reinterpret_cast<char*>(&unknown), 4); input.read(reinterpret_cast<char*>(&folder.mOffset), 8); } else { input.read(reinterpret_cast<char*>(&folder.mOffset), 4); } } if (input.bad()) fail("Failed to read compressed BSA folder records: input error"); // file record blocks if ((mHeader.mFlags & ArchiveFlag_FolderNames) == 0) mHeader.mFolderCount = 1; // TODO: not tested - unit test necessary for (auto& [folder, filelist] : folders) { if ((mHeader.mFlags & ArchiveFlag_FolderNames) != 0) { uint8_t size = 0; input.read(reinterpret_cast<char*>(&size), 1); if (size > 0) { folder.mName.resize(size); input.getline(folder.mName.data(), size, '\0'); if (input.gcount() != static_cast<std::streamsize>(size)) fail("Folder name size mismatch: " + std::to_string(input.gcount()) + " bytes read, expected " + std::to_string(size)); if (mHeader.mFolderNamesLength < size) fail("Failed to read folder names: " + std::to_string(mHeader.mFolderNamesLength) + " < " + std::to_string(size)); folder.mName.resize(size - 1); } mHeader.mFolderNamesLength -= size; } filelist.resize(folder.mCount); for (auto& file : filelist) { input.read(reinterpret_cast<char*>(&file.mHash), 8); input.read(reinterpret_cast<char*>(&file.mSize), 4); input.read(reinterpret_cast<char*>(&file.mOffset), 4); } } if (mHeader.mFolderNamesLength != 0) input.ignore(mHeader.mFolderNamesLength); if (input.bad()) fail("Failed to read compressed BSA file records: input error"); if ((mHeader.mFlags & ArchiveFlag_FileNames) != 0) { for (auto& [folder, filelist] : folders) { for (auto& file : filelist) { auto& name = file.mName; name.resize(256); input.getline(name.data(), 256, '\0'); if (input.gcount() <= 1) fail("Failed to read a filename: filename is empty"); if (mHeader.mFileNamesLength < input.gcount()) fail("Failed to read file names: " + std::to_string(mHeader.mFileNamesLength) + " < " + std::to_string(input.gcount())); name.resize(input.gcount()); if (name.back() != '\0') fail("Failed to read a filename: filename is too long"); mHeader.mFileNamesLength -= static_cast<std::uint32_t>(input.gcount()); file.mName.insert(file.mName.begin(), folder.mName.begin(), folder.mName.end()); file.mName.insert(file.mName.begin() + folder.mName.size(), '\\'); } } } if (mHeader.mFileNamesLength != 0) input.ignore(mHeader.mFileNamesLength); if (input.bad()) fail("Failed to read compressed BSA filenames: input error"); for (auto& [folder, filelist] : folders) { std::map<std::uint64_t, FileRecord> fileMap; for (const auto& file : filelist) fileMap[file.mHash] = std::move(file); auto& folderMap = mFolders[folder.mHash]; folderMap = FolderRecord{ folder.mCount, folder.mOffset, std::move(fileMap) }; for (auto& [hash, fileRec] : folderMap.mFiles) { FileStruct fileStruct{}; fileStruct.fileSize = fileRec.mSize & (~FileSizeFlag_Compression); fileStruct.offset = fileRec.mOffset; fileStruct.setNameInfos(0, &fileRec.mName); mFiles.emplace_back(fileStruct); } } mIsLoaded = true; } CompressedBSAFile::FileRecord CompressedBSAFile::getFileRecord(const std::string& str) const { for (const auto c : str) { if (((static_cast<unsigned>(c) >> 7U) & 1U) != 0U) { fail("File record " + str + " contains unicode characters, refusing to load."); } } #ifdef _WIN32 const auto& path = str; #else // Force-convert the path into something UNIX can handle first // to make sure std::filesystem::path doesn't think the entire path is the filename on Linux // and subsequently purge it to determine the file folder. std::string path = str; std::replace(path.begin(), path.end(), '\\', '/'); #endif const auto p = std::filesystem::path{ path }; // Purposefully damage Unicode strings. const auto stem = p.stem(); const auto ext = p.extension().string(); // Purposefully damage Unicode strings. std::uint64_t folderHash = generateHash(p.parent_path(), {}); auto it = mFolders.find(folderHash); if (it == mFolders.end()) return FileRecord(); std::uint64_t fileHash = generateHash(stem, ext); auto iter = it->second.mFiles.find(fileHash); if (iter == it->second.mFiles.end()) return FileRecord(); return iter->second; } Files::IStreamPtr CompressedBSAFile::getFile(const FileStruct* file) { FileRecord fileRec = getFileRecord(file->name()); if (fileRec.mOffset == std::numeric_limits<uint32_t>::max()) { fail("File not found: " + std::string(file->name())); } return getFile(fileRec); } void CompressedBSAFile::addFile(const std::string& filename, std::istream& file) { assert(false); // not implemented yet fail("Add file is not implemented for compressed BSA: " + filename); } Files::IStreamPtr CompressedBSAFile::getFile(const char* file) { FileRecord fileRec = getFileRecord(file); if (fileRec.mOffset == std::numeric_limits<uint32_t>::max()) { fail("File not found: " + std::string(file)); } return getFile(fileRec); } Files::IStreamPtr CompressedBSAFile::getFile(const FileRecord& fileRecord) { size_t size = fileRecord.mSize & (~FileSizeFlag_Compression); size_t resultSize = size; Files::IStreamPtr streamPtr = Files::openConstrainedFileStream(mFilepath, fileRecord.mOffset, size); bool compressed = (fileRecord.mSize != size) == ((mHeader.mFlags & ArchiveFlag_Compress) == 0); if ((mHeader.mFlags & ArchiveFlag_EmbeddedNames) != 0) { // Skip over the embedded file name uint8_t length = 0; streamPtr->read(reinterpret_cast<char*>(&length), 1); streamPtr->ignore(length); size -= length + sizeof(uint8_t); } if (compressed) { streamPtr->read(reinterpret_cast<char*>(&resultSize), sizeof(uint32_t)); size -= sizeof(uint32_t); } auto memoryStreamPtr = std::make_unique<MemoryInputStream>(resultSize); if (compressed) { if (mHeader.mVersion != Version_SSE) { boost::iostreams::filtering_streambuf<boost::iostreams::input> inputStreamBuf; inputStreamBuf.push(boost::iostreams::zlib_decompressor()); inputStreamBuf.push(*streamPtr); boost::iostreams::basic_array_sink<char> sr(memoryStreamPtr->getRawData(), resultSize); boost::iostreams::copy(inputStreamBuf, sr); } else { auto buffer = std::vector<char>(size); streamPtr->read(buffer.data(), size); LZ4F_decompressionContext_t context = nullptr; LZ4F_createDecompressionContext(&context, LZ4F_VERSION); LZ4F_decompressOptions_t options = {}; LZ4F_errorCode_t errorCode = LZ4F_decompress( context, memoryStreamPtr->getRawData(), &resultSize, buffer.data(), &size, &options); if (LZ4F_isError(errorCode)) fail("LZ4 decompression error (file " + Files::pathToUnicodeString(mFilepath) + "): " + LZ4F_getErrorName(errorCode)); errorCode = LZ4F_freeDecompressionContext(context); if (LZ4F_isError(errorCode)) fail("LZ4 decompression error (file " + Files::pathToUnicodeString(mFilepath) + "): " + LZ4F_getErrorName(errorCode)); } } else { streamPtr->read(memoryStreamPtr->getRawData(), size); } return std::make_unique<Files::StreamWithBuffer<MemoryInputStream>>(std::move(memoryStreamPtr)); } std::uint64_t CompressedBSAFile::generateHash(const std::filesystem::path& stem, std::string extension) { auto str = stem.u8string(); size_t len = str.length(); if (len == 0) return 0; std::replace(str.begin(), str.end(), '/', '\\'); Misc::StringUtils::lowerCaseInPlace(str); uint64_t result = str[len - 1]; if (len >= 3) result |= str[len - 2] << 8; result |= len << 16; result |= static_cast<uint32_t>(str[0] << 24); if (len >= 4) { uint32_t hash = 0; for (size_t i = 1; i <= len - 3; ++i) hash = hash * 0x1003f + str[i]; result += static_cast<uint64_t>(hash) << 32; } if (extension.empty()) return result; Misc::StringUtils::lowerCaseInPlace(extension); if (extension == ".kf") result |= 0x80; else if (extension == ".nif") result |= 0x8000; else if (extension == ".dds") result |= 0x8080; else if (extension == ".wav") result |= 0x80000000; uint32_t hash = 0; for (const auto& c : extension) hash = hash * 0x1003f + c; result += static_cast<uint64_t>(hash) << 32; return result; } } // namespace Bsa
13,943
C++
.cpp
319
32.815047
118
0.578331
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,506
npcstate.cpp
OpenMW_openmw/components/esm3/npcstate.cpp
#include "npcstate.hpp" namespace ESM { void NpcState::load(ESMReader& esm) { ObjectState::load(esm); if (mHasCustomState) { mInventory.load(esm); mNpcStats.load(esm); mCreatureStats.load(esm); } } void NpcState::save(ESMWriter& esm, bool inInventory) const { ObjectState::save(esm, inInventory); if (mHasCustomState) { mInventory.save(esm); mNpcStats.save(esm); mCreatureStats.save(esm); } } void NpcState::blank() { ObjectState::blank(); mNpcStats.blank(); mCreatureStats.blank(); mHasCustomState = true; } }
726
C++
.cpp
31
15.483871
63
0.555556
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,507
loadlock.cpp
OpenMW_openmw/components/esm3/loadlock.cpp
#include "loadlock.hpp" #include "esmreader.hpp" #include "esmwriter.hpp" #include <components/misc/concepts.hpp> namespace ESM { template <Misc::SameAsWithoutCvref<Lockpick::Data> T> void decompose(T&& v, const auto& f) { f(v.mWeight, v.mValue, v.mQuality, v.mUses); } void Lockpick::load(ESMReader& esm, bool& isDeleted) { isDeleted = false; mRecordFlags = esm.getRecordFlags(); bool hasName = false; bool hasData = false; while (esm.hasMoreSubs()) { esm.getSubName(); switch (esm.retSubName().toInt()) { case SREC_NAME: mId = esm.getRefId(); hasName = true; break; case fourCC("MODL"): mModel = esm.getHString(); break; case fourCC("FNAM"): mName = esm.getHString(); break; case fourCC("LKDT"): esm.getSubComposite(mData); hasData = true; break; case fourCC("SCRI"): mScript = esm.getRefId(); break; case fourCC("ITEX"): mIcon = esm.getHString(); break; case SREC_DELE: esm.skipHSub(); isDeleted = true; break; default: esm.fail("Unknown subrecord"); break; } } if (!hasName) esm.fail("Missing NAME subrecord"); if (!hasData && !isDeleted) esm.fail("Missing LKDT subrecord"); } void Lockpick::save(ESMWriter& esm, bool isDeleted) const { esm.writeHNCRefId("NAME", mId); if (isDeleted) { esm.writeHNString("DELE", "", 3); return; } esm.writeHNCString("MODL", mModel); esm.writeHNOCString("FNAM", mName); esm.writeNamedComposite("LKDT", mData); esm.writeHNORefId("SCRI", mScript); esm.writeHNOCString("ITEX", mIcon); } void Lockpick::blank() { mRecordFlags = 0; mData.mWeight = 0; mData.mValue = 0; mData.mQuality = 0; mData.mUses = 0; mName.clear(); mModel.clear(); mIcon.clear(); mScript = ESM::RefId(); } }
2,502
C++
.cpp
83
18.409639
61
0.475083
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,508
weatherstate.cpp
OpenMW_openmw/components/esm3/weatherstate.cpp
#include "weatherstate.hpp" #include "esmreader.hpp" #include "esmwriter.hpp" namespace ESM { namespace { constexpr NAME currentRegionRecord = "CREG"; constexpr NAME timePassedRecord = "TMPS"; constexpr NAME fastForwardRecord = "FAST"; constexpr NAME weatherUpdateTimeRecord = "WUPD"; constexpr NAME transitionFactorRecord = "TRFC"; constexpr NAME currentWeatherRecord = "CWTH"; constexpr NAME nextWeatherRecord = "NWTH"; constexpr NAME queuedWeatherRecord = "QWTH"; constexpr NAME regionNameRecord = "RGNN"; constexpr NAME regionWeatherRecord = "RGNW"; constexpr NAME regionChanceRecord = "RGNC"; } } namespace ESM { void WeatherState::load(ESMReader& esm) { mCurrentRegion = esm.getHNRefId(currentRegionRecord); esm.getHNT(mTimePassed, timePassedRecord); esm.getHNT(mFastForward, fastForwardRecord); esm.getHNT(mWeatherUpdateTime, weatherUpdateTimeRecord); esm.getHNT(mTransitionFactor, transitionFactorRecord); esm.getHNT(mCurrentWeather, currentWeatherRecord); esm.getHNT(mNextWeather, nextWeatherRecord); esm.getHNT(mQueuedWeather, queuedWeatherRecord); while (esm.isNextSub(regionNameRecord)) { ESM::RefId regionID = esm.getRefId(); RegionWeatherState region; esm.getHNT(region.mWeather, regionWeatherRecord); while (esm.isNextSub(regionChanceRecord)) { uint8_t chance; esm.getHT(chance); region.mChances.push_back(chance); } mRegions.insert(std::make_pair(regionID, region)); } } void WeatherState::save(ESMWriter& esm) const { esm.writeHNCRefId(currentRegionRecord, mCurrentRegion); esm.writeHNT(timePassedRecord, mTimePassed); esm.writeHNT(fastForwardRecord, mFastForward); esm.writeHNT(weatherUpdateTimeRecord, mWeatherUpdateTime); esm.writeHNT(transitionFactorRecord, mTransitionFactor); esm.writeHNT(currentWeatherRecord, mCurrentWeather); esm.writeHNT(nextWeatherRecord, mNextWeather); esm.writeHNT(queuedWeatherRecord, mQueuedWeather); auto it = mRegions.begin(); for (; it != mRegions.end(); ++it) { esm.writeHNCRefId(regionNameRecord, it->first); esm.writeHNT(regionWeatherRecord, it->second.mWeather); for (const uint8_t& chance : it->second.mChances) { esm.writeHNT(regionChanceRecord, chance); } } } }
2,644
C++
.cpp
68
30.191176
67
0.662904
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