hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
daa0c17779817c4faebf17bdb6d6a40329a596bd
1,449
cpp
C++
ConsoleApplication3/ConsoleApplication3/Roomc.cpp
msSarriman/UniversityProject_C-_CommandLineInterfaceForHotelReservations
c94c6fee42d64246cd99d102fb63de93840be700
[ "MIT" ]
null
null
null
ConsoleApplication3/ConsoleApplication3/Roomc.cpp
msSarriman/UniversityProject_C-_CommandLineInterfaceForHotelReservations
c94c6fee42d64246cd99d102fb63de93840be700
[ "MIT" ]
null
null
null
ConsoleApplication3/ConsoleApplication3/Roomc.cpp
msSarriman/UniversityProject_C-_CommandLineInterfaceForHotelReservations
c94c6fee42d64246cd99d102fb63de93840be700
[ "MIT" ]
null
null
null
/* * Roomc.cpp * * Created on: May 21, 2017 * Author: root */ #include "Roomc.h" namespace std { Roomc::Roomc() { // // Default Constructor. } Roomc::Roomc(int number, int capacity, double price, int discount, int minpersons, int minnights) { for (int i = 1; i < 31; i++) { // Make Room available for all days of the Month. roomAvailability[i] = NULL; } roomNumber = number; roomCapacity = capacity; roomPrice = price; roomcMinNights = minnights; roomcMinPersons = minpersons; } bool Roomc::roomReservationAdd(Reservation* r) { // // Overlaped method for reservation assignment to this Roomc type. if (r->rsrvPersons > roomCapacity) return 0; // If Reservation's persons are greater than room's capacity, return FALSE. for (unsigned int i = r->rsrvDate; i < r->rsrvDate + r->rsrvNights; i++) // If Room is not available the desired days, return FALSE. if (roomAvailability[i] != NULL) return 0; if (r->rsrvPersons >= roomcMinPersons || r->rsrvNights >= roomcMinNights) // If persons >= min and nights >= minnights return 0; for (unsigned int i = r->rsrvDate; i < r->rsrvDate + r->rsrvNights; i++) // If the above checks, assign to the Room for the specific days, the Reservation object. roomAvailability[i] = r; r->rsrvRoomAssignment(this); // Update Room object that the specific reservations points to. return 1; // Return TRUE. } Roomc::~Roomc() { } }
33.697674
164
0.665977
[ "object" ]
daa600ff3abb5ed862609cd4f5867666ab1e748c
12,223
cc
C++
test/utils/html5lib_tokenizer_test_helpers.cc
hooddanielc/yourhtml
ef0387743c62c89414c977f381f2a5be1133ba11
[ "MIT" ]
null
null
null
test/utils/html5lib_tokenizer_test_helpers.cc
hooddanielc/yourhtml
ef0387743c62c89414c977f381f2a5be1133ba11
[ "MIT" ]
null
null
null
test/utils/html5lib_tokenizer_test_helpers.cc
hooddanielc/yourhtml
ef0387743c62c89414c977f381f2a5be1133ba11
[ "MIT" ]
null
null
null
#include <test/utils/html5lib_tokenizer_test_helpers.h> using namespace yourhtml; void html5lib_test_lexer_t::on_character(const character_t &token) { if (tokens.size() > 0 && tokens.back()->get_kind() == token_t::CHARACTER) { auto data = dynamic_cast<character_t*>(tokens.back().get())->get_data(); tokens.back() = std::make_shared<character_t>( tokens.back()->get_pos(), (data + token.get_data()).c_str() ); } else { tokens.push_back(std::make_shared<character_t>(token)); } } void html5lib_test_lexer_t::on_eof(const eof_t &) {} void html5lib_test_lexer_t::on_parse_error(const lexer_error_t &error) { lexer_with_errors_t::on_parse_error(error); error_positions.push_back(error.get_pos()); } html5lib_tokenizer_test_t::~html5lib_tokenizer_test_t() = default; void print_json(const rapidjson::Value &val) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); val.Accept(writer); } testing::internal::ParamGenerator<html5lib_test_param_t> html5lib_test_params_in(const std::string &filename, const std::string &test_key) { std::unordered_map<std::string, token_t::kind_t> token_kind_map({ {"Comment", token_t::COMMENT}, {"DOCTYPE", token_t::DOCTYPE}, {"Character", token_t::CHARACTER}, {"StartTag", token_t::START_TAG}, {"EndTag", token_t::END_TAG} }); FILE* fp = fopen(filename.c_str(), "rb"); // non-Windows use "r" char readBuffer[65536]; rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer)); rapidjson::Document document; document.ParseStream(is); fclose(fp); if (!document[test_key.c_str()].IsArray()) { throw std::runtime_error("no tests array in json"); } auto tests = document[test_key.c_str()].GetArray(); std::vector<html5lib_test_param_t> lexer_test_params; for (rapidjson::SizeType i = 0; i < tests.Size(); ++i) { auto obj = tests[i].GetObject(); html5lib_test_param_t test_param = { "", "", "", std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, }; if (test_key == "xmlViolationTests") { test_param.replacement_chars = " "; test_param.form_feed_chars = " "; } if (obj.HasMember("description") && obj["description"].IsString()) { test_param.description = obj["description"].GetString(); } else { throw std::runtime_error("all lexer tests must have description string"); } if (obj.HasMember("input") && obj["input"].IsString()) { const char *str = obj["input"].GetString(); size_t size = obj["input"].GetStringLength(); test_param.input = std::string{ str, size }; } else { throw std::runtime_error("all lexer tests must have input string"); } test_param.id = testfs::path(filename).stem().string() + "_" + std::to_string(i); if (obj.HasMember("errors") && obj["errors"].IsArray()) { std::vector<std::pair<std::string, pos_t>> errors; auto errors_val = obj["errors"].GetArray(); for (rapidjson::SizeType ei = 0; ei < errors_val.Size(); ++ei) { int line = 0; int col = 0; std::string code = ""; if (!errors_val[ei].IsObject()) { throw std::runtime_error("errors array should contain only objects"); } auto error_val = errors_val[ei].GetObject(); if (error_val.HasMember("line") && error_val["line"].IsInt()) { line = error_val["line"].GetInt(); } else { throw std::runtime_error("errors object must contain line int"); } if (error_val.HasMember("col") && error_val["col"].IsInt()) { col = error_val["col"].GetInt(); } else { throw std::runtime_error("errors object must contain col int"); } if (error_val.HasMember("code") && error_val["code"].IsString()) { code = error_val["code"].GetString(); } else { throw std::runtime_error("errors object must contain code int"); } errors.push_back(std::make_pair(code, pos_t(line, col))); } test_param.errors = errors; } if (obj.HasMember("output") && obj["output"].IsArray()) { std::vector<std::shared_ptr<token_t>> tokens; auto output_val = obj["output"].GetArray(); for (rapidjson::SizeType oi = 0; oi < output_val.Size(); ++oi) { if (!output_val[oi].IsArray()) { throw std::runtime_error("output array must be a list of arrays"); } auto token_val = output_val[oi].GetArray(); if (token_val.Size() >= 1 && token_val[0].IsString()) { std::string token_kind_str = token_val[0].GetString(); auto kind = token_kind_map[token_kind_str]; switch (kind) { case token_t::COMMENT: { auto token = std::make_shared<comment_t>(); tokens.push_back(token); break; } case token_t::DOCTYPE: { auto token = std::make_shared<doctype_t>(); if (token_val.Size() >= 2 && token_val[1].IsString()) { token->set_doctype_name(token_val[1].GetString()); } if (token_val.Size() >= 3 && token_val[2].IsString()) { token->set_public_identifier(token_val[2].GetString()); } if (token_val.Size() >= 4 && token_val[3].IsString()) { token->set_system_identifier(token_val[3].GetString()); } if (token_val.Size() >= 5 && token_val[4].IsBool()) { token->set_force_quirks(!token_val[4].GetBool()); } tokens.push_back(token); break; } case token_t::CHARACTER: { std::string character_str; if (token_val.Size() < 2 || !token_val[1].IsString()) { throw std::runtime_error("character token in output must contain second string"); } character_str = token_val[1].GetString(); auto token = std::make_shared<character_t>(character_str); tokens.push_back(token); break; } case token_t::END_TAG: case token_t::START_TAG: { std::shared_ptr<tag_t> token; std::string tag_name; if (token_val.Size() < 2 || !token_val[1].IsString()) { throw std::runtime_error("start tag token in output must contain second string"); } if (kind == token_t::END_TAG) { token = std::make_shared<tag_t>(true); } else { token = std::make_shared<tag_t>(false); } tag_name = token_val[1].GetString(); token->append_tag_name(tag_name); if (token_val.Size() >= 3) { if (token_val[2].IsObject()) { auto attr_val = token_val[2].GetObject(); for (auto iter = attr_val.MemberBegin(); iter != attr_val.MemberEnd(); ++iter) { token->start_new_attribute(); token->append_attribute_name(std::string{iter->name.GetString(), iter->name.GetStringLength()}); token->append_attribute_value(std::string{iter->value.GetString(), iter->value.GetStringLength()}); } } else { throw std::runtime_error("tag token expected output 3rd item must be object"); } } if (token_val.Size() >= 4) { if (token_val[3].IsBool()) { auto self_closing = token_val[3].GetBool(); token->set_self_closing(self_closing); } else { throw std::runtime_error("tag token expected output 4th item must be boolean"); } } tokens.push_back(token); break; } case token_t::END_OF_FILE: { throw std::runtime_error("unexpected end of file in test"); } } } else { throw std::runtime_error("first item in token array must be a string"); } } test_param.output = tokens; } lexer_test_params.push_back(test_param); } return testing::ValuesIn(lexer_test_params.begin(), lexer_test_params.end()); } std::string html5lib_tokenizer_test_title_generator_t::operator()(const testing::TestParamInfo<html5lib_test_param_t> &test_param_info) { return test_param_info.param.id; } ::testing::AssertionResult has_lexer_error(html5lib_test_lexer_t &lexer, const std::string &code) { auto iter = std::find(lexer.error_types.begin(), lexer.error_types.end(), code); if (iter == lexer.error_types.end()) { return ::testing::AssertionFailure() << "expecting error code " << code << " but found none"; } else { return ::testing::AssertionSuccess() << "contains error code " << code; } } TEST_P(html5lib_tokenizer_test_t, tokenizes_as_expected) { auto param = GetParam(); auto test_info = ::testing::UnitTest::GetInstance()->current_test_info(); std::string name(test_info->test_case_name()); name += "."; name += test_info->name(); if (ignored_tests.count(name) > 0 && ignored_tests[name]) { param.ignored = true; } if (getenv("GTEST_FILTER")) { std::cout << "TESTING USING INPUT: ```" << std::endl; std::cout << "(" << param.input << std::endl << ")"; std::cout << "```" << std::endl; std::cout << "TOTAL INPUT SIZE: " << param.input.size() << std::endl; } else if (param.ignored) { std::cout << "WARNING SKIPPING TEST: " << param.id << std::endl; return; } html5lib_test_lexer_t lexer(param.input.c_str(), param.input.size()); lexer.lex(); if (param.errors) { if (getenv("GTEST_FILTER")) { for (auto actual_error: lexer.error_types) { std::cout << "ERROR ACTUAL: " << actual_error << std::endl; } for (auto expected_error: (*param.errors)) { std::cout << "EXPECTING ERROR: " << std::get<0>(expected_error) << std::endl; } } for (auto error_type: (*param.errors)) { auto str = std::get<0>(error_type); EXPECT_TRUE(has_lexer_error(lexer, str)); } if (getenv("GTEST_FILTER")) { if ((*param.errors).size() != lexer.error_types.size()) { std::cout << "Mismatching expected and actual tokenizer errors" << std::endl; } } } else { EXPECT_EQ(lexer.error_types.size(), size_t(0)); if (getenv("GTEST_FILTER")) { for (auto actual_error: lexer.error_types) { std::cout << "ERROR ACTUAL: " << actual_error << std::endl; } } } if (param.output) { auto expected = (*param.output); auto actual = lexer.tokens; EXPECT_EQ(actual.size(), expected.size()); for (size_t i = 0; i < actual.size(); ++i) { EXPECT_EQ(actual[i]->get_kind(), expected[i]->get_kind()); if (actual[i]->get_kind() == expected[i]->get_kind()) { switch (actual[i]->get_kind()) { case token_t::END_TAG: case token_t::START_TAG: { auto actual_token = dynamic_cast<tag_t*>(actual[i].get()); auto expected_token = dynamic_cast<tag_t*>(expected[i].get()); EXPECT_EQ(*actual_token, *expected_token); break; } case token_t::CHARACTER: { auto actual_token = dynamic_cast<character_t*>(actual[i].get()); auto expected_token = dynamic_cast<character_t*>(expected[i].get()); EXPECT_EQ(*actual_token, *expected_token); break; } case token_t::DOCTYPE: { auto actual_token = dynamic_cast<doctype_t*>(actual[i].get()); auto expected_token = dynamic_cast<doctype_t*>(expected[i].get()); EXPECT_EQ(*actual_token, *expected_token); break; } case token_t::COMMENT: case token_t::END_OF_FILE: {} } } else { EXPECT_EQ(actual[i]->get_kind(), expected[i]->get_kind()); } } } if (getenv("GTEST_FILTER")) { std::cout << "==========================" << std::endl; } }
38.077882
140
0.5785
[ "object", "vector" ]
dab43e809c5d6484c31461d6f92780543f50e225
631
cc
C++
skel/skel.cc
abhiranjankumar00/dot-vim
2e737f54df73443094f1c7641882e55623f00820
[ "MIT" ]
null
null
null
skel/skel.cc
abhiranjankumar00/dot-vim
2e737f54df73443094f1c7641882e55623f00820
[ "MIT" ]
1
2015-12-28T13:14:40.000Z
2015-12-28T13:15:26.000Z
skel/skel.cc
abhiranjankumar00/dot-vim
2e737f54df73443094f1c7641882e55623f00820
[ "MIT" ]
null
null
null
//Name : Shinchan Nohara //Age : 5 years //Organisation : Kasukabe Defense Force #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <list> #include <deque> #include <bitset> #include <functional> // Don't know why it is here. #include <numeric> // +1 #include <cassert> #include <utility> // +1 #include <sstream> #include <iomanip> #include <climits> #include <ctime> #include <iterator> #include <fstream> using namespace std; int main() { return 0; }
17.527778
51
0.681458
[ "vector" ]
dab4b067c4f56f744ef2781cb07402d970d21755
138,921
cpp
C++
qtdeclarative/src/quick/items/qquicktextinput.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtdeclarative/src/quick/items/qquicktextinput.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtdeclarative/src/quick/items/qquicktextinput.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qquicktextinput_p.h" #include "qquicktextinput_p_p.h" #include "qquickwindow.h" #include "qquicktextutil_p.h" #include <private/qqmlglobal_p.h> #include <QtCore/qcoreapplication.h> #include <QtCore/qmimedata.h> #include <QtQml/qqmlinfo.h> #include <QtGui/qevent.h> #include <QTextBoundaryFinder> #include "qquicktextnode_p.h" #include <QtQuick/qsgsimplerectnode.h> #include <QtGui/qstylehints.h> #include <QtGui/qinputmethod.h> #include <QtCore/qmath.h> #ifndef QT_NO_ACCESSIBILITY #include "qaccessible.h" #include "qquickaccessibleattached_p.h" #endif #include <QtGui/private/qtextengine_p.h> #include <QtGui/private/qinputcontrol_p.h> QT_BEGIN_NAMESPACE DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD) /*! \qmltype TextInput \instantiates QQuickTextInput \inqmlmodule QtQuick \ingroup qtquick-visual \ingroup qtquick-input \inherits Item \brief Displays an editable line of text The TextInput type displays a single line of editable plain text. TextInput is used to accept a line of text input. Input constraints can be placed on a TextInput item (for example, through a \l validator or \l inputMask), and setting \l echoMode to an appropriate value enables TextInput to be used for a password input field. On \macos, the Up/Down key bindings for Home/End are explicitly disabled. If you want such bindings (on any platform), you will need to construct them in QML. \sa TextEdit, Text */ QQuickTextInput::QQuickTextInput(QQuickItem* parent) : QQuickImplicitSizeItem(*(new QQuickTextInputPrivate), parent) { Q_D(QQuickTextInput); d->init(); } QQuickTextInput::QQuickTextInput(QQuickTextInputPrivate &dd, QQuickItem *parent) : QQuickImplicitSizeItem(dd, parent) { Q_D(QQuickTextInput); d->init(); } QQuickTextInput::~QQuickTextInput() { } void QQuickTextInput::componentComplete() { Q_D(QQuickTextInput); QQuickImplicitSizeItem::componentComplete(); d->checkIsValid(); d->updateLayout(); updateCursorRectangle(); if (d->cursorComponent && isCursorVisible()) QQuickTextUtil::createCursor(d); } /*! \qmlproperty string QtQuick::TextInput::text The text in the TextInput. */ QString QQuickTextInput::text() const { Q_D(const QQuickTextInput); QString content = d->m_text; QString res = d->m_maskData ? d->stripString(content) : content; return (res.isNull() ? QString::fromLatin1("") : res); } void QQuickTextInput::setText(const QString &s) { Q_D(QQuickTextInput); if (s == text()) return; #ifndef QT_NO_IM d->cancelPreedit(); #endif d->internalSetText(s, -1, false); } /*! \qmlproperty enumeration QtQuick::TextInput::renderType Override the default rendering type for this component. Supported render types are: \list \li Text.QtRendering - the default \li Text.NativeRendering \endlist Select Text.NativeRendering if you prefer text to look native on the target platform and do not require advanced features such as transformation of the text. Using such features in combination with the NativeRendering render type will lend poor and sometimes pixelated results. */ QQuickTextInput::RenderType QQuickTextInput::renderType() const { Q_D(const QQuickTextInput); return d->renderType; } void QQuickTextInput::setRenderType(QQuickTextInput::RenderType renderType) { Q_D(QQuickTextInput); if (d->renderType == renderType) return; d->renderType = renderType; emit renderTypeChanged(); if (isComponentComplete()) d->updateLayout(); } /*! \qmlproperty int QtQuick::TextInput::length Returns the total number of characters in the TextInput item. If the TextInput has an inputMask the length will include mask characters and may differ from the length of the string returned by the \l text property. This property can be faster than querying the length the \l text property as it doesn't require any copying or conversion of the TextInput's internal string data. */ int QQuickTextInput::length() const { Q_D(const QQuickTextInput); return d->m_text.length(); } /*! \qmlmethod string QtQuick::TextInput::getText(int start, int end) Returns the section of text that is between the \a start and \a end positions. If the TextInput has an inputMask the length will include mask characters. */ QString QQuickTextInput::getText(int start, int end) const { Q_D(const QQuickTextInput); if (start > end) qSwap(start, end); return d->m_text.mid(start, end - start); } QString QQuickTextInputPrivate::realText() const { QString res = m_maskData ? stripString(m_text) : m_text; return (res.isNull() ? QString::fromLatin1("") : res); } /*! \qmlproperty string QtQuick::TextInput::font.family Sets the family name of the font. The family name is case insensitive and may optionally include a foundry name, e.g. "Helvetica [Cronyx]". If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen. If the family isn't available a family will be set using the font matching algorithm. */ /*! \qmlproperty string QtQuick::TextInput::font.styleName \since 5.6 Sets the style name of the font. The style name is case insensitive. If set, the font will be matched against style name instead of the font properties \l font.weight, \l font.bold and \l font.italic. */ /*! \qmlproperty bool QtQuick::TextInput::font.bold Sets whether the font weight is bold. */ /*! \qmlproperty enumeration QtQuick::TextInput::font.weight Sets the font's weight. The weight can be one of: \list \li Font.Thin \li Font.Light \li Font.ExtraLight \li Font.Normal - the default \li Font.Medium \li Font.DemiBold \li Font.Bold \li Font.ExtraBold \li Font.Black \endlist \qml TextInput { text: "Hello"; font.weight: Font.DemiBold } \endqml */ /*! \qmlproperty bool QtQuick::TextInput::font.italic Sets whether the font has an italic style. */ /*! \qmlproperty bool QtQuick::TextInput::font.underline Sets whether the text is underlined. */ /*! \qmlproperty bool QtQuick::TextInput::font.strikeout Sets whether the font has a strikeout style. */ /*! \qmlproperty real QtQuick::TextInput::font.pointSize Sets the font size in points. The point size must be greater than zero. */ /*! \qmlproperty int QtQuick::TextInput::font.pixelSize Sets the font size in pixels. Using this function makes the font device dependent. Use \c pointSize to set the size of the font in a device independent manner. */ /*! \qmlproperty real QtQuick::TextInput::font.letterSpacing Sets the letter spacing for the font. Letter spacing changes the default spacing between individual letters in the font. A positive value increases the letter spacing by the corresponding pixels; a negative value decreases the spacing. */ /*! \qmlproperty real QtQuick::TextInput::font.wordSpacing Sets the word spacing for the font. Word spacing changes the default spacing between individual words. A positive value increases the word spacing by a corresponding amount of pixels, while a negative value decreases the inter-word spacing accordingly. */ /*! \qmlproperty enumeration QtQuick::TextInput::font.capitalization Sets the capitalization for the text. \list \li Font.MixedCase - This is the normal text rendering option where no capitalization change is applied. \li Font.AllUppercase - This alters the text to be rendered in all uppercase type. \li Font.AllLowercase - This alters the text to be rendered in all lowercase type. \li Font.SmallCaps - This alters the text to be rendered in small-caps type. \li Font.Capitalize - This alters the text to be rendered with the first character of each word as an uppercase character. \endlist \qml TextInput { text: "Hello"; font.capitalization: Font.AllLowercase } \endqml */ QFont QQuickTextInput::font() const { Q_D(const QQuickTextInput); return d->sourceFont; } void QQuickTextInput::setFont(const QFont &font) { Q_D(QQuickTextInput); if (d->sourceFont == font) return; d->sourceFont = font; QFont oldFont = d->font; d->font = font; if (d->font.pointSizeF() != -1) { // 0.5pt resolution qreal size = qRound(d->font.pointSizeF()*2.0); d->font.setPointSizeF(size/2.0); } if (oldFont != d->font) { d->updateLayout(); updateCursorRectangle(); #ifndef QT_NO_IM updateInputMethod(Qt::ImCursorRectangle | Qt::ImFont); #endif } emit fontChanged(d->sourceFont); } /*! \qmlproperty color QtQuick::TextInput::color The text color. */ QColor QQuickTextInput::color() const { Q_D(const QQuickTextInput); return d->color; } void QQuickTextInput::setColor(const QColor &c) { Q_D(QQuickTextInput); if (c != d->color) { d->color = c; d->textLayoutDirty = true; d->updateType = QQuickTextInputPrivate::UpdatePaintNode; polish(); update(); emit colorChanged(); } } /*! \qmlproperty color QtQuick::TextInput::selectionColor The text highlight color, used behind selections. */ QColor QQuickTextInput::selectionColor() const { Q_D(const QQuickTextInput); return d->selectionColor; } void QQuickTextInput::setSelectionColor(const QColor &color) { Q_D(QQuickTextInput); if (d->selectionColor == color) return; d->selectionColor = color; if (d->hasSelectedText()) { d->textLayoutDirty = true; d->updateType = QQuickTextInputPrivate::UpdatePaintNode; polish(); update(); } emit selectionColorChanged(); } /*! \qmlproperty color QtQuick::TextInput::selectedTextColor The highlighted text color, used in selections. */ QColor QQuickTextInput::selectedTextColor() const { Q_D(const QQuickTextInput); return d->selectedTextColor; } void QQuickTextInput::setSelectedTextColor(const QColor &color) { Q_D(QQuickTextInput); if (d->selectedTextColor == color) return; d->selectedTextColor = color; if (d->hasSelectedText()) { d->textLayoutDirty = true; d->updateType = QQuickTextInputPrivate::UpdatePaintNode; polish(); update(); } emit selectedTextColorChanged(); } /*! \qmlproperty enumeration QtQuick::TextInput::horizontalAlignment \qmlproperty enumeration QtQuick::TextInput::effectiveHorizontalAlignment \qmlproperty enumeration QtQuick::TextInput::verticalAlignment Sets the horizontal alignment of the text within the TextInput item's width and height. By default, the text alignment follows the natural alignment of the text, for example text that is read from left to right will be aligned to the left. TextInput does not have vertical alignment, as the natural height is exactly the height of the single line of text. If you set the height manually to something larger, TextInput will always be top aligned vertically. You can use anchors to align it however you want within another item. The valid values for \c horizontalAlignment are \c TextInput.AlignLeft, \c TextInput.AlignRight and \c TextInput.AlignHCenter. Valid values for \c verticalAlignment are \c TextInput.AlignTop (default), \c TextInput.AlignBottom \c TextInput.AlignVCenter. When using the attached property LayoutMirroring::enabled to mirror application layouts, the horizontal alignment of text will also be mirrored. However, the property \c horizontalAlignment will remain unchanged. To query the effective horizontal alignment of TextInput, use the read-only property \c effectiveHorizontalAlignment. */ QQuickTextInput::HAlignment QQuickTextInput::hAlign() const { Q_D(const QQuickTextInput); return d->hAlign; } void QQuickTextInput::setHAlign(HAlignment align) { Q_D(QQuickTextInput); bool forceAlign = d->hAlignImplicit && d->effectiveLayoutMirror; d->hAlignImplicit = false; if (d->setHAlign(align, forceAlign) && isComponentComplete()) { d->updateLayout(); updateCursorRectangle(); } } void QQuickTextInput::resetHAlign() { Q_D(QQuickTextInput); d->hAlignImplicit = true; if (d->determineHorizontalAlignment() && isComponentComplete()) { d->updateLayout(); updateCursorRectangle(); } } QQuickTextInput::HAlignment QQuickTextInput::effectiveHAlign() const { Q_D(const QQuickTextInput); QQuickTextInput::HAlignment effectiveAlignment = d->hAlign; if (!d->hAlignImplicit && d->effectiveLayoutMirror) { switch (d->hAlign) { case QQuickTextInput::AlignLeft: effectiveAlignment = QQuickTextInput::AlignRight; break; case QQuickTextInput::AlignRight: effectiveAlignment = QQuickTextInput::AlignLeft; break; default: break; } } return effectiveAlignment; } bool QQuickTextInputPrivate::setHAlign(QQuickTextInput::HAlignment alignment, bool forceAlign) { Q_Q(QQuickTextInput); if ((hAlign != alignment || forceAlign) && alignment <= QQuickTextInput::AlignHCenter) { // justify not supported QQuickTextInput::HAlignment oldEffectiveHAlign = q->effectiveHAlign(); hAlign = alignment; emit q->horizontalAlignmentChanged(alignment); if (oldEffectiveHAlign != q->effectiveHAlign()) emit q->effectiveHorizontalAlignmentChanged(); return true; } return false; } Qt::LayoutDirection QQuickTextInputPrivate::textDirection() const { QString text = m_text; #ifndef QT_NO_IM if (text.isEmpty()) text = m_textLayout.preeditAreaText(); #endif const QChar *character = text.constData(); while (!character->isNull()) { switch (character->direction()) { case QChar::DirL: return Qt::LeftToRight; case QChar::DirR: case QChar::DirAL: case QChar::DirAN: return Qt::RightToLeft; default: break; } character++; } return Qt::LayoutDirectionAuto; } Qt::LayoutDirection QQuickTextInputPrivate::layoutDirection() const { Qt::LayoutDirection direction = m_layoutDirection; if (direction == Qt::LayoutDirectionAuto) { direction = textDirection(); #ifndef QT_NO_IM if (direction == Qt::LayoutDirectionAuto) direction = QGuiApplication::inputMethod()->inputDirection(); #endif } return (direction == Qt::LayoutDirectionAuto) ? Qt::LeftToRight : direction; } bool QQuickTextInputPrivate::determineHorizontalAlignment() { if (hAlignImplicit) { // if no explicit alignment has been set, follow the natural layout direction of the text Qt::LayoutDirection direction = textDirection(); #ifndef QT_NO_IM if (direction == Qt::LayoutDirectionAuto) direction = QGuiApplication::inputMethod()->inputDirection(); #endif return setHAlign(direction == Qt::RightToLeft ? QQuickTextInput::AlignRight : QQuickTextInput::AlignLeft); } return false; } QQuickTextInput::VAlignment QQuickTextInput::vAlign() const { Q_D(const QQuickTextInput); return d->vAlign; } void QQuickTextInput::setVAlign(QQuickTextInput::VAlignment alignment) { Q_D(QQuickTextInput); if (alignment == d->vAlign) return; d->vAlign = alignment; emit verticalAlignmentChanged(d->vAlign); if (isComponentComplete()) { updateCursorRectangle(); d->updateBaselineOffset(); } } /*! \qmlproperty enumeration QtQuick::TextInput::wrapMode Set this property to wrap the text to the TextInput item's width. The text will only wrap if an explicit width has been set. \list \li TextInput.NoWrap - no wrapping will be performed. If the text contains insufficient newlines, then implicitWidth will exceed a set width. \li TextInput.WordWrap - wrapping is done on word boundaries only. If a word is too long, implicitWidth will exceed a set width. \li TextInput.WrapAnywhere - wrapping is done at any point on a line, even if it occurs in the middle of a word. \li TextInput.Wrap - if possible, wrapping occurs at a word boundary; otherwise it will occur at the appropriate point on the line, even in the middle of a word. \endlist The default is TextInput.NoWrap. If you set a width, consider using TextInput.Wrap. */ QQuickTextInput::WrapMode QQuickTextInput::wrapMode() const { Q_D(const QQuickTextInput); return d->wrapMode; } void QQuickTextInput::setWrapMode(WrapMode mode) { Q_D(QQuickTextInput); if (mode == d->wrapMode) return; d->wrapMode = mode; d->updateLayout(); updateCursorRectangle(); emit wrapModeChanged(); } void QQuickTextInputPrivate::mirrorChange() { Q_Q(QQuickTextInput); if (q->isComponentComplete()) { if (!hAlignImplicit && (hAlign == QQuickTextInput::AlignRight || hAlign == QQuickTextInput::AlignLeft)) { q->updateCursorRectangle(); emit q->effectiveHorizontalAlignmentChanged(); } } } /*! \qmlproperty bool QtQuick::TextInput::readOnly Sets whether user input can modify the contents of the TextInput. If readOnly is set to true, then user input will not affect the text property. Any bindings or attempts to set the text property will still work. */ bool QQuickTextInput::isReadOnly() const { Q_D(const QQuickTextInput); return d->m_readOnly; } void QQuickTextInput::setReadOnly(bool ro) { Q_D(QQuickTextInput); if (d->m_readOnly == ro) return; #ifndef QT_NO_IM setFlag(QQuickItem::ItemAcceptsInputMethod, !ro); #endif d->m_readOnly = ro; if (!ro) d->setCursorPosition(d->end()); #ifndef QT_NO_IM updateInputMethod(Qt::ImEnabled); #endif q_canPasteChanged(); d->emitUndoRedoChanged(); emit readOnlyChanged(ro); if (ro) { setCursorVisible(false); } else if (hasActiveFocus()) { setCursorVisible(true); } update(); } /*! \qmlproperty int QtQuick::TextInput::maximumLength The maximum permitted length of the text in the TextInput. If the text is too long, it is truncated at the limit. By default, this property contains a value of 32767. */ int QQuickTextInput::maxLength() const { Q_D(const QQuickTextInput); return d->m_maxLength; } void QQuickTextInput::setMaxLength(int ml) { Q_D(QQuickTextInput); if (d->m_maxLength == ml || d->m_maskData) return; d->m_maxLength = ml; d->internalSetText(d->m_text, -1, false); emit maximumLengthChanged(ml); } /*! \qmlproperty bool QtQuick::TextInput::cursorVisible Set to true when the TextInput shows a cursor. This property is set and unset when the TextInput gets active focus, so that other properties can be bound to whether the cursor is currently showing. As it gets set and unset automatically, when you set the value yourself you must keep in mind that your value may be overwritten. It can be set directly in script, for example if a KeyProxy might forward keys to it and you desire it to look active when this happens (but without actually giving it active focus). It should not be set directly on the item, like in the below QML, as the specified value will be overridden an lost on focus changes. \code TextInput { text: "Text" cursorVisible: false } \endcode In the above snippet the cursor will still become visible when the TextInput gains active focus. */ bool QQuickTextInput::isCursorVisible() const { Q_D(const QQuickTextInput); return d->cursorVisible; } void QQuickTextInput::setCursorVisible(bool on) { Q_D(QQuickTextInput); if (d->cursorVisible == on) return; d->cursorVisible = on; if (on && isComponentComplete()) QQuickTextUtil::createCursor(d); if (!d->cursorItem) { d->setCursorBlinkPeriod(on ? QGuiApplication::styleHints()->cursorFlashTime() : 0); d->updateType = QQuickTextInputPrivate::UpdatePaintNode; polish(); update(); } emit cursorVisibleChanged(d->cursorVisible); } /*! \qmlproperty int QtQuick::TextInput::cursorPosition The position of the cursor in the TextInput. */ int QQuickTextInput::cursorPosition() const { Q_D(const QQuickTextInput); return d->m_cursor; } void QQuickTextInput::setCursorPosition(int cp) { Q_D(QQuickTextInput); if (cp < 0 || cp > text().length()) return; d->moveCursor(cp); } /*! \qmlproperty rectangle QtQuick::TextInput::cursorRectangle The rectangle where the standard text cursor is rendered within the text input. Read only. The position and height of a custom cursorDelegate are updated to follow the cursorRectangle automatically when it changes. The width of the delegate is unaffected by changes in the cursor rectangle. */ QRectF QQuickTextInput::cursorRectangle() const { Q_D(const QQuickTextInput); int c = d->m_cursor; #ifndef QT_NO_IM c += d->m_preeditCursor; #endif if (d->m_echoMode == NoEcho) c = 0; QTextLine l = d->m_textLayout.lineForTextPosition(c); if (!l.isValid()) return QRectF(); qreal x = l.cursorToX(c) - d->hscroll + leftPadding(); qreal y = l.y() - d->vscroll + topPadding(); return QRectF(x, y, 1, l.height()); } /*! \qmlproperty int QtQuick::TextInput::selectionStart The cursor position before the first character in the current selection. This property is read-only. To change the selection, use select(start,end), selectAll(), or selectWord(). \sa selectionEnd, cursorPosition, selectedText */ int QQuickTextInput::selectionStart() const { Q_D(const QQuickTextInput); return d->lastSelectionStart; } /*! \qmlproperty int QtQuick::TextInput::selectionEnd The cursor position after the last character in the current selection. This property is read-only. To change the selection, use select(start,end), selectAll(), or selectWord(). \sa selectionStart, cursorPosition, selectedText */ int QQuickTextInput::selectionEnd() const { Q_D(const QQuickTextInput); return d->lastSelectionEnd; } /*! \qmlmethod QtQuick::TextInput::select(int start, int end) Causes the text from \a start to \a end to be selected. If either start or end is out of range, the selection is not changed. After calling this, selectionStart will become the lesser and selectionEnd will become the greater (regardless of the order passed to this method). \sa selectionStart, selectionEnd */ void QQuickTextInput::select(int start, int end) { Q_D(QQuickTextInput); if (start < 0 || end < 0 || start > d->m_text.length() || end > d->m_text.length()) return; d->setSelection(start, end-start); } /*! \qmlproperty string QtQuick::TextInput::selectedText This read-only property provides the text currently selected in the text input. It is equivalent to the following snippet, but is faster and easier to use. \js myTextInput.text.toString().substring(myTextInput.selectionStart, myTextInput.selectionEnd); \endjs */ QString QQuickTextInput::selectedText() const { Q_D(const QQuickTextInput); return d->selectedText(); } /*! \qmlproperty bool QtQuick::TextInput::activeFocusOnPress Whether the TextInput should gain active focus on a mouse press. By default this is set to true. */ bool QQuickTextInput::focusOnPress() const { Q_D(const QQuickTextInput); return d->focusOnPress; } void QQuickTextInput::setFocusOnPress(bool b) { Q_D(QQuickTextInput); if (d->focusOnPress == b) return; d->focusOnPress = b; emit activeFocusOnPressChanged(d->focusOnPress); } /*! \qmlproperty bool QtQuick::TextInput::autoScroll Whether the TextInput should scroll when the text is longer than the width. By default this is set to true. \sa ensureVisible() */ bool QQuickTextInput::autoScroll() const { Q_D(const QQuickTextInput); return d->autoScroll; } void QQuickTextInput::setAutoScroll(bool b) { Q_D(QQuickTextInput); if (d->autoScroll == b) return; d->autoScroll = b; //We need to repaint so that the scrolling is taking into account. updateCursorRectangle(); emit autoScrollChanged(d->autoScroll); } /*! \qmlproperty Validator QtQuick::TextInput::validator Allows you to set a validator on the TextInput. When a validator is set the TextInput will only accept input which leaves the text property in an acceptable or intermediate state. The accepted signal will only be sent if the text is in an acceptable state when enter is pressed. Currently supported validators are IntValidator, DoubleValidator and RegExpValidator. An example of using validators is shown below, which allows input of integers between 11 and 31 into the text input: \code import QtQuick 2.0 TextInput{ validator: IntValidator{bottom: 11; top: 31;} focus: true } \endcode \sa acceptableInput, inputMask */ QValidator* QQuickTextInput::validator() const { #ifdef QT_NO_VALIDATOR return 0; #else Q_D(const QQuickTextInput); return d->m_validator; #endif // QT_NO_VALIDATOR } void QQuickTextInput::setValidator(QValidator* v) { #ifdef QT_NO_VALIDATOR Q_UNUSED(v); #else Q_D(QQuickTextInput); if (d->m_validator == v) return; if (d->m_validator) { qmlobject_disconnect( d->m_validator, QValidator, SIGNAL(changed()), this, QQuickTextInput, SLOT(q_validatorChanged())); } d->m_validator = v; if (d->m_validator) { qmlobject_connect( d->m_validator, QValidator, SIGNAL(changed()), this, QQuickTextInput, SLOT(q_validatorChanged())); } if (isComponentComplete()) d->checkIsValid(); emit validatorChanged(); #endif // QT_NO_VALIDATOR } #ifndef QT_NO_VALIDATOR void QQuickTextInput::q_validatorChanged() { Q_D(QQuickTextInput); d->checkIsValid(); } #endif // QT_NO_VALIDATOR void QQuickTextInputPrivate::checkIsValid() { Q_Q(QQuickTextInput); ValidatorState state = hasAcceptableInput(m_text); m_validInput = state != InvalidInput; if (state != AcceptableInput) { if (m_acceptableInput) { m_acceptableInput = false; emit q->acceptableInputChanged(); } } else if (!m_acceptableInput) { m_acceptableInput = true; emit q->acceptableInputChanged(); } } /*! \qmlproperty string QtQuick::TextInput::inputMask Allows you to set an input mask on the TextInput, restricting the allowable text inputs. See QLineEdit::inputMask for further details, as the exact same mask strings are used by TextInput. \sa acceptableInput, validator */ QString QQuickTextInput::inputMask() const { Q_D(const QQuickTextInput); return d->inputMask(); } void QQuickTextInput::setInputMask(const QString &im) { Q_D(QQuickTextInput); if (d->inputMask() == im) return; d->setInputMask(im); emit inputMaskChanged(d->inputMask()); } /*! \qmlproperty bool QtQuick::TextInput::acceptableInput This property is always true unless a validator or input mask has been set. If a validator or input mask has been set, this property will only be true if the current text is acceptable to the validator or input mask as a final string (not as an intermediate string). */ bool QQuickTextInput::hasAcceptableInput() const { Q_D(const QQuickTextInput); return d->m_acceptableInput; } /*! \qmlsignal QtQuick::TextInput::accepted() This signal is emitted when the Return or Enter key is pressed. Note that if there is a \l validator or \l inputMask set on the text input, the signal will only be emitted if the input is in an acceptable state. The corresponding handler is \c onAccepted. */ /*! \qmlsignal QtQuick::TextInput::editingFinished() \since 5.2 This signal is emitted when the Return or Enter key is pressed or the text input loses focus. Note that if there is a validator or inputMask set on the text input and enter/return is pressed, this signal will only be emitted if the input follows the inputMask and the validator returns an acceptable state. The corresponding handler is \c onEditingFinished. */ #ifndef QT_NO_IM Qt::InputMethodHints QQuickTextInputPrivate::effectiveInputMethodHints() const { Qt::InputMethodHints hints = inputMethodHints; if (m_echoMode == QQuickTextInput::Password || m_echoMode == QQuickTextInput::NoEcho) hints |= Qt::ImhHiddenText; else if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit) hints &= ~Qt::ImhHiddenText; if (m_echoMode != QQuickTextInput::Normal) hints |= (Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText | Qt::ImhSensitiveData); return hints; } #endif /*! \qmlproperty enumeration QtQuick::TextInput::echoMode Specifies how the text should be displayed in the TextInput. \list \li TextInput.Normal - Displays the text as it is. (Default) \li TextInput.Password - Displays platform-dependent password mask characters instead of the actual characters. \li TextInput.NoEcho - Displays nothing. \li TextInput.PasswordEchoOnEdit - Displays characters as they are entered while editing, otherwise identical to \c TextInput.Password. \endlist */ QQuickTextInput::EchoMode QQuickTextInput::echoMode() const { Q_D(const QQuickTextInput); return QQuickTextInput::EchoMode(d->m_echoMode); } void QQuickTextInput::setEchoMode(QQuickTextInput::EchoMode echo) { Q_D(QQuickTextInput); if (echoMode() == echo) return; d->cancelPasswordEchoTimer(); d->m_echoMode = echo; d->m_passwordEchoEditing = false; #ifndef QT_NO_IM updateInputMethod(Qt::ImHints); #endif d->updateDisplayText(); updateCursorRectangle(); emit echoModeChanged(echoMode()); } /*! \qmlproperty enumeration QtQuick::TextInput::inputMethodHints Provides hints to the input method about the expected content of the text input and how it should operate. The value is a bit-wise combination of flags, or Qt.ImhNone if no hints are set. Flags that alter behaviour are: \list \li Qt.ImhHiddenText - Characters should be hidden, as is typically used when entering passwords. This is automatically set when setting echoMode to \c TextInput.Password. \li Qt.ImhSensitiveData - Typed text should not be stored by the active input method in any persistent storage like predictive user dictionary. \li Qt.ImhNoAutoUppercase - The input method should not try to automatically switch to upper case when a sentence ends. \li Qt.ImhPreferNumbers - Numbers are preferred (but not required). \li Qt.ImhPreferUppercase - Upper case letters are preferred (but not required). \li Qt.ImhPreferLowercase - Lower case letters are preferred (but not required). \li Qt.ImhNoPredictiveText - Do not use predictive text (i.e. dictionary lookup) while typing. \li Qt.ImhDate - The text editor functions as a date field. \li Qt.ImhTime - The text editor functions as a time field. \li Qt.ImhMultiLine - The text editor doesn't close software input keyboard when Return or Enter key is pressed (since QtQuick 2.4). \endlist Flags that restrict input (exclusive flags) are: \list \li Qt.ImhDigitsOnly - Only digits are allowed. \li Qt.ImhFormattedNumbersOnly - Only number input is allowed. This includes decimal point and minus sign. \li Qt.ImhUppercaseOnly - Only upper case letter input is allowed. \li Qt.ImhLowercaseOnly - Only lower case letter input is allowed. \li Qt.ImhDialableCharactersOnly - Only characters suitable for phone dialing are allowed. \li Qt.ImhEmailCharactersOnly - Only characters suitable for email addresses are allowed. \li Qt.ImhUrlCharactersOnly - Only characters suitable for URLs are allowed. \endlist Masks: \list \li Qt.ImhExclusiveInputMask - This mask yields nonzero if any of the exclusive flags are used. \endlist */ Qt::InputMethodHints QQuickTextInput::inputMethodHints() const { #ifdef QT_NO_IM return Qt::ImhNone; #else Q_D(const QQuickTextInput); return d->inputMethodHints; #endif // QT_NO_IM } void QQuickTextInput::setInputMethodHints(Qt::InputMethodHints hints) { #ifdef QT_NO_IM Q_UNUSED(hints); #else Q_D(QQuickTextInput); if (hints == d->inputMethodHints) return; d->inputMethodHints = hints; updateInputMethod(Qt::ImHints); emit inputMethodHintsChanged(); #endif // QT_NO_IM } /*! \qmlproperty Component QtQuick::TextInput::cursorDelegate The delegate for the cursor in the TextInput. If you set a cursorDelegate for a TextInput, this delegate will be used for drawing the cursor instead of the standard cursor. An instance of the delegate will be created and managed by the TextInput when a cursor is needed, and the x property of the delegate instance will be set so as to be one pixel before the top left of the current character. Note that the root item of the delegate component must be a QQuickItem or QQuickItem derived item. */ QQmlComponent* QQuickTextInput::cursorDelegate() const { Q_D(const QQuickTextInput); return d->cursorComponent; } void QQuickTextInput::setCursorDelegate(QQmlComponent* c) { Q_D(QQuickTextInput); QQuickTextUtil::setCursorDelegate(d, c); } void QQuickTextInput::createCursor() { Q_D(QQuickTextInput); d->cursorPending = true; QQuickTextUtil::createCursor(d); } /*! \qmlmethod rect QtQuick::TextInput::positionToRectangle(int pos) This function takes a character position and returns the rectangle that the cursor would occupy, if it was placed at that character position. This is similar to setting the cursorPosition, and then querying the cursor rectangle, but the cursorPosition is not changed. */ QRectF QQuickTextInput::positionToRectangle(int pos) const { Q_D(const QQuickTextInput); if (d->m_echoMode == NoEcho) pos = 0; #ifndef QT_NO_IM else if (pos > d->m_cursor) pos += d->preeditAreaText().length(); #endif QTextLine l = d->m_textLayout.lineForTextPosition(pos); if (!l.isValid()) return QRectF(); qreal x = l.cursorToX(pos) - d->hscroll; qreal y = l.y() - d->vscroll; return QRectF(x, y, 1, l.height()); } /*! \qmlmethod int QtQuick::TextInput::positionAt(real x, real y, CursorPosition position = CursorBetweenCharacters) This function returns the character position at x and y pixels from the top left of the textInput. Position 0 is before the first character, position 1 is after the first character but before the second, and so on until position text.length, which is after all characters. This means that for all x values before the first character this function returns 0, and for all x values after the last character this function returns text.length. If the y value is above the text the position will be that of the nearest character on the first line and if it is below the text the position of the nearest character on the last line will be returned. The cursor position type specifies how the cursor position should be resolved. \list \li TextInput.CursorBetweenCharacters - Returns the position between characters that is nearest x. \li TextInput.CursorOnCharacter - Returns the position before the character that is nearest x. \endlist */ void QQuickTextInput::positionAt(QQmlV4Function *args) const { Q_D(const QQuickTextInput); qreal x = 0; qreal y = 0; QTextLine::CursorPosition position = QTextLine::CursorBetweenCharacters; if (args->length() < 1) return; int i = 0; QV4::Scope scope(args->v4engine()); QV4::ScopedValue arg(scope, (*args)[0]); x = arg->toNumber(); if (++i < args->length()) { arg = (*args)[i]; y = arg->toNumber(); } if (++i < args->length()) { arg = (*args)[i]; position = QTextLine::CursorPosition(arg->toInt32()); } int pos = d->positionAt(x, y, position); const int cursor = d->m_cursor; if (pos > cursor) { #ifndef QT_NO_IM const int preeditLength = d->preeditAreaText().length(); pos = pos > cursor + preeditLength ? pos - preeditLength : cursor; #else pos = cursor; #endif } args->setReturnValue(QV4::Encode(pos)); } int QQuickTextInputPrivate::positionAt(qreal x, qreal y, QTextLine::CursorPosition position) const { Q_Q(const QQuickTextInput); x += hscroll - q->leftPadding(); y += vscroll - q->topPadding(); QTextLine line = m_textLayout.lineAt(0); for (int i = 1; i < m_textLayout.lineCount(); ++i) { QTextLine nextLine = m_textLayout.lineAt(i); if (y < (line.rect().bottom() + nextLine.y()) / 2) break; line = nextLine; } return line.isValid() ? line.xToCursor(x, position) : 0; } void QQuickTextInput::keyPressEvent(QKeyEvent* ev) { Q_D(QQuickTextInput); // Don't allow MacOSX up/down support, and we don't allow a completer. bool ignore = (ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) && ev->modifiers() == Qt::NoModifier; if (!ignore && (d->lastSelectionStart == d->lastSelectionEnd) && (ev->key() == Qt::Key_Right || ev->key() == Qt::Key_Left)) { // Ignore when moving off the end unless there is a selection, // because then moving will do something (deselect). int cursorPosition = d->m_cursor; if (cursorPosition == 0) ignore = ev->key() == (d->layoutDirection() == Qt::LeftToRight ? Qt::Key_Left : Qt::Key_Right); if (!ignore && cursorPosition == d->m_text.length()) ignore = ev->key() == (d->layoutDirection() == Qt::LeftToRight ? Qt::Key_Right : Qt::Key_Left); } if (ignore) { ev->ignore(); } else { d->processKeyEvent(ev); } if (!ev->isAccepted()) QQuickImplicitSizeItem::keyPressEvent(ev); } #ifndef QT_NO_IM void QQuickTextInput::inputMethodEvent(QInputMethodEvent *ev) { Q_D(QQuickTextInput); const bool wasComposing = d->hasImState; if (d->m_readOnly) { ev->ignore(); } else { d->processInputMethodEvent(ev); } if (!ev->isAccepted()) QQuickImplicitSizeItem::inputMethodEvent(ev); if (wasComposing != d->hasImState) emit inputMethodComposingChanged(); } #endif void QQuickTextInput::mouseDoubleClickEvent(QMouseEvent *event) { Q_D(QQuickTextInput); if (d->selectByMouse && event->button() == Qt::LeftButton) { #ifndef QT_NO_IM d->commitPreedit(); #endif int cursor = d->positionAt(event->localPos()); d->selectWordAtPos(cursor); event->setAccepted(true); if (!d->hasPendingTripleClick()) { d->tripleClickStartPoint = event->localPos(); d->tripleClickTimer.start(); } } else { if (d->sendMouseEventToInputContext(event)) return; QQuickImplicitSizeItem::mouseDoubleClickEvent(event); } } void QQuickTextInput::mousePressEvent(QMouseEvent *event) { Q_D(QQuickTextInput); d->pressPos = event->localPos(); if (d->sendMouseEventToInputContext(event)) return; if (d->selectByMouse) { setKeepMouseGrab(false); d->selectPressed = true; QPointF distanceVector = d->pressPos - d->tripleClickStartPoint; if (d->hasPendingTripleClick() && distanceVector.manhattanLength() < QGuiApplication::styleHints()->startDragDistance()) { event->setAccepted(true); selectAll(); return; } } bool mark = (event->modifiers() & Qt::ShiftModifier) && d->selectByMouse; int cursor = d->positionAt(event->localPos()); d->moveCursor(cursor, mark); if (d->focusOnPress && !qGuiApp->styleHints()->setFocusOnTouchRelease()) ensureActiveFocus(); event->setAccepted(true); } void QQuickTextInput::mouseMoveEvent(QMouseEvent *event) { Q_D(QQuickTextInput); if (d->selectPressed) { if (qAbs(int(event->localPos().x() - d->pressPos.x())) > QGuiApplication::styleHints()->startDragDistance()) setKeepMouseGrab(true); #ifndef QT_NO_IM if (d->composeMode()) { // start selection int startPos = d->positionAt(d->pressPos); int currentPos = d->positionAt(event->localPos()); if (startPos != currentPos) d->setSelection(startPos, currentPos - startPos); } else #endif { moveCursorSelection(d->positionAt(event->localPos()), d->mouseSelectionMode); } event->setAccepted(true); } else { QQuickImplicitSizeItem::mouseMoveEvent(event); } } void QQuickTextInput::mouseReleaseEvent(QMouseEvent *event) { Q_D(QQuickTextInput); if (d->sendMouseEventToInputContext(event)) return; if (d->selectPressed) { d->selectPressed = false; setKeepMouseGrab(false); } #ifndef QT_NO_CLIPBOARD if (QGuiApplication::clipboard()->supportsSelection()) { if (event->button() == Qt::LeftButton) { d->copy(QClipboard::Selection); } else if (!d->m_readOnly && event->button() == Qt::MidButton) { d->deselect(); d->insert(QGuiApplication::clipboard()->text(QClipboard::Selection)); } } #endif if (d->focusOnPress && qGuiApp->styleHints()->setFocusOnTouchRelease()) ensureActiveFocus(); if (!event->isAccepted()) QQuickImplicitSizeItem::mouseReleaseEvent(event); } bool QQuickTextInputPrivate::sendMouseEventToInputContext(QMouseEvent *event) { #if !defined QT_NO_IM if (composeMode()) { int tmp_cursor = positionAt(event->localPos()); int mousePos = tmp_cursor - m_cursor; if (mousePos >= 0 && mousePos <= m_textLayout.preeditAreaText().length()) { if (event->type() == QEvent::MouseButtonRelease) { QGuiApplication::inputMethod()->invokeAction(QInputMethod::Click, mousePos); } return true; } } #else Q_UNUSED(event); #endif return false; } void QQuickTextInput::mouseUngrabEvent() { Q_D(QQuickTextInput); d->selectPressed = false; setKeepMouseGrab(false); } bool QQuickTextInput::event(QEvent* ev) { #ifndef QT_NO_SHORTCUT Q_D(QQuickTextInput); if (ev->type() == QEvent::ShortcutOverride) { if (d->m_readOnly) return false; QKeyEvent* ke = static_cast<QKeyEvent*>(ev); if (ke == QKeySequence::Copy || ke == QKeySequence::Paste || ke == QKeySequence::Cut || ke == QKeySequence::Redo || ke == QKeySequence::Undo || ke == QKeySequence::MoveToNextWord || ke == QKeySequence::MoveToPreviousWord || ke == QKeySequence::MoveToStartOfDocument || ke == QKeySequence::MoveToEndOfDocument || ke == QKeySequence::SelectNextWord || ke == QKeySequence::SelectPreviousWord || ke == QKeySequence::SelectStartOfLine || ke == QKeySequence::SelectEndOfLine || ke == QKeySequence::SelectStartOfBlock || ke == QKeySequence::SelectEndOfBlock || ke == QKeySequence::SelectStartOfDocument || ke == QKeySequence::SelectAll || ke == QKeySequence::SelectEndOfDocument || ke == QKeySequence::DeleteCompleteLine) { ke->accept(); return true; } else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier || ke->modifiers() == Qt::KeypadModifier) { if (ke->key() < Qt::Key_Escape) { ke->accept(); return true; } else { switch (ke->key()) { case Qt::Key_Delete: case Qt::Key_Home: case Qt::Key_End: case Qt::Key_Backspace: case Qt::Key_Left: case Qt::Key_Right: ke->accept(); return true; default: break; } } } } #endif return QQuickImplicitSizeItem::event(ev); } void QQuickTextInput::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { Q_D(QQuickTextInput); if (!d->inLayout) { if (newGeometry.width() != oldGeometry.width()) d->updateLayout(); else if (newGeometry.height() != oldGeometry.height() && d->vAlign != QQuickTextInput::AlignTop) d->updateBaselineOffset(); updateCursorRectangle(); } QQuickImplicitSizeItem::geometryChanged(newGeometry, oldGeometry); } void QQuickTextInputPrivate::ensureVisible(int position, int preeditCursor, int preeditLength) { Q_Q(QQuickTextInput); QTextLine textLine = m_textLayout.lineForTextPosition(position + preeditCursor); const qreal width = qMax<qreal>(0, q->width() - q->leftPadding() - q->rightPadding()); qreal cix = 0; qreal widthUsed = 0; if (textLine.isValid()) { cix = textLine.cursorToX(position + preeditLength); const qreal cursorWidth = cix >= 0 ? cix : width - cix; widthUsed = qMax(textLine.naturalTextWidth(), cursorWidth); } int previousScroll = hscroll; if (widthUsed <= width) { hscroll = 0; } else { Q_ASSERT(textLine.isValid()); if (cix - hscroll >= width) { // text doesn't fit, cursor is to the right of br (scroll right) hscroll = cix - width; } else if (cix - hscroll < 0 && hscroll < widthUsed) { // text doesn't fit, cursor is to the left of br (scroll left) hscroll = cix; } else if (widthUsed - hscroll < width) { // text doesn't fit, text document is to the left of br; align // right hscroll = widthUsed - width; } else if (width - hscroll > widthUsed) { // text doesn't fit, text document is to the right of br; align // left hscroll = width - widthUsed; } #ifndef QT_NO_IM if (preeditLength > 0) { // check to ensure long pre-edit text doesn't push the cursor // off to the left cix = textLine.cursorToX(position + qMax(0, preeditCursor - 1)); if (cix < hscroll) hscroll = cix; } #endif } if (previousScroll != hscroll) textLayoutDirty = true; } void QQuickTextInputPrivate::updateHorizontalScroll() { if (autoScroll && m_echoMode != QQuickTextInput::NoEcho) { #ifndef QT_NO_IM const int preeditLength = m_textLayout.preeditAreaText().length(); ensureVisible(m_cursor, m_preeditCursor, preeditLength); #else ensureVisible(m_cursor); #endif } else { hscroll = 0; } } void QQuickTextInputPrivate::updateVerticalScroll() { Q_Q(QQuickTextInput); #ifndef QT_NO_IM const int preeditLength = m_textLayout.preeditAreaText().length(); #endif const qreal height = qMax<qreal>(0, q->height() - q->topPadding() - q->bottomPadding()); qreal heightUsed = contentSize.height(); qreal previousScroll = vscroll; if (!autoScroll || heightUsed <= height) { // text fits in br; use vscroll for alignment vscroll = -QQuickTextUtil::alignedY( heightUsed, height, vAlign & ~(Qt::AlignAbsolute|Qt::AlignHorizontal_Mask)); } else { #ifndef QT_NO_IM QTextLine currentLine = m_textLayout.lineForTextPosition(m_cursor + preeditLength); #else QTextLine currentLine = m_textLayout.lineForTextPosition(m_cursor); #endif QRectF r = currentLine.isValid() ? currentLine.rect() : QRectF(); qreal top = r.top(); int bottom = r.bottom(); if (bottom - vscroll >= height) { // text doesn't fit, cursor is to the below the br (scroll down) vscroll = bottom - height; } else if (top - vscroll < 0 && vscroll < heightUsed) { // text doesn't fit, cursor is above br (scroll up) vscroll = top; } else if (heightUsed - vscroll < height) { // text doesn't fit, text document is to the left of br; align // right vscroll = heightUsed - height; } #ifndef QT_NO_IM if (preeditLength > 0) { // check to ensure long pre-edit text doesn't push the cursor // off the top currentLine = m_textLayout.lineForTextPosition(m_cursor + qMax(0, m_preeditCursor - 1)); top = currentLine.isValid() ? currentLine.rect().top() : 0; if (top < vscroll) vscroll = top; } #endif } if (previousScroll != vscroll) textLayoutDirty = true; } void QQuickTextInput::triggerPreprocess() { Q_D(QQuickTextInput); if (d->updateType == QQuickTextInputPrivate::UpdateNone) d->updateType = QQuickTextInputPrivate::UpdateOnlyPreprocess; polish(); update(); } void QQuickTextInput::updatePolish() { invalidateFontCaches(); } void QQuickTextInput::invalidateFontCaches() { Q_D(QQuickTextInput); if (d->m_textLayout.engine() != 0) d->m_textLayout.engine()->resetFontEngineCache(); } void QQuickTextInput::ensureActiveFocus() { bool hadActiveFocus = hasActiveFocus(); forceActiveFocus(); #ifndef QT_NO_IM Q_D(QQuickTextInput); // re-open input panel on press if already focused if (hasActiveFocus() && hadActiveFocus && !d->m_readOnly) qGuiApp->inputMethod()->show(); #else Q_UNUSED(hadActiveFocus); #endif } QSGNode *QQuickTextInput::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data) { Q_UNUSED(data); Q_D(QQuickTextInput); if (d->updateType != QQuickTextInputPrivate::UpdatePaintNode && oldNode != 0) { // Update done in preprocess() in the nodes d->updateType = QQuickTextInputPrivate::UpdateNone; return oldNode; } d->updateType = QQuickTextInputPrivate::UpdateNone; QQuickTextNode *node = static_cast<QQuickTextNode *>(oldNode); if (node == 0) node = new QQuickTextNode(this); d->textNode = node; const bool showCursor = !isReadOnly() && d->cursorItem == 0 && d->cursorVisible && (d->m_blinkStatus || d->m_blinkPeriod == 0); if (!d->textLayoutDirty && oldNode != 0) { if (showCursor) node->setCursor(cursorRectangle(), d->color); else node->clearCursor(); } else { node->setUseNativeRenderer(d->renderType == NativeRendering); node->deleteContent(); node->setMatrix(QMatrix4x4()); QPointF offset(leftPadding(), topPadding()); if (d->autoScroll && d->m_textLayout.lineCount() > 0) { QFontMetricsF fm(d->font); // the y offset is there to keep the baseline constant in case we have script changes in the text. offset += -QPointF(d->hscroll, d->vscroll + d->m_textLayout.lineAt(0).ascent() - fm.ascent()); } else { offset += -QPointF(d->hscroll, d->vscroll); } if (!d->m_textLayout.text().isEmpty() #ifndef QT_NO_IM || !d->m_textLayout.preeditAreaText().isEmpty() #endif ) { node->addTextLayout(offset, &d->m_textLayout, d->color, QQuickText::Normal, QColor(), QColor(), d->selectionColor, d->selectedTextColor, d->selectionStart(), d->selectionEnd() - 1); // selectionEnd() returns first char after // selection } if (showCursor) node->setCursor(cursorRectangle(), d->color); d->textLayoutDirty = false; } invalidateFontCaches(); return node; } #ifndef QT_NO_IM QVariant QQuickTextInput::inputMethodQuery(Qt::InputMethodQuery property) const { return inputMethodQuery(property, QVariant()); } QVariant QQuickTextInput::inputMethodQuery(Qt::InputMethodQuery property, QVariant argument) const { Q_D(const QQuickTextInput); switch (property) { case Qt::ImEnabled: return QVariant((bool)(flags() & ItemAcceptsInputMethod)); case Qt::ImHints: return QVariant((int) d->effectiveInputMethodHints()); case Qt::ImCursorRectangle: return cursorRectangle(); case Qt::ImFont: return font(); case Qt::ImCursorPosition: return QVariant(d->m_cursor); case Qt::ImSurroundingText: if (d->m_echoMode == PasswordEchoOnEdit && !d->m_passwordEchoEditing) { return QVariant(displayText()); } else { return QVariant(d->realText()); } case Qt::ImCurrentSelection: return QVariant(selectedText()); case Qt::ImMaximumTextLength: return QVariant(maxLength()); case Qt::ImAnchorPosition: if (d->selectionStart() == d->selectionEnd()) return QVariant(d->m_cursor); else if (d->selectionStart() == d->m_cursor) return QVariant(d->selectionEnd()); else return QVariant(d->selectionStart()); case Qt::ImAbsolutePosition: return QVariant(d->m_cursor); case Qt::ImTextAfterCursor: if (argument.isValid()) return QVariant(d->m_text.mid(d->m_cursor, argument.toInt())); return QVariant(d->m_text.mid(d->m_cursor)); case Qt::ImTextBeforeCursor: if (argument.isValid()) return QVariant(d->m_text.left(d->m_cursor).right(argument.toInt())); return QVariant(d->m_text.left(d->m_cursor)); default: return QQuickItem::inputMethodQuery(property); } } #endif // QT_NO_IM /*! \qmlmethod QtQuick::TextInput::deselect() Removes active text selection. */ void QQuickTextInput::deselect() { Q_D(QQuickTextInput); d->deselect(); } /*! \qmlmethod QtQuick::TextInput::selectAll() Causes all text to be selected. */ void QQuickTextInput::selectAll() { Q_D(QQuickTextInput); d->setSelection(0, text().length()); } /*! \qmlmethod QtQuick::TextInput::isRightToLeft(int start, int end) Returns true if the natural reading direction of the editor text found between positions \a start and \a end is right to left. */ bool QQuickTextInput::isRightToLeft(int start, int end) { if (start > end) { qmlInfo(this) << "isRightToLeft(start, end) called with the end property being smaller than the start."; return false; } else { return text().mid(start, end - start).isRightToLeft(); } } #ifndef QT_NO_CLIPBOARD /*! \qmlmethod QtQuick::TextInput::cut() Moves the currently selected text to the system clipboard. \note If the echo mode is set to a mode other than Normal then cut will not work. This is to prevent using cut as a method of bypassing password features of the line control. */ void QQuickTextInput::cut() { Q_D(QQuickTextInput); if (!d->m_readOnly && d->m_echoMode == QQuickTextInput::Normal) { d->copy(); d->del(); } } /*! \qmlmethod QtQuick::TextInput::copy() Copies the currently selected text to the system clipboard. \note If the echo mode is set to a mode other than Normal then copy will not work. This is to prevent using copy as a method of bypassing password features of the line control. */ void QQuickTextInput::copy() { Q_D(QQuickTextInput); d->copy(); } /*! \qmlmethod QtQuick::TextInput::paste() Replaces the currently selected text by the contents of the system clipboard. */ void QQuickTextInput::paste() { Q_D(QQuickTextInput); if (!d->m_readOnly) d->paste(); } #endif // QT_NO_CLIPBOARD /*! \qmlmethod QtQuick::TextInput::undo() Undoes the last operation if undo is \l {canUndo}{available}. Deselects any current selection, and updates the selection start to the current cursor position. */ void QQuickTextInput::undo() { Q_D(QQuickTextInput); if (!d->m_readOnly) { d->internalUndo(); d->finishChange(-1, true); } } /*! \qmlmethod QtQuick::TextInput::redo() Redoes the last operation if redo is \l {canRedo}{available}. */ void QQuickTextInput::redo() { Q_D(QQuickTextInput); if (!d->m_readOnly) { d->internalRedo(); d->finishChange(); } } /*! \qmlmethod QtQuick::TextInput::insert(int position, string text) Inserts \a text into the TextInput at position. */ void QQuickTextInput::insert(int position, const QString &text) { Q_D(QQuickTextInput); if (d->m_echoMode == QQuickTextInput::Password) { if (d->m_passwordMaskDelay > 0) d->m_passwordEchoTimer.start(d->m_passwordMaskDelay, this); } if (position < 0 || position > d->m_text.length()) return; const int priorState = d->m_undoState; QString insertText = text; if (d->hasSelectedText()) { d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::SetSelection, d->m_cursor, 0, d->m_selstart, d->m_selend)); } if (d->m_maskData) { insertText = d->maskString(position, insertText); for (int i = 0; i < insertText.length(); ++i) { d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::DeleteSelection, position + i, d->m_text.at(position + i), -1, -1)); d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::Insert, position + i, insertText.at(i), -1, -1)); } d->m_text.replace(position, insertText.length(), insertText); if (!insertText.isEmpty()) d->m_textDirty = true; if (position < d->m_selend && position + insertText.length() > d->m_selstart) d->m_selDirty = true; } else { int remaining = d->m_maxLength - d->m_text.length(); if (remaining != 0) { insertText = insertText.left(remaining); d->m_text.insert(position, insertText); for (int i = 0; i < insertText.length(); ++i) d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::Insert, position + i, insertText.at(i), -1, -1)); if (d->m_cursor >= position) d->m_cursor += insertText.length(); if (d->m_selstart >= position) d->m_selstart += insertText.length(); if (d->m_selend >= position) d->m_selend += insertText.length(); d->m_textDirty = true; if (position >= d->m_selstart && position <= d->m_selend) d->m_selDirty = true; } } d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::SetSelection, d->m_cursor, 0, d->m_selstart, d->m_selend)); d->finishChange(priorState); if (d->lastSelectionStart != d->lastSelectionEnd) { if (d->m_selstart != d->lastSelectionStart) { d->lastSelectionStart = d->m_selstart; emit selectionStartChanged(); } if (d->m_selend != d->lastSelectionEnd) { d->lastSelectionEnd = d->m_selend; emit selectionEndChanged(); } } } /*! \qmlmethod QtQuick::TextInput::remove(int start, int end) Removes the section of text that is between the \a start and \a end positions from the TextInput. */ void QQuickTextInput::remove(int start, int end) { Q_D(QQuickTextInput); start = qBound(0, start, d->m_text.length()); end = qBound(0, end, d->m_text.length()); if (start > end) qSwap(start, end); else if (start == end) return; if (start < d->m_selend && end > d->m_selstart) d->m_selDirty = true; const int priorState = d->m_undoState; d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::SetSelection, d->m_cursor, 0, d->m_selstart, d->m_selend)); if (start <= d->m_cursor && d->m_cursor < end) { // cursor is within the selection. Split up the commands // to be able to restore the correct cursor position for (int i = d->m_cursor; i >= start; --i) { d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::DeleteSelection, i, d->m_text.at(i), -1, 1)); } for (int i = end - 1; i > d->m_cursor; --i) { d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::DeleteSelection, i - d->m_cursor + start - 1, d->m_text.at(i), -1, -1)); } } else { for (int i = end - 1; i >= start; --i) { d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::RemoveSelection, i, d->m_text.at(i), -1, -1)); } } if (d->m_maskData) { d->m_text.replace(start, end - start, d->clearString(start, end - start)); for (int i = 0; i < end - start; ++i) { d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::Insert, start + i, d->m_text.at(start + i), -1, -1)); } } else { d->m_text.remove(start, end - start); if (d->m_cursor > start) d->m_cursor -= qMin(d->m_cursor, end) - start; if (d->m_selstart > start) d->m_selstart -= qMin(d->m_selstart, end) - start; if (d->m_selend > end) d->m_selend -= qMin(d->m_selend, end) - start; } d->addCommand(QQuickTextInputPrivate::Command( QQuickTextInputPrivate::SetSelection, d->m_cursor, 0, d->m_selstart, d->m_selend)); d->m_textDirty = true; d->finishChange(priorState); if (d->lastSelectionStart != d->lastSelectionEnd) { if (d->m_selstart != d->lastSelectionStart) { d->lastSelectionStart = d->m_selstart; emit selectionStartChanged(); } if (d->m_selend != d->lastSelectionEnd) { d->lastSelectionEnd = d->m_selend; emit selectionEndChanged(); } } } /*! \qmlmethod QtQuick::TextInput::selectWord() Causes the word closest to the current cursor position to be selected. */ void QQuickTextInput::selectWord() { Q_D(QQuickTextInput); d->selectWordAtPos(d->m_cursor); } /*! \qmlproperty string QtQuick::TextInput::passwordCharacter This is the character displayed when echoMode is set to Password or PasswordEchoOnEdit. By default it is the password character used by the platform theme. If this property is set to a string with more than one character, the first character is used. If the string is empty, the value is ignored and the property is not set. */ QString QQuickTextInput::passwordCharacter() const { Q_D(const QQuickTextInput); return QString(d->m_passwordCharacter); } void QQuickTextInput::setPasswordCharacter(const QString &str) { Q_D(QQuickTextInput); if (str.length() < 1) return; d->m_passwordCharacter = str.constData()[0]; if (d->m_echoMode == Password || d->m_echoMode == PasswordEchoOnEdit) d->updateDisplayText(); emit passwordCharacterChanged(); } /*! \qmlproperty int QtQuick::TextInput::passwordMaskDelay \since 5.4 Sets the delay before visible character is masked with password character, in milliseconds. The reset method will be called by assigning undefined. */ int QQuickTextInput::passwordMaskDelay() const { Q_D(const QQuickTextInput); return d->m_passwordMaskDelay; } void QQuickTextInput::setPasswordMaskDelay(int delay) { Q_D(QQuickTextInput); if (d->m_passwordMaskDelay != delay) { d->m_passwordMaskDelay = delay; emit passwordMaskDelayChanged(delay); } } void QQuickTextInput::resetPasswordMaskDelay() { setPasswordMaskDelay(qGuiApp->styleHints()->passwordMaskDelay()); } /*! \qmlproperty string QtQuick::TextInput::displayText This is the text displayed in the TextInput. If \l echoMode is set to TextInput::Normal, this holds the same value as the TextInput::text property. Otherwise, this property holds the text visible to the user, while the \l text property holds the actual entered text. \note Unlike the TextInput::text property, this contains partial text input from an input method. \readonly */ QString QQuickTextInput::displayText() const { Q_D(const QQuickTextInput); return d->m_textLayout.text().insert(d->m_textLayout.preeditAreaPosition(), d->m_textLayout.preeditAreaText()); } /*! \qmlproperty bool QtQuick::TextInput::selectByMouse Defaults to false. If true, the user can use the mouse to select text in some platform-specific way. Note that for some platforms this may not be an appropriate interaction (it may conflict with how the text needs to behave inside a \l Flickable, for example). */ bool QQuickTextInput::selectByMouse() const { Q_D(const QQuickTextInput); return d->selectByMouse; } void QQuickTextInput::setSelectByMouse(bool on) { Q_D(QQuickTextInput); if (d->selectByMouse != on) { d->selectByMouse = on; emit selectByMouseChanged(on); } } /*! \qmlproperty enumeration QtQuick::TextInput::mouseSelectionMode Specifies how text should be selected using a mouse. \list \li TextInput.SelectCharacters - The selection is updated with individual characters. (Default) \li TextInput.SelectWords - The selection is updated with whole words. \endlist This property only applies when \l selectByMouse is true. */ QQuickTextInput::SelectionMode QQuickTextInput::mouseSelectionMode() const { Q_D(const QQuickTextInput); return d->mouseSelectionMode; } void QQuickTextInput::setMouseSelectionMode(SelectionMode mode) { Q_D(QQuickTextInput); if (d->mouseSelectionMode != mode) { d->mouseSelectionMode = mode; emit mouseSelectionModeChanged(mode); } } /*! \qmlproperty bool QtQuick::TextInput::persistentSelection Whether the TextInput should keep its selection when it loses active focus to another item in the scene. By default this is set to false; */ bool QQuickTextInput::persistentSelection() const { Q_D(const QQuickTextInput); return d->persistentSelection; } void QQuickTextInput::setPersistentSelection(bool on) { Q_D(QQuickTextInput); if (d->persistentSelection == on) return; d->persistentSelection = on; emit persistentSelectionChanged(); } /*! \qmlproperty bool QtQuick::TextInput::canPaste Returns true if the TextInput is writable and the content of the clipboard is suitable for pasting into the TextInput. */ bool QQuickTextInput::canPaste() const { #if !defined(QT_NO_CLIPBOARD) Q_D(const QQuickTextInput); if (!d->canPasteValid) { if (const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData()) const_cast<QQuickTextInputPrivate *>(d)->canPaste = !d->m_readOnly && mimeData->hasText(); const_cast<QQuickTextInputPrivate *>(d)->canPasteValid = true; } return d->canPaste; #else return false; #endif } /*! \qmlproperty bool QtQuick::TextInput::canUndo Returns true if the TextInput is writable and there are previous operations that can be undone. */ bool QQuickTextInput::canUndo() const { Q_D(const QQuickTextInput); return d->canUndo; } /*! \qmlproperty bool QtQuick::TextInput::canRedo Returns true if the TextInput is writable and there are \l {undo}{undone} operations that can be redone. */ bool QQuickTextInput::canRedo() const { Q_D(const QQuickTextInput); return d->canRedo; } /*! \qmlproperty real QtQuick::TextInput::contentWidth Returns the width of the text, including the width past the width which is covered due to insufficient wrapping if \l wrapMode is set. */ qreal QQuickTextInput::contentWidth() const { Q_D(const QQuickTextInput); return d->contentSize.width(); } /*! \qmlproperty real QtQuick::TextInput::contentHeight Returns the height of the text, including the height past the height that is covered if the text does not fit within the set height. */ qreal QQuickTextInput::contentHeight() const { Q_D(const QQuickTextInput); return d->contentSize.height(); } void QQuickTextInput::moveCursorSelection(int position) { Q_D(QQuickTextInput); d->moveCursor(position, true); } /*! \qmlmethod QtQuick::TextInput::moveCursorSelection(int position, SelectionMode mode = TextInput.SelectCharacters) Moves the cursor to \a position and updates the selection according to the optional \a mode parameter. (To only move the cursor, set the \l cursorPosition property.) When this method is called it additionally sets either the selectionStart or the selectionEnd (whichever was at the previous cursor position) to the specified position. This allows you to easily extend and contract the selected text range. The selection mode specifies whether the selection is updated on a per character or a per word basis. If not specified the selection mode will default to TextInput.SelectCharacters. \list \li TextInput.SelectCharacters - Sets either the selectionStart or selectionEnd (whichever was at the previous cursor position) to the specified position. \li TextInput.SelectWords - Sets the selectionStart and selectionEnd to include all words between the specified position and the previous cursor position. Words partially in the range are included. \endlist For example, take this sequence of calls: \code cursorPosition = 5 moveCursorSelection(9, TextInput.SelectCharacters) moveCursorSelection(7, TextInput.SelectCharacters) \endcode This moves the cursor to position 5, extend the selection end from 5 to 9 and then retract the selection end from 9 to 7, leaving the text from position 5 to 7 selected (the 6th and 7th characters). The same sequence with TextInput.SelectWords will extend the selection start to a word boundary before or on position 5 and extend the selection end to a word boundary on or past position 9. */ void QQuickTextInput::moveCursorSelection(int pos, SelectionMode mode) { Q_D(QQuickTextInput); if (mode == SelectCharacters) { d->moveCursor(pos, true); } else if (pos != d->m_cursor){ const int cursor = d->m_cursor; int anchor; if (!d->hasSelectedText()) anchor = d->m_cursor; else if (d->selectionStart() == d->m_cursor) anchor = d->selectionEnd(); else anchor = d->selectionStart(); if (anchor < pos || (anchor == pos && cursor < pos)) { const QString text = this->text(); QTextBoundaryFinder finder(QTextBoundaryFinder::Word, text); finder.setPosition(anchor); const QTextBoundaryFinder::BoundaryReasons reasons = finder.boundaryReasons(); if (anchor < text.length() && (reasons == QTextBoundaryFinder::NotAtBoundary || (reasons & QTextBoundaryFinder::EndOfItem))) { finder.toPreviousBoundary(); } anchor = finder.position() != -1 ? finder.position() : 0; finder.setPosition(pos); if (pos > 0 && !finder.boundaryReasons()) finder.toNextBoundary(); const int cursor = finder.position() != -1 ? finder.position() : text.length(); d->setSelection(anchor, cursor - anchor); } else if (anchor > pos || (anchor == pos && cursor > pos)) { const QString text = this->text(); QTextBoundaryFinder finder(QTextBoundaryFinder::Word, text); finder.setPosition(anchor); const QTextBoundaryFinder::BoundaryReasons reasons = finder.boundaryReasons(); if (anchor > 0 && (reasons == QTextBoundaryFinder::NotAtBoundary || (reasons & QTextBoundaryFinder::StartOfItem))) { finder.toNextBoundary(); } anchor = finder.position() != -1 ? finder.position() : text.length(); finder.setPosition(pos); if (pos < text.length() && !finder.boundaryReasons()) finder.toPreviousBoundary(); const int cursor = finder.position() != -1 ? finder.position() : 0; d->setSelection(anchor, cursor - anchor); } } } void QQuickTextInput::focusInEvent(QFocusEvent *event) { Q_D(QQuickTextInput); d->handleFocusEvent(event); QQuickImplicitSizeItem::focusInEvent(event); } void QQuickTextInputPrivate::handleFocusEvent(QFocusEvent *event) { Q_Q(QQuickTextInput); bool focus = event->gotFocus(); if (!m_readOnly) q->setCursorVisible(focus); if (focus) { q->q_updateAlignment(); #ifndef QT_NO_IM if (focusOnPress && !m_readOnly) qGuiApp->inputMethod()->show(); q->connect(QGuiApplication::inputMethod(), SIGNAL(inputDirectionChanged(Qt::LayoutDirection)), q, SLOT(q_updateAlignment())); #endif } else { if ((m_passwordEchoEditing || m_passwordEchoTimer.isActive())) { updatePasswordEchoEditing(false);//QQuickTextInputPrivate sets it on key events, but doesn't deal with focus events } if (event->reason() != Qt::ActiveWindowFocusReason && event->reason() != Qt::PopupFocusReason && hasSelectedText() && !persistentSelection) deselect(); if (hasAcceptableInput(m_text) == AcceptableInput || fixup()) emit q->editingFinished(); #ifndef QT_NO_IM q->disconnect(QGuiApplication::inputMethod(), SIGNAL(inputDirectionChanged(Qt::LayoutDirection)), q, SLOT(q_updateAlignment())); #endif } } void QQuickTextInput::focusOutEvent(QFocusEvent *event) { Q_D(QQuickTextInput); d->handleFocusEvent(event); QQuickImplicitSizeItem::focusOutEvent(event); } /*! \qmlproperty bool QtQuick::TextInput::inputMethodComposing This property holds whether the TextInput has partial text input from an input method. While it is composing an input method may rely on mouse or key events from the TextInput to edit or commit the partial text. This property can be used to determine when to disable events handlers that may interfere with the correct operation of an input method. */ bool QQuickTextInput::isInputMethodComposing() const { #ifdef QT_NO_IM return false; #else Q_D(const QQuickTextInput); return d->hasImState; #endif } QQuickTextInputPrivate::ExtraData::ExtraData() : padding(0) , topPadding(0) , leftPadding(0) , rightPadding(0) , bottomPadding(0) , explicitTopPadding(false) , explicitLeftPadding(false) , explicitRightPadding(false) , explicitBottomPadding(false) , implicitResize(true) { } void QQuickTextInputPrivate::init() { Q_Q(QQuickTextInput); #ifndef QT_NO_CLIPBOARD if (QGuiApplication::clipboard()->supportsSelection()) q->setAcceptedMouseButtons(Qt::LeftButton | Qt::MiddleButton); else #endif q->setAcceptedMouseButtons(Qt::LeftButton); #ifndef QT_NO_IM q->setFlag(QQuickItem::ItemAcceptsInputMethod); #endif q->setFlag(QQuickItem::ItemHasContents); #ifndef QT_NO_CLIPBOARD q->connect(QGuiApplication::clipboard(), SIGNAL(dataChanged()), q, SLOT(q_canPasteChanged())); #endif // QT_NO_CLIPBOARD lastSelectionStart = 0; lastSelectionEnd = 0; determineHorizontalAlignment(); if (!qmlDisableDistanceField()) { QTextOption option = m_textLayout.textOption(); option.setUseDesignMetrics(renderType != QQuickTextInput::NativeRendering); m_textLayout.setTextOption(option); } m_inputControl = new QInputControl(QInputControl::LineEdit, q); } void QQuickTextInput::updateCursorRectangle(bool scroll) { Q_D(QQuickTextInput); if (!isComponentComplete()) return; if (scroll) { d->updateHorizontalScroll(); d->updateVerticalScroll(); } d->updateType = QQuickTextInputPrivate::UpdatePaintNode; polish(); update(); emit cursorRectangleChanged(); if (d->cursorItem) { QRectF r = cursorRectangle(); d->cursorItem->setPosition(r.topLeft()); d->cursorItem->setHeight(r.height()); } #ifndef QT_NO_IM updateInputMethod(Qt::ImCursorRectangle); #endif } void QQuickTextInput::selectionChanged() { Q_D(QQuickTextInput); d->textLayoutDirty = true; //TODO: Only update rect in selection d->updateType = QQuickTextInputPrivate::UpdatePaintNode; polish(); update(); emit selectedTextChanged(); if (d->lastSelectionStart != d->selectionStart()) { d->lastSelectionStart = d->selectionStart(); if (d->lastSelectionStart == -1) d->lastSelectionStart = d->m_cursor; emit selectionStartChanged(); } if (d->lastSelectionEnd != d->selectionEnd()) { d->lastSelectionEnd = d->selectionEnd(); if (d->lastSelectionEnd == -1) d->lastSelectionEnd = d->m_cursor; emit selectionEndChanged(); } } QRectF QQuickTextInput::boundingRect() const { Q_D(const QQuickTextInput); int cursorWidth = d->cursorItem ? 0 : 1; qreal hscroll = d->hscroll; if (!d->autoScroll || d->contentSize.width() < width()) hscroll -= QQuickTextUtil::alignedX(d->contentSize.width(), width(), effectiveHAlign()); // Could include font max left/right bearings to either side of rectangle. QRectF r(-hscroll, -d->vscroll, d->contentSize.width(), d->contentSize.height()); r.setRight(r.right() + cursorWidth); return r; } QRectF QQuickTextInput::clipRect() const { Q_D(const QQuickTextInput); int cursorWidth = d->cursorItem ? d->cursorItem->width() : 1; // Could include font max left/right bearings to either side of rectangle. QRectF r = QQuickImplicitSizeItem::clipRect(); r.setRight(r.right() + cursorWidth); return r; } void QQuickTextInput::q_canPasteChanged() { Q_D(QQuickTextInput); bool old = d->canPaste; #ifndef QT_NO_CLIPBOARD if (const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData()) d->canPaste = !d->m_readOnly && mimeData->hasText(); else d->canPaste = false; #endif bool changed = d->canPaste != old || !d->canPasteValid; d->canPasteValid = true; if (changed) emit canPasteChanged(); } void QQuickTextInput::q_updateAlignment() { Q_D(QQuickTextInput); if (d->determineHorizontalAlignment()) { d->updateLayout(); updateCursorRectangle(); } } /*! \internal Updates the display text based of the current edit text If the text has changed will emit displayTextChanged() */ void QQuickTextInputPrivate::updateDisplayText(bool forceUpdate) { QString orig = m_textLayout.text(); QString str; if (m_echoMode == QQuickTextInput::NoEcho) str = QString::fromLatin1(""); else str = m_text; if (m_echoMode == QQuickTextInput::Password) { str.fill(m_passwordCharacter); if (m_passwordEchoTimer.isActive() && m_cursor > 0 && m_cursor <= m_text.length()) { int cursor = m_cursor - 1; QChar uc = m_text.at(cursor); str[cursor] = uc; if (cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) { // second half of a surrogate, check if we have the first half as well, // if yes restore both at once uc = m_text.at(cursor - 1); if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) str[cursor - 1] = uc; } } } else if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit && !m_passwordEchoEditing) { str.fill(m_passwordCharacter); } // replace certain non-printable characters with spaces (to avoid // drawing boxes when using fonts that don't have glyphs for such // characters) QChar* uc = str.data(); for (int i = 0; i < (int)str.length(); ++i) { if ((uc[i] < 0x20 && uc[i] != 0x09) || uc[i] == QChar::LineSeparator || uc[i] == QChar::ParagraphSeparator || uc[i] == QChar::ObjectReplacementCharacter) uc[i] = QChar(0x0020); } if (str != orig || forceUpdate) { m_textLayout.setText(str); updateLayout(); // polish? emit q_func()->displayTextChanged(); } } qreal QQuickTextInputPrivate::getImplicitWidth() const { Q_Q(const QQuickTextInput); if (!requireImplicitWidth) { QQuickTextInputPrivate *d = const_cast<QQuickTextInputPrivate *>(this); d->requireImplicitWidth = true; if (q->isComponentComplete()) { // One time cost, only incurred if implicitWidth is first requested after // componentComplete. QTextLayout layout(m_text); QTextOption option = m_textLayout.textOption(); option.setTextDirection(m_layoutDirection); option.setFlags(QTextOption::IncludeTrailingSpaces); option.setWrapMode(QTextOption::WrapMode(wrapMode)); option.setAlignment(Qt::Alignment(q->effectiveHAlign())); layout.setTextOption(option); layout.setFont(font); #ifndef QT_NO_IM layout.setPreeditArea(m_textLayout.preeditAreaPosition(), m_textLayout.preeditAreaText()); #endif layout.beginLayout(); QTextLine line = layout.createLine(); line.setLineWidth(INT_MAX); d->implicitWidth = qCeil(line.naturalTextWidth()) + q->leftPadding() + q->rightPadding(); layout.endLayout(); } } return implicitWidth; } void QQuickTextInputPrivate::setTopPadding(qreal value, bool reset) { Q_Q(QQuickTextInput); qreal oldPadding = q->topPadding(); if (!reset || extra.isAllocated()) { extra.value().topPadding = value; extra.value().explicitTopPadding = !reset; } if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) { updateLayout(); emit q->topPaddingChanged(); } } void QQuickTextInputPrivate::setLeftPadding(qreal value, bool reset) { Q_Q(QQuickTextInput); qreal oldPadding = q->leftPadding(); if (!reset || extra.isAllocated()) { extra.value().leftPadding = value; extra.value().explicitLeftPadding = !reset; } if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) { updateLayout(); emit q->leftPaddingChanged(); } } void QQuickTextInputPrivate::setRightPadding(qreal value, bool reset) { Q_Q(QQuickTextInput); qreal oldPadding = q->rightPadding(); if (!reset || extra.isAllocated()) { extra.value().rightPadding = value; extra.value().explicitRightPadding = !reset; } if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) { updateLayout(); emit q->rightPaddingChanged(); } } void QQuickTextInputPrivate::setBottomPadding(qreal value, bool reset) { Q_Q(QQuickTextInput); qreal oldPadding = q->bottomPadding(); if (!reset || extra.isAllocated()) { extra.value().bottomPadding = value; extra.value().explicitBottomPadding = !reset; } if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) { updateLayout(); emit q->bottomPaddingChanged(); } } bool QQuickTextInputPrivate::isImplicitResizeEnabled() const { return !extra.isAllocated() || extra->implicitResize; } void QQuickTextInputPrivate::setImplicitResizeEnabled(bool enabled) { if (!enabled) extra.value().implicitResize = false; else if (extra.isAllocated()) extra->implicitResize = true; } void QQuickTextInputPrivate::updateLayout() { Q_Q(QQuickTextInput); if (!q->isComponentComplete()) return; QTextOption option = m_textLayout.textOption(); option.setTextDirection(layoutDirection()); option.setWrapMode(QTextOption::WrapMode(wrapMode)); option.setAlignment(Qt::Alignment(q->effectiveHAlign())); if (!qmlDisableDistanceField()) option.setUseDesignMetrics(renderType != QQuickTextInput::NativeRendering); m_textLayout.setTextOption(option); m_textLayout.setFont(font); m_textLayout.beginLayout(); QTextLine line = m_textLayout.createLine(); if (requireImplicitWidth) { line.setLineWidth(INT_MAX); const bool wasInLayout = inLayout; inLayout = true; if (isImplicitResizeEnabled()) q->setImplicitWidth(qCeil(line.naturalTextWidth()) + q->leftPadding() + q->rightPadding()); inLayout = wasInLayout; if (inLayout) // probably the result of a binding loop, but by letting it return; // get this far we'll get a warning to that effect. } qreal lineWidth = q->widthValid() ? q->width() - q->leftPadding() - q->rightPadding() : INT_MAX; qreal height = 0; qreal width = 0; do { line.setLineWidth(lineWidth); line.setPosition(QPointF(0, height)); height += line.height(); width = qMax(width, line.naturalTextWidth()); line = m_textLayout.createLine(); } while (line.isValid()); m_textLayout.endLayout(); option.setWrapMode(QTextOption::NoWrap); m_textLayout.setTextOption(option); textLayoutDirty = true; const QSizeF previousSize = contentSize; contentSize = QSizeF(width, height); updateType = UpdatePaintNode; q->polish(); q->update(); if (isImplicitResizeEnabled()) { if (!requireImplicitWidth && !q->widthValid()) q->setImplicitSize(width + q->leftPadding() + q->rightPadding(), height + q->topPadding() + q->bottomPadding()); else q->setImplicitHeight(height + q->topPadding() + q->bottomPadding()); } updateBaselineOffset(); if (previousSize != contentSize) emit q->contentSizeChanged(); } /*! \internal \brief QQuickTextInputPrivate::updateBaselineOffset Assumes contentSize.height() is already calculated. */ void QQuickTextInputPrivate::updateBaselineOffset() { Q_Q(QQuickTextInput); if (!q->isComponentComplete()) return; QFontMetricsF fm(font); qreal yoff = 0; if (q->heightValid()) { const qreal surplusHeight = q->height() - contentSize.height() - q->topPadding() - q->bottomPadding(); if (vAlign == QQuickTextInput::AlignBottom) yoff = surplusHeight; else if (vAlign == QQuickTextInput::AlignVCenter) yoff = surplusHeight/2; } q->setBaselineOffset(fm.ascent() + yoff + q->topPadding()); } #ifndef QT_NO_CLIPBOARD /*! \internal Copies the currently selected text into the clipboard using the given \a mode. \note If the echo mode is set to a mode other than Normal then copy will not work. This is to prevent using copy as a method of bypassing password features of the line control. */ void QQuickTextInputPrivate::copy(QClipboard::Mode mode) const { QString t = selectedText(); if (!t.isEmpty() && m_echoMode == QQuickTextInput::Normal) { QGuiApplication::clipboard()->setText(t, mode); } } /*! \internal Inserts the text stored in the application clipboard into the line control. \sa insert() */ void QQuickTextInputPrivate::paste(QClipboard::Mode clipboardMode) { QString clip = QGuiApplication::clipboard()->text(clipboardMode); if (!clip.isEmpty() || hasSelectedText()) { separate(); //make it a separate undo/redo command insert(clip); separate(); } } #endif // !QT_NO_CLIPBOARD #ifndef QT_NO_IM /*! \internal */ void QQuickTextInputPrivate::commitPreedit() { Q_Q(QQuickTextInput); if (!hasImState) return; QGuiApplication::inputMethod()->commit(); if (!hasImState) return; QInputMethodEvent ev; QCoreApplication::sendEvent(q, &ev); } void QQuickTextInputPrivate::cancelPreedit() { Q_Q(QQuickTextInput); if (!hasImState) return; QGuiApplication::inputMethod()->reset(); QInputMethodEvent ev; QCoreApplication::sendEvent(q, &ev); } #endif // QT_NO_IM /*! \internal Handles the behavior for the backspace key or function. Removes the current selection if there is a selection, otherwise removes the character prior to the cursor position. \sa del() */ void QQuickTextInputPrivate::backspace() { int priorState = m_undoState; if (separateSelection()) { removeSelectedText(); } else if (m_cursor) { --m_cursor; if (m_maskData) m_cursor = prevMaskBlank(m_cursor); QChar uc = m_text.at(m_cursor); if (m_cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) { // second half of a surrogate, check if we have the first half as well, // if yes delete both at once uc = m_text.at(m_cursor - 1); if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) { internalDelete(true); --m_cursor; } } internalDelete(true); } finishChange(priorState); } /*! \internal Handles the behavior for the delete key or function. Removes the current selection if there is a selection, otherwise removes the character after the cursor position. \sa del() */ void QQuickTextInputPrivate::del() { int priorState = m_undoState; if (separateSelection()) { removeSelectedText(); } else { int n = m_textLayout.nextCursorPosition(m_cursor) - m_cursor; while (n--) internalDelete(); } finishChange(priorState); } /*! \internal Inserts the given \a newText at the current cursor position. If there is any selected text it is removed prior to insertion of the new text. */ void QQuickTextInputPrivate::insert(const QString &newText) { int priorState = m_undoState; if (separateSelection()) removeSelectedText(); internalInsert(newText); finishChange(priorState); } /*! \internal Clears the line control text. */ void QQuickTextInputPrivate::clear() { int priorState = m_undoState; separateSelection(); m_selstart = 0; m_selend = m_text.length(); removeSelectedText(); separate(); finishChange(priorState, /*update*/false, /*edited*/false); } /*! \internal Sets \a length characters from the given \a start position as selected. The given \a start position must be within the current text for the line control. If \a length characters cannot be selected, then the selection will extend to the end of the current text. */ void QQuickTextInputPrivate::setSelection(int start, int length) { Q_Q(QQuickTextInput); #ifndef QT_NO_IM commitPreedit(); #endif if (start < 0 || start > (int)m_text.length()){ qWarning("QQuickTextInputPrivate::setSelection: Invalid start position"); return; } if (length > 0) { if (start == m_selstart && start + length == m_selend && m_cursor == m_selend) return; m_selstart = start; m_selend = qMin(start + length, (int)m_text.length()); m_cursor = m_selend; } else if (length < 0){ if (start == m_selend && start + length == m_selstart && m_cursor == m_selstart) return; m_selstart = qMax(start + length, 0); m_selend = start; m_cursor = m_selstart; } else if (m_selstart != m_selend) { m_selstart = 0; m_selend = 0; m_cursor = start; } else { m_cursor = start; emitCursorPositionChanged(); return; } emit q->selectionChanged(); emitCursorPositionChanged(); #ifndef QT_NO_IM q->updateInputMethod(Qt::ImCursorRectangle | Qt::ImAnchorPosition | Qt::ImCursorPosition | Qt::ImCurrentSelection); #endif } /*! \internal Sets the password echo editing to \a editing. If password echo editing is true, then the text of the password is displayed even if the echo mode is set to QLineEdit::PasswordEchoOnEdit. Password echoing editing does not affect other echo modes. */ void QQuickTextInputPrivate::updatePasswordEchoEditing(bool editing) { cancelPasswordEchoTimer(); m_passwordEchoEditing = editing; updateDisplayText(); } /*! \internal Fixes the current text so that it is valid given any set validators. Returns true if the text was changed. Otherwise returns false. */ bool QQuickTextInputPrivate::fixup() // this function assumes that validate currently returns != Acceptable { #ifndef QT_NO_VALIDATOR if (m_validator) { QString textCopy = m_text; int cursorCopy = m_cursor; m_validator->fixup(textCopy); if (m_validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) { if (textCopy != m_text || cursorCopy != m_cursor) internalSetText(textCopy, cursorCopy); return true; } } #endif return false; } /*! \internal Moves the cursor to the given position \a pos. If \a mark is true will adjust the currently selected text. */ void QQuickTextInputPrivate::moveCursor(int pos, bool mark) { Q_Q(QQuickTextInput); #ifndef QT_NO_IM commitPreedit(); #endif if (pos != m_cursor) { separate(); if (m_maskData) pos = pos > m_cursor ? nextMaskBlank(pos) : prevMaskBlank(pos); } if (mark) { int anchor; if (m_selend > m_selstart && m_cursor == m_selstart) anchor = m_selend; else if (m_selend > m_selstart && m_cursor == m_selend) anchor = m_selstart; else anchor = m_cursor; m_selstart = qMin(anchor, pos); m_selend = qMax(anchor, pos); } else { internalDeselect(); } m_cursor = pos; if (mark || m_selDirty) { m_selDirty = false; emit q->selectionChanged(); } emitCursorPositionChanged(); #ifndef QT_NO_IM q->updateInputMethod(); #endif } #ifndef QT_NO_IM /*! \internal Applies the given input method event \a event to the text of the line control */ void QQuickTextInputPrivate::processInputMethodEvent(QInputMethodEvent *event) { Q_Q(QQuickTextInput); int priorState = -1; bool isGettingInput = !event->commitString().isEmpty() || event->preeditString() != preeditAreaText() || event->replacementLength() > 0; bool cursorPositionChanged = false; bool selectionChange = false; m_preeditDirty = event->preeditString() != preeditAreaText(); if (isGettingInput) { // If any text is being input, remove selected text. priorState = m_undoState; separateSelection(); if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit && !m_passwordEchoEditing) { updatePasswordEchoEditing(true); m_selstart = 0; m_selend = m_text.length(); } removeSelectedText(); } int c = m_cursor; // cursor position after insertion of commit string if (event->replacementStart() <= 0) c += event->commitString().length() - qMin(-event->replacementStart(), event->replacementLength()); m_cursor += event->replacementStart(); if (m_cursor < 0) m_cursor = 0; // insert commit string if (event->replacementLength()) { m_selstart = m_cursor; m_selend = m_selstart + event->replacementLength(); m_selend = qMin(m_selend, m_text.length()); removeSelectedText(); } if (!event->commitString().isEmpty()) { internalInsert(event->commitString()); cursorPositionChanged = true; } m_cursor = qBound(0, c, m_text.length()); for (int i = 0; i < event->attributes().size(); ++i) { const QInputMethodEvent::Attribute &a = event->attributes().at(i); if (a.type == QInputMethodEvent::Selection) { m_cursor = qBound(0, a.start + a.length, m_text.length()); if (a.length) { m_selstart = qMax(0, qMin(a.start, m_text.length())); m_selend = m_cursor; if (m_selend < m_selstart) { qSwap(m_selstart, m_selend); } selectionChange = true; } else { m_selstart = m_selend = 0; } cursorPositionChanged = true; } } m_textLayout.setPreeditArea(m_cursor, event->preeditString()); const int oldPreeditCursor = m_preeditCursor; m_preeditCursor = event->preeditString().length(); hasImState = !event->preeditString().isEmpty(); bool cursorVisible = true; QVector<QTextLayout::FormatRange> formats; for (int i = 0; i < event->attributes().size(); ++i) { const QInputMethodEvent::Attribute &a = event->attributes().at(i); if (a.type == QInputMethodEvent::Cursor) { hasImState = true; m_preeditCursor = a.start; cursorVisible = a.length != 0; } else if (a.type == QInputMethodEvent::TextFormat) { hasImState = true; QTextCharFormat f = qvariant_cast<QTextFormat>(a.value).toCharFormat(); if (f.isValid()) { QTextLayout::FormatRange o; o.start = a.start + m_cursor; o.length = a.length; o.format = f; formats.append(o); } } } m_textLayout.setFormats(formats); updateDisplayText(/*force*/ true); if ((cursorPositionChanged && !emitCursorPositionChanged()) || m_preeditCursor != oldPreeditCursor || isGettingInput) { q->updateCursorRectangle(); } if (isGettingInput) finishChange(priorState); q->setCursorVisible(cursorVisible); if (selectionChange) { emit q->selectionChanged(); q->updateInputMethod(Qt::ImCursorRectangle | Qt::ImAnchorPosition | Qt::ImCursorPosition | Qt::ImCurrentSelection); } } #endif // QT_NO_IM /*! \internal Sets the selection to cover the word at the given cursor position. The word boundaries are defined by the behavior of QTextLayout::SkipWords cursor mode. */ void QQuickTextInputPrivate::selectWordAtPos(int cursor) { int next = cursor + 1; if (next > end()) --next; int c = m_textLayout.previousCursorPosition(next, QTextLayout::SkipWords); moveCursor(c, false); // ## text layout should support end of words. int end = m_textLayout.nextCursorPosition(c, QTextLayout::SkipWords); while (end > cursor && m_text[end-1].isSpace()) --end; moveCursor(end, true); } /*! \internal Completes a change to the line control text. If the change is not valid will undo the line control state back to the given \a validateFromState. If \a edited is true and the change is valid, will emit textEdited() in addition to textChanged(). Otherwise only emits textChanged() on a valid change. The \a update value is currently unused. */ bool QQuickTextInputPrivate::finishChange(int validateFromState, bool update, bool /*edited*/) { Q_Q(QQuickTextInput); Q_UNUSED(update) #ifndef QT_NO_IM bool inputMethodAttributesChanged = m_textDirty || m_selDirty; #endif bool alignmentChanged = false; bool textChanged = false; if (m_textDirty) { // do validation bool wasValidInput = m_validInput; bool wasAcceptable = m_acceptableInput; m_validInput = true; m_acceptableInput = true; #ifndef QT_NO_VALIDATOR if (m_validator) { QString textCopy = m_text; int cursorCopy = m_cursor; QValidator::State state = m_validator->validate(textCopy, cursorCopy); m_validInput = state != QValidator::Invalid; m_acceptableInput = state == QValidator::Acceptable; if (m_validInput) { if (m_text != textCopy) { internalSetText(textCopy, cursorCopy); return true; } m_cursor = cursorCopy; } } #endif if (m_maskData) { if (m_text.length() != m_maxLength) { m_acceptableInput = false; } else { for (int i = 0; i < m_maxLength; ++i) { if (m_maskData[i].separator) { if (m_text.at(i) != m_maskData[i].maskChar) { m_acceptableInput = false; break; } } else { if (!isValidInput(m_text.at(i), m_maskData[i].maskChar)) { m_acceptableInput = false; break; } } } } } if (validateFromState >= 0 && wasValidInput && !m_validInput) { if (m_transactions.count()) return false; internalUndo(validateFromState); m_history.resize(m_undoState); m_validInput = true; m_acceptableInput = wasAcceptable; m_textDirty = false; } if (m_textDirty) { textChanged = true; m_textDirty = false; #ifndef QT_NO_IM m_preeditDirty = false; #endif alignmentChanged = determineHorizontalAlignment(); emit q->textChanged(); } updateDisplayText(alignmentChanged); if (m_acceptableInput != wasAcceptable) emit q->acceptableInputChanged(); } #ifndef QT_NO_IM if (m_preeditDirty) { m_preeditDirty = false; if (determineHorizontalAlignment()) { alignmentChanged = true; updateLayout(); } } #endif if (m_selDirty) { m_selDirty = false; emit q->selectionChanged(); } #ifndef QT_NO_IM inputMethodAttributesChanged |= (m_cursor != m_lastCursorPos); if (inputMethodAttributesChanged) q->updateInputMethod(); #endif emitUndoRedoChanged(); if (!emitCursorPositionChanged() && (alignmentChanged || textChanged)) q->updateCursorRectangle(); return true; } /*! \internal An internal function for setting the text of the line control. */ void QQuickTextInputPrivate::internalSetText(const QString &txt, int pos, bool edited) { internalDeselect(); QString oldText = m_text; if (m_maskData) { m_text = maskString(0, txt, true); m_text += clearString(m_text.length(), m_maxLength - m_text.length()); } else { m_text = txt.isEmpty() ? txt : txt.left(m_maxLength); } m_history.clear(); m_undoState = 0; m_cursor = (pos < 0 || pos > m_text.length()) ? m_text.length() : pos; m_textDirty = (oldText != m_text); bool changed = finishChange(-1, true, edited); #ifdef QT_NO_ACCESSIBILITY Q_UNUSED(changed) #else Q_Q(QQuickTextInput); if (changed && QAccessible::isActive()) { if (QObject *acc = QQuickAccessibleAttached::findAccessible(q, QAccessible::EditableText)) { QAccessibleTextUpdateEvent ev(acc, 0, oldText, m_text); QAccessible::updateAccessibility(&ev); } } #endif } /*! \internal Adds the given \a command to the undo history of the line control. Does not apply the command. */ void QQuickTextInputPrivate::addCommand(const Command &cmd) { if (m_separator && m_undoState && m_history[m_undoState - 1].type != Separator) { m_history.resize(m_undoState + 2); m_history[m_undoState++] = Command(Separator, m_cursor, 0, m_selstart, m_selend); } else { m_history.resize(m_undoState + 1); } m_separator = false; m_history[m_undoState++] = cmd; } /*! \internal Inserts the given string \a s into the line control. Also adds the appropriate commands into the undo history. This function does not call finishChange(), and may leave the text in an invalid state. */ void QQuickTextInputPrivate::internalInsert(const QString &s) { Q_Q(QQuickTextInput); if (m_echoMode == QQuickTextInput::Password) { if (m_passwordMaskDelay > 0) m_passwordEchoTimer.start(m_passwordMaskDelay, q); } Q_ASSERT(!hasSelectedText()); // insert(), processInputMethodEvent() call removeSelectedText() first. if (m_maskData) { QString ms = maskString(m_cursor, s); for (int i = 0; i < (int) ms.length(); ++i) { addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1)); addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1)); } m_text.replace(m_cursor, ms.length(), ms); m_cursor += ms.length(); m_cursor = nextMaskBlank(m_cursor); m_textDirty = true; } else { int remaining = m_maxLength - m_text.length(); if (remaining != 0) { m_text.insert(m_cursor, s.left(remaining)); for (int i = 0; i < (int) s.left(remaining).length(); ++i) addCommand(Command(Insert, m_cursor++, s.at(i), -1, -1)); m_textDirty = true; } } } /*! \internal deletes a single character from the current text. If \a wasBackspace, the character prior to the cursor is removed. Otherwise the character after the cursor is removed. Also adds the appropriate commands into the undo history. This function does not call finishChange(), and may leave the text in an invalid state. */ void QQuickTextInputPrivate::internalDelete(bool wasBackspace) { if (m_cursor < (int) m_text.length()) { cancelPasswordEchoTimer(); Q_ASSERT(!hasSelectedText()); // del(), backspace() call removeSelectedText() first. addCommand(Command((CommandType)((m_maskData ? 2 : 0) + (wasBackspace ? Remove : Delete)), m_cursor, m_text.at(m_cursor), -1, -1)); if (m_maskData) { m_text.replace(m_cursor, 1, clearString(m_cursor, 1)); addCommand(Command(Insert, m_cursor, m_text.at(m_cursor), -1, -1)); } else { m_text.remove(m_cursor, 1); } m_textDirty = true; } } /*! \internal removes the currently selected text from the line control. Also adds the appropriate commands into the undo history. This function does not call finishChange(), and may leave the text in an invalid state. */ void QQuickTextInputPrivate::removeSelectedText() { if (m_selstart < m_selend && m_selend <= (int) m_text.length()) { cancelPasswordEchoTimer(); int i ; if (m_selstart <= m_cursor && m_cursor < m_selend) { // cursor is within the selection. Split up the commands // to be able to restore the correct cursor position for (i = m_cursor; i >= m_selstart; --i) addCommand (Command(DeleteSelection, i, m_text.at(i), -1, 1)); for (i = m_selend - 1; i > m_cursor; --i) addCommand (Command(DeleteSelection, i - m_cursor + m_selstart - 1, m_text.at(i), -1, -1)); } else { for (i = m_selend-1; i >= m_selstart; --i) addCommand (Command(RemoveSelection, i, m_text.at(i), -1, -1)); } if (m_maskData) { m_text.replace(m_selstart, m_selend - m_selstart, clearString(m_selstart, m_selend - m_selstart)); for (int i = 0; i < m_selend - m_selstart; ++i) addCommand(Command(Insert, m_selstart + i, m_text.at(m_selstart + i), -1, -1)); } else { m_text.remove(m_selstart, m_selend - m_selstart); } if (m_cursor > m_selstart) m_cursor -= qMin(m_cursor, m_selend) - m_selstart; internalDeselect(); m_textDirty = true; } } /*! \internal Adds the current selection to the undo history. Returns true if there is a current selection and false otherwise. */ bool QQuickTextInputPrivate::separateSelection() { if (hasSelectedText()) { separate(); addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); return true; } else { return false; } } /*! \internal Parses the input mask specified by \a maskFields to generate the mask data used to handle input masks. */ void QQuickTextInputPrivate::parseInputMask(const QString &maskFields) { int delimiter = maskFields.indexOf(QLatin1Char(';')); if (maskFields.isEmpty() || delimiter == 0) { if (m_maskData) { delete [] m_maskData; m_maskData = 0; m_maxLength = 32767; internalSetText(QString()); } return; } if (delimiter == -1) { m_blank = QLatin1Char(' '); m_inputMask = maskFields; } else { m_inputMask = maskFields.left(delimiter); m_blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : QLatin1Char(' '); } // calculate m_maxLength / m_maskData length m_maxLength = 0; QChar c = 0; for (int i=0; i<m_inputMask.length(); i++) { c = m_inputMask.at(i); if (i > 0 && m_inputMask.at(i-1) == QLatin1Char('\\')) { m_maxLength++; continue; } if (c != QLatin1Char('\\') && c != QLatin1Char('!') && c != QLatin1Char('<') && c != QLatin1Char('>') && c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) m_maxLength++; } delete [] m_maskData; m_maskData = new MaskInputData[m_maxLength]; MaskInputData::Casemode m = MaskInputData::NoCaseMode; c = 0; bool s; bool escape = false; int index = 0; for (int i = 0; i < m_inputMask.length(); i++) { c = m_inputMask.at(i); if (escape) { s = true; m_maskData[index].maskChar = c; m_maskData[index].separator = s; m_maskData[index].caseMode = m; index++; escape = false; } else if (c == QLatin1Char('<')) { m = MaskInputData::Lower; } else if (c == QLatin1Char('>')) { m = MaskInputData::Upper; } else if (c == QLatin1Char('!')) { m = MaskInputData::NoCaseMode; } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) { switch (c.unicode()) { case 'A': case 'a': case 'N': case 'n': case 'X': case 'x': case '9': case '0': case 'D': case 'd': case '#': case 'H': case 'h': case 'B': case 'b': s = false; break; case '\\': escape = true; default: s = true; break; } if (!escape) { m_maskData[index].maskChar = c; m_maskData[index].separator = s; m_maskData[index].caseMode = m; index++; } } } internalSetText(m_text); } /*! \internal checks if the key is valid compared to the inputMask */ bool QQuickTextInputPrivate::isValidInput(QChar key, QChar mask) const { switch (mask.unicode()) { case 'A': if (key.isLetter()) return true; break; case 'a': if (key.isLetter() || key == m_blank) return true; break; case 'N': if (key.isLetterOrNumber()) return true; break; case 'n': if (key.isLetterOrNumber() || key == m_blank) return true; break; case 'X': if (key.isPrint()) return true; break; case 'x': if (key.isPrint() || key == m_blank) return true; break; case '9': if (key.isNumber()) return true; break; case '0': if (key.isNumber() || key == m_blank) return true; break; case 'D': if (key.isNumber() && key.digitValue() > 0) return true; break; case 'd': if ((key.isNumber() && key.digitValue() > 0) || key == m_blank) return true; break; case '#': if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == m_blank) return true; break; case 'B': if (key == QLatin1Char('0') || key == QLatin1Char('1')) return true; break; case 'b': if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == m_blank) return true; break; case 'H': if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F'))) return true; break; case 'h': if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == m_blank) return true; break; default: break; } return false; } /*! \internal Returns true if the given text \a str is valid for any validator or input mask set for the line control. Otherwise returns false */ QQuickTextInputPrivate::ValidatorState QQuickTextInputPrivate::hasAcceptableInput(const QString &str) const { #ifndef QT_NO_VALIDATOR QString textCopy = str; int cursorCopy = m_cursor; if (m_validator) { QValidator::State state = m_validator->validate(textCopy, cursorCopy); if (state != QValidator::Acceptable) return ValidatorState(state); } #endif if (!m_maskData) return AcceptableInput; if (str.length() != m_maxLength) return InvalidInput; for (int i=0; i < m_maxLength; ++i) { if (m_maskData[i].separator) { if (str.at(i) != m_maskData[i].maskChar) return InvalidInput; } else { if (!isValidInput(str.at(i), m_maskData[i].maskChar)) return InvalidInput; } } return AcceptableInput; } /*! \internal Applies the inputMask on \a str starting from position \a pos in the mask. \a clear specifies from where characters should be gotten when a separator is met in \a str - true means that blanks will be used, false that previous input is used. Calling this when no inputMask is set is undefined. */ QString QQuickTextInputPrivate::maskString(uint pos, const QString &str, bool clear) const { if (pos >= (uint)m_maxLength) return QString::fromLatin1(""); QString fill; fill = clear ? clearString(0, m_maxLength) : m_text; int strIndex = 0; QString s = QString::fromLatin1(""); int i = pos; while (i < m_maxLength) { if (strIndex < str.length()) { if (m_maskData[i].separator) { s += m_maskData[i].maskChar; if (str[(int)strIndex] == m_maskData[i].maskChar) strIndex++; ++i; } else { if (isValidInput(str[(int)strIndex], m_maskData[i].maskChar)) { switch (m_maskData[i].caseMode) { case MaskInputData::Upper: s += str[(int)strIndex].toUpper(); break; case MaskInputData::Lower: s += str[(int)strIndex].toLower(); break; default: s += str[(int)strIndex]; } ++i; } else { // search for separator first int n = findInMask(i, true, true, str[(int)strIndex]); if (n != -1) { if (str.length() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[(int)strIndex]))) { s += fill.mid(i, n-i+1); i = n + 1; // update i to find + 1 } } else { // search for valid m_blank if not n = findInMask(i, true, false, str[(int)strIndex]); if (n != -1) { s += fill.mid(i, n-i); switch (m_maskData[n].caseMode) { case MaskInputData::Upper: s += str[(int)strIndex].toUpper(); break; case MaskInputData::Lower: s += str[(int)strIndex].toLower(); break; default: s += str[(int)strIndex]; } i = n + 1; // updates i to find + 1 } } } ++strIndex; } } else break; } return s; } /*! \internal Returns a "cleared" string with only separators and blank chars. Calling this when no inputMask is set is undefined. */ QString QQuickTextInputPrivate::clearString(uint pos, uint len) const { if (pos >= (uint)m_maxLength) return QString(); QString s; int end = qMin((uint)m_maxLength, pos + len); for (int i = pos; i < end; ++i) if (m_maskData[i].separator) s += m_maskData[i].maskChar; else s += m_blank; return s; } /*! \internal Strips blank parts of the input in a QQuickTextInputPrivate when an inputMask is set, separators are still included. Typically "127.0__.0__.1__" becomes "127.0.0.1". */ QString QQuickTextInputPrivate::stripString(const QString &str) const { if (!m_maskData) return str; QString s; int end = qMin(m_maxLength, (int)str.length()); for (int i = 0; i < end; ++i) { if (m_maskData[i].separator) s += m_maskData[i].maskChar; else if (str[i] != m_blank) s += str[i]; } return s; } /*! \internal searches forward/backward in m_maskData for either a separator or a m_blank */ int QQuickTextInputPrivate::findInMask(int pos, bool forward, bool findSeparator, QChar searchChar) const { if (pos >= m_maxLength || pos < 0) return -1; int end = forward ? m_maxLength : -1; int step = forward ? 1 : -1; int i = pos; while (i != end) { if (findSeparator) { if (m_maskData[i].separator && m_maskData[i].maskChar == searchChar) return i; } else { if (!m_maskData[i].separator) { if (searchChar.isNull()) return i; else if (isValidInput(searchChar, m_maskData[i].maskChar)) return i; } } i += step; } return -1; } void QQuickTextInputPrivate::internalUndo(int until) { if (!isUndoAvailable()) return; cancelPasswordEchoTimer(); internalDeselect(); while (m_undoState && m_undoState > until) { Command& cmd = m_history[--m_undoState]; switch (cmd.type) { case Insert: m_text.remove(cmd.pos, 1); m_cursor = cmd.pos; break; case SetSelection: m_selstart = cmd.selStart; m_selend = cmd.selEnd; m_cursor = cmd.pos; break; case Remove: case RemoveSelection: m_text.insert(cmd.pos, cmd.uc); m_cursor = cmd.pos + 1; break; case Delete: case DeleteSelection: m_text.insert(cmd.pos, cmd.uc); m_cursor = cmd.pos; break; case Separator: continue; } if (until < 0 && m_undoState) { Command& next = m_history[m_undoState-1]; if (next.type != cmd.type && next.type < RemoveSelection && (cmd.type < RemoveSelection || next.type == Separator)) { break; } } } separate(); m_textDirty = true; } void QQuickTextInputPrivate::internalRedo() { if (!isRedoAvailable()) return; internalDeselect(); while (m_undoState < (int)m_history.size()) { Command& cmd = m_history[m_undoState++]; switch (cmd.type) { case Insert: m_text.insert(cmd.pos, cmd.uc); m_cursor = cmd.pos + 1; break; case SetSelection: m_selstart = cmd.selStart; m_selend = cmd.selEnd; m_cursor = cmd.pos; break; case Remove: case Delete: case RemoveSelection: case DeleteSelection: m_text.remove(cmd.pos, 1); m_selstart = cmd.selStart; m_selend = cmd.selEnd; m_cursor = cmd.pos; break; case Separator: m_selstart = cmd.selStart; m_selend = cmd.selEnd; m_cursor = cmd.pos; break; } if (m_undoState < (int)m_history.size()) { Command& next = m_history[m_undoState]; if (next.type != cmd.type && cmd.type < RemoveSelection && next.type != Separator && (next.type < RemoveSelection || cmd.type == Separator)) { break; } } } m_textDirty = true; } void QQuickTextInputPrivate::emitUndoRedoChanged() { Q_Q(QQuickTextInput); const bool previousUndo = canUndo; const bool previousRedo = canRedo; canUndo = isUndoAvailable(); canRedo = isRedoAvailable(); if (previousUndo != canUndo) emit q->canUndoChanged(); if (previousRedo != canRedo) emit q->canRedoChanged(); } /*! \internal If the current cursor position differs from the last emitted cursor position, emits cursorPositionChanged(). */ bool QQuickTextInputPrivate::emitCursorPositionChanged() { Q_Q(QQuickTextInput); if (m_cursor != m_lastCursorPos) { m_lastCursorPos = m_cursor; q->updateCursorRectangle(); emit q->cursorPositionChanged(); if (!hasSelectedText()) { if (lastSelectionStart != m_cursor) { lastSelectionStart = m_cursor; emit q->selectionStartChanged(); } if (lastSelectionEnd != m_cursor) { lastSelectionEnd = m_cursor; emit q->selectionEndChanged(); } } #ifndef QT_NO_ACCESSIBILITY if (QAccessible::isActive()) { if (QObject *acc = QQuickAccessibleAttached::findAccessible(q, QAccessible::EditableText)) { QAccessibleTextCursorEvent ev(acc, m_cursor); QAccessible::updateAccessibility(&ev); } } #endif return true; } return false; } void QQuickTextInputPrivate::setCursorBlinkPeriod(int msec) { Q_Q(QQuickTextInput); if (msec == m_blinkPeriod) return; if (m_blinkTimer) { q->killTimer(m_blinkTimer); } if (msec) { m_blinkTimer = q->startTimer(msec / 2); m_blinkStatus = 1; } else { m_blinkTimer = 0; if (m_blinkStatus == 1) { updateType = UpdatePaintNode; q->polish(); q->update(); } } m_blinkPeriod = msec; } void QQuickTextInput::timerEvent(QTimerEvent *event) { Q_D(QQuickTextInput); if (event->timerId() == d->m_blinkTimer) { d->m_blinkStatus = !d->m_blinkStatus; d->updateType = QQuickTextInputPrivate::UpdatePaintNode; polish(); update(); } else if (event->timerId() == d->m_passwordEchoTimer.timerId()) { d->m_passwordEchoTimer.stop(); d->updateDisplayText(); updateCursorRectangle(); } } void QQuickTextInputPrivate::processKeyEvent(QKeyEvent* event) { Q_Q(QQuickTextInput); if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { if (hasAcceptableInput(m_text) == AcceptableInput || fixup()) { QInputMethod *inputMethod = QGuiApplication::inputMethod(); inputMethod->commit(); if (!(q->inputMethodHints() & Qt::ImhMultiLine)) inputMethod->hide(); if (activeFocus) { // If we lost focus after hiding the virtual keyboard, we've already emitted // editingFinished from handleFocusEvent. Otherwise we emit it now. emit q->editingFinished(); } emit q->accepted(); } event->ignore(); return; } if (m_blinkPeriod > 0) { if (m_blinkTimer) q->killTimer(m_blinkTimer); m_blinkTimer = q->startTimer(m_blinkPeriod / 2); if (m_blinkStatus == 0) { m_blinkStatus = 1; updateType = UpdatePaintNode; q->polish(); q->update(); } } if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit && !m_passwordEchoEditing && !m_readOnly && !event->text().isEmpty() && !(event->modifiers() & Qt::ControlModifier)) { // Clear the edit and reset to normal echo mode while editing; the // echo mode switches back when the edit loses focus // ### resets current content. dubious code; you can // navigate with keys up, down, back, and select(?), but if you press // "left" or "right" it clears? updatePasswordEchoEditing(true); clear(); } bool unknown = false; bool visual = cursorMoveStyle() == Qt::VisualMoveStyle; if (false) { } #ifndef QT_NO_SHORTCUT else if (event == QKeySequence::Undo) { q->undo(); } else if (event == QKeySequence::Redo) { q->redo(); } else if (event == QKeySequence::SelectAll) { selectAll(); } #ifndef QT_NO_CLIPBOARD else if (event == QKeySequence::Copy) { copy(); } else if (event == QKeySequence::Paste) { if (!m_readOnly) { QClipboard::Mode mode = QClipboard::Clipboard; paste(mode); } } else if (event == QKeySequence::Cut) { q->cut(); } else if (event == QKeySequence::DeleteEndOfLine) { if (!m_readOnly) deleteEndOfLine(); } #endif //QT_NO_CLIPBOARD else if (event == QKeySequence::MoveToStartOfLine || event == QKeySequence::MoveToStartOfBlock) { home(0); } else if (event == QKeySequence::MoveToEndOfLine || event == QKeySequence::MoveToEndOfBlock) { end(0); } else if (event == QKeySequence::SelectStartOfLine || event == QKeySequence::SelectStartOfBlock) { home(1); } else if (event == QKeySequence::SelectEndOfLine || event == QKeySequence::SelectEndOfBlock) { end(1); } else if (event == QKeySequence::MoveToNextChar) { if (hasSelectedText()) { moveCursor(selectionEnd(), false); } else { cursorForward(0, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1)); } } else if (event == QKeySequence::SelectNextChar) { cursorForward(1, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1)); } else if (event == QKeySequence::MoveToPreviousChar) { if (hasSelectedText()) { moveCursor(selectionStart(), false); } else { cursorForward(0, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1)); } } else if (event == QKeySequence::SelectPreviousChar) { cursorForward(1, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1)); } else if (event == QKeySequence::MoveToNextWord) { if (m_echoMode == QQuickTextInput::Normal) layoutDirection() == Qt::LeftToRight ? cursorWordForward(0) : cursorWordBackward(0); else layoutDirection() == Qt::LeftToRight ? end(0) : home(0); } else if (event == QKeySequence::MoveToPreviousWord) { if (m_echoMode == QQuickTextInput::Normal) layoutDirection() == Qt::LeftToRight ? cursorWordBackward(0) : cursorWordForward(0); else if (!m_readOnly) { layoutDirection() == Qt::LeftToRight ? home(0) : end(0); } } else if (event == QKeySequence::SelectNextWord) { if (m_echoMode == QQuickTextInput::Normal) layoutDirection() == Qt::LeftToRight ? cursorWordForward(1) : cursorWordBackward(1); else layoutDirection() == Qt::LeftToRight ? end(1) : home(1); } else if (event == QKeySequence::SelectPreviousWord) { if (m_echoMode == QQuickTextInput::Normal) layoutDirection() == Qt::LeftToRight ? cursorWordBackward(1) : cursorWordForward(1); else layoutDirection() == Qt::LeftToRight ? home(1) : end(1); } else if (event == QKeySequence::Delete) { if (!m_readOnly) del(); } else if (event == QKeySequence::DeleteEndOfWord) { if (!m_readOnly) deleteEndOfWord(); } else if (event == QKeySequence::DeleteStartOfWord) { if (!m_readOnly) deleteStartOfWord(); } else if (event == QKeySequence::DeleteCompleteLine) { if (!m_readOnly) { selectAll(); #ifndef QT_NO_CLIPBOARD copy(); #endif del(); } } #endif // QT_NO_SHORTCUT else { bool handled = false; if (event->modifiers() & Qt::ControlModifier) { switch (event->key()) { case Qt::Key_Backspace: if (!m_readOnly) deleteStartOfWord(); break; default: if (!handled) unknown = true; } } else { // ### check for *no* modifier switch (event->key()) { case Qt::Key_Backspace: if (!m_readOnly) { backspace(); } break; default: if (!handled) unknown = true; } } } if (event->key() == Qt::Key_Direction_L || event->key() == Qt::Key_Direction_R) { setLayoutDirection((event->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft); unknown = false; } if (unknown && !m_readOnly) { if (m_inputControl->isAcceptableInput(event)) { insert(event->text()); event->accept(); return; } } if (unknown) event->ignore(); else event->accept(); } /*! \internal Deletes the portion of the word before the current cursor position. */ void QQuickTextInputPrivate::deleteStartOfWord() { int priorState = m_undoState; Command cmd(SetSelection, m_cursor, 0, m_selstart, m_selend); separate(); cursorWordBackward(true); addCommand(cmd); removeSelectedText(); finishChange(priorState); } /*! \internal Deletes the portion of the word after the current cursor position. */ void QQuickTextInputPrivate::deleteEndOfWord() { int priorState = m_undoState; Command cmd(SetSelection, m_cursor, 0, m_selstart, m_selend); separate(); cursorWordForward(true); // moveCursor (sometimes) calls separate() so we need to add the command after that so the // cursor position and selection are restored in the same undo operation as the remove. addCommand(cmd); removeSelectedText(); finishChange(priorState); } /*! \internal Deletes all text from the cursor position to the end of the line. */ void QQuickTextInputPrivate::deleteEndOfLine() { int priorState = m_undoState; Command cmd(SetSelection, m_cursor, 0, m_selstart, m_selend); separate(); setSelection(m_cursor, end()); addCommand(cmd); removeSelectedText(); finishChange(priorState); } /*! \qmlmethod QtQuick::TextInput::ensureVisible(int position) \since 5.4 Scrolls the contents of the text input so that the specified character \a position is visible inside the boundaries of the text input. \sa autoScroll */ void QQuickTextInput::ensureVisible(int position) { Q_D(QQuickTextInput); d->ensureVisible(position); updateCursorRectangle(false); } /*! \since 5.6 \qmlproperty real QtQuick::TextInput::padding \qmlproperty real QtQuick::TextInput::topPadding \qmlproperty real QtQuick::TextInput::leftPadding \qmlproperty real QtQuick::TextInput::bottomPadding \qmlproperty real QtQuick::TextInput::rightPadding These properties hold the padding around the content. This space is reserved in addition to the contentWidth and contentHeight. */ qreal QQuickTextInput::padding() const { Q_D(const QQuickTextInput); return d->padding(); } void QQuickTextInput::setPadding(qreal padding) { Q_D(QQuickTextInput); if (qFuzzyCompare(d->padding(), padding)) return; d->extra.value().padding = padding; d->updateLayout(); emit paddingChanged(); if (!d->extra.isAllocated() || !d->extra->explicitTopPadding) emit topPaddingChanged(); if (!d->extra.isAllocated() || !d->extra->explicitLeftPadding) emit leftPaddingChanged(); if (!d->extra.isAllocated() || !d->extra->explicitRightPadding) emit rightPaddingChanged(); if (!d->extra.isAllocated() || !d->extra->explicitBottomPadding) emit bottomPaddingChanged(); } void QQuickTextInput::resetPadding() { setPadding(0); } qreal QQuickTextInput::topPadding() const { Q_D(const QQuickTextInput); if (d->extra.isAllocated() && d->extra->explicitTopPadding) return d->extra->topPadding; return d->padding(); } void QQuickTextInput::setTopPadding(qreal padding) { Q_D(QQuickTextInput); d->setTopPadding(padding); } void QQuickTextInput::resetTopPadding() { Q_D(QQuickTextInput); d->setTopPadding(0, true); } qreal QQuickTextInput::leftPadding() const { Q_D(const QQuickTextInput); if (d->extra.isAllocated() && d->extra->explicitLeftPadding) return d->extra->leftPadding; return d->padding(); } void QQuickTextInput::setLeftPadding(qreal padding) { Q_D(QQuickTextInput); d->setLeftPadding(padding); } void QQuickTextInput::resetLeftPadding() { Q_D(QQuickTextInput); d->setLeftPadding(0, true); } qreal QQuickTextInput::rightPadding() const { Q_D(const QQuickTextInput); if (d->extra.isAllocated() && d->extra->explicitRightPadding) return d->extra->rightPadding; return d->padding(); } void QQuickTextInput::setRightPadding(qreal padding) { Q_D(QQuickTextInput); d->setRightPadding(padding); } void QQuickTextInput::resetRightPadding() { Q_D(QQuickTextInput); d->setRightPadding(0, true); } qreal QQuickTextInput::bottomPadding() const { Q_D(const QQuickTextInput); if (d->extra.isAllocated() && d->extra->explicitBottomPadding) return d->extra->bottomPadding; return d->padding(); } void QQuickTextInput::setBottomPadding(qreal padding) { Q_D(QQuickTextInput); d->setBottomPadding(padding); } void QQuickTextInput::resetBottomPadding() { Q_D(QQuickTextInput); d->setBottomPadding(0, true); } QT_END_NAMESPACE
30.252831
165
0.629264
[ "render" ]
dab55d0421214b866b24dddb259d6b815eab8307
5,050
hpp
C++
Entity.hpp
RFDonovan/RADAMA-GAME
999771c5105b6dba8d5616c52995d0c4a26b66d7
[ "MIT" ]
null
null
null
Entity.hpp
RFDonovan/RADAMA-GAME
999771c5105b6dba8d5616c52995d0c4a26b66d7
[ "MIT" ]
null
null
null
Entity.hpp
RFDonovan/RADAMA-GAME
999771c5105b6dba8d5616c52995d0c4a26b66d7
[ "MIT" ]
null
null
null
#ifndef ENTITY_HPP_INCLUDED #define ENTITY_HPP_INCLUDED #include <random> #include<SFML/Graphics.hpp> #include<Box2D/Box2D.h> #include<iostream> #include<cmath> #include<vector> #include<sstream> #include "Globals.h" #include "AnimatedSprite.hpp" #include "TextureHolder.h" #include "Structures.hpp" #include "RayCastCallback.h" #include "Projectile.hpp" #include "Item.hpp" #include "pugixml.hpp" struct bodyUserData { int bodyKind; }; class Entity : public ObjectType{ public: enum Type{ Player, Human, Other, }; //class member variables struct jointStruct{ b2Joint* joint; std::string bodyA; std::string bodyB; }; b2Body* m_body, *m_legs, *m_head, *m_sensor, *m_sensorL, *m_sensorR; float m_radius; Type kind; std::vector<b2Joint *> jointList; std::vector<b2Fixture *> FSList; std::vector<jointStruct> jointBodyList; std::map<std::string, b2Body*> bodyList; sf::RenderWindow& mWindow; sf::Clock noRestartClock; //animation control sf::Texture* texture; TextureHolder* textureHolder; TextureHolder Textures; bool grounded = false; int nb_contacts = 0; b2World *p_world; b2Vec2 vel; b2Fixture *basFixture; int jump = 0; ///ANIMATION sf::Clock frameClock; Animation *currentAnimation; Animation walkingAnimationLeft, walkingAnimationRight, stopLeft, stopRight, jumpLeft, jumpRight, shiftRight, shiftLeft; Animation atkLeft, atkRight; AnimatedSprite animatedSprite; std::map<std::string, Animation>* animList; float max_width = 0; sf::Vector2f mouseInit, mousePos, playerPos, velocityForce; float desiredVel; float velocityLimit = 5.f; float jumpLimit = 5.f; sf::Clock jumpClock; ///SPRINT MAX sf::Clock shiftClock; bool isShifted = false; int lastTime = 0; sf::Sprite shiftSprite; sf::Clock clock; ///FINITE STATE MACHINE RayCastCallback callback; b2Body* targetBody; sf::Clock fsmClock,stateClock; bool fsm_hunting = false; bool fsm_attack = false; bool fsm_alert = false; bool fsm_shocked = false; bool fsm_normal = true; ///SENSOR sf::Clock visionClock; float rayRange = 300.f; sf::Sprite visionSprite; bool showFX = false; ///LIFE HANDLER int m_life = 80; // sur 100 int m_mana = 100; // sur 100 int maxLife; bool deleted = false; sf::Clock lifeClock; // sf::Texture *lifeTex, *deathTex; sf::Sprite lifeSprite, deathSprite; sf::Clock textClock; sf::Text Text; sf::Font MyFont; bool haveToSpeak = false; int textDelay=5; ///WEAPON TAKING bool isWeaponDispo = false; Projectile* weaponDispo; ///ATTACK DEF INTERACTION bool isAttacked = false; int defense = 0; b2Fixture* fixtureOnSensor; bool isAttacking = false; sf::Clock atkClock, atackedClock; public: Entity(sf::RenderWindow& mWindow, b2World* world, float radius, std::vector<bodyData> *bDList, std::map<std::string, b2Joint*> *jMap); //void loadPlayerSprite(TextureHolder* Textures); //void processLogic(); //void processLogic(sf::RenderWindow& mWindow); //void render(sf::RenderWindow& mWindow,sf::Time frameTime, TextureHolder* Textures){} //void onCommand(sf::Event e); int getY(); int getX(); sf::Vector2f getPosition(); void setPosition(sf::Vector2f position); bool isGrounded(); b2Vec2 getVelocity(); float getMass(); void startContact(b2Fixture *fixture, b2Fixture *fixtureB); void removeFromFSList(b2Fixture *fixture); void endContact(b2Fixture *fixture, b2Fixture *fixtureB); //void attachStuff(sf::Shader* shader, TextureHolder::TexName tex); int getObjectType(){return ENTITY;} void wipeJoints(); void exportToXML(std::string filename); void addBodyNode(pugi::xml_node parent, std::string name, b2Body* body); void addJointNode(pugi::xml_node parent, std::string name, jointStruct* jStruct); void sense(); void jumpOnObstacle(); void goTo(b2Vec2); void commitLogic(); void getHit(int damage, float impulse); void applyForce(float f); bool isDead(); void doTheDead(); void takeItem(Item* item); ///FINITE STATE MACHINE virtual void doNormalThings()=0; virtual void doAlertThings()=0; virtual void doHuntingThings()=0; virtual void doAttackThings()=0; virtual void doShockedThings()=0; void resetFSM(); ///DRAWING SOMETHING void drawVision(sf::RenderWindow& mWindow); void drawLife(sf::RenderWindow& mWindow); void speak(sf::RenderWindow& mWindow); void say(std::string,int delay=5); ///ATTACK RANGE virtual void addAttackRange() = 0; b2Vec2 getSensorPosition(); ~Entity(); }; #endif // ENTITY_HPP_INCLUDED
26.165803
146
0.648119
[ "render", "vector" ]
dabf6d7b86a6781e6a6684e47099e9a2bcdb7226
4,992
cpp
C++
src/miyuki.server/main.cpp
shiinamiyuki/MiyukiRenderer
81f45a86509b0c003ea7fa8c092c5b96b557d6c3
[ "MIT" ]
53
2019-06-13T12:34:46.000Z
2019-09-26T02:20:01.000Z
src/miyuki.server/main.cpp
shiinamiyuki/miyuki-renderer
81f45a86509b0c003ea7fa8c092c5b96b557d6c3
[ "MIT" ]
null
null
null
src/miyuki.server/main.cpp
shiinamiyuki/miyuki-renderer
81f45a86509b0c003ea7fa8c092c5b96b557d6c3
[ "MIT" ]
5
2020-01-01T03:05:39.000Z
2022-01-22T14:38:19.000Z
// // main.cpp // ~~~~~~~~ // // Copyright (c) 2003-2019 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) // #include <chrono> #include <cstdio> #include <httplib.h> #include <miyuki.renderer/graph.h> #include <miyuki.foundation/log.hpp> #include "../core/export.h" #define SERVER_CERT_FILE "./cert.pem" #define SERVER_PRIVATE_KEY_FILE "./key.pem" namespace miyuki::server { using namespace httplib; std::string dump_headers(const Headers &headers) { std::string s; char buf[BUFSIZ]; for (auto it = headers.begin(); it != headers.end(); ++it) { const auto &x = *it; snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str()); s += buf; } return s; } std::string log(const Request &req, const Response &res) { std::string s; char buf[BUFSIZ]; s += "================================\n"; snprintf(buf, sizeof(buf), "%s %s %s", req.method.c_str(), req.version.c_str(), req.path.c_str()); s += buf; std::string query; for (auto it = req.params.begin(); it != req.params.end(); ++it) { const auto &x = *it; snprintf(buf, sizeof(buf), "%c%s=%s", (it == req.params.begin()) ? '?' : '&', x.first.c_str(), x.second.c_str()); query += buf; } snprintf(buf, sizeof(buf), "%s\n", query.c_str()); s += buf; s += dump_headers(req.headers); s += "--------------------------------\n"; snprintf(buf, sizeof(buf), "%d %s\n", res.status, res.version.c_str()); s += buf; s += dump_headers(res.headers); s += "\n"; if (!res.body.empty()) { s += res.body; } s += "\n"; return s; } class RenderServer { #ifdef CPPHTTPLIB_OPENSSL_SUPPORT SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE); #else Server svr; #endif int port; std::optional<core::SceneGraph> graph; std::shared_ptr<serialize::Context> context; public: explicit RenderServer(int port) : port(port) { if (!svr.is_valid()) { fprintf(stderr, "server has an error...\n"); exit(1); } context = core::Initialize(); svr.Post("/render/start", [=](const Request &req, Response &res, const ContentReader &content_reader) { auto it = req.headers.find("Content-Type"); if (it != req.headers.end()) { auto type = it->second; if (type == "application/json") { std::string body; content_reader([&](const char *data, size_t data_length) { body.append(data, data_length); return true; }); auto data = json::parse(body); auto path = data.at("workdir").get<std::string>(); res.set_content(body, "text/plain"); fs::current_path(fs::absolute(fs::path(path))); auto &scene = data.at("scene"); graph = serialize::fromJson<core::SceneGraph>(*context, scene); graph->render(context, "out.png"); } } }); svr.Get("/render/status", [=](const Request &req, Response &res) { auto body = R"({ "status":"stopped" })"; res.set_content(body, "application/json"); }); svr.Get("/render/output", [=](const Request &req, Response &res) { auto body = R"({ "status":"stopped" })"; res.set_content(body, "application/json"); }); svr.Get("/stop", [&](const Request & /*req*/, Response & /*res*/) { svr.stop(); }); svr.set_error_handler([](const Request & /*req*/, Response &res) { const char *fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>"; char buf[BUFSIZ]; snprintf(buf, sizeof(buf), fmt, res.status); res.set_content(buf, "text/html"); }); svr.set_logger([](const Request &req, const Response &res) { // printf("%s", log(req, res).c_str()); }); } void run() { svr.listen("localhost", port); } }; } int main(int argc, char **argv) { miyuki::server::RenderServer server(8080); server.run(); return 0; }
33.28
116
0.46895
[ "render" ]
dac07acb26e3317482ef789021cadafe56b7b528
6,961
cpp
C++
mvm-reversed/server/tf/bot/behavior/spy/tf_bot_spy_infiltrate.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
7
2021-03-02T02:27:18.000Z
2022-02-18T00:56:28.000Z
mvm-reversed/server/tf/bot/behavior/spy/tf_bot_spy_infiltrate.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
3
2021-11-29T15:53:02.000Z
2022-02-21T13:09:22.000Z
mvm-reversed/server/tf/bot/behavior/spy/tf_bot_spy_infiltrate.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
5
2021-03-04T20:26:11.000Z
2021-11-26T07:09:24.000Z
/* reverse engineering by sigsegv * based on TF2 version 20151007a * server/tf/bot/behavior/spy/tf_bot_spy_infiltrate.cpp * used in MvM: TODO */ ConVar tf_bot_debug_spy("tf_bot_debug_spy", "0", FCVAR_CHEAT); CTFBotSpyInfiltrate::CTFBotSpyInfiltrate() { } CTFBotSpyInfiltrate::~CTFBotSpyInfiltrate() { } const char *CTFBotSpyInfiltrate::GetName() const { return "SpyInfiltrate"; } ActionResult<CTFBot> CTFBotSpyInfiltrate::OnStart(CTFBot *actor, Action<CTFBot> *action) { /* BUG: doesn't set PathFollower's min lookahead distance */ this->m_HidingArea = nullptr; this->m_bCloaked = false; return ActionResult<CTFBot>::Continue(); } ActionResult<CTFBot> CTFBotSpyInfiltrate::Update(CTFBot *actor, float dt) { CBaseCombatWeapon *revolver = actor->Weapon_GetSlot(0); if (revolver != nullptr) { actor->Weapon_Switch(revolver); } auto area = static_cast<CTFNavArea *>(actor->GetLastKnownArea()); if (area == nullptr) { return ActionResult<CTFBot>::Continue(); } if (!actor->m_Shared.IsStealthed() && !area->IsSpawnRoom() && area->IsInCombat() && !this->m_bCloaked) { this->m_bCloaked = true; actor->PressAltFireButton(); } const CKnownEntity *threat = actor->GetVisionInterface()->GetPrimaryKnownThreat(false); if (threat != nullptr && threat->GetEntity() != nullptr && threat->GetEntity()->IsBaseObject()) { auto obj = static_cast<CBaseObject *>(threat->GetEntity()); if (!obj->HasSapper() && actor->IsEnemy(obj)) { return ActionResult<CTFBot>::SuspendFor(new CTFBotSpySap(obj), "Sapping an enemy object"); } } if (actor->m_hTargetSentry != nullptr && !actor->m_hTargetSentry->HasSapper()) { return ActionResult<CTFBot>::SuspendFor(new CTFBotSpySap(actor->m_hTargetSentry), "Sapping a Sentry"); } if (this->m_HidingArea == nullptr && this->m_ctFindHidingArea.IsElapsed()) { this->FindHidingSpot(actor); this->m_ctFindHidingArea.Start(3.0f); } if (!TFGameRules()->InSetup() && threat != nullptr && threat->GetTimeSinceLastKnown() < 3.0f) { CTFPlayer *victim = ToTFPlayer(threat->GetEntity()); if (victim != nullptr) { auto victim_area = static_cast<CTFNavArea *>(victim->GetLastKnownArea()); if (victim_area != nullptr && victim->GetTeamNumber() < TF_TEAM_COUNT && victim_area->GetIncursionDistance(victim->GetTeamNumber()) > area->GetIncursionDistance(victim->GetTeamNumber())) { if (actor->m_Shared.IsStealthed()) { return ActionResult<CTFBot>::SuspendFor(new CTFBotRetreatToCover(new CTFBotSpyAttack(victim)), "Hiding to decloak before going after a backstab victim"); } else { return ActionResult<CTFBot>::SuspendFor(new CTFBotSpyAttack(victim), "Going after a backstab victim"); } } } } if (this->m_HidingArea == nullptr) { return ActionResult<CTFBot>::Continue(); } if (tf_bot_debug_spy.GetBool()) { this->m_HidingArea->DrawFilled(0xff, 0xff, 0x00, 0xff, 0.0f, true, 5.0f); } if (this->m_HidingArea == area) { if (TFGameRules()->InSetup()) { this->m_ctWait.Start(RandomFloat(0.0f, 5.0f)); } else { if (this->m_ctWait.HasStarted() && this->m_ctWait.IsElapsed()) { this->m_ctWait.Invalidate(); } else { this->m_ctWait.Start(RandomFloat(5.0f, 10.0f)); } } } else { if (this->m_ctRecomputePath.IsElapsed()) { this->m_ctRecomputePath.Start(RandomFloat(1.0f, 2.0f)); CTFBotPathCost cost_func(actor, SAFEST_ROUTE); this->m_PathFollower.Compute(actor, this->m_HidingArea->GetCenter(), cost_func, 0.0f, true); } this->m_PathFollower.Update(actor); this->m_ctWait.Invalidate(); } return ActionResult<CTFBot>::Continue(); } void CTFBotSpyInfiltrate::OnEnd(CTFBot *actor, Action<CTFBot> *action) { } ActionResult<CTFBot> CTFBotSpyInfiltrate::OnSuspend(CTFBot *actor, Action<CTFBot> *action) { return ActionResult<CTFBot>::Continue(); } ActionResult<CTFBot> CTFBotSpyInfiltrate::OnResume(CTFBot *actor, Action<CTFBot> *action) { this->m_ctRecomputePath.Invalidate(); return ActionResult<CTFBot>::Continue(); } EventDesiredResult<CTFBot> CTFBotSpyInfiltrate::OnStuck(CTFBot *actor) { this->m_HidingArea = nullptr; this->m_ctFindHidingArea.Invalidate(); return ActionResult<CTFBot>::Continue(); } EventDesiredResult<CTFBot> CTFBotSpyInfiltrate::OnTerritoryCaptured(CTFBot *actor, int i1) { this->m_ctFindHidingArea.Start(5.0f); return EventDesiredResult<CTFBot>::Continue(); } EventDesiredResult<CTFBot> CTFBotSpyInfiltrate::OnTerritoryLost(CTFBot *actor, int i1) { this->m_ctFindHidingArea.Start(5.0f); return EventDesiredResult<CTFBot>::Continue(); } QueryResponse CTFBotSpyInfiltrate::ShouldAttack(const INextBot *nextbot, const CKnownEntity *threat) const { return QueryResponse::NO; } bool CTFBotSpyInfiltrate::FindHidingSpot(CTFBot *actor) { this->m_HidingArea = nullptr; if (actor->GetAliveDuration() < 5.0f && TFGameRules()->InSetup()) { return false; } CUtlVector<CTFNavArea *> *exits; if (actor->GetTeamNumber() == TF_TEAM_RED) { exits = &TheNavMesh->m_SpawnExits[TF_TEAM_BLUE]; } else if (actor->GetTeamNumber() == TF_TEAM_BLUE) { exits = &TheNavMesh->m_SpawnExits[TF_TEAM_RED]; } if (exits == nullptr || exits->IsEmpty()) { if (tf_bot_debug_spy.GetBool()) { DevMsg("%3.2f: No enemy spawn room exit areas found\n", gpGlobals->curtime); } return false; } CUtlVector<CTFNavArea *> surrounding; FOR_EACH_VEC(*exits, i) { CUtlVector<CTFNavArea *> temp; CollectSurroundingAreas(&temp, (*exits)[i], 2500.0f, actor->GetLocomotionInterface()->GetStepHeight(), actor->GetLocomotionInterface()->GetStepHeight()); surrounding.AddVectorToTail(temp); } CUtlVector<CTFNavArea *> areas; FOR_EACH_VEC(surrounding, i) { if (!actor->GetLocomotionInterface()->IsAreaTraversable(surrounding[i])) { continue; } bool visible = false; FOR_EACH_VEC(exits, j) { if (surrounding[i]->IsPotentiallyVisible(exits[j])) { visible = true; break; } } if (!visible) { areas.AddToTail(surrounding[i]); } } if (areas.IsEmpty()) { if (tf_bot_debug_spy.GetBool()) { DevMsg("%3.2f: Can't find any non-visible hiding areas, " "trying for anything near the spawn exit...\n", gpGlobals->curtime); } FOR_EACH_VEC(surrounding, i) { if (actor->GetLocomotionInterface()->IsAreaTraversable(surrounding[i])) { areas.AddToTail(surrounding[i]); } } if (areas.IsEmpty()) { if (tf_bot_debug_spy.GetBool()) { DevMsg("%3.2f: Can't find any areas near the enemy spawn exit - " "just heading to the enemy spawn and hoping...\n", gpGlobals->curtime); } this->m_HidingArea = exits.Random(); return false; } } this->m_HidingArea = areas.Random(); return true; }
27.844
120
0.675621
[ "object" ]
dac847f9517e25ab23379264f51693be2198bf13
6,085
cpp
C++
source/code/programs/transcompilers/old_unilang/main/program_options/program_options.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
33
2019-05-30T07:43:32.000Z
2021-12-30T13:12:32.000Z
source/code/programs/transcompilers/old_unilang/main/program_options/program_options.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
371
2019-05-16T15:23:50.000Z
2021-09-04T15:45:27.000Z
source/code/programs/transcompilers/old_unilang/main/program_options/program_options.cpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
6
2019-08-22T17:37:36.000Z
2020-11-07T07:15:32.000Z
#include "program_options.hpp" #include <string> #include <iostream> //constructor Program_Options::Program_Options(int const& argc, char** const& argv){ using namespace boost::program_options; //build all the possible flags and add description. options_description desc (Get_Options_Description()); //set positional arguments positional_options_description pod; //build variable map Build_Variable_Map(argc,argv,desc,pod); //process immediate options Process_Immediate_Options(desc); //validate the mandatory flags Check_For_Mandatory_Flags_Not_Passed(); } boost::program_options::options_description Program_Options::Get_Options_Description(void){ using namespace boost::program_options; //Program Description options_description desc(DESCRIPTION); //Program Flags desc.add_options() //these are flag descriptions of that can be passed into the class. //the code inserted, are the flags added by the user through the //program_options_maker flag interface ("input_files",value<std::vector<std::string>>()->multitoken(),"the name of the UniLang file to compile") ("dir",value<std::string>(),"the directory to convert all unilang files from") ("exporter",value<std::string>(),"the exporter front-end to use for generating the source code (often a company or interested party)") ("languages",value<std::vector<std::string>>(),"the resulting languages to export unilang to") ("style",value<std::string>(),"the style you'd like the exporter to employ. Each exporter has their own set of styles for each of the languages they support") ("recursive_dependency_paths",value<std::vector<std::string>>()->multitoken(),"paths to recursively search for the dependencies of the file being compiled. This can point to both real code, or Unilang files") ("dependency_paths",value<std::vector<std::string>>()->multitoken(),"paths to search for the dependencies of the file being compiled. This can point to both real code, or Unilang files") ("no-transfer","Decide whether to skip transferring the exported file (this usually entails sending over files over a network possibly)") ("no-remote-programs","Dont run remote programs on transfered code") ("no-local-programs","Dont run local programs on exported code") ("no-build","Decide whether we should try to build the repo where could would be transfered to") ("build-only","Only do a build") //+----------------------------------------------------------+ //| Obligatory | //+----------------------------------------------------------+ ("help,h","produce this help message") ("version,v","display version") ; return desc; } void Program_Options::Build_Variable_Map(int const& argc, char** const& argv, boost::program_options::options_description const& desc, boost::program_options::positional_options_description const& pod){ using namespace boost::program_options; //store user flag data. crash elegantly if they pass incorrect flags. try{ store(command_line_parser(argc, argv).options(desc).positional(pod).run(), vm); notify(vm); } catch(error& e){ std::cerr << "ERROR: " << e.what() << std::endl; std::cerr << desc << std::endl; exit(EXIT_FAILURE); } return; } void Program_Options::Process_Immediate_Options( boost::program_options::options_description const& desc){ //do not continue the program if the user wanted to see the version or help data if (vm.count("version")){ std::cout << "\nThis is version " << VERSION_NUMBER << " of the " + TOOL_NAME + ".\n\n"; exit(EXIT_SUCCESS); } else if (vm.count("help")){ std::cout << '\n' << desc << '\n'; exit(EXIT_SUCCESS); } return; } void Program_Options::Check_For_Mandatory_Flags_Not_Passed(){ std::vector<std::string> flags_not_passed; //if(!vm.count("input_files")){flags_not_passed.push_back("input_files");} //if(!vm.count("exporter")){flags_not_passed.push_back("exporter");} //if(!vm.count("language")){flags_not_passed.push_back("language");} if (!flags_not_passed.empty()){ std::cerr << "you need to pass the following flags still:\n"; for (auto it: flags_not_passed){ std::cerr << '\t' << it << '\n'; } exit(EXIT_FAILURE); } return; } std::vector<std::string> Program_Options::Input_Files() const{ std::vector<std::string> data; if (vm.count("input_files")){ data = vm["input_files"].as<std::vector<std::string>>(); } return data; } std::string Program_Options::Dir() const{ std::string data; if (vm.count("dir")){ data = vm["dir"].as<std::string>(); } return data; } Chosen_Exporter Program_Options::Exporter() const{ std::string data; if (vm.count("exporter")){ data = vm["exporter"].as<std::string>(); } else { return Chosen_Exporter::NONE; } return enum_cast_to_Chosen_Exporter(data); } std::vector<Artifact_Type> Program_Options::Languages() const{ std::vector<std::string> data; if (vm.count("languages")){ data = vm["languages"].as<std::vector<std::string>>(); } //convert strings to enums auto data2 = enum_cast_to_Artifact_Type(data); return data2; } std::string Program_Options::Style() const{ std::string data; if (vm.count("style")){ data = vm["style"].as<std::string>(); } return data; } std::vector<std::string> Program_Options::Recursive_Dependency_Paths() const{ std::vector<std::string> data; if (vm.count("recursive_dependency_paths")){ data = vm["recursive_dependency_paths"].as<std::vector<std::string>>(); } return data; } std::vector<std::string> Program_Options::Dependency_Paths() const{ std::vector<std::string> data; if (vm.count("dependency_paths")){ data = vm["dependency_paths"].as<std::vector<std::string>>(); } return data; } bool Program_Options::Skip_Transfer() const{ return vm.count("no-transfer");} bool Program_Options::Skip_Build() const{ return vm.count("no-build");} bool Program_Options::Build_Only()const{ return vm.count("build-only");} bool Program_Options::Skip_Remote_Programs() const{ return vm.count("no-remote-programs");} bool Program_Options::Skip_Local_Programs() const{ return vm.count("no-local-programs");}
33.251366
210
0.704519
[ "vector" ]
dacd765791aa6e7829479f16dc8961270fbabca7
43,061
cpp
C++
src/Tools/C64CommandLine.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
34
2021-05-29T07:04:17.000Z
2022-03-10T20:16:03.000Z
src/Tools/C64CommandLine.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-25T13:05:21.000Z
2022-01-19T17:35:17.000Z
src/Tools/C64CommandLine.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-24T18:37:41.000Z
2022-02-06T23:06:02.000Z
#include "C64CommandLine.h" #include "SYS_FileSystem.h" #include "CViewC64.h" #include "SYS_CommandLine.h" #include "CDebugSymbols.h" #include "CViewMainMenu.h" #include "CViewSnapshots.h" #include "CSlrString.h" #include "RES_ResourceManager.h" #include "C64SettingsStorage.h" #include "C64SharedMemory.h" #include "CViewVicEditor.h" #include "CGuiMain.h" #include "SND_SoundEngine.h" #include "CViewJukeboxPlaylist.h" #include "C64D_Version.h" #include "SYS_Platform.h" #include "CDebugInterfaceC64.h" #include "CDebugInterfaceAtari.h" #include "CDebugInterfaceNes.h" // TODO: fixme, plugins should also pare command line options extern char *crtMakerConfigFilePath; #define C64D_PASS_CONFIG_DATA_MARKER 0x029A #define C64D_PASS_CONFIG_DATA_VERSION 0x0002 CSlrMutex *c64DebuggerStartupTasksCallbacksMutex; std::list<C64DebuggerStartupTaskCallback *> c64DebuggerStartupTasksCallbacks; bool isPRGInCommandLine = false; bool isD64InCommandLine = false; bool isSNAPInCommandLine = false; bool isTAPInCommandLine = false; bool isCRTInCommandLine = false; bool isXEXInCommandLine = false; bool isATRInCommandLine = false; void C64DebuggerPassConfigToRunningInstance(); #if !defined(WIN32) #define printLine printf #define printInfo printf #define printHelp printf #else // Warning: on Win32 API apps do not have a console, so this will not be printed to console but log instead: #define printLine LOGM #define printInfo(...) { MessageBox(NULL, __VA_ARGS__, "Retro Debugger", MB_ICONWARNING | MB_OK); } #define printHelp printf #include "SYS_Startup.h" #endif void C64DebuggerInitStartupTasks() { LOGD("C64DebuggerInitStartupTasks"); c64DebuggerStartupTasksCallbacksMutex = new CSlrMutex("c64DebuggerStartupTasksCallbacksMutex"); } void c64PrintC64DebuggerVersion() { printHelp("Retro Debugger v%s by Slajerek/Samar\n", RETRODEBUGGER_VERSION_STRING); #if defined(RUN_COMMODORE64) printHelp("VICE %s by The VICE Team\n", C64DEBUGGER_VICE_VERSION_STRING); #endif #if defined(RUN_ATARI) printHelp("Atari 800 Emulator, Version %s\n", C64DEBUGGER_ATARI800_VERSION_STRING); #endif #if defined(RUN_NES) printHelp("NestopiaUE, Version %s\n", C64DEBUGGER_NES_VERSION_STRING); #endif } void c64PrintCommandLineHelp() { SYS_AttachConsole(); c64PrintC64DebuggerVersion(); printHelp("\n"); printHelp("-help\n"); printHelp(" show this help\n"); printHelp("-version\n"); printHelp(" display version string\n"); printHelp("\n"); // printHelp("-layout <id>\n"); // printHelp(" start with layout id <1-%d>\n", SCREEN_LAYOUT_MAX); printHelp("-breakpoints <file>\n"); printHelp(" load breakpoints\n"); printHelp("-symbols <file>\n"); printHelp(" load symbols (code labels)"); printHelp("-watch <file>\n"); printHelp(" load watches"); printHelp("-debuginfo <file>\n"); printHelp(" load debug symbols (*.dbg)"); printHelp("\n"); printHelp("-wait <ms>\n"); printHelp(" wait before performing tasks\n"); #if defined(RUN_COMMODORE64) printHelp("-c64 select emulator: C64 Vice"); printHelp("-prg <file>\n"); printHelp(" load PRG file into memory\n"); printHelp("-d64 <file>\n"); printHelp(" insert D64 disk\n"); printHelp("-tap <file>\n"); printHelp(" attach TAP file\n"); printHelp("-crt <file>\n"); printHelp(" attach cartridge\n"); printHelp("-snapshot <file>\n"); printHelp(" load snapshot from file\n"); printHelp("-jmp <addr>\n"); printHelp(" jmp to address, for example jmp x1000, jmp $1000 or jmp 4096\n"); printHelp("-autojmp\n"); printHelp(" automatically jmp to address if basic SYS is detected\n"); printHelp("-alwaysjmp\n"); printHelp(" always jmp to load address of PRG\n"); printHelp("-autorundisk\n"); printHelp(" automatically load first PRG from inserted disk\n"); #endif printHelp("-unpause\n"); printHelp(" force code running\n"); printHelp("-reset\n"); printHelp(" hard reset machine\n"); #if defined(RUN_ATARI) printHelp("-atari select emulator: Atari800"); printHelp("-xex <file>\n"); printHelp(" load XEX file into memory\n"); printHelp("-atr <file>\n"); printHelp(" insert ATR disk\n"); #endif #if defined(RUN_NES) printHelp("-nes select emulator: NestopiaUE"); printHelp("-ines <file>\n"); printHelp(" insert iNES cartridge\n"); #endif printHelp("-soundout <\"device name\" | device number>\n"); printHelp(" set sound out device by name or number\n"); printHelp("-fullscreen"); printHelp(" start in full screen mode"); printHelp("-playlist <file>\n"); printHelp(" load and start jukebox playlist from json file\n"); printHelp("\n"); printHelp("-clearsettings\n"); printHelp(" clear all config settings\n"); printHelp("-pass\n"); printHelp(" pass parameters to already running instance\n"); printHelp("\n"); } std::vector<const char *>::iterator c64cmdIt; char *c64ParseCommandLineGetArgument() { if (c64cmdIt == sysCommandLineArguments.end()) { c64PrintCommandLineHelp(); SYS_CleanExit(); } const char *arg = *c64cmdIt; c64cmdIt++; LOGD("c64ParseCommandLineGetArgument: arg='%s'", arg); return (char*)arg; } void C64DebuggerParseCommandLine0() { LOGD("C64DebuggerParseCommandLine0"); if (sysCommandLineArguments.empty()) return; // check if it's just a single argument with file path (drop file on exe in Win32) if (sysCommandLineArguments.size() == 1) // 1 , 3 for dev xcode { const char *arg = sysCommandLineArguments[0]; LOGD("arg=%s", arg); if (SYS_FileExists(arg)) { CSlrString *filePath = new CSlrString(arg); filePath->DebugPrint("filePath="); CSlrString *ext = filePath->GetFileExtensionComponentFromPath(); ext->DebugPrint("ext="); #if defined(RUN_COMMODORE64) if (ext->CompareWith("prg") || ext->CompareWith("PRG")) { isPRGInCommandLine = true; const char *path = sysCommandLineArguments[0]; sysCommandLineArguments.clear(); sysCommandLineArguments.push_back("-pass"); sysCommandLineArguments.push_back("-c64"); sysCommandLineArguments.push_back("-wait"); sysCommandLineArguments.push_back("700"); sysCommandLineArguments.push_back("-prg"); sysCommandLineArguments.push_back(path); sysCommandLineArguments.push_back("-autojmp"); // TODO: this will be overwritten by settings loader c64SettingsFastBootKernalPatch = true; LOGD("delete filePath"); delete filePath; // c64SettingsPathToPRG = filePath; c64SettingsWaitOnStartup = 500; // c64SettingsAutoJmp = true; LOGD("delete ext"); delete ext; // pass to running instance if exists C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); return; } else if (ext->CompareWith("d64") || ext->CompareWith("D64") || ext->CompareWith("g64") || ext->CompareWith("G64")) { isD64InCommandLine = true; const char *path = sysCommandLineArguments[0]; sysCommandLineArguments.clear(); sysCommandLineArguments.push_back("-pass"); sysCommandLineArguments.push_back("-c64"); sysCommandLineArguments.push_back("-d64"); sysCommandLineArguments.push_back(path); delete filePath; // c64SettingsPathToD64 = filePath; // c64SettingsWaitOnStartup = 500; delete ext; // pass to running instance if exists C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); return; } else if (ext->CompareWith("tap") || ext->CompareWith("TAP") || ext->CompareWith("t64") || ext->CompareWith("T64")) { isTAPInCommandLine = true; const char *path = sysCommandLineArguments[0]; sysCommandLineArguments.clear(); sysCommandLineArguments.push_back("-pass"); sysCommandLineArguments.push_back("-c64"); sysCommandLineArguments.push_back("-tap"); sysCommandLineArguments.push_back(path); delete filePath; delete ext; // pass to running instance if exists C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); return; } else if (ext->CompareWith("crt") || ext->CompareWith("CRT")) { isCRTInCommandLine = true; const char *path = sysCommandLineArguments[0]; sysCommandLineArguments.clear(); sysCommandLineArguments.push_back("-pass"); sysCommandLineArguments.push_back("-c64"); sysCommandLineArguments.push_back("-crt"); sysCommandLineArguments.push_back(path); delete filePath; // c64SettingsPathToCartridge = filePath; // c64SettingsWaitOnStartup = 500; delete ext; // pass to running instance if exists C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); return; } else if (ext->CompareWith("snap") || ext->CompareWith("SNAP") || ext->CompareWith("vsf") || ext->CompareWith("VSF")) { isSNAPInCommandLine = true; const char *path = sysCommandLineArguments[0]; sysCommandLineArguments.clear(); sysCommandLineArguments.push_back("-pass"); sysCommandLineArguments.push_back("-c64"); sysCommandLineArguments.push_back("-snapshot"); sysCommandLineArguments.push_back(path); delete filePath; // c64SettingsPathToViceSnapshot = filePath; // c64SettingsWaitOnStartup = 500; delete ext; // pass to running instance if exists C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); return; } #endif #if defined(RUN_ATARI) // if (ext->CompareWith("xex") || ext->CompareWith("XEX")) { isXEXInCommandLine = true; const char *path = sysCommandLineArguments[0]; sysCommandLineArguments.clear(); sysCommandLineArguments.push_back("-pass"); sysCommandLineArguments.push_back("-atari"); sysCommandLineArguments.push_back("-wait"); sysCommandLineArguments.push_back("700"); sysCommandLineArguments.push_back("-xex"); sysCommandLineArguments.push_back(path); sysCommandLineArguments.push_back("-autojmp"); // TODO: this will be overwritten by settings loader c64SettingsFastBootKernalPatch = true; LOGD("delete filePath"); delete filePath; // c64SettingsPathToXEX = filePath; c64SettingsWaitOnStartup = 500; // c64SettingsAutoJmp = true; LOGD("delete ext"); delete ext; // pass to running instance if exists C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); return; } else if (ext->CompareWith("atr") || ext->CompareWith("ATR")) { isATRInCommandLine = true; const char *path = sysCommandLineArguments[0]; sysCommandLineArguments.clear(); sysCommandLineArguments.push_back("-pass"); sysCommandLineArguments.push_back("-atari"); sysCommandLineArguments.push_back("-atr"); sysCommandLineArguments.push_back(path); delete filePath; // c64SettingsPathToATR = filePath; // c64SettingsWaitOnStartup = 500; delete ext; // pass to running instance if exists C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); return; } #endif #if defined(RUN_NES) if (ext->CompareWith("nes")) { const char *path = sysCommandLineArguments[0]; sysCommandLineArguments.clear(); sysCommandLineArguments.push_back("-pass"); sysCommandLineArguments.push_back("-nes"); sysCommandLineArguments.push_back("-wait"); sysCommandLineArguments.push_back("100"); sysCommandLineArguments.push_back("-ines"); sysCommandLineArguments.push_back(path); LOGD("delete filePath"); delete filePath; c64SettingsWaitOnStartup = 50; LOGD("delete ext"); delete ext; // pass to running instance if exists C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); return; } #endif delete filePath; delete ext; } } c64cmdIt = sysCommandLineArguments.begin(); while(c64cmdIt != sysCommandLineArguments.end()) { char *cmd = c64ParseCommandLineGetArgument(); if (!strcmp(cmd, "help") || !strcmp(cmd, "h") || !strcmp(cmd, "-help") || !strcmp(cmd, "-h") || !strcmp(cmd, "--help") || !strcmp(cmd, "--h")) { c64PrintCommandLineHelp(); SYS_CleanExit(); } if (!strcmp(cmd, "version") || !strcmp(cmd, "v") || !strcmp(cmd, "-version") || !strcmp(cmd, "-v") || !strcmp(cmd, "--version") || !strcmp(cmd, "--v")) { c64PrintC64DebuggerVersion(); SYS_CleanExit(); } if (!strcmp(cmd, "-pass") || !strcmp(cmd, "pass")) { C64DebuggerInitSharedMemory(); C64DebuggerPassConfigToRunningInstance(); } } } void C64DebuggerParseCommandLine1() { if (sysCommandLineArguments.empty()) return; c64cmdIt = sysCommandLineArguments.begin(); while(c64cmdIt != sysCommandLineArguments.end()) { char *cmd = c64ParseCommandLineGetArgument(); if (!strcmp(cmd, "help") || !strcmp(cmd, "h") || !strcmp(cmd, "-help") || !strcmp(cmd, "-h") || !strcmp(cmd, "--help") || !strcmp(cmd, "--h")) { c64PrintCommandLineHelp(); SYS_CleanExit(); } if (!strcmp(cmd, "version") || !strcmp(cmd, "v") || !strcmp(cmd, "-version") || !strcmp(cmd, "-v") || !strcmp(cmd, "--version") || !strcmp(cmd, "--v")) { c64PrintC64DebuggerVersion(); SYS_CleanExit(); } if (!strcmp(cmd, "-clearsettings") || !strcmp(cmd, "clearsettings")) { c64SettingsSkipConfig = true; printInfo("Skipping loading config\n"); LOGD("Skipping auto loading settings config"); } } } /////////// void C64DebuggerAddStartupTaskCallback(C64DebuggerStartupTaskCallback *callback) { c64DebuggerStartupTasksCallbacksMutex->Lock(); c64DebuggerStartupTasksCallbacks.push_back(callback); c64DebuggerStartupTasksCallbacksMutex->Unlock(); } CSlrString *c64CommandLineAudioOutDevice = NULL; bool c64CommandLineHardReset = false; bool c64CommandLineWindowFullScreen = false; void c64PreRunStartupCallbacks() { c64DebuggerStartupTasksCallbacksMutex->Lock(); if (!c64DebuggerStartupTasksCallbacks.empty()) { LOGD("pre-run c64DebuggerStartupTasksCallbacks"); for (std::list<C64DebuggerStartupTaskCallback *>::iterator it = c64DebuggerStartupTasksCallbacks.begin(); it != c64DebuggerStartupTasksCallbacks.end(); it++) { C64DebuggerStartupTaskCallback *callback = *it; callback->PreRunStartupTaskCallback(); } LOGD("pre-run c64DebuggerStartupTasksCallbacks completed"); } c64DebuggerStartupTasksCallbacksMutex->Unlock(); } void c64PostRunStartupCallbacks() { c64DebuggerStartupTasksCallbacksMutex->Lock(); if (!c64DebuggerStartupTasksCallbacks.empty()) { LOGD("post-run c64DebuggerStartupTasksCallbacks"); while (!c64DebuggerStartupTasksCallbacks.empty()) { C64DebuggerStartupTaskCallback *callback = c64DebuggerStartupTasksCallbacks.front(); callback->PostRunStartupTaskCallback(); c64DebuggerStartupTasksCallbacks.pop_front(); delete callback; } LOGD("post-run c64DebuggerStartupTasksCallbacks completed, tasks deleted"); } c64DebuggerStartupTasksCallbacksMutex->Unlock(); } void c64PerformStartupTasksThreaded() { LOGM("START c64PerformStartupTasksThreaded"); SYS_Sleep(100); guiMain->SetApplicationWindowAlwaysOnTop(c64SettingsWindowAlwaysOnTop); LOGD("c64CommandLineWindowFullScreen=%s", STRBOOL(c64CommandLineWindowFullScreen)); if (c64CommandLineWindowFullScreen) { viewC64->GoFullScreen(NULL); } c64PreRunStartupCallbacks(); if (c64CommandLineAudioOutDevice != NULL) { gSoundEngine->LockMutex("c64PerformStartupTasksThreaded/c64CommandLineAudioOutDevice"); char *cDeviceName = c64CommandLineAudioOutDevice->GetStdASCII(); if (gSoundEngine->SetOutputAudioDevice(cDeviceName) == false) { printInfo("Selected sound out device not found, falling back to default output.\n"); } delete [] cDeviceName; gSoundEngine->UnlockMutex("c64PerformStartupTasksThreaded/c64CommandLineAudioOutDevice"); } // load breakpoints & symbols LOGTODO("c64PerformStartupTasksThreaded: SYMBOLS & BREAKPOINTS FOR BOTH ATARI & C64 + NES. GENERALIZE ME"); CDebugInterface *debugInterface = NULL; if (viewC64->debugInterfaceC64) { debugInterface = viewC64->debugInterfaceC64; } else if (viewC64->debugInterfaceAtari) { debugInterface = viewC64->debugInterfaceAtari; } if (c64SettingsPathToBreakpoints != NULL) { debugInterface->symbols->DeleteAllBreakpoints(); debugInterface->symbols->ParseBreakpoints(c64SettingsPathToBreakpoints); } if (c64SettingsPathToSymbols != NULL) { debugInterface->symbols->DeleteAllSymbols(); debugInterface->symbols->ParseSymbols(c64SettingsPathToSymbols); } if (c64SettingsPathToWatches != NULL) { debugInterface->symbols->DeleteAllWatches(); debugInterface->symbols->ParseWatches(c64SettingsPathToWatches); } if (c64SettingsPathToDebugInfo != NULL) { debugInterface->symbols->DeleteAllSymbols(); debugInterface->symbols->ParseSourceDebugInfo(c64SettingsPathToDebugInfo); } // skip any automatic loading if jukebox is active if (viewC64->viewJukeboxPlaylist != NULL) { if (c64SettingsSIDEngineModel != 0) { //viewC64->debugInterfaceC64->LockMutex(); gSoundEngine->LockMutex("c64PerformStartupTasksThreaded/viewJukeboxPlaylist"); viewC64->debugInterfaceC64->SetSidType(c64SettingsSIDEngineModel); gSoundEngine->UnlockMutex("c64PerformStartupTasksThreaded/viewJukeboxPlaylist"); //viewC64->debugInterfaceC64->UnlockMutex(); } viewC64->viewJukeboxPlaylist->StartPlaylist(); c64PostRunStartupCallbacks(); return; } if (viewC64->debugInterfaceC64) { // process, order is important // we need to create new strings for path as they will be deleted and updated by loaders if (c64SettingsPathToViceSnapshot != NULL) { viewC64->viewC64Snapshots->LoadSnapshot(c64SettingsPathToViceSnapshot, false, viewC64->debugInterfaceC64); SYS_Sleep(150); } else { // DONE?: Is it possible to init VICE with proper Engines at startup to not re-create here? // DONE?: Vice 3.1 by default starts with strange model (unknown=99), check cmdline parsing how it's handled in VICE if (c64SettingsC64Model != 0) { // SYS_Sleep(300); // viewC64->debugInterface->SetC64ModelType(c64SettingsC64Model); } // setup SID if (c64SettingsSIDEngineModel != 0) { gSoundEngine->LockMutex("c64PerformStartupTasksThreaded"); viewC64->debugInterfaceC64->SetSidType(c64SettingsSIDEngineModel); gSoundEngine->UnlockMutex("c64PerformStartupTasksThreaded"); } // if (c64SettingsPathToD64 != NULL) { LOGD("isPRGInCommandLine=%s", STRBOOL(isPRGInCommandLine)); if (isPRGInCommandLine == false && isD64InCommandLine == true) { // start disk based on settings if (c64SettingsAutoJmpFromInsertedDiskFirstPrg) { SYS_Sleep(100); } viewC64->viewC64MainMenu->InsertD64(c64SettingsPathToD64, false, c64SettingsAutoJmpFromInsertedDiskFirstPrg, 0, true); } else { // just load disk, do not start, we will start PRG instead viewC64->viewC64MainMenu->InsertD64(c64SettingsPathToD64, false, false, 0, false); } } if (c64SettingsPathToTAP != NULL) { // LOGD("isPRGInCommandLine=%s", STRBOOL(isPRGInCommandLine)); // if (isPRGInCommandLine == false && isD64InCommandLine == true) // { // // start disk based on settings // if (c64SettingsAutoJmpFromInsertedDiskFirstPrg) // { // SYS_Sleep(100); // } // viewC64->viewC64MainMenu->InsertD64(c64SettingsPathToD64, false, c64SettingsAutoJmpFromInsertedDiskFirstPrg, 0, true); // } // else { // just load tape, do not start viewC64->viewC64MainMenu->LoadTape(c64SettingsPathToTAP, false, false, false); } } if (c64SettingsPathToCartridge != NULL) { viewC64->viewC64MainMenu->InsertCartridge(c64SettingsPathToCartridge, false); SYS_Sleep(666); } } if (c64SettingsPathToPRG != NULL) { LOGD("c64PerformStartupTasksThreaded: loading PRG, isPRGInCommandLine=%s isD64InCommandLine=%s", STRBOOL(isPRGInCommandLine), STRBOOL(isD64InCommandLine)); c64SettingsPathToPRG->DebugPrint("c64SettingsPathToPRG="); if ((isPRGInCommandLine == false) && (isD64InCommandLine == true) && c64SettingsAutoJmpFromInsertedDiskFirstPrg) { // do not load prg when disk inserted from command line and autostart } else //if (isPRGInCommandLine == true) { viewC64->viewC64MainMenu->LoadPRG(c64SettingsPathToPRG, c64SettingsAutoJmp, false, true, false); } } if (c64CommandLineHardReset) { viewC64->debugInterfaceC64->HardReset(); } } // /////////// // if (viewC64->debugInterfaceAtari) // { // viewC64->debugInterfaceAtari->SetMachineType(c64SettingsAtariMachineType); // viewC64->debugInterfaceAtari->SetVideoSystem(c64SettingsAtariVideoSystem); // } if (viewC64->debugInterfaceAtari) { // process, order is important // we need to create new strings for path as they will be deleted and updated by loaders // TODO: change command line to detect type of snapshot // if (c64SettingsPathToAtariSnapshot != NULL) // { // viewC64->viewAtariSnapshots->LoadSnapshot(c64SettingsPathToAtariSnapshot, false); // SYS_Sleep(150); // } // else { // if (c64SettingsPathToATR != NULL) { LOGD("isXEXInCommandLine=%s", STRBOOL(isXEXInCommandLine)); if (isXEXInCommandLine == false && isATRInCommandLine == true) { // start disk based on settings if (c64SettingsAutoJmpFromInsertedDiskFirstPrg) { SYS_Sleep(100); } viewC64->viewC64MainMenu->InsertATR(c64SettingsPathToATR, false, c64SettingsAutoJmpFromInsertedDiskFirstPrg, 0, true); } else { // just load disk, do not start, we will start XEX instead viewC64->viewC64MainMenu->InsertATR(c64SettingsPathToATR, false, false, 0, false); } } // TODO: Atari TAPE files // if (c64SettingsPathToTAP != NULL) // { // // LOGD("isPRGInCommandLine=%s", STRBOOL(isPRGInCommandLine)); // // if (isPRGInCommandLine == false && isD64InCommandLine == true) // // { // // // start disk based on settings // // if (c64SettingsAutoJmpFromInsertedDiskFirstPrg) // // { // // SYS_Sleep(100); // // } // // viewC64->viewC64MainMenu->InsertD64(c64SettingsPathToD64, false, c64SettingsAutoJmpFromInsertedDiskFirstPrg, 0, true); // // } // // else // { // // just load tape, do not start // viewC64->viewC64MainMenu->LoadTape(c64SettingsPathToTAP, false, false, false); // } // } // TODO: ATARI Cartridge command line // if (c64SettingsPathToCartridge != NULL) // { // viewC64->viewC64MainMenu->InsertCartridge(c64SettingsPathToCartridge, false); // SYS_Sleep(666); // } if (c64CommandLineHardReset) { viewC64->debugInterfaceAtari->HardReset(); } } if (c64SettingsPathToXEX != NULL) { LOGD("c64PerformStartupTasksThreaded: loading XEX, isXEXInCommandLine=%s isATRInCommandLine=%s", STRBOOL(isXEXInCommandLine), STRBOOL(isATRInCommandLine)); c64SettingsPathToXEX->DebugPrint("c64SettingsPathToXEX="); if ((isXEXInCommandLine == false) && (isATRInCommandLine == true) && c64SettingsAutoJmpFromInsertedDiskFirstPrg) { // do not load xex when disk inserted from command line and autostart } else //if (isXEXInCommandLine == true) { viewC64->viewC64MainMenu->LoadXEX(c64SettingsPathToXEX, c64SettingsAutoJmp, false, true); } } } /////////// if (viewC64->debugInterfaceNes) { if (c64SettingsPathToNES != NULL) { viewC64->viewC64MainMenu->LoadNES(c64SettingsPathToNES, false); } } if (c64SettingsJmpOnStartupAddr > 0 && c64SettingsJmpOnStartupAddr < 0x10000) { //SYS_Sleep(150); LOGD("c64PerformStartupTasksThreaded: c64SettingsJmpOnStartupAddr=%04x", c64SettingsJmpOnStartupAddr); viewC64->debugInterfaceC64->MakeJsrC64(c64SettingsJmpOnStartupAddr); } // if (viewC64->debugInterfaceC64) { viewC64->viewVicEditor->RunDebug(); } c64PostRunStartupCallbacks(); } class C64PerformStartupTasksThread : public CSlrThread { virtual void ThreadRun(void *data) { LOGM("C64PerformStartupTasksThread: ThreadRun"); if (c64SettingsPathToViceSnapshot != NULL && c64SettingsWaitOnStartup < 150) c64SettingsWaitOnStartup = 150; if (c64SettingsPathToAtariSnapshot != NULL && c64SettingsWaitOnStartup < 150) c64SettingsWaitOnStartup = 150; if (c64dStartupTime == 0 || (SYS_GetCurrentTimeInMillis() - c64dStartupTime < 100)) { LOGD("C64PerformStartupTasksThread: early run, wait 100ms"); c64SettingsWaitOnStartup += 100; } LOGD("C64PerformStartupTasksThread: c64SettingsWaitOnStartup=%d", c64SettingsWaitOnStartup); SYS_Sleep(c64SettingsWaitOnStartup); c64PerformStartupTasksThreaded(); }; }; //////////////////////// void C64DebuggerParseCommandLine2() { LOGD("C64DebuggerParseCommandLine2"); if (sysCommandLineArguments.empty()) return; c64cmdIt = sysCommandLineArguments.begin(); LOGD("C64DebuggerParseCommandLine2: iterate"); while(c64cmdIt != sysCommandLineArguments.end()) { char *cmd = c64ParseCommandLineGetArgument(); //LOGD("...cmd='%s'", cmd); if (cmd[0] == '-') cmd++; if (!strcmp(cmd, "c64")) { c64SettingsSelectEmulator = EMULATOR_TYPE_C64_VICE; } else if (!strcmp(cmd, "atari")) { c64SettingsSelectEmulator = EMULATOR_TYPE_ATARI800; } else if (!strcmp(cmd, "nes")) { c64SettingsSelectEmulator = EMULATOR_TYPE_NESTOPIA; } else if (!strcmp(cmd, "breakpoints") || !strcmp(cmd, "b")) { char *arg = c64ParseCommandLineGetArgument(); c64SettingsPathToBreakpoints = new CSlrString(arg); } else if (!strcmp(cmd, "symbols") || !strcmp(cmd, "vicesymbols") || !strcmp(cmd, "vs")) { char *arg = c64ParseCommandLineGetArgument(); c64SettingsPathToSymbols = new CSlrString(arg); } else if (!strcmp(cmd, "watch") || !strcmp(cmd, "w")) { char *arg = c64ParseCommandLineGetArgument(); c64SettingsPathToWatches = new CSlrString(arg); } else if (!strcmp(cmd, "debuginfo")) { char *arg = c64ParseCommandLineGetArgument(); c64SettingsPathToDebugInfo = new CSlrString(arg); } else if (!strcmp(cmd, "autojmp") || !strcmp(cmd, "autojump")) { c64SettingsAutoJmp = true; } else if (!strcmp(cmd, "unpause")) { c64SettingsForceUnpause = true; } else if (!strcmp(cmd, "autorundisk")) { c64SettingsAutoJmpFromInsertedDiskFirstPrg = true; } else if (!strcmp(cmd, "alwaysjmp") || !strcmp(cmd, "alwaysjump")) { c64SettingsAutoJmpAlwaysToLoadedPRGAddress = true; } else if (!strcmp(cmd, "d64")) { char *arg = c64ParseCommandLineGetArgument(); c64SettingsPathToD64 = new CSlrString(arg); isD64InCommandLine = true; } else if (!strcmp(cmd, "tap")) { char *arg = c64ParseCommandLineGetArgument(); c64SettingsPathToTAP = new CSlrString(arg); } else if (!strcmp(cmd, "prg")) { char *arg = c64ParseCommandLineGetArgument(); LOGD("C64DebuggerParseCommandLine2: set c64SettingsPathToPRG=%s", arg); c64SettingsPathToPRG = new CSlrString(arg); } else if (!strcmp(cmd, "cartridge")) { char *arg = c64ParseCommandLineGetArgument(); c64SettingsPathToCartridge = new CSlrString(arg); } else if (!strcmp(cmd, "snapshot")) { char *arg = c64ParseCommandLineGetArgument(); c64SettingsPathToViceSnapshot = new CSlrString(arg); } else if (!strcmp(cmd, "xex")) { char *arg = c64ParseCommandLineGetArgument(); LOGD("C64DebuggerParseCommandLine2: set c64SettingsPathToXEX=%s", arg); c64SettingsPathToXEX = new CSlrString(arg); } else if (!strcmp(cmd, "atr")) { char *arg = c64ParseCommandLineGetArgument(); LOGD("C64DebuggerParseCommandLine2: set c64SettingsPathToATR=%s", arg); c64SettingsPathToATR = new CSlrString(arg); } else if (!strcmp(cmd, "nes")) { char *arg = c64ParseCommandLineGetArgument(); LOGD("C64DebuggerParseCommandLine2: set c64SettingsPathToNES=%s", arg); c64SettingsPathToNES = new CSlrString(arg); } else if (!strcmp(cmd, "jmp")) { int addr; char *str = c64ParseCommandLineGetArgument(); if (str[0] == '$' || str[0] == 'x') { // hex str++; sscanf(str, "%x", &addr); } else { sscanf(str, "%d", &addr); } c64SettingsJmpOnStartupAddr = addr; } else if (!strcmp(cmd, "layout")) { int layoutId; char *str = c64ParseCommandLineGetArgument(); layoutId = atoi(str)-1; c64SettingsDefaultScreenLayoutId = layoutId; LOGD("c64SettingsDefaultScreenLayoutId=%d", layoutId); } else if (!strcmp(cmd, "wait")) { char *str = c64ParseCommandLineGetArgument(); c64SettingsWaitOnStartup = atoi(str); } else if (!strcmp(cmd, "soundout")) { char *str = c64ParseCommandLineGetArgument(); LOGD("soundout='%s'", str); c64CommandLineAudioOutDevice = new CSlrString(str); } else if (!strcmp(cmd, "playlist") || !strcmp(cmd, "jukebox")) { char *str = c64ParseCommandLineGetArgument(); LOGD("playlist='%s'", str); c64SettingsPathToJukeboxPlaylist = new CSlrString(str); } else if (!strcmp(cmd, "reset")) { c64CommandLineHardReset = true; } else if (!strcmp(cmd, "fullscreen")) { c64CommandLineWindowFullScreen = true; } // TODO: fixme, plugins should also parse command line options else if (!strcmp(cmd, "crtmaker")) { char *str = c64ParseCommandLineGetArgument(); LOGD("crtMakerConfigFilePath='%s'", str); crtMakerConfigFilePath = STRALLOC(str); c64SettingsPathToCartridge = NULL; } } } void C64DebuggerPerformStartupTasks() { LOGM("C64DebuggerPerformStartupTasks()"); C64PerformStartupTasksThread *thread = new C64PerformStartupTasksThread(); thread->ThreadSetName("C64PerformStartupTasksThread"); SYS_StartThread(thread, NULL); } // void C64DebuggerPassConfigToRunningInstance() { //NSLog(@"C64DebuggerPassConfigToRunningInstance"); SYS_AttachConsole(); c64SettingsPassConfigToRunningInstance = true; printLine("-----< RetroDebugger v%s by Slajerek/Samar >------\n", RETRODEBUGGER_VERSION_STRING); fflush(stdout); //printLine("Passing parameters to running instance\n"); LOGD("C64DebuggerPassConfigToRunningInstance: C64DebuggerParseCommandLine2"); c64SettingsForceUnpause = false; C64DebuggerParseCommandLine2(); LOGD("C64DebuggerPassConfigToRunningInstance: after C64DebuggerParseCommandLine2"); // check if we need just to pass parameters to other running instance // and pass them if necessary CByteBuffer *byteBuffer = new CByteBuffer(); LOGD("...C64D_PASS_CONFIG_DATA_MARKER"); byteBuffer->PutU16(C64D_PASS_CONFIG_DATA_MARKER); byteBuffer->PutU16(C64D_PASS_CONFIG_DATA_VERSION); LOGD("... put folder"); gUTFPathToCurrentDirectory->DebugPrint("gUTFPathToCurrentDirectory="); byteBuffer->PutSlrString(gUTFPathToCurrentDirectory); if (c64SettingsSelectEmulator != EMULATOR_TYPE_UNKNOWN) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_SELECT_EMULATOR); byteBuffer->PutU8(c64SettingsSelectEmulator); } if (c64SettingsPathToViceSnapshot) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_LOAD_SNAPSHOT_VICE); byteBuffer->PutSlrString(c64SettingsPathToViceSnapshot); } if (c64SettingsPathToBreakpoints) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_BREAKPOINTS_FILE); byteBuffer->PutSlrString(c64SettingsPathToBreakpoints); } if (c64SettingsPathToSymbols) { LOGD("c64SettingsPathToSymbols"); c64SettingsPathToSymbols->DebugPrint("c64SettingsPathToSymbols="); byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_SYMBOLS_FILE); byteBuffer->PutSlrString(c64SettingsPathToSymbols); } if (c64SettingsPathToWatches) { LOGD("c64SettingsPathToWatches"); c64SettingsPathToWatches->DebugPrint("c64SettingsPathToWatches="); byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_WATCHES_FILE); byteBuffer->PutSlrString(c64SettingsPathToWatches); } if (c64SettingsPathToDebugInfo) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_DEBUG_INFO); byteBuffer->PutSlrString(c64SettingsPathToDebugInfo); } if (c64CommandLineHardReset) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_HARD_RESET); } if (c64SettingsWaitOnStartup > 0) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_WAIT); byteBuffer->putInt(c64SettingsWaitOnStartup); } if (c64SettingsPathToCartridge) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_PATH_TO_CRT); byteBuffer->PutSlrString(c64SettingsPathToCartridge); } if (c64SettingsPathToD64) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_PATH_TO_D64); byteBuffer->PutSlrString(c64SettingsPathToD64); } if (c64SettingsPathToTAP) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_PATH_TO_TAP); byteBuffer->PutSlrString(c64SettingsPathToTAP); } if (c64SettingsPathToXEX) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_PATH_TO_XEX); byteBuffer->PutSlrString(c64SettingsPathToXEX); } if (c64SettingsPathToNES) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_PATH_TO_NES); byteBuffer->PutSlrString(c64SettingsPathToNES); } if (c64SettingsPathToATR) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_PATH_TO_ATR); byteBuffer->PutSlrString(c64SettingsPathToATR); } if (c64SettingsAutoJmp) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_SET_AUTOJMP); byteBuffer->PutBool(c64SettingsAutoJmp); } if (c64SettingsForceUnpause) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_FORCE_UNPAUSE); byteBuffer->PutBool(c64SettingsForceUnpause); } if (c64SettingsAutoJmpFromInsertedDiskFirstPrg) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_AUTO_RUN_DISK); byteBuffer->PutBool(c64SettingsAutoJmpFromInsertedDiskFirstPrg); } if (c64SettingsAutoJmpAlwaysToLoadedPRGAddress) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_ALWAYS_JMP); byteBuffer->PutBool(c64SettingsAutoJmpAlwaysToLoadedPRGAddress); } if (c64SettingsPathToPRG) { LOGD("c64SettingsPathToPRG"); c64SettingsPathToPRG->DebugPrint("c64SettingsPathToPRG="); byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_PATH_TO_PRG); byteBuffer->PutSlrString(c64SettingsPathToPRG); } if (c64SettingsJmpOnStartupAddr >= 0) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_JMP); byteBuffer->putInt(c64SettingsJmpOnStartupAddr); } if (c64SettingsDefaultScreenLayoutId >= 0) { LOGD("c64SettingsDefaultScreenLayoutId=%d", c64SettingsDefaultScreenLayoutId); byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_LAYOUT); byteBuffer->putInt(c64SettingsDefaultScreenLayoutId); } if (c64CommandLineAudioOutDevice != NULL) { LOGD("c64CommandLineAudioOutDevice"); byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_SOUND_DEVICE_OUT); byteBuffer->PutSlrString(c64CommandLineAudioOutDevice); } if (c64CommandLineWindowFullScreen) { byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_FULL_SCREEN); } LOGD("...C64D_PASS_CONFIG_DATA_EOF"); byteBuffer->PutU8(C64D_PASS_CONFIG_DATA_EOF); int pid = C64DebuggerSendConfiguration(byteBuffer); if (pid > 0) { printLine("Parameters sent to instance pid=%d. Bye.\n", pid); fflush(stdout); SYS_CleanExit(); } else { printLine("Other instance was not found, performing regular startup instead.\n"); fflush(stdout); } } void c64PerformNewConfigurationTasksThreaded(CByteBuffer *byteBuffer) { LOGD("c64PerformNewConfigurationTasksThreaded"); //byteBuffer->DebugPrint(); byteBuffer->Rewind(); u16 marker = byteBuffer->GetU16(); if (marker != C64D_PASS_CONFIG_DATA_MARKER) { LOGError("Config data marker not found (received %04x, should be %04x)", marker, C64D_PASS_CONFIG_DATA_MARKER); return; } u16 v = byteBuffer->GetU16(); if (v != C64D_PASS_CONFIG_DATA_VERSION) { LOGError("Config data version not correct (received %04x, should be %04x)", v, C64D_PASS_CONFIG_DATA_VERSION); return; } CSlrString *currentFolder = byteBuffer->GetSlrString(); LOGD("... got folder"); currentFolder->DebugPrint("currentFolder="); SYS_SetCurrentFolder(currentFolder); delete currentFolder; CDebugInterface *debugInterface = viewC64->debugInterfaces.front(); // select default emulator as the first that is running for (std::vector<CDebugInterface *>::iterator it = viewC64->debugInterfaces.begin(); it != viewC64->debugInterfaces.end(); it++) { CDebugInterface *d = *it; if (d->isRunning) { debugInterface = d; } } while(!byteBuffer->IsEof()) { uint8 t = byteBuffer->GetU8(); if (t == C64D_PASS_CONFIG_DATA_EOF) break; LOGD("Process passed message=%d", t); if (t == C64D_PASS_CONFIG_DATA_WAIT) { int wait = byteBuffer->getInt(); LOGD("C64D_PASS_CONFIG_DATA_WAIT: %dms", wait); SYS_Sleep(wait); } else if (t == C64D_PASS_CONFIG_DATA_SELECT_EMULATOR) { u8 emulatorType = byteBuffer->GetU8(); c64SettingsSelectEmulator = emulatorType; debugInterface = viewC64->GetDebugInterface(emulatorType); if (debugInterface->isRunning == false) { viewC64->StartEmulationThread(debugInterface); } } else if (t == C64D_PASS_CONFIG_DATA_LOAD_SNAPSHOT_VICE) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64Snapshots->LoadSnapshot(str, false, viewC64->debugInterfaceC64); delete str; SYS_Sleep(150); } else if (t == C64D_PASS_CONFIG_DATA_LOAD_SNAPSHOT_ATARI800) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64Snapshots->LoadSnapshot(str, false, viewC64->debugInterfaceAtari); delete str; SYS_Sleep(150); } else if (t == C64D_PASS_CONFIG_DATA_LOAD_SNAPSHOT_NESTOPIA) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64Snapshots->LoadSnapshot(str, false, viewC64->debugInterfaceNes); delete str; SYS_Sleep(150); } else if (t == C64D_PASS_CONFIG_DATA_BREAKPOINTS_FILE) { CSlrString *str = byteBuffer->GetSlrString(); debugInterface->symbols->DeleteAllBreakpoints(); debugInterface->symbols->ParseBreakpoints(str); delete str; } else if (t == C64D_PASS_CONFIG_DATA_SYMBOLS_FILE) { CSlrString *str = byteBuffer->GetSlrString(); debugInterface->symbols->DeleteAllSymbols(); debugInterface->symbols->ParseSymbols(str); delete str; } else if (t == C64D_PASS_CONFIG_DATA_WATCHES_FILE) { CSlrString *str = byteBuffer->GetSlrString(); debugInterface->symbols->DeleteAllWatches(); debugInterface->symbols->ParseWatches(str); delete str; } else if (t == C64D_PASS_CONFIG_DATA_DEBUG_INFO) { CSlrString *str = byteBuffer->GetSlrString(); debugInterface->symbols->DeleteAllSymbols(); debugInterface->symbols->ParseSymbols(str); delete str; } else if (t == C64D_PASS_CONFIG_DATA_PATH_TO_D64) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64MainMenu->InsertD64(str, false, c64SettingsAutoJmpFromInsertedDiskFirstPrg, 0, true); delete str; } else if (t == C64D_PASS_CONFIG_DATA_PATH_TO_TAP) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64MainMenu->LoadTape(str, false, false, true); delete str; } else if (t == C64D_PASS_CONFIG_DATA_PATH_TO_CRT) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64MainMenu->InsertCartridge(str, false); SYS_Sleep(666); delete str; } else if (t == C64D_PASS_CONFIG_DATA_PATH_TO_XEX) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64MainMenu->LoadXEX(str, c64SettingsAutoJmp, false, true); delete str; } else if (t == C64D_PASS_CONFIG_DATA_PATH_TO_ATR) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64MainMenu->InsertATR(str, false, c64SettingsAutoJmpFromInsertedDiskFirstPrg, 0, true); delete str; } else if (t == C64D_PASS_CONFIG_DATA_PATH_TO_NES) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64MainMenu->LoadNES(str, true); delete str; } else if (t == C64D_PASS_CONFIG_DATA_SET_AUTOJMP) { bool b = byteBuffer->GetBool(); c64SettingsAutoJmp = b; } else if (t == C64D_PASS_CONFIG_DATA_FORCE_UNPAUSE) { bool b = byteBuffer->GetBool(); c64SettingsForceUnpause = b; } else if (t == C64D_PASS_CONFIG_DATA_AUTO_RUN_DISK) { bool b = byteBuffer->GetBool(); c64SettingsAutoJmpFromInsertedDiskFirstPrg = b; } else if (t == C64D_PASS_CONFIG_DATA_ALWAYS_JMP) { bool b = byteBuffer->GetBool(); c64SettingsAutoJmpAlwaysToLoadedPRGAddress = b; } else if (t == C64D_PASS_CONFIG_DATA_PATH_TO_PRG) { CSlrString *str = byteBuffer->GetSlrString(); viewC64->viewC64MainMenu->LoadPRG(str, c64SettingsAutoJmp, false, true, false); delete str; } // else if (t == C64D_PASS_CONFIG_DATA_LAYOUT) // { // int layoutId = byteBuffer->getInt(); // c64SettingsDefaultScreenLayoutId = layoutId; // if (c64SettingsDefaultScreenLayoutId >= SCREEN_LAYOUT_MAX) // { // c64SettingsDefaultScreenLayoutId = SCREEN_LAYOUT_C64_DEBUGGER; // } // LOGError("Layout selection not supported yet"); //// viewC64->SwitchToScreenLayout(c64SettingsDefaultScreenLayoutId); // // } else if (t == C64D_PASS_CONFIG_DATA_JMP) { int jmpAddr = byteBuffer->getInt(); viewC64->debugInterfaceC64->MakeJsrC64(jmpAddr); } else if (t == C64D_PASS_CONFIG_DATA_SOUND_DEVICE_OUT) { CSlrString *str = byteBuffer->GetSlrString(); char *cDeviceName = str->GetStdASCII(); if (gSoundEngine->SetOutputAudioDevice(cDeviceName) == false) { printInfo("Selected sound out device not found, fall back to default output.\n"); } delete [] cDeviceName; delete str; } else if (t == C64D_PASS_CONFIG_DATA_HARD_RESET) { debugInterface->HardReset(); } else if (t == C64D_PASS_CONFIG_DATA_FULL_SCREEN) { viewC64->GoFullScreen(NULL); } } if (c64SettingsForceUnpause) { if (viewC64->debugInterfaceC64) { viewC64->debugInterfaceC64->SetDebugMode(DEBUGGER_MODE_RUNNING); } if (viewC64->debugInterfaceAtari) { viewC64->debugInterfaceAtari->SetDebugMode(DEBUGGER_MODE_RUNNING); } if (viewC64->debugInterfaceNes) { viewC64->debugInterfaceNes->SetDebugMode(DEBUGGER_MODE_RUNNING); } } //guiMain->ShowMessage("updated"); delete byteBuffer; } class C64PerformNewConfigurationTasksThread : public CSlrThread { virtual void ThreadRun(void *data) { LOGD("C64PerformNewConfigurationTasksThread: ThreadRun"); CByteBuffer *byteBuffer = (CByteBuffer *)data; c64PerformNewConfigurationTasksThreaded(byteBuffer); }; }; void C64DebuggerPerformNewConfigurationTasks(CByteBuffer *byteBuffer) { CByteBuffer *copyByteBuffer = new CByteBuffer(byteBuffer); C64PerformNewConfigurationTasksThread *thread = new C64PerformNewConfigurationTasksThread(); SYS_StartThread(thread, copyByteBuffer); } void C64DebuggerStartupTaskCallback::PreRunStartupTaskCallback() { } void C64DebuggerStartupTaskCallback::PostRunStartupTaskCallback() { } // //{ // //// TEST // // LOGD("CViewC64::DoTap: TEST C64DebuggerSendConfiguration"); // CByteBuffer *b = new CByteBuffer(); // b->PutFloat(x); // b->PutFloat(y); // // C64DebuggerSendConfiguration(b); // //}
28.236721
158
0.713592
[ "vector", "model" ]
dad5435b636d3fa0c70381da422d175ad8aaa81c
1,678
cpp
C++
3569-degrees_of_separation/3569-degrees_of_separation.cpp
ErwanCheriaux/INF280
79234b6cc9dbd08d4dd02b76928a7e48ae396a2f
[ "Xnet", "X11" ]
null
null
null
3569-degrees_of_separation/3569-degrees_of_separation.cpp
ErwanCheriaux/INF280
79234b6cc9dbd08d4dd02b76928a7e48ae396a2f
[ "Xnet", "X11" ]
null
null
null
3569-degrees_of_separation/3569-degrees_of_separation.cpp
ErwanCheriaux/INF280
79234b6cc9dbd08d4dd02b76928a7e48ae396a2f
[ "Xnet", "X11" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <cstring> #include <iostream> #include <cstdint> #include <algorithm> #include <vector> #include <map> using namespace std; const int MAXN = 50; vector<int> Adj[MAXN]; map<string,int> node; int N, MAXLEN; int Dist[MAXN][MAXN]; void FloydWarshall(); int main(void) { int cpt = 1; while(1) { int P, R, index=0, degree_of_separation=0; scanf("%d %d", &P, &R); if(!P and !R) return 0; node.clear(); for(int i=0; i<MAXN; i++) Adj[i].clear(); for(int i=0; i<R; i++) { string str1, str2; cin >> str1 >> str2; if(node.find(str1) == node.end()) node[str1] = index++; if(node.find(str2) == node.end()) node[str2] = index++; Adj[node[str1]].push_back(node[str2]); Adj[node[str2]].push_back(node[str1]); } N = MAXLEN = P; FloydWarshall(); for(int i=0; i<N; i++) for(int j=0; j<N; j++) degree_of_separation = max(degree_of_separation,Dist[i][j]); if(degree_of_separation >= N) printf("Network %d: DISCONNECTED\n\n", cpt++); else printf("Network %d: %d\n\n", cpt++, degree_of_separation); } } /* Alogorithme récupéré dans les slides de cours */ void FloydWarshall() { fill_n((int *)Dist, MAXN * MAXN, MAXLEN); for(int u=0; u < N; u++) { Dist[u][u] = 0; for(auto v : Adj[u]) Dist[u][v] = 1; } for(int k=0; k < N; k++) // check sub-path combinations for(int i=0; i < N; i++) for(int j=0; j < N; j++) // concatenate paths Dist[i][j] = min(Dist[i][j], Dist[i][k] + Dist[k][j]); }
22.675676
94
0.533373
[ "vector" ]
dad884060e7b374b84cd943bfc3625973c7e5a6a
6,532
cpp
C++
config.cpp
fledge-iot/fledge-notify-setpoint
63839608ac6cf2841f5aa26dd663c4f7f8d9b2a6
[ "Apache-2.0" ]
null
null
null
config.cpp
fledge-iot/fledge-notify-setpoint
63839608ac6cf2841f5aa26dd663c4f7f8d9b2a6
[ "Apache-2.0" ]
2
2021-04-19T13:13:27.000Z
2021-05-27T13:46:02.000Z
config.cpp
fledge-iot/fledge-notify-setpoint
63839608ac6cf2841f5aa26dd663c4f7f8d9b2a6
[ "Apache-2.0" ]
null
null
null
/* * FogLAMP Configuration Delivery plugin * * Copyright (c) 2020 Dianomic Systems * * Released under the Apache 2.0 Licence * * Author: Mark Riddoch */ #include <plugin_api.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string> #include <logger.h> #include <plugin_exception.h> #include <iostream> #include <config_category.h> #include "rapidjson/document.h" #include <rapidjson/ostreamwrapper.h> #include <rapidjson/error/en.h> #include <rapidjson/writer.h> #include <rapidjson/pointer.h> #include <sstream> #include <unistd.h> #include <query.h> #include <where.h> #include <config.h> #include <JSONPath.h> #include <string_utils.h> using namespace std; using namespace rapidjson; /** * Construct for ConfigJSONDelivery class * * @param category The configuration of the plugin */ ConfigJSONDelivery::ConfigJSONDelivery(ConfigCategory *category) { // Configuration set is protected by a lock lock_guard<mutex> guard(m_configMutex); // Create default values m_enable = false; // Set configuration this->configure(category); } /** * The destructor for the ConfigJSONDelivery class */ ConfigJSONDelivery::~ConfigJSONDelivery() { } /** * Send a notification This simply sets a configuration option * * @param notificationName The name of this notification * @param triggerReason Why the notification is being sent * @param message The message to send */ bool ConfigJSONDelivery::notify(const string& notificationName, const string& triggerReason, const string& customMessage) { Logger::getLogger()->info("Delivery plugin %s: " "JSON trigger reason '%s'", PLUGIN_NAME, triggerReason.c_str()); // Configuration fetch is protected by a mutex m_configMutex.lock(); // Check for enable and for required clients if (!m_enable || !m_mngmtClient) { // Release lock m_configMutex.unlock(); return false; } /* * Parse the triggerReason docuemnt and determine of this is a * trigger event or a clear event. Then set the value accordingly */ string value; Document doc; doc.Parse(triggerReason.c_str()); if (!doc.HasParseError()) { if (doc.HasMember("reason")) { if (doc["reason"].IsString()) { string reasonStr = doc["reason"].GetString(); if (reasonStr.compare("triggered") == 0) { value = m_triggerValue; } else { value = m_clearValue; } } else { return false; } } else { return false; } } else { return false; } string category = m_category; string item = m_item; // Release lock m_configMutex.unlock(); // Update the configuration item with the new value try { ConfigCategory config = m_mngmtClient->getCategory(category); if (config.isJSON(item)) { string json = config.getValue(item); json = setValue(json, value); StringEscapeQuotes(json); string res = m_mngmtClient->setCategoryItemValue(category, item, json); } else { Logger::getLogger()->error("Configuration item %s is not a JSON item", item.c_str()); } return true; } catch (exception &e) { Logger::getLogger()->error("Failed to set value %s for item %s in category %s, %s", value.c_str(), item.c_str(), category.c_str(), e.what()); return false; } } /** * Reconfigure the delivery plugin * * @param newConfig The new configuration */ void ConfigJSONDelivery::reconfigure(const string& newConfig) { ConfigCategory category("new", newConfig); // Configuration change is protected by a lock lock_guard<mutex> guard(m_configMutex); // Set the new configuration this->configure(&category); } /** * Configure the delivery plugin * * @param category The plugin configuration */ void ConfigJSONDelivery::configure(ConfigCategory *category) { // Get the configuration category we are changing if (category->itemExists("category")) { m_category = category->getValue("category"); } // Get the item in the configuration category if (category->itemExists("item")) { m_item = category->getValue("item"); } // Get the JSON Path in the configuration item to set if (category->itemExists("path")) { m_path = category->getValue("path"); } // Get the JSON property in the configuration item to set if (category->itemExists("property")) { m_property = category->getValue("property"); } // Get value to set on triggering if (category->itemExists("triggerValue")) { m_triggerValue = category->getValue("triggerValue"); } // Get value to set on clearing if (category->itemExists("clearValue")) { m_clearValue = category->getValue("clearValue"); } if (category->itemExists("enable")) { m_enable = category->getValue("enable").compare("true") == 0 || category->getValue("enable").compare("True") == 0; } } /** * Update the JSON configuration item and return the new item. * * Use the m_path to determine the item to update and then set it to value * * @param json The JSON to modify * @param value THe new value to set * @return The updated JSON or throws a runtime error if the path was not matched */ string ConfigJSONDelivery::setValue(string& json, const string& value) { Document d; if (d.Parse(json.c_str()).HasParseError()) { Logger::getLogger()->error("Failed to parse configuration item, %s at %u", GetParseError_En(d.GetParseError()), (unsigned)d.GetErrorOffset()); Logger::getLogger()->error("Item is: '%s'", json.c_str()); throw runtime_error("Invalid JSON in configuration item"); } const char *val = value.c_str(); JSONPath path(m_path); Value *jval = path.findNode(d); if (!jval->IsObject()) { Logger::getLogger()->error("The path %s does not specify a JSON object", m_path.c_str()); throw runtime_error("Path does not reference an object"); } if (jval->HasMember(m_property.c_str())) { Value& item = (*jval)[m_property.c_str()]; if (item.IsString()) { item.SetString(value.c_str(), value.size(), d.GetAllocator()); } else if (item.IsInt()) { long ival = strtol(value.c_str(), NULL, 10); item.SetInt64(ival); } else if (item.IsDouble()) { double dval = strtod(value.c_str(), NULL); item.SetDouble(dval); } } else { Logger::getLogger()->error("The path %s does not contain a property called %s", m_path.c_str(), m_property.c_str()); throw runtime_error("Path does not contain configured item"); } StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); const char *config = buffer.GetString(); return string(config); }
23.412186
91
0.686314
[ "object" ]
dae19955d72071568dbffe8b2e0d4ac5e863d028
3,742
cpp
C++
04_Cap04/ModuleScene.cpp
Gabroide/DevelopingAnEngine
096b4f8ddcf7b17819e256a4fd56934c953493f5
[ "MIT" ]
null
null
null
04_Cap04/ModuleScene.cpp
Gabroide/DevelopingAnEngine
096b4f8ddcf7b17819e256a4fd56934c953493f5
[ "MIT" ]
null
null
null
04_Cap04/ModuleScene.cpp
Gabroide/DevelopingAnEngine
096b4f8ddcf7b17819e256a4fd56934c953493f5
[ "MIT" ]
null
null
null
#include "Application.h" #include "ModuleScene.h" #include "ModuleWindow.h" #include "ModuleProgram.h" #include "ModuleCamera.h" #include "GL\glew.h" #include "SDL.h" #include "MathGeoLib\include\Geometry\Frustum.h" #include "MathGeoLib\include\Math\MathConstants.h" #include "MathGeoLib\include\Math\float3.h" #include "MathGeoLib\include\Math\float4.h" ModuleScene::ModuleScene() { } ModuleScene::~ModuleScene() { } bool ModuleScene::Init() { // texture = App->textures->Load("./Textures/Lenna.png"); float vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, }; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); return vbo; } update_status ModuleScene::Update() { glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer( 0, // attribute 0 3, // number of componentes (3 floats) GL_FLOAT, // data type GL_FALSE, // should be normalized? 0, // stride (void*)0 // array buffer offset ); glEnableVertexAttribArray(1); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(float) * 3 * 6) // buffer offset ); glUseProgram(App->program->program); math::float4x4 model(math::float4x4::identity); glUniformMatrix4fv(glGetUniformLocation(App->program->program, "model"), 1, GL_TRUE, &model[0][0]); glUniformMatrix4fv(glGetUniformLocation(App->program->program, "view"), 1, GL_TRUE, &App->camera->LookAt(App->camera->cameraPosition, App->camera->cameraFront, App->camera->cameraUp)[0][0]); glUniformMatrix4fv(glGetUniformLocation(App->program->program, "proj"), 1, GL_TRUE, &App->camera->frustum.ProjectionMatrix()[0][0]); //glActiveTexture(GL_TEXTURE0); //glBindTexture(GL_TEXTURE_2D, texture); //glUniform1i(glGetUniformLocation(App->program->program, "texture0"), 0); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, 0); //glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); return UPDATE_CONTINUE; } /* float4x4 ModuleScene::Transform(float3 eye, float3 target) { float4x4 resultMatrix; float3 f(target - eye); f.Normalize(); float3 s(f.Cross(up)); s.Normalize(); float3 u(s.Cross(f)); viewMatrix[0][0] = s.x; viewMatrix[0][1] = s.y; viewMatrix[0][2] = s.z; viewMatrix[3][0] = 0; viewMatrix[1][0] = u.x; viewMatrix[1][1] = u.y; viewMatrix[1][2] = u.z; viewMatrix[3][1] = 0; viewMatrix[2][0] = -f.x; viewMatrix[2][1] = -f.y; viewMatrix[2][2] = -f.z; viewMatrix[3][2] = 0; viewMatrix[0][3] = -s.Dot(eye); viewMatrix[1][3] = -u.Dot(eye); viewMatrix[2][3] = f.Dot(eye); viewMatrix[3][3] = 1; Frustum frustum; float aspect = SCREEN_WIDTH / SCREEN_HEIGHT; frustum.type = FrustumType::PerspectiveFrustum; frustum.pos = float3::zero; frustum.front = -float3::unitZ; frustum.up = float3::unitY; frustum.nearPlaneDistance = 0.1f; frustum.farPlaneDistance = 100.0f; frustum.verticalFov = math::pi / 4.0f; frustum.horizontalFov = 2.f * atanf(tanf(frustum.verticalFov * 0.5f)) * aspect; math::float4x4 proj = frustum.ProjectionMatrix(); this->viewMatrix = viewMatrix; this->projectionMatrix = proj; resultMatrix = proj * viewMatrix; return resultMatrix; } */ bool ModuleScene::CleanUp() { if(vbo != 0) { glDeleteBuffers(1, &vbo); } return true; }
25.986111
191
0.664885
[ "geometry", "model", "transform" ]
dae7681682b098e98e2baf058e82b1b19a1e4604
1,516
cpp
C++
smolengine.graphics/src/Backends/Vulkan/Aftermath/AftermathShaderTracker.cpp
Floritte/Game-Engine-Samples
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
[ "Apache-2.0" ]
3
2021-05-18T00:01:06.000Z
2021-07-09T15:39:23.000Z
smolengine.graphics/src/Backends/Vulkan/Aftermath/AftermathShaderTracker.cpp
Floritte/Game-Engine-Samples
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
[ "Apache-2.0" ]
null
null
null
smolengine.graphics/src/Backends/Vulkan/Aftermath/AftermathShaderTracker.cpp
Floritte/Game-Engine-Samples
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #ifdef AFTERMATH #include "Backends/Vulkan/Aftermath/AftermathShaderTracker.h" namespace SmolEngine { bool AftermathShaderTracker::FindShaderBinary(const GFSDK_Aftermath_ShaderHash& shaderHash, std::vector<uint8_t>& shader) const { // Find shader binary data for the shader hash auto i_shader = m_shaderBinaries.find(shaderHash); if (i_shader == m_shaderBinaries.end()) { // Nothing found. return false; } shader = i_shader->second; return true; } void AftermathShaderTracker::AddShaderBinary(const char* shaderFilePath) { // Read the shader binary code from the file std::vector<uint8_t> data; if (!ReadFile(shaderFilePath, data)) { return; } // Create shader hash for the shader const GFSDK_Aftermath_SpirvCode shader{ data.data(), uint32_t(data.size()) }; GFSDK_Aftermath_ShaderHash shaderHash; AFTERMATH_CHECK_ERROR(GFSDK_Aftermath_GetShaderHashSpirv( GFSDK_Aftermath_Version_API, &shader, &shaderHash)); // Store the data for shader mapping when decoding GPU crash dumps. // cf. FindShaderBinary() m_shaderBinaries[shaderHash].swap(data); } bool AftermathShaderTracker::ReadFile(const char* filename, std::vector<uint8_t>& data) { std::ifstream fs(filename, std::ios::in | std::ios::binary); if (!fs) { return false; } fs.seekg(0, std::ios::end); data.resize(fs.tellg()); fs.seekg(0, std::ios::beg); fs.read(reinterpret_cast<char*>(data.data()), data.size()); fs.close(); return true; } } #endif
25.266667
128
0.719657
[ "vector" ]
daefcb6cb0381d9184de04b73e49a479b0d750e9
2,348
cpp
C++
src/ar/posecamerapnp.cpp
chili-epfl/qml-ar
e48e67d28b3b8556787df65b50bb196ff2a169db
[ "MIT" ]
32
2018-01-31T13:07:36.000Z
2021-12-21T14:33:59.000Z
src/ar/posecamerapnp.cpp
chili-epfl/qml-ar
e48e67d28b3b8556787df65b50bb196ff2a169db
[ "MIT" ]
1
2021-05-10T15:11:52.000Z
2021-05-10T15:11:52.000Z
src/ar/posecamerapnp.cpp
chili-epfl/qml-ar
e48e67d28b3b8556787df65b50bb196ff2a169db
[ "MIT" ]
6
2018-02-19T02:19:02.000Z
2021-04-07T11:20:18.000Z
/** * @file posecamerapnp.cpp * @brief This class converts camera + 3D-2D correspondences * to a camera pose * @author Sergei Volodin * @version 1.0 * @date 2018-07-25 */ #include "posecamerapnp.h" #include <QtCore> #include <QMatrix4x4> #include <opencv2/calib3d.hpp> #include <opencv2/core.hpp> #include "cvmatandqimage.h" Pose CameraPoseEstimatorCorrespondences::estimate(CalibratedCamera *camera, WorldImageCorrespondences *correspondences) { Q_ASSERT(camera != NULL); Q_ASSERT(correspondences != NULL); Q_ASSERT(correspondences->size() > 0); // number of points in correspondences int points_n = correspondences->size(); // matrix for world points cv::Mat cv_world_points(points_n, 3, CV_64F); // matrix for image points cv::Mat cv_image_points(points_n, 2, CV_64F); // filling matrices from correspondences for(int i = 0; i < points_n; i++) { cv_world_points.at<double>(i, 0) = correspondences->getWorldPoint(i).x(); cv_world_points.at<double>(i, 1) = correspondences->getWorldPoint(i).y(); cv_world_points.at<double>(i, 2) = correspondences->getWorldPoint(i).z(); cv_image_points.at<double>(i, 0) = correspondences->getImagePoint(i).x(); cv_image_points.at<double>(i, 1) = correspondences->getImagePoint(i).y(); } // camera matrix cv::Mat cv_camera_matrix(3, 3, CV_64F); // filling camera matrix for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) cv_camera_matrix.at<double>(i, j) = camera->getMatrix()(i, j); // rotation vector cv::Mat rvec; // translation vector cv::Mat tvec; // solving PnP task bool res = cv::solvePnP(cv_world_points, cv_image_points, cv_camera_matrix, cv::Mat(), rvec, tvec, false, CV_ITERATIVE); // if failed, return invalid pose if(!res) return Pose(); // rotation matrix cv::Mat rmat; // compute rotation matrix cv::Rodrigues(rvec, rmat, cv::noArray()); // translation vector (Qt) QVector3D tvec_qt; for(int i = 0; i < 3; i++) tvec_qt[i] = tvec.at<double>(i, 0); // rotation matrix (Qt) QMatrix3x3 rmat_qt; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) rmat_qt(i, j) = rmat.at<double>(i, j); // returning pose return Pose(tvec_qt, rmat_qt); }
28.289157
124
0.63586
[ "vector", "3d" ]
9703d79580ef237cc7b72e6a8d63229e7993ac84
1,405
cpp
C++
Test/MathTest.cpp
davemc0/DMcTools
7fa65abc99330c4cc49cf4037cf629051aa516a6
[ "CC0-1.0" ]
null
null
null
Test/MathTest.cpp
davemc0/DMcTools
7fa65abc99330c4cc49cf4037cf629051aa516a6
[ "CC0-1.0" ]
null
null
null
Test/MathTest.cpp
davemc0/DMcTools
7fa65abc99330c4cc49cf4037cf629051aa516a6
[ "CC0-1.0" ]
null
null
null
#include "Math/BinaryRep.h" #include "Math/Random.h" #include "Math/Vector.h" #include <iostream> void vectorTest() { { f3vec a(1, 0, 0), b(0, 1, 0); f3vec c = cross(a, b); std::cerr << a << b << c << '\n'; } { d3vec a(1.f, (double)0, (int)0), b(0, 1, 0); d3vec c = cross(a, b); std::cerr << a << b << c << '\n'; } } void deconstructFloatTest() { int tries = 0, fails = 0; while (1) { float frnd = abs(nfrand(0, 1)); uint32_t fsign, fexp, fmant; deconstructFloat(frnd, fsign, fexp, fmant); int expVal = fexp + irand(10); int nBits = irand(8, 25); uint32_t fixed = floatToFixedGivenExp(frnd, expVal, nBits); float fout = fixedToFloatGivenExp(fixed, expVal, nBits); tries++; if (floatAsUint(frnd) >> 16 != floatAsUint(fout) >> 16) { fails++; printf("I %9.9g %d %d %006x ", frnd, fsign, fexp, fmant); printf("fixed=%06x nbits=%d expVal=%d\n", fixed, nBits, expVal); deconstructFloat(fout, fsign, fexp, fmant); printf("O %9.9g %d %d %006x %d/%d\n", fout, fsign, fexp, fmant, fails, tries); } } } bool MathTest(int argc, char** argv) { std::cerr << "Starting MathTest\n"; vectorTest(); // deconstructFloatTest(); std::cerr << "Ending MathTest\n"; return true; }
23.813559
90
0.525267
[ "vector" ]
8cc918d3cdc16dd81b9ff53ba19666cb69e8414b
3,787
cxx
C++
odb-tests-2.4.0/common/callback/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/common/callback/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/common/callback/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
// file : common/callback/driver.cxx // copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC // license : GNU GPL v2; see accompanying LICENSE file // Test database operation callbacks. // #include <memory> // std::auto_ptr #include <cassert> #include <iostream> #include <odb/database.hxx> #include <odb/transaction.hxx> #include <common/common.hxx> #include "test.hxx" #include "test-odb.hxx" using namespace std; using namespace odb::core; const char* events[] = { "pre_persist", "post_persist", "pre_load", "post_load", "pre_update", "post_update", "pre_erase", "post_erase" }; void object:: db_callback (callback_event e, database& db) { cout << " " << events[e] << " " << id_ << endl; // Test custom recursive loading. // if (e == callback_event::post_load && ref != 0) { robj = db.load<object> (ref); cout << " " << id_ << ' ' << ref << ' ' << robj->id_ << endl; } } void object:: db_callback (callback_event e, database&) const { cout << " " << events[e] << " " << id_ << " const" << endl; } int main (int argc, char* argv[]) { try { auto_ptr<database> db (create_database (argc, argv)); // Persist. // cout << "persist" << endl; { object o1 (1, 1); object const o2 (2, 2); transaction t (db->begin ()); db->persist (o1); db->persist (&o2); t.commit (); } cout << "***" << endl; // Load. // cout << "load" << endl; { transaction t (db->begin ()); auto_ptr<object> o1 (db->load<object> (1)); object o2; db->load<object> (2, o2); t.commit (); } cout << "***" << endl; // Query. // cout << "query" << endl; { typedef odb::query<object> query; typedef odb::result<object> result; transaction t (db->begin ()); result r (db->query<object> ((query::id < 3) + "ORDER BY" + query::id)); for (result::iterator i (r.begin ()); i != r.end (); ++i) { if (i->id_ > 3) // Load. break; } t.commit (); } cout << "***" << endl; // Update. // cout << "update" << endl; { transaction t (db->begin ()); auto_ptr<object> o1 (db->load<object> (1)); auto_ptr<object> o2 (db->load<object> (2)); o1->data++; o2->data++; db->update (o1.get ()); db->update (static_cast<const object&> (*o2)); t.commit (); } cout << "***" << endl; // Erase. // cout << "erase" << endl; { transaction t (db->begin ()); auto_ptr<object> o1 (db->load<object> (1)); auto_ptr<object> o2 (db->load<object> (2)); db->erase (static_cast<const object*> (o1.get ())); db->erase (*o2); t.commit (); } cout << "***" << endl; // Delayed (recursive) load. // cout << "delayed load" << endl; { { object o1 (1, 1); object o2 (2, 2); object o3 (3, 3); object o4 (4, 4); o1.pobj = &o2; o1.ref = 4; o2.pobj = &o3; o2.ref = 4; transaction t (db->begin ()); db->persist (o1); db->persist (o2); db->persist (o3); db->persist (o4); t.commit (); } { transaction t (db->begin ()); auto_ptr<object> o1 (db->load<object> (1)); object* o2 (o1->pobj); cout << o1->id_ << ' ' << o1->ref << ' ' << o1->robj->id_ << endl; cout << o2->id_ << ' ' << o2->ref << ' ' << o2->robj->id_ << endl; delete o1->robj; delete o2->robj; delete o2->pobj; delete o2; t.commit (); } } cout << "***" << endl; } catch (const odb::exception& e) { cerr << e.what () << endl; return 1; } }
20.581522
78
0.486665
[ "object" ]
8ccb32d0be256f7a0ee2cc4b008dafd2c0f625a7
16,644
cpp
C++
BossAttack1_DomJudge/BA1_C_html parser.cpp
Ping6666/Compiler-Projects
31c7c437a2fad66b7b7424d9b2a468b61d94fdd3
[ "MIT" ]
1
2021-11-21T15:52:23.000Z
2021-11-21T15:52:23.000Z
BossAttack1_DomJudge/BA1_C_html parser.cpp
Ping6666/Compiler-Projects
31c7c437a2fad66b7b7424d9b2a468b61d94fdd3
[ "MIT" ]
null
null
null
BossAttack1_DomJudge/BA1_C_html parser.cpp
Ping6666/Compiler-Projects
31c7c437a2fad66b7b7424d9b2a468b61d94fdd3
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> // DEBUG // bool print_check = true; bool print_check = false; /* Recursive-Decent-Parsing: Since need to fit the question needed, therefore try to use many function and if / else. */ // <div><span>text in span<div></span></div> // htmlElement htmlContent htmlContent htmlElement htmlContent htmlChardata /* 1 htmlDocument -> htmlElement htmlDocument $ 2 htmlDocument -> λ 3 htmlElement -> TAG_OPEN TAG_NAME htmlAttributeList TAG_CLOSE htmlContent TAG_OPEN_SLASH TAG_NAME TAG_CLOSE 4 htmlContent -> htmlChardata htmlContent 5 htmlContent -> htmlElement htmlContent 6 htmlContent -> λ 7 htmlAttributeList -> htmlAttribute htmlAttributeList 8 htmlAttributeList -> λ 9 htmlAttribute -> TAG_NAME TAG_EQUALS attribute 10 htmlChardata -> HTML_TEXT 11 attribute -> DOUBLE_QUOTE_STRING 12 attribute -> SINGLE_QUOTE_STRING */ struct AnsForm { std::string TerminalName; AnsForm(std::string a) { this->TerminalName = a; } }; // global variable std::string tmp; std::vector<AnsForm> ansForm; void printVector() { for (int i = 0; i < (int)ansForm.size(); i++) { std::cout << ansForm[i].TerminalName << "\n"; } return; } void stringManipulate() { bool set = false; for (int i = 0; i < (int)tmp.length(); i++) { if (set) { if (tmp[i] == ' ') { tmp.erase(tmp.begin() + i); i--; } else { set = false; } } else { if (tmp[i] == ' ') { set = true; } } } return; } // Productions int GET__htmlDocument(int index); int GET__htmlElement(int index); int GET__htmlContent(int index, bool second = false); int GET__htmlAttributeList(int index, bool second = false); int GET__htmlAttribute(int index); int GET__htmlChardata(int index); int GET__attribute(int index); // Terminal: Regular Expression int GET_TAG_NAME(int index, bool first = true); // [a-z|A-Z|0-9]+ int GET_HTML_TEXT(int index, bool first = true); // [^<]+ int GET_HTML_DOUBLE_QUOTE_STRING(int index, bool first = true); // "[^"<]*" int GET_HTML_SINGLE_QUOTE_STRING(int index, bool first = true); // '[^'<]*' int GET_TAG_OPEN(int index); // < int GET_TAG_CLOSE(int index); // > int GET_TAG_OPEN_SLASH(int index); // </ int GET_TAG_EQUALS(int index); // = int main() { tmp.clear(); while (true) { char ch = getchar(); if (ch == EOF) { break; } else if (ch == '\n') { tmp += "\0"; } else { tmp += ch; } } stringManipulate(); // tmp += '\0'; // this is no need now if (print_check) std::cout << tmp << " " << tmp.length() << "\n"; int result_ = GET__htmlDocument(0); if (result_ >= 0) { ansForm.push_back(AnsForm("htmlDocument")); printVector(); std::cout << "valid\n"; } else { printVector(); std::cout << "invalid\n"; } return 0; } /* Productions */ int GET__htmlDocument(int index) { if (print_check) std::cout << "GET__htmlDocument " << index << '\n'; int index_ = GET__htmlElement(index); index += index_; // this shoud not do first, but it is ok to do first here if (index_ < 0) { return -1; } else if (index >= (int)tmp.length() - 1) { if (index_ > 0) { ansForm.push_back(AnsForm("htmlElement")); } return 0; // success } else if (index_ == 0) { ansForm.push_back(AnsForm("htmlElement")); return 0; } return GET__htmlDocument(index); } int GET__htmlElement(int index) { if (print_check) std::cout << "GET__htmlElement " << index << '\n'; int index_1 = GET_TAG_OPEN(index); if (index_1 < 0) { return 0; // this is diff. (maybe is 0) } index += index_1; int index_2 = GET_TAG_NAME(index); if (index_2 < 0) { return -1; } index += index_2; int index_3 = GET__htmlAttributeList(index); if (index_3 < 0) { return -1; } if (index_3 > 0) { ansForm.push_back(AnsForm("htmlAttributeList")); } index += index_3; int index_4 = GET_TAG_CLOSE(index); if (index_4 < 0) { return -1; } index += index_4; int index_5 = GET__htmlContent(index); if (index_5 < 0) { return -1; } if (index_5 > 0) { ansForm.push_back(AnsForm("htmlContent")); } index += index_5; int index_6 = GET_TAG_OPEN_SLASH(index); if (index_6 < 0) { return -1; } index += index_6; int index_7 = GET_TAG_NAME(index); if (index_7 < 0) { return -1; } index += index_7; int index_8 = GET_TAG_CLOSE(index); if (index_8 < 0) { return -1; } index += index_8; return index_1 + index_2 + index_3 + index_4 + index_5 + index_6 + index_7 + index_8; } // difficult func. int GET__htmlContent(int index, bool second) { if (print_check) std::cout << "GET__htmlContent " << index << '\n'; int index_1 = GET__htmlChardata(index); if (index_1 < 0) { int index_1_1 = GET__htmlElement(index); if (index_1_1 < 0) { return 0; // this is diff. (maybe is 0), this is correct } if (index_1 == 0 || index_1_1 == 0) return 0; // the key factor for the wrong token seq. index += index_1_1; if (index_1_1 > 0) { ansForm.push_back(AnsForm("htmlElement")); } int index_1_2 = GET__htmlContent(index, true); if (index_1_2 < 0) { return -1; // this is diff. (maybe is 0) } index += index_1_2; if (index_1_1 + index_1_2 == 0) return -1; if (index_1_2 > 0) { ansForm.push_back(AnsForm("htmlContent")); } return index_1_1 + index_1_2; } else { index += index_1; if (index_1 > 0) { if (ansForm.size() == 0) { ansForm.push_back(AnsForm("htmlCharData")); } else if (ansForm.size() > 0 && ansForm.back().TerminalName.compare("htmlCharData") != 0) { ansForm.push_back(AnsForm("htmlCharData")); } } int index_2_1 = GET__htmlContent(index, true); if (index_2_1 < 0) { return -1; // this is diff. (maybe is 0) } index += index_2_1; if (index_2_1 > 0 && !second) { ansForm.push_back(AnsForm("htmlContent")); } if (index_1 + index_2_1 == 0) return -1; return index_1 + index_2_1; } return -1; // this is λ (0), this is diff. (maybe is 0) } int GET__htmlAttributeList(int index, bool second) { if (print_check) std::cout << "GET__htmlAttributeList " << index << '\n'; int index_ = GET__htmlAttribute(index); index += index_; // this shoud not do first, but it is ok to do first here if (index_ < 0) { return 0; // this is λ (0) } if (index_ > 0) { ansForm.push_back(AnsForm("htmlAttribute")); } int index_1 = GET__htmlAttributeList(index); /* the main problem of all may be here */ if (index_1 < 0) { return -1; // this is diff. (maybe is 0) } index += index_1; if (index_1 > 0) { ansForm.push_back(AnsForm("htmlAttributeList")); } return index_ + index_1; } int GET__htmlAttribute(int index) { if (print_check) std::cout << "GET__htmlAttribute " << index << '\n'; int index_1 = GET_TAG_NAME(index); if (index_1 <= 0) { return -1; // this is diff. (maybe is 0) } index += index_1; int index_2 = GET_TAG_EQUALS(index); if (index_2 < 0) { return -1; } index += index_2; int index_3 = GET__attribute(index); if (index_3 < 0) { return -1; } index += index_3; if (index_3 > 0) { ansForm.push_back(AnsForm("attribute")); } return index_1 + index_2 + index_3; } int GET__htmlChardata(int index) { if (print_check) std::cout << "GET__htmlChardata " << index << '\n'; int index_1 = GET_HTML_TEXT(index); if (index_1 <= 0) { return -1; // this is diff. (maybe is 0) } index += index_1; return index_1; } int GET__attribute(int index) { if (print_check) std::cout << "GET__attribute " << index << '\n'; int index_1 = GET_HTML_DOUBLE_QUOTE_STRING(index); if (index_1 <= 0) { int index_2 = GET_HTML_SINGLE_QUOTE_STRING(index); if (index_2 <= 0) { return -1; // this is fail } return index_2; } else { ansForm.push_back(AnsForm("attribute")); return index_1; } } /* Terminal: Regular Expression */ // [a-z|A-Z|0-9]+ int GET_TAG_NAME(int index, bool first) { if (print_check) std::cout << "GET_TAG_NAME " << index << '\n'; if (index >= (int)tmp.length()) return -1; // out of range if (first) // first time call GET_TAG_NAME { if (((tmp[index] >= 'a') && (tmp[index] <= 'z')) || ((tmp[index] >= 'A') && (tmp[index] <= 'Z')) || ((tmp[index] >= '0') && (tmp[index] <= '9'))) { int index_ = GET_TAG_NAME(index + 1, false); if (index_ < 0) { return -1; } return index_ + 1; } else if (tmp[index] == ' ') { int index_ = GET_TAG_NAME(index + 1, true); if (index_ < 0) { return -1; } return index_ + 1; } return -1; } else // second time call GET_TAG_NAME { if (((tmp[index] >= 'a') && (tmp[index] <= 'z')) || ((tmp[index] >= 'A') && (tmp[index] <= 'Z')) || ((tmp[index] >= '0') && (tmp[index] <= '9'))) { int index_ = GET_TAG_NAME(index + 1, false); if (index_ < 0) { return -1; } return index_ + 1; } else if ((tmp[index] == '\n') || (tmp[index] == '\0') || (tmp[index] == ' ') || (tmp[index] == '<') || (tmp[index] == '>') || (tmp[index] == '=')) { return 0; // not include this char (+0) (????) } return -1; } } // [^<]+ int GET_HTML_TEXT(int index, bool first) { if (print_check) std::cout << "GET_HTML_TEXT " << index << " " << tmp[index] << '\n'; if (index >= (int)tmp.length()) return -1; // out of range if (first) // first time call GET_HTML_TEXT { if ((tmp[index] != '<') && (tmp[index] != '\0') && (index < (int)tmp.length() - 1)) { return GET_HTML_TEXT(index + 1, false) + 1; } else if (tmp[index] == ' ') { int index_ = GET_HTML_TEXT(index + 1, true); if (index_ < 0) { return -1; } return index_ + 1; } return -1; } else // second time call GET_HTML_TEXT { if (tmp[index] == '<') { return 0; } // this if is just for one special testcase else if ((tmp[index] == '\n') || (tmp[index] == '\0') || (tmp[index] == ' ') || (tmp[index] == '<') || (tmp[index] == '/') || (tmp[index] == '>') || (tmp[index] == '=')) { return 0; // not include this char (+0) (????) } /* NOT sure for this */ // this if is just for one special testcase else if (index >= (int)tmp.length() - 1) { std::cout << "invalid input\n"; exit(0); } // end of if return GET_HTML_TEXT(index + 1, false) + 1; } } // "[^"<]*" int GET_HTML_DOUBLE_QUOTE_STRING(int index, bool first) { if (print_check) std::cout << "GET_HTML_DOUBLE_QUOTE_STRING " << index << '\n'; if (first) // first time call GET_HTML_DOUBLE_QUOTE_STRING (left) { if (tmp[index] == '"') { return GET_HTML_DOUBLE_QUOTE_STRING(index + 1, false) + 1; } else if (tmp[index] == ' ') { int index_ = GET_HTML_DOUBLE_QUOTE_STRING(index + 1, true); if (index_ < 0) { return -1; } return index_ + 1; } return -1; } else // second time call GET_HTML_DOUBLE_QUOTE_STRING (right) { if (tmp[index] == '"') { return 1; // include this char (+1) } // this if is just for one special testcase else if (index >= (int)tmp.length() - 1) { std::cout << "invalid input\n"; exit(0); } // end of if return GET_HTML_DOUBLE_QUOTE_STRING(index + 1, false) + 1; } } // '[^'<]*' int GET_HTML_SINGLE_QUOTE_STRING(int index, bool first) { if (print_check) std::cout << "GET_HTML_SINGLE_QUOTE_STRING " << index << '\n'; if (first) // first time call GET_HTML_SINGLE_QUOTE_STRING (left) { if (tmp[index] == '\'') { return GET_HTML_SINGLE_QUOTE_STRING(index + 1, false) + 1; } else if (tmp[index] == ' ') { int index_ = GET_HTML_SINGLE_QUOTE_STRING(index + 1, true); if (index_ < 0) { return -1; } return index_ + 1; } return -1; } else // second time call GET_HTML_SINGLE_QUOTE_STRING (right) { if (tmp[index] == '\'') { return 1; // include this char (+1) } // this if is just for one special testcase else if (index >= (int)tmp.length() - 1) { std::cout << "invalid input\n"; exit(0); } // end of if return GET_HTML_SINGLE_QUOTE_STRING(index + 1, false) + 1; } } // < int GET_TAG_OPEN(int index) { if (print_check) std::cout << "GET_TAG_OPEN " << index << '\n'; if (tmp[index] == '<') { return 1; } else if (tmp[index] == ' ') { int index_ = GET_TAG_OPEN(index + 1); if (index_ < 0) { return -1; } return index_ + 1; } return -1; } // > int GET_TAG_CLOSE(int index) { if (print_check) std::cout << "GET_TAG_CLOSE " << index << '\n'; if (tmp[index] == '>') { return 1; } else if (tmp[index] == ' ') { int index_ = GET_TAG_CLOSE(index + 1); if (index_ < 0) { return -1; } return index_ + 1; } return -1; } // </ int GET_TAG_OPEN_SLASH(int index) { if (print_check) std::cout << "GET_TAG_OPEN_SLASH " << index << '\n'; if ((tmp[index] == '<') && (tmp[index + 1] == '/')) { return 2; } else if (tmp[index] == ' ') { int index_ = GET_TAG_OPEN_SLASH(index + 1); if (index_ < 0) { return -1; } return index_ + 1; } return -1; } // = int GET_TAG_EQUALS(int index) { if (print_check) std::cout << "GET_TAG_EQUALS " << index << '\n'; if (tmp[index] == '=') { return 1; } else if (tmp[index] == ' ') { int index_ = GET_TAG_EQUALS(index + 1); if (index_ < 0) { return -1; } return index_ + 1; } return -1; }
24.584934
178
0.471882
[ "vector" ]
8cd32b0b0284e3676aab7b603971f0a66473b45f
5,179
hpp
C++
Source/AllProjects/Drivers/HAIOmniTCP/Shared/HAIOmniTCPSh.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/HAIOmniTCP/Shared/HAIOmniTCPSh.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/HAIOmniTCP/Shared/HAIOmniTCPSh.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: HAIOmniTCPSh.hpp // // AUTHOR: Dean Roddey // // CREATED: 05/16/2008 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the public facility header. It defines and includes stuff that // is publically visible // // CAVEATS/GOTCHAS: // // LOG: // #pragma once // --------------------------------------------------------------------------- // Set up our import/export attributes // --------------------------------------------------------------------------- #if defined(PROJ_HAIOMNITCPSH) #define HAIOMNITCPSHEXPORT CID_DLLEXPORT #else #define HAIOMNITCPSHEXPORT CID_DLLIMPORT #endif // --------------------------------------------------------------------------- // Bring in the stuff we need // --------------------------------------------------------------------------- #include "CIDLib.hpp" #include "CIDOrbUC.hpp" #include "CQCKit.hpp" // --------------------------------------------------------------------------- // Constants // --------------------------------------------------------------------------- namespace kHAIOmniTCPSh { // ----------------------------------------------------------------------- // These are the numbers of all the things we deal with in the Omni. // These are the worst cases, from the Omni ProII. We also support the // regular IIe, can have fewer. We get the actual counts from the // device. But we can use these to allocate storage areas and know it's // enough to hold anything we'll be asked to handle. // ----------------------------------------------------------------------- const tCIDLib::TCard4 c4MaxAreas(8); const tCIDLib::TCard4 c4MaxButtons(128); const tCIDLib::TCard4 c4MaxEnclosures(8); const tCIDLib::TCard4 c4MaxExps(8); const tCIDLib::TCard4 c4MaxMsgs(128); const tCIDLib::TCard4 c4MaxThermos(64); const tCIDLib::TCard4 c4MaxUnits(511); const tCIDLib::TCard4 c4MaxZones(176); // // The version of the config data we write out. Version 2 is our new // format as of 4.2.917. // const tCIDLib::TCard4 c4ConfigVer = 2; // ----------------------------------------------------------------------- // The base name of our facility // ----------------------------------------------------------------------- const tCIDLib::TCh* const pszClientFacName = L"HAIOmniTCPC"; const tCIDLib::TCh* const pszServerFacName = L"HAIOmniTCPS"; } // --------------------------------------------------------------------------- // Bring in our own public headers. Some others have to come in below after // the types namespace. // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Public facility types // --------------------------------------------------------------------------- namespace tHAIOmniTCPSh { // // The types of named items in the Omni // // Add new ones at the end! These are presisted. // enum EItemTypes { EItem_Unknown , EItem_Area , EItem_Button , EItem_Code , EItem_Message , EItem_Thermo , EItem_Unit , EItem_Zone }; // // Used in units to indicate what type of unit. Unused needs to be the // first value, so that it comes out zero! // // Add new ones at the end! These are presisted. // enum EUnitTypes { EUnit_Unused , EUnit_Binary , EUnit_Dimmer , EUnit_Flag }; // // Used in zones to indicate what type of zone. Unused needs to be the // first value, so that it comes out zero! There are other zone types // but these are the only ones we support for now. // // Add new ones at the end! These are presisted. // enum EZoneTypes { EZone_Unused , EZone_Alarm , EZone_Humidity , EZone_Temp , EZone_Motion }; } // --------------------------------------------------------------------------- // Provide streaming support for some enums // --------------------------------------------------------------------------- EnumBinStreamMacros(tHAIOmniTCPSh::EItemTypes) EnumBinStreamMacros(tHAIOmniTCPSh::EUnitTypes) EnumBinStreamMacros(tHAIOmniTCPSh::EZoneTypes) // --------------------------------------------------------------------------- // Bring in some more headers that need the above types // --------------------------------------------------------------------------- #include "HAIOmniTCPSh_ErrorIds.hpp" #include "HAIOmniTCPSh_Item.hpp" #include "HAIOmniTCPSh_DrvConfig.hpp" // --------------------------------------------------------------------------- // The lazy eval method for our facility object // --------------------------------------------------------------------------- extern HAIOMNITCPSHEXPORT TFacility& facHAIOmniTCPSh();
30.827381
78
0.460707
[ "object" ]
8cd6867646f04917524ed91422968421eca9ca5b
14,145
cc
C++
whisperstreamlib/f4v/atoms/movie/esds_atom.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/f4v/atoms/movie/esds_atom.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/f4v/atoms/movie/esds_atom.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
#include "f4v/atoms/movie/esds_atom.h" #include <whisperlib/common/io/num_streaming.h> #include <whisperlib/common/base/scoped_ptr.h> namespace streaming { namespace f4v { EsdsAtom::EsdsAtom() : VersionedAtom(kType), raw_data_(), mp4_es_desc_tag_id_(0), mp4_es_desc_tag_priority_(0), mp4_dec_config_desc_tag_object_type_id_(0), mp4_dec_config_desc_tag_stream_type_(0), mp4_dec_config_desc_tag_buffer_size_db_(0), mp4_dec_config_desc_tag_max_bit_rate_(0), mp4_dec_config_desc_tag_avg_bit_rate_(0), extra_data_() { } EsdsAtom::EsdsAtom(const EsdsAtom& other) : VersionedAtom(other), raw_data_(), mp4_es_desc_tag_id_(other.mp4_es_desc_tag_id_), mp4_es_desc_tag_priority_(other.mp4_es_desc_tag_priority_), mp4_dec_config_desc_tag_object_type_id_(other.mp4_dec_config_desc_tag_object_type_id_), mp4_dec_config_desc_tag_stream_type_(other.mp4_dec_config_desc_tag_stream_type_), mp4_dec_config_desc_tag_buffer_size_db_(other.mp4_dec_config_desc_tag_buffer_size_db_), mp4_dec_config_desc_tag_max_bit_rate_(other.mp4_dec_config_desc_tag_max_bit_rate_), mp4_dec_config_desc_tag_avg_bit_rate_(other.mp4_dec_config_desc_tag_avg_bit_rate_), extra_data_() { raw_data_.AppendStreamNonDestructive(&other.raw_data_); extra_data_.AppendStreamNonDestructive(&other.extra_data_); } EsdsAtom::~EsdsAtom() { } const io::MemoryStream& EsdsAtom::extra_data() const { return extra_data_; } void EsdsAtom::set_mp4_es_desc_tag_id(uint16 mp4_es_desc_tag_id) { mp4_es_desc_tag_id_ = mp4_es_desc_tag_id; } void EsdsAtom::set_mp4_es_desc_tag_priority(uint8 mp4_es_desc_tag_priority) { mp4_es_desc_tag_priority_ = mp4_es_desc_tag_priority; } void EsdsAtom::set_mp4_dec_config_desc_tag_object_type_id(uint8 mp4_dec_config_desc_tag_object_type_id) { mp4_dec_config_desc_tag_object_type_id_ = mp4_dec_config_desc_tag_object_type_id; } void EsdsAtom::set_mp4_dec_config_desc_tag_stream_type(uint8 mp4_dec_config_desc_tag_stream_type) { mp4_dec_config_desc_tag_stream_type_ = mp4_dec_config_desc_tag_stream_type; } void EsdsAtom::set_mp4_dec_config_desc_tag_buffer_size_db(uint32 mp4_dec_config_desc_tag_buffer_size_db) { mp4_dec_config_desc_tag_buffer_size_db_ = mp4_dec_config_desc_tag_buffer_size_db; } void EsdsAtom::set_mp4_dec_config_desc_tag_max_bit_rate(uint32 mp4_dec_config_desc_tag_max_bit_rate) { mp4_dec_config_desc_tag_max_bit_rate_ = mp4_dec_config_desc_tag_max_bit_rate; } void EsdsAtom::set_mp4_dec_config_desc_tag_avg_bit_rate(uint32 mp4_dec_config_desc_tag_avg_bit_rate) { mp4_dec_config_desc_tag_avg_bit_rate_ = mp4_dec_config_desc_tag_avg_bit_rate; } void EsdsAtom::set_extra_data(const io::MemoryStream& extra_data) { extra_data_.Clear(); extra_data_.AppendStreamNonDestructive(&extra_data); } void EsdsAtom::set_extra_data(const void* extra_data, uint32 size) { extra_data_.Clear(); extra_data_.Write(extra_data, size); } //static TagDecodeStatus EsdsAtom::ReadTagTypeAndLength(io::MemoryStream& in, uint8& type, uint32& length) { type = io::NumStreamer::ReadByte(&in); length = 0; for ( int i = 0; i < 4; i++ ) { if ( in.Size() < 1 ) { return TAG_DECODE_NO_DATA; } uint8 b = io::NumStreamer::ReadByte(&in); length = (length << 7) | (b & 0x7f); if ( (b & 0x80) == 0 ) { break; } } return TAG_DECODE_SUCCESS; } //static void EsdsAtom::WriteTagTypeAndLength(io::MemoryStream& out, uint8 type, uint32 length) { // The 'length' is written as 4 bytes with 7 bits each. // general format is: |1...b3...|1...b2...|1...b1...|0...b0...| // where: length = b0 + b1 << 7 + b2 << 14 + b3 << 21; // e.g. for length = 0x9D8BA = 0000000 0100111 0110001 0111010 // We devide length in 7 bit parts. // And the encoded length is: 10000000 10100111 10110001 00111010 // ^ ^ ^ ^ // If first bit is 1 => decoding continues // 0 => this is last byte, decoding stops. CHECK_LT(length, 1 << 29); uint8 enc_len[4] = {0,}; uint32 len = length; for ( int i = 3; i >= 0; i-- ) { uint8 b = len & 0x7f; len = (len >> 7) & 0x1fffff; enc_len[i] = b | 0x80; // first bit is generally 1 } enc_len[3] &= 0x7f; // clear the first bit of the last byte io::NumStreamer::WriteByte(&out, type); out.Write(enc_len, 4); } bool EsdsAtom::EqualsVersionedBody(const VersionedAtom& other) const { const EsdsAtom& a = static_cast<const EsdsAtom&>(other); return raw_data_.Equals(a.raw_data_); } void EsdsAtom::GetSubatoms(vector<const BaseAtom*>& subatoms) const { } BaseAtom* EsdsAtom::Clone() const { return new EsdsAtom(*this); } TagDecodeStatus EsdsAtom::DecodeVersionedBody(uint64 size, io::MemoryStream& in, Decoder& decoder) { // TEST ReadTagTypeAndLength WriteTagTypeAndLength /* { #define TEST_WRITE_READ(type, length, expected_ms_size) {\ LOG_WARNING << "testing type: " << type << ", length: " << length;\ io::MemoryStream ms;\ WriteTagTypeAndLength(ms, type, length);\ CHECK_EQ(ms.Size(), expected_ms_size);\ uint8 out_type;\ uint32 out_length;\ TagDecodeStatus result = ReadTagTypeAndLength(ms, out_type, out_length);\ CHECK(ms.IsEmpty()) << " Ms not empty";\ CHECK_EQ(result, TAG_DECODE_SUCCESS) << "ReadTagTypeAndLength failed: " << result;\ CHECK_EQ(out_type, type) << " Type mismatch";\ CHECK_EQ(out_length, length) << " Length mismatch";\ } TEST_WRITE_READ(0, 0, 5); TEST_WRITE_READ(1, 1, 5); TEST_WRITE_READ(3, 7, 5); TEST_WRITE_READ(13, 0x7f, 5); TEST_WRITE_READ(13, 0x80, 5); TEST_WRITE_READ(13, 0x81, 5); TEST_WRITE_READ(13, 0x3fff, 5); TEST_WRITE_READ(13, 0x4000, 5); TEST_WRITE_READ(13, 0x4001, 5); TEST_WRITE_READ(13, 0x1fffff, 5); TEST_WRITE_READ(13, 0x200000, 5); TEST_WRITE_READ(13, 0x200001, 5); TEST_WRITE_READ(13, 0xfffffff, 5); } */ #define VERIFY_IN_SIZE(expected_size) {\ if ( in.Size() < expected_size ) {\ DATOMLOG << "Not enough data in stream: " << in.Size()\ << " is less than expected: " << expected_size;\ return TAG_DECODE_NO_DATA;\ }\ } VERIFY_IN_SIZE(size); DATOMLOG << "total body size: " << size; // put all the body in raw_data_. The rest of the decode is just to // find extra_data_ and for attributes printing. // raw_data_.Clear(); raw_data_.AppendStreamNonDestructive(&in, 0, size); const int32 begin_size = in.Size(); uint8 tag_type = 0; uint32 tag_length = 0; TagDecodeStatus result = TAG_DECODE_SUCCESS; result = ReadTagTypeAndLength(in, tag_type, tag_length); if ( result != TAG_DECODE_SUCCESS ) { EATOMLOG << "ReadTagTypeAndLength failed"; return result; } DATOMLOG << "sub tag, type: " << (uint32)tag_type << ", length: " << tag_length << ", remaining body size: " << (size - begin_size + in.Size()); VERIFY_IN_SIZE(2); mp4_es_desc_tag_id_ = io::NumStreamer::ReadUInt16(&in, common::BIGENDIAN); if ( tag_type == MP4ESDescrTag ) { VERIFY_IN_SIZE(1); mp4_es_desc_tag_priority_ = io::NumStreamer::ReadByte(&in); } result = ReadTagTypeAndLength(in, tag_type, tag_length); if ( result != TAG_DECODE_SUCCESS ) { EATOMLOG << "ReadTagTypeAndLength failed"; return result; } DATOMLOG << "sub tag, type: " << (uint32)tag_type << ", length: " << tag_length << ", remaining body size: " << (size - begin_size + in.Size()); if ( tag_type == MP4DecConfigDescrTag ) { VERIFY_IN_SIZE(13); mp4_dec_config_desc_tag_object_type_id_ = io::NumStreamer::ReadByte(&in); mp4_dec_config_desc_tag_stream_type_ = io::NumStreamer::ReadByte(&in); mp4_dec_config_desc_tag_buffer_size_db_ = io::NumStreamer::ReadUInt24(&in, common::BIGENDIAN); mp4_dec_config_desc_tag_max_bit_rate_ = io::NumStreamer::ReadUInt32(&in, common::BIGENDIAN); mp4_dec_config_desc_tag_avg_bit_rate_ = io::NumStreamer::ReadUInt32(&in, common::BIGENDIAN); result = ReadTagTypeAndLength(in, tag_type, tag_length); if ( result != TAG_DECODE_SUCCESS ) { EATOMLOG << "ReadTagTypeAndLength failed"; return result; } DATOMLOG << "sub tag, type: " << (uint32)tag_type << ", length: " << tag_length << ", remaining body size: " << (size - begin_size + in.Size()); if (tag_type == MP4UnknownTag) { VERIFY_IN_SIZE(1); uint8 unknown = io::NumStreamer::ReadByte(&in); WATOMLOG << "MP4UnknownTag: " << (uint32)unknown; result = ReadTagTypeAndLength(in, tag_type, tag_length); if ( result != TAG_DECODE_SUCCESS ) { EATOMLOG << "ReadTagTypeAndLength failed"; return result; } } if ( tag_type == MP4DecSpecificDescrTag ) { //iso14496-3 //http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio if ( in.Size() < tag_length ) { EATOMLOG << "Not enough data for MP4DecSpecificDescrTag extra data" ", expected: " << tag_length << ", have: " << in.Size(); return TAG_DECODE_NO_DATA; } extra_data_.AppendStream(&in, tag_length); #if false // decode extra_data. Not sure about correctness. // static const uint32 kSampleRates[] = {96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350}; uint8* tmp = new uint8[tag_length]; scoped_ptr<uint8> auto_del_tmp(tmp); extra_data_.Peek(tmp, tag_length); io::BitArray ba; ba.Wrap(tmp, tag_length); uint8 object_type = ba.Read<uint8>(5); WATOMLOG << "object_type: " << (uint32)object_type; uint8 sample_rate = ba.Read<uint8>(4); WATOMLOG << "sample_rate: " << (uint32)sample_rate << " => " << (sample_rate < sizeof(kSampleRates) ? kSampleRates[sample_rate] : 0); uint8 channels = ba.Read<uint8>(4); WATOMLOG << "channels: " << (uint32)channels; while (ba.Size() >= 21) { if (ba.Peek<uint16>(11) == 0x02b7) { ba.Skip(11); uint8 ext_object_type = ba.Read<uint8>(5); WATOMLOG << "ext_object_type: " << (uint32)ext_object_type; uint8 sbr = ba.Read<uint8>(1); WATOMLOG << "sbr: " << (uint32)sbr; uint8 ext_sample_rate = ba.Read<uint8>(4); WATOMLOG << "ext_sample_rate: " << (uint32)ext_sample_rate << " => " << (ext_sample_rate < sizeof(kSampleRates) ? kSampleRates[ext_sample_rate] : 0); WATOMLOG << "ext leftovers bits count: " << ba.Size(); break; } ba.Skip(1); } WATOMLOG << "extra data leftovers bits count: " << ba.Size(); #endif } } const int32 end_size = in.Size(); CHECK_GE(begin_size, end_size); const int32 decoded_size = begin_size - end_size; CHECK_GE(size, decoded_size); const int32 decode_leftover_size = size - decoded_size; // skip what's left undecoded. if ( decode_leftover_size > 0 ) { WATOMLOG << "undecoded leftover bytes: " << in.DumpContentInline(decode_leftover_size); in.Skip(decode_leftover_size); } return TAG_DECODE_SUCCESS; } void EsdsAtom::EncodeVersionedBody(io::MemoryStream& out, Encoder& encoder) const { if ( !raw_data_.IsEmpty() ) { out.AppendStreamNonDestructive(&raw_data_); return; } // TODO(cosmin): the ESDS encoding is a mess, mostly hardcoded. // Find some official documentation. WriteTagTypeAndLength(out, MP4ESDescrTag, 34); io::NumStreamer::WriteUInt16(&out, mp4_es_desc_tag_id_, common::BIGENDIAN); io::NumStreamer::WriteByte(&out, mp4_es_desc_tag_priority_); WriteTagTypeAndLength(out, MP4DecConfigDescrTag, 20); io::NumStreamer::WriteByte(&out, mp4_dec_config_desc_tag_object_type_id_); io::NumStreamer::WriteByte(&out, mp4_dec_config_desc_tag_stream_type_); io::NumStreamer::WriteUInt24(&out, mp4_dec_config_desc_tag_buffer_size_db_, common::BIGENDIAN); io::NumStreamer::WriteUInt32(&out, mp4_dec_config_desc_tag_max_bit_rate_, common::BIGENDIAN); io::NumStreamer::WriteUInt32(&out, mp4_dec_config_desc_tag_avg_bit_rate_, common::BIGENDIAN); WriteTagTypeAndLength(out, MP4DecSpecificDescrTag , 2); out.AppendStreamNonDestructive(&extra_data_); out.Write("\x06\x80\x80\x80\x01\x02", 6); // from 'backcountry.f4v' } uint64 EsdsAtom::MeasureVersionedBodySize() const { return raw_data_.Size(); } string EsdsAtom::ToStringVersionedBody(uint32 indent) const { return strutil::StringPrintf("raw_data_(full atom body): %u bytes" ", mp4_es_desc_tag_id_: %u" ", mp4_es_desc_tag_priority_: %u" ", mp4_dec_config_desc_tag_object_type_id_: %u" ", mp4_dec_config_desc_tag_stream_type_: %u" ", mp4_dec_config_desc_tag_buffer_size_db_: %u" ", mp4_dec_config_desc_tag_max_bit_rate_: %u" ", mp4_dec_config_desc_tag_avg_bit_rate_: %u" ", extra_data_: %s", raw_data_.Size(), mp4_es_desc_tag_id_, mp4_es_desc_tag_priority_, mp4_dec_config_desc_tag_object_type_id_, mp4_dec_config_desc_tag_stream_type_, mp4_dec_config_desc_tag_buffer_size_db_, mp4_dec_config_desc_tag_max_bit_rate_, mp4_dec_config_desc_tag_avg_bit_rate_, extra_data_.DumpContentInline().c_str()); } } }
39.074586
106
0.649558
[ "vector" ]
8ce94b73d0be0891f2db140d1ba82334bc714e27
3,481
cpp
C++
src/Core/CommandBuffers.cpp
Developmentprogramming/VulkanApi
0bd2adf6c90e167ea9e955d345727c3ac9ad93dc
[ "Apache-2.0" ]
null
null
null
src/Core/CommandBuffers.cpp
Developmentprogramming/VulkanApi
0bd2adf6c90e167ea9e955d345727c3ac9ad93dc
[ "Apache-2.0" ]
null
null
null
src/Core/CommandBuffers.cpp
Developmentprogramming/VulkanApi
0bd2adf6c90e167ea9e955d345727c3ac9ad93dc
[ "Apache-2.0" ]
null
null
null
// // Created by aeternum on 9/9/21. // #include "CommandBuffers.h" #include <stdexcept> #include "Buffer.h" namespace VulkanApi { CommandBuffers::CommandBuffers(const Ref<CommandPool>& commandPool, const Ref<SwapChain>& swapChain, const Ref<RenderPass>& renderPass, const Ref<Pipeline>& pipeline) : m_CommandPool(commandPool), m_SwapChain(swapChain), m_RenderPass(renderPass), m_Pipeline(pipeline), m_CommandBuffers(swapChain->GetFrameBuffers().size()) { VkCommandBufferAllocateInfo allocateInfo {}; allocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocateInfo.commandPool = m_CommandPool->GetVkCommandPool(); allocateInfo.commandBufferCount = (uint32_t)m_CommandBuffers.size(); if (vkAllocateCommandBuffers(m_CommandPool->GetDevice()->GetVkDevice(), &allocateInfo, m_CommandBuffers.data()) != VK_SUCCESS) throw std::runtime_error("Failed to allocate command buffers!"); } CommandBuffers::~CommandBuffers() { vkFreeCommandBuffers(m_CommandPool->GetDevice()->GetVkDevice(), m_CommandPool->GetVkCommandPool(), (uint32_t)m_CommandBuffers.size(), m_CommandBuffers.data()); } void CommandBuffers::Begin(const std::vector<Ref<Buffer>>& buffers) const { for (size_t i = 0; i < m_CommandBuffers.size(); i++) { VkCommandBufferBeginInfo beginInfo {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = 0; beginInfo.pInheritanceInfo = nullptr; if (vkBeginCommandBuffer(m_CommandBuffers[i], &beginInfo) != VK_SUCCESS) throw std::runtime_error("Failed to begin recording command buffer!"); VkRenderPassBeginInfo renderPassBeginInfo {}; renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassBeginInfo.renderPass = m_RenderPass->GetVkRenderPass(); renderPassBeginInfo.framebuffer = m_SwapChain->GetFrameBuffers()[i]; renderPassBeginInfo.renderArea.offset = { 0, 0 }; renderPassBeginInfo.renderArea.extent = m_SwapChain->GetVkExtent(); VkClearValue colorValue = { { { 0.0f, 0.0f, 0.0f, 1.0f } } }; renderPassBeginInfo.clearValueCount = 1; renderPassBeginInfo.pClearValues = &colorValue; vkCmdBeginRenderPass(m_CommandBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(m_CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_Pipeline->GetVkPipeline()); bool drawIndexed = false; uint32_t indexCount; for (auto& buffer : buffers) { buffer->Bind(m_CommandBuffers[i]); if (buffer->GetVkBufferUsage() == VK_BUFFER_USAGE_INDEX_BUFFER_BIT) { auto ibo = reinterpret_cast<IndexBuffer*>(buffer.get()); drawIndexed = true; indexCount = ibo->GetIndexCount(); } } if (drawIndexed) vkCmdDrawIndexed(m_CommandBuffers[i], indexCount, 1, 0, 0, 0); else vkCmdDraw(m_CommandBuffers[i], 3, 1, 0, 0); vkCmdEndRenderPass(m_CommandBuffers[i]); if (vkEndCommandBuffer(m_CommandBuffers[i]) != VK_SUCCESS) throw std::runtime_error("Failed to record command buffers!"); } } }
41.939759
170
0.649813
[ "vector" ]
8ceaa15a8736919778e4f8b946385e5c5be20e04
6,076
cpp
C++
src/hardware/platforms/DummyExo/ExoRobot.cpp
shortmr/CANOpenRobotController
61602c2d19ff1e87408152ca61b4f37df1598bfa
[ "Apache-2.0" ]
null
null
null
src/hardware/platforms/DummyExo/ExoRobot.cpp
shortmr/CANOpenRobotController
61602c2d19ff1e87408152ca61b4f37df1598bfa
[ "Apache-2.0" ]
null
null
null
src/hardware/platforms/DummyExo/ExoRobot.cpp
shortmr/CANOpenRobotController
61602c2d19ff1e87408152ca61b4f37df1598bfa
[ "Apache-2.0" ]
1
2021-05-04T17:19:45.000Z
2021-05-04T17:19:45.000Z
#include "ExoRobot.h" ExoRobot::ExoRobot() : Robot() { } ExoRobot::~ExoRobot() { spdlog::debug("Delete ExoRobot object begins"); freeMemory(); // joints.clear(); // copleyDrives.clear(); spdlog::debug("ExoRobot deleted"); } bool ExoRobot::initPositionControl() { spdlog::debug("Initialising Position Control on all joints "); bool returnValue = true; for (auto p : joints) { if (p->setMode(CM_POSITION_CONTROL, posControlMotorProfile) != CM_POSITION_CONTROL) { // Something back happened if were are here spdlog::error("Something bad happened"); returnValue = false; } // Put into ReadyToSwitchOn() p->readyToSwitchOn(); } // Pause for a bit to let commands go usleep(2000); for (auto p : joints) { p->enable(); } return returnValue; } bool ExoRobot::initVelocityControl() { spdlog::debug("Initialising Velocity Control on all joints "); bool returnValue = true; for (auto p : joints) { if (p->setMode(CM_VELOCITY_CONTROL) != CM_VELOCITY_CONTROL) { // Something back happened if were are here spdlog::error("Something bad happened"); returnValue = false; } // Put into ReadyToSwitchOn() p->readyToSwitchOn(); } // Pause for a bit to let commands go usleep(2000); for (auto p : joints) { p->enable(); } return returnValue; } bool ExoRobot::initTorqueControl() { spdlog::debug("Initialising Torque Control on all joints "); bool returnValue = true; for (auto p : joints) { if (p->setMode(CM_TORQUE_CONTROL) != CM_TORQUE_CONTROL) { // Something back happened if were are here spdlog::error("Something bad happened"); returnValue = false; } // Put into ReadyToSwitchOn() p->readyToSwitchOn(); } // Pause for a bit to let commands go usleep(2000); for (auto p : joints) { p->enable(); } return returnValue; } setMovementReturnCode_t ExoRobot::setPosition(std::vector<double> positions) { int i = 0; setMovementReturnCode_t returnValue = SUCCESS; for (auto p : joints) { setMovementReturnCode_t setPosCode = ((DummyActJoint *)p)->setPosition(positions[i]); if (setPosCode == INCORRECT_MODE) { std::cout << "Joint ID " << p->getId() << ": is not in Position Control " << std::endl; returnValue = INCORRECT_MODE; } else if (setPosCode != SUCCESS) { // Something bad happened std::cout << "Joint " << p->getId() << ": Unknown Error " << std::endl; returnValue = UNKNOWN_ERROR; } i++; } return returnValue; } setMovementReturnCode_t ExoRobot::setVelocity(std::vector<double> velocities) { int i = 0; setMovementReturnCode_t returnValue = SUCCESS; for (auto p : joints) { setMovementReturnCode_t setPosCode = ((DummyActJoint *)p)->setVelocity(velocities[i]); if (setPosCode == INCORRECT_MODE) { std::cout << "Joint ID " << p->getId() << ": is not in Velocity Control " << std::endl; returnValue = INCORRECT_MODE; } else if (setPosCode != SUCCESS) { // Something bad happened std::cout << "Joint " << p->getId() << ": Unknown Error " << std::endl; returnValue = UNKNOWN_ERROR; } i++; } return returnValue; } setMovementReturnCode_t ExoRobot::setTorque(std::vector<double> torques) { int i = 0; setMovementReturnCode_t returnValue = SUCCESS; for (auto p : joints) { setMovementReturnCode_t setPosCode = ((DummyActJoint *)p)->setTorque(torques[i]); if (setPosCode == INCORRECT_MODE) { std::cout << "Joint ID " << p->getId() << ": is not in Torque Control " << std::endl; returnValue = INCORRECT_MODE; } else if (setPosCode != SUCCESS) { // Something bad happened std::cout << "Joint " << p->getId() << ": Unknown Error " << std::endl; returnValue = UNKNOWN_ERROR; } i++; } return returnValue; } std::vector<double> ExoRobot::getPosition() { int i = 0; std::vector<double> actualJointPositions(joints.size()); for (auto p : joints) { actualJointPositions[i] = ((DummyActJoint *)p)->getPosition(); i++; } return actualJointPositions; } std::vector<double> ExoRobot::getVelocity() { int i = 0; std::vector<double> actualJointVelocities(joints.size()); for (auto p : joints) { actualJointVelocities[i] = ((DummyActJoint *)p)->getVelocity(); i++; } return actualJointVelocities; } std::vector<double> ExoRobot::getTorque() { int i = 0; std::vector<double> actualJointTorques(joints.size()); for (auto p : joints) { actualJointTorques[i] = ((DummyActJoint *)p)->getTorque(); i++; } return actualJointTorques; } bool ExoRobot::initialiseJoints() { for (int id = 0; id < NUM_JOINTS; id++) { copleyDrives.push_back(new CopleyDrive(id + 1)); joints.push_back(new DummyActJoint(id, jointMinMap[id], jointMaxMap[id], copleyDrives[id])); } return true; } bool ExoRobot::initialiseNetwork() { spdlog::debug("ExoRobot::initialiseNetwork()"); bool status; for (auto joint : joints) { status = joint->initNetwork(); if (!status) return false; } return true; } bool ExoRobot::initialiseInputs() { inputs.push_back(keyboard = new Keyboard()); return true; } void ExoRobot::freeMemory() { for (auto p : copleyDrives) { spdlog::debug("Delete Drive Node: {}", p->getNodeID()); delete p; } for (auto p : joints) { spdlog::debug("Delete Joint ID: {}", p->getId()); delete p; } for (auto p : inputs) { spdlog::debug("Deleting Input"); delete p; } } void ExoRobot::updateRobot() { Robot::updateRobot(); }
29.639024
100
0.590355
[ "object", "vector" ]
8cf539a4d8bc0233a5b45469871bde212b97cfe6
6,744
cpp
C++
PSME/common/agent-framework/src/module/constants/common.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/common/agent-framework/src/module/constants/common.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
null
null
null
PSME/common/agent-framework/src/module/constants/common.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/*! * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * @file common.cpp * @brief Contains common constants used all over the model * */ #include "agent-framework/module/constants/common.hpp" namespace agent_framework { namespace model { namespace literals { constexpr const char ServiceUuid::UUID[]; constexpr const char Status::STATUS[]; constexpr const char Status::STATE[]; constexpr const char Status::HEALTH[]; constexpr const char FruInfo::FRU_INFO[]; constexpr const char FruInfo::SERIAL[]; constexpr const char FruInfo::MANUFACTURER[]; constexpr const char FruInfo::MODEL[]; constexpr const char FruInfo::PART[]; constexpr const char Collections::COLLECTIONS[]; constexpr const char Collections::NAME[]; constexpr const char Collections::TYPE[]; constexpr const char Collections::SLOT_MASK[]; constexpr const char Collection::COMPONENT[]; constexpr const char Collection::NAME[]; constexpr const char HeartBeat::TIME_STAMP[]; constexpr const char HeartBeat::MIN_DELAY[]; constexpr const char Oem::OEM[]; constexpr const char Component::COMPONENT[]; constexpr const char Component::ATTRIBUTES[]; constexpr const char Component::ATTRIBUTE[]; constexpr const char Component::NOTIFICATION[]; constexpr const char Component::PARENT[]; constexpr const char Component::TYPE[]; constexpr const char Component::TIME_STAMP[]; constexpr const char Component::MESSAGE[]; constexpr const char Component::CODE[]; constexpr const char SubcomponentEntry::SUBCOMPONENT[]; constexpr const char ManagerEntry::MANAGER[]; constexpr const char TaskEntry::TASK[]; constexpr const char TaskEntry::OEM[]; constexpr const char SerialConsole::SERIAL_CONSOLE[]; constexpr const char SerialConsole::SIGNAL_TYPE[]; constexpr const char SerialConsole::BITRATE[]; constexpr const char SerialConsole::PARITY[]; constexpr const char SerialConsole::DATA_BITS[]; constexpr const char SerialConsole::STOP_BITS[]; constexpr const char SerialConsole::FLOW_CONTROL[]; constexpr const char SerialConsole::PIN_OUT[]; constexpr const char SerialConsole::ENABLED[]; constexpr const char SerialConsole::MAX_SESSIONS[]; constexpr const char SerialConsole::TYPES_SUPPORTED[]; constexpr const char NetworkService::NETWORK_SERVICES[]; constexpr const char NetworkService::NAME[]; constexpr const char NetworkService::PORT[]; constexpr const char NetworkService::ENABLED[]; constexpr const char Manager::MANAGER[]; constexpr const char Manager::OEM[]; constexpr const char Manager::STATUS[]; constexpr const char Manager::TYPE[]; constexpr const char Manager::MODEL[]; constexpr const char Manager::LOCATION[]; constexpr const char Manager::FIRMWARE_VERSION[]; constexpr const char Manager::IPv4_ADDRESS[]; constexpr const char Manager::NETWORK_SERVICES[]; constexpr const char Manager::GRAPHICAL_CONSOLE[]; constexpr const char Manager::SERIAL_CONSOLE[]; constexpr const char Manager::COMMAND_SHELL[]; constexpr const char Manager::COLLECTIONS[]; constexpr const char Manager::PARENT_ID[]; constexpr const char Manager::GUID[]; constexpr const char Manager::DATE_TIME[]; constexpr const char Manager::DATE_TIME_LOCAL_OFFSET[]; constexpr const char GraphicalConsole::ENABLED[]; constexpr const char GraphicalConsole::MAX_SESSIONS[]; constexpr const char GraphicalConsole::TYPES_SUPPORTED[]; constexpr const char CommandShell::ENABLED[]; constexpr const char CommandShell::MAX_SESSIONS[]; constexpr const char CommandShell::TYPES_SUPPORTED[]; constexpr const char Ipv4Address::IPv4_ADDRESS[]; constexpr const char Ipv4Address::ADDRESS[]; constexpr const char Ipv4Address::SUBNET_MASK[]; constexpr const char Ipv4Address::ADDRESS_ORIGIN[]; constexpr const char Ipv4Address::GATEWAY[]; constexpr const char Ipv6Address::IPv6_ADDRESS[]; constexpr const char Ipv6Address::ADDRESS[]; constexpr const char Ipv6Address::PREFIX_LENGTH[]; constexpr const char Ipv6Address::ADDRESS_ORIGIN[]; constexpr const char Ipv6Address::ADDRESS_STATE[]; constexpr const char Intel::INTEL_CORP[]; constexpr const char Drive::DRIVE[]; constexpr const char Drive::STATUS[]; constexpr const char Drive::PHYSICAL_ID[]; constexpr const char Drive::INTERFACE[]; constexpr const char Drive::TYPE[]; constexpr const char Drive::RPM[]; constexpr const char Drive::FIRMWARE_VERSION[]; constexpr const char Drive::CAPACITY[]; constexpr const char Drive::FRU_INFO[]; constexpr const char Drive::INDICATOR_LED[]; constexpr const char Drive::ASSET_TAG[]; constexpr const char Drive::CAPABLE_SPEED_GBS[]; constexpr const char Drive::NEGOTIATED_SPEED_GBS[]; constexpr const char Drive::LOCATION[]; constexpr const char Drive::STATUS_INDICATOR[]; constexpr const char Drive::REVISION[]; constexpr const char Drive::FAILURE_PREDICTED[]; constexpr const char Drive::SKU[]; constexpr const char Drive::IDENTIFIERS[]; constexpr const char Drive::HOTSPARE_TYPE[]; constexpr const char Drive::ENCRYPTION_ABILITY[]; constexpr const char Drive::ENCRYPTION_STATUS[]; constexpr const char Drive::BLOCK_SIZE_BYTES[]; constexpr const char Drive::PREDICTED_MEDIA_LIFE_LEFT[]; constexpr const char Drive::ERASED[]; constexpr const char Drive::COLLECTIONS[]; constexpr const char Drive::OEM[]; constexpr const char Drive::SECURELY_ERASE[]; constexpr const char Location::INFO[]; constexpr const char Location::INFO_FORMAT[]; constexpr const char Identifier::DURABLE_NAME[]; constexpr const char Identifier::DURABLE_NAME_FORMAT[]; constexpr const char Message::MESSAGE_ID[]; constexpr const char Message::MESSAGE[]; constexpr const char Message::RELATED_PROPERTIES[]; constexpr const char Message::MESSAGE_ARGS[]; constexpr const char Message::SEVERITY[]; constexpr const char Message::RESOLUTION[]; constexpr const char Message::OEM[]; constexpr const char Task::TASK[]; constexpr const char Task::STATE[]; constexpr const char Task::START_TIME[]; constexpr const char Task::END_TIME[]; constexpr const char Task::STATUS[]; constexpr const char Task::MESSAGES[]; constexpr const char Task::NAME[]; constexpr const char Task::OEM[]; constexpr const char ConnectedEntity::ENTITY_TYPE[]; constexpr const char ConnectedEntity::ENTITY_ROLE[]; constexpr const char ConnectedEntity::ENTITY[]; } } }
35.125
75
0.786922
[ "model" ]
8cf82cb280de3825057aa8095977f23f65701bd2
955
cpp
C++
src/iqrf/IQRFJsonRequest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
7
2018-06-09T05:55:59.000Z
2021-01-05T05:19:02.000Z
src/iqrf/IQRFJsonRequest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
1
2019-12-25T10:39:06.000Z
2020-01-03T08:35:29.000Z
src/iqrf/IQRFJsonRequest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
11
2018-05-10T08:29:05.000Z
2020-01-22T20:49:32.000Z
#include "iqrf/IQRFJsonRequest.h" #ifndef JSON_PRESERVE_KEY_ORDER #define JSON_PRESERVE_KEY_ORDER 1 #endif using namespace BeeeOn; using namespace Poco; using namespace std; IQRFJsonRequest::IQRFJsonRequest(): IQRFJsonMessage() { } string IQRFJsonRequest::request() const { return m_request; } void IQRFJsonRequest::setRequest(const string &request) { m_request = request; } string IQRFJsonRequest::toString() { JSON::Object::Ptr root = new JSON::Object(JSON_PRESERVE_KEY_ORDER); JSON::Object::Ptr data = new JSON::Object(JSON_PRESERVE_KEY_ORDER); JSON::Object::Ptr request = new JSON::Object(JSON_PRESERVE_KEY_ORDER); root->set("mType", "iqrfRaw"); data->set("msgId", messageID()); data->set("timeout", static_cast<int>(timeout().totalMilliseconds())); // DPA datagram request->set("rData", m_request); data->set("req",request); data->set("returnVerbose", true); root->set("data", data); return Dynamic::Var::toString(root); }
20.319149
71
0.737173
[ "object" ]
8cf997f49057a9e10ee1650f7e97f6ad9c4e8e7c
15,355
hpp
C++
src/cpp/probability_distribution.hpp
plewis/phycas
9f5a4d9b2342dab907d14a46eb91f92ad80a5605
[ "MIT" ]
3
2015-09-24T23:12:57.000Z
2021-04-12T07:07:01.000Z
src/cpp/probability_distribution.hpp
plewis/phycas
9f5a4d9b2342dab907d14a46eb91f92ad80a5605
[ "MIT" ]
null
null
null
src/cpp/probability_distribution.hpp
plewis/phycas
9f5a4d9b2342dab907d14a46eb91f92ad80a5605
[ "MIT" ]
1
2015-11-23T10:35:43.000Z
2015-11-23T10:35:43.000Z
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ | Phycas: Python software for phylogenetic analysis | | Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford | | | | 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. | \~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #if !defined(PROBABILITY_DISTRIBUTION_HPP) #define PROBABILITY_DISTRIBUTION_HPP #if defined(_MSC_VER) # pragma warning(disable: 4267) // warning about loss of data when converting size_t to int #endif #include <cmath> #include "ncl/nxsdefs.h" #include "states_patterns.hpp" #include <boost/shared_ptr.hpp> #include <boost/format.hpp> #include "basic_cdf.hpp" #include "basic_lot.hpp" #include "phycas_string.hpp" #if defined(PYTHON_ONLY) && defined(USING_NUMARRAY) # include <boost/python/tuple.hpp> # include <boost/python/numeric.hpp> # include "thirdparty/num_util/num_util.h" #endif #include "xprobdist.hpp" class XUnderflow{}; namespace phycas { struct AdHocDensity { virtual ~AdHocDensity() { //std::cerr << "\n>>>>> AdHocDensity dying..." << std::endl; } virtual double operator()(double) = 0; }; class ProbabilityDistribution : public AdHocDensity { public: ProbabilityDistribution() {lot = &myLot;} virtual ~ProbabilityDistribution(); double LnGamma(double x); virtual void SetLot(Lot * other); //@POL seems like this should be a shared pointer virtual Lot * GetLot() {return lot;} virtual void ResetLot(); virtual void SetSeed(unsigned rnseed); virtual bool IsDiscrete() const = 0; virtual std::string GetDistributionName() const = 0; virtual std::string GetDistributionDescription() const = 0; virtual double GetMean() const = 0; virtual double GetVar() const = 0; virtual double GetStdDev() const = 0; virtual double GetCDF(double x) const = 0; virtual double Sample() const = 0; virtual double GetLnPDF(double x) const = 0; virtual double GetRelativeLnPDF(double x) const = 0; double GetRelativeLnPDFArray(double *x, int arrLen) const; virtual void SetMeanAndVariance(double m, double v) = 0; virtual double operator()(double x); CDF cdf; Lot myLot; Lot * lot; }; typedef boost::shared_ptr<ProbabilityDistribution> ProbDistShPtr; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | Encapsulates the discrete bernoulli probability distribution with parameter p, the probability of success. */ class BernoulliDistribution : public ProbabilityDistribution { protected: double p; /* the probability of success on any given trial */ public: BernoulliDistribution(); BernoulliDistribution(double prob_success); BernoulliDistribution(const BernoulliDistribution & other); ~BernoulliDistribution(); BernoulliDistribution * Clone() const; BernoulliDistribution * cloneAndSetLot(Lot * other) const; virtual bool IsDiscrete() const; virtual std::string GetDistributionName() const; virtual std::string GetDistributionDescription() const; virtual double GetMean() const; virtual double GetVar() const; virtual double GetStdDev() const; virtual double GetCDF(double x) const; virtual double Sample() const; virtual double GetLnPDF(double x) const; virtual double GetRelativeLnPDF(double x) const; virtual void SetMeanAndVariance(double mean, double var); }; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | Encapsulates the discrete binomial probability distribution with parameter p, the probability of success. */ class BinomialDistribution : public BernoulliDistribution { public: BinomialDistribution(); BinomialDistribution(double sample_size, double prob_success); BinomialDistribution(const BinomialDistribution & other); ~BinomialDistribution(); BinomialDistribution * cloneAndSetLot(Lot * other) const; BinomialDistribution * Clone() const; virtual bool IsDiscrete() const; virtual std::string GetDistributionName() const; virtual std::string GetDistributionDescription() const; virtual double GetMean() const; virtual double GetVar() const; virtual double GetStdDev() const; virtual double GetCDF(double x) const; virtual double Sample() const; virtual double GetLnPDF(double x) const; virtual double GetRelativeLnPDF(double x) const; virtual void SetMeanAndVariance(double mean, double var); private: double q; double lnp; double lnq; protected: double n; }; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | Encapsulates the continuous Beta probability distribution with parameters alpha and beta. */ class BetaDistribution : public ProbabilityDistribution { double alphaParam; double betaParam; public: BetaDistribution() : alphaParam(1.0), betaParam(1.0) {} BetaDistribution(double a, double b); BetaDistribution(const BetaDistribution & other); ~BetaDistribution(); BetaDistribution * cloneAndSetLot(Lot * other) const; BetaDistribution * Clone() const; bool IsDiscrete() const; std::string GetDistributionName() const; std::string GetDistributionDescription() const; double GetMean() const; double GetVar() const; double GetStdDev() const; double GetCDF(double x) const; double GetQuantile(double p) const; double Sample() const; double GetLnPDF(double x) const; double GetRelativeLnPDF(double x) const; void SetMeanAndVariance(double m, double v); }; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | Encapsulates the continuous Beta prime probability distribution with parameters alpha and beta. */ class BetaPrimeDistribution : public ProbabilityDistribution { double alphaParam; double betaParam; public: BetaPrimeDistribution() : alphaParam(1.0), betaParam(1.0) {} BetaPrimeDistribution(double a, double b); BetaPrimeDistribution(const BetaPrimeDistribution & other); ~BetaPrimeDistribution(); BetaPrimeDistribution * cloneAndSetLot(Lot * other) const; BetaPrimeDistribution * Clone() const; bool IsDiscrete() const; std::string GetDistributionName() const; std::string GetDistributionDescription() const; double GetMean() const; double GetVar() const; double GetStdDev() const; double GetCDF(double x) const; double GetQuantile(double p) const; double Sample() const; double GetLnPDF(double x) const; double GetRelativeLnPDF(double x) const; void SetMeanAndVariance(double m, double v); }; /*---------------------------------------------------------------------------------------------------------------------- | A uniform probability distribution with left bound 0.0 and right bound infinity. This is an improper distribution | (the area under its density curve is infinite). */ class ImproperUniformDistribution : public ProbabilityDistribution { public: ImproperUniformDistribution(); ImproperUniformDistribution(const ImproperUniformDistribution & other); ~ImproperUniformDistribution(); ImproperUniformDistribution * cloneAndSetLot(Lot * other) const; ImproperUniformDistribution * Clone() const; bool IsDiscrete() const; std::string GetDistributionName() const; std::string GetDistributionDescription() const; double GetMean() const; double GetVar() const; double GetStdDev() const; double GetCDF(double x) const; double Sample() const; double GetLnPDF(double x) const; double GetRelativeLnPDF(double x) const; void SetMeanAndVariance(double mean, double var); }; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | Encapsulates the continuous uniform probability distribution with left bound a and right bound b. */ class UniformDistribution : public ProbabilityDistribution { public: UniformDistribution(); UniformDistribution(double left_bound, double right_bound); UniformDistribution(const UniformDistribution & other); ~UniformDistribution(); UniformDistribution * cloneAndSetLot(Lot * other) const; UniformDistribution * Clone() const; bool IsDiscrete() const; std::string GetDistributionName() const; std::string GetDistributionDescription() const; double GetMean() const; double GetVar() const; double GetStdDev() const; double GetCDF(double x) const; double Sample() const; double GetLnPDF(double x) const; double GetRelativeLnPDF(double x) const; void SetMeanAndVariance(double mean, double var); virtual double GetLeftSupportBoundary() const; virtual double GetRightSupportBoundary() const; protected: double a; /**< the left bound */ double b; /**< the right bound */ double log_density; /**< the precalculated log of the density function */ }; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | Encapsulates the gamma probability distribution with shape parameter (alpha) and scale parameter (beta). */ class GammaDistribution : public ProbabilityDistribution { public: GammaDistribution(); GammaDistribution(double shape, double scale); GammaDistribution(const GammaDistribution & other); ~GammaDistribution(); GammaDistribution * cloneAndSetLot(Lot * other) const; GammaDistribution * Clone() const; bool IsDiscrete() const; std::string GetDistributionName() const; std::string GetDistributionDescription() const; double GetMean() const; double GetVar() const; double GetStdDev() const; double GetCDF(double x) const; double Sample() const; virtual double GetLnPDF(double x) const; double GetRelativeLnPDF(double x) const; void SetMeanAndVariance(double mean, double var); protected: void ComputeLnConst(); protected: double alpha; /* the shape parameter */ double beta; /* the scale parameter */ double ln_const; /* the natural logarithm of the constant part of the density function */ }; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | The inverse (or inverted) gamma distribution with parameters alpha and beta is the distribution of 1/X where X is a gamma distributed random variable with shape | parameter alpha and scale parameter beta. */ class InverseGammaDistribution : public GammaDistribution { public: InverseGammaDistribution(); InverseGammaDistribution(double shape, double scale); InverseGammaDistribution(const InverseGammaDistribution & other); ~InverseGammaDistribution(); InverseGammaDistribution * cloneAndSetLot(Lot * other) const; InverseGammaDistribution * Clone() const; bool IsDiscrete() const; std::string GetDistributionName() const; std::string GetDistributionDescription() const; double GetMean() const; double GetVar() const; double GetStdDev() const; double GetCDF(double x) const; double Sample() const; double GetLnPDF(double x) const; double GetRelativeLnPDF(double x) const; void SetMeanAndVariance(double mean, double var); }; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | This is a special case of the gamma distribution in which the shape parameter equals the mean and the scale parameter is 1.0. */ class ExponentialDistribution : public GammaDistribution { public : ExponentialDistribution(); ExponentialDistribution(double lambda); ExponentialDistribution(const ExponentialDistribution & other); ~ExponentialDistribution(); ExponentialDistribution * cloneAndSetLot(Lot * other) const; ExponentialDistribution * Clone() const; bool IsDiscrete() const; std::string GetDistributionName() const; std::string GetDistributionDescription() const; void SetMeanAndVariance(double mean, double var = 0.0); double GetLnPDF(double x) const; }; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------ | The Normal distribution with two parameters, the mean and standard deviation. */ class NormalDistribution : public ProbabilityDistribution { public: NormalDistribution(); NormalDistribution(double mean, double stddev); NormalDistribution(const NormalDistribution & other); ~NormalDistribution(); NormalDistribution * cloneAndSetLot(Lot * other) const; NormalDistribution * Clone() const; bool IsDiscrete() const; std::string GetDistributionName() const; std::string GetDistributionDescription() const; double GetMean() const; double GetVar() const; double GetStdDev() const; double GetCDF(double x) const; double Sample() const; double GetLnPDF(double x) const; double GetRelativeLnPDF(double x) const; void SetMeanAndVariance(double mean, double var); protected: void ComputeLnConst(); protected: double mean; /**< the mean parameter of the normal distribution */ double sd; /**< the standard deviation parameter of the normal distribution */ double ln_const; /**< the natural logarithm of the constant part of the density function */ double pi_const; /**< precalculated (in constructor) value of pi */ double sqrt2_const; /**< precalculated (in constructor) value of sqrt(2.0) */ }; } // namespace phycas #endif
38.580402
164
0.622403
[ "shape" ]
ea049f946b78418c34fa45dce5db86c465d9444c
13,942
cpp
C++
test/unittest.cpp
ckobayashi714/121-Milestone-Project-4-Quiz-Maker
a348afc996718ad5758dd9b3678f0bac584c976e
[ "MIT" ]
null
null
null
test/unittest.cpp
ckobayashi714/121-Milestone-Project-4-Quiz-Maker
a348afc996718ad5758dd9b3678f0bac584c976e
[ "MIT" ]
null
null
null
test/unittest.cpp
ckobayashi714/121-Milestone-Project-4-Quiz-Maker
a348afc996718ad5758dd9b3678f0bac584c976e
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <fstream> #include <cstdio> #include <cstring> #include "gtest_ext.h" #include "../quiz.hpp" using ::testing::HasSubstr; using ::testing::StartsWith; using ::testing::MatchesRegex; using ::testing::ContainsRegex; TEST(Quiz, PublicMethodsPresent) { question q; ASSERT_NO_THROW({ q.text(); q.answer(); q.set_text("a"); q.set_answer("b"); }); } TEST(Quiz, MutatorsAndAccessors) { question q; std::string text, answer; text = generate_string(10); answer = generate_string(10); ASSERT_NO_THROW({ q.set_text(text); q.set_answer(answer); }); ASSERT_EQ(q.text(), text); ASSERT_EQ(q.answer(), answer); } TEST(Quiz, CreateQuestion) { for(int i = 0; i < 10; i++) { std::string text, answer; text = generate_string(10); answer = generate_string(10); question temp, actual; temp.set_text(text); temp.set_answer(answer); std::string input = text+"\n"+answer; SIMULATE_CIN(input, { actual = create_question(); }); ASSERT_EQ(temp.text(), actual.text()); ASSERT_EQ(temp.answer(), actual.answer()); } } TEST(Quiz, SaveQuestion) { for(int i = 0; i < 10; i++) { int repetitions = rand() % 10 + 1; question questions[repetitions]; for (int i = 0; i < repetitions; i++) { std::string text, answer; text = generate_string(10); answer = generate_string(10); questions[i].set_text(text); questions[i].set_answer(answer); } std::string filename = generate_string(5) + ".txt"; ASSERT_DURATION_LE(3, { ASSERT_SIO_EQ("", "File saved successfully!\n\n", { save_questions(questions, repetitions, filename); }); }); ifstream test_file(filename.c_str()); ASSERT_TRUE(test_file.good()); remove(filename.c_str()); } } TEST(Quiz, SaveFileFormat) { for(int i = 0; i < 10; i++) { int repetitions = rand() % 10 + 1; question questions[repetitions]; std::string expected = std::to_string(repetitions) + "\n"; for (int j = 0; j < repetitions; j++) { std::string text, answer; text = generate_string(10); answer = generate_string(10); questions[j].set_text(text); questions[j].set_answer(answer); expected += "[SQ]\n"; expected += text + "\n"; expected += answer + "\n"; } std::string filename = generate_string(5) + ".txt"; ASSERT_DURATION_LE(3, { ASSERT_SIO_EQ("", "File saved successfully!\n\n", { save_questions(questions, repetitions, filename); }); }); ifstream save_file(filename); ASSERT_TRUE(save_file.good()) << "Save file was not created"; std::string file_contents, temp_holder; while(save_file >> temp_holder) { file_contents += temp_holder + "\n"; } save_file.close(); remove(filename.c_str()); ASSERT_EQ(file_contents, expected); } } TEST(Quiz, LoadQuestions) { for(int i = 0; i < 10; i++) { int file_questions_size = rand() % 10 + 1; question file_questions[file_questions_size]; std::string file_contents = std::to_string(file_questions_size) + "\n"; for (int j = 0; j < file_questions_size; j++) { std::string text, answer; text = generate_string(10); answer = generate_string(10); file_questions[j].set_text(text); file_questions[j].set_answer(answer); file_contents += "[SQ]\n"; file_contents += text + "\n"; file_contents += answer + "\n"; } std::string filename = generate_string(5) + ".txt"; ofstream out_file(filename); out_file << file_contents; out_file.close(); question question_list[100]; int size = 0; ASSERT_DURATION_LE(3, { ASSERT_SIO_EQ("", "File loaded successfully!\n\n", { load_questions(question_list, &size, filename); }); }); ASSERT_EQ(size, file_questions_size); for (int j = 0; j < file_questions_size; j++) { ASSERT_EQ(question_list[j].text(), file_questions[j].text()); ASSERT_EQ(question_list[j].answer(), file_questions[j].answer()); } remove(filename.c_str()); } } TEST(Quiz, DisplayQuestions) { for(int i = 0; i < 10; i++) { int repetitions = rand() % 10 + 1; question questions[repetitions]; std::string expected = "Question and Answer list\n"; for (int i = 0; i < repetitions; i++) { std::string text, answer; text = generate_string(10); answer = generate_string(10); questions[i].set_text(text); questions[i].set_answer(answer); expected += std::to_string(i+1) + ". "+ text +"\nAnswer: " + answer + "\n"; } expected += "\n"; ASSERT_DURATION_LE(3, { ASSERT_SIO_EQ("", expected, display_questions(questions, repetitions)); }); } } TEST(Quiz, CreateQuestionChoice) { std::string expected = "Welcome to QuizMaker\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nPlease enter your question: Please enter the " "answer: Question added!\n\nWhat would you like to do?" "\na. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit" "\nChoice: \nThank you for using QuizMaker!\n"; ASSERT_DURATION_LE(3, { ASSERT_EXECIO_EQ("quizgen", "a\nX\nX\ne", expected); }); } TEST(Quiz, FiniteChoiceLoop) { srand (time(NULL)); ASSERT_DURATION_LE(3, { main_output("quizgen", "a\nX\nX\ne"); }); } TEST(Quiz, DisplayQuestionsChoice) { std::string expected = "Welcome to QuizMaker\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nPlease enter your question: Please enter the " "answer: Question added!\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nQuestion and Answer list\n1. X\nAnswer: X" "\n\nWhat would you like to do?\na. Create a question" "\nb. Display questions\nc. Save questions\nd. Load " "questions\ne. Quit\nChoice: \nThank you for using " "QuizMaker!\n"; ASSERT_DURATION_LE(3, { ASSERT_EXECIO_EQ("quizgen", "a\nX\nX\nb\ne", expected); }); } TEST(Quiz, SaveQuestionsChoice) { std::string expected = "Welcome to QuizMaker\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nWhat filename would you like to use? File " "saved successfully!\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nThank you for using QuizMaker!\n"; string filename = generate_string(5) + ".txt"; string input = "c\n" + filename + "\ne"; ASSERT_DURATION_LE(3, { ASSERT_EXECIO_EQ("quizgen", input, expected); }); std::remove(filename.c_str()); } TEST(Quiz, LoadQuestionsChoice) { std::string expected = "Welcome to QuizMaker\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nWhat file would you like to load? File " "loaded successfully!\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nThank you for using QuizMaker!\n"; string filename = generate_string(5) + ".txt"; string input = "d\n" + filename + "\ne"; ASSERT_DURATION_LE(3, { ASSERT_EXECIO_EQ("quizgen", input, expected); }); std::remove(filename.c_str()); } TEST(Quiz, QuitChoice) { std::string expected = "Welcome to QuizMaker\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nThank you for using QuizMaker!\n"; ASSERT_DURATION_LE(3, { ASSERT_EXECIO_EQ("quizgen", "e", expected); }); } TEST(Quiz, InvalidOptionChoice) { std::string expected = "Welcome to QuizMaker\n\nWhat would you like to do?\n" "a. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nInvalid option\n\nWhat would you like to " "do?\na. Create a question\nb. Display questions\n" "c. Save questions\nd. Load questions\ne. Quit\n" "Choice: \nThank you for using QuizMaker!\n"; ASSERT_DURATION_LE(3, { ASSERT_EXECIO_EQ("quizgen", "x\ne",expected); }); } TEST(Quiz, ChoiceLoopLowercase) { int repetitions = rand() % 10 + 1; for (int i = 0; i < repetitions; i++) { std::string input = ""; std::string question_list = "Question and Answer list\n"; std::string expected = "Welcome to QuizMaker\n\n"; std::vector<std::string> filenames; std::string load_file_name = generate_string(10) + ".txt"; ofstream out_file(load_file_name); out_file << 1 << "\n" << "[SQ]\nq\na\n"; out_file.close(); int question_ctr = 1; char choice; do { choice = rand() % 5 + 97; expected += "What would you like to do?\na. Create a question\n" "b. Display questions\nc. Save questions\nd. Load questions\n" "e. Quit\nChoice: \n"; std::string s_choice(1, choice); input += s_choice + "\\n"; switch (choice) { case 'a': expected += "Please enter your question: Please enter the answer: " "Question added!\n\n"; input += "q\\na\\n"; question_list += std::to_string(question_ctr) +". q\nAnswer: a\n"; question_ctr++; break; case 'b': expected += question_list + "\n"; break; case 'c': { expected += "What filename would you like to use? File saved successfully!\n\n"; std::string filename = generate_string(5) + ".txt"; filenames.push_back(filename); input += filename+"\n"; break; } case 'd': { expected += "What file would you like to load? File loaded successfully!\n\n"; input += load_file_name+"\n"; question_list = "Question and Answer list\n1. q\nAnswer: a\n"; question_ctr = 2; break; } case 'e': expected += "Thank you for using QuizMaker!\n"; break; default: expected += "Invalid option\n\n"; } } while(choice!= 'e'); ASSERT_DURATION_LE(3, { ASSERT_EXECIO_EQ("quizgen", input, expected); }); remove(load_file_name.c_str()); for(std::string fn : filenames) { remove(fn.c_str()); } } } TEST(Quiz, ChoiceLoopUppercase) { int repetitions = rand() % 10 + 1; for (int i = 0; i < repetitions; i++) { std::string input = ""; std::string question_list = "Question and Answer list\n"; std::string expected = "Welcome to QuizMaker\n\n"; std::vector<std::string> filenames; std::string load_file_name = generate_string(10) + ".txt"; ofstream out_file(load_file_name); out_file << 1 << "\n" << "[SQ]\nq\na\n"; out_file.close(); int question_ctr = 1; char choice; do { choice = rand() % 5 + 65; expected += "What would you like to do?\na. Create a question\n" "b. Display questions\nc. Save questions\nd. Load questions\n" "e. Quit\nChoice: \n"; std::string s_choice(1, choice); input += s_choice + "\\n"; switch (choice) { case 'A': expected += "Please enter your question: Please enter the answer: " "Question added!\n\n"; input += "q\\na\\n"; question_list += std::to_string(question_ctr) +". q\nAnswer: a\n"; question_ctr++; break; case 'B': expected += question_list + "\n"; break; case 'C': { expected += "What filename would you like to use? File saved successfully!\n\n"; std::string filename = generate_string(5) + ".txt"; filenames.push_back(filename); input += filename+"\n"; break; } case 'D': { expected += "What file would you like to load? File loaded successfully!\n\n"; input += load_file_name+"\n"; question_list = "Question and Answer list\n1. q\nAnswer: a\n"; question_ctr = 2; break; } case 'E': expected += "Thank you for using QuizMaker!\n"; break; default: expected += "Invalid option\n\n"; } } while(choice!= 'E'); ASSERT_DURATION_LE(3, { ASSERT_EXECIO_EQ("quizgen", input, expected); }); remove(load_file_name.c_str()); for(std::string fn : filenames) { remove(fn.c_str()); } } } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.681592
92
0.566561
[ "vector" ]
ea08197d599acd8d84bfd15e85342aa1cf13d873
2,441
cpp
C++
Sail/src/Sail/graphics/postprocessing/stages/BlendStage.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
9
2019-03-18T18:35:29.000Z
2020-10-26T06:30:18.000Z
Sail/src/Sail/graphics/postprocessing/stages/BlendStage.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
11
2019-06-10T19:54:11.000Z
2020-04-14T08:50:47.000Z
Sail/src/Sail/graphics/postprocessing/stages/BlendStage.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
5
2019-06-16T20:24:50.000Z
2020-03-03T09:27:18.000Z
#include "BlendStage.h" BlendStage::BlendStage(UINT width, UINT height, Model* fullScreenQuad) : PostProcessStage(width, height, fullScreenQuad, D3D11_BIND_UNORDERED_ACCESS) { // Set up sampler m_sampler = std::make_unique<ShaderComponent::Sampler>(D3D11_TEXTURE_ADDRESS_MIRROR, D3D11_FILTER_MIN_MAG_MIP_LINEAR); // Set up constant buffer CBuffer data = { 0.5f }; m_cBuffer = std::unique_ptr<ShaderComponent::ConstantBuffer>(new ShaderComponent::ConstantBuffer(&data, sizeof(data))); // Compile and assign shaders auto vsBlob = ShaderSet::compileShader(L"postprocess/BlendShader.hlsl", "VSMain", "vs_5_0"); auto psBlob = ShaderSet::compileShader(L"postprocess/BlendShader.hlsl", "PSMain", "ps_5_0"); m_VS = std::make_unique<VertexShader>(vsBlob); m_PS = std::make_unique<PixelShader>(psBlob); Memory::safeRelease(vsBlob); Memory::safeRelease(psBlob); } BlendStage::~BlendStage() {} void BlendStage::setBlendInput(ID3D11ShaderResourceView** blendSRV, float blendFactor) { m_blendSRV = blendSRV; CBuffer data = { blendFactor }; m_cBuffer->updateData(&data, sizeof(data)); } void BlendStage::run(RenderableTexture& inputTexture) { // TODO: fix //Application* app = Application::getInstance(); //ID3D11DeviceContext* con = app->getDXManager()->getDeviceContext(); //// Bind shaders //m_VS->bind(); //m_PS->bind(); //// Bind sampler //m_sampler->bind(); //// Bind constant buffer //m_cBuffer->bind(ShaderComponent::PS); //// Set output target //OutputTexture.begin(); //// Bind the input textures to the pixel shader //con->PSSetShaderResources(0, 1, inputTexture.getColorSRV()); //con->PSSetShaderResources(1, 1, m_blendSRV); //// Bind vertex buffer //UINT stride = sizeof(PostProcessStage::Vertex); //UINT offset = 0; //con->IASetVertexBuffers(0, 1, FullscreenQuad->getVertexBuffer(), &stride, &offset); //// Bind index buffer if one exitsts //auto iBuffer = FullscreenQuad->getIndexBuffer(); //if (iBuffer) // con->IASetIndexBuffer(iBuffer, DXGI_FORMAT_R32_UINT, 0); //// Set topology //con->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); //// Draw horizontal //if (iBuffer) // con->DrawIndexed(FullscreenQuad->getNumIndices(), 0, 0); //else // con->Draw(FullscreenQuad->getNumVertices(), 0); //ID3D11ShaderResourceView* nullSRV[2] = { nullptr, nullptr }; //Application::getInstance()->getDXManager()->getDeviceContext()->PSSetShaderResources(0, 2, nullSRV); }
32.546667
120
0.732487
[ "model" ]
ea086685f58eb19197b2b95b147d432dc2562457
10,574
cc
C++
qrisp/recurrences-nbest.cc
google/qrisp
1970d13166cddcd05cb10fccdb34247c7b0dddf3
[ "Apache-2.0" ]
11
2015-12-14T07:03:31.000Z
2020-03-15T07:13:27.000Z
qrisp/recurrences-nbest.cc
google/qrisp
1970d13166cddcd05cb10fccdb34247c7b0dddf3
[ "Apache-2.0" ]
1
2016-04-01T20:40:12.000Z
2016-04-06T00:01:34.000Z
qrisp/recurrences-nbest.cc
google/qrisp
1970d13166cddcd05cb10fccdb34247c7b0dddf3
[ "Apache-2.0" ]
10
2016-02-25T08:08:09.000Z
2021-10-21T12:40:33.000Z
// Copyright 2014 Google Inc.All Rights Reserved. // // Licensed under the Apache License, // Version 2.0(the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "recurrences-nbest.h" namespace qrisp { namespace nbest { const NBestCells& DPTable::Get(const int& i, const int& j, const int& k) const { CHECK(i < d1_size && j < d2_size && k < d3_size); return data_[i + d1_size * (j + d2_size * k)]; } NBestCells& DPTable::operator()(const int& i, const int& j, const int& k) { CHECK(i < d1_size && j < d2_size && k < d3_size); return data_[i + d1_size * (j + d2_size * k)]; } DPTable::~DPTable() { for (auto& cells : data_) { for_each(cells.begin(), cells.end(), nbest::ObjectDeleter()); } } void CreateCellsFromSingleCoordinate(DPTable* tbl, const int k, const int i, const int j, const int kp, const int ip, const int jp, const double score) { NBestCells& current_cells = (*tbl)(k, i, j); if (kp == -1) { current_cells.push_back(new Cell(k, i, j, score, nullptr)); } else { // Find source cells. const NBestCells& previous_cells = tbl->Get(kp, ip, jp); // Create new cells. for (auto it = previous_cells.begin(); it != previous_cells.end(); ++it) { current_cells.push_back(new Cell(k, i, j, score + (*it)->score_, *it)); } } if (current_cells.size() > max_nbest) { sort(current_cells.begin(), current_cells.end(), CellCompWithScoreReversed); for (int i = max_nbest; i < current_cells.size(); i++) { delete current_cells[i]; } current_cells.resize(max_nbest); } } void CreateCellsFromTwoCoordinates(DPTable* tbl, const int k, const int i, const int j, const int kp, const int ip, const int jp, const int kpp, const int ipp, const int jpp, const double score) { const NBestCells& cells_a = tbl->Get(kp, ip, jp); const NBestCells& cells_b = tbl->Get(kpp, ipp, jpp); NBestCells& current_cells = (*tbl)(k, i, j); for (auto it = cells_a.begin(); it != cells_a.end(); ++it) { for (auto jt = cells_b.begin(); jt != cells_b.end(); ++jt) { current_cells.push_back( new Cell(k, i, j, (*it)->score_ + (*jt)->score_ + score, *it, *jt)); } } if (current_cells.size() > max_nbest) { sort(current_cells.begin(), current_cells.end(), CellCompWithScoreReversed); for (int i = max_nbest; i < current_cells.size(); i++) { delete current_cells[i]; } current_cells.resize(max_nbest); } } namespace sp = std::placeholders; #define BIND_SC(func_ptr) bind(GenericScorer, func_ptr, input, ph, params); void FillTable(const Structure& input, DECODING_MODE vmode, double loss_factor, const FeatureVec& params, DPTable* tbl) { // Initialize scoring functions. auto ph = std::placeholders::_1; auto Hairpin = BIND_SC(&HairpinWeights); auto HelixBasePair = BIND_SC(&HelixBasePairWeights); auto HelixChange = BIND_SC(&HelixChangeWeights); auto HelixClosing = BIND_SC(&HelixClosingWeights); auto HelixExtend = BIND_SC(&HelixExtendWeights); auto HelixStacking = BIND_SC(&HelixStackingWeights); auto MultiBase = BIND_SC(&MultiBaseWeights); auto MultiMismatch = BIND_SC(&MultiMismatchWeights); auto MultiPaired = BIND_SC(&MultiPairedWeights); auto MultiUnpaired = BIND_SC(&MultiUnpairedWeights); auto OuterBranch = BIND_SC(&OuterBranchWeights); auto OuterUnpaired = BIND_SC(&OuterUnpairedWeights); auto Single = BIND_SC(&SingleWeights); const idx_t rna_size = input.Size(); const size_t length = rna_size - 1; // Create the functor for losses based on the input structure. LossFunctor* loss_functor = new LossFunctor(input, vmode, loss_factor); // Insertion functions. auto INSERT = std::bind(CreateCellsFromSingleCoordinate, tbl, sp::_1, sp::_2, sp::_3, sp::_4, sp::_5, sp::_6, sp::_7); auto INSERT2 = std::bind(CreateCellsFromTwoCoordinates, tbl, sp::_1, sp::_2, sp::_3, sp::_4, sp::_5, sp::_6, sp::_7, sp::_8, sp::_9, sp::_10); // Some scoring functions do not need positional information. This tuple // provides neutral positional information for these cases. const Tuple ZERO = Tuple(0, 0, 0, 0); const int D = 5; score_t sum = 0.0; for (size_t m = 0; m <= length; m++) { // if (tbl->size() > 10000) { // exit(0); //} // LOG(INFO) << "Outer index: " << m; for (size_t i = 0, j = m; j <= length; i++, j++) { double pair = 0; double single = 0; std::tie(pair, single) = loss_functor->GetLossTerms(i, j); // DO_HELIX 0 if (i + 2 <= j) { sum = HelixChange(mt3(i + 1, j, 1)) + HelixClosing(mt2(i + 1, j)) + pair + HelixBasePair(mt2(i + 1, j)); INSERT(DO_HELIX, i, j, DO_HELIX + 1, i + 1, j - 1, sum); } // OUTER if (j == length) { if (i == length) { INSERT(DO_OUTER, i, j, -1, 0, 0, 0.0); } if (i < length) { sum = single + OuterUnpaired(mt1(i + 1)); INSERT(DO_OUTER, i, j, DO_OUTER, i + 1, j, sum); } for (size_t ip = i + 2; ip <= length; ip++) { sum = OuterBranch(ZERO); INSERT2(DO_OUTER, i, j, DO_HELIX, i, ip, DO_OUTER, ip, j, sum); } } // DO_MULTI if (i == j) { INSERT(DO_MULTI + 2, i, j, -1, 0, 0, 0.0); } for (int n = 0; n <= 2; n++) { if (i < j) { sum = single + MultiUnpaired(mt3(i + 1, j, i + 1)); INSERT(DO_MULTI + n, i, j, DO_MULTI + n, i + 1, j, sum); } if (i > 0 && j < length) { for (size_t jp = i + 2; jp <= j; jp++) { sum = MultiPaired(mt2(i, j)) + MultiMismatch(mt(jp, i + 1, jp + 1, i)); INSERT2(DO_MULTI + n, i, j, DO_HELIX, i, jp, DO_MULTI + min(2, n + 1), jp, j, sum); } } } // DO_LOOP if (i + 3 <= j && i > 0 && j < length) { double hairpin_loss = loss_functor->PairingLoss(i, j); INSERT(DO_LOOP, i, j, -1, 0, 0, hairpin_loss + Hairpin(mt(i, j + 1, i + 1, j))); for (int li = 0; li <= MAX_LOOP_SIZE; li++) { for (int lj = 0; li + lj <= MAX_LOOP_SIZE; lj++) { if (li + lj > 0) { int ip = i + li; int jp = j - lj; if (!(ip + 2 <= jp)) { continue; } double single_loop_loss = loss_functor->PairingLoss(i, ip) + loss_functor->PairingLoss(jp, j); sum = single_loop_loss + Single(mt(i, j, ip, jp)); INSERT(DO_LOOP, i, j, DO_HELIX, ip, jp, sum); } } } if (i + 2 <= j) { sum = MultiBase(ZERO) + MultiPaired(ZERO) + MultiMismatch(mt(i, j + 1, i + 1, j)); INSERT(DO_LOOP, i, j, DO_MULTI, i, j, sum); } } // DO_HELIX if (i > 0 && j < length) { for (int n = 1; n <= D; n++) { if (i + 2 <= j) { score_t score0 = HelixStacking(mt(i, j + 1, i + 1, j)) + pair + HelixBasePair(mt2(i + 1, j)); if (n < D) { sum = score0 + HelixChange(mt3(i + 1, j, n + 1)); INSERT(DO_HELIX + n, i, j, DO_HELIX + n + 1, i + 1, j - 1, sum); } else { sum = score0 + HelixExtend(mt2(i + 1, j)); INSERT(DO_HELIX + n, i, j, DO_HELIX + D, i + 1, j - 1, sum); } } if (n > 1) { sum = HelixClosing(mt2(j + 1, i)); INSERT(DO_HELIX + n, i, j, DO_LOOP, i, j, sum); } } } } } delete loss_functor; } score_t PerformTraceback(const int n, const DPTable& tbl, const int rna_size, vector<idx_t>* result) { result->clear(); result->resize(rna_size, 0); (*result)[0] = IDX_NOT_SET; NBestCells cells(tbl.Get(DO_OUTER, 0, rna_size - 1)); std::sort(cells.begin(), cells.end(), CellCompWithScoreReversed); if (n >= cells.size()) { return 0.0; } Cell* nth_final_cell = *(cells.begin() + n); if (nth_final_cell == nullptr) { return 0.0; } score_t score = nth_final_cell->score_; // Initialize stack by pushing n-best end cell. queue<Cell*> path; path.push(nth_final_cell); // Enter the main loop to decode the best structure. while (!path.empty()) { Cell* c = path.front(); const int v = c->state_; const int i = c->i_; const int j = c->j_; path.pop(); if (c->trace_ != nullptr) { path.push(c->trace_); } if (c->trace_snd_ != nullptr) { path.push(c->trace_snd_); } CHECK(i >= 0); CHECK(j >= 0); switch (v) { case DO_OUTER: case DO_LOOP: case DO_MULTI: case DO_MULTI1: case DO_MULTI2: break; case DO_HELIX: case DO_HELIX1: case DO_HELIX2: case DO_HELIX3: case DO_HELIX4: case DO_HELIX5: if (j - i > 3 && c->trace_->state_ != DO_LOOP) { (*result)[i + 1] = j; (*result)[j] = i + 1; } break; default: CHECK(false); }; } return score; } double DecodePaths(const int n, const Structure& rna, const FeatureVec& model, const DECODING_MODE& vmode, const double& loss_factor, vector<vector<idx_t>>* result) { const idx_t rna_size = rna.Size(); FeatureVec model_transformed = model; InitializeFeatures(&model_transformed); // Create and fill dynamic programming tables. nbest::DPTable tbl(NUM_STATES, rna_size, rna_size); FillTable(rna, vmode, loss_factor, model_transformed, &tbl); // Perform backtracking on the tables to infer the highest scoring path. for (int i = 0; i < n; i++) { vector<idx_t> res; PerformTraceback(i, tbl, rna_size, &res); result->push_back(res); } double best_path_score = 0.0; return best_path_score; } } // namespace nbest } // namespace qrisp
35.483221
80
0.559864
[ "vector", "model" ]
ea0d87cb64d7c346df499855f2cabb050bff1fef
1,560
hpp
C++
SickzilSFMLUI/includes/sub_window.hpp
0x00000FF/SickzilSFMLUI
a4c227ff8173f15742593b8d91fb1c9c575ab826
[ "MIT" ]
3
2019-08-16T05:48:40.000Z
2019-08-19T13:22:48.000Z
SickzilSFMLUI/includes/sub_window.hpp
0x00000FF/SickzilSFMLUI
a4c227ff8173f15742593b8d91fb1c9c575ab826
[ "MIT" ]
4
2019-08-17T07:15:05.000Z
2019-08-17T21:15:57.000Z
SickzilSFMLUI/includes/sub_window.hpp
0x00000FF/SickzilSFMLUI
a4c227ff8173f15742593b8d91fb1c9c575ab826
[ "MIT" ]
null
null
null
#ifndef __SUB_WINDOW_HPP__ #define __SUB_WINDOW_HPP__ #include <string> #include <vector> #include <SFML/Graphics.hpp> #include <controls.hpp> #include <draw_object.hpp> using namespace sf; struct sub_window_appearances { sf::RectangleShape window_panel; sf::RectangleShape title_bar; sf::Text title_text; sf::RectangleShape window_close_button; sf::Text window_close_x; }; class sub_window : public draw_object { public: sub_window() : sub_window("Window", {100, 100}) { } sub_window(const std::string& title); sub_window(const std::pair<int, int>& resolution); sub_window(const std::string& title, const std::pair<int, int>& res); sub_window(const sub_window& _clone) = default; sub_window(sub_window&&) = delete; void draw(RenderTarget& target, RenderStates states) const; const std::pair<int, int> get_size () const; void set_size (const std::pair<int, int>& size); const sf::Color get_border_color() const; void set_border_color(const sf::Color& color); const sf::Color get_fg_color() const; void set_fg_color(const sf::Color& color); const sf::Color get_bg_color() const; void set_bg_color(const sf::Color& color); protected: bool m_dragging = false; private: std::pair<int, int> m_position; std::vector<control> m_sub_controls; sub_window_appearances m_appearance; public: std::string title; }; #endif
25.57377
70
0.646795
[ "vector" ]
ea12668f66d458ac21ac0134274814de732fd47d
4,052
cc
C++
src/game/entities/selectable_component.cc
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
null
null
null
src/game/entities/selectable_component.cc
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
null
null
null
src/game/entities/selectable_component.cc
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
3
2017-07-17T22:24:17.000Z
2019-10-15T18:37:15.000Z
#include <boost/foreach.hpp> #include <framework/framework.h> #include <framework/graphics.h> #include <framework/shader.h> #include <framework/texture.h> #include <framework/scenegraph.h> #include <framework/vector.h> #include <game/entities/entity.h> #include <game/entities/entity_factory.h> #include <game/entities/selectable_component.h> #include <game/entities/position_component.h> #include <game/entities/ownable_component.h> #include <game/world/world.h> #include <game/world/terrain.h> namespace ent { static std::shared_ptr<fw::shader> _shader; static std::shared_ptr<fw::vertex_buffer> _vb; static std::shared_ptr<fw::index_buffer> _ib; // register the selectable component with the entity_factory ENT_COMPONENT_REGISTER("Selectable", selectable_component); selectable_component::selectable_component() : _is_selected(false), _selection_radius(2.0f), _is_highlighted(false), _ownable(nullptr) { } selectable_component::~selectable_component() { } void selectable_component::initialize() { // grab a reference to the ownable component of our entity so we can refer to it // later on. std::shared_ptr<entity> entity(_entity); _ownable = entity->get_component<ownable_component>(); } // this is called when we start up, and also when our device is reset. we need to populate // the vertex buffer and index buffer void selectable_component::populate_buffers() { std::shared_ptr<fw::vertex_buffer> vb = fw::vertex_buffer::create<fw::vertex::xyz_uv>(); fw::vertex::xyz_uv vertices[4] = { fw::vertex::xyz_uv(-1.0f, 0.0f, -1.0f, 0.0f, 0.0f), fw::vertex::xyz_uv(-1.0f, 0.0f, 1.0f, 0.0f, 1.0f), fw::vertex::xyz_uv(1.0f, 0.0f, 1.0f, 1.0f, 1.0f), fw::vertex::xyz_uv(1.0f, 0.0f, -1.0f, 1.0f, 0.0f) }; vb->set_data(4, vertices); _vb = vb; std::shared_ptr<fw::index_buffer> ib(new fw::index_buffer()); uint16_t indices[6] = { 0, 1, 2, 0, 2, 3 }; ib->set_data(6, indices); _ib = ib; if (!_shader) { _shader = fw::shader::create("selection.shader"); } } void selectable_component::set_is_selected(bool selected) { _is_selected = selected; sig_selected(selected); } void selectable_component::apply_template(luabind::object const &tmpl) { for (luabind::iterator it(tmpl), end; it != end; ++it) { if (it.key() == "SelectionRadius") { set_selection_radius(luabind::object_cast<float>(*it)); } } } void selectable_component::set_selection_radius(float value) { _selection_radius = value; } void selectable_component::highlight(fw::colour const &col) { _is_highlighted = true; _highlight_colour = col; } void selectable_component::unhighlight() { _is_highlighted = false; } void selectable_component::render(fw::sg::scenegraph &scenegraph, fw::matrix const &transform) { if (!_vb) { populate_buffers(); } bool draw = false; fw::colour col(1, 1, 1); if (_is_selected) { draw = true; col = fw::colour(1, 1, 1); } else if (_is_highlighted) { draw = true; col = _highlight_colour; } if (!draw) return; std::shared_ptr<entity> entity(_entity); position_component *pos = entity->get_component<position_component>(); if (pos != 0) { std::shared_ptr<fw::shader_parameters> shader_params = _shader->create_parameters(); shader_params->set_colour("selection_colour", col); fw::matrix m = pos->get_transform() * transform; m *= fw::translation(fw::vector(0.0f, 0.2f, 0.0f)); // lift it off the ground a bit m = fw::scale(_selection_radius) * m; // scale it to the size of our selection radius std::shared_ptr<fw::sg::node> node(new fw::sg::node()); node->set_vertex_buffer(_vb); node->set_index_buffer(_ib); node->set_shader(_shader); node->set_shader_parameters(shader_params); node->set_world_matrix(m); node->set_primitive_type(fw::sg::primitive_trianglelist); node->set_cast_shadows(false); scenegraph.add_node(node); } } }
31.410853
97
0.678924
[ "render", "object", "vector", "transform" ]
ea1a2c7c5c29d371c921b024577bd242c91bdd6f
779
cpp
C++
Interviewbit/Hashing/PointsOnTheStraightLine.cpp
sawantaditi24/Competitive-Programming
36e024215d8041c92c5ec78a22561aaa0025f8d2
[ "MIT" ]
2
2019-08-27T21:48:55.000Z
2020-04-20T05:56:56.000Z
Interviewbit/Hashing/PointsOnTheStraightLine.cpp
sawantaditi24/Competitive-Programming
36e024215d8041c92c5ec78a22561aaa0025f8d2
[ "MIT" ]
null
null
null
Interviewbit/Hashing/PointsOnTheStraightLine.cpp
sawantaditi24/Competitive-Programming
36e024215d8041c92c5ec78a22561aaa0025f8d2
[ "MIT" ]
2
2020-10-21T17:12:05.000Z
2020-10-27T09:34:57.000Z
int Solution::maxPoints(vector<int> &X, vector<int> &Y) { vector<vector<int>> points; for (int i = 0; i < X.size(); i++) { points.push_back({X[i], Y[i]}); } if (points.size() <= 2) return points.size(); int res = 2; for (int i = 1; i < points.size(); i++) { int x0 = points[i - 1][0]; int y0 = points[i - 1][1]; int x1 = points[i][0]; int y1 = points[i][1]; int cnt = 0; if (x0 == x1 && y0 == y1) { for (int j = 0; j < points.size(); j++) { if (points[j][0] == x1 && points[j][1] == y1) cnt++; } } else { for (int j = 0; j < points.size(); j++) { int x2 = points[j][0]; int y2 = points[j][1]; if ((long long)(y2 - y1) * (x1 - x0) == (long long)(x2 - x1) * (y1 - y0)) cnt++; } } res = max(res, cnt); } return res; }
24.34375
84
0.481386
[ "vector" ]
ea1de258c82589d6ebcc55553629e23e1ec2286b
1,302
hpp
C++
src/instrumentation/instrument_array.hpp
SlaybaughLab/Transport
8eb32cb8ae50c92875526a7540350ef9a85bc050
[ "MIT" ]
12
2018-03-14T12:30:53.000Z
2022-01-23T14:46:44.000Z
src/instrumentation/instrument_array.hpp
jsrehak/BART
0460dfffbcf5671a730448de7f45cce39fd4a485
[ "MIT" ]
194
2017-07-07T01:38:15.000Z
2021-05-19T18:21:19.000Z
src/instrumentation/instrument_array.hpp
jsrehak/BART
0460dfffbcf5671a730448de7f45cce39fd4a485
[ "MIT" ]
10
2017-07-06T22:58:59.000Z
2021-03-15T07:01:21.000Z
#ifndef BART_SRC_INSTRUMENTATION_INSTRUMENT_ARRAY_HPP_ #define BART_SRC_INSTRUMENTATION_INSTRUMENT_ARRAY_HPP_ #include <memory> #include <vector> #include "instrumentation/instrument_i.h" #include "utility/uncopyable.h" namespace bart::instrumentation { /*! \brief An instrument that can hold multiple other instruments to call. * * Derives from the base instrument, so it can be used anywhere that a normal * instrument may be called. This is best used for reading out to multiple * outstreams or performing different conversions on the same data. * * @tparam InputType type of data to be read. */ template <typename InputType> class InstrumentArray : public InstrumentI<InputType>, public utility::Uncopyable { public: using InstrumentType = InstrumentI<InputType>; InstrumentArray& AddInstrument(std::unique_ptr<InstrumentType>); void Read(const InputType &input) override; constexpr auto begin() noexcept { return instruments_.begin(); } constexpr auto end() noexcept { return instruments_.end(); } constexpr std::size_t size() const noexcept { return instruments_.size(); } private: std::vector<std::unique_ptr<InstrumentType>> instruments_{}; }; } // namespace bart::instrumentation #endif //BART_SRC_INSTRUMENTATION_INSTRUMENT_ARRAY_HPP_
31.756098
77
0.764977
[ "vector" ]
ea27a59800716635175da1959980a24cfb294e88
1,802
cpp
C++
test/unit_tests/math/test_geometry/test_line2d_par.cpp
Danpihl/arl
9c71ddd93523ffb72cad597ce09f986d638ea828
[ "MIT" ]
null
null
null
test/unit_tests/math/test_geometry/test_line2d_par.cpp
Danpihl/arl
9c71ddd93523ffb72cad597ce09f986d638ea828
[ "MIT" ]
null
null
null
test/unit_tests/math/test_geometry/test_line2d_par.cpp
Danpihl/arl
9c71ddd93523ffb72cad597ce09f986d638ea828
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <cmath> #include <iostream> #include <string> #include <vector> #include "arl/math.h" #include "test/unit_tests/math/math_test_utils.h" namespace arl { namespace { class ParametricLine2DTest : public testing::Test { protected: std::vector<double> px_vec; std::vector<double> py_vec; std::vector<double> vx_vec; std::vector<double> vy_vec; std::vector<double> t_vec; const double test_a[8] = {0.2342, -1.381, -0.982, 2.523, 0.2342, -1.381, -0.982, 2.523}; const double test_b[8] = {1.231, -0.903, 2.412, -0.124, 1.231, -0.903, 2.412, -0.124}; const double test_c[8] = {0.251, 0.912, 3.212, 0.553, -0.251, -0.912, -3.212, -0.553}; const double x_vec[10] = { -2.124, -1.141, -0.101, 0.0, 0.141, 1.624, 1.971, 2.012, 3.512, 9.124}; const double y_vec[10] = { -1.224, -1.113, -0.112, 0.0, 0.122, 1.723, 1.992, 2.113, 4.612, 10.324}; void SetUp() override { const size_t num_iterations = 10; px_vec.clear(); py_vec.clear(); vx_vec.clear(); vy_vec.clear(); t_vec.clear(); double phi = 0.0; for (size_t k = 0; k < num_iterations; k++) { phi = 2.0 * M_PI * static_cast<double>(k) / static_cast<double>(num_iterations - 1) - DEG2RAD(2.0); px_vec.push_back(std::cos(static_cast<double>(k))); py_vec.push_back(std::sin(static_cast<double>(k))); t_vec.push_back(std::sin(3.0 * static_cast<double>(k))); vx_vec.push_back(std::cos(phi)); vy_vec.push_back(std::sin(phi)); } } void TearDown() override {} }; TEST_F(ParametricLine2DTest, Initialization) { std::cout << "Hello" << std::endl; } } // namespace } // namespace arl
27.30303
97
0.576027
[ "vector" ]
ea321a8f33d53df299aa903fc135d702de159e24
17,775
cc
C++
tensorpipe/transport/shm/connection.cc
osalpekar/tensorpipe
bff4c20ebd6e64b084307015660c14d005cd7da3
[ "BSD-3-Clause" ]
null
null
null
tensorpipe/transport/shm/connection.cc
osalpekar/tensorpipe
bff4c20ebd6e64b084307015660c14d005cd7da3
[ "BSD-3-Clause" ]
null
null
null
tensorpipe/transport/shm/connection.cc
osalpekar/tensorpipe
bff4c20ebd6e64b084307015660c14d005cd7da3
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <tensorpipe/transport/shm/connection.h> #include <string.h> #include <vector> #include <tensorpipe/common/callback.h> #include <tensorpipe/common/defs.h> #include <tensorpipe/common/error_macros.h> #include <tensorpipe/transport/error.h> #include <tensorpipe/util/ringbuffer/protobuf_streams.h> namespace tensorpipe { namespace transport { namespace shm { std::shared_ptr<Connection> Connection::create( std::shared_ptr<Loop> loop, std::shared_ptr<Socket> socket) { auto conn = std::make_shared<Connection>( ConstructorToken(), std::move(loop), std::move(socket)); conn->start(); return conn; } Connection::Connection( ConstructorToken /* unused */, std::shared_ptr<Loop> loop, std::shared_ptr<Socket> socket) : loop_(std::move(loop)), reactor_(loop_->reactor()), socket_(std::move(socket)) { // Ensure underlying control socket is non-blocking such that it // works well with event driven I/O. socket_->block(false); } Connection::~Connection() { close(); } void Connection::start() { // Create ringbuffer for inbox. std::shared_ptr<util::ringbuffer::RingBuffer> inboxRingBuffer; std::tie(inboxHeaderFd_, inboxDataFd_, inboxRingBuffer) = util::ringbuffer::shm::create(kDefaultSize); inbox_.emplace(std::move(inboxRingBuffer)); // Register method to be called when our peer writes to our inbox. inboxReactorToken_ = reactor_->add( runIfAlive(*this, std::function<void(Connection&)>([](Connection& conn) { conn.handleInboxReadableFromReactor(); }))); // Register method to be called when our peer reads from our outbox. outboxReactorToken_ = reactor_->add( runIfAlive(*this, std::function<void(Connection&)>([](Connection& conn) { conn.handleOutboxWritableFromReactor(); }))); // We're sending file descriptors first, so wait for writability. state_ = SEND_FDS; loop_->registerDescriptor(socket_->fd(), EPOLLOUT, shared_from_this()); } // Implementation of transport::Connection. void Connection::read(read_callback_fn fn) { std::unique_lock<std::mutex> guard(mutex_); readOperations_.emplace_back(std::move(fn)); // If there are pending read operations, make sure the event loop // processes them, now that we have an additional callback. triggerProcessReadOperations(); } // Implementation of transport::Connection. void Connection::read( google::protobuf::MessageLite& message, read_proto_callback_fn fn) { std::unique_lock<std::mutex> guard(mutex_); readOperations_.emplace_back( [&message](util::ringbuffer::Consumer& inbox) -> ssize_t { uint32_t len; { const auto ret = inbox.copyInTx(sizeof(len), &len); if (ret == -ENODATA) { return -ENODATA; } TP_THROW_SYSTEM_IF(ret < 0, -ret); } if (len + sizeof(uint32_t) > kDefaultSize) { return -EPERM; } util::ringbuffer::ZeroCopyInputStream is(&inbox, len); if (!message.ParseFromZeroCopyStream(&is)) { return -ENODATA; } TP_DCHECK_EQ(len, is.ByteCount()); return is.ByteCount(); }, [fn{std::move(fn)}]( const Error& error, const void* /* unused */, size_t /* unused */) { fn(error); }); // If there are pending read operations, make sure the event loop // processes them, now that we have an additional callback. triggerProcessReadOperations(); } // Implementation of transport::Connection. void Connection::read(void* ptr, size_t length, read_callback_fn fn) { std::unique_lock<std::mutex> guard(mutex_); readOperations_.emplace_back(ptr, length, std::move(fn)); // If there are pending read operations, make sure the event loop // processes them, now that we have an additional callback. triggerProcessReadOperations(); } // Implementation of transport::Connection void Connection::write(const void* ptr, size_t length, write_callback_fn fn) { std::unique_lock<std::mutex> guard(mutex_); writeOperations_.emplace_back(ptr, length, std::move(fn)); triggerProcessWriteOperations(); } // Implementation of transport::Connection void Connection::write( const google::protobuf::MessageLite& message, write_callback_fn fn) { std::unique_lock<std::mutex> guard(mutex_); writeOperations_.emplace_back( [&message](util::ringbuffer::Producer& outbox) -> ssize_t { size_t len = message.ByteSize(); if (len + sizeof(uint32_t) > kDefaultSize) { return -EPERM; } const auto ret = outbox.writeInTx<uint32_t>(len); if (ret < 0) { return ret; } util::ringbuffer::ZeroCopyOutputStream os(&outbox, len); if (!message.SerializeToZeroCopyStream(&os)) { return -ENOSPC; } TP_DCHECK_EQ(len, os.ByteCount()); return os.ByteCount(); }, std::move(fn)); triggerProcessWriteOperations(); } void Connection::handleEventsFromReactor(int events) { TP_DCHECK(loop_->inReactorThread()); std::unique_lock<std::mutex> lock(mutex_); // Handle only one of the events in the mask. Events on the control // file descriptor are rare enough for the cost of having epoll call // into this function multiple times to not matter. The benefit is // that we never have to acquire the lock more than once and that // every handler can close and unregister the control file // descriptor from the event loop, without worrying about the next // handler trying to do so as well. if (events & EPOLLIN) { handleEventInFromReactor(std::move(lock)); return; } if (events & EPOLLOUT) { handleEventOutFromReactor(std::move(lock)); return; } if (events & EPOLLERR) { handleEventErrFromReactor(std::move(lock)); return; } if (events & EPOLLHUP) { handleEventHupFromReactor(std::move(lock)); return; } } void Connection::handleEventInFromReactor(std::unique_lock<std::mutex> lock) { TP_DCHECK(loop_->inReactorThread()); if (state_ == RECV_FDS) { Fd reactorHeaderFd; Fd reactorDataFd; Fd outboxHeaderFd; Fd outboxDataFd; Reactor::TToken peerInboxReactorToken; Reactor::TToken peerOutboxReactorToken; // Receive the reactor token, reactor fds, and inbox fds. auto err = socket_->recvPayloadAndFds( peerInboxReactorToken, peerOutboxReactorToken, reactorHeaderFd, reactorDataFd, outboxHeaderFd, outboxDataFd); if (err) { failHoldingMutexFromReactor(std::move(err), lock); return; } // Load ringbuffer for outbox. outbox_.emplace(util::ringbuffer::shm::load( outboxHeaderFd.release(), outboxDataFd.release())); // Initialize remote reactor trigger. peerReactorTrigger_.emplace( std::move(reactorHeaderFd), std::move(reactorDataFd)); peerInboxReactorToken_ = peerInboxReactorToken; peerOutboxReactorToken_ = peerOutboxReactorToken; // The connection is usable now. state_ = ESTABLISHED; processWriteOperationsFromReactor(lock); // Trigger read operations in case a pair of local read() and remote // write() happened before connection is established. Otherwise read() // callback would lose if it's the only read() request. processReadOperationsFromReactor(lock); return; } if (state_ == ESTABLISHED) { // We don't expect to read anything on this socket once the // connection has been established. If we do, assume it's a // zero-byte read indicating EOF. setErrorHoldingMutexFromReactor(TP_CREATE_ERROR(EOFError)); closeHoldingMutex(); processReadOperationsFromReactor(lock); return; } TP_LOG_WARNING() << "handleEventIn not handled"; } void Connection::handleEventOutFromReactor(std::unique_lock<std::mutex> lock) { TP_DCHECK(loop_->inReactorThread()); if (state_ == SEND_FDS) { int reactorHeaderFd; int reactorDataFd; std::tie(reactorHeaderFd, reactorDataFd) = reactor_->fds(); // Send our reactor token, reactor fds, and inbox fds. auto err = socket_->sendPayloadAndFds( inboxReactorToken_.value(), outboxReactorToken_.value(), reactorHeaderFd, reactorDataFd, inboxHeaderFd_, inboxDataFd_); if (err) { failHoldingMutexFromReactor(std::move(err), lock); return; } // Sent our fds. Wait for fds from peer. state_ = RECV_FDS; loop_->registerDescriptor(socket_->fd(), EPOLLIN, shared_from_this()); return; } TP_LOG_WARNING() << "handleEventOut not handled"; } void Connection::handleEventErrFromReactor(std::unique_lock<std::mutex> lock) { TP_DCHECK(loop_->inReactorThread()); setErrorHoldingMutexFromReactor(TP_CREATE_ERROR(EOFError)); closeHoldingMutex(); processReadOperationsFromReactor(lock); } void Connection::handleEventHupFromReactor(std::unique_lock<std::mutex> lock) { TP_DCHECK(loop_->inReactorThread()); setErrorHoldingMutexFromReactor(TP_CREATE_ERROR(EOFError)); closeHoldingMutex(); processReadOperationsFromReactor(lock); } void Connection::handleInboxReadableFromReactor() { TP_DCHECK(loop_->inReactorThread()); std::unique_lock<std::mutex> lock(mutex_); processReadOperationsFromReactor(lock); } void Connection::handleOutboxWritableFromReactor() { TP_DCHECK(loop_->inReactorThread()); std::unique_lock<std::mutex> lock(mutex_); processWriteOperationsFromReactor(lock); } void Connection::triggerProcessReadOperations() { loop_->deferToReactor([ptr{shared_from_this()}, this] { std::unique_lock<std::mutex> lock(mutex_); processReadOperationsFromReactor(lock); }); } void Connection::processReadOperationsFromReactor( std::unique_lock<std::mutex>& lock) { TP_DCHECK(loop_->inReactorThread()); TP_DCHECK(lock.owns_lock()); if (error_) { std::deque<ReadOperation> operationsToError; std::swap(operationsToError, readOperations_); lock.unlock(); for (auto& readOperation : operationsToError) { readOperation.handleError(error_); } lock.lock(); return; } // Process all read read operations that we can immediately serve, only // when connection is established. if (state_ != ESTABLISHED) { return; } // Serve read operations while (!readOperations_.empty()) { auto readOperation = std::move(readOperations_.front()); readOperations_.pop_front(); lock.unlock(); if (readOperation.handleRead(*inbox_)) { peerReactorTrigger_->run(peerOutboxReactorToken_.value()); } lock.lock(); if (!readOperation.completed()) { readOperations_.push_front(std::move(readOperation)); break; } } TP_DCHECK(lock.owns_lock()); } void Connection::triggerProcessWriteOperations() { loop_->deferToReactor([ptr{shared_from_this()}, this] { std::unique_lock<std::mutex> lock(mutex_); processWriteOperationsFromReactor(lock); }); } void Connection::processWriteOperationsFromReactor( std::unique_lock<std::mutex>& lock) { TP_DCHECK(loop_->inReactorThread()); TP_DCHECK(lock.owns_lock()); if (state_ < ESTABLISHED) { return; } if (error_) { std::deque<WriteOperation> operationsToError; std::swap(operationsToError, writeOperations_); lock.unlock(); for (auto& writeOperation : operationsToError) { writeOperation.handleError(error_); } lock.lock(); return; } while (!writeOperations_.empty()) { auto writeOperation = std::move(writeOperations_.front()); writeOperations_.pop_front(); lock.unlock(); if (writeOperation.handleWrite(*outbox_)) { peerReactorTrigger_->run(peerInboxReactorToken_.value()); } lock.lock(); if (!writeOperation.completed()) { writeOperations_.push_front(writeOperation); break; } } TP_DCHECK(lock.owns_lock()); } void Connection::setErrorHoldingMutexFromReactor(Error&& error) { TP_DCHECK(loop_->inReactorThread()); error_ = error; } void Connection::failHoldingMutexFromReactor( Error&& error, std::unique_lock<std::mutex>& lock) { TP_DCHECK(loop_->inReactorThread()); setErrorHoldingMutexFromReactor(std::move(error)); while (!readOperations_.empty()) { auto& readOperation = readOperations_.front(); lock.unlock(); readOperation.handleError(error_); lock.lock(); readOperations_.pop_front(); } while (!writeOperations_.empty()) { auto& writeOperation = writeOperations_.front(); lock.unlock(); writeOperation.handleError(error_); lock.lock(); writeOperations_.pop_front(); } } void Connection::close() { // To avoid races, the close operation should also be queued and deferred to // the reactor. However, since close can be called from the destructor, we // can't extend its lifetime by capturing a shared_ptr and increasing its // refcount. std::unique_lock<std::mutex> guard(mutex_); closeHoldingMutex(); } void Connection::closeHoldingMutex() { if (inboxReactorToken_.has_value()) { reactor_->remove(inboxReactorToken_.value()); inboxReactorToken_.reset(); } if (outboxReactorToken_.has_value()) { reactor_->remove(outboxReactorToken_.value()); outboxReactorToken_.reset(); } if (socket_) { loop_->unregisterDescriptor(socket_->fd()); socket_.reset(); } } Connection::ReadOperation::ReadOperation( void* ptr, size_t len, read_callback_fn fn) : ptr_(ptr), len_(len), fn_(std::move(fn)), ptrProvided_(true) {} Connection::ReadOperation::ReadOperation(read_fn reader, read_callback_fn fn) : reader_(std::move(reader)), fn_(std::move(fn)), ptrProvided_(false) {} Connection::ReadOperation::ReadOperation(read_callback_fn fn) : fn_(std::move(fn)), ptrProvided_(false) {} bool Connection::ReadOperation::handleRead(util::ringbuffer::Consumer& inbox) { // Start read transaction. // Retry because this must succeed. for (;;) { const auto ret = inbox.startTx(); TP_DCHECK(ret >= 0 || ret == -EAGAIN); if (ret < 0) { continue; } break; } bool lengthRead = false; if (reader_) { auto ret = reader_(inbox); if (ret == -ENODATA) { ret = inbox.cancelTx(); TP_THROW_SYSTEM_IF(ret < 0, -ret); return false; } TP_THROW_SYSTEM_IF(ret < 0, -ret); mode_ = READ_PAYLOAD; bytesRead_ = len_ = ret; } else { if (mode_ == READ_LENGTH) { uint32_t length; { ssize_t ret; ret = inbox.copyInTx(sizeof(length), &length); if (ret == -ENODATA) { ret = inbox.cancelTx(); TP_THROW_SYSTEM_IF(ret < 0, -ret); return false; } TP_THROW_SYSTEM_IF(ret < 0, -ret); } if (ptrProvided_) { TP_DCHECK_EQ(length, len_); } else { len_ = length; buf_ = std::make_unique<uint8_t[]>(len_); ptr_ = buf_.get(); } mode_ = READ_PAYLOAD; lengthRead = true; } // If reading empty buffer, skip payload read. if (len_ > 0) { const auto ret = inbox.copyAtMostInTx( len_ - bytesRead_, reinterpret_cast<uint8_t*>(ptr_) + bytesRead_); if (ret == -ENODATA) { if (lengthRead) { const auto ret = inbox.commitTx(); TP_THROW_SYSTEM_IF(ret < 0, -ret); return true; } else { const auto ret = inbox.cancelTx(); TP_THROW_SYSTEM_IF(ret < 0, -ret); return false; } } TP_THROW_SYSTEM_IF(ret < 0, -ret); bytesRead_ += ret; } } { const auto ret = inbox.commitTx(); TP_THROW_SYSTEM_IF(ret < 0, -ret); } if (completed()) { fn_(Error::kSuccess, ptr_, len_); } return true; } void Connection::ReadOperation::handleError(const Error& error) { fn_(error, nullptr, 0); } Connection::WriteOperation::WriteOperation( const void* ptr, size_t len, write_callback_fn fn) : ptr_(ptr), len_(len), fn_(std::move(fn)) {} Connection::WriteOperation::WriteOperation( write_fn writer, write_callback_fn fn) : writer_(std::move(writer)), fn_(std::move(fn)) {} bool Connection::WriteOperation::handleWrite( util::ringbuffer::Producer& outbox) { // Start write transaction. // Retry because this must succeed. // TODO: fallback if it doesn't. for (;;) { const auto ret = outbox.startTx(); TP_DCHECK(ret >= 0 || ret == -EAGAIN); if (ret < 0) { continue; } break; } ssize_t ret; if (writer_) { ret = writer_(outbox); if (ret > 0) { mode_ = WRITE_PAYLOAD; bytesWritten_ = len_ = ret; } } else { if (mode_ == WRITE_LENGTH) { ret = outbox.writeInTx<uint32_t>(len_); if (ret > 0) { mode_ = WRITE_PAYLOAD; } } // If writing empty buffer, skip payload write because ptr_ // could be nullptr. if (mode_ == WRITE_PAYLOAD && len_ > 0) { ret = outbox.writeAtMostInTx( len_ - bytesWritten_, static_cast<const uint8_t*>(ptr_) + bytesWritten_); if (ret > 0) { bytesWritten_ += ret; } } } if (ret == -ENOSPC) { const auto ret = outbox.cancelTx(); TP_THROW_SYSTEM_IF(ret < 0, -ret); return false; } TP_THROW_SYSTEM_IF(ret < 0, -ret); { const auto ret = outbox.commitTx(); TP_THROW_SYSTEM_IF(ret < 0, -ret); } if (completed()) { fn_(Error::kSuccess); } return true; } void Connection::WriteOperation::handleError(const Error& error) { fn_(error); } } // namespace shm } // namespace transport } // namespace tensorpipe
28.44
79
0.667173
[ "vector" ]
ea3500e90af963726b25fbff8c67ed1d5151e82a
3,006
cc
C++
addon/thread_safe_callback.cc
deatough/electron-fhl
d6ffb6f488b208b4d490b87eff9a7fde10f999a0
[ "CC0-1.0" ]
null
null
null
addon/thread_safe_callback.cc
deatough/electron-fhl
d6ffb6f488b208b4d490b87eff9a7fde10f999a0
[ "CC0-1.0" ]
null
null
null
addon/thread_safe_callback.cc
deatough/electron-fhl
d6ffb6f488b208b4d490b87eff9a7fde10f999a0
[ "CC0-1.0" ]
null
null
null
#include "thread_safe_callback.h" #include "napi_utils.h" /** * Called when the the ThreadSafeFunction has been finalized */ __declspec(noinline) /*static*/ void ThreadSafeCallback::NApiFinalizeCallback(napi_env /*env*/, void* finalize_data, void* /*finalize_hint*/) { ThreadSafeCallback* spThis = reinterpret_cast<ThreadSafeCallback*>(finalize_data); std::lock_guard<std::mutex> lockForUpdate(spThis->lockObject); spThis->function = nullptr; } /** * Called to initialize the thread safe function, when invoked the napi_threadsafe_function_call_js * will be called to marshal the arguments for the JavaScript call. */ __declspec(noinline) bool ThreadSafeCallback::InitializeThreadSafeFunction(napi_env env, const char* javaScriptFunction, napi_threadsafe_function_call_js call_js_cb) { std::lock_guard<std::mutex> lockForUpdate(lockObject); if (function != nullptr) { // the thread safe function has already been initialized return true; } // The JavaScript function will be loacated on the global object, so we need to first // get the global object. napi_value global; if (!CheckNApiCallResult(env, napi_get_global(env, &global))) { return false; } // Then get the function via the name property and confirm that it is in fact a function napi_value functionToCall; if (!CheckNApiCallResult(env, napi_get_named_property(env, global, javaScriptFunction, &functionToCall))) { return false; } napi_valuetype functionType; if (!CheckNApiCallResult(env, napi_typeof(env, functionToCall, &functionType))) { return false; } if (functionType != napi_valuetype::napi_function) { return false; } // In order to create a thread safe function we need to supply an async resouce name, if // we don't we will get an invalid argument result when creating the thread safe function. napi_value asyncResourceName; if (!CheckNApiCallResult(env, napi_create_string_utf8(env, javaScriptFunction, NAPI_AUTO_LENGTH, &asyncResourceName))) { return false; } napi_value noAsycnResource = nullptr; size_t unlimitedQueueSize = 0; size_t initialThreadCount = 1; void* finalizeData = this; void* noContext = nullptr; return CheckNApiCallResult(env, napi_create_threadsafe_function(env, functionToCall, noAsycnResource, asyncResourceName, unlimitedQueueSize, initialThreadCount, finalizeData, NApiFinalizeCallback, noContext, call_js_cb, &function)); } /** * Calls the thread safe function, returns false if unable to call the function */ __declspec(noinline) bool ThreadSafeCallback::CallThreadSafeFunction(void* data) { std::lock_guard<std::mutex> lockForUpdate(lockObject); if (function == nullptr) { return false; } napi_status status = napi_call_threadsafe_function(function, data, napi_threadsafe_function_call_mode::napi_tsfn_blocking); return (status == napi_ok); }
35.364706
165
0.729874
[ "object" ]
ea3563bc10a91485bc1e5fe2df5021f2ab4928f5
2,474
cpp
C++
Source/WTF/wtf/DebugHeap.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
wtf/DebugHeap.cpp
apple-opensource/WTF
08551665a4d9763afa5a3c78f35fc4583f1f4d16
[ "MIT" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
wtf/DebugHeap.cpp
apple-opensource/WTF
08551665a4d9763afa5a3c78f35fc4583f1f4d16
[ "MIT" ]
null
null
null
/* * Copyright (C) 2020 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <wtf/DebugHeap.h> #if ENABLE(MALLOC_HEAP_BREAKDOWN) #include <cstdlib> #include <thread> namespace WTF { DebugHeap::DebugHeap(const char* heapName) : m_zone(malloc_create_zone(0, 0)) { malloc_set_zone_name(m_zone, heapName); } void* DebugHeap::malloc(size_t size) { void* result = malloc_zone_malloc(m_zone, size); if (!result) CRASH(); return result; } void* DebugHeap::calloc(size_t numElements, size_t elementSize) { void* result = malloc_zone_calloc(m_zone, numElements, elementSize); if (!result) CRASH(); return result; } void* DebugHeap::memalign(size_t alignment, size_t size, bool crashOnFailure) { void* result = malloc_zone_memalign(m_zone, alignment, size); if (!result && crashOnFailure) CRASH(); return result; } void* DebugHeap::realloc(void* object, size_t size) { void* result = malloc_zone_realloc(m_zone, object, size); if (!result) CRASH(); return result; } void DebugHeap::free(void* object) { malloc_zone_free(m_zone, object); } } // namespace WTF #endif // ENABLE(MALLOC_HEAP_BREAKDOWN)
30.170732
77
0.727162
[ "object" ]
ea393c983581cd8eb8430bab2e7a25d7d5d91439
7,740
cpp
C++
a1003/main.cpp
Ji-Yuhang/pat_cpp
100525878db4119eaa4be25ef192af9a3b9543bd
[ "MIT" ]
null
null
null
a1003/main.cpp
Ji-Yuhang/pat_cpp
100525878db4119eaa4be25ef192af9a3b9543bd
[ "MIT" ]
null
null
null
a1003/main.cpp
Ji-Yuhang/pat_cpp
100525878db4119eaa4be25ef192af9a3b9543bd
[ "MIT" ]
null
null
null
#include <iostream> #include <set> #include <map> #include <vector> #include <algorithm> using namespace std; // 1003 Emergency (25) map<int, int> find_near_citys(const map<pair<int, int>, int>& citys, int city_id) { map<int, int> near_citys; map<pair<int, int>, int>::const_iterator it = citys.begin(); for( ; it != citys.end(); it++){ int city_a = it->first.first; int city_b = it->first.second; int length = it->second; int other_city_id = 0; if (city_a == city_id || city_b == city_id) { if (city_a == city_id){ other_city_id = city_b; } if (city_b == city_id){ other_city_id = city_a; } near_citys.insert(make_pair(other_city_id, length)); } } //near_citys.insert(make_pair(near_city_id, length)); return near_citys; } void save_city_path(vector<vector<int> >& paths,int tail_city_id, int city_id) { if (paths.empty()) { vector<int> new_path; new_path.push_back(tail_city_id); paths.push_back(new_path); } vector<vector<int> >::iterator it = paths.begin(); for( ;it != paths.end(); it++){ if ( !it->empty() && it->back() == tail_city_id && find( it->begin(), it->end(), city_id) == it->end()){ vector<int> new_path = *it; new_path.push_back(city_id); paths.push_back(new_path); // for (int i = 0; i < new_path.size(); ++i){ // cout << new_path.at(i) << " "; // } // cout << endl; } } } vector<vector<int> > find_paths_with_tail(const vector<vector<int> >& paths, int tail_city_id, int city_id) { vector<vector<int> > result; vector<vector<int> >::const_iterator it = paths.begin(); for(; it != paths.end(); it++){ if ( !it->empty() && it->back() == tail_city_id && find( it->begin(), it->end(), city_id) == it->end()) { result.push_back(*it); } } return result; } void build_roads(const map<pair<int, int>, int>& citys, int tail_city_id, int target_city_id, vector<vector<int> >& paths) { // cout << "build_roads( tail_city_id:"<< tail_city_id<<" target_city_id:"<< target_city_id<< " paths.size:"<< paths.size()<< endl; //map<vector<int>, int> roads_with_length; // int current_city_id = 0; map<int, int> near_citys = find_near_citys(citys, tail_city_id); map<int, int>::iterator it = near_citys.begin(); for( ; it != near_citys.end(); it++){ int city_id = it->first; int length = it->second; // save_city_path(paths, tail_city_id, city_id); { if (paths.empty()) { vector<int> new_path; new_path.push_back(tail_city_id); paths.push_back(new_path); } if (false){ vector<vector<int> > possible_paths = paths; int index = 0; vector<vector<int> >::iterator it = possible_paths.begin(); for( ;it != possible_paths.end(); it++){ //if ( !it->empty() && it->back() == tail_city_id && find( it->begin(), it->end(), city_id) == it->end()){ vector<int> new_path = *it; new_path.push_back(city_id); // vector<vector<int> >::iterator erase_it = find( paths.begin(), paths.end(), *it); // if (erase_it != paths.end()){ // paths.erase(erase_it); // } paths.push_back(new_path); if (city_id != target_city_id){ build_roads(citys, city_id, target_city_id, paths); } //} index++; } } else { vector<vector<int> > need_copy_paths = find_paths_with_tail(paths, tail_city_id, city_id); vector<vector<int> >::iterator it = need_copy_paths.begin(); for( ;it != need_copy_paths.end(); it++){ if ( !it->empty() && it->back() == tail_city_id && find( it->begin(), it->end(), city_id) == it->end()){ vector<int> new_path = *it; new_path.push_back(city_id); paths.push_back(new_path); if (city_id != target_city_id){ build_roads(citys, city_id, target_city_id, paths); } } } } } } } int main_old() { // 5 6 0 2 // 1 2 1 5 3 // 0 1 1 // 0 2 2 // 0 3 1 // 1 2 1 // 2 4 1 // 3 4 1 // 2 4 int city_count = 0; int road_count = 0; int current_city_id = 0; int target_city_id = 0; cin >> city_count >> road_count >> current_city_id >> target_city_id; map<int, int> teams; for(int i = 0; i < city_count; ++i){ int city_id = i; int city_team_member_count = 0; cin >> city_team_member_count; teams[city_id] = city_team_member_count; } // <int, map<int, int> > // <city_a, map<city_b, length> > //map<int, map<int, int> > citys; map<pair<int, int>, int> citys; for(int i = 0; i < road_count; ++i){ int city_a = 0; int city_b = 0; int length_between_city_a_b = 0; cin >> city_a >> city_b >> length_between_city_a_b; pair<int, int> city_pair = make_pair(city_a, city_b); citys.insert(make_pair(city_pair, length_between_city_a_b)); pair<int, int> same_pair = make_pair(city_b, city_a); citys.insert(make_pair(same_pair, length_between_city_a_b)); } map<vector<int>, pair<int, int> > path_detail; int tail_city_id = current_city_id; vector<vector<int> > paths; if (paths.empty()) { vector<int> new_path; new_path.push_back(tail_city_id); paths.push_back(new_path); } build_roads(citys, tail_city_id, target_city_id, paths); { vector<vector<int> >::iterator it = paths.begin(); for(; it != paths.end(); it++){ if (it->front() == current_city_id && it->back() == target_city_id){ int member_count = 0; int length = 0; for (int i = 0; i < it->size(); ++i){ member_count += teams[it->at(i)]; } for (int i = 0; i < it->size() - 1; ++i){ int city_a = it->at(i); int city_b = it->at(i+1); length += citys[make_pair(city_a, city_b)]; } path_detail[*it] = make_pair(length, member_count); } } } { int min_length = 0; map<vector<int>, pair<int, int> >::iterator it = path_detail.begin(); for(; it != path_detail.end(); it++){ int length = it->second.first; int member_count = it->second.second; if (min_length == 0){ min_length = length; } else { min_length = min(min_length, length); } } int path_count = 0; int max_member_count = 0; it = path_detail.begin(); for(; it != path_detail.end(); it++){ int length = it->second.first; int member_count = it->second.second; if (length == min_length){ path_count++; max_member_count = max(member_count, max_member_count); } } cout << path_count << " " << max_member_count; } return 0; }
32.116183
134
0.504134
[ "vector" ]
ea3e9b329094f3b835b7c9c0836ac5939e670ca0
50,010
cpp
C++
inetcore/setup/ieak5/ieaksie/cs.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/setup/ieak5/ieaksie/cs.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/setup/ieak5/ieaksie/cs.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "precomp.h" #include <inetcpl.h> #include "rsop.h" #include "resource.h" #include <tchar.h> // Private forward decalarations static void pxyEnableDlgItems(HWND hDlg, BOOL fSame, BOOL fUseProxy); static INT_PTR CALLBACK importConnSettingsRSoPProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); // defines for tree view image list #define BITMAP_WIDTH 16 #define BITMAP_HEIGHT 16 #define CONN_BITMAPS 2 #define IMAGE_LAN 0 #define IMAGE_MODEM 1 ///////////////////////////////////////////////////////////////////// void InitCSDlgInRSoPMode(HWND hDlg, CDlgRSoPData *pDRD) { __try { BOOL bImport = FALSE; _bstr_t bstrClass = L"RSOP_IEConnectionSettings"; HRESULT hr = pDRD->GetArrayOfPSObjects(bstrClass, L"rsopPrecedence"); if (SUCCEEDED(hr)) { CPSObjData **paCSObj = pDRD->GetCSObjArray(); long nCSObjects = pDRD->GetCSObjCount(); BOOL bImportHandled = FALSE; BOOL bDeleteHandled = FALSE; for (long nObj = 0; nObj < nCSObjects; nObj++) { // importCurrentConnSettings field _variant_t vtValue; if (!bImportHandled) { hr = paCSObj[nObj]->pObj->Get(L"importCurrentConnSettings", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bImport = (bool)vtValue ? TRUE : FALSE; CheckRadioButton(hDlg, IDC_CSNOIMPORT, IDC_CSIMPORT, (bool)vtValue ? IDC_CSIMPORT : IDC_CSNOIMPORT); bImportHandled = TRUE; DWORD dwCurGPOPrec = GetGPOPrecedence(paCSObj[nObj]->pObj, L"rsopPrecedence"); pDRD->SetImportedConnSettPrec(dwCurGPOPrec); } } // deleteExistingConnSettings field if (!bDeleteHandled) { hr = paCSObj[nObj]->pObj->Get(L"deleteExistingConnSettings", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { CheckDlgButton(hDlg, IDC_DELCONNECT, BST_CHECKED); bDeleteHandled = TRUE; } } // no need to process other GPOs since enabled properties have been found if (bImportHandled && bDeleteHandled) break; } } EnableDlgItem2(hDlg, IDC_CSNOIMPORT, FALSE); EnableDlgItem2(hDlg, IDC_CSIMPORT, FALSE); EnableDlgItem2(hDlg, IDC_MODIFYCONNECT, bImport); EnableDlgItem2(hDlg, IDC_DELCONNECT, FALSE); } __except(TRUE) { } } ///////////////////////////////////////////////////////////////////// HRESULT InitCSPrecPage(CDlgRSoPData *pDRD, HWND hwndList) { HRESULT hr = NOERROR; __try { _bstr_t bstrClass = L"RSOP_IEConnectionSettings"; hr = pDRD->GetArrayOfPSObjects(bstrClass); if (SUCCEEDED(hr)) { CPSObjData **paCSObj = pDRD->GetCSObjArray(); long nCSObjects = pDRD->GetCSObjCount(); for (long nObj = 0; nObj < nCSObjects; nObj++) { _bstr_t bstrGPOName = pDRD->GetGPONameFromPSAssociation(paCSObj[nObj]->pObj, L"rsopPrecedence"); // importCurrentConnSettings field BOOL bImport = FALSE; _variant_t vtValue; hr = paCSObj[nObj]->pObj->Get(L"importCurrentConnSettings", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) bImport = (bool)vtValue ? TRUE : FALSE; // deleteExistingConnSettings field BOOL bDelete = FALSE; hr = paCSObj[nObj]->pObj->Get(L"deleteExistingConnSettings", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) bDelete = (bool)vtValue ? TRUE : FALSE; _bstr_t bstrSetting; UINT iSettingString = 0; WCHAR wszTemp[128]; if (bImport && bDelete) iSettingString = IDS_CS_IMP_DEL_SETTING; else if (bImport) iSettingString = IDS_CS_IMPORT_SETTING; else if (bDelete) iSettingString = IDS_CS_DELETE_SETTING; else bstrSetting = GetDisabledString(); if (iSettingString > 0) { LoadString(g_hInstance, iSettingString, wszTemp, countof(wszTemp)); bstrSetting = wszTemp; } InsertPrecedenceListItem(hwndList, nObj, bstrGPOName, bstrSetting); } } } __except(TRUE) { } return hr; } ///////////////////////////////////////////////////////////////////// void InitAutoConfigDlgInRSoPMode(HWND hDlg, CDlgRSoPData *pDRD) { __try { _bstr_t bstrClass = L"RSOP_IEConnectionSettings"; HRESULT hr = pDRD->GetArrayOfPSObjects(bstrClass, L"rsopPrecedence"); if (SUCCEEDED(hr)) { CPSObjData **paCSObj = pDRD->GetCSObjArray(); long nCSObjects = pDRD->GetCSObjCount(); BOOL bDetectHandled = FALSE; BOOL bEnableHandled = FALSE; for (long nObj = 0; nObj < nCSObjects; nObj++) { // autoDetectConfigSettings field _variant_t vtValue; if (!bDetectHandled) { hr = paCSObj[nObj]->pObj->Get(L"autoDetectConfigSettings", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { CheckDlgButton(hDlg, IDC_AUTODETECT, BST_CHECKED); bDetectHandled = TRUE; } } // autoConfigEnable field if (!bEnableHandled) { hr = paCSObj[nObj]->pObj->Get(L"autoConfigEnable", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { CheckDlgButton(hDlg, IDC_YESAUTOCON, BST_CHECKED); bEnableHandled = TRUE; // autoConfigTime hr = paCSObj[nObj]->pObj->Get(L"autoConfigTime", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { TCHAR szTime[10] = _T(""); wnsprintf(szTime, countof(szTime), _T("%ld"), (long)vtValue); SetDlgItemText(hDlg, IDE_AUTOCONFIGTIME, szTime); } // autoConfigURL _bstr_t bstrValue; hr = paCSObj[nObj]->pObj->Get(L"autoConfigURL", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrValue = vtValue; SetDlgItemText(hDlg, IDE_AUTOCONFIGURL, (LPCTSTR)bstrValue); } // autoProxyURL hr = paCSObj[nObj]->pObj->Get(L"autoProxyURL", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrValue = vtValue; SetDlgItemText(hDlg, IDE_AUTOPROXYURL, (LPCTSTR)bstrValue); } } } // no need to process other GPOs since enabled properties have been found if (bDetectHandled && bEnableHandled) break; } } EnableDlgItem2(hDlg, IDC_AUTODETECT, FALSE); EnableDlgItem2(hDlg, IDC_YESAUTOCON, FALSE); EnableDlgItem2(hDlg, IDE_AUTOCONFIGTIME, FALSE); EnableDlgItem2(hDlg, IDE_AUTOCONFIGURL, FALSE); EnableDlgItem2(hDlg, IDE_AUTOPROXYURL, FALSE); } __except(TRUE) { } } ///////////////////////////////////////////////////////////////////// HRESULT InitAutoDetectCfgPrecPage(CDlgRSoPData *pDRD, HWND hwndList) { HRESULT hr = NOERROR; __try { _bstr_t bstrClass = L"RSOP_IEConnectionSettings"; hr = pDRD->GetArrayOfPSObjects(bstrClass); if (SUCCEEDED(hr)) { CPSObjData **paCSObj = pDRD->GetCSObjArray(); long nCSObjects = pDRD->GetCSObjCount(); for (long nObj = 0; nObj < nCSObjects; nObj++) { _bstr_t bstrGPOName = pDRD->GetGPONameFromPSAssociation(paCSObj[nObj]->pObj, L"rsopPrecedence"); // autoDetectConfigSettings field BOOL bDetect = FALSE; _variant_t vtValue; hr = paCSObj[nObj]->pObj->Get(L"autoDetectConfigSettings", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) bDetect = (bool)vtValue ? TRUE : FALSE; _bstr_t bstrSetting; if (bDetect) bstrSetting = GetEnabledString(); else bstrSetting = GetDisabledString(); InsertPrecedenceListItem(hwndList, nObj, bstrGPOName, bstrSetting); } } } __except(TRUE) { } return hr; } ///////////////////////////////////////////////////////////////////// HRESULT InitAutoCfgEnablePrecPage(CDlgRSoPData *pDRD, HWND hwndList) { HRESULT hr = NOERROR; __try { _bstr_t bstrClass = L"RSOP_IEConnectionSettings"; hr = pDRD->GetArrayOfPSObjects(bstrClass); if (SUCCEEDED(hr)) { CPSObjData **paCSObj = pDRD->GetCSObjArray(); long nCSObjects = pDRD->GetCSObjCount(); for (long nObj = 0; nObj < nCSObjects; nObj++) { _bstr_t bstrGPOName = pDRD->GetGPONameFromPSAssociation(paCSObj[nObj]->pObj, L"rsopPrecedence"); // autoConfigEnable field BOOL bEnable = FALSE; _variant_t vtValue; hr = paCSObj[nObj]->pObj->Get(L"autoConfigEnable", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) bEnable = (bool)vtValue ? TRUE : FALSE; _bstr_t bstrSetting; if (bEnable) bstrSetting = GetEnabledString(); else bstrSetting = GetDisabledString(); InsertPrecedenceListItem(hwndList, nObj, bstrGPOName, bstrSetting); } } } __except(TRUE) { } return hr; } ///////////////////////////////////////////////////////////////////// void InitProxyDlgInRSoPMode(HWND hDlg, CDlgRSoPData *pDRD) { __try { _bstr_t bstrClass = L"RSOP_IEConnectionSettings"; HRESULT hr = pDRD->GetArrayOfPSObjects(bstrClass, L"rsopPrecedence"); if (SUCCEEDED(hr)) { CPSObjData **paCSObj = pDRD->GetCSObjArray(); long nCSObjects = pDRD->GetCSObjCount(); for (long nObj = 0; nObj < nCSObjects; nObj++) { // enableProxy field _variant_t vtValue; hr = paCSObj[nObj]->pObj->Get(L"enableProxy", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { if ((bool)vtValue) CheckDlgButton(hDlg, IDC_YESPROXY, BST_CHECKED); // httpProxyServer _bstr_t bstrValue; hr = paCSObj[nObj]->pObj->Get(L"httpProxyServer", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrValue = vtValue; SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_HTTPPROXY, IDE_HTTPPORT, TRUE); } // useSameProxy hr = paCSObj[nObj]->pObj->Get(L"useSameProxy", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { if ((bool)vtValue) { CheckDlgButton(hDlg, IDC_SAMEFORALL, BST_CHECKED); SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_FTPPROXY, IDE_FTPPORT, TRUE); SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_GOPHERPROXY, IDE_GOPHERPORT, TRUE); SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_SECPROXY, IDE_SECPORT, TRUE); SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_SOCKSPROXY, IDE_SOCKSPORT, FALSE); } else { // ftpProxyServer hr = paCSObj[nObj]->pObj->Get(L"ftpProxyServer", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrValue = vtValue; SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_FTPPROXY, IDE_FTPPORT, TRUE); } // gopherProxyServer hr = paCSObj[nObj]->pObj->Get(L"gopherProxyServer", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrValue = vtValue; SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_GOPHERPROXY, IDE_GOPHERPORT, TRUE); } // secureProxyServer hr = paCSObj[nObj]->pObj->Get(L"secureProxyServer", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrValue = vtValue; SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_SECPROXY, IDE_SECPORT, TRUE); } // socksProxyServer hr = paCSObj[nObj]->pObj->Get(L"socksProxyServer", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrValue = vtValue; SetProxyDlg(hDlg, (LPCTSTR)bstrValue, IDE_SOCKSPROXY, IDE_SOCKSPORT, FALSE); } } } // proxyOverride hr = paCSObj[nObj]->pObj->Get(L"proxyOverride", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrValue = vtValue; TCHAR szProxy[MAX_PATH]; StrCpy(szProxy, (LPCTSTR)bstrValue); if (TEXT('\0') == szProxy[0]) StrCpy(szProxy, LOCALPROXY); LPTSTR pszLocal = StrStr(szProxy, LOCALPROXY); if (NULL != pszLocal) { if (pszLocal == szProxy) { LPTSTR pszSemicolon = pszLocal + countof(LOCALPROXY)-1; if (TEXT(';') == *pszSemicolon) pszSemicolon++; StrCpy(pszLocal, pszSemicolon); } else if (TEXT('\0') == *(pszLocal + countof(LOCALPROXY)-1)) *(pszLocal - 1) = TEXT('\0'); CheckDlgButton(hDlg, IDC_DISPROXYLOCAL, TRUE); } SetDlgItemText(hDlg, IDE_DISPROXYADR, szProxy); } break; } } } EnableDlgItem2(hDlg, IDC_YESPROXY, FALSE); EnableDlgItem2(hDlg, IDC_SAMEFORALL, FALSE); EnableDlgItem2(hDlg, IDE_HTTPPROXY, FALSE); EnableDlgItem2(hDlg, IDE_HTTPPORT, FALSE); EnableDlgItem2(hDlg, IDE_FTPPROXY, FALSE); EnableDlgItem2(hDlg, IDE_FTPPORT, FALSE); EnableDlgItem2(hDlg, IDE_GOPHERPROXY, FALSE); EnableDlgItem2(hDlg, IDE_GOPHERPORT, FALSE); EnableDlgItem2(hDlg, IDE_SECPROXY, FALSE); EnableDlgItem2(hDlg, IDE_SECPORT, FALSE); EnableDlgItem2(hDlg, IDE_SOCKSPROXY, FALSE); EnableDlgItem2(hDlg, IDE_SOCKSPORT, FALSE); EnableDlgItem2(hDlg, IDC_DISPROXYLOCAL, FALSE); EnableDlgItem2(hDlg, IDE_DISPROXYADR, FALSE); } __except(TRUE) { } } ///////////////////////////////////////////////////////////////////// HRESULT InitProxyPrecPage(CDlgRSoPData *pDRD, HWND hwndList) { HRESULT hr = NOERROR; __try { _bstr_t bstrClass = L"RSOP_IEConnectionSettings"; hr = pDRD->GetArrayOfPSObjects(bstrClass); if (SUCCEEDED(hr)) { CPSObjData **paCSObj = pDRD->GetCSObjArray(); long nCSObjects = pDRD->GetCSObjCount(); for (long nObj = 0; nObj < nCSObjects; nObj++) { _bstr_t bstrGPOName = pDRD->GetGPONameFromPSAssociation(paCSObj[nObj]->pObj, L"rsopPrecedence"); // enableProxy field BOOL bEnable = FALSE; _variant_t vtValue; hr = paCSObj[nObj]->pObj->Get(L"enableProxy", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) bEnable = (bool)vtValue ? TRUE : FALSE; _bstr_t bstrSetting; if (bEnable) bstrSetting = GetEnabledString(); else bstrSetting = GetDisabledString(); InsertPrecedenceListItem(hwndList, nObj, bstrGPOName, bstrSetting); } } } __except(TRUE) { } return hr; } ///////////////////////////////////////////////////////////////////// INT_PTR CALLBACK ConnectSetDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) { // Retrieve Property Sheet Page info for each call into dlg proc. LPPROPSHEETCOOKIE psCookie = (LPPROPSHEETCOOKIE)GetWindowLongPtr(hDlg, DWLP_USER); TCHAR szWorkDir[MAX_PATH]; BOOL fImport; switch (msg) { case WM_INITDIALOG: SetPropSheetCookie(hDlg, lParam); // find out if this dlg is in RSoP mode psCookie = (LPPROPSHEETCOOKIE)GetWindowLongPtr(hDlg, DWLP_USER); if (psCookie->pCS->IsRSoP()) { TCHAR szViewSettings[128]; LoadString(g_hInstance, IDS_VIEW_SETTINGS, szViewSettings, countof(szViewSettings)); SetDlgItemText(hDlg, IDC_MODIFYCONNECT, szViewSettings); CDlgRSoPData *pDRD = GetDlgRSoPData(hDlg, psCookie->pCS); if (pDRD) InitCSDlgInRSoPMode(hDlg, pDRD); } break; case WM_DESTROY: if (psCookie->pCS->IsRSoP()) DestroyDlgRSoPData(hDlg); break; case WM_COMMAND: if (BN_CLICKED != GET_WM_COMMAND_CMD(wParam, lParam)) return FALSE; switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDC_CSNOIMPORT: DisableDlgItem(hDlg, IDC_MODIFYCONNECT); break; case IDC_CSIMPORT: EnableDlgItem(hDlg, IDC_MODIFYCONNECT); break; case IDC_MODIFYCONNECT: if (psCookie->pCS->IsRSoP()) { CDlgRSoPData *pDRD = GetDlgRSoPData(hDlg, psCookie->pCS); if (NULL != pDRD) { CreateINetCplLookALikePage(hDlg, IDD_IMPORTEDCONNSETTINGS, importConnSettingsRSoPProc, (LPARAM)pDRD); } } else ShowInetcpl(hDlg, INET_PAGE_CONNECTION); break; default: return FALSE; } break; case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case PSN_SETACTIVE: // don't do any of this stuff in RSoP mode if (!psCookie->pCS->IsRSoP()) { fImport = InsGetBool(IS_CONNECTSET, IK_OPTION, FALSE, GetInsFile(hDlg)); CheckRadioButton(hDlg, IDC_CSNOIMPORT, IDC_CSIMPORT, fImport ? IDC_CSIMPORT : IDC_CSNOIMPORT); EnableDlgItem2 (hDlg, IDC_MODIFYCONNECT, fImport); ReadBoolAndCheckButton(IS_CONNECTSET, IK_DELETECONN, FALSE, GetInsFile(hDlg), hDlg, IDC_DELCONNECT); } break; case PSN_HELP: ShowHelpTopic(hDlg); break; case PSN_APPLY: if (psCookie->pCS->IsRSoP()) return FALSE; else { CNewCursor cur(IDC_WAIT); CreateWorkDir(GetInsFile(hDlg), IEAK_GPE_BRANDING_SUBDIR TEXT("\\cs"), szWorkDir); fImport = (BST_CHECKED == IsDlgButtonChecked(hDlg, IDC_CSIMPORT)); if (!AcquireWriteCriticalSection(hDlg)) { SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE); break; } ImportConnectSet(GetInsFile(hDlg), szWorkDir, szWorkDir, fImport, IEM_GP); CheckButtonAndWriteBool(hDlg, IDC_DELCONNECT, IS_CONNECTSET, IK_DELETECONN, GetInsFile(hDlg)); if (PathIsDirectoryEmpty(szWorkDir)) PathRemovePath(szWorkDir); SignalPolicyChanged(hDlg, FALSE, TRUE, &g_guidClientExt, &g_guidSnapinExt); } break; default: return FALSE; } break; case WM_HELP: ShowHelpTopic(hDlg); break; default: return FALSE; } return TRUE; } ///////////////////////////////////////////////////////////////////// INT_PTR CALLBACK AutoconfigDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) { // Retrieve Property Sheet Page info for each call into dlg proc. LPPROPSHEETCOOKIE psCookie = (LPPROPSHEETCOOKIE)GetWindowLongPtr(hDlg, DWLP_USER); TCHAR szAutoConfigURL[INTERNET_MAX_URL_LENGTH], szAutoProxyURL[INTERNET_MAX_URL_LENGTH], szAutoConfigTime[7]; BOOL fDetectConfig, fUseAutoConfig; switch (msg) { case WM_INITDIALOG: { SetPropSheetCookie(hDlg, lParam); // find out if this dlg is in RSoP mode psCookie = (LPPROPSHEETCOOKIE)GetWindowLongPtr(hDlg, DWLP_USER); BOOL bIsRSoP = psCookie->pCS->IsRSoP(); if (bIsRSoP) { CDlgRSoPData *pDRD = GetDlgRSoPData(hDlg, psCookie->pCS); if (pDRD) InitAutoConfigDlgInRSoPMode(hDlg, pDRD); } else { // warn the user that settings on this page will override imported connection settings if (InsGetBool(IS_CONNECTSET, IK_OPTION, FALSE, GetInsFile(hDlg))) ErrorMessageBox(hDlg, IDS_CONNECTSET_WARN); DisableDBCSChars(hDlg, IDE_AUTOCONFIGTIME); } EnableDBCSChars(hDlg, IDE_AUTOCONFIGURL); EnableDBCSChars(hDlg, IDE_AUTOPROXYURL); if (!bIsRSoP) { Edit_LimitText(GetDlgItem(hDlg, IDE_AUTOCONFIGTIME), countof(szAutoConfigTime) - 1); Edit_LimitText(GetDlgItem(hDlg, IDE_AUTOCONFIGURL), countof(szAutoConfigURL) - 1); Edit_LimitText(GetDlgItem(hDlg, IDE_AUTOPROXYURL), countof(szAutoProxyURL) - 1); } break; } case WM_DESTROY: if (psCookie->pCS->IsRSoP()) DestroyDlgRSoPData(hDlg); break; case WM_COMMAND: if (BN_CLICKED != GET_WM_COMMAND_CMD(wParam, lParam)) return FALSE; switch(GET_WM_COMMAND_ID(wParam, lParam)) { case IDC_YESAUTOCON: fUseAutoConfig = (BST_CHECKED == IsDlgButtonChecked(hDlg, IDC_YESAUTOCON)); EnableDlgItem2(hDlg, IDE_AUTOCONFIGTIME, fUseAutoConfig); EnableDlgItem2(hDlg, IDC_AUTOCONFIGTEXT2, fUseAutoConfig); EnableDlgItem2(hDlg, IDC_AUTOCONFIGTEXT3, fUseAutoConfig); EnableDlgItem2(hDlg, IDE_AUTOCONFIGURL, fUseAutoConfig); EnableDlgItem2(hDlg, IDC_AUTOCONFIGURL_TXT, fUseAutoConfig); EnableDlgItem2(hDlg, IDE_AUTOPROXYURL, fUseAutoConfig); EnableDlgItem2(hDlg, IDC_AUTOPROXYURL_TXT, fUseAutoConfig); break; default: return FALSE; } break; case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case PSN_SETACTIVE: // don't do any of this stuff in RSoP mode if (!psCookie->pCS->IsRSoP()) { fDetectConfig = InsGetBool(IS_URL, IK_DETECTCONFIG, TRUE, GetInsFile(hDlg)); CheckDlgButton(hDlg, IDC_AUTODETECT, fDetectConfig ? BST_CHECKED : BST_UNCHECKED); fUseAutoConfig = InsGetBool(IS_URL, IK_USEAUTOCONF, FALSE, GetInsFile(hDlg)); CheckDlgButton(hDlg, IDC_YESAUTOCON, fUseAutoConfig ? BST_CHECKED : BST_UNCHECKED); InsGetString(IS_URL, IK_AUTOCONFTIME, szAutoConfigTime, countof(szAutoConfigTime), GetInsFile(hDlg)); SetDlgItemText(hDlg, IDE_AUTOCONFIGTIME, szAutoConfigTime); EnableDlgItem2(hDlg, IDE_AUTOCONFIGTIME, fUseAutoConfig); EnableDlgItem2(hDlg, IDC_AUTOCONFIGTEXT2, fUseAutoConfig); EnableDlgItem2(hDlg, IDC_AUTOCONFIGTEXT3, fUseAutoConfig); InsGetString(IS_URL, IK_AUTOCONFURL, szAutoConfigURL, countof(szAutoConfigURL), GetInsFile(hDlg)); SetDlgItemText(hDlg, IDE_AUTOCONFIGURL, szAutoConfigURL); EnableDlgItem2(hDlg, IDE_AUTOCONFIGURL, fUseAutoConfig); EnableDlgItem2(hDlg, IDC_AUTOCONFIGURL_TXT, fUseAutoConfig); InsGetString(IS_URL, IK_AUTOCONFURLJS, szAutoProxyURL, countof(szAutoProxyURL), GetInsFile(hDlg)); SetDlgItemText(hDlg, IDE_AUTOPROXYURL, szAutoProxyURL); EnableDlgItem2(hDlg, IDE_AUTOPROXYURL, fUseAutoConfig); EnableDlgItem2(hDlg, IDC_AUTOPROXYURL_TXT, fUseAutoConfig); } break; case PSN_HELP: ShowHelpTopic(hDlg); break; case PSN_APPLY: if (psCookie->pCS->IsRSoP()) return FALSE; else { fDetectConfig = (BST_CHECKED == IsDlgButtonChecked(hDlg, IDC_AUTODETECT)); fUseAutoConfig = (BST_CHECKED == IsDlgButtonChecked(hDlg, IDC_YESAUTOCON)); GetDlgItemText(hDlg, IDE_AUTOCONFIGTIME, szAutoConfigTime, countof(szAutoConfigTime)); GetDlgItemText(hDlg, IDE_AUTOCONFIGURL, szAutoConfigURL, countof(szAutoConfigURL)); GetDlgItemText(hDlg, IDE_AUTOPROXYURL, szAutoProxyURL, countof(szAutoProxyURL)); // do error checking if (fUseAutoConfig) { if (IsWindowEnabled(GetDlgItem(hDlg, IDE_AUTOCONFIGTIME)) && !CheckField(hDlg, IDE_AUTOCONFIGTIME, FC_NUMBER)) { SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE); return TRUE; } if (*szAutoConfigURL == TEXT('\0') && *szAutoProxyURL == TEXT('\0')) { ErrorMessageBox(hDlg, IDS_AUTOCONFIG_NULL); SetFocus(GetDlgItem(hDlg, IDE_AUTOCONFIGURL)); SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE); return TRUE; } if (!CheckField(hDlg, IDE_AUTOCONFIGURL, FC_URL) || !CheckField(hDlg, IDE_AUTOPROXYURL, FC_URL)) { SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE); return TRUE; } } // write the values to the ins file if (!AcquireWriteCriticalSection(hDlg)) { SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE); break; } InsWriteBoolEx(IS_URL, IK_DETECTCONFIG, fDetectConfig, GetInsFile(hDlg)); InsWriteBoolEx(IS_URL, IK_USEAUTOCONF, fUseAutoConfig, GetInsFile(hDlg)); InsWriteString(IS_URL, IK_AUTOCONFTIME, szAutoConfigTime, GetInsFile(hDlg)); InsWriteString(IS_URL, IK_AUTOCONFURL, szAutoConfigURL, GetInsFile(hDlg)); InsWriteString(IS_URL, IK_AUTOCONFURLJS, szAutoProxyURL, GetInsFile(hDlg)); SignalPolicyChanged(hDlg, FALSE, TRUE, &g_guidClientExt, &g_guidSnapinExt); } break; default: return FALSE; } break; case WM_HELP: ShowHelpTopic(hDlg); break; default: return FALSE; } return TRUE; } ///////////////////////////////////////////////////////////////////// INT_PTR CALLBACK ProxyDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) { // Retrieve Property Sheet Page info for each call into dlg proc. LPPROPSHEETCOOKIE psCookie = (LPPROPSHEETCOOKIE)GetWindowLongPtr(hDlg, DWLP_USER); TCHAR szProxy[MAX_PATH]; PTSTR pszLocal; BOOL fSameProxy, fUseProxy, fLocal; switch (msg) { case WM_INITDIALOG: { SetPropSheetCookie(hDlg, lParam); // find out if this dlg is in RSoP mode psCookie = (LPPROPSHEETCOOKIE)GetWindowLongPtr(hDlg, DWLP_USER); BOOL bIsRSoP = psCookie->pCS->IsRSoP(); if (bIsRSoP) { CDlgRSoPData *pDRD = GetDlgRSoPData(hDlg, psCookie->pCS); if (pDRD) InitProxyDlgInRSoPMode(hDlg, pDRD); } else { // warn the user that settings on this page will override imported connection settings if (InsGetBool(IS_CONNECTSET, IK_OPTION, FALSE, GetInsFile(hDlg))) ErrorMessageBox(hDlg, IDS_CONNECTSET_WARN); } EnableDBCSChars(hDlg, IDE_HTTPPROXY); EnableDBCSChars(hDlg, IDE_SECPROXY); EnableDBCSChars(hDlg, IDE_FTPPROXY); EnableDBCSChars(hDlg, IDE_GOPHERPROXY); EnableDBCSChars(hDlg, IDE_SOCKSPROXY); EnableDBCSChars(hDlg, IDE_DISPROXYADR); if (!bIsRSoP) { Edit_LimitText(GetDlgItem(hDlg, IDE_HTTPPORT), 5); Edit_LimitText(GetDlgItem(hDlg, IDE_FTPPORT), 5); Edit_LimitText(GetDlgItem(hDlg, IDE_GOPHERPORT), 5); Edit_LimitText(GetDlgItem(hDlg, IDE_SECPORT), 5); Edit_LimitText(GetDlgItem(hDlg, IDE_SOCKSPORT), 5); Edit_LimitText(GetDlgItem(hDlg, IDE_DISPROXYADR),(MAX_PATH - 11)); //size of <local>, etc } break; } case WM_DESTROY: if (psCookie->pCS->IsRSoP()) DestroyDlgRSoPData(hDlg); break; case WM_COMMAND: fSameProxy = fUseProxy = fLocal = FALSE; if (BN_CLICKED == GET_WM_COMMAND_CMD(wParam, lParam)) { fSameProxy = IsDlgButtonChecked(hDlg, IDC_SAMEFORALL); fUseProxy = IsDlgButtonChecked(hDlg, IDC_YESPROXY); fLocal = IsDlgButtonChecked(hDlg, IDC_DISPROXYLOCAL); } switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDC_SAMEFORALL: if (BN_CLICKED != GET_WM_COMMAND_CMD(wParam, lParam)) return FALSE; GetProxyDlg(hDlg, szProxy, IDE_HTTPPROXY, IDE_HTTPPORT); if (fSameProxy) { SetProxyDlg(hDlg, szProxy, IDE_HTTPPROXY, IDE_HTTPPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_FTPPROXY, IDE_FTPPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_GOPHERPROXY, IDE_GOPHERPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_SECPROXY, IDE_SECPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_SOCKSPROXY, IDE_SOCKSPORT, FALSE); } // fallthrough case IDC_YESPROXY: if (BN_CLICKED != GET_WM_COMMAND_CMD(wParam, lParam)) return FALSE; pxyEnableDlgItems(hDlg, fSameProxy, fUseProxy); break; case IDE_HTTPPROXY: case IDE_HTTPPORT: if (EN_UPDATE != GET_WM_COMMAND_CMD(wParam, lParam)) return FALSE; if (fSameProxy) { GetProxyDlg(hDlg, szProxy, IDE_HTTPPROXY, IDE_HTTPPORT); SetProxyDlg(hDlg, szProxy, IDE_FTPPROXY, IDE_FTPPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_GOPHERPROXY, IDE_GOPHERPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_SECPROXY, IDE_SECPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_SOCKSPROXY, IDE_SOCKSPORT, FALSE); } break; default: return FALSE; } break; case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case PSN_SETACTIVE: // don't do any of this stuff in RSoP mode if (!psCookie->pCS->IsRSoP()) { fUseProxy = InsGetBool(IS_PROXY, IK_PROXYENABLE, FALSE, GetInsFile(hDlg)); CheckDlgButton(hDlg, IDC_YESPROXY, fUseProxy); fSameProxy = InsGetBool(IS_PROXY, IK_SAMEPROXY, TRUE, GetInsFile(hDlg)); CheckDlgButton(hDlg, IDC_SAMEFORALL, fSameProxy); InsGetString(IS_PROXY, IK_HTTPPROXY, szProxy, countof(szProxy), GetInsFile(hDlg)); if (fSameProxy) { SetProxyDlg(hDlg, szProxy, IDE_HTTPPROXY, IDE_HTTPPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_FTPPROXY, IDE_FTPPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_GOPHERPROXY, IDE_GOPHERPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_SECPROXY, IDE_SECPORT, TRUE); SetProxyDlg(hDlg, szProxy, IDE_SOCKSPROXY, IDE_SOCKSPORT, FALSE); } else { SetProxyDlg(hDlg, szProxy, IDE_HTTPPROXY, IDE_HTTPPORT, TRUE); InsGetString(IS_PROXY, IK_FTPPROXY, szProxy, countof(szProxy), GetInsFile(hDlg)); SetProxyDlg(hDlg, szProxy, IDE_FTPPROXY, IDE_FTPPORT, TRUE); InsGetString(IS_PROXY, IK_GOPHERPROXY, szProxy, countof(szProxy), GetInsFile(hDlg)); SetProxyDlg(hDlg, szProxy, IDE_GOPHERPROXY, IDE_GOPHERPORT, TRUE); InsGetString(IS_PROXY, IK_SECPROXY, szProxy, countof(szProxy), GetInsFile(hDlg)); SetProxyDlg(hDlg, szProxy, IDE_SECPROXY, IDE_SECPORT, TRUE); InsGetString(IS_PROXY, IK_SOCKSPROXY, szProxy, countof(szProxy), GetInsFile(hDlg)); if (TEXT('\0') != szProxy[0]) SetProxyDlg(hDlg, szProxy, IDE_SOCKSPROXY, IDE_SOCKSPORT, FALSE); } InsGetString(IS_PROXY, IK_PROXYOVERRIDE, szProxy, countof(szProxy), GetInsFile(hDlg)); if (TEXT('\0') == szProxy[0]) StrCpy(szProxy, LOCALPROXY); pszLocal = StrStr(szProxy, LOCALPROXY); fLocal = FALSE; if (NULL != pszLocal) { if (pszLocal == szProxy) { PTSTR pszSemicolon; pszSemicolon = pszLocal + countof(LOCALPROXY)-1; if (TEXT(';') == *pszSemicolon) pszSemicolon++; StrCpy(pszLocal, pszSemicolon); } else if (TEXT('\0') == *(pszLocal + countof(LOCALPROXY)-1)) *(pszLocal - 1) = TEXT('\0'); fLocal = TRUE; } CheckDlgButton(hDlg, IDC_DISPROXYLOCAL, fLocal); SetDlgItemText(hDlg, IDE_DISPROXYADR, szProxy); pxyEnableDlgItems(hDlg, fSameProxy, fUseProxy); } break; case PSN_HELP: ShowHelpTopic(hDlg); break; case PSN_APPLY: if (psCookie->pCS->IsRSoP()) return FALSE; else { if (!CheckField(hDlg, IDE_HTTPPORT, FC_NUMBER) || !CheckField(hDlg, IDE_FTPPORT, FC_NUMBER) || !CheckField(hDlg, IDE_GOPHERPORT, FC_NUMBER) || !CheckField(hDlg, IDE_SECPORT, FC_NUMBER) || !CheckField(hDlg, IDE_SOCKSPORT, FC_NUMBER)) return TRUE; fUseProxy = IsDlgButtonChecked(hDlg, IDC_YESPROXY); fSameProxy = IsDlgButtonChecked(hDlg, IDC_SAMEFORALL); fLocal = IsDlgButtonChecked(hDlg, IDC_DISPROXYLOCAL); if (!AcquireWriteCriticalSection(hDlg)) { SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE); break; } InsWriteBoolEx(IS_PROXY, IK_PROXYENABLE, fUseProxy, GetInsFile(hDlg)); GetProxyDlg(hDlg, szProxy, IDE_HTTPPROXY, IDE_HTTPPORT); InsWriteString(IS_PROXY, IK_HTTPPROXY, szProxy, GetInsFile(hDlg)); GetProxyDlg(hDlg, szProxy, IDE_FTPPROXY, IDE_FTPPORT); InsWriteString(IS_PROXY, IK_FTPPROXY, szProxy, GetInsFile(hDlg)); GetProxyDlg(hDlg, szProxy, IDE_GOPHERPROXY, IDE_GOPHERPORT); InsWriteString(IS_PROXY, IK_GOPHERPROXY, szProxy, GetInsFile(hDlg)); GetProxyDlg(hDlg, szProxy, IDE_SECPROXY, IDE_SECPORT); InsWriteString(IS_PROXY, IK_SECPROXY, szProxy, GetInsFile(hDlg)); GetProxyDlg(hDlg, szProxy, IDE_SOCKSPROXY, IDE_SOCKSPORT); InsWriteString(IS_PROXY, IK_SOCKSPROXY, szProxy, GetInsFile(hDlg)); InsWriteBoolEx(IS_PROXY, IK_SAMEPROXY, fSameProxy, GetInsFile(hDlg)); GetDlgItemText(hDlg, IDE_DISPROXYADR, szProxy, countof(szProxy)); if (fLocal) { if (TEXT('\0') != szProxy[0]) { TCHAR szAux[MAX_PATH]; StrRemoveAllWhiteSpace(szProxy); wnsprintf(szAux, countof(szAux), TEXT("%s;%s"), szProxy, LOCALPROXY); InsWriteQuotedString(IS_PROXY, IK_PROXYOVERRIDE, szAux, GetInsFile(hDlg)); } else InsWriteString(IS_PROXY, IK_PROXYOVERRIDE, LOCALPROXY, GetInsFile(hDlg)); } else InsWriteString(IS_PROXY, IK_PROXYOVERRIDE, szProxy, GetInsFile(hDlg)); SignalPolicyChanged(hDlg, FALSE, TRUE, &g_guidClientExt, &g_guidSnapinExt); } break; default: return FALSE; } break; case WM_HELP: ShowHelpTopic(hDlg); break; default: return FALSE; } return TRUE; } ///////////////////////////////////////////////////////////////////////////// // Implementation helper routines static void pxyEnableDlgItems(HWND hDlg, BOOL fSame, BOOL fUseProxy) { EnableDlgItem2(hDlg, IDC_FTPPROXY1, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDE_FTPPROXY, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDE_FTPPORT, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDC_SECPROXY1, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDE_SECPROXY, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDE_SECPORT, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDC_GOPHERPROXY1, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDE_GOPHERPROXY, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDE_GOPHERPORT, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDC_SOCKSPROXY1, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDE_SOCKSPROXY, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDE_SOCKSPORT, !fSame && fUseProxy); EnableDlgItem2(hDlg, IDC_HTTPPROXY1, fUseProxy); EnableDlgItem2(hDlg, IDE_HTTPPROXY, fUseProxy); EnableDlgItem2(hDlg, IDE_HTTPPORT, fUseProxy); EnableDlgItem2(hDlg, IDC_DISPROXYADR1, fUseProxy); EnableDlgItem2(hDlg, IDE_DISPROXYADR, fUseProxy); EnableDlgItem2(hDlg, IDC_DISPROXYLOCAL, fUseProxy); EnableDlgItem2(hDlg, IDC_SAMEFORALL, fUseProxy); } //******************************************************************* // CODE FROM INETCPL //******************************************************************* ///////////////////////////////////////////////////////////////////// void InitImportedConnSettingsDlgInRSoPMode(HWND hDlg, CDlgRSoPData *pDRD) { __try { if (NULL != pDRD->ConnectToNamespace()) { // get our stored precedence value DWORD dwCurGPOPrec = pDRD->GetImportedConnSettPrec(); // create the object path of the program settings for this GPO WCHAR wszObjPath[128]; wnsprintf(wszObjPath, countof(wszObjPath), L"RSOP_IEConnectionSettings.rsopID=\"IEAK\",rsopPrecedence=%ld", dwCurGPOPrec); _bstr_t bstrObjPath = wszObjPath; // get the RSOP_IEProgramSettings object and its properties ComPtr<IWbemServices> pWbemServices = pDRD->GetWbemServices(); ComPtr<IWbemClassObject> pPSObj = NULL; HRESULT hr = pWbemServices->GetObject(bstrObjPath, 0L, NULL, (IWbemClassObject**)&pPSObj, NULL); if (SUCCEEDED(hr)) { // defaultDialUpConnection field _variant_t vtValue; _bstr_t bstrDefault; hr = pPSObj->Get(L"defaultDialUpConnection", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { bstrDefault = vtValue; if (bstrDefault.length() > 0) SetDlgItemText(hDlg, IDC_DIAL_DEF_ISP, (LPCTSTR)bstrDefault); } // dialUpState field hr = pPSObj->Get(L"dialUpState", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { if (1 == (long)vtValue) CheckRadioButton(hDlg, IDC_DIALUP_NEVER, IDC_DIALUP, IDC_DIALUP_ON_NONET); else if (2 == (long)vtValue) CheckRadioButton(hDlg, IDC_DIALUP_NEVER, IDC_DIALUP, IDC_DIALUP); else CheckRadioButton(hDlg, IDC_DIALUP_NEVER, IDC_DIALUP, IDC_DIALUP_NEVER); } // dialUpConnections field hr = pPSObj->Get(L"dialUpConnections", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { HWND hwndTree = GetDlgItem(hDlg, IDC_CONN_LIST); ASSERT(hwndTree); // init tvi and tvins TVITEM tvi; TVINSERTSTRUCT tvins; tvi.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM; tvi.lParam = 0; tvins.hInsertAfter = (HTREEITEM)TVI_SORT; tvins.hParent = TVI_ROOT; // clear list TreeView_DeleteAllItems(hwndTree); SAFEARRAY *psa = vtValue.parray; //------------------------------- // Get the upper and lower bounds of the Names array long lLower = 0; long lUpper = 0; hr = SafeArrayGetLBound(psa, 1, &lLower); if (SUCCEEDED(hr)) hr = SafeArrayGetUBound(psa, 1, &lUpper); // check the case of no instances or a null array if (SUCCEEDED(hr) && lUpper >= lLower) { _bstr_t bstrName; HTREEITEM hFirst = NULL, hDefault = NULL; for (long lItem = lLower; lItem <= lUpper; lItem++) { BSTR bstrValue = NULL; hr = SafeArrayGetElement(psa, &lItem, (void*)&bstrValue); if (SUCCEEDED(hr)) { bstrName = bstrValue; tvi.pszText = (LPTSTR)(LPCTSTR)bstrName; tvi.iImage = IMAGE_MODEM; tvi.iSelectedImage = IMAGE_MODEM; tvi.lParam = lItem; tvins.item = tvi; HTREEITEM hItem = TreeView_InsertItem(hwndTree, &tvins); if (0 == lItem) hFirst = hItem; if (NULL != hItem && bstrName == bstrDefault) hDefault = hItem; } } // select default or first entry if there is one if(NULL != hDefault) TreeView_Select(hwndTree, hDefault, TVGN_CARET); else if (NULL != hFirst) TreeView_Select(hwndTree, hFirst, TVGN_CARET); } } } } } __except(TRUE) { } } ///////////////////////////////////////////////////////////////////// INT_PTR CALLBACK importConnSettingsRSoPProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { BOOL fResult = FALSE; switch (uMsg) { case WM_INITDIALOG: { // create image list for tree view HIMAGELIST himl = ImageList_Create(BITMAP_WIDTH, BITMAP_HEIGHT, ILC_COLOR | ILC_MASK, CONN_BITMAPS, 4 ); HICON hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_LAN)); ImageList_AddIcon(himl, hIcon); hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_PHONE)); ImageList_AddIcon(himl, hIcon); TreeView_SetImageList(GetDlgItem(hDlg, IDC_CONN_LIST), himl, TVSIL_NORMAL); // init the data CDlgRSoPData *pDRD = (CDlgRSoPData*)((LPPROPSHEETPAGE)lParam)->lParam; InitImportedConnSettingsDlgInRSoPMode(hDlg, pDRD); // init other controls CheckRadioButton(hDlg, IDC_DIALUP_NEVER, IDC_DIALUP, IDC_DIALUP_NEVER); ShowWindow(GetDlgItem(hDlg, IDC_ENABLE_SECURITY), SW_HIDE); // only for 95 machines // disable everything EnableDlgItem2(hDlg, IDC_CONNECTION_WIZARD, FALSE); EnableDlgItem2(hDlg, IDC_DIALUP_ADD, FALSE); EnableDlgItem2(hDlg, IDC_DIALUP_REMOVE, FALSE); EnableDlgItem2(hDlg, IDC_MODEM_SETTINGS, FALSE); EnableDlgItem2(hDlg, IDC_DIALUP_NEVER, FALSE); EnableDlgItem2(hDlg, IDC_DIALUP_ON_NONET, FALSE); EnableDlgItem2(hDlg, IDC_DIALUP, FALSE); EnableDlgItem2(hDlg, IDC_SET_DEFAULT, FALSE); EnableDlgItem2(hDlg, IDC_ENABLE_SECURITY, FALSE); EnableDlgItem2(hDlg, IDC_CON_SHARING, FALSE); EnableDlgItem2(hDlg, IDC_LAN_SETTINGS, FALSE); fResult = TRUE; break; } case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: EndDialog(hDlg, IDOK); fResult = TRUE; break; case IDCANCEL: EndDialog(hDlg, IDCANCEL); fResult = TRUE; break; } break; } return fResult; }
40.298147
118
0.512797
[ "object" ]
ea403bd3f967909545034e0687eec1fcd51e8992
1,532
cpp
C++
src/cpp/constant-source-node.cpp
node-3d/waa-raub
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
17
2018-10-03T00:44:33.000Z
2022-03-17T06:40:15.000Z
src/cpp/constant-source-node.cpp
raub/node-waa
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
7
2019-07-16T08:22:31.000Z
2021-11-29T21:45:06.000Z
src/cpp/constant-source-node.cpp
raub/node-waa
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
2
2019-08-05T20:00:42.000Z
2020-03-15T13:25:41.000Z
#include "constant-source-node.hpp" ConstantSourceNode::ConstantSourceNode() : AudioScheduledSourceNode() { _isDestroyed = false; } ConstantSourceNode::~ConstantSourceNode() { _destroy(); } void ConstantSourceNode::_destroy() { DES_CHECK; _isDestroyed = true; AudioScheduledSourceNode::_destroy(); } // ------ Methods and props JS_IMPLEMENT_GETTER(ConstantSourceNode, offset) { THIS_CHECK; RET_VALUE(_offset.Value()); } // ------ System methods and props for Napi::ObjectWrap IMPLEMENT_ES5_CLASS(ConstantSourceNode); void ConstantSourceNode::init(Napi::Env env, Napi::Object exports) { Napi::Function ctor = wrap(env); JS_ASSIGN_METHOD(destroy); JS_ASSIGN_GETTER(offset); JS_ASSIGN_GETTER(isDestroyed); exports.Set("ConstantSourceNode", ctor); } bool ConstantSourceNode::isConstantSourceNode(Napi::Object obj) { return obj.InstanceOf(_ctorEs5.Value()); } Napi::Object ConstantSourceNode::getNew() { Napi::Function ctor = Nan::New(_constructor); // Napi::Value argv[] = { /* arg1, arg2, ... */ }; return Nan::NewInstance(ctor, 0/*argc*/, nullptr/*argv*/).ToLocalChecked(); } ConstantSourceNode::ConstantSourceNode(const Napi::CallbackInfo &info): Napi::ObjectWrap<ConstantSourceNode>(info) { ConstantSourceNode *constantSourceNode = new ConstantSourceNode(); } JS_IMPLEMENT_METHOD(ConstantSourceNode, destroy) { THIS_CHECK; emit("destroy"); _destroy(); } JS_IMPLEMENT_GETTER(ConstantSourceNode, isDestroyed) { NAPI_ENV; RET_BOOL(_isDestroyed); }
16.473118
76
0.726501
[ "object" ]
ea404da0ad723efbc2dd26aef23e2ab86761c1d9
4,938
hpp
C++
Algorithm/svgpp/nvprsvg/svg_loader.hpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
32
2016-12-13T05:49:12.000Z
2022-02-04T06:15:47.000Z
Algorithm/svgpp/nvprsvg/svg_loader.hpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
2
2019-07-30T02:01:16.000Z
2020-03-12T15:06:51.000Z
Algorithm/svgpp/nvprsvg/svg_loader.hpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
18
2017-11-16T13:37:06.000Z
2022-03-11T08:13:46.000Z
/* svg_loader.hpp - class declaration for SVG loader */ // Copyright (c) NVIDIA Corporation. All rights reserved. #ifndef __svg_loader_hpp__ #define __svg_loader_hpp__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include "scene.hpp" #include <string> #include <map> using std::map; extern float pixels_per_millimeter; SvgScenePtr svg_loader(const char *xmlFile); struct Gradient; typedef shared_ptr<Gradient> GradientPtr; struct ClipInfo; typedef shared_ptr<ClipInfo> ClipInfoPtr; struct Use; typedef shared_ptr<Use> UsePtr; typedef map<string,GradientPtr> GradientMap; typedef map<string,class TiXmlElement*> UseMap; typedef map<string,ClipInfoPtr> ClipPathMap; // http://www.w3.org/TR/2002/WD-SVG11-20020215/painting.html#SpecifyingPaint struct PaintServer { virtual void resolve(const GradientMap &gradient_map) {} virtual PaintPtr makePaintPtr() = 0; virtual ~PaintServer() {} }; typedef shared_ptr<PaintServer> PaintServerPtr; typedef map<string,PaintServerPtr> PaintServerMap; // http://www.w3.org/TR/2002/WD-SVG11-20020215/color.html#SolidColorElement // The solidColor paint server seems to have gone away in SVG 1.1 2nd edition struct SolidColor : PaintServer { float4 color; SolidColor(const float4 &c) : color(c) { color.a = 1; } SolidColor() : color(float4(0,0,0,1)) {} PaintPtr makePaintPtr() { return SolidColorPaintPtr(new SolidColorPaint(color)); } }; typedef shared_ptr<SolidColor> SolidColorPtr; // http://www.w3.org/TR/2002/WD-SVG11-20020215/pservers.html#Gradients struct Gradient : PaintServer { // Generic gradient attributes enum GradientType { LINEAR, RADIAL } gradient_type; GradientUnits gradient_units; float3x3 gradient_transform; // could be float4x4 SpreadMethod spread_method; GradientStopsPtr gradient_stops; string href; // Linear gradient attributes float2 v1, v2; // Radial gradient attributes float2 c; // center float2 f; // focal point float r; // radius enum UndefinedAttribs { // Gradient generic GRADIENT_UNITS = 0x01, GRADIENT_TRANSFORM = 0x02, SPREAD_METHOD = 0x04, STOP_ARRAY = 0x08, // LinearGradient specific X1 = 0x0100, Y1 = 0x0200, X2 = 0x0400, Y2 = 0x0800, // RadialGradient specific CX = 0x010000, CY = 0x020000, FX = 0x040000, FY = 0x080000, R = 0x100000, ALL = ~0 }; UndefinedAttribs unspecified_attribs; bool resolved; Gradient(GradientType type); virtual void resolve(const GradientMap &gradient_map); void resolveUnspecifiedAttributes(const GradientPtr); inline void markAttribSpecified(UndefinedAttribs attr) { unspecified_attribs = UndefinedAttribs(int(unspecified_attribs) & ~attr); } void setX1(float v) { v1.x = v; markAttribSpecified(X1); } void setY1(float v) { v1.y = v; markAttribSpecified(Y1); } void setX2(float v) { v2.x = v; markAttribSpecified(X2); } void setY2(float v) { v2.y = v; markAttribSpecified(Y2); } void setCX(float v) { c.x = v; markAttribSpecified(CX); } void setCY(float v) { c.y = v; markAttribSpecified(CY); } void setFX(float v) { f.x = v; markAttribSpecified(FX); } void setFY(float v) { f.y = v; markAttribSpecified(FY); } void setR(float v) { r = v; markAttribSpecified(R); } void setUnits(GradientUnits v) { gradient_units = v; markAttribSpecified(GRADIENT_UNITS); } void setTransform(const double3x3 &m) { gradient_transform = m; markAttribSpecified(GRADIENT_TRANSFORM); } void setSpreadMethod(SpreadMethod v) { spread_method = v; markAttribSpecified(SPREAD_METHOD); } void setHref(string v) { href = v; } inline const float3x3 &getGradientTransform() { return gradient_transform; } void initGenericGradientParameters(GradientPaintPtr gradient); }; struct LinearGradient; typedef shared_ptr<LinearGradient> LinearGradientPtr; struct LinearGradient : Gradient { LinearGradient() : Gradient(LINEAR) {} PaintPtr makePaintPtr(); }; struct RadialGradient; typedef shared_ptr<RadialGradient> RadialGradientPtr; struct RadialGradient : Gradient { RadialGradient() : Gradient(RADIAL) {} PaintPtr makePaintPtr(); }; struct ClipInfo { GroupPtr group; ClipInfoPtr clip_info; double3x3 transform; ClipMerge clip_merge; enum { USER_SPACE_ON_USE, OBJECT_BOUNDING_BOX } units; ClipInfo(); NodePtr createClip(NodePtr node); }; #endif // __svg_loader_hpp__
23.514286
81
0.652491
[ "transform" ]
356a76549e2610da4550b9fe95a57be1f5bf6118
1,505
cpp
C++
ad_map_opendrive_reader/src/parser/ControllerParser.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
61
2019-12-19T20:57:24.000Z
2022-03-29T15:20:51.000Z
ad_map_opendrive_reader/src/parser/ControllerParser.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
54
2020-04-05T05:32:47.000Z
2022-03-15T18:42:33.000Z
ad_map_opendrive_reader/src/parser/ControllerParser.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
31
2019-12-20T07:37:39.000Z
2022-03-16T13:06:16.000Z
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma * de Barcelona (UAB). * Copyright (C) 2019-2021 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ #include "opendrive/parser/ControllerParser.h" void opendrive::parser::ControllerParser::Parse(const pugi::xml_node &xmlNode, std::vector<opendrive::Controller> &out_controllers, std::vector<opendrive::ControllerSignal> &out_controller_signals) { for (pugi::xml_node controller_node = xmlNode.child("controller"); controller_node; controller_node = controller_node.next_sibling("controller")) { opendrive::Controller gController; gController.id = std::stoi(controller_node.attribute("id").value()); gController.name = controller_node.attribute("name").value(); gController.sequence = controller_node.attribute("sequence").as_int(); out_controllers.emplace_back(gController); for (pugi::xml_node control_node : controller_node.children("control")) { opendrive::ControllerSignal gControllerSignal; gControllerSignal.id = control_node.attribute("signalId").as_int(); gControllerSignal.type = control_node.attribute("type").value(); out_controller_signals.emplace_back(gControllerSignal); } } }
39.605263
113
0.641196
[ "vector" ]
356c9e392bcfcb0a7a654484f70d1099101f8fe9
3,086
cpp
C++
utils/utils.cpp
Kristian-Popov/Burstcoin-OpenCL-plotter
eb48f4d3dc41dc393321dadd30a1b58141924f4b
[ "Apache-2.0" ]
null
null
null
utils/utils.cpp
Kristian-Popov/Burstcoin-OpenCL-plotter
eb48f4d3dc41dc393321dadd30a1b58141924f4b
[ "Apache-2.0" ]
2
2018-03-04T18:44:47.000Z
2018-06-03T09:51:13.000Z
utils/utils.cpp
Kristian-Popov/Burstcoin-OpenCL-plotter
eb48f4d3dc41dc393321dadd30a1b58141924f4b
[ "Apache-2.0" ]
null
null
null
#include "utils.h" #include <type_traits> #include <boost/format.hpp> #ifdef __linux__ # include <sys/sysinfo.h> #endif // TODO move these functions to separate project/repository namespace Utils { std::string ReadFile( const std::string& fileName ) { std::ifstream stream( fileName ); std::stringbuf buf; if( !stream.is_open() ) { throw std::runtime_error( "File not found" ); } stream >> &buf; stream.close(); return buf.str(); } std::string FormatQuantityString( int value ) { std::string result; if (value % 1000000 == 0) { result = std::to_string(value / 1000000) + "M"; } else if( value % 1000 == 0 ) { result = std::to_string( value / 1000 ) + "K"; } else { result = std::to_string( value); } return result; } long double ChooseConvenientUnit( long double value, const std::vector<long double>& units ) { EXCEPTION_ASSERT( !units.empty() ); EXCEPTION_ASSERT( std::is_sorted( units.begin(), units.end() ) ); // First the biggest unit that is smaller than input value auto resultIter = std::find_if( units.crbegin(), units.crend(), [value] (long double unit ) { return unit < value; } ); long double result = 1.0f; if ( resultIter == units.crend() ) { result = *units.begin(); } else { result = *resultIter; } return result; } long double ChooseConvenientUnit( const std::vector<long double>& values, const std::vector<long double>& units ) { std::vector<long double> convUnits; convUnits.reserve( values.size() ); std::transform( values.begin(), values.end(), std::back_inserter( convUnits ), [&units] (long double value) { return ChooseConvenientUnit(value, units); } ); // Count how many times every unit occurs std::unordered_map<long double, int> counts; for( long double unit: convUnits ) { ++counts[unit]; } EXCEPTION_ASSERT( !counts.empty() ); // TODO find a unit that occurs most frequently auto resultIter = std::max_element( counts.begin(), counts.end(), CompareSecond<long double, int> ); return resultIter->first; } std::string CombineStrings( const std::vector<std::string>& strings, const std::string & delimiter ) { return VectorToString( strings, delimiter ); } // TODO add versions for other OS uint64_t CalcAmountOfFreeRAMInBytes() { #ifdef __linux__ struct sysinfo queryResult; EXCEPTION_ASSERT(sysinfo(&queryResult) == 0); return queryResult.freeram * queryResult.mem_unit; #else // Entering YOLO mode, return 8 GiB return 8 * 1024 * 1024 * 1024; // 8 GiB #endif } }
27.801802
104
0.55606
[ "vector", "transform" ]
356cbbbcb8165d55bc9bc14e0e7f9fdb34ac15a4
3,247
cpp
C++
src/ms_outputformat.cpp
mapsherpa/node-mapserver
0675064c0209d88be82b9830abf042f8e0732d3f
[ "ISC" ]
null
null
null
src/ms_outputformat.cpp
mapsherpa/node-mapserver
0675064c0209d88be82b9830abf042f8e0732d3f
[ "ISC" ]
null
null
null
src/ms_outputformat.cpp
mapsherpa/node-mapserver
0675064c0209d88be82b9830abf042f8e0732d3f
[ "ISC" ]
null
null
null
#include "ms_outputformat.hpp" Nan::Persistent<v8::FunctionTemplate> MSOutputFormat::constructor; void MSOutputFormat::Initialize(v8::Local<v8::Object> target) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(MSOutputFormat::New); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(Nan::New("OutputFormat").ToLocalChecked()); RO_ATTR(tpl, "name", PropertyGetter); RO_ATTR(tpl, "mimetype", PropertyGetter); RO_ATTR(tpl, "driver", PropertyGetter); RO_ATTR(tpl, "extension", PropertyGetter); RO_ATTR(tpl, "renderer", PropertyGetter); RO_ATTR(tpl, "imagemode", PropertyGetter); RO_ATTR(tpl, "transparent", PropertyGetter); target->Set(Nan::New("OutputFormat").ToLocalChecked(), tpl->GetFunction()); constructor.Reset(tpl); } MSOutputFormat::MSOutputFormat(outputFormatObj *of) : ObjectWrap(), this_(of) {} MSOutputFormat::MSOutputFormat() : ObjectWrap(), this_(0) {} MSOutputFormat::~MSOutputFormat() { } NAN_METHOD(MSOutputFormat::New) { MSOutputFormat *obj; if (!info.IsConstructCall()) { Nan::ThrowError("Cannot call constructor as function, you need to use 'new' keyword"); } if (info[0]->IsExternal()) { v8::Local<v8::External> ext = info[0].As<v8::External>(); void* ptr = ext->Value(); obj = static_cast<MSOutputFormat*>(ptr); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); return; } if (!ISSTR(info, 0) || !ISSTR(info,1)) { Nan::ThrowTypeError("MSOutputFormat requires two string arguments"); } outputFormatObj *format = msCreateDefaultOutputFormat(NULL, TOSTR(info[0]), TOSTR(info[1])); /* in the case of unsupported formats, msCreateDefaultOutputFormat should return NULL */ if (!format) { msSetError(MS_MISCERR, "Unsupported format driver: %s", "outputFormatObj()", TOSTR(info[0])); info.GetReturnValue().Set(info.This()); return; } msInitializeRendererVTable(format); /* Else, continue */ format->refcount++; format->inmapfile = MS_TRUE; obj = new MSOutputFormat(format); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } v8::Local<v8::Value> MSOutputFormat::NewInstance(outputFormatObj *of_ptr) { Nan::EscapableHandleScope scope; MSOutputFormat* of = new MSOutputFormat(); of->this_ = of_ptr; v8::Local<v8::Value> ext = Nan::New<v8::External>(of); return scope.Escape(Nan::New(constructor)->GetFunction()->NewInstance(1, &ext)); } NAN_GETTER(MSOutputFormat::PropertyGetter) { MSOutputFormat *of = Nan::ObjectWrap::Unwrap<MSOutputFormat>(info.Holder()); if (STRCMP(property, "name")) { info.GetReturnValue().Set(Nan::New(of->this_->name).ToLocalChecked()); } else if (STRCMP(property, "mimetype")) { info.GetReturnValue().Set(Nan::New(of->this_->mimetype).ToLocalChecked()); } else if (STRCMP(property, "driver")) { info.GetReturnValue().Set(Nan::New(of->this_->driver).ToLocalChecked()); } else if (STRCMP(property, "renderer")) { info.GetReturnValue().Set(of->this_->renderer); } else if (STRCMP(property, "imagemode")) { info.GetReturnValue().Set(of->this_->imagemode); } else if (STRCMP(property, "transparent")) { info.GetReturnValue().Set(of->this_->transparent); } }
34.542553
94
0.691715
[ "object" ]
356cbd6414bc241df3d83139abda9667b424960d
1,419
cpp
C++
Competitive Programming/Dynamic Programming Intro/CSES Problem Set/removingDigits.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
1
2022-03-24T06:38:53.000Z
2022-03-24T06:38:53.000Z
Competitive Programming/Dynamic Programming Intro/CSES Problem Set/removingDigits.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
null
null
null
Competitive Programming/Dynamic Programming Intro/CSES Problem Set/removingDigits.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long int #define ld long double #define mod 1000000007 #define inf 1e18 #define endl "\n" #define pb emplace_back #define vi vector<ll> #define vs vector<string> #define pii pair<ll,ll> #define ump unordered_map #define mp map #define pq_max priority_queue<ll> #define pq_min priority_queue<ll,vi,greater<ll> > #define ff first #define ss second #define mid(l,r) (l+(r-l)/2) #define loop(i,a,b) for(int i=(a);i<=(b);i++) #define looprev(i,a,b) for(int i=(a);i>=(b);i--) #define log(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); } #define logarr(arr,a,b) for(int z=(a);z<=(b);z++) cout<<(arr[z])<<" ";cout<<endl; #define token(str,ch) (std::istringstream var((str)); vs v; string t; while(getline((var), t, (ch))) {v.pb(t);} return v;) vi getDigits(int n) { vi result; while(n) { if(n%10 !=0) { result.pb(n%10); } n/=10; } return result; } int main(int argc, char const *argv[]) { int n; cin>>n; vi dp(n+1, INT_MAX); loop(i, 1, 9) { dp[i] = 1; } loop(i, 10, n) { vi digits = getDigits(i); loop(j, 0, digits.size() - 1) { dp[i] = min(dp[i], 1+dp[i-digits[j]]); } } cout<<dp[n]; return 0; // n-1,2,3,4,5,6,7,8,9 }
25.8
158
0.568006
[ "vector" ]
357cac670ac0509134f1255a118ac3bda7ebc2a5
401
cpp
C++
275.cpp
zhangchbin/LeetRecord
7f377b1a61e8f2a6fd86d028911c2722c1d03650
[ "MIT" ]
1
2020-09-12T07:38:23.000Z
2020-09-12T07:38:23.000Z
275.cpp
zhangchbin/LeetRecord
7f377b1a61e8f2a6fd86d028911c2722c1d03650
[ "MIT" ]
1
2020-09-12T07:38:27.000Z
2020-09-12T07:40:26.000Z
275.cpp
zhangchbin/LeetRecord
7f377b1a61e8f2a6fd86d028911c2722c1d03650
[ "MIT" ]
null
null
null
class Solution { public: int hIndex(vector<int>& citations) { int l = 0, r = citations.size()-1; int mid; int ans = citations.size(); while(l <= r){ mid=(l+r)/2; if(citations[mid]<(citations.size()-mid)){ l = mid+1; } else r = mid-1, ans=mid; } return citations.size()-ans; } };
21.105263
54
0.438903
[ "vector" ]
357e682eae89b631870254d7cc785c400f6e183f
2,630
cpp
C++
aws-cpp-sdk-compute-optimizer/source/model/LambdaFunctionRecommendationFinding.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-compute-optimizer/source/model/LambdaFunctionRecommendationFinding.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-compute-optimizer/source/model/LambdaFunctionRecommendationFinding.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/compute-optimizer/model/LambdaFunctionRecommendationFinding.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ComputeOptimizer { namespace Model { namespace LambdaFunctionRecommendationFindingMapper { static const int Optimized_HASH = HashingUtils::HashString("Optimized"); static const int NotOptimized_HASH = HashingUtils::HashString("NotOptimized"); static const int Unavailable_HASH = HashingUtils::HashString("Unavailable"); LambdaFunctionRecommendationFinding GetLambdaFunctionRecommendationFindingForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == Optimized_HASH) { return LambdaFunctionRecommendationFinding::Optimized; } else if (hashCode == NotOptimized_HASH) { return LambdaFunctionRecommendationFinding::NotOptimized; } else if (hashCode == Unavailable_HASH) { return LambdaFunctionRecommendationFinding::Unavailable; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<LambdaFunctionRecommendationFinding>(hashCode); } return LambdaFunctionRecommendationFinding::NOT_SET; } Aws::String GetNameForLambdaFunctionRecommendationFinding(LambdaFunctionRecommendationFinding enumValue) { switch(enumValue) { case LambdaFunctionRecommendationFinding::Optimized: return "Optimized"; case LambdaFunctionRecommendationFinding::NotOptimized: return "NotOptimized"; case LambdaFunctionRecommendationFinding::Unavailable: return "Unavailable"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace LambdaFunctionRecommendationFindingMapper } // namespace Model } // namespace ComputeOptimizer } // namespace Aws
33.717949
114
0.6673
[ "model" ]
358bd9e9bbecc5e167aedc61b75c17c1e1a8a53d
19,266
cpp
C++
src/test/tests.cpp
kattkieru/palladio
7fca9d56244d5445f2ff7fe10b3f27423e86eb06
[ "Apache-2.0" ]
null
null
null
src/test/tests.cpp
kattkieru/palladio
7fca9d56244d5445f2ff7fe10b3f27423e86eb06
[ "Apache-2.0" ]
null
null
null
src/test/tests.cpp
kattkieru/palladio
7fca9d56244d5445f2ff7fe10b3f27423e86eb06
[ "Apache-2.0" ]
1
2020-02-16T00:53:52.000Z
2020-02-16T00:53:52.000Z
/* * Copyright 2014-2018 Esri R&D Zurich and VRBN * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TestCallbacks.h" #include "TestUtils.h" #include "../palladio/PRTContext.h" #include "../palladio/Utils.h" #include "../palladio/ModelConverter.h" #include "../palladio/AttributeConversion.h" #include "../codec/encoder/HoudiniEncoder.h" #include "prt/AttributeMap.h" #include "prtx/Geometry.h" #include "boost/filesystem/path.hpp" #define CATCH_CONFIG_RUNNER #include "catch.hpp" #include <algorithm> namespace { PRTContextUPtr prtCtx; const boost::filesystem::path testDataPath = TEST_DATA_PATH; } // namespace int main( int argc, char* argv[] ) { assert(!prtCtx); const std::vector<boost::filesystem::path> addExtDirs = { "../lib", // adapt to default prt dir layout (core is in bin subdir) HOUDINI_CODEC_PATH // set to absolute path to houdini encoder lib via cmake }; prtCtx.reset(new PRTContext(addExtDirs)); int result = Catch::Session().run( argc, argv ); prtCtx.reset(); return result; } TEST_CASE("create file URI from path", "[utils]" ) { #ifdef PLD_LINUX const auto u = toFileURI(boost::filesystem::path("/tmp/foo.txt")); CHECK(u.compare(L"file:/tmp/foo.txt") == 0); #elif defined(PLD_WINDOWS) const auto u = toFileURI(boost::filesystem::path("c:\\tmp\\foo.txt")); INFO(toOSNarrowFromUTF16(u)); CHECK(u.compare(L"file:/c:/tmp/foo.txt") == 0); #endif } TEST_CASE("percent-encode a UTF-8 string", "[utils]") { CHECK(percentEncode("with space") == L"with%20space"); } TEST_CASE("get XML representation of a PRT object", "[utils]") { AttributeMapBuilderUPtr amb(prt::AttributeMapBuilder::create()); amb->setString(L"foo", L"bar"); AttributeMapUPtr am(amb->createAttributeMap()); std::string xml = objectToXML(am.get()); CHECK(xml == "<attributable>\n\t<attribute key=\"foo\" value=\"bar\" type=\"str\"/>\n</attributable>"); // TODO: use R? } TEST_CASE("replace chars not in set", "[utils]") { const std::wstring ac = L"abc"; SECTION("basic") { std::wstring s = L"abc_def"; replace_all_not_of(s, ac); CHECK(s == L"abc____"); } SECTION("empty") { std::wstring s = L""; replace_all_not_of(s, ac); CHECK(s == L""); } SECTION("one char") { std::wstring s = L" "; replace_all_not_of(s, ac); CHECK(s == L"_"); } SECTION("one allowed char") { std::wstring s = L"_"; replace_all_not_of(s, ac); CHECK(s == L"_"); } } TEST_CASE("separate fully qualified name into style and name", "[NameConversion]") { std::wstring style, name; SECTION("default case") { NameConversion::separate(L"foo$bar", style, name); CHECK(style == L"foo"); CHECK(name == L"bar"); } SECTION("no style") { NameConversion::separate(L"foo", style, name); CHECK(style.empty()); CHECK(name == L"foo"); } SECTION("edge case 1") { NameConversion::separate(L"foo$", style, name); CHECK(style == L"foo"); CHECK(name.empty()); } SECTION("edge case 2") { NameConversion::separate(L"$foo", style, name); CHECK(style.empty()); CHECK(name == L"foo"); } SECTION("separator only") { NameConversion::separate(L"$", style, name); CHECK(style.empty()); CHECK(name.empty()); } SECTION("empty") { NameConversion::separate(L"", style, name); CHECK(style.empty()); CHECK(name.empty()); } SECTION("two separators") { NameConversion::separate(L"foo$bar$baz", style, name); CHECK(style == L"foo"); CHECK(name == L"bar$baz"); } } TEST_CASE("extract attribute names", "[AttributeConversion]") { AttributeMapBuilderUPtr amb(prt::AttributeMapBuilder::create()); amb->setFloat(L"foo", 1.23); amb->setFloat(L"bar.r", 1.0); amb->setFloat(L"bar.g", 0.5); amb->setFloat(L"bar.b", 0.3); amb->setString(L"baz.r", L"a"); amb->setString(L"baz.g", L"b"); amb->setString(L"baz.b", L"c"); amb->setString(L"same.ext", L"foo"); amb->setFloat(L"same", 3.0); AttributeMapUPtr am(amb->createAttributeMap()); AttributeConversion::HandleMap hm; AttributeConversion::extractAttributeNames(hm, am.get()); REQUIRE(hm.size() == 7); SECTION("simple") { const auto& ph = hm.at("foo"); const std::vector<std::wstring> expKeys = { L"foo" }; CHECK(ph.keys == expKeys); CHECK(ph.type == prt::AttributeMap::PT_FLOAT); CHECK(ph.handleType.which() == 0); // houdini handle type must not be changed } SECTION("group rgb floats") { const auto& ph = hm.at("bar"); const std::vector<std::wstring> expKeys = { L"bar.r", L"bar.g", L"bar.b" }; CHECK(ph.keys == expKeys); CHECK(ph.type == prt::AttributeMap::PT_FLOAT); CHECK(ph.handleType.which() == 0); // houdini handle type must not be changed } SECTION("don't group strings") { REQUIRE(hm.count("baz") == 0); const auto& ph = hm.at("baz__r"); const std::vector<std::wstring> expKeys = { L"baz.r" }; CHECK(ph.keys == expKeys); CHECK(ph.type == prt::AttributeMap::PT_STRING); CHECK(ph.handleType.which() == 0); // houdini handle type must not be changed } SECTION("same primary key") { const auto& ph = hm.at("same"); const std::vector<std::wstring> expKeys = { L"same" }; CHECK(ph.keys == expKeys); CHECK(ph.type == prt::AttributeMap::PT_FLOAT); CHECK(ph.handleType.which() == 0); // houdini handle type must not be changed } SECTION("same.ext primary key") { const auto& ph = hm.at("same__ext"); const std::vector<std::wstring> expKeys = { L"same.ext" }; CHECK(ph.keys == expKeys); CHECK(ph.type == prt::AttributeMap::PT_STRING); CHECK(ph.handleType.which() == 0); // houdini handle type must not be changed } } TEST_CASE("deserialize uv set", "[ModelConversion]") { const prtx::IndexVector faceCnt = { 4 }; const prtx::IndexVector uvCounts = { 4, 4 }; const prtx::IndexVector uvIdx = { 3, 2, 1, 0, 4, 5, 6, 7 }; std::vector<uint32_t> uvIndicesPerSet; SECTION("test uv set 0") { ModelConversion::getUVSet(uvIndicesPerSet, faceCnt.data(), faceCnt.size(), uvCounts.data(), uvCounts.size(), 0, 2, uvIdx.data(), uvIdx.size()); const prtx::IndexVector uvIndicesPerSetExp = { 3, 2, 1, 0 }; CHECK(uvIndicesPerSet == uvIndicesPerSetExp); } SECTION("test uv set 1") { ModelConversion::getUVSet(uvIndicesPerSet, faceCnt.data(), faceCnt.size(), uvCounts.data(), uvCounts.size(), 1, 2, uvIdx.data(), uvIdx.size()); const prtx::IndexVector uvIndicesPerSetExp = { 4, 5, 6, 7 }; CHECK(uvIndicesPerSet == uvIndicesPerSetExp); } } // -- encoder test cases TEST_CASE("serialize basic mesh") { const prtx::IndexVector faceCnt = { 4 }; const prtx::DoubleVector vtx = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0 }; const prtx::IndexVector vtxInd = { 0, 1, 2, 3 }; const prtx::IndexVector vtxIndRev = [&vtxInd]() { auto c = vtxInd; std::reverse_copy(vtxInd.begin(), vtxInd.end(), c.begin()); return c; }(); prtx::MeshBuilder mb; mb.addVertexCoords(vtx); uint32_t faceIdx = mb.addFace(); mb.setFaceVertexIndices(faceIdx, vtxInd); prtx::GeometryBuilder gb; gb.addMesh(mb.createShared()); auto geo = gb.createShared(); CHECK(geo->getMeshes().front()->getUVSetsCount() == 0); const prtx::GeometryPtrVector geos = { geo }; SerializedGeometry sg; serializeGeometry(sg, geos); CHECK(sg.counts == faceCnt); CHECK(sg.coords == vtx); CHECK(sg.indices == vtxIndRev); // reverses winding CHECK(sg.uvSets == 0); const prtx::IndexVector uvCountsExp = { }; CHECK(sg.uvCounts == uvCountsExp); } TEST_CASE("serialize mesh with one uv set") { const prtx::IndexVector faceCnt = { 4 }; const prtx::DoubleVector vtx = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0 }; const prtx::IndexVector vtxIdx = { 0, 1, 2, 3 }; const prtx::DoubleVector uvs = { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0 }; const prtx::IndexVector uvIdx = { 0, 1, 2, 3 }; prtx::MeshBuilder mb; mb.addVertexCoords(vtx); mb.addUVCoords(0, uvs); uint32_t faceIdx = mb.addFace(); mb.setFaceVertexIndices(faceIdx, vtxIdx); mb.setFaceUVIndices(faceIdx, 0, uvIdx); const auto m = mb.createShared(); CHECK(m->getUVSetsCount() == 2); // TODO: correct would be 1!!! prtx::GeometryBuilder gb; gb.addMesh(m); auto geo = gb.createShared(); const prtx::GeometryPtrVector geos = { geo }; SerializedGeometry sg; serializeGeometry(sg, geos); CHECK(sg.counts == faceCnt); CHECK(sg.coords == vtx); const prtx::IndexVector vtxIdxExp = { 3, 2, 1, 0 }; CHECK(sg.indices == vtxIdxExp); CHECK(sg.uvCoords == uvs); CHECK(sg.uvSets == 2); // TODO: actually wrong expected value const prtx::IndexVector uvCountsExp = { 4, 0 }; CHECK(sg.uvCounts == uvCountsExp); const prtx::IndexVector uvIdxExp = { 3, 2, 1, 0 }; CHECK(sg.uvIndices == uvIdxExp); } TEST_CASE("serialize mesh with two uv sets") { const prtx::IndexVector faceCnt = { 4 }; const prtx::DoubleVector vtx = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0 }; const prtx::IndexVector vtxIdx = { 0, 1, 2, 3 }; const prtx::DoubleVector uvs0 = { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0 }; const prtx::IndexVector uvIdx0 = { 0, 1, 2, 3 }; const prtx::DoubleVector uvs1 = { 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.0, 0.5 }; const prtx::IndexVector uvIdx1 = { 3, 2, 1, 0 }; prtx::MeshBuilder mb; mb.addVertexCoords(vtx); mb.addUVCoords(0, uvs0); mb.addUVCoords(1, uvs1); uint32_t faceIdx = mb.addFace(); mb.setFaceVertexIndices(faceIdx, vtxIdx); mb.setFaceUVIndices(faceIdx, 0, uvIdx0); mb.setFaceUVIndices(faceIdx, 1, uvIdx1); const auto m = mb.createShared(); CHECK(m->getUVSetsCount() == 2); prtx::GeometryBuilder gb; gb.addMesh(m); auto geo = gb.createShared(); const prtx::GeometryPtrVector geos = { geo }; SerializedGeometry sg; serializeGeometry(sg, geos); CHECK(sg.counts == faceCnt); CHECK(sg.coords == vtx); const prtx::IndexVector vtxIdxExp = { 3, 2, 1, 0 }; CHECK(sg.indices == vtxIdxExp); const prtx::DoubleVector uvsExp = { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.0, 0.5 }; CHECK(sg.uvCoords == uvsExp); CHECK(sg.uvSets == 2); const prtx::IndexVector uvCountsExp = { 4, 4 }; CHECK(sg.uvCounts == uvCountsExp); const prtx::IndexVector uvIdxExp = { 3, 2, 1, 0, 4, 5, 6, 7 }; CHECK(sg.uvIndices == uvIdxExp); } TEST_CASE("serialize mesh with two non-consecutive uv sets") { const prtx::IndexVector faceCnt = { 4 }; const prtx::DoubleVector vtx = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0 }; const prtx::IndexVector vtxIdx = { 0, 1, 2, 3 }; const prtx::DoubleVector uvs0 = { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0 }; const prtx::IndexVector uvIdx0 = { 0, 1, 2, 3 }; const prtx::DoubleVector uvs2 = { 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.0, 0.5 }; const prtx::IndexVector uvIdx2 = { 3, 2, 1, 0 }; prtx::MeshBuilder mb; mb.addVertexCoords(vtx); mb.addUVCoords(0, uvs0); mb.addUVCoords(2, uvs2); uint32_t faceIdx = mb.addFace(); mb.setFaceVertexIndices(faceIdx, vtxIdx); mb.setFaceUVIndices(faceIdx, 0, uvIdx0); mb.setFaceUVIndices(faceIdx, 2, uvIdx2); const auto m = mb.createShared(); CHECK(m->getUVSetsCount() == 4); // TODO: this is wrong! prtx::GeometryBuilder gb; gb.addMesh(m); auto geo = gb.createShared(); const prtx::GeometryPtrVector geos = { geo }; SerializedGeometry sg; serializeGeometry(sg, geos); CHECK(sg.counts == faceCnt); CHECK(sg.coords == vtx); const prtx::IndexVector vtxIdxExp = { 3, 2, 1, 0 }; CHECK(sg.indices == vtxIdxExp); const prtx::DoubleVector uvsExp = { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.0, 0.5 }; CHECK(sg.uvCoords == uvsExp); CHECK(sg.uvSets == 4); // TODO: wrong! const prtx::IndexVector uvCountsExp = { 4, 0, 4, 0 }; CHECK(sg.uvCounts == uvCountsExp); const prtx::IndexVector uvIdxExp = { 3, 2, 1, 0, 4, 5, 6, 7 }; CHECK(sg.uvIndices == uvIdxExp); } TEST_CASE("serialize mesh with mixed face uvs (one uv set)") { const prtx::IndexVector faceCnt = { 4, 3, 5 }; const prtx::DoubleVector vtx = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0 }; const prtx::IndexVector vtxIdx[] = { { 0, 1, 2, 3 }, { 0, 1, 4 }, { 0, 1, 2, 3, 4 } }; const prtx::DoubleVector uvs = { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0 }; const prtx::IndexVector uvIdx[] = { { 0, 1, 2, 3 }, { }, { 0, 1, 2, 3, 0 } }; // face 1 has no uvs prtx::MeshBuilder mb; mb.addVertexCoords(vtx); mb.addUVCoords(0, uvs); mb.addFace(); mb.setFaceVertexIndices(0, vtxIdx[0]); mb.setFaceUVIndices(0, 0, uvIdx[0]); mb.addFace(); mb.setFaceVertexIndices(1, vtxIdx[1]); mb.setFaceUVIndices(1, 0, uvIdx[1]); // has no uvs mb.addFace(); mb.setFaceVertexIndices(2, vtxIdx[2]); mb.setFaceUVIndices(2, 0, uvIdx[2]); const auto m = mb.createShared(); CHECK(m->getUVSetsCount() == 2); // TODO prtx::GeometryBuilder gb; gb.addMesh(m); auto geo = gb.createShared(); const prtx::GeometryPtrVector geos = { geo }; SerializedGeometry sg; serializeGeometry(sg, geos); CHECK(sg.counts == faceCnt); CHECK(sg.coords == vtx); const prtx::IndexVector vtxIdxExp = { 3, 2, 1, 0, 4, 1, 0, 4, 3, 2, 1, 0 }; CHECK(sg.indices == vtxIdxExp); CHECK(sg.uvCoords == uvs); CHECK(sg.uvSets == 2); // TODO const prtx::IndexVector uvCountsExp = { 4, 0, 0, 0, 5, 0 }; CHECK(sg.uvCounts == uvCountsExp); const prtx::IndexVector uvIdxExp = { 3, 2, 1, 0, 0, 3, 2, 1, 0 }; CHECK(sg.uvIndices == uvIdxExp); } TEST_CASE("serialize two meshes with one uv set") { const prtx::IndexVector faceCnt = {4}; const prtx::DoubleVector vtx = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0}; const prtx::IndexVector vtxIdx = {0, 1, 2, 3}; const prtx::DoubleVector uvs = {0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0}; const prtx::IndexVector uvIdx = {0, 1, 2, 3}; prtx::MeshBuilder mb; mb.addVertexCoords(vtx); mb.addUVCoords(0, uvs); uint32_t faceIdx = mb.addFace(); mb.setFaceVertexIndices(faceIdx, vtxIdx); mb.setFaceUVIndices(faceIdx, 0, uvIdx); const auto m1 = mb.createShared(); const auto m2 = mb.createShared(); CHECK(m1->getUVSetsCount() == 2); // TODO CHECK(m2->getUVSetsCount() == 2); // TODO prtx::GeometryBuilder gb; gb.addMesh(m1); gb.addMesh(m2); auto geo = gb.createShared(); const prtx::GeometryPtrVector geos = {geo}; SerializedGeometry sg; serializeGeometry(sg, geos); const prtx::IndexVector expFaceCnt = {4, 4}; CHECK(sg.counts == expFaceCnt); const prtx::DoubleVector expVtx = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0 }; CHECK(sg.coords == expVtx); const prtx::IndexVector expVtxIdx = { 3, 2, 1, 0, 7, 6, 5, 4 }; CHECK(sg.indices == expVtxIdx); const prtx::DoubleVector expUvs = { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0 }; CHECK(sg.uvCoords == expUvs); CHECK(sg.uvSets == 2); // TODO: actually wrong expected value const prtx::IndexVector uvCountsExp = { 4, 0, 4, 0 }; CHECK(sg.uvCounts == uvCountsExp); const prtx::IndexVector expUvIdx = { 3, 2, 1, 0, 7, 6, 5, 4 }; CHECK(sg.uvIndices == expUvIdx); } TEST_CASE("generate two cubes with two uv sets") { const std::vector<boost::filesystem::path> initialShapeSources = { testDataPath / "quad0.obj", testDataPath / "quad1.obj" }; const std::vector<std::wstring> initialShapeURIs = { toFileURI(initialShapeSources[0]), toFileURI(initialShapeSources[1]) }; const std::vector<std::wstring> startRules = { L"Default$OneSet", L"Default$TwoSets" }; const boost::filesystem::path rpkPath = testDataPath / "uvsets.rpk"; const std::wstring ruleFile = L"bin/r1.cgb"; TestCallbacks tc; generate(tc, prtCtx, rpkPath, ruleFile, initialShapeURIs, startRules); REQUIRE(tc.results.size() == 2); // TODO: also check actual coordinates etc { const CallbackResult& cr = tc.results[0]; CHECK(cr.name == L"shape0"); const std::vector<uint32_t> cntsExp = { 4, 4, 4, 4, 4, 4 }; CHECK(cr.cnts == cntsExp); const std::vector<uint32_t> idxExp = { 3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12, 19, 18, 17, 16, 23, 22, 21, 20 }; CHECK(cr.idx == idxExp); const std::vector<uint32_t> uvCntsExp = { 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0 }; CHECK(cr.uvCnts == uvCntsExp); const std::vector<uint32_t> uvIdxExp = { 3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12, 19, 18, 17, 16, 23, 22, 21, 20 }; CHECK(cr.uvIdx == uvIdxExp); CHECK(cr.uvSets == 2); const std::vector<uint32_t> faceRangesExp = { 0, 6 }; CHECK(cr.faceRanges == faceRangesExp); } { const CallbackResult& cr = tc.results[1]; CHECK(cr.name == L"shape1"); const std::vector<uint32_t> cntsExp = { 4, 4, 4, 4, 4, 4 }; CHECK(cr.cnts == cntsExp); const std::vector<uint32_t> idxExp = { 3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12, 19, 18, 17, 16, 23, 22, 21, 20 }; CHECK(cr.idx == idxExp); const std::vector<uint32_t> uvCntsExp = { 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0 }; CHECK(cr.uvCnts == uvCntsExp); const std::vector<uint32_t> uvIdxExp = { 3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12, 19, 18, 17, 16, 23, 22, 21, 20, 27, 26, 25, 24, 31, 30, 29, 28, 35, 34, 33, 32, 39, 38, 37, 36, 43, 42, 41, 40, 47, 46, 45, 44 }; CHECK(cr.uvIdx == uvIdxExp); CHECK(cr.uvSets == 4); const std::vector<uint32_t> faceRangesExp = { 0, 1, 2, 3, 4, 5, 6 }; CHECK(cr.faceRanges == faceRangesExp); } } TEST_CASE("generate with generic attributes") { const std::vector<boost::filesystem::path> initialShapeSources = { testDataPath / "quad0.obj" }; const std::vector<std::wstring> initialShapeURIs = { toFileURI(initialShapeSources[0]) }; const std::vector<std::wstring> startRules = { L"Default$Init" }; const boost::filesystem::path rpkPath = testDataPath / "GenAttrs1.rpk"; const std::wstring ruleFile = L"bin/r1.cgb"; TestCallbacks tc; generate(tc, prtCtx, rpkPath, ruleFile, initialShapeURIs, startRules); REQUIRE(tc.results.size() == 1); const CallbackResult& cr = tc.results[0]; const std::vector<uint32_t> faceRangesExp = { 0, 6, 12 }; CHECK(cr.faceRanges == faceRangesExp); REQUIRE(cr.attrsPerShapeID.size() == 2); { const auto& a = cr.attrsPerShapeID.at(4); CHECK(std::wcscmp(a->getString(L"Default$foo"), L"bar") == 0); } { const auto& a = cr.attrsPerShapeID.at(5); CHECK(std::wcscmp(a->getString(L"Default$foo"), L"baz") == 0); } }
31.429038
145
0.627271
[ "mesh", "geometry", "object", "vector" ]
35928eb03d0f32cc95d2bed85745c05c66b20fb8
580,032
cpp
C++
glslang/MachineIndependent/glslang_tab.cpp
cmarcelo/glslang
d352577a99cfbd1dca01cf19ae3b2b988b662922
[ "Apache-2.0" ]
null
null
null
glslang/MachineIndependent/glslang_tab.cpp
cmarcelo/glslang
d352577a99cfbd1dca01cf19ae3b2b988b662922
[ "Apache-2.0" ]
null
null
null
glslang/MachineIndependent/glslang_tab.cpp
cmarcelo/glslang
d352577a99cfbd1dca01cf19ae3b2b988b662922
[ "Apache-2.0" ]
null
null
null
/* A Bison parser, made by GNU Bison 3.7.5. */ /* Bison implementation 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 <http://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. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* 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. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output, and Bison version. */ #define YYBISON 30705 /* Bison version string. */ #define YYBISON_VERSION "3.7.5" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* First part of user prologue. */ #line 69 "MachineIndependent/glslang.y" /* Based on: ANSI C Yacc grammar In 1985, Jeff Lee published his Yacc grammar (which is accompanied by a matching Lex specification) for the April 30, 1985 draft version of the ANSI C standard. Tom Stockfisch reposted it to net.sources in 1987; that original, as mentioned in the answer to question 17.25 of the comp.lang.c FAQ, can be ftp'ed from ftp.uu.net, file usenet/net.sources/ansi.c.grammar.Z. I intend to keep this version as close to the current C Standard grammar as possible; please let me know if you discover discrepancies. Jutta Degener, 1995 */ #include "SymbolTable.h" #include "ParseHelper.h" #include "../Public/ShaderLang.h" #include "attribute.h" using namespace glslang; #line 97 "MachineIndependent/glslang_tab.cpp" # ifndef YY_CAST # ifdef __cplusplus # define YY_CAST(Type, Val) static_cast<Type> (Val) # define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val) # else # define YY_CAST(Type, Val) ((Type) (Val)) # define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) # endif # endif # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif #include "glslang_tab.cpp.h" /* Symbol kind. */ enum yysymbol_kind_t { YYSYMBOL_YYEMPTY = -2, YYSYMBOL_YYEOF = 0, /* "end of file" */ YYSYMBOL_YYerror = 1, /* error */ YYSYMBOL_YYUNDEF = 2, /* "invalid token" */ YYSYMBOL_CONST = 3, /* CONST */ YYSYMBOL_BOOL = 4, /* BOOL */ YYSYMBOL_INT = 5, /* INT */ YYSYMBOL_UINT = 6, /* UINT */ YYSYMBOL_FLOAT = 7, /* FLOAT */ YYSYMBOL_BVEC2 = 8, /* BVEC2 */ YYSYMBOL_BVEC3 = 9, /* BVEC3 */ YYSYMBOL_BVEC4 = 10, /* BVEC4 */ YYSYMBOL_IVEC2 = 11, /* IVEC2 */ YYSYMBOL_IVEC3 = 12, /* IVEC3 */ YYSYMBOL_IVEC4 = 13, /* IVEC4 */ YYSYMBOL_UVEC2 = 14, /* UVEC2 */ YYSYMBOL_UVEC3 = 15, /* UVEC3 */ YYSYMBOL_UVEC4 = 16, /* UVEC4 */ YYSYMBOL_VEC2 = 17, /* VEC2 */ YYSYMBOL_VEC3 = 18, /* VEC3 */ YYSYMBOL_VEC4 = 19, /* VEC4 */ YYSYMBOL_MAT2 = 20, /* MAT2 */ YYSYMBOL_MAT3 = 21, /* MAT3 */ YYSYMBOL_MAT4 = 22, /* MAT4 */ YYSYMBOL_MAT2X2 = 23, /* MAT2X2 */ YYSYMBOL_MAT2X3 = 24, /* MAT2X3 */ YYSYMBOL_MAT2X4 = 25, /* MAT2X4 */ YYSYMBOL_MAT3X2 = 26, /* MAT3X2 */ YYSYMBOL_MAT3X3 = 27, /* MAT3X3 */ YYSYMBOL_MAT3X4 = 28, /* MAT3X4 */ YYSYMBOL_MAT4X2 = 29, /* MAT4X2 */ YYSYMBOL_MAT4X3 = 30, /* MAT4X3 */ YYSYMBOL_MAT4X4 = 31, /* MAT4X4 */ YYSYMBOL_SAMPLER2D = 32, /* SAMPLER2D */ YYSYMBOL_SAMPLER3D = 33, /* SAMPLER3D */ YYSYMBOL_SAMPLERCUBE = 34, /* SAMPLERCUBE */ YYSYMBOL_SAMPLER2DSHADOW = 35, /* SAMPLER2DSHADOW */ YYSYMBOL_SAMPLERCUBESHADOW = 36, /* SAMPLERCUBESHADOW */ YYSYMBOL_SAMPLER2DARRAY = 37, /* SAMPLER2DARRAY */ YYSYMBOL_SAMPLER2DARRAYSHADOW = 38, /* SAMPLER2DARRAYSHADOW */ YYSYMBOL_ISAMPLER2D = 39, /* ISAMPLER2D */ YYSYMBOL_ISAMPLER3D = 40, /* ISAMPLER3D */ YYSYMBOL_ISAMPLERCUBE = 41, /* ISAMPLERCUBE */ YYSYMBOL_ISAMPLER2DARRAY = 42, /* ISAMPLER2DARRAY */ YYSYMBOL_USAMPLER2D = 43, /* USAMPLER2D */ YYSYMBOL_USAMPLER3D = 44, /* USAMPLER3D */ YYSYMBOL_USAMPLERCUBE = 45, /* USAMPLERCUBE */ YYSYMBOL_USAMPLER2DARRAY = 46, /* USAMPLER2DARRAY */ YYSYMBOL_SAMPLER = 47, /* SAMPLER */ YYSYMBOL_SAMPLERSHADOW = 48, /* SAMPLERSHADOW */ YYSYMBOL_TEXTURE2D = 49, /* TEXTURE2D */ YYSYMBOL_TEXTURE3D = 50, /* TEXTURE3D */ YYSYMBOL_TEXTURECUBE = 51, /* TEXTURECUBE */ YYSYMBOL_TEXTURE2DARRAY = 52, /* TEXTURE2DARRAY */ YYSYMBOL_ITEXTURE2D = 53, /* ITEXTURE2D */ YYSYMBOL_ITEXTURE3D = 54, /* ITEXTURE3D */ YYSYMBOL_ITEXTURECUBE = 55, /* ITEXTURECUBE */ YYSYMBOL_ITEXTURE2DARRAY = 56, /* ITEXTURE2DARRAY */ YYSYMBOL_UTEXTURE2D = 57, /* UTEXTURE2D */ YYSYMBOL_UTEXTURE3D = 58, /* UTEXTURE3D */ YYSYMBOL_UTEXTURECUBE = 59, /* UTEXTURECUBE */ YYSYMBOL_UTEXTURE2DARRAY = 60, /* UTEXTURE2DARRAY */ YYSYMBOL_ATTRIBUTE = 61, /* ATTRIBUTE */ YYSYMBOL_VARYING = 62, /* VARYING */ YYSYMBOL_FLOAT16_T = 63, /* FLOAT16_T */ YYSYMBOL_FLOAT32_T = 64, /* FLOAT32_T */ YYSYMBOL_DOUBLE = 65, /* DOUBLE */ YYSYMBOL_FLOAT64_T = 66, /* FLOAT64_T */ YYSYMBOL_INT64_T = 67, /* INT64_T */ YYSYMBOL_UINT64_T = 68, /* UINT64_T */ YYSYMBOL_INT32_T = 69, /* INT32_T */ YYSYMBOL_UINT32_T = 70, /* UINT32_T */ YYSYMBOL_INT16_T = 71, /* INT16_T */ YYSYMBOL_UINT16_T = 72, /* UINT16_T */ YYSYMBOL_INT8_T = 73, /* INT8_T */ YYSYMBOL_UINT8_T = 74, /* UINT8_T */ YYSYMBOL_I64VEC2 = 75, /* I64VEC2 */ YYSYMBOL_I64VEC3 = 76, /* I64VEC3 */ YYSYMBOL_I64VEC4 = 77, /* I64VEC4 */ YYSYMBOL_U64VEC2 = 78, /* U64VEC2 */ YYSYMBOL_U64VEC3 = 79, /* U64VEC3 */ YYSYMBOL_U64VEC4 = 80, /* U64VEC4 */ YYSYMBOL_I32VEC2 = 81, /* I32VEC2 */ YYSYMBOL_I32VEC3 = 82, /* I32VEC3 */ YYSYMBOL_I32VEC4 = 83, /* I32VEC4 */ YYSYMBOL_U32VEC2 = 84, /* U32VEC2 */ YYSYMBOL_U32VEC3 = 85, /* U32VEC3 */ YYSYMBOL_U32VEC4 = 86, /* U32VEC4 */ YYSYMBOL_I16VEC2 = 87, /* I16VEC2 */ YYSYMBOL_I16VEC3 = 88, /* I16VEC3 */ YYSYMBOL_I16VEC4 = 89, /* I16VEC4 */ YYSYMBOL_U16VEC2 = 90, /* U16VEC2 */ YYSYMBOL_U16VEC3 = 91, /* U16VEC3 */ YYSYMBOL_U16VEC4 = 92, /* U16VEC4 */ YYSYMBOL_I8VEC2 = 93, /* I8VEC2 */ YYSYMBOL_I8VEC3 = 94, /* I8VEC3 */ YYSYMBOL_I8VEC4 = 95, /* I8VEC4 */ YYSYMBOL_U8VEC2 = 96, /* U8VEC2 */ YYSYMBOL_U8VEC3 = 97, /* U8VEC3 */ YYSYMBOL_U8VEC4 = 98, /* U8VEC4 */ YYSYMBOL_DVEC2 = 99, /* DVEC2 */ YYSYMBOL_DVEC3 = 100, /* DVEC3 */ YYSYMBOL_DVEC4 = 101, /* DVEC4 */ YYSYMBOL_DMAT2 = 102, /* DMAT2 */ YYSYMBOL_DMAT3 = 103, /* DMAT3 */ YYSYMBOL_DMAT4 = 104, /* DMAT4 */ YYSYMBOL_F16VEC2 = 105, /* F16VEC2 */ YYSYMBOL_F16VEC3 = 106, /* F16VEC3 */ YYSYMBOL_F16VEC4 = 107, /* F16VEC4 */ YYSYMBOL_F16MAT2 = 108, /* F16MAT2 */ YYSYMBOL_F16MAT3 = 109, /* F16MAT3 */ YYSYMBOL_F16MAT4 = 110, /* F16MAT4 */ YYSYMBOL_F32VEC2 = 111, /* F32VEC2 */ YYSYMBOL_F32VEC3 = 112, /* F32VEC3 */ YYSYMBOL_F32VEC4 = 113, /* F32VEC4 */ YYSYMBOL_F32MAT2 = 114, /* F32MAT2 */ YYSYMBOL_F32MAT3 = 115, /* F32MAT3 */ YYSYMBOL_F32MAT4 = 116, /* F32MAT4 */ YYSYMBOL_F64VEC2 = 117, /* F64VEC2 */ YYSYMBOL_F64VEC3 = 118, /* F64VEC3 */ YYSYMBOL_F64VEC4 = 119, /* F64VEC4 */ YYSYMBOL_F64MAT2 = 120, /* F64MAT2 */ YYSYMBOL_F64MAT3 = 121, /* F64MAT3 */ YYSYMBOL_F64MAT4 = 122, /* F64MAT4 */ YYSYMBOL_DMAT2X2 = 123, /* DMAT2X2 */ YYSYMBOL_DMAT2X3 = 124, /* DMAT2X3 */ YYSYMBOL_DMAT2X4 = 125, /* DMAT2X4 */ YYSYMBOL_DMAT3X2 = 126, /* DMAT3X2 */ YYSYMBOL_DMAT3X3 = 127, /* DMAT3X3 */ YYSYMBOL_DMAT3X4 = 128, /* DMAT3X4 */ YYSYMBOL_DMAT4X2 = 129, /* DMAT4X2 */ YYSYMBOL_DMAT4X3 = 130, /* DMAT4X3 */ YYSYMBOL_DMAT4X4 = 131, /* DMAT4X4 */ YYSYMBOL_F16MAT2X2 = 132, /* F16MAT2X2 */ YYSYMBOL_F16MAT2X3 = 133, /* F16MAT2X3 */ YYSYMBOL_F16MAT2X4 = 134, /* F16MAT2X4 */ YYSYMBOL_F16MAT3X2 = 135, /* F16MAT3X2 */ YYSYMBOL_F16MAT3X3 = 136, /* F16MAT3X3 */ YYSYMBOL_F16MAT3X4 = 137, /* F16MAT3X4 */ YYSYMBOL_F16MAT4X2 = 138, /* F16MAT4X2 */ YYSYMBOL_F16MAT4X3 = 139, /* F16MAT4X3 */ YYSYMBOL_F16MAT4X4 = 140, /* F16MAT4X4 */ YYSYMBOL_F32MAT2X2 = 141, /* F32MAT2X2 */ YYSYMBOL_F32MAT2X3 = 142, /* F32MAT2X3 */ YYSYMBOL_F32MAT2X4 = 143, /* F32MAT2X4 */ YYSYMBOL_F32MAT3X2 = 144, /* F32MAT3X2 */ YYSYMBOL_F32MAT3X3 = 145, /* F32MAT3X3 */ YYSYMBOL_F32MAT3X4 = 146, /* F32MAT3X4 */ YYSYMBOL_F32MAT4X2 = 147, /* F32MAT4X2 */ YYSYMBOL_F32MAT4X3 = 148, /* F32MAT4X3 */ YYSYMBOL_F32MAT4X4 = 149, /* F32MAT4X4 */ YYSYMBOL_F64MAT2X2 = 150, /* F64MAT2X2 */ YYSYMBOL_F64MAT2X3 = 151, /* F64MAT2X3 */ YYSYMBOL_F64MAT2X4 = 152, /* F64MAT2X4 */ YYSYMBOL_F64MAT3X2 = 153, /* F64MAT3X2 */ YYSYMBOL_F64MAT3X3 = 154, /* F64MAT3X3 */ YYSYMBOL_F64MAT3X4 = 155, /* F64MAT3X4 */ YYSYMBOL_F64MAT4X2 = 156, /* F64MAT4X2 */ YYSYMBOL_F64MAT4X3 = 157, /* F64MAT4X3 */ YYSYMBOL_F64MAT4X4 = 158, /* F64MAT4X4 */ YYSYMBOL_ATOMIC_UINT = 159, /* ATOMIC_UINT */ YYSYMBOL_ACCSTRUCTNV = 160, /* ACCSTRUCTNV */ YYSYMBOL_ACCSTRUCTEXT = 161, /* ACCSTRUCTEXT */ YYSYMBOL_RAYQUERYEXT = 162, /* RAYQUERYEXT */ YYSYMBOL_FCOOPMATNV = 163, /* FCOOPMATNV */ YYSYMBOL_ICOOPMATNV = 164, /* ICOOPMATNV */ YYSYMBOL_UCOOPMATNV = 165, /* UCOOPMATNV */ YYSYMBOL_SAMPLERCUBEARRAY = 166, /* SAMPLERCUBEARRAY */ YYSYMBOL_SAMPLERCUBEARRAYSHADOW = 167, /* SAMPLERCUBEARRAYSHADOW */ YYSYMBOL_ISAMPLERCUBEARRAY = 168, /* ISAMPLERCUBEARRAY */ YYSYMBOL_USAMPLERCUBEARRAY = 169, /* USAMPLERCUBEARRAY */ YYSYMBOL_SAMPLER1D = 170, /* SAMPLER1D */ YYSYMBOL_SAMPLER1DARRAY = 171, /* SAMPLER1DARRAY */ YYSYMBOL_SAMPLER1DARRAYSHADOW = 172, /* SAMPLER1DARRAYSHADOW */ YYSYMBOL_ISAMPLER1D = 173, /* ISAMPLER1D */ YYSYMBOL_SAMPLER1DSHADOW = 174, /* SAMPLER1DSHADOW */ YYSYMBOL_SAMPLER2DRECT = 175, /* SAMPLER2DRECT */ YYSYMBOL_SAMPLER2DRECTSHADOW = 176, /* SAMPLER2DRECTSHADOW */ YYSYMBOL_ISAMPLER2DRECT = 177, /* ISAMPLER2DRECT */ YYSYMBOL_USAMPLER2DRECT = 178, /* USAMPLER2DRECT */ YYSYMBOL_SAMPLERBUFFER = 179, /* SAMPLERBUFFER */ YYSYMBOL_ISAMPLERBUFFER = 180, /* ISAMPLERBUFFER */ YYSYMBOL_USAMPLERBUFFER = 181, /* USAMPLERBUFFER */ YYSYMBOL_SAMPLER2DMS = 182, /* SAMPLER2DMS */ YYSYMBOL_ISAMPLER2DMS = 183, /* ISAMPLER2DMS */ YYSYMBOL_USAMPLER2DMS = 184, /* USAMPLER2DMS */ YYSYMBOL_SAMPLER2DMSARRAY = 185, /* SAMPLER2DMSARRAY */ YYSYMBOL_ISAMPLER2DMSARRAY = 186, /* ISAMPLER2DMSARRAY */ YYSYMBOL_USAMPLER2DMSARRAY = 187, /* USAMPLER2DMSARRAY */ YYSYMBOL_SAMPLEREXTERNALOES = 188, /* SAMPLEREXTERNALOES */ YYSYMBOL_SAMPLEREXTERNAL2DY2YEXT = 189, /* SAMPLEREXTERNAL2DY2YEXT */ YYSYMBOL_ISAMPLER1DARRAY = 190, /* ISAMPLER1DARRAY */ YYSYMBOL_USAMPLER1D = 191, /* USAMPLER1D */ YYSYMBOL_USAMPLER1DARRAY = 192, /* USAMPLER1DARRAY */ YYSYMBOL_F16SAMPLER1D = 193, /* F16SAMPLER1D */ YYSYMBOL_F16SAMPLER2D = 194, /* F16SAMPLER2D */ YYSYMBOL_F16SAMPLER3D = 195, /* F16SAMPLER3D */ YYSYMBOL_F16SAMPLER2DRECT = 196, /* F16SAMPLER2DRECT */ YYSYMBOL_F16SAMPLERCUBE = 197, /* F16SAMPLERCUBE */ YYSYMBOL_F16SAMPLER1DARRAY = 198, /* F16SAMPLER1DARRAY */ YYSYMBOL_F16SAMPLER2DARRAY = 199, /* F16SAMPLER2DARRAY */ YYSYMBOL_F16SAMPLERCUBEARRAY = 200, /* F16SAMPLERCUBEARRAY */ YYSYMBOL_F16SAMPLERBUFFER = 201, /* F16SAMPLERBUFFER */ YYSYMBOL_F16SAMPLER2DMS = 202, /* F16SAMPLER2DMS */ YYSYMBOL_F16SAMPLER2DMSARRAY = 203, /* F16SAMPLER2DMSARRAY */ YYSYMBOL_F16SAMPLER1DSHADOW = 204, /* F16SAMPLER1DSHADOW */ YYSYMBOL_F16SAMPLER2DSHADOW = 205, /* F16SAMPLER2DSHADOW */ YYSYMBOL_F16SAMPLER1DARRAYSHADOW = 206, /* F16SAMPLER1DARRAYSHADOW */ YYSYMBOL_F16SAMPLER2DARRAYSHADOW = 207, /* F16SAMPLER2DARRAYSHADOW */ YYSYMBOL_F16SAMPLER2DRECTSHADOW = 208, /* F16SAMPLER2DRECTSHADOW */ YYSYMBOL_F16SAMPLERCUBESHADOW = 209, /* F16SAMPLERCUBESHADOW */ YYSYMBOL_F16SAMPLERCUBEARRAYSHADOW = 210, /* F16SAMPLERCUBEARRAYSHADOW */ YYSYMBOL_IMAGE1D = 211, /* IMAGE1D */ YYSYMBOL_IIMAGE1D = 212, /* IIMAGE1D */ YYSYMBOL_UIMAGE1D = 213, /* UIMAGE1D */ YYSYMBOL_IMAGE2D = 214, /* IMAGE2D */ YYSYMBOL_IIMAGE2D = 215, /* IIMAGE2D */ YYSYMBOL_UIMAGE2D = 216, /* UIMAGE2D */ YYSYMBOL_IMAGE3D = 217, /* IMAGE3D */ YYSYMBOL_IIMAGE3D = 218, /* IIMAGE3D */ YYSYMBOL_UIMAGE3D = 219, /* UIMAGE3D */ YYSYMBOL_IMAGE2DRECT = 220, /* IMAGE2DRECT */ YYSYMBOL_IIMAGE2DRECT = 221, /* IIMAGE2DRECT */ YYSYMBOL_UIMAGE2DRECT = 222, /* UIMAGE2DRECT */ YYSYMBOL_IMAGECUBE = 223, /* IMAGECUBE */ YYSYMBOL_IIMAGECUBE = 224, /* IIMAGECUBE */ YYSYMBOL_UIMAGECUBE = 225, /* UIMAGECUBE */ YYSYMBOL_IMAGEBUFFER = 226, /* IMAGEBUFFER */ YYSYMBOL_IIMAGEBUFFER = 227, /* IIMAGEBUFFER */ YYSYMBOL_UIMAGEBUFFER = 228, /* UIMAGEBUFFER */ YYSYMBOL_IMAGE1DARRAY = 229, /* IMAGE1DARRAY */ YYSYMBOL_IIMAGE1DARRAY = 230, /* IIMAGE1DARRAY */ YYSYMBOL_UIMAGE1DARRAY = 231, /* UIMAGE1DARRAY */ YYSYMBOL_IMAGE2DARRAY = 232, /* IMAGE2DARRAY */ YYSYMBOL_IIMAGE2DARRAY = 233, /* IIMAGE2DARRAY */ YYSYMBOL_UIMAGE2DARRAY = 234, /* UIMAGE2DARRAY */ YYSYMBOL_IMAGECUBEARRAY = 235, /* IMAGECUBEARRAY */ YYSYMBOL_IIMAGECUBEARRAY = 236, /* IIMAGECUBEARRAY */ YYSYMBOL_UIMAGECUBEARRAY = 237, /* UIMAGECUBEARRAY */ YYSYMBOL_IMAGE2DMS = 238, /* IMAGE2DMS */ YYSYMBOL_IIMAGE2DMS = 239, /* IIMAGE2DMS */ YYSYMBOL_UIMAGE2DMS = 240, /* UIMAGE2DMS */ YYSYMBOL_IMAGE2DMSARRAY = 241, /* IMAGE2DMSARRAY */ YYSYMBOL_IIMAGE2DMSARRAY = 242, /* IIMAGE2DMSARRAY */ YYSYMBOL_UIMAGE2DMSARRAY = 243, /* UIMAGE2DMSARRAY */ YYSYMBOL_F16IMAGE1D = 244, /* F16IMAGE1D */ YYSYMBOL_F16IMAGE2D = 245, /* F16IMAGE2D */ YYSYMBOL_F16IMAGE3D = 246, /* F16IMAGE3D */ YYSYMBOL_F16IMAGE2DRECT = 247, /* F16IMAGE2DRECT */ YYSYMBOL_F16IMAGECUBE = 248, /* F16IMAGECUBE */ YYSYMBOL_F16IMAGE1DARRAY = 249, /* F16IMAGE1DARRAY */ YYSYMBOL_F16IMAGE2DARRAY = 250, /* F16IMAGE2DARRAY */ YYSYMBOL_F16IMAGECUBEARRAY = 251, /* F16IMAGECUBEARRAY */ YYSYMBOL_F16IMAGEBUFFER = 252, /* F16IMAGEBUFFER */ YYSYMBOL_F16IMAGE2DMS = 253, /* F16IMAGE2DMS */ YYSYMBOL_F16IMAGE2DMSARRAY = 254, /* F16IMAGE2DMSARRAY */ YYSYMBOL_I64IMAGE1D = 255, /* I64IMAGE1D */ YYSYMBOL_U64IMAGE1D = 256, /* U64IMAGE1D */ YYSYMBOL_I64IMAGE2D = 257, /* I64IMAGE2D */ YYSYMBOL_U64IMAGE2D = 258, /* U64IMAGE2D */ YYSYMBOL_I64IMAGE3D = 259, /* I64IMAGE3D */ YYSYMBOL_U64IMAGE3D = 260, /* U64IMAGE3D */ YYSYMBOL_I64IMAGE2DRECT = 261, /* I64IMAGE2DRECT */ YYSYMBOL_U64IMAGE2DRECT = 262, /* U64IMAGE2DRECT */ YYSYMBOL_I64IMAGECUBE = 263, /* I64IMAGECUBE */ YYSYMBOL_U64IMAGECUBE = 264, /* U64IMAGECUBE */ YYSYMBOL_I64IMAGEBUFFER = 265, /* I64IMAGEBUFFER */ YYSYMBOL_U64IMAGEBUFFER = 266, /* U64IMAGEBUFFER */ YYSYMBOL_I64IMAGE1DARRAY = 267, /* I64IMAGE1DARRAY */ YYSYMBOL_U64IMAGE1DARRAY = 268, /* U64IMAGE1DARRAY */ YYSYMBOL_I64IMAGE2DARRAY = 269, /* I64IMAGE2DARRAY */ YYSYMBOL_U64IMAGE2DARRAY = 270, /* U64IMAGE2DARRAY */ YYSYMBOL_I64IMAGECUBEARRAY = 271, /* I64IMAGECUBEARRAY */ YYSYMBOL_U64IMAGECUBEARRAY = 272, /* U64IMAGECUBEARRAY */ YYSYMBOL_I64IMAGE2DMS = 273, /* I64IMAGE2DMS */ YYSYMBOL_U64IMAGE2DMS = 274, /* U64IMAGE2DMS */ YYSYMBOL_I64IMAGE2DMSARRAY = 275, /* I64IMAGE2DMSARRAY */ YYSYMBOL_U64IMAGE2DMSARRAY = 276, /* U64IMAGE2DMSARRAY */ YYSYMBOL_TEXTURECUBEARRAY = 277, /* TEXTURECUBEARRAY */ YYSYMBOL_ITEXTURECUBEARRAY = 278, /* ITEXTURECUBEARRAY */ YYSYMBOL_UTEXTURECUBEARRAY = 279, /* UTEXTURECUBEARRAY */ YYSYMBOL_TEXTURE1D = 280, /* TEXTURE1D */ YYSYMBOL_ITEXTURE1D = 281, /* ITEXTURE1D */ YYSYMBOL_UTEXTURE1D = 282, /* UTEXTURE1D */ YYSYMBOL_TEXTURE1DARRAY = 283, /* TEXTURE1DARRAY */ YYSYMBOL_ITEXTURE1DARRAY = 284, /* ITEXTURE1DARRAY */ YYSYMBOL_UTEXTURE1DARRAY = 285, /* UTEXTURE1DARRAY */ YYSYMBOL_TEXTURE2DRECT = 286, /* TEXTURE2DRECT */ YYSYMBOL_ITEXTURE2DRECT = 287, /* ITEXTURE2DRECT */ YYSYMBOL_UTEXTURE2DRECT = 288, /* UTEXTURE2DRECT */ YYSYMBOL_TEXTUREBUFFER = 289, /* TEXTUREBUFFER */ YYSYMBOL_ITEXTUREBUFFER = 290, /* ITEXTUREBUFFER */ YYSYMBOL_UTEXTUREBUFFER = 291, /* UTEXTUREBUFFER */ YYSYMBOL_TEXTURE2DMS = 292, /* TEXTURE2DMS */ YYSYMBOL_ITEXTURE2DMS = 293, /* ITEXTURE2DMS */ YYSYMBOL_UTEXTURE2DMS = 294, /* UTEXTURE2DMS */ YYSYMBOL_TEXTURE2DMSARRAY = 295, /* TEXTURE2DMSARRAY */ YYSYMBOL_ITEXTURE2DMSARRAY = 296, /* ITEXTURE2DMSARRAY */ YYSYMBOL_UTEXTURE2DMSARRAY = 297, /* UTEXTURE2DMSARRAY */ YYSYMBOL_F16TEXTURE1D = 298, /* F16TEXTURE1D */ YYSYMBOL_F16TEXTURE2D = 299, /* F16TEXTURE2D */ YYSYMBOL_F16TEXTURE3D = 300, /* F16TEXTURE3D */ YYSYMBOL_F16TEXTURE2DRECT = 301, /* F16TEXTURE2DRECT */ YYSYMBOL_F16TEXTURECUBE = 302, /* F16TEXTURECUBE */ YYSYMBOL_F16TEXTURE1DARRAY = 303, /* F16TEXTURE1DARRAY */ YYSYMBOL_F16TEXTURE2DARRAY = 304, /* F16TEXTURE2DARRAY */ YYSYMBOL_F16TEXTURECUBEARRAY = 305, /* F16TEXTURECUBEARRAY */ YYSYMBOL_F16TEXTUREBUFFER = 306, /* F16TEXTUREBUFFER */ YYSYMBOL_F16TEXTURE2DMS = 307, /* F16TEXTURE2DMS */ YYSYMBOL_F16TEXTURE2DMSARRAY = 308, /* F16TEXTURE2DMSARRAY */ YYSYMBOL_SUBPASSINPUT = 309, /* SUBPASSINPUT */ YYSYMBOL_SUBPASSINPUTMS = 310, /* SUBPASSINPUTMS */ YYSYMBOL_ISUBPASSINPUT = 311, /* ISUBPASSINPUT */ YYSYMBOL_ISUBPASSINPUTMS = 312, /* ISUBPASSINPUTMS */ YYSYMBOL_USUBPASSINPUT = 313, /* USUBPASSINPUT */ YYSYMBOL_USUBPASSINPUTMS = 314, /* USUBPASSINPUTMS */ YYSYMBOL_F16SUBPASSINPUT = 315, /* F16SUBPASSINPUT */ YYSYMBOL_F16SUBPASSINPUTMS = 316, /* F16SUBPASSINPUTMS */ YYSYMBOL_LEFT_OP = 317, /* LEFT_OP */ YYSYMBOL_RIGHT_OP = 318, /* RIGHT_OP */ YYSYMBOL_INC_OP = 319, /* INC_OP */ YYSYMBOL_DEC_OP = 320, /* DEC_OP */ YYSYMBOL_LE_OP = 321, /* LE_OP */ YYSYMBOL_GE_OP = 322, /* GE_OP */ YYSYMBOL_EQ_OP = 323, /* EQ_OP */ YYSYMBOL_NE_OP = 324, /* NE_OP */ YYSYMBOL_AND_OP = 325, /* AND_OP */ YYSYMBOL_OR_OP = 326, /* OR_OP */ YYSYMBOL_XOR_OP = 327, /* XOR_OP */ YYSYMBOL_MUL_ASSIGN = 328, /* MUL_ASSIGN */ YYSYMBOL_DIV_ASSIGN = 329, /* DIV_ASSIGN */ YYSYMBOL_ADD_ASSIGN = 330, /* ADD_ASSIGN */ YYSYMBOL_MOD_ASSIGN = 331, /* MOD_ASSIGN */ YYSYMBOL_LEFT_ASSIGN = 332, /* LEFT_ASSIGN */ YYSYMBOL_RIGHT_ASSIGN = 333, /* RIGHT_ASSIGN */ YYSYMBOL_AND_ASSIGN = 334, /* AND_ASSIGN */ YYSYMBOL_XOR_ASSIGN = 335, /* XOR_ASSIGN */ YYSYMBOL_OR_ASSIGN = 336, /* OR_ASSIGN */ YYSYMBOL_SUB_ASSIGN = 337, /* SUB_ASSIGN */ YYSYMBOL_STRING_LITERAL = 338, /* STRING_LITERAL */ YYSYMBOL_LEFT_PAREN = 339, /* LEFT_PAREN */ YYSYMBOL_RIGHT_PAREN = 340, /* RIGHT_PAREN */ YYSYMBOL_LEFT_BRACKET = 341, /* LEFT_BRACKET */ YYSYMBOL_RIGHT_BRACKET = 342, /* RIGHT_BRACKET */ YYSYMBOL_LEFT_BRACE = 343, /* LEFT_BRACE */ YYSYMBOL_RIGHT_BRACE = 344, /* RIGHT_BRACE */ YYSYMBOL_DOT = 345, /* DOT */ YYSYMBOL_COMMA = 346, /* COMMA */ YYSYMBOL_COLON = 347, /* COLON */ YYSYMBOL_EQUAL = 348, /* EQUAL */ YYSYMBOL_SEMICOLON = 349, /* SEMICOLON */ YYSYMBOL_BANG = 350, /* BANG */ YYSYMBOL_DASH = 351, /* DASH */ YYSYMBOL_TILDE = 352, /* TILDE */ YYSYMBOL_PLUS = 353, /* PLUS */ YYSYMBOL_STAR = 354, /* STAR */ YYSYMBOL_SLASH = 355, /* SLASH */ YYSYMBOL_PERCENT = 356, /* PERCENT */ YYSYMBOL_LEFT_ANGLE = 357, /* LEFT_ANGLE */ YYSYMBOL_RIGHT_ANGLE = 358, /* RIGHT_ANGLE */ YYSYMBOL_VERTICAL_BAR = 359, /* VERTICAL_BAR */ YYSYMBOL_CARET = 360, /* CARET */ YYSYMBOL_AMPERSAND = 361, /* AMPERSAND */ YYSYMBOL_QUESTION = 362, /* QUESTION */ YYSYMBOL_INVARIANT = 363, /* INVARIANT */ YYSYMBOL_HIGH_PRECISION = 364, /* HIGH_PRECISION */ YYSYMBOL_MEDIUM_PRECISION = 365, /* MEDIUM_PRECISION */ YYSYMBOL_LOW_PRECISION = 366, /* LOW_PRECISION */ YYSYMBOL_PRECISION = 367, /* PRECISION */ YYSYMBOL_PACKED = 368, /* PACKED */ YYSYMBOL_RESOURCE = 369, /* RESOURCE */ YYSYMBOL_SUPERP = 370, /* SUPERP */ YYSYMBOL_FLOATCONSTANT = 371, /* FLOATCONSTANT */ YYSYMBOL_INTCONSTANT = 372, /* INTCONSTANT */ YYSYMBOL_UINTCONSTANT = 373, /* UINTCONSTANT */ YYSYMBOL_BOOLCONSTANT = 374, /* BOOLCONSTANT */ YYSYMBOL_IDENTIFIER = 375, /* IDENTIFIER */ YYSYMBOL_TYPE_NAME = 376, /* TYPE_NAME */ YYSYMBOL_CENTROID = 377, /* CENTROID */ YYSYMBOL_IN = 378, /* IN */ YYSYMBOL_OUT = 379, /* OUT */ YYSYMBOL_INOUT = 380, /* INOUT */ YYSYMBOL_STRUCT = 381, /* STRUCT */ YYSYMBOL_VOID = 382, /* VOID */ YYSYMBOL_WHILE = 383, /* WHILE */ YYSYMBOL_BREAK = 384, /* BREAK */ YYSYMBOL_CONTINUE = 385, /* CONTINUE */ YYSYMBOL_DO = 386, /* DO */ YYSYMBOL_ELSE = 387, /* ELSE */ YYSYMBOL_FOR = 388, /* FOR */ YYSYMBOL_IF = 389, /* IF */ YYSYMBOL_DISCARD = 390, /* DISCARD */ YYSYMBOL_RETURN = 391, /* RETURN */ YYSYMBOL_SWITCH = 392, /* SWITCH */ YYSYMBOL_CASE = 393, /* CASE */ YYSYMBOL_DEFAULT = 394, /* DEFAULT */ YYSYMBOL_TERMINATE_INVOCATION = 395, /* TERMINATE_INVOCATION */ YYSYMBOL_TERMINATE_RAY = 396, /* TERMINATE_RAY */ YYSYMBOL_IGNORE_INTERSECTION = 397, /* IGNORE_INTERSECTION */ YYSYMBOL_UNIFORM = 398, /* UNIFORM */ YYSYMBOL_SHARED = 399, /* SHARED */ YYSYMBOL_BUFFER = 400, /* BUFFER */ YYSYMBOL_FLAT = 401, /* FLAT */ YYSYMBOL_SMOOTH = 402, /* SMOOTH */ YYSYMBOL_LAYOUT = 403, /* LAYOUT */ YYSYMBOL_DOUBLECONSTANT = 404, /* DOUBLECONSTANT */ YYSYMBOL_INT16CONSTANT = 405, /* INT16CONSTANT */ YYSYMBOL_UINT16CONSTANT = 406, /* UINT16CONSTANT */ YYSYMBOL_FLOAT16CONSTANT = 407, /* FLOAT16CONSTANT */ YYSYMBOL_INT32CONSTANT = 408, /* INT32CONSTANT */ YYSYMBOL_UINT32CONSTANT = 409, /* UINT32CONSTANT */ YYSYMBOL_INT64CONSTANT = 410, /* INT64CONSTANT */ YYSYMBOL_UINT64CONSTANT = 411, /* UINT64CONSTANT */ YYSYMBOL_SUBROUTINE = 412, /* SUBROUTINE */ YYSYMBOL_DEMOTE = 413, /* DEMOTE */ YYSYMBOL_PAYLOADNV = 414, /* PAYLOADNV */ YYSYMBOL_PAYLOADINNV = 415, /* PAYLOADINNV */ YYSYMBOL_HITATTRNV = 416, /* HITATTRNV */ YYSYMBOL_CALLDATANV = 417, /* CALLDATANV */ YYSYMBOL_CALLDATAINNV = 418, /* CALLDATAINNV */ YYSYMBOL_PAYLOADEXT = 419, /* PAYLOADEXT */ YYSYMBOL_PAYLOADINEXT = 420, /* PAYLOADINEXT */ YYSYMBOL_HITATTREXT = 421, /* HITATTREXT */ YYSYMBOL_CALLDATAEXT = 422, /* CALLDATAEXT */ YYSYMBOL_CALLDATAINEXT = 423, /* CALLDATAINEXT */ YYSYMBOL_PATCH = 424, /* PATCH */ YYSYMBOL_SAMPLE = 425, /* SAMPLE */ YYSYMBOL_NONUNIFORM = 426, /* NONUNIFORM */ YYSYMBOL_COHERENT = 427, /* COHERENT */ YYSYMBOL_VOLATILE = 428, /* VOLATILE */ YYSYMBOL_RESTRICT = 429, /* RESTRICT */ YYSYMBOL_READONLY = 430, /* READONLY */ YYSYMBOL_WRITEONLY = 431, /* WRITEONLY */ YYSYMBOL_DEVICECOHERENT = 432, /* DEVICECOHERENT */ YYSYMBOL_QUEUEFAMILYCOHERENT = 433, /* QUEUEFAMILYCOHERENT */ YYSYMBOL_WORKGROUPCOHERENT = 434, /* WORKGROUPCOHERENT */ YYSYMBOL_SUBGROUPCOHERENT = 435, /* SUBGROUPCOHERENT */ YYSYMBOL_NONPRIVATE = 436, /* NONPRIVATE */ YYSYMBOL_SHADERCALLCOHERENT = 437, /* SHADERCALLCOHERENT */ YYSYMBOL_NOPERSPECTIVE = 438, /* NOPERSPECTIVE */ YYSYMBOL_EXPLICITINTERPAMD = 439, /* EXPLICITINTERPAMD */ YYSYMBOL_PERVERTEXNV = 440, /* PERVERTEXNV */ YYSYMBOL_PERPRIMITIVENV = 441, /* PERPRIMITIVENV */ YYSYMBOL_PERVIEWNV = 442, /* PERVIEWNV */ YYSYMBOL_PERTASKNV = 443, /* PERTASKNV */ YYSYMBOL_PRECISE = 444, /* PRECISE */ YYSYMBOL_YYACCEPT = 445, /* $accept */ YYSYMBOL_variable_identifier = 446, /* variable_identifier */ YYSYMBOL_primary_expression = 447, /* primary_expression */ YYSYMBOL_postfix_expression = 448, /* postfix_expression */ YYSYMBOL_integer_expression = 449, /* integer_expression */ YYSYMBOL_function_call = 450, /* function_call */ YYSYMBOL_function_call_or_method = 451, /* function_call_or_method */ YYSYMBOL_function_call_generic = 452, /* function_call_generic */ YYSYMBOL_function_call_header_no_parameters = 453, /* function_call_header_no_parameters */ YYSYMBOL_function_call_header_with_parameters = 454, /* function_call_header_with_parameters */ YYSYMBOL_function_call_header = 455, /* function_call_header */ YYSYMBOL_function_identifier = 456, /* function_identifier */ YYSYMBOL_unary_expression = 457, /* unary_expression */ YYSYMBOL_unary_operator = 458, /* unary_operator */ YYSYMBOL_multiplicative_expression = 459, /* multiplicative_expression */ YYSYMBOL_additive_expression = 460, /* additive_expression */ YYSYMBOL_shift_expression = 461, /* shift_expression */ YYSYMBOL_relational_expression = 462, /* relational_expression */ YYSYMBOL_equality_expression = 463, /* equality_expression */ YYSYMBOL_and_expression = 464, /* and_expression */ YYSYMBOL_exclusive_or_expression = 465, /* exclusive_or_expression */ YYSYMBOL_inclusive_or_expression = 466, /* inclusive_or_expression */ YYSYMBOL_logical_and_expression = 467, /* logical_and_expression */ YYSYMBOL_logical_xor_expression = 468, /* logical_xor_expression */ YYSYMBOL_logical_or_expression = 469, /* logical_or_expression */ YYSYMBOL_conditional_expression = 470, /* conditional_expression */ YYSYMBOL_471_1 = 471, /* $@1 */ YYSYMBOL_assignment_expression = 472, /* assignment_expression */ YYSYMBOL_assignment_operator = 473, /* assignment_operator */ YYSYMBOL_expression = 474, /* expression */ YYSYMBOL_constant_expression = 475, /* constant_expression */ YYSYMBOL_declaration = 476, /* declaration */ YYSYMBOL_block_structure = 477, /* block_structure */ YYSYMBOL_478_2 = 478, /* $@2 */ YYSYMBOL_identifier_list = 479, /* identifier_list */ YYSYMBOL_function_prototype = 480, /* function_prototype */ YYSYMBOL_function_declarator = 481, /* function_declarator */ YYSYMBOL_function_header_with_parameters = 482, /* function_header_with_parameters */ YYSYMBOL_function_header = 483, /* function_header */ YYSYMBOL_parameter_declarator = 484, /* parameter_declarator */ YYSYMBOL_parameter_declaration = 485, /* parameter_declaration */ YYSYMBOL_parameter_type_specifier = 486, /* parameter_type_specifier */ YYSYMBOL_init_declarator_list = 487, /* init_declarator_list */ YYSYMBOL_single_declaration = 488, /* single_declaration */ YYSYMBOL_fully_specified_type = 489, /* fully_specified_type */ YYSYMBOL_invariant_qualifier = 490, /* invariant_qualifier */ YYSYMBOL_interpolation_qualifier = 491, /* interpolation_qualifier */ YYSYMBOL_layout_qualifier = 492, /* layout_qualifier */ YYSYMBOL_layout_qualifier_id_list = 493, /* layout_qualifier_id_list */ YYSYMBOL_layout_qualifier_id = 494, /* layout_qualifier_id */ YYSYMBOL_precise_qualifier = 495, /* precise_qualifier */ YYSYMBOL_type_qualifier = 496, /* type_qualifier */ YYSYMBOL_single_type_qualifier = 497, /* single_type_qualifier */ YYSYMBOL_storage_qualifier = 498, /* storage_qualifier */ YYSYMBOL_non_uniform_qualifier = 499, /* non_uniform_qualifier */ YYSYMBOL_type_name_list = 500, /* type_name_list */ YYSYMBOL_type_specifier = 501, /* type_specifier */ YYSYMBOL_array_specifier = 502, /* array_specifier */ YYSYMBOL_type_parameter_specifier_opt = 503, /* type_parameter_specifier_opt */ YYSYMBOL_type_parameter_specifier = 504, /* type_parameter_specifier */ YYSYMBOL_type_parameter_specifier_list = 505, /* type_parameter_specifier_list */ YYSYMBOL_type_specifier_nonarray = 506, /* type_specifier_nonarray */ YYSYMBOL_precision_qualifier = 507, /* precision_qualifier */ YYSYMBOL_struct_specifier = 508, /* struct_specifier */ YYSYMBOL_509_3 = 509, /* $@3 */ YYSYMBOL_510_4 = 510, /* $@4 */ YYSYMBOL_struct_declaration_list = 511, /* struct_declaration_list */ YYSYMBOL_struct_declaration = 512, /* struct_declaration */ YYSYMBOL_struct_declarator_list = 513, /* struct_declarator_list */ YYSYMBOL_struct_declarator = 514, /* struct_declarator */ YYSYMBOL_initializer = 515, /* initializer */ YYSYMBOL_initializer_list = 516, /* initializer_list */ YYSYMBOL_declaration_statement = 517, /* declaration_statement */ YYSYMBOL_statement = 518, /* statement */ YYSYMBOL_simple_statement = 519, /* simple_statement */ YYSYMBOL_demote_statement = 520, /* demote_statement */ YYSYMBOL_compound_statement = 521, /* compound_statement */ YYSYMBOL_522_5 = 522, /* $@5 */ YYSYMBOL_523_6 = 523, /* $@6 */ YYSYMBOL_statement_no_new_scope = 524, /* statement_no_new_scope */ YYSYMBOL_statement_scoped = 525, /* statement_scoped */ YYSYMBOL_526_7 = 526, /* $@7 */ YYSYMBOL_527_8 = 527, /* $@8 */ YYSYMBOL_compound_statement_no_new_scope = 528, /* compound_statement_no_new_scope */ YYSYMBOL_statement_list = 529, /* statement_list */ YYSYMBOL_expression_statement = 530, /* expression_statement */ YYSYMBOL_selection_statement = 531, /* selection_statement */ YYSYMBOL_selection_statement_nonattributed = 532, /* selection_statement_nonattributed */ YYSYMBOL_selection_rest_statement = 533, /* selection_rest_statement */ YYSYMBOL_condition = 534, /* condition */ YYSYMBOL_switch_statement = 535, /* switch_statement */ YYSYMBOL_switch_statement_nonattributed = 536, /* switch_statement_nonattributed */ YYSYMBOL_537_9 = 537, /* $@9 */ YYSYMBOL_switch_statement_list = 538, /* switch_statement_list */ YYSYMBOL_case_label = 539, /* case_label */ YYSYMBOL_iteration_statement = 540, /* iteration_statement */ YYSYMBOL_iteration_statement_nonattributed = 541, /* iteration_statement_nonattributed */ YYSYMBOL_542_10 = 542, /* $@10 */ YYSYMBOL_543_11 = 543, /* $@11 */ YYSYMBOL_544_12 = 544, /* $@12 */ YYSYMBOL_for_init_statement = 545, /* for_init_statement */ YYSYMBOL_conditionopt = 546, /* conditionopt */ YYSYMBOL_for_rest_statement = 547, /* for_rest_statement */ YYSYMBOL_jump_statement = 548, /* jump_statement */ YYSYMBOL_translation_unit = 549, /* translation_unit */ YYSYMBOL_external_declaration = 550, /* external_declaration */ YYSYMBOL_function_definition = 551, /* function_definition */ YYSYMBOL_552_13 = 552, /* $@13 */ YYSYMBOL_attribute = 553, /* attribute */ YYSYMBOL_attribute_list = 554, /* attribute_list */ YYSYMBOL_single_attribute = 555 /* single_attribute */ }; typedef enum yysymbol_kind_t yysymbol_kind_t; /* Second part of user prologue. */ #line 133 "MachineIndependent/glslang.y" /* windows only pragma */ #ifdef _MSC_VER #pragma warning(disable : 4065) #pragma warning(disable : 4127) #pragma warning(disable : 4244) #endif #define parseContext (*pParseContext) #define yyerror(context, msg) context->parserError(msg) extern int yylex(YYSTYPE*, TParseContext&); #line 702 "MachineIndependent/glslang_tab.cpp" #ifdef short # undef short #endif /* On compilers that do not define __PTRDIFF_MAX__ etc., make sure <limits.h> and (if available) <stdint.h> are included so that the code can choose integer types of a good width. */ #ifndef __PTRDIFF_MAX__ # include <limits.h> /* INFRINGES ON USER NAME SPACE */ # if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stdint.h> /* INFRINGES ON USER NAME SPACE */ # define YY_STDINT_H # endif #endif /* Narrow types that promote to a signed type and that can represent a signed or unsigned integer of at least N bits. In tables they can save space and decrease cache pressure. Promoting to a signed type helps avoid bugs in integer arithmetic. */ #ifdef __INT_LEAST8_MAX__ typedef __INT_LEAST8_TYPE__ yytype_int8; #elif defined YY_STDINT_H typedef int_least8_t yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef __INT_LEAST16_MAX__ typedef __INT_LEAST16_TYPE__ yytype_int16; #elif defined YY_STDINT_H typedef int_least16_t yytype_int16; #else typedef short yytype_int16; #endif /* Work around bug in HP-UX 11.23, which defines these macros incorrectly for preprocessor constants. This workaround can likely be removed in 2023, as HPE has promised support for HP-UX 11.23 (aka HP-UX 11i v2) only through the end of 2022; see Table 2 of <https://h20195.www2.hpe.com/V2/getpdf.aspx/4AA4-7673ENW.pdf>. */ #ifdef __hpux # undef UINT_LEAST8_MAX # undef UINT_LEAST16_MAX # define UINT_LEAST8_MAX 255 # define UINT_LEAST16_MAX 65535 #endif #if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__ typedef __UINT_LEAST8_TYPE__ yytype_uint8; #elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \ && UINT_LEAST8_MAX <= INT_MAX) typedef uint_least8_t yytype_uint8; #elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX typedef unsigned char yytype_uint8; #else typedef short yytype_uint8; #endif #if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__ typedef __UINT_LEAST16_TYPE__ yytype_uint16; #elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \ && UINT_LEAST16_MAX <= INT_MAX) typedef uint_least16_t yytype_uint16; #elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX typedef unsigned short yytype_uint16; #else typedef int yytype_uint16; #endif #ifndef YYPTRDIFF_T # if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__ # define YYPTRDIFF_T __PTRDIFF_TYPE__ # define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__ # elif defined PTRDIFF_MAX # ifndef ptrdiff_t # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # endif # define YYPTRDIFF_T ptrdiff_t # define YYPTRDIFF_MAXIMUM PTRDIFF_MAX # else # define YYPTRDIFF_T long # define YYPTRDIFF_MAXIMUM LONG_MAX # endif #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM \ YY_CAST (YYPTRDIFF_T, \ (YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \ ? YYPTRDIFF_MAXIMUM \ : YY_CAST (YYSIZE_T, -1))) #define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X)) /* Stored state numbers (used for stacks). */ typedef yytype_int16 yy_state_t; /* State numbers in computations. */ typedef int yy_state_fast_t; #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE_PURE # if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) # else # define YY_ATTRIBUTE_PURE # endif #endif #ifndef YY_ATTRIBUTE_UNUSED # if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) # else # define YY_ATTRIBUTE_UNUSED # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YY_USE(E) ((void) (E)) #else # define YY_USE(E) /* empty */ #endif #if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ # define YY_IGNORE_USELESS_CAST_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") # define YY_IGNORE_USELESS_CAST_END \ _Pragma ("GCC diagnostic pop") #endif #ifndef YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_END #endif #define YY_ASSERT(E) ((void) (0 && (E))) #if 1 /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* 1 */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yy_state_t yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYPTRDIFF_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / YYSIZEOF (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYPTRDIFF_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 419 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 10891 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 445 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 111 /* YYNRULES -- Number of rules. */ #define YYNRULES 620 /* YYNSTATES -- Number of states. */ #define YYNSTATES 772 /* YYMAXUTOK -- Last valid token kind. */ #define YYMAXUTOK 699 /* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM as returned by yylex, with out-of-bounds checking. */ #define YYTRANSLATE(YYX) \ (0 <= (YYX) && (YYX) <= YYMAXUTOK \ ? YY_CAST (yysymbol_kind_t, yytranslate[YYX]) \ : YYSYMBOL_YYUNDEF) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex. */ static const yytype_int16 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_int16 yyrline[] = { 0, 371, 371, 377, 380, 385, 388, 391, 395, 399, 402, 406, 410, 414, 418, 422, 426, 432, 440, 443, 446, 449, 452, 457, 465, 472, 479, 485, 489, 496, 499, 505, 512, 522, 530, 535, 563, 572, 578, 582, 586, 606, 607, 608, 609, 615, 616, 621, 626, 635, 636, 641, 649, 650, 656, 665, 666, 671, 676, 681, 689, 690, 699, 711, 712, 721, 722, 731, 732, 741, 742, 750, 751, 759, 760, 768, 769, 769, 787, 788, 804, 808, 812, 816, 821, 825, 829, 833, 837, 841, 845, 852, 855, 866, 873, 878, 883, 890, 894, 898, 902, 907, 912, 921, 921, 932, 936, 943, 947, 953, 959, 969, 972, 979, 987, 1007, 1030, 1045, 1070, 1081, 1091, 1101, 1111, 1120, 1123, 1127, 1131, 1136, 1144, 1151, 1156, 1161, 1166, 1175, 1185, 1212, 1221, 1228, 1236, 1243, 1250, 1258, 1268, 1275, 1286, 1292, 1295, 1302, 1306, 1310, 1319, 1329, 1332, 1343, 1346, 1349, 1353, 1357, 1362, 1366, 1373, 1377, 1382, 1388, 1394, 1401, 1406, 1414, 1420, 1432, 1446, 1452, 1457, 1465, 1473, 1481, 1489, 1497, 1505, 1513, 1521, 1528, 1535, 1539, 1544, 1549, 1554, 1559, 1564, 1569, 1573, 1577, 1581, 1585, 1591, 1602, 1609, 1612, 1621, 1626, 1636, 1641, 1649, 1653, 1663, 1666, 1672, 1678, 1685, 1695, 1699, 1703, 1707, 1712, 1716, 1721, 1726, 1731, 1736, 1741, 1746, 1751, 1756, 1761, 1767, 1773, 1779, 1784, 1789, 1794, 1799, 1804, 1809, 1814, 1819, 1824, 1829, 1834, 1840, 1847, 1852, 1857, 1862, 1867, 1872, 1877, 1882, 1887, 1892, 1897, 1902, 1910, 1918, 1926, 1932, 1938, 1944, 1950, 1956, 1962, 1968, 1974, 1980, 1986, 1992, 1998, 2004, 2010, 2016, 2022, 2028, 2034, 2040, 2046, 2052, 2058, 2064, 2070, 2076, 2082, 2088, 2094, 2100, 2106, 2112, 2118, 2124, 2132, 2140, 2148, 2156, 2164, 2172, 2180, 2188, 2196, 2204, 2212, 2220, 2226, 2232, 2238, 2244, 2250, 2256, 2262, 2268, 2274, 2280, 2286, 2292, 2298, 2304, 2310, 2316, 2322, 2328, 2334, 2340, 2346, 2352, 2358, 2364, 2370, 2376, 2382, 2388, 2394, 2400, 2406, 2412, 2418, 2424, 2430, 2436, 2440, 2444, 2448, 2453, 2459, 2464, 2469, 2474, 2479, 2484, 2489, 2495, 2500, 2505, 2510, 2515, 2520, 2526, 2532, 2538, 2544, 2550, 2556, 2562, 2568, 2574, 2580, 2586, 2592, 2598, 2604, 2609, 2614, 2619, 2624, 2629, 2634, 2640, 2645, 2650, 2655, 2660, 2665, 2670, 2675, 2681, 2686, 2691, 2696, 2701, 2706, 2711, 2716, 2721, 2726, 2731, 2736, 2741, 2746, 2751, 2757, 2762, 2767, 2773, 2779, 2784, 2789, 2794, 2800, 2805, 2810, 2815, 2821, 2826, 2831, 2836, 2842, 2847, 2852, 2857, 2863, 2869, 2875, 2881, 2886, 2892, 2898, 2904, 2909, 2914, 2919, 2924, 2929, 2935, 2940, 2945, 2950, 2956, 2961, 2966, 2971, 2977, 2982, 2987, 2992, 2998, 3003, 3008, 3013, 3019, 3024, 3029, 3034, 3040, 3045, 3050, 3055, 3061, 3066, 3071, 3076, 3082, 3087, 3092, 3097, 3103, 3108, 3113, 3118, 3124, 3129, 3134, 3139, 3145, 3150, 3155, 3160, 3166, 3171, 3176, 3181, 3187, 3192, 3197, 3202, 3208, 3213, 3218, 3223, 3229, 3234, 3239, 3244, 3249, 3254, 3259, 3264, 3269, 3274, 3279, 3284, 3289, 3294, 3299, 3304, 3309, 3314, 3319, 3324, 3329, 3334, 3339, 3344, 3349, 3355, 3361, 3367, 3373, 3380, 3387, 3393, 3399, 3405, 3411, 3417, 3423, 3430, 3435, 3451, 3456, 3461, 3469, 3469, 3480, 3480, 3490, 3493, 3506, 3528, 3555, 3559, 3565, 3570, 3581, 3585, 3591, 3597, 3608, 3611, 3618, 3622, 3623, 3629, 3630, 3631, 3632, 3633, 3634, 3635, 3637, 3643, 3652, 3653, 3657, 3653, 3669, 3670, 3674, 3674, 3681, 3681, 3695, 3698, 3706, 3714, 3725, 3726, 3730, 3734, 3742, 3749, 3753, 3761, 3765, 3778, 3782, 3790, 3790, 3810, 3813, 3819, 3831, 3843, 3847, 3855, 3855, 3870, 3870, 3886, 3886, 3907, 3910, 3916, 3919, 3925, 3929, 3936, 3941, 3946, 3953, 3956, 3960, 3965, 3969, 3979, 3983, 3992, 3995, 3999, 4008, 4008, 4050, 4055, 4058, 4063, 4066 }; #endif /** Accessing symbol of state STATE. */ #define YY_ACCESSING_SYMBOL(State) YY_CAST (yysymbol_kind_t, yystos[State]) #if 1 /* The user-facing name of the symbol whose (internal) number is YYSYMBOL. No bounds checking. */ static const char *yysymbol_name (yysymbol_kind_t yysymbol) YY_ATTRIBUTE_UNUSED; /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "\"end of file\"", "error", "\"invalid token\"", "CONST", "BOOL", "INT", "UINT", "FLOAT", "BVEC2", "BVEC3", "BVEC4", "IVEC2", "IVEC3", "IVEC4", "UVEC2", "UVEC3", "UVEC4", "VEC2", "VEC3", "VEC4", "MAT2", "MAT3", "MAT4", "MAT2X2", "MAT2X3", "MAT2X4", "MAT3X2", "MAT3X3", "MAT3X4", "MAT4X2", "MAT4X3", "MAT4X4", "SAMPLER2D", "SAMPLER3D", "SAMPLERCUBE", "SAMPLER2DSHADOW", "SAMPLERCUBESHADOW", "SAMPLER2DARRAY", "SAMPLER2DARRAYSHADOW", "ISAMPLER2D", "ISAMPLER3D", "ISAMPLERCUBE", "ISAMPLER2DARRAY", "USAMPLER2D", "USAMPLER3D", "USAMPLERCUBE", "USAMPLER2DARRAY", "SAMPLER", "SAMPLERSHADOW", "TEXTURE2D", "TEXTURE3D", "TEXTURECUBE", "TEXTURE2DARRAY", "ITEXTURE2D", "ITEXTURE3D", "ITEXTURECUBE", "ITEXTURE2DARRAY", "UTEXTURE2D", "UTEXTURE3D", "UTEXTURECUBE", "UTEXTURE2DARRAY", "ATTRIBUTE", "VARYING", "FLOAT16_T", "FLOAT32_T", "DOUBLE", "FLOAT64_T", "INT64_T", "UINT64_T", "INT32_T", "UINT32_T", "INT16_T", "UINT16_T", "INT8_T", "UINT8_T", "I64VEC2", "I64VEC3", "I64VEC4", "U64VEC2", "U64VEC3", "U64VEC4", "I32VEC2", "I32VEC3", "I32VEC4", "U32VEC2", "U32VEC3", "U32VEC4", "I16VEC2", "I16VEC3", "I16VEC4", "U16VEC2", "U16VEC3", "U16VEC4", "I8VEC2", "I8VEC3", "I8VEC4", "U8VEC2", "U8VEC3", "U8VEC4", "DVEC2", "DVEC3", "DVEC4", "DMAT2", "DMAT3", "DMAT4", "F16VEC2", "F16VEC3", "F16VEC4", "F16MAT2", "F16MAT3", "F16MAT4", "F32VEC2", "F32VEC3", "F32VEC4", "F32MAT2", "F32MAT3", "F32MAT4", "F64VEC2", "F64VEC3", "F64VEC4", "F64MAT2", "F64MAT3", "F64MAT4", "DMAT2X2", "DMAT2X3", "DMAT2X4", "DMAT3X2", "DMAT3X3", "DMAT3X4", "DMAT4X2", "DMAT4X3", "DMAT4X4", "F16MAT2X2", "F16MAT2X3", "F16MAT2X4", "F16MAT3X2", "F16MAT3X3", "F16MAT3X4", "F16MAT4X2", "F16MAT4X3", "F16MAT4X4", "F32MAT2X2", "F32MAT2X3", "F32MAT2X4", "F32MAT3X2", "F32MAT3X3", "F32MAT3X4", "F32MAT4X2", "F32MAT4X3", "F32MAT4X4", "F64MAT2X2", "F64MAT2X3", "F64MAT2X4", "F64MAT3X2", "F64MAT3X3", "F64MAT3X4", "F64MAT4X2", "F64MAT4X3", "F64MAT4X4", "ATOMIC_UINT", "ACCSTRUCTNV", "ACCSTRUCTEXT", "RAYQUERYEXT", "FCOOPMATNV", "ICOOPMATNV", "UCOOPMATNV", "SAMPLERCUBEARRAY", "SAMPLERCUBEARRAYSHADOW", "ISAMPLERCUBEARRAY", "USAMPLERCUBEARRAY", "SAMPLER1D", "SAMPLER1DARRAY", "SAMPLER1DARRAYSHADOW", "ISAMPLER1D", "SAMPLER1DSHADOW", "SAMPLER2DRECT", "SAMPLER2DRECTSHADOW", "ISAMPLER2DRECT", "USAMPLER2DRECT", "SAMPLERBUFFER", "ISAMPLERBUFFER", "USAMPLERBUFFER", "SAMPLER2DMS", "ISAMPLER2DMS", "USAMPLER2DMS", "SAMPLER2DMSARRAY", "ISAMPLER2DMSARRAY", "USAMPLER2DMSARRAY", "SAMPLEREXTERNALOES", "SAMPLEREXTERNAL2DY2YEXT", "ISAMPLER1DARRAY", "USAMPLER1D", "USAMPLER1DARRAY", "F16SAMPLER1D", "F16SAMPLER2D", "F16SAMPLER3D", "F16SAMPLER2DRECT", "F16SAMPLERCUBE", "F16SAMPLER1DARRAY", "F16SAMPLER2DARRAY", "F16SAMPLERCUBEARRAY", "F16SAMPLERBUFFER", "F16SAMPLER2DMS", "F16SAMPLER2DMSARRAY", "F16SAMPLER1DSHADOW", "F16SAMPLER2DSHADOW", "F16SAMPLER1DARRAYSHADOW", "F16SAMPLER2DARRAYSHADOW", "F16SAMPLER2DRECTSHADOW", "F16SAMPLERCUBESHADOW", "F16SAMPLERCUBEARRAYSHADOW", "IMAGE1D", "IIMAGE1D", "UIMAGE1D", "IMAGE2D", "IIMAGE2D", "UIMAGE2D", "IMAGE3D", "IIMAGE3D", "UIMAGE3D", "IMAGE2DRECT", "IIMAGE2DRECT", "UIMAGE2DRECT", "IMAGECUBE", "IIMAGECUBE", "UIMAGECUBE", "IMAGEBUFFER", "IIMAGEBUFFER", "UIMAGEBUFFER", "IMAGE1DARRAY", "IIMAGE1DARRAY", "UIMAGE1DARRAY", "IMAGE2DARRAY", "IIMAGE2DARRAY", "UIMAGE2DARRAY", "IMAGECUBEARRAY", "IIMAGECUBEARRAY", "UIMAGECUBEARRAY", "IMAGE2DMS", "IIMAGE2DMS", "UIMAGE2DMS", "IMAGE2DMSARRAY", "IIMAGE2DMSARRAY", "UIMAGE2DMSARRAY", "F16IMAGE1D", "F16IMAGE2D", "F16IMAGE3D", "F16IMAGE2DRECT", "F16IMAGECUBE", "F16IMAGE1DARRAY", "F16IMAGE2DARRAY", "F16IMAGECUBEARRAY", "F16IMAGEBUFFER", "F16IMAGE2DMS", "F16IMAGE2DMSARRAY", "I64IMAGE1D", "U64IMAGE1D", "I64IMAGE2D", "U64IMAGE2D", "I64IMAGE3D", "U64IMAGE3D", "I64IMAGE2DRECT", "U64IMAGE2DRECT", "I64IMAGECUBE", "U64IMAGECUBE", "I64IMAGEBUFFER", "U64IMAGEBUFFER", "I64IMAGE1DARRAY", "U64IMAGE1DARRAY", "I64IMAGE2DARRAY", "U64IMAGE2DARRAY", "I64IMAGECUBEARRAY", "U64IMAGECUBEARRAY", "I64IMAGE2DMS", "U64IMAGE2DMS", "I64IMAGE2DMSARRAY", "U64IMAGE2DMSARRAY", "TEXTURECUBEARRAY", "ITEXTURECUBEARRAY", "UTEXTURECUBEARRAY", "TEXTURE1D", "ITEXTURE1D", "UTEXTURE1D", "TEXTURE1DARRAY", "ITEXTURE1DARRAY", "UTEXTURE1DARRAY", "TEXTURE2DRECT", "ITEXTURE2DRECT", "UTEXTURE2DRECT", "TEXTUREBUFFER", "ITEXTUREBUFFER", "UTEXTUREBUFFER", "TEXTURE2DMS", "ITEXTURE2DMS", "UTEXTURE2DMS", "TEXTURE2DMSARRAY", "ITEXTURE2DMSARRAY", "UTEXTURE2DMSARRAY", "F16TEXTURE1D", "F16TEXTURE2D", "F16TEXTURE3D", "F16TEXTURE2DRECT", "F16TEXTURECUBE", "F16TEXTURE1DARRAY", "F16TEXTURE2DARRAY", "F16TEXTURECUBEARRAY", "F16TEXTUREBUFFER", "F16TEXTURE2DMS", "F16TEXTURE2DMSARRAY", "SUBPASSINPUT", "SUBPASSINPUTMS", "ISUBPASSINPUT", "ISUBPASSINPUTMS", "USUBPASSINPUT", "USUBPASSINPUTMS", "F16SUBPASSINPUT", "F16SUBPASSINPUTMS", "LEFT_OP", "RIGHT_OP", "INC_OP", "DEC_OP", "LE_OP", "GE_OP", "EQ_OP", "NE_OP", "AND_OP", "OR_OP", "XOR_OP", "MUL_ASSIGN", "DIV_ASSIGN", "ADD_ASSIGN", "MOD_ASSIGN", "LEFT_ASSIGN", "RIGHT_ASSIGN", "AND_ASSIGN", "XOR_ASSIGN", "OR_ASSIGN", "SUB_ASSIGN", "STRING_LITERAL", "LEFT_PAREN", "RIGHT_PAREN", "LEFT_BRACKET", "RIGHT_BRACKET", "LEFT_BRACE", "RIGHT_BRACE", "DOT", "COMMA", "COLON", "EQUAL", "SEMICOLON", "BANG", "DASH", "TILDE", "PLUS", "STAR", "SLASH", "PERCENT", "LEFT_ANGLE", "RIGHT_ANGLE", "VERTICAL_BAR", "CARET", "AMPERSAND", "QUESTION", "INVARIANT", "HIGH_PRECISION", "MEDIUM_PRECISION", "LOW_PRECISION", "PRECISION", "PACKED", "RESOURCE", "SUPERP", "FLOATCONSTANT", "INTCONSTANT", "UINTCONSTANT", "BOOLCONSTANT", "IDENTIFIER", "TYPE_NAME", "CENTROID", "IN", "OUT", "INOUT", "STRUCT", "VOID", "WHILE", "BREAK", "CONTINUE", "DO", "ELSE", "FOR", "IF", "DISCARD", "RETURN", "SWITCH", "CASE", "DEFAULT", "TERMINATE_INVOCATION", "TERMINATE_RAY", "IGNORE_INTERSECTION", "UNIFORM", "SHARED", "BUFFER", "FLAT", "SMOOTH", "LAYOUT", "DOUBLECONSTANT", "INT16CONSTANT", "UINT16CONSTANT", "FLOAT16CONSTANT", "INT32CONSTANT", "UINT32CONSTANT", "INT64CONSTANT", "UINT64CONSTANT", "SUBROUTINE", "DEMOTE", "PAYLOADNV", "PAYLOADINNV", "HITATTRNV", "CALLDATANV", "CALLDATAINNV", "PAYLOADEXT", "PAYLOADINEXT", "HITATTREXT", "CALLDATAEXT", "CALLDATAINEXT", "PATCH", "SAMPLE", "NONUNIFORM", "COHERENT", "VOLATILE", "RESTRICT", "READONLY", "WRITEONLY", "DEVICECOHERENT", "QUEUEFAMILYCOHERENT", "WORKGROUPCOHERENT", "SUBGROUPCOHERENT", "NONPRIVATE", "SHADERCALLCOHERENT", "NOPERSPECTIVE", "EXPLICITINTERPAMD", "PERVERTEXNV", "PERPRIMITIVENV", "PERVIEWNV", "PERTASKNV", "PRECISE", "$accept", "variable_identifier", "primary_expression", "postfix_expression", "integer_expression", "function_call", "function_call_or_method", "function_call_generic", "function_call_header_no_parameters", "function_call_header_with_parameters", "function_call_header", "function_identifier", "unary_expression", "unary_operator", "multiplicative_expression", "additive_expression", "shift_expression", "relational_expression", "equality_expression", "and_expression", "exclusive_or_expression", "inclusive_or_expression", "logical_and_expression", "logical_xor_expression", "logical_or_expression", "conditional_expression", "$@1", "assignment_expression", "assignment_operator", "expression", "constant_expression", "declaration", "block_structure", "$@2", "identifier_list", "function_prototype", "function_declarator", "function_header_with_parameters", "function_header", "parameter_declarator", "parameter_declaration", "parameter_type_specifier", "init_declarator_list", "single_declaration", "fully_specified_type", "invariant_qualifier", "interpolation_qualifier", "layout_qualifier", "layout_qualifier_id_list", "layout_qualifier_id", "precise_qualifier", "type_qualifier", "single_type_qualifier", "storage_qualifier", "non_uniform_qualifier", "type_name_list", "type_specifier", "array_specifier", "type_parameter_specifier_opt", "type_parameter_specifier", "type_parameter_specifier_list", "type_specifier_nonarray", "precision_qualifier", "struct_specifier", "$@3", "$@4", "struct_declaration_list", "struct_declaration", "struct_declarator_list", "struct_declarator", "initializer", "initializer_list", "declaration_statement", "statement", "simple_statement", "demote_statement", "compound_statement", "$@5", "$@6", "statement_no_new_scope", "statement_scoped", "$@7", "$@8", "compound_statement_no_new_scope", "statement_list", "expression_statement", "selection_statement", "selection_statement_nonattributed", "selection_rest_statement", "condition", "switch_statement", "switch_statement_nonattributed", "$@9", "switch_statement_list", "case_label", "iteration_statement", "iteration_statement_nonattributed", "$@10", "$@11", "$@12", "for_init_statement", "conditionopt", "for_rest_statement", "jump_statement", "translation_unit", "external_declaration", "function_definition", "$@13", "attribute", "attribute_list", "single_attribute", YY_NULLPTR }; static const char * yysymbol_name (yysymbol_kind_t yysymbol) { return yytname[yysymbol]; } #endif #ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_int16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699 }; #endif #define YYPACT_NINF (-741) #define yypact_value_is_default(Yyn) \ ((Yyn) == YYPACT_NINF) #define YYTABLE_NINF (-563) #define yytable_value_is_error(Yyn) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 4753, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -328, -741, -741, -741, -741, -741, 102, -741, -741, -741, -741, -741, 7, -741, -741, -741, -741, -741, -741, -322, -257, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, 10, 8, 47, 64, 6963, 87, -741, 46, -741, -741, -741, -741, 5195, -741, -741, -741, -741, 77, -741, -741, 775, -741, -741, 6963, 63, 20, -741, 104, -24, 106, -741, -330, -741, 121, 142, 6963, -741, -741, -741, 6963, 112, 115, -741, -334, -741, 22, -741, -741, 9942, 151, -741, -741, -741, 154, 125, 6963, 163, 24, -741, 155, 6963, -741, 157, -741, 18, -741, -741, 38, 8250, -741, -329, 1217, -741, -741, -741, -741, -741, 151, -325, -741, 8673, 12, -741, 128, -741, 94, 9942, 9942, -741, 9942, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, 86, -741, -741, -741, 167, 68, 10365, 170, -741, 9942, -741, -741, -343, 172, 142, 176, 9942, 169, 63, -741, 6963, 143, 5637, -741, 6963, 9942, -741, -24, -741, 144, -741, -741, 116, 16, -296, 41, 150, 156, 160, 164, 197, 199, 21, 182, 9096, -741, 183, -741, -741, 189, 193, 194, -741, 192, 205, 196, 9519, 207, 9942, 201, 208, 210, 211, 212, 204, -741, -741, 96, -741, 8, 214, 217, -741, -741, -741, -741, -741, 1659, -741, -741, -741, -741, -741, -741, -741, -741, -741, 4311, 172, 8673, 13, 7404, -741, -741, 8673, 6963, -741, 187, -741, -741, -741, 69, -741, -741, 9942, 190, -741, -741, 9942, 226, -741, -741, -741, 9942, -741, -741, -741, 227, -741, -741, 143, 151, 108, -741, -741, -741, 6079, -741, -741, -741, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, 9942, -741, -741, -741, 228, -741, 2101, -741, -741, -741, 2101, -741, 9942, -741, -741, 113, 9942, 131, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, 9942, 9942, -741, -741, -741, -741, -741, -741, -741, 8673, -741, -741, 109, -741, 6521, -741, -741, 229, 222, -741, -741, -741, -741, 114, 172, 143, -741, -741, -741, -741, -741, 116, 116, 16, 16, -296, -296, -296, -296, 41, 41, 150, 156, 160, 164, 197, 199, 9942, -741, 2101, 3869, 186, 3427, 80, -741, 84, -741, -741, -741, -741, -741, 7827, -741, -741, -741, -741, 133, 230, 222, 200, 236, 238, -741, -741, 3869, 235, -741, -741, -741, 9942, -741, 231, 2543, 9942, -741, 233, 240, 198, 241, 2985, -741, 244, -741, 8673, -741, -741, -741, 89, 9942, 2543, 235, -741, -741, 2101, -741, 234, 222, -741, -741, 2101, 245, -741, -741 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_int16 yydefact[] = { 0, 160, 213, 211, 212, 210, 217, 218, 219, 220, 221, 222, 223, 224, 225, 214, 215, 216, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 339, 340, 341, 342, 343, 344, 345, 365, 366, 367, 368, 369, 370, 371, 380, 393, 394, 381, 382, 384, 383, 385, 386, 387, 388, 389, 390, 391, 392, 168, 169, 239, 240, 238, 241, 248, 249, 246, 247, 244, 245, 242, 243, 271, 272, 273, 283, 284, 285, 268, 269, 270, 280, 281, 282, 265, 266, 267, 277, 278, 279, 262, 263, 264, 274, 275, 276, 250, 251, 252, 286, 287, 288, 253, 254, 255, 298, 299, 300, 256, 257, 258, 310, 311, 312, 259, 260, 261, 322, 323, 324, 289, 290, 291, 292, 293, 294, 295, 296, 297, 301, 302, 303, 304, 305, 306, 307, 308, 309, 313, 314, 315, 316, 317, 318, 319, 320, 321, 325, 326, 327, 328, 329, 330, 331, 332, 333, 337, 334, 335, 336, 518, 519, 520, 349, 350, 373, 376, 338, 347, 348, 364, 346, 395, 396, 399, 400, 401, 403, 404, 405, 407, 408, 409, 411, 412, 508, 509, 372, 374, 375, 351, 352, 353, 397, 354, 358, 359, 362, 402, 406, 410, 355, 356, 360, 361, 398, 357, 363, 442, 444, 445, 446, 448, 449, 450, 452, 453, 454, 456, 457, 458, 460, 461, 462, 464, 465, 466, 468, 469, 470, 472, 473, 474, 476, 477, 478, 480, 481, 482, 484, 485, 443, 447, 451, 455, 459, 467, 471, 475, 463, 479, 483, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 377, 378, 379, 413, 422, 424, 418, 423, 425, 426, 428, 429, 430, 432, 433, 434, 436, 437, 438, 440, 441, 414, 415, 416, 427, 417, 419, 420, 421, 431, 435, 439, 510, 511, 514, 515, 516, 517, 512, 513, 0, 613, 135, 523, 524, 525, 0, 522, 164, 162, 163, 161, 0, 209, 165, 166, 167, 137, 136, 0, 193, 174, 176, 172, 178, 180, 175, 177, 173, 179, 181, 170, 171, 195, 182, 189, 190, 191, 192, 183, 184, 185, 186, 187, 188, 138, 139, 140, 141, 142, 143, 150, 612, 0, 614, 0, 112, 111, 0, 123, 128, 157, 156, 154, 158, 0, 151, 153, 159, 133, 205, 155, 521, 0, 609, 611, 0, 0, 0, 528, 0, 0, 0, 97, 0, 94, 0, 107, 0, 119, 113, 121, 0, 122, 0, 95, 129, 100, 0, 152, 134, 0, 198, 204, 1, 610, 0, 0, 0, 619, 0, 617, 0, 0, 526, 147, 149, 0, 145, 196, 0, 0, 98, 0, 0, 615, 108, 114, 118, 120, 116, 124, 115, 0, 130, 103, 0, 101, 0, 0, 0, 9, 0, 43, 42, 44, 41, 5, 6, 7, 8, 2, 16, 14, 15, 17, 10, 11, 12, 13, 3, 18, 37, 20, 25, 26, 0, 0, 30, 0, 207, 0, 36, 34, 0, 199, 109, 0, 0, 0, 0, 96, 0, 0, 0, 530, 0, 0, 144, 0, 194, 0, 200, 45, 49, 52, 55, 60, 63, 65, 67, 69, 71, 73, 75, 0, 0, 99, 557, 566, 570, 0, 0, 0, 591, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 45, 78, 91, 0, 544, 0, 159, 133, 547, 568, 546, 554, 545, 0, 548, 549, 572, 550, 579, 551, 552, 587, 553, 0, 117, 0, 125, 0, 538, 132, 0, 0, 105, 0, 102, 38, 39, 0, 22, 23, 0, 0, 28, 27, 0, 209, 31, 33, 40, 0, 206, 110, 93, 0, 616, 618, 0, 536, 0, 534, 529, 531, 0, 148, 146, 197, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 201, 202, 0, 556, 0, 589, 602, 601, 0, 593, 0, 605, 603, 0, 0, 0, 586, 606, 607, 608, 555, 81, 82, 84, 83, 86, 87, 88, 89, 90, 85, 80, 0, 0, 571, 567, 569, 573, 580, 588, 127, 0, 541, 542, 0, 131, 0, 106, 4, 0, 24, 21, 32, 208, 620, 0, 537, 0, 532, 527, 46, 47, 48, 51, 50, 53, 54, 58, 59, 56, 57, 61, 62, 64, 66, 68, 70, 72, 74, 0, 203, 558, 0, 0, 0, 0, 604, 0, 585, 79, 92, 126, 539, 0, 104, 19, 533, 535, 0, 0, 577, 0, 0, 0, 596, 595, 598, 564, 581, 540, 543, 0, 559, 0, 0, 0, 597, 0, 0, 576, 0, 0, 574, 0, 77, 0, 561, 590, 560, 0, 599, 0, 564, 563, 565, 583, 578, 0, 600, 594, 575, 584, 0, 592, 582 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, -741, 10266, -741, -125, -124, -165, -123, -32, -30, -27, -31, -26, -29, -741, -80, -741, -110, -741, -116, 92, 4, -741, -741, -741, 6, -48, -741, -741, 195, 202, 206, -741, -741, -52, -741, -741, -741, -741, 93, -741, -17, -28, -741, 9, -741, 0, -69, -741, -741, -741, -741, 278, -741, -741, -741, -491, -159, 3, -83, -222, -741, -107, -217, -740, -741, -141, -741, -741, -151, -150, -741, -741, 213, -286, -103, -741, 51, -741, -122, -741, 52, -741, -741, -741, -741, 54, -741, -741, -741, -741, -741, -741, -741, -741, 232, -741, -741, 2, -741, 124 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { 0, 475, 476, 477, 676, 478, 479, 480, 481, 482, 483, 484, 541, 486, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 542, 706, 543, 659, 544, 594, 545, 368, 572, 453, 546, 370, 371, 372, 404, 405, 406, 373, 374, 375, 376, 377, 378, 432, 433, 379, 380, 381, 382, 487, 435, 488, 438, 417, 418, 489, 385, 386, 387, 501, 428, 499, 500, 599, 600, 570, 671, 549, 550, 551, 552, 553, 631, 726, 754, 746, 747, 748, 755, 554, 555, 556, 557, 749, 729, 558, 559, 750, 769, 560, 561, 562, 709, 635, 711, 733, 744, 745, 563, 388, 389, 390, 401, 564, 425, 426 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 384, 753, 391, 590, 367, 447, 369, 436, 761, 383, 603, 436, 521, 392, 448, 591, 436, 396, 753, 437, 522, 612, 613, 566, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 673, 397, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 663, 569, 422, 602, 578, 449, 421, 667, 708, 670, 625, 490, 672, 394, 430, 414, 521, 521, 407, 520, 400, 503, 398, 571, 668, 614, 615, 504, 450, 494, 610, 451, 611, 495, 452, 408, 587, 423, 431, 565, 567, 505, 414, 415, 383, 395, 626, 506, 399, 407, 402, 384, 383, 391, 384, 367, 427, 369, 414, 322, 383, 616, 617, 383, 327, 328, 408, 441, 579, 580, 408, 584, 675, 403, 497, 383, 593, 585, 660, 383, 640, 710, 642, 734, 411, 593, 415, 735, -35, 660, 581, 498, 764, 660, 582, 383, 409, 416, 660, 410, 383, 424, 548, 574, 629, 660, 575, 602, 661, 718, 429, 547, 694, 695, 696, 697, 719, 684, 720, 569, 685, 569, 660, 684, 569, 713, 723, 439, 677, 318, 319, 320, 414, 607, 608, 609, 618, 619, 679, 768, 660, 715, 660, 738, 434, 497, 315, 497, 690, 691, 445, 692, 693, 446, 663, 436, 592, 491, 698, 699, 597, 737, 498, 492, 498, 493, 573, 496, 502, 383, 583, 383, 588, 383, 595, 422, 521, 602, 447, 421, 620, 598, 606, 621, 712, 623, 622, 627, 714, 624, 630, 632, 683, 763, 636, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 633, 634, 637, 638, 641, 423, 643, 716, 717, 663, 658, -36, 548, 497, -34, 644, 569, 645, 646, 647, 674, 547, 384, 678, -29, 681, 660, 730, 707, 722, 498, 383, 739, 740, 741, 742, -562, 752, 758, 383, 757, 770, 523, 759, 497, 762, 700, 771, 725, 701, 703, 727, 604, 702, 705, 605, 704, 393, 682, 724, 443, 498, 731, 442, 760, 766, 732, 767, 569, 743, 383, 444, 440, 664, 665, 727, 666, 596, 420, 0, 0, 0, 0, 0, 756, 0, 751, 0, 0, 548, 0, 0, 0, 548, 0, 0, 0, 0, 547, 765, 569, 0, 547, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 497, 728, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 498, 0, 0, 0, 0, 0, 0, 0, 728, 383, 0, 0, 0, 0, 0, 0, 0, 0, 0, 423, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 548, 548, 0, 548, 0, 391, 0, 0, 423, 547, 547, 0, 547, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 548, 0, 0, 0, 0, 0, 0, 0, 548, 547, 0, 0, 0, 0, 0, 548, 0, 547, 0, 0, 0, 0, 0, 0, 547, 548, 0, 0, 0, 548, 0, 0, 0, 0, 547, 548, 0, 0, 547, 0, 0, 0, 419, 0, 547, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 315, 0, 0, 0, 0, 0, 0, 0, 316, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 321, 0, 0, 0, 0, 0, 0, 0, 0, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 0, 0, 0, 0, 0, 0, 0, 0, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 315, 0, 523, 524, 0, 0, 0, 0, 525, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 321, 0, 0, 0, 462, 463, 464, 465, 466, 322, 323, 324, 325, 326, 327, 328, 526, 527, 528, 529, 0, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 329, 330, 331, 332, 333, 334, 467, 468, 469, 470, 471, 472, 473, 474, 335, 540, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 315, 0, 523, 662, 0, 0, 0, 0, 525, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 321, 0, 0, 0, 462, 463, 464, 465, 466, 322, 323, 324, 325, 326, 327, 328, 526, 527, 528, 529, 0, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 329, 330, 331, 332, 333, 334, 467, 468, 469, 470, 471, 472, 473, 474, 335, 540, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 315, 0, 523, 0, 0, 0, 0, 0, 525, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 321, 0, 0, 0, 462, 463, 464, 465, 466, 322, 323, 324, 325, 326, 327, 328, 526, 527, 528, 529, 0, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 329, 330, 331, 332, 333, 334, 467, 468, 469, 470, 471, 472, 473, 474, 335, 540, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 315, 0, 439, 0, 0, 0, 0, 0, 525, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 321, 0, 0, 0, 462, 463, 464, 465, 466, 322, 323, 324, 325, 326, 327, 328, 526, 527, 528, 529, 0, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 329, 330, 331, 332, 333, 334, 467, 468, 469, 470, 471, 472, 473, 474, 335, 540, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 315, 0, 0, 0, 0, 0, 0, 0, 525, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 321, 0, 0, 0, 462, 463, 464, 465, 466, 322, 323, 324, 325, 326, 327, 328, 526, 527, 528, 529, 0, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 329, 330, 331, 332, 333, 334, 467, 468, 469, 470, 471, 472, 473, 474, 335, 540, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 315, 0, 0, 0, 0, 0, 0, 0, 525, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 321, 0, 0, 0, 462, 463, 464, 465, 466, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 467, 468, 469, 470, 471, 472, 473, 474, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 467, 468, 469, 470, 471, 472, 473, 474, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 322, 323, 324, 325, 326, 327, 328, 526, 0, 0, 529, 0, 530, 531, 0, 0, 534, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 0, 0, 0, 0, 0, 0, 0, 0, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 315, 0, 0, 0, 0, 0, 0, 0, 316, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 321, 0, 0, 0, 0, 0, 0, 0, 0, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 0, 0, 0, 0, 0, 0, 0, 0, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 412, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 0, 0, 0, 0, 0, 0, 0, 0, 413, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 0, 0, 0, 0, 0, 0, 0, 0, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 601, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 0, 0, 0, 0, 0, 0, 0, 0, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 686, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 0, 0, 0, 0, 0, 0, 0, 0, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 721, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 0, 0, 0, 0, 0, 0, 0, 0, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 317, 318, 319, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 322, 323, 324, 325, 326, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 329, 330, 331, 332, 333, 334, 0, 0, 0, 0, 0, 0, 0, 0, 335, 0, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 0, 0, 568, 669, 0, 0, 0, 0, 0, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 0, 0, 0, 0, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 467, 468, 469, 470, 471, 472, 473, 474, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 348, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 0, 0, 568, 736, 0, 0, 0, 0, 0, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 0, 0, 0, 0, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 467, 468, 469, 470, 471, 472, 473, 474, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 348, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 0, 507, 0, 0, 0, 0, 0, 0, 0, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 0, 0, 0, 0, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 467, 468, 469, 470, 471, 472, 473, 474, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 348, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 0, 0, 568, 0, 0, 0, 0, 0, 0, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 0, 0, 0, 0, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 467, 468, 469, 470, 471, 472, 473, 474, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 348, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 0, 628, 0, 0, 0, 0, 0, 0, 0, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 0, 0, 0, 0, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 467, 468, 469, 470, 471, 472, 473, 474, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 348, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 0, 0, 0, 0, 0, 0, 0, 0, 639, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 0, 0, 0, 0, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 467, 468, 469, 470, 471, 472, 473, 474, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 348, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 0, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 457, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 458, 459, 460, 461, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 0, 0, 0, 0, 327, 328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 467, 468, 469, 470, 471, 472, 473, 474, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 348, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 485, 0, 454, 455, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 508, 456, 457, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 458, 459, 460, 461, 0, 576, 577, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 462, 463, 464, 465, 466, 322, 0, 0, 0, 0, 327, 586, 0, 0, 0, 0, 589, 0, 0, 0, 0, 0, 0, 508, 0, 0, 0, 0, 0, 0, 0, 0, 508, 467, 468, 469, 470, 471, 472, 473, 474, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 508, 0, 0, 0, 348, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 680, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 687, 688, 689, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508 }; static const yytype_int16 yycheck[] = { 0, 741, 0, 346, 0, 339, 0, 341, 748, 0, 501, 341, 341, 341, 348, 358, 341, 339, 758, 349, 349, 317, 318, 348, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 572, 339, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 554, 448, 391, 499, 457, 411, 391, 566, 631, 568, 326, 417, 571, 343, 375, 380, 341, 341, 372, 436, 349, 340, 349, 348, 348, 321, 322, 346, 343, 342, 351, 346, 353, 346, 349, 372, 483, 391, 399, 445, 446, 340, 407, 380, 372, 375, 362, 346, 375, 403, 340, 388, 380, 388, 391, 388, 393, 388, 423, 376, 388, 357, 358, 391, 381, 382, 403, 402, 319, 320, 407, 340, 340, 346, 428, 403, 493, 346, 346, 407, 533, 635, 535, 340, 375, 502, 423, 340, 339, 346, 341, 428, 340, 346, 345, 423, 346, 357, 346, 349, 428, 375, 439, 346, 521, 346, 349, 603, 349, 668, 343, 439, 614, 615, 616, 617, 344, 346, 346, 566, 349, 568, 346, 346, 571, 349, 349, 343, 581, 364, 365, 366, 497, 354, 355, 356, 323, 324, 585, 762, 346, 347, 346, 347, 375, 499, 341, 501, 610, 611, 375, 612, 613, 375, 708, 341, 491, 340, 618, 619, 497, 720, 499, 375, 501, 339, 375, 349, 348, 497, 340, 499, 339, 501, 342, 564, 341, 673, 339, 564, 361, 375, 375, 360, 637, 325, 359, 342, 641, 327, 344, 339, 598, 752, 339, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 349, 349, 339, 349, 339, 564, 347, 659, 660, 768, 348, 339, 554, 572, 339, 349, 668, 349, 349, 349, 375, 554, 564, 375, 340, 340, 346, 383, 342, 342, 572, 564, 344, 375, 340, 339, 343, 348, 340, 572, 349, 349, 343, 387, 603, 343, 620, 344, 706, 621, 623, 709, 502, 622, 625, 504, 624, 321, 597, 684, 407, 603, 711, 403, 747, 758, 711, 759, 720, 733, 603, 407, 401, 564, 564, 733, 564, 495, 388, -1, -1, -1, -1, -1, 742, -1, 738, -1, -1, 631, -1, -1, -1, 635, -1, -1, -1, -1, 631, 757, 752, -1, 635, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 673, 709, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 673, -1, -1, -1, -1, -1, -1, -1, 733, 673, -1, -1, -1, -1, -1, -1, -1, -1, -1, 709, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 708, 709, -1, 711, -1, 711, -1, -1, 733, 708, 709, -1, 711, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 733, -1, -1, -1, -1, -1, -1, -1, 741, 733, -1, -1, -1, -1, -1, 748, -1, 741, -1, -1, -1, -1, -1, -1, 748, 758, -1, -1, -1, 762, -1, -1, -1, -1, 758, 768, -1, -1, 762, -1, -1, -1, 0, -1, 768, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 341, -1, -1, -1, -1, -1, -1, -1, 349, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, 367, -1, -1, -1, -1, -1, -1, -1, -1, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, -1, -1, -1, -1, -1, -1, -1, -1, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, 341, -1, 343, 344, -1, -1, -1, -1, 349, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, 367, -1, -1, -1, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, -1, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, 341, -1, 343, 344, -1, -1, -1, -1, 349, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, 367, -1, -1, -1, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, -1, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, 341, -1, 343, -1, -1, -1, -1, -1, 349, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, 367, -1, -1, -1, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, -1, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, 341, -1, 343, -1, -1, -1, -1, -1, 349, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, 367, -1, -1, -1, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, -1, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, 341, -1, -1, -1, -1, -1, -1, -1, 349, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, 367, -1, -1, -1, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, -1, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, 341, -1, -1, -1, -1, -1, -1, -1, 349, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, 367, -1, -1, -1, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, -1, -1, -1, -1, -1, -1, -1, -1, -1, 376, 377, 378, 379, 380, 381, 382, 383, -1, -1, 386, -1, 388, 389, -1, -1, 392, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, -1, -1, -1, -1, -1, -1, -1, -1, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 341, -1, -1, -1, -1, -1, -1, -1, 349, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, 367, -1, -1, -1, -1, -1, -1, -1, -1, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, -1, -1, -1, -1, -1, -1, -1, -1, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 349, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, -1, -1, -1, -1, -1, -1, -1, -1, 375, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, -1, -1, -1, -1, -1, -1, -1, -1, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 344, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, -1, -1, -1, -1, -1, -1, -1, -1, -1, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, -1, -1, -1, -1, -1, -1, -1, -1, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 344, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, -1, -1, -1, -1, -1, -1, -1, -1, -1, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, -1, -1, -1, -1, -1, -1, -1, -1, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 344, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, -1, -1, -1, -1, -1, -1, -1, -1, -1, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, -1, -1, -1, -1, -1, -1, -1, -1, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 363, 364, 365, 366, -1, -1, -1, -1, -1, -1, -1, -1, -1, 376, 377, 378, 379, 380, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 398, 399, 400, 401, 402, 403, -1, -1, -1, -1, -1, -1, -1, -1, 412, -1, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, -1, -1, 343, 344, -1, -1, -1, -1, -1, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, -1, -1, -1, -1, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 404, 405, 406, 407, 408, 409, 410, 411, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 426, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, -1, -1, 343, 344, -1, -1, -1, -1, -1, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, -1, -1, -1, -1, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 404, 405, 406, 407, 408, 409, 410, 411, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 426, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, -1, 342, -1, -1, -1, -1, -1, -1, -1, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, -1, -1, -1, -1, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 404, 405, 406, 407, 408, 409, 410, 411, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 426, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, -1, -1, 343, -1, -1, -1, -1, -1, -1, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, -1, -1, -1, -1, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 404, 405, 406, 407, 408, 409, 410, 411, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 426, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, -1, 342, -1, -1, -1, -1, -1, -1, -1, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, -1, -1, -1, -1, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 404, 405, 406, 407, 408, 409, 410, 411, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 426, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, -1, -1, -1, -1, -1, -1, -1, -1, 349, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, -1, -1, -1, -1, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 404, 405, 406, 407, 408, 409, 410, 411, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 426, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, -1, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 338, 339, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 350, 351, 352, 353, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, -1, -1, -1, -1, 381, 382, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 404, 405, 406, 407, 408, 409, 410, 411, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 426, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 416, -1, 319, 320, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 436, 338, 339, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 350, 351, 352, 353, -1, 454, 455, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 371, 372, 373, 374, 375, 376, -1, -1, -1, -1, 381, 382, -1, -1, -1, -1, 486, -1, -1, -1, -1, -1, -1, 493, -1, -1, -1, -1, -1, -1, -1, -1, 502, 404, 405, 406, 407, 408, 409, 410, 411, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 521, -1, -1, -1, 426, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 590, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_int16 yystos[] = { 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 341, 349, 363, 364, 365, 366, 367, 376, 377, 378, 379, 380, 381, 382, 398, 399, 400, 401, 402, 403, 412, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 476, 477, 480, 481, 482, 483, 487, 488, 489, 490, 491, 492, 495, 496, 497, 498, 499, 501, 506, 507, 508, 549, 550, 551, 553, 341, 507, 343, 375, 339, 339, 349, 375, 349, 552, 340, 346, 484, 485, 486, 496, 501, 346, 349, 375, 349, 375, 497, 501, 357, 503, 504, 0, 550, 481, 489, 496, 375, 554, 555, 501, 510, 343, 375, 399, 493, 494, 375, 500, 341, 349, 502, 343, 528, 553, 485, 484, 486, 375, 375, 339, 348, 502, 343, 346, 349, 479, 319, 320, 338, 339, 350, 351, 352, 353, 371, 372, 373, 374, 375, 404, 405, 406, 407, 408, 409, 410, 411, 446, 447, 448, 450, 451, 452, 453, 454, 455, 456, 457, 458, 499, 501, 505, 502, 340, 375, 339, 342, 346, 349, 496, 501, 511, 512, 509, 348, 340, 346, 340, 346, 342, 457, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 341, 349, 343, 344, 349, 383, 384, 385, 386, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 413, 457, 470, 472, 474, 476, 480, 499, 501, 517, 518, 519, 520, 521, 529, 530, 531, 532, 535, 536, 539, 540, 541, 548, 553, 502, 348, 502, 343, 472, 515, 348, 478, 375, 346, 349, 457, 457, 474, 319, 320, 341, 345, 340, 340, 346, 382, 472, 339, 457, 346, 358, 553, 470, 475, 342, 555, 501, 375, 513, 514, 344, 512, 511, 475, 494, 375, 354, 355, 356, 351, 353, 317, 318, 321, 322, 357, 358, 323, 324, 361, 360, 359, 325, 327, 326, 362, 342, 342, 470, 344, 522, 339, 349, 349, 543, 339, 339, 349, 349, 474, 339, 474, 347, 349, 349, 349, 349, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 348, 473, 346, 349, 344, 518, 532, 536, 541, 515, 348, 344, 515, 516, 515, 511, 375, 340, 449, 474, 375, 472, 457, 340, 513, 502, 346, 349, 344, 457, 457, 457, 459, 459, 460, 460, 461, 461, 461, 461, 462, 462, 463, 464, 465, 466, 467, 468, 471, 342, 529, 542, 518, 544, 474, 349, 474, 347, 472, 472, 515, 344, 346, 344, 342, 349, 514, 474, 523, 474, 489, 534, 383, 517, 530, 545, 340, 340, 344, 515, 347, 344, 375, 340, 339, 534, 546, 547, 525, 526, 527, 533, 537, 472, 348, 519, 524, 528, 474, 349, 340, 387, 521, 519, 343, 515, 340, 474, 524, 525, 529, 538, 349, 344 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_int16 yyr1[] = { 0, 445, 446, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 448, 448, 448, 448, 448, 448, 449, 450, 451, 452, 452, 453, 453, 454, 454, 455, 456, 456, 456, 457, 457, 457, 457, 458, 458, 458, 458, 459, 459, 459, 459, 460, 460, 460, 461, 461, 461, 462, 462, 462, 462, 462, 463, 463, 463, 464, 464, 465, 465, 466, 466, 467, 467, 468, 468, 469, 469, 470, 471, 470, 472, 472, 473, 473, 473, 473, 473, 473, 473, 473, 473, 473, 473, 474, 474, 475, 476, 476, 476, 476, 476, 476, 476, 476, 476, 478, 477, 479, 479, 480, 480, 480, 480, 481, 481, 482, 482, 483, 484, 484, 485, 485, 485, 485, 486, 487, 487, 487, 487, 487, 488, 488, 488, 488, 488, 489, 489, 490, 491, 491, 491, 491, 491, 491, 491, 491, 492, 493, 493, 494, 494, 494, 495, 496, 496, 497, 497, 497, 497, 497, 497, 497, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 499, 500, 500, 501, 501, 502, 502, 502, 502, 503, 503, 504, 505, 505, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 507, 507, 507, 509, 508, 510, 508, 511, 511, 512, 512, 513, 513, 514, 514, 515, 515, 515, 515, 516, 516, 517, 518, 518, 519, 519, 519, 519, 519, 519, 519, 519, 520, 521, 522, 523, 521, 524, 524, 526, 525, 527, 525, 528, 528, 529, 529, 530, 530, 531, 531, 532, 533, 533, 534, 534, 535, 535, 537, 536, 538, 538, 539, 539, 540, 540, 542, 541, 543, 541, 544, 541, 545, 545, 546, 546, 547, 547, 548, 548, 548, 548, 548, 548, 548, 548, 549, 549, 550, 550, 550, 552, 551, 553, 554, 554, 555, 555 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_int8 yyr2[] = { 0, 2, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 3, 2, 2, 1, 1, 1, 2, 2, 2, 1, 2, 3, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 3, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 0, 6, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 2, 2, 4, 2, 3, 4, 2, 3, 4, 0, 6, 2, 3, 2, 3, 3, 4, 1, 1, 2, 3, 3, 2, 3, 2, 1, 2, 1, 1, 1, 3, 4, 6, 5, 1, 2, 3, 5, 4, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 3, 1, 3, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 1, 3, 2, 3, 2, 3, 3, 4, 1, 0, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 6, 0, 5, 1, 2, 3, 4, 1, 3, 1, 2, 1, 3, 4, 2, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 0, 0, 5, 1, 1, 0, 2, 0, 2, 2, 3, 1, 2, 1, 2, 1, 2, 5, 3, 1, 1, 4, 1, 2, 0, 8, 0, 1, 3, 2, 1, 2, 0, 6, 0, 8, 0, 7, 1, 1, 1, 0, 2, 3, 2, 2, 2, 3, 2, 2, 2, 2, 1, 2, 1, 1, 1, 0, 3, 5, 1, 3, 1, 4 }; enum { YYENOMEM = -2 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (pParseContext, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Backward compatibility with an undocumented macro. Use YYerror or YYUNDEF. */ #define YYERRCODE YYUNDEF /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* This macro is provided for backward compatibility. */ # ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif # define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Kind, Value, pParseContext); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep, glslang::TParseContext* pParseContext) { FILE *yyoutput = yyo; YY_USE (yyoutput); YY_USE (pParseContext); if (!yyvaluep) return; # ifdef YYPRINT if (yykind < YYNTOKENS) YYPRINT (yyo, yytoknum[yykind], *yyvaluep); # endif YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YY_USE (yykind); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep, glslang::TParseContext* pParseContext) { YYFPRINTF (yyo, "%s %s (", yykind < YYNTOKENS ? "token" : "nterm", yysymbol_name (yykind)); yy_symbol_value_print (yyo, yykind, yyvaluep, pParseContext); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yy_state_t *yybottom, yy_state_t *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yy_state_t *yyssp, YYSTYPE *yyvsp, int yyrule, glslang::TParseContext* pParseContext) { int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %d):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, YY_ACCESSING_SYMBOL (+yyssp[yyi + 1 - yynrhs]), &yyvsp[(yyi + 1) - (yynrhs)], pParseContext); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule, pParseContext); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) ((void) 0) # define YY_SYMBOL_PRINT(Title, Kind, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif /* Context of a parse error. */ typedef struct { yy_state_t *yyssp; yysymbol_kind_t yytoken; } yypcontext_t; /* Put in YYARG at most YYARGN of the expected tokens given the current YYCTX, and return the number of tokens stored in YYARG. If YYARG is null, return the number of expected tokens (guaranteed to be less than YYNTOKENS). Return YYENOMEM on memory exhaustion. Return 0 if there are more than YYARGN expected tokens, yet fill YYARG up to YYARGN. */ static int yypcontext_expected_tokens (const yypcontext_t *yyctx, yysymbol_kind_t yyarg[], int yyargn) { /* Actual size of YYARG. */ int yycount = 0; int yyn = yypact[+*yyctx->yyssp]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYSYMBOL_YYerror && !yytable_value_is_error (yytable[yyx + yyn])) { if (!yyarg) ++yycount; else if (yycount == yyargn) return 0; else yyarg[yycount++] = YY_CAST (yysymbol_kind_t, yyx); } } if (yyarg && yycount == 0 && 0 < yyargn) yyarg[0] = YYSYMBOL_YYEMPTY; return yycount; } #ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen(S) (YY_CAST (YYPTRDIFF_T, strlen (S))) # else /* Return the length of YYSTR. */ static YYPTRDIFF_T yystrlen (const char *yystr) { YYPTRDIFF_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif #endif #ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif #endif #ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYPTRDIFF_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYPTRDIFF_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; else goto append; append: default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (yyres) return yystpcpy (yyres, yystr) - yyres; else return yystrlen (yystr); } #endif static int yy_syntax_error_arguments (const yypcontext_t *yyctx, yysymbol_kind_t yyarg[], int yyargn) { /* Actual size of YYARG. */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yyctx->yytoken != YYSYMBOL_YYEMPTY) { int yyn; if (yyarg) yyarg[yycount] = yyctx->yytoken; ++yycount; yyn = yypcontext_expected_tokens (yyctx, yyarg ? yyarg + 1 : yyarg, yyargn - 1); if (yyn == YYENOMEM) return YYENOMEM; else yycount += yyn; } return yycount; } /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return -1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return YYENOMEM if the required number of bytes is too large to store. */ static int yysyntax_error (YYPTRDIFF_T *yymsg_alloc, char **yymsg, const yypcontext_t *yyctx) { enum { YYARGS_MAX = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat: reported tokens (one for the "unexpected", one per "expected"). */ yysymbol_kind_t yyarg[YYARGS_MAX]; /* Cumulated lengths of YYARG. */ YYPTRDIFF_T yysize = 0; /* Actual size of YYARG. */ int yycount = yy_syntax_error_arguments (yyctx, yyarg, YYARGS_MAX); if (yycount == YYENOMEM) return YYENOMEM; switch (yycount) { #define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); #undef YYCASE_ } /* Compute error message size. Don't count the "%s"s, but reserve room for the terminator. */ yysize = yystrlen (yyformat) - 2 * yycount + 1; { int yyi; for (yyi = 0; yyi < yycount; ++yyi) { YYPTRDIFF_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyarg[yyi]]); if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM) yysize = yysize1; else return YYENOMEM; } } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return -1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yytname[yyarg[yyi++]]); yyformat += 2; } else { ++yyp; ++yyformat; } } return 0; } /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, yysymbol_kind_t yykind, YYSTYPE *yyvaluep, glslang::TParseContext* pParseContext) { YY_USE (yyvaluep); YY_USE (pParseContext); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yykind, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YY_USE (yykind); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*----------. | yyparse. | `----------*/ int yyparse (glslang::TParseContext* pParseContext) { /* Lookahead token kind. */ int yychar; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Number of syntax errors so far. */ int yynerrs = 0; yy_state_fast_t yystate = 0; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus = 0; /* Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* Their size. */ YYPTRDIFF_T yystacksize = YYINITDEPTH; /* The state stack: array, bottom, top. */ yy_state_t yyssa[YYINITDEPTH]; yy_state_t *yyss = yyssa; yy_state_t *yyssp = yyss; /* The semantic value stack: array, bottom, top. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp = yyvs; int yyn; /* The return value of yyparse. */ int yyresult; /* Lookahead symbol kind. */ yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYPTRDIFF_T yymsg_alloc = sizeof yymsgbuf; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; /*--------------------------------------------------------------------. | yysetstate -- set current state (the top of the stack) to yystate. | `--------------------------------------------------------------------*/ yysetstate: YYDPRINTF ((stderr, "Entering state %d\n", yystate)); YY_ASSERT (0 <= yystate && yystate < YYNSTATES); YY_IGNORE_USELESS_CAST_BEGIN *yyssp = YY_CAST (yy_state_t, yystate); YY_IGNORE_USELESS_CAST_END YY_STACK_PRINT (yyss, yyssp); if (yyss + yystacksize - 1 <= yyssp) #if !defined yyoverflow && !defined YYSTACK_RELOCATE goto yyexhaustedlab; #else { /* Get the current used size of the three stacks, in elements. */ YYPTRDIFF_T yysize = yyssp - yyss + 1; # if defined yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ yy_state_t *yyss1 = yyss; YYSTYPE *yyvs1 = yyvs; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * YYSIZEOF (*yyssp), &yyvs1, yysize * YYSIZEOF (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } # else /* defined YYSTACK_RELOCATE */ /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yy_state_t *yyss1 = yyss; union yyalloc *yyptr = YY_CAST (union yyalloc *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, YYSTACK_BYTES (yystacksize)))); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YY_IGNORE_USELESS_CAST_BEGIN YYDPRINTF ((stderr, "Stack size increased to %ld\n", YY_CAST (long, yystacksize))); YY_IGNORE_USELESS_CAST_END if (yyss + yystacksize - 1 <= yyssp) YYABORT; } #endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */ if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either empty, or end-of-input, or a valid lookahead. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token\n")); yychar = yylex (&yylval, parseContext); } if (yychar <= YYEOF) { yychar = YYEOF; yytoken = YYSYMBOL_YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else if (yychar == YYerror) { /* The scanner already issued an error message, process directly to error recovery. But do not keep the error token as lookahead, it is too special and may lead us to an endless loop in error recovery. */ yychar = YYUNDEF; yytoken = YYSYMBOL_YYerror; goto yyerrlab1; } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Discard the shifted token. */ yychar = YYEMPTY; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: /* variable_identifier: IDENTIFIER */ #line 371 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleVariable((yyvsp[0].lex).loc, (yyvsp[0].lex).symbol, (yyvsp[0].lex).string); } #line 4768 "MachineIndependent/glslang_tab.cpp" break; case 3: /* primary_expression: variable_identifier */ #line 377 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 4776 "MachineIndependent/glslang_tab.cpp" break; case 4: /* primary_expression: LEFT_PAREN expression RIGHT_PAREN */ #line 380 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[-1].interm.intermTypedNode); if ((yyval.interm.intermTypedNode)->getAsConstantUnion()) (yyval.interm.intermTypedNode)->getAsConstantUnion()->setExpression(); } #line 4786 "MachineIndependent/glslang_tab.cpp" break; case 5: /* primary_expression: FLOATCONSTANT */ #line 385 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).d, EbtFloat, (yyvsp[0].lex).loc, true); } #line 4794 "MachineIndependent/glslang_tab.cpp" break; case 6: /* primary_expression: INTCONSTANT */ #line 388 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).i, (yyvsp[0].lex).loc, true); } #line 4802 "MachineIndependent/glslang_tab.cpp" break; case 7: /* primary_expression: UINTCONSTANT */ #line 391 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "unsigned literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).u, (yyvsp[0].lex).loc, true); } #line 4811 "MachineIndependent/glslang_tab.cpp" break; case 8: /* primary_expression: BOOLCONSTANT */ #line 395 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).b, (yyvsp[0].lex).loc, true); } #line 4819 "MachineIndependent/glslang_tab.cpp" break; case 9: /* primary_expression: STRING_LITERAL */ #line 399 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).string, (yyvsp[0].lex).loc, true); } #line 4827 "MachineIndependent/glslang_tab.cpp" break; case 10: /* primary_expression: INT32CONSTANT */ #line 402 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit signed literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).i, (yyvsp[0].lex).loc, true); } #line 4836 "MachineIndependent/glslang_tab.cpp" break; case 11: /* primary_expression: UINT32CONSTANT */ #line 406 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit signed literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).u, (yyvsp[0].lex).loc, true); } #line 4845 "MachineIndependent/glslang_tab.cpp" break; case 12: /* primary_expression: INT64CONSTANT */ #line 410 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit integer literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).i64, (yyvsp[0].lex).loc, true); } #line 4854 "MachineIndependent/glslang_tab.cpp" break; case 13: /* primary_expression: UINT64CONSTANT */ #line 414 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit unsigned integer literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).u64, (yyvsp[0].lex).loc, true); } #line 4863 "MachineIndependent/glslang_tab.cpp" break; case 14: /* primary_expression: INT16CONSTANT */ #line 418 "MachineIndependent/glslang.y" { parseContext.explicitInt16Check((yyvsp[0].lex).loc, "16-bit integer literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((short)(yyvsp[0].lex).i, (yyvsp[0].lex).loc, true); } #line 4872 "MachineIndependent/glslang_tab.cpp" break; case 15: /* primary_expression: UINT16CONSTANT */ #line 422 "MachineIndependent/glslang.y" { parseContext.explicitInt16Check((yyvsp[0].lex).loc, "16-bit unsigned integer literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((unsigned short)(yyvsp[0].lex).u, (yyvsp[0].lex).loc, true); } #line 4881 "MachineIndependent/glslang_tab.cpp" break; case 16: /* primary_expression: DOUBLECONSTANT */ #line 426 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double literal"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).d, EbtDouble, (yyvsp[0].lex).loc, true); } #line 4892 "MachineIndependent/glslang_tab.cpp" break; case 17: /* primary_expression: FLOAT16CONSTANT */ #line 432 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float literal"); (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion((yyvsp[0].lex).d, EbtFloat16, (yyvsp[0].lex).loc, true); } #line 4901 "MachineIndependent/glslang_tab.cpp" break; case 18: /* postfix_expression: primary_expression */ #line 440 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 4909 "MachineIndependent/glslang_tab.cpp" break; case 19: /* postfix_expression: postfix_expression LEFT_BRACKET integer_expression RIGHT_BRACKET */ #line 443 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBracketDereference((yyvsp[-2].lex).loc, (yyvsp[-3].interm.intermTypedNode), (yyvsp[-1].interm.intermTypedNode)); } #line 4917 "MachineIndependent/glslang_tab.cpp" break; case 20: /* postfix_expression: function_call */ #line 446 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 4925 "MachineIndependent/glslang_tab.cpp" break; case 21: /* postfix_expression: postfix_expression DOT IDENTIFIER */ #line 449 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleDotDereference((yyvsp[0].lex).loc, (yyvsp[-2].interm.intermTypedNode), *(yyvsp[0].lex).string); } #line 4933 "MachineIndependent/glslang_tab.cpp" break; case 22: /* postfix_expression: postfix_expression INC_OP */ #line 452 "MachineIndependent/glslang.y" { parseContext.variableCheck((yyvsp[-1].interm.intermTypedNode)); parseContext.lValueErrorCheck((yyvsp[0].lex).loc, "++", (yyvsp[-1].interm.intermTypedNode)); (yyval.interm.intermTypedNode) = parseContext.handleUnaryMath((yyvsp[0].lex).loc, "++", EOpPostIncrement, (yyvsp[-1].interm.intermTypedNode)); } #line 4943 "MachineIndependent/glslang_tab.cpp" break; case 23: /* postfix_expression: postfix_expression DEC_OP */ #line 457 "MachineIndependent/glslang.y" { parseContext.variableCheck((yyvsp[-1].interm.intermTypedNode)); parseContext.lValueErrorCheck((yyvsp[0].lex).loc, "--", (yyvsp[-1].interm.intermTypedNode)); (yyval.interm.intermTypedNode) = parseContext.handleUnaryMath((yyvsp[0].lex).loc, "--", EOpPostDecrement, (yyvsp[-1].interm.intermTypedNode)); } #line 4953 "MachineIndependent/glslang_tab.cpp" break; case 24: /* integer_expression: expression */ #line 465 "MachineIndependent/glslang.y" { parseContext.integerCheck((yyvsp[0].interm.intermTypedNode), "[]"); (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 4962 "MachineIndependent/glslang_tab.cpp" break; case 25: /* function_call: function_call_or_method */ #line 472 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleFunctionCall((yyvsp[0].interm).loc, (yyvsp[0].interm).function, (yyvsp[0].interm).intermNode); delete (yyvsp[0].interm).function; } #line 4971 "MachineIndependent/glslang_tab.cpp" break; case 26: /* function_call_or_method: function_call_generic */ #line 479 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[0].interm); } #line 4979 "MachineIndependent/glslang_tab.cpp" break; case 27: /* function_call_generic: function_call_header_with_parameters RIGHT_PAREN */ #line 485 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[-1].interm); (yyval.interm).loc = (yyvsp[0].lex).loc; } #line 4988 "MachineIndependent/glslang_tab.cpp" break; case 28: /* function_call_generic: function_call_header_no_parameters RIGHT_PAREN */ #line 489 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[-1].interm); (yyval.interm).loc = (yyvsp[0].lex).loc; } #line 4997 "MachineIndependent/glslang_tab.cpp" break; case 29: /* function_call_header_no_parameters: function_call_header VOID */ #line 496 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[-1].interm); } #line 5005 "MachineIndependent/glslang_tab.cpp" break; case 30: /* function_call_header_no_parameters: function_call_header */ #line 499 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[0].interm); } #line 5013 "MachineIndependent/glslang_tab.cpp" break; case 31: /* function_call_header_with_parameters: function_call_header assignment_expression */ #line 505 "MachineIndependent/glslang.y" { TParameter param = { 0, new TType }; param.type->shallowCopy((yyvsp[0].interm.intermTypedNode)->getType()); (yyvsp[-1].interm).function->addParameter(param); (yyval.interm).function = (yyvsp[-1].interm).function; (yyval.interm).intermNode = (yyvsp[0].interm.intermTypedNode); } #line 5025 "MachineIndependent/glslang_tab.cpp" break; case 32: /* function_call_header_with_parameters: function_call_header_with_parameters COMMA assignment_expression */ #line 512 "MachineIndependent/glslang.y" { TParameter param = { 0, new TType }; param.type->shallowCopy((yyvsp[0].interm.intermTypedNode)->getType()); (yyvsp[-2].interm).function->addParameter(param); (yyval.interm).function = (yyvsp[-2].interm).function; (yyval.interm).intermNode = parseContext.intermediate.growAggregate((yyvsp[-2].interm).intermNode, (yyvsp[0].interm.intermTypedNode), (yyvsp[-1].lex).loc); } #line 5037 "MachineIndependent/glslang_tab.cpp" break; case 33: /* function_call_header: function_identifier LEFT_PAREN */ #line 522 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[-1].interm); } #line 5045 "MachineIndependent/glslang_tab.cpp" break; case 34: /* function_identifier: type_specifier */ #line 530 "MachineIndependent/glslang.y" { // Constructor (yyval.interm).intermNode = 0; (yyval.interm).function = parseContext.handleConstructorCall((yyvsp[0].interm.type).loc, (yyvsp[0].interm.type)); } #line 5055 "MachineIndependent/glslang_tab.cpp" break; case 35: /* function_identifier: postfix_expression */ #line 535 "MachineIndependent/glslang.y" { // // Should be a method or subroutine call, but we haven't recognized the arguments yet. // (yyval.interm).function = 0; (yyval.interm).intermNode = 0; TIntermMethod* method = (yyvsp[0].interm.intermTypedNode)->getAsMethodNode(); if (method) { (yyval.interm).function = new TFunction(&method->getMethodName(), TType(EbtInt), EOpArrayLength); (yyval.interm).intermNode = method->getObject(); } else { TIntermSymbol* symbol = (yyvsp[0].interm.intermTypedNode)->getAsSymbolNode(); if (symbol) { parseContext.reservedErrorCheck(symbol->getLoc(), symbol->getName()); TFunction *function = new TFunction(&symbol->getName(), TType(EbtVoid)); (yyval.interm).function = function; } else parseContext.error((yyvsp[0].interm.intermTypedNode)->getLoc(), "function call, method, or subroutine call expected", "", ""); } if ((yyval.interm).function == 0) { // error recover TString* empty = NewPoolTString(""); (yyval.interm).function = new TFunction(empty, TType(EbtVoid), EOpNull); } } #line 5087 "MachineIndependent/glslang_tab.cpp" break; case 36: /* function_identifier: non_uniform_qualifier */ #line 563 "MachineIndependent/glslang.y" { // Constructor (yyval.interm).intermNode = 0; (yyval.interm).function = parseContext.handleConstructorCall((yyvsp[0].interm.type).loc, (yyvsp[0].interm.type)); } #line 5097 "MachineIndependent/glslang_tab.cpp" break; case 37: /* unary_expression: postfix_expression */ #line 572 "MachineIndependent/glslang.y" { parseContext.variableCheck((yyvsp[0].interm.intermTypedNode)); (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); if (TIntermMethod* method = (yyvsp[0].interm.intermTypedNode)->getAsMethodNode()) parseContext.error((yyvsp[0].interm.intermTypedNode)->getLoc(), "incomplete method syntax", method->getMethodName().c_str(), ""); } #line 5108 "MachineIndependent/glslang_tab.cpp" break; case 38: /* unary_expression: INC_OP unary_expression */ #line 578 "MachineIndependent/glslang.y" { parseContext.lValueErrorCheck((yyvsp[-1].lex).loc, "++", (yyvsp[0].interm.intermTypedNode)); (yyval.interm.intermTypedNode) = parseContext.handleUnaryMath((yyvsp[-1].lex).loc, "++", EOpPreIncrement, (yyvsp[0].interm.intermTypedNode)); } #line 5117 "MachineIndependent/glslang_tab.cpp" break; case 39: /* unary_expression: DEC_OP unary_expression */ #line 582 "MachineIndependent/glslang.y" { parseContext.lValueErrorCheck((yyvsp[-1].lex).loc, "--", (yyvsp[0].interm.intermTypedNode)); (yyval.interm.intermTypedNode) = parseContext.handleUnaryMath((yyvsp[-1].lex).loc, "--", EOpPreDecrement, (yyvsp[0].interm.intermTypedNode)); } #line 5126 "MachineIndependent/glslang_tab.cpp" break; case 40: /* unary_expression: unary_operator unary_expression */ #line 586 "MachineIndependent/glslang.y" { if ((yyvsp[-1].interm).op != EOpNull) { char errorOp[2] = {0, 0}; switch((yyvsp[-1].interm).op) { case EOpNegative: errorOp[0] = '-'; break; case EOpLogicalNot: errorOp[0] = '!'; break; case EOpBitwiseNot: errorOp[0] = '~'; break; default: break; // some compilers want this } (yyval.interm.intermTypedNode) = parseContext.handleUnaryMath((yyvsp[-1].interm).loc, errorOp, (yyvsp[-1].interm).op, (yyvsp[0].interm.intermTypedNode)); } else { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); if ((yyval.interm.intermTypedNode)->getAsConstantUnion()) (yyval.interm.intermTypedNode)->getAsConstantUnion()->setExpression(); } } #line 5147 "MachineIndependent/glslang_tab.cpp" break; case 41: /* unary_operator: PLUS */ #line 606 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpNull; } #line 5153 "MachineIndependent/glslang_tab.cpp" break; case 42: /* unary_operator: DASH */ #line 607 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpNegative; } #line 5159 "MachineIndependent/glslang_tab.cpp" break; case 43: /* unary_operator: BANG */ #line 608 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpLogicalNot; } #line 5165 "MachineIndependent/glslang_tab.cpp" break; case 44: /* unary_operator: TILDE */ #line 609 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpBitwiseNot; parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "bitwise not"); } #line 5172 "MachineIndependent/glslang_tab.cpp" break; case 45: /* multiplicative_expression: unary_expression */ #line 615 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5178 "MachineIndependent/glslang_tab.cpp" break; case 46: /* multiplicative_expression: multiplicative_expression STAR unary_expression */ #line 616 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "*", EOpMul, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5188 "MachineIndependent/glslang_tab.cpp" break; case 47: /* multiplicative_expression: multiplicative_expression SLASH unary_expression */ #line 621 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "/", EOpDiv, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5198 "MachineIndependent/glslang_tab.cpp" break; case 48: /* multiplicative_expression: multiplicative_expression PERCENT unary_expression */ #line 626 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[-1].lex).loc, "%"); (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "%", EOpMod, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5209 "MachineIndependent/glslang_tab.cpp" break; case 49: /* additive_expression: multiplicative_expression */ #line 635 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5215 "MachineIndependent/glslang_tab.cpp" break; case 50: /* additive_expression: additive_expression PLUS multiplicative_expression */ #line 636 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "+", EOpAdd, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5225 "MachineIndependent/glslang_tab.cpp" break; case 51: /* additive_expression: additive_expression DASH multiplicative_expression */ #line 641 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "-", EOpSub, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5235 "MachineIndependent/glslang_tab.cpp" break; case 52: /* shift_expression: additive_expression */ #line 649 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5241 "MachineIndependent/glslang_tab.cpp" break; case 53: /* shift_expression: shift_expression LEFT_OP additive_expression */ #line 650 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[-1].lex).loc, "bit shift left"); (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "<<", EOpLeftShift, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5252 "MachineIndependent/glslang_tab.cpp" break; case 54: /* shift_expression: shift_expression RIGHT_OP additive_expression */ #line 656 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[-1].lex).loc, "bit shift right"); (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, ">>", EOpRightShift, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5263 "MachineIndependent/glslang_tab.cpp" break; case 55: /* relational_expression: shift_expression */ #line 665 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5269 "MachineIndependent/glslang_tab.cpp" break; case 56: /* relational_expression: relational_expression LEFT_ANGLE shift_expression */ #line 666 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "<", EOpLessThan, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5279 "MachineIndependent/glslang_tab.cpp" break; case 57: /* relational_expression: relational_expression RIGHT_ANGLE shift_expression */ #line 671 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, ">", EOpGreaterThan, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5289 "MachineIndependent/glslang_tab.cpp" break; case 58: /* relational_expression: relational_expression LE_OP shift_expression */ #line 676 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "<=", EOpLessThanEqual, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5299 "MachineIndependent/glslang_tab.cpp" break; case 59: /* relational_expression: relational_expression GE_OP shift_expression */ #line 681 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, ">=", EOpGreaterThanEqual, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5309 "MachineIndependent/glslang_tab.cpp" break; case 60: /* equality_expression: relational_expression */ #line 689 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5315 "MachineIndependent/glslang_tab.cpp" break; case 61: /* equality_expression: equality_expression EQ_OP relational_expression */ #line 690 "MachineIndependent/glslang.y" { parseContext.arrayObjectCheck((yyvsp[-1].lex).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "array comparison"); parseContext.opaqueCheck((yyvsp[-1].lex).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "=="); parseContext.specializationCheck((yyvsp[-1].lex).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "=="); parseContext.referenceCheck((yyvsp[-1].lex).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "=="); (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "==", EOpEqual, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5329 "MachineIndependent/glslang_tab.cpp" break; case 62: /* equality_expression: equality_expression NE_OP relational_expression */ #line 699 "MachineIndependent/glslang.y" { parseContext.arrayObjectCheck((yyvsp[-1].lex).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "array comparison"); parseContext.opaqueCheck((yyvsp[-1].lex).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "!="); parseContext.specializationCheck((yyvsp[-1].lex).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "!="); parseContext.referenceCheck((yyvsp[-1].lex).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "!="); (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "!=", EOpNotEqual, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5343 "MachineIndependent/glslang_tab.cpp" break; case 63: /* and_expression: equality_expression */ #line 711 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5349 "MachineIndependent/glslang_tab.cpp" break; case 64: /* and_expression: and_expression AMPERSAND equality_expression */ #line 712 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[-1].lex).loc, "bitwise and"); (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "&", EOpAnd, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5360 "MachineIndependent/glslang_tab.cpp" break; case 65: /* exclusive_or_expression: and_expression */ #line 721 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5366 "MachineIndependent/glslang_tab.cpp" break; case 66: /* exclusive_or_expression: exclusive_or_expression CARET and_expression */ #line 722 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[-1].lex).loc, "bitwise exclusive or"); (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "^", EOpExclusiveOr, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5377 "MachineIndependent/glslang_tab.cpp" break; case 67: /* inclusive_or_expression: exclusive_or_expression */ #line 731 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5383 "MachineIndependent/glslang_tab.cpp" break; case 68: /* inclusive_or_expression: inclusive_or_expression VERTICAL_BAR exclusive_or_expression */ #line 732 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[-1].lex).loc, "bitwise inclusive or"); (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "|", EOpInclusiveOr, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 5394 "MachineIndependent/glslang_tab.cpp" break; case 69: /* logical_and_expression: inclusive_or_expression */ #line 741 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5400 "MachineIndependent/glslang_tab.cpp" break; case 70: /* logical_and_expression: logical_and_expression AND_OP inclusive_or_expression */ #line 742 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "&&", EOpLogicalAnd, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5410 "MachineIndependent/glslang_tab.cpp" break; case 71: /* logical_xor_expression: logical_and_expression */ #line 750 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5416 "MachineIndependent/glslang_tab.cpp" break; case 72: /* logical_xor_expression: logical_xor_expression XOR_OP logical_and_expression */ #line 751 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "^^", EOpLogicalXor, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5426 "MachineIndependent/glslang_tab.cpp" break; case 73: /* logical_or_expression: logical_xor_expression */ #line 759 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5432 "MachineIndependent/glslang_tab.cpp" break; case 74: /* logical_or_expression: logical_or_expression OR_OP logical_xor_expression */ #line 760 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.handleBinaryMath((yyvsp[-1].lex).loc, "||", EOpLogicalOr, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) (yyval.interm.intermTypedNode) = parseContext.intermediate.addConstantUnion(false, (yyvsp[-1].lex).loc); } #line 5442 "MachineIndependent/glslang_tab.cpp" break; case 75: /* conditional_expression: logical_or_expression */ #line 768 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5448 "MachineIndependent/glslang_tab.cpp" break; case 76: /* $@1: %empty */ #line 769 "MachineIndependent/glslang.y" { ++parseContext.controlFlowNestingLevel; } #line 5456 "MachineIndependent/glslang_tab.cpp" break; case 77: /* conditional_expression: logical_or_expression QUESTION $@1 expression COLON assignment_expression */ #line 772 "MachineIndependent/glslang.y" { --parseContext.controlFlowNestingLevel; parseContext.boolCheck((yyvsp[-4].lex).loc, (yyvsp[-5].interm.intermTypedNode)); parseContext.rValueErrorCheck((yyvsp[-4].lex).loc, "?", (yyvsp[-5].interm.intermTypedNode)); parseContext.rValueErrorCheck((yyvsp[-1].lex).loc, ":", (yyvsp[-2].interm.intermTypedNode)); parseContext.rValueErrorCheck((yyvsp[-1].lex).loc, ":", (yyvsp[0].interm.intermTypedNode)); (yyval.interm.intermTypedNode) = parseContext.intermediate.addSelection((yyvsp[-5].interm.intermTypedNode), (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode), (yyvsp[-4].lex).loc); if ((yyval.interm.intermTypedNode) == 0) { parseContext.binaryOpError((yyvsp[-4].lex).loc, ":", (yyvsp[-2].interm.intermTypedNode)->getCompleteString(), (yyvsp[0].interm.intermTypedNode)->getCompleteString()); (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } } #line 5473 "MachineIndependent/glslang_tab.cpp" break; case 78: /* assignment_expression: conditional_expression */ #line 787 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5479 "MachineIndependent/glslang_tab.cpp" break; case 79: /* assignment_expression: unary_expression assignment_operator assignment_expression */ #line 788 "MachineIndependent/glslang.y" { parseContext.arrayObjectCheck((yyvsp[-1].interm).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "array assignment"); parseContext.opaqueCheck((yyvsp[-1].interm).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "="); parseContext.storage16BitAssignmentCheck((yyvsp[-1].interm).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "="); parseContext.specializationCheck((yyvsp[-1].interm).loc, (yyvsp[-2].interm.intermTypedNode)->getType(), "="); parseContext.lValueErrorCheck((yyvsp[-1].interm).loc, "assign", (yyvsp[-2].interm.intermTypedNode)); parseContext.rValueErrorCheck((yyvsp[-1].interm).loc, "assign", (yyvsp[0].interm.intermTypedNode)); (yyval.interm.intermTypedNode) = parseContext.addAssign((yyvsp[-1].interm).loc, (yyvsp[-1].interm).op, (yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); if ((yyval.interm.intermTypedNode) == 0) { parseContext.assignError((yyvsp[-1].interm).loc, "assign", (yyvsp[-2].interm.intermTypedNode)->getCompleteString(), (yyvsp[0].interm.intermTypedNode)->getCompleteString()); (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } } #line 5497 "MachineIndependent/glslang_tab.cpp" break; case 80: /* assignment_operator: EQUAL */ #line 804 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpAssign; } #line 5506 "MachineIndependent/glslang_tab.cpp" break; case 81: /* assignment_operator: MUL_ASSIGN */ #line 808 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpMulAssign; } #line 5515 "MachineIndependent/glslang_tab.cpp" break; case 82: /* assignment_operator: DIV_ASSIGN */ #line 812 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpDivAssign; } #line 5524 "MachineIndependent/glslang_tab.cpp" break; case 83: /* assignment_operator: MOD_ASSIGN */ #line 816 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "%="); (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpModAssign; } #line 5534 "MachineIndependent/glslang_tab.cpp" break; case 84: /* assignment_operator: ADD_ASSIGN */ #line 821 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpAddAssign; } #line 5543 "MachineIndependent/glslang_tab.cpp" break; case 85: /* assignment_operator: SUB_ASSIGN */ #line 825 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpSubAssign; } #line 5552 "MachineIndependent/glslang_tab.cpp" break; case 86: /* assignment_operator: LEFT_ASSIGN */ #line 829 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "bit-shift left assign"); (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpLeftShiftAssign; } #line 5561 "MachineIndependent/glslang_tab.cpp" break; case 87: /* assignment_operator: RIGHT_ASSIGN */ #line 833 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "bit-shift right assign"); (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpRightShiftAssign; } #line 5570 "MachineIndependent/glslang_tab.cpp" break; case 88: /* assignment_operator: AND_ASSIGN */ #line 837 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "bitwise-and assign"); (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpAndAssign; } #line 5579 "MachineIndependent/glslang_tab.cpp" break; case 89: /* assignment_operator: XOR_ASSIGN */ #line 841 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "bitwise-xor assign"); (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpExclusiveOrAssign; } #line 5588 "MachineIndependent/glslang_tab.cpp" break; case 90: /* assignment_operator: OR_ASSIGN */ #line 845 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "bitwise-or assign"); (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).op = EOpInclusiveOrAssign; } #line 5597 "MachineIndependent/glslang_tab.cpp" break; case 91: /* expression: assignment_expression */ #line 852 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5605 "MachineIndependent/glslang_tab.cpp" break; case 92: /* expression: expression COMMA assignment_expression */ #line 855 "MachineIndependent/glslang.y" { parseContext.samplerConstructorLocationCheck((yyvsp[-1].lex).loc, ",", (yyvsp[0].interm.intermTypedNode)); (yyval.interm.intermTypedNode) = parseContext.intermediate.addComma((yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode), (yyvsp[-1].lex).loc); if ((yyval.interm.intermTypedNode) == 0) { parseContext.binaryOpError((yyvsp[-1].lex).loc, ",", (yyvsp[-2].interm.intermTypedNode)->getCompleteString(), (yyvsp[0].interm.intermTypedNode)->getCompleteString()); (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } } #line 5618 "MachineIndependent/glslang_tab.cpp" break; case 93: /* constant_expression: conditional_expression */ #line 866 "MachineIndependent/glslang.y" { parseContext.constantValueCheck((yyvsp[0].interm.intermTypedNode), ""); (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 5627 "MachineIndependent/glslang_tab.cpp" break; case 94: /* declaration: function_prototype SEMICOLON */ #line 873 "MachineIndependent/glslang.y" { parseContext.handleFunctionDeclarator((yyvsp[-1].interm).loc, *(yyvsp[-1].interm).function, true /* prototype */); (yyval.interm.intermNode) = 0; // TODO: 4.0 functionality: subroutines: make the identifier a user type for this signature } #line 5637 "MachineIndependent/glslang_tab.cpp" break; case 95: /* declaration: init_declarator_list SEMICOLON */ #line 878 "MachineIndependent/glslang.y" { if ((yyvsp[-1].interm).intermNode && (yyvsp[-1].interm).intermNode->getAsAggregate()) (yyvsp[-1].interm).intermNode->getAsAggregate()->setOperator(EOpSequence); (yyval.interm.intermNode) = (yyvsp[-1].interm).intermNode; } #line 5647 "MachineIndependent/glslang_tab.cpp" break; case 96: /* declaration: PRECISION precision_qualifier type_specifier SEMICOLON */ #line 883 "MachineIndependent/glslang.y" { parseContext.profileRequires((yyvsp[-3].lex).loc, ENoProfile, 130, 0, "precision statement"); // lazy setting of the previous scope's defaults, has effect only the first time it is called in a particular scope parseContext.symbolTable.setPreviousDefaultPrecisions(&parseContext.defaultPrecision[0]); parseContext.setDefaultPrecision((yyvsp[-3].lex).loc, (yyvsp[-1].interm.type), (yyvsp[-2].interm.type).qualifier.precision); (yyval.interm.intermNode) = 0; } #line 5659 "MachineIndependent/glslang_tab.cpp" break; case 97: /* declaration: block_structure SEMICOLON */ #line 890 "MachineIndependent/glslang.y" { parseContext.declareBlock((yyvsp[-1].interm).loc, *(yyvsp[-1].interm).typeList); (yyval.interm.intermNode) = 0; } #line 5668 "MachineIndependent/glslang_tab.cpp" break; case 98: /* declaration: block_structure IDENTIFIER SEMICOLON */ #line 894 "MachineIndependent/glslang.y" { parseContext.declareBlock((yyvsp[-2].interm).loc, *(yyvsp[-2].interm).typeList, (yyvsp[-1].lex).string); (yyval.interm.intermNode) = 0; } #line 5677 "MachineIndependent/glslang_tab.cpp" break; case 99: /* declaration: block_structure IDENTIFIER array_specifier SEMICOLON */ #line 898 "MachineIndependent/glslang.y" { parseContext.declareBlock((yyvsp[-3].interm).loc, *(yyvsp[-3].interm).typeList, (yyvsp[-2].lex).string, (yyvsp[-1].interm).arraySizes); (yyval.interm.intermNode) = 0; } #line 5686 "MachineIndependent/glslang_tab.cpp" break; case 100: /* declaration: type_qualifier SEMICOLON */ #line 902 "MachineIndependent/glslang.y" { parseContext.globalQualifierFixCheck((yyvsp[-1].interm.type).loc, (yyvsp[-1].interm.type).qualifier); parseContext.updateStandaloneQualifierDefaults((yyvsp[-1].interm.type).loc, (yyvsp[-1].interm.type)); (yyval.interm.intermNode) = 0; } #line 5696 "MachineIndependent/glslang_tab.cpp" break; case 101: /* declaration: type_qualifier IDENTIFIER SEMICOLON */ #line 907 "MachineIndependent/glslang.y" { parseContext.checkNoShaderLayouts((yyvsp[-2].interm.type).loc, (yyvsp[-2].interm.type).shaderQualifiers); parseContext.addQualifierToExisting((yyvsp[-2].interm.type).loc, (yyvsp[-2].interm.type).qualifier, *(yyvsp[-1].lex).string); (yyval.interm.intermNode) = 0; } #line 5706 "MachineIndependent/glslang_tab.cpp" break; case 102: /* declaration: type_qualifier IDENTIFIER identifier_list SEMICOLON */ #line 912 "MachineIndependent/glslang.y" { parseContext.checkNoShaderLayouts((yyvsp[-3].interm.type).loc, (yyvsp[-3].interm.type).shaderQualifiers); (yyvsp[-1].interm.identifierList)->push_back((yyvsp[-2].lex).string); parseContext.addQualifierToExisting((yyvsp[-3].interm.type).loc, (yyvsp[-3].interm.type).qualifier, *(yyvsp[-1].interm.identifierList)); (yyval.interm.intermNode) = 0; } #line 5717 "MachineIndependent/glslang_tab.cpp" break; case 103: /* $@2: %empty */ #line 921 "MachineIndependent/glslang.y" { parseContext.nestedBlockCheck((yyvsp[-2].interm.type).loc); } #line 5723 "MachineIndependent/glslang_tab.cpp" break; case 104: /* block_structure: type_qualifier IDENTIFIER LEFT_BRACE $@2 struct_declaration_list RIGHT_BRACE */ #line 921 "MachineIndependent/glslang.y" { --parseContext.blockNestingLevel; parseContext.blockName = (yyvsp[-4].lex).string; parseContext.globalQualifierFixCheck((yyvsp[-5].interm.type).loc, (yyvsp[-5].interm.type).qualifier); parseContext.checkNoShaderLayouts((yyvsp[-5].interm.type).loc, (yyvsp[-5].interm.type).shaderQualifiers); parseContext.currentBlockQualifier = (yyvsp[-5].interm.type).qualifier; (yyval.interm).loc = (yyvsp[-5].interm.type).loc; (yyval.interm).typeList = (yyvsp[-1].interm.typeList); } #line 5737 "MachineIndependent/glslang_tab.cpp" break; case 105: /* identifier_list: COMMA IDENTIFIER */ #line 932 "MachineIndependent/glslang.y" { (yyval.interm.identifierList) = new TIdentifierList; (yyval.interm.identifierList)->push_back((yyvsp[0].lex).string); } #line 5746 "MachineIndependent/glslang_tab.cpp" break; case 106: /* identifier_list: identifier_list COMMA IDENTIFIER */ #line 936 "MachineIndependent/glslang.y" { (yyval.interm.identifierList) = (yyvsp[-2].interm.identifierList); (yyval.interm.identifierList)->push_back((yyvsp[0].lex).string); } #line 5755 "MachineIndependent/glslang_tab.cpp" break; case 107: /* function_prototype: function_declarator RIGHT_PAREN */ #line 943 "MachineIndependent/glslang.y" { (yyval.interm).function = (yyvsp[-1].interm.function); (yyval.interm).loc = (yyvsp[0].lex).loc; } #line 5764 "MachineIndependent/glslang_tab.cpp" break; case 108: /* function_prototype: function_declarator RIGHT_PAREN attribute */ #line 947 "MachineIndependent/glslang.y" { (yyval.interm).function = (yyvsp[-2].interm.function); (yyval.interm).loc = (yyvsp[-1].lex).loc; parseContext.requireExtensions((yyvsp[-1].lex).loc, 1, &E_GL_EXT_subgroup_uniform_control_flow, "attribute"); parseContext.handleFunctionAttributes((yyvsp[-1].lex).loc, *(yyvsp[0].interm.attributes), (yyval.interm).function); } #line 5775 "MachineIndependent/glslang_tab.cpp" break; case 109: /* function_prototype: attribute function_declarator RIGHT_PAREN */ #line 953 "MachineIndependent/glslang.y" { (yyval.interm).function = (yyvsp[-1].interm.function); (yyval.interm).loc = (yyvsp[0].lex).loc; parseContext.requireExtensions((yyvsp[0].lex).loc, 1, &E_GL_EXT_subgroup_uniform_control_flow, "attribute"); parseContext.handleFunctionAttributes((yyvsp[0].lex).loc, *(yyvsp[-2].interm.attributes), (yyval.interm).function); } #line 5786 "MachineIndependent/glslang_tab.cpp" break; case 110: /* function_prototype: attribute function_declarator RIGHT_PAREN attribute */ #line 959 "MachineIndependent/glslang.y" { (yyval.interm).function = (yyvsp[-2].interm.function); (yyval.interm).loc = (yyvsp[-1].lex).loc; parseContext.requireExtensions((yyvsp[-1].lex).loc, 1, &E_GL_EXT_subgroup_uniform_control_flow, "attribute"); parseContext.handleFunctionAttributes((yyvsp[-1].lex).loc, *(yyvsp[-3].interm.attributes), (yyval.interm).function); parseContext.handleFunctionAttributes((yyvsp[-1].lex).loc, *(yyvsp[0].interm.attributes), (yyval.interm).function); } #line 5798 "MachineIndependent/glslang_tab.cpp" break; case 111: /* function_declarator: function_header */ #line 969 "MachineIndependent/glslang.y" { (yyval.interm.function) = (yyvsp[0].interm.function); } #line 5806 "MachineIndependent/glslang_tab.cpp" break; case 112: /* function_declarator: function_header_with_parameters */ #line 972 "MachineIndependent/glslang.y" { (yyval.interm.function) = (yyvsp[0].interm.function); } #line 5814 "MachineIndependent/glslang_tab.cpp" break; case 113: /* function_header_with_parameters: function_header parameter_declaration */ #line 979 "MachineIndependent/glslang.y" { // Add the parameter (yyval.interm.function) = (yyvsp[-1].interm.function); if ((yyvsp[0].interm).param.type->getBasicType() != EbtVoid) (yyvsp[-1].interm.function)->addParameter((yyvsp[0].interm).param); else delete (yyvsp[0].interm).param.type; } #line 5827 "MachineIndependent/glslang_tab.cpp" break; case 114: /* function_header_with_parameters: function_header_with_parameters COMMA parameter_declaration */ #line 987 "MachineIndependent/glslang.y" { // // Only first parameter of one-parameter functions can be void // The check for named parameters not being void is done in parameter_declarator // if ((yyvsp[0].interm).param.type->getBasicType() == EbtVoid) { // // This parameter > first is void // parseContext.error((yyvsp[-1].lex).loc, "cannot be an argument type except for '(void)'", "void", ""); delete (yyvsp[0].interm).param.type; } else { // Add the parameter (yyval.interm.function) = (yyvsp[-2].interm.function); (yyvsp[-2].interm.function)->addParameter((yyvsp[0].interm).param); } } #line 5849 "MachineIndependent/glslang_tab.cpp" break; case 115: /* function_header: fully_specified_type IDENTIFIER LEFT_PAREN */ #line 1007 "MachineIndependent/glslang.y" { if ((yyvsp[-2].interm.type).qualifier.storage != EvqGlobal && (yyvsp[-2].interm.type).qualifier.storage != EvqTemporary) { parseContext.error((yyvsp[-1].lex).loc, "no qualifiers allowed for function return", GetStorageQualifierString((yyvsp[-2].interm.type).qualifier.storage), ""); } if ((yyvsp[-2].interm.type).arraySizes) parseContext.arraySizeRequiredCheck((yyvsp[-2].interm.type).loc, *(yyvsp[-2].interm.type).arraySizes); // Add the function as a prototype after parsing it (we do not support recursion) TFunction *function; TType type((yyvsp[-2].interm.type)); // Potentially rename shader entry point function. No-op most of the time. parseContext.renameShaderFunction((yyvsp[-1].lex).string); // Make the function function = new TFunction((yyvsp[-1].lex).string, type); (yyval.interm.function) = function; } #line 5873 "MachineIndependent/glslang_tab.cpp" break; case 116: /* parameter_declarator: type_specifier IDENTIFIER */ #line 1030 "MachineIndependent/glslang.y" { if ((yyvsp[-1].interm.type).arraySizes) { parseContext.profileRequires((yyvsp[-1].interm.type).loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed type"); parseContext.profileRequires((yyvsp[-1].interm.type).loc, EEsProfile, 300, 0, "arrayed type"); parseContext.arraySizeRequiredCheck((yyvsp[-1].interm.type).loc, *(yyvsp[-1].interm.type).arraySizes); } if ((yyvsp[-1].interm.type).basicType == EbtVoid) { parseContext.error((yyvsp[0].lex).loc, "illegal use of type 'void'", (yyvsp[0].lex).string->c_str(), ""); } parseContext.reservedErrorCheck((yyvsp[0].lex).loc, *(yyvsp[0].lex).string); TParameter param = {(yyvsp[0].lex).string, new TType((yyvsp[-1].interm.type))}; (yyval.interm).loc = (yyvsp[0].lex).loc; (yyval.interm).param = param; } #line 5893 "MachineIndependent/glslang_tab.cpp" break; case 117: /* parameter_declarator: type_specifier IDENTIFIER array_specifier */ #line 1045 "MachineIndependent/glslang.y" { if ((yyvsp[-2].interm.type).arraySizes) { parseContext.profileRequires((yyvsp[-2].interm.type).loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed type"); parseContext.profileRequires((yyvsp[-2].interm.type).loc, EEsProfile, 300, 0, "arrayed type"); parseContext.arraySizeRequiredCheck((yyvsp[-2].interm.type).loc, *(yyvsp[-2].interm.type).arraySizes); } TType* type = new TType((yyvsp[-2].interm.type)); type->transferArraySizes((yyvsp[0].interm).arraySizes); type->copyArrayInnerSizes((yyvsp[-2].interm.type).arraySizes); parseContext.arrayOfArrayVersionCheck((yyvsp[-1].lex).loc, type->getArraySizes()); parseContext.arraySizeRequiredCheck((yyvsp[0].interm).loc, *(yyvsp[0].interm).arraySizes); parseContext.reservedErrorCheck((yyvsp[-1].lex).loc, *(yyvsp[-1].lex).string); TParameter param = { (yyvsp[-1].lex).string, type }; (yyval.interm).loc = (yyvsp[-1].lex).loc; (yyval.interm).param = param; } #line 5917 "MachineIndependent/glslang_tab.cpp" break; case 118: /* parameter_declaration: type_qualifier parameter_declarator */ #line 1070 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[0].interm); if ((yyvsp[-1].interm.type).qualifier.precision != EpqNone) (yyval.interm).param.type->getQualifier().precision = (yyvsp[-1].interm.type).qualifier.precision; parseContext.precisionQualifierCheck((yyval.interm).loc, (yyval.interm).param.type->getBasicType(), (yyval.interm).param.type->getQualifier()); parseContext.checkNoShaderLayouts((yyvsp[-1].interm.type).loc, (yyvsp[-1].interm.type).shaderQualifiers); parseContext.parameterTypeCheck((yyvsp[0].interm).loc, (yyvsp[-1].interm.type).qualifier.storage, *(yyval.interm).param.type); parseContext.paramCheckFix((yyvsp[-1].interm.type).loc, (yyvsp[-1].interm.type).qualifier, *(yyval.interm).param.type); } #line 5933 "MachineIndependent/glslang_tab.cpp" break; case 119: /* parameter_declaration: parameter_declarator */ #line 1081 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[0].interm); parseContext.parameterTypeCheck((yyvsp[0].interm).loc, EvqIn, *(yyvsp[0].interm).param.type); parseContext.paramCheckFixStorage((yyvsp[0].interm).loc, EvqTemporary, *(yyval.interm).param.type); parseContext.precisionQualifierCheck((yyval.interm).loc, (yyval.interm).param.type->getBasicType(), (yyval.interm).param.type->getQualifier()); } #line 5945 "MachineIndependent/glslang_tab.cpp" break; case 120: /* parameter_declaration: type_qualifier parameter_type_specifier */ #line 1091 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[0].interm); if ((yyvsp[-1].interm.type).qualifier.precision != EpqNone) (yyval.interm).param.type->getQualifier().precision = (yyvsp[-1].interm.type).qualifier.precision; parseContext.precisionQualifierCheck((yyvsp[-1].interm.type).loc, (yyval.interm).param.type->getBasicType(), (yyval.interm).param.type->getQualifier()); parseContext.checkNoShaderLayouts((yyvsp[-1].interm.type).loc, (yyvsp[-1].interm.type).shaderQualifiers); parseContext.parameterTypeCheck((yyvsp[0].interm).loc, (yyvsp[-1].interm.type).qualifier.storage, *(yyval.interm).param.type); parseContext.paramCheckFix((yyvsp[-1].interm.type).loc, (yyvsp[-1].interm.type).qualifier, *(yyval.interm).param.type); } #line 5960 "MachineIndependent/glslang_tab.cpp" break; case 121: /* parameter_declaration: parameter_type_specifier */ #line 1101 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[0].interm); parseContext.parameterTypeCheck((yyvsp[0].interm).loc, EvqIn, *(yyvsp[0].interm).param.type); parseContext.paramCheckFixStorage((yyvsp[0].interm).loc, EvqTemporary, *(yyval.interm).param.type); parseContext.precisionQualifierCheck((yyval.interm).loc, (yyval.interm).param.type->getBasicType(), (yyval.interm).param.type->getQualifier()); } #line 5972 "MachineIndependent/glslang_tab.cpp" break; case 122: /* parameter_type_specifier: type_specifier */ #line 1111 "MachineIndependent/glslang.y" { TParameter param = { 0, new TType((yyvsp[0].interm.type)) }; (yyval.interm).param = param; if ((yyvsp[0].interm.type).arraySizes) parseContext.arraySizeRequiredCheck((yyvsp[0].interm.type).loc, *(yyvsp[0].interm.type).arraySizes); } #line 5983 "MachineIndependent/glslang_tab.cpp" break; case 123: /* init_declarator_list: single_declaration */ #line 1120 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[0].interm); } #line 5991 "MachineIndependent/glslang_tab.cpp" break; case 124: /* init_declarator_list: init_declarator_list COMMA IDENTIFIER */ #line 1123 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[-2].interm); parseContext.declareVariable((yyvsp[0].lex).loc, *(yyvsp[0].lex).string, (yyvsp[-2].interm).type); } #line 6000 "MachineIndependent/glslang_tab.cpp" break; case 125: /* init_declarator_list: init_declarator_list COMMA IDENTIFIER array_specifier */ #line 1127 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[-3].interm); parseContext.declareVariable((yyvsp[-1].lex).loc, *(yyvsp[-1].lex).string, (yyvsp[-3].interm).type, (yyvsp[0].interm).arraySizes); } #line 6009 "MachineIndependent/glslang_tab.cpp" break; case 126: /* init_declarator_list: init_declarator_list COMMA IDENTIFIER array_specifier EQUAL initializer */ #line 1131 "MachineIndependent/glslang.y" { (yyval.interm).type = (yyvsp[-5].interm).type; TIntermNode* initNode = parseContext.declareVariable((yyvsp[-3].lex).loc, *(yyvsp[-3].lex).string, (yyvsp[-5].interm).type, (yyvsp[-2].interm).arraySizes, (yyvsp[0].interm.intermTypedNode)); (yyval.interm).intermNode = parseContext.intermediate.growAggregate((yyvsp[-5].interm).intermNode, initNode, (yyvsp[-1].lex).loc); } #line 6019 "MachineIndependent/glslang_tab.cpp" break; case 127: /* init_declarator_list: init_declarator_list COMMA IDENTIFIER EQUAL initializer */ #line 1136 "MachineIndependent/glslang.y" { (yyval.interm).type = (yyvsp[-4].interm).type; TIntermNode* initNode = parseContext.declareVariable((yyvsp[-2].lex).loc, *(yyvsp[-2].lex).string, (yyvsp[-4].interm).type, 0, (yyvsp[0].interm.intermTypedNode)); (yyval.interm).intermNode = parseContext.intermediate.growAggregate((yyvsp[-4].interm).intermNode, initNode, (yyvsp[-1].lex).loc); } #line 6029 "MachineIndependent/glslang_tab.cpp" break; case 128: /* single_declaration: fully_specified_type */ #line 1144 "MachineIndependent/glslang.y" { (yyval.interm).type = (yyvsp[0].interm.type); (yyval.interm).intermNode = 0; parseContext.declareTypeDefaults((yyval.interm).loc, (yyval.interm).type); } #line 6041 "MachineIndependent/glslang_tab.cpp" break; case 129: /* single_declaration: fully_specified_type IDENTIFIER */ #line 1151 "MachineIndependent/glslang.y" { (yyval.interm).type = (yyvsp[-1].interm.type); (yyval.interm).intermNode = 0; parseContext.declareVariable((yyvsp[0].lex).loc, *(yyvsp[0].lex).string, (yyvsp[-1].interm.type)); } #line 6051 "MachineIndependent/glslang_tab.cpp" break; case 130: /* single_declaration: fully_specified_type IDENTIFIER array_specifier */ #line 1156 "MachineIndependent/glslang.y" { (yyval.interm).type = (yyvsp[-2].interm.type); (yyval.interm).intermNode = 0; parseContext.declareVariable((yyvsp[-1].lex).loc, *(yyvsp[-1].lex).string, (yyvsp[-2].interm.type), (yyvsp[0].interm).arraySizes); } #line 6061 "MachineIndependent/glslang_tab.cpp" break; case 131: /* single_declaration: fully_specified_type IDENTIFIER array_specifier EQUAL initializer */ #line 1161 "MachineIndependent/glslang.y" { (yyval.interm).type = (yyvsp[-4].interm.type); TIntermNode* initNode = parseContext.declareVariable((yyvsp[-3].lex).loc, *(yyvsp[-3].lex).string, (yyvsp[-4].interm.type), (yyvsp[-2].interm).arraySizes, (yyvsp[0].interm.intermTypedNode)); (yyval.interm).intermNode = parseContext.intermediate.growAggregate(0, initNode, (yyvsp[-1].lex).loc); } #line 6071 "MachineIndependent/glslang_tab.cpp" break; case 132: /* single_declaration: fully_specified_type IDENTIFIER EQUAL initializer */ #line 1166 "MachineIndependent/glslang.y" { (yyval.interm).type = (yyvsp[-3].interm.type); TIntermNode* initNode = parseContext.declareVariable((yyvsp[-2].lex).loc, *(yyvsp[-2].lex).string, (yyvsp[-3].interm.type), 0, (yyvsp[0].interm.intermTypedNode)); (yyval.interm).intermNode = parseContext.intermediate.growAggregate(0, initNode, (yyvsp[-1].lex).loc); } #line 6081 "MachineIndependent/glslang_tab.cpp" break; case 133: /* fully_specified_type: type_specifier */ #line 1175 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[0].interm.type); parseContext.globalQualifierTypeCheck((yyvsp[0].interm.type).loc, (yyvsp[0].interm.type).qualifier, (yyval.interm.type)); if ((yyvsp[0].interm.type).arraySizes) { parseContext.profileRequires((yyvsp[0].interm.type).loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed type"); parseContext.profileRequires((yyvsp[0].interm.type).loc, EEsProfile, 300, 0, "arrayed type"); } parseContext.precisionQualifierCheck((yyval.interm.type).loc, (yyval.interm.type).basicType, (yyval.interm.type).qualifier); } #line 6096 "MachineIndependent/glslang_tab.cpp" break; case 134: /* fully_specified_type: type_qualifier type_specifier */ #line 1185 "MachineIndependent/glslang.y" { parseContext.globalQualifierFixCheck((yyvsp[-1].interm.type).loc, (yyvsp[-1].interm.type).qualifier); parseContext.globalQualifierTypeCheck((yyvsp[-1].interm.type).loc, (yyvsp[-1].interm.type).qualifier, (yyvsp[0].interm.type)); if ((yyvsp[0].interm.type).arraySizes) { parseContext.profileRequires((yyvsp[0].interm.type).loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed type"); parseContext.profileRequires((yyvsp[0].interm.type).loc, EEsProfile, 300, 0, "arrayed type"); } if ((yyvsp[0].interm.type).arraySizes && parseContext.arrayQualifierError((yyvsp[0].interm.type).loc, (yyvsp[-1].interm.type).qualifier)) (yyvsp[0].interm.type).arraySizes = nullptr; parseContext.checkNoShaderLayouts((yyvsp[0].interm.type).loc, (yyvsp[-1].interm.type).shaderQualifiers); (yyvsp[0].interm.type).shaderQualifiers.merge((yyvsp[-1].interm.type).shaderQualifiers); parseContext.mergeQualifiers((yyvsp[0].interm.type).loc, (yyvsp[0].interm.type).qualifier, (yyvsp[-1].interm.type).qualifier, true); parseContext.precisionQualifierCheck((yyvsp[0].interm.type).loc, (yyvsp[0].interm.type).basicType, (yyvsp[0].interm.type).qualifier); (yyval.interm.type) = (yyvsp[0].interm.type); if (! (yyval.interm.type).qualifier.isInterpolation() && ((parseContext.language == EShLangVertex && (yyval.interm.type).qualifier.storage == EvqVaryingOut) || (parseContext.language == EShLangFragment && (yyval.interm.type).qualifier.storage == EvqVaryingIn))) (yyval.interm.type).qualifier.smooth = true; } #line 6125 "MachineIndependent/glslang_tab.cpp" break; case 135: /* invariant_qualifier: INVARIANT */ #line 1212 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "invariant"); parseContext.profileRequires((yyval.interm.type).loc, ENoProfile, 120, 0, "invariant"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.invariant = true; } #line 6136 "MachineIndependent/glslang_tab.cpp" break; case 136: /* interpolation_qualifier: SMOOTH */ #line 1221 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "smooth"); parseContext.profileRequires((yyvsp[0].lex).loc, ENoProfile, 130, 0, "smooth"); parseContext.profileRequires((yyvsp[0].lex).loc, EEsProfile, 300, 0, "smooth"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.smooth = true; } #line 6148 "MachineIndependent/glslang_tab.cpp" break; case 137: /* interpolation_qualifier: FLAT */ #line 1228 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "flat"); parseContext.profileRequires((yyvsp[0].lex).loc, ENoProfile, 130, 0, "flat"); parseContext.profileRequires((yyvsp[0].lex).loc, EEsProfile, 300, 0, "flat"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.flat = true; } #line 6160 "MachineIndependent/glslang_tab.cpp" break; case 138: /* interpolation_qualifier: NOPERSPECTIVE */ #line 1236 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "noperspective"); parseContext.profileRequires((yyvsp[0].lex).loc, EEsProfile, 0, E_GL_NV_shader_noperspective_interpolation, "noperspective"); parseContext.profileRequires((yyvsp[0].lex).loc, ENoProfile, 130, 0, "noperspective"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.nopersp = true; } #line 6172 "MachineIndependent/glslang_tab.cpp" break; case 139: /* interpolation_qualifier: EXPLICITINTERPAMD */ #line 1243 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "__explicitInterpAMD"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 450, E_GL_AMD_shader_explicit_vertex_parameter, "explicit interpolation"); parseContext.profileRequires((yyvsp[0].lex).loc, ECompatibilityProfile, 450, E_GL_AMD_shader_explicit_vertex_parameter, "explicit interpolation"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.explicitInterp = true; } #line 6184 "MachineIndependent/glslang_tab.cpp" break; case 140: /* interpolation_qualifier: PERVERTEXNV */ #line 1250 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "pervertexNV"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 0, E_GL_NV_fragment_shader_barycentric, "fragment shader barycentric"); parseContext.profileRequires((yyvsp[0].lex).loc, ECompatibilityProfile, 0, E_GL_NV_fragment_shader_barycentric, "fragment shader barycentric"); parseContext.profileRequires((yyvsp[0].lex).loc, EEsProfile, 0, E_GL_NV_fragment_shader_barycentric, "fragment shader barycentric"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.pervertexNV = true; } #line 6197 "MachineIndependent/glslang_tab.cpp" break; case 141: /* interpolation_qualifier: PERPRIMITIVENV */ #line 1258 "MachineIndependent/glslang.y" { // No need for profile version or extension check. Shader stage already checks both. parseContext.globalCheck((yyvsp[0].lex).loc, "perprimitiveNV"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangFragmentMask | EShLangMeshNVMask), "perprimitiveNV"); // Fragment shader stage doesn't check for extension. So we explicitly add below extension check. if (parseContext.language == EShLangFragment) parseContext.requireExtensions((yyvsp[0].lex).loc, 1, &E_GL_NV_mesh_shader, "perprimitiveNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.perPrimitiveNV = true; } #line 6212 "MachineIndependent/glslang_tab.cpp" break; case 142: /* interpolation_qualifier: PERVIEWNV */ #line 1268 "MachineIndependent/glslang.y" { // No need for profile version or extension check. Shader stage already checks both. parseContext.globalCheck((yyvsp[0].lex).loc, "perviewNV"); parseContext.requireStage((yyvsp[0].lex).loc, EShLangMeshNV, "perviewNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.perViewNV = true; } #line 6224 "MachineIndependent/glslang_tab.cpp" break; case 143: /* interpolation_qualifier: PERTASKNV */ #line 1275 "MachineIndependent/glslang.y" { // No need for profile version or extension check. Shader stage already checks both. parseContext.globalCheck((yyvsp[0].lex).loc, "taskNV"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangTaskNVMask | EShLangMeshNVMask), "taskNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.perTaskNV = true; } #line 6236 "MachineIndependent/glslang_tab.cpp" break; case 144: /* layout_qualifier: LAYOUT LEFT_PAREN layout_qualifier_id_list RIGHT_PAREN */ #line 1286 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[-1].interm.type); } #line 6244 "MachineIndependent/glslang_tab.cpp" break; case 145: /* layout_qualifier_id_list: layout_qualifier_id */ #line 1292 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6252 "MachineIndependent/glslang_tab.cpp" break; case 146: /* layout_qualifier_id_list: layout_qualifier_id_list COMMA layout_qualifier_id */ #line 1295 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[-2].interm.type); (yyval.interm.type).shaderQualifiers.merge((yyvsp[0].interm.type).shaderQualifiers); parseContext.mergeObjectLayoutQualifiers((yyval.interm.type).qualifier, (yyvsp[0].interm.type).qualifier, false); } #line 6262 "MachineIndependent/glslang_tab.cpp" break; case 147: /* layout_qualifier_id: IDENTIFIER */ #line 1302 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); parseContext.setLayoutQualifier((yyvsp[0].lex).loc, (yyval.interm.type), *(yyvsp[0].lex).string); } #line 6271 "MachineIndependent/glslang_tab.cpp" break; case 148: /* layout_qualifier_id: IDENTIFIER EQUAL constant_expression */ #line 1306 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[-2].lex).loc); parseContext.setLayoutQualifier((yyvsp[-2].lex).loc, (yyval.interm.type), *(yyvsp[-2].lex).string, (yyvsp[0].interm.intermTypedNode)); } #line 6280 "MachineIndependent/glslang_tab.cpp" break; case 149: /* layout_qualifier_id: SHARED */ #line 1310 "MachineIndependent/glslang.y" { // because "shared" is both an identifier and a keyword (yyval.interm.type).init((yyvsp[0].lex).loc); TString strShared("shared"); parseContext.setLayoutQualifier((yyvsp[0].lex).loc, (yyval.interm.type), strShared); } #line 6290 "MachineIndependent/glslang_tab.cpp" break; case 150: /* precise_qualifier: PRECISE */ #line 1319 "MachineIndependent/glslang.y" { parseContext.profileRequires((yyval.interm.type).loc, ECoreProfile | ECompatibilityProfile, 400, E_GL_ARB_gpu_shader5, "precise"); parseContext.profileRequires((yyvsp[0].lex).loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5, "precise"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.noContraction = true; } #line 6301 "MachineIndependent/glslang_tab.cpp" break; case 151: /* type_qualifier: single_type_qualifier */ #line 1329 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6309 "MachineIndependent/glslang_tab.cpp" break; case 152: /* type_qualifier: type_qualifier single_type_qualifier */ #line 1332 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[-1].interm.type); if ((yyval.interm.type).basicType == EbtVoid) (yyval.interm.type).basicType = (yyvsp[0].interm.type).basicType; (yyval.interm.type).shaderQualifiers.merge((yyvsp[0].interm.type).shaderQualifiers); parseContext.mergeQualifiers((yyval.interm.type).loc, (yyval.interm.type).qualifier, (yyvsp[0].interm.type).qualifier, false); } #line 6322 "MachineIndependent/glslang_tab.cpp" break; case 153: /* single_type_qualifier: storage_qualifier */ #line 1343 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6330 "MachineIndependent/glslang_tab.cpp" break; case 154: /* single_type_qualifier: layout_qualifier */ #line 1346 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6338 "MachineIndependent/glslang_tab.cpp" break; case 155: /* single_type_qualifier: precision_qualifier */ #line 1349 "MachineIndependent/glslang.y" { parseContext.checkPrecisionQualifier((yyvsp[0].interm.type).loc, (yyvsp[0].interm.type).qualifier.precision); (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6347 "MachineIndependent/glslang_tab.cpp" break; case 156: /* single_type_qualifier: interpolation_qualifier */ #line 1353 "MachineIndependent/glslang.y" { // allow inheritance of storage qualifier from block declaration (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6356 "MachineIndependent/glslang_tab.cpp" break; case 157: /* single_type_qualifier: invariant_qualifier */ #line 1357 "MachineIndependent/glslang.y" { // allow inheritance of storage qualifier from block declaration (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6365 "MachineIndependent/glslang_tab.cpp" break; case 158: /* single_type_qualifier: precise_qualifier */ #line 1362 "MachineIndependent/glslang.y" { // allow inheritance of storage qualifier from block declaration (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6374 "MachineIndependent/glslang_tab.cpp" break; case 159: /* single_type_qualifier: non_uniform_qualifier */ #line 1366 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[0].interm.type); } #line 6382 "MachineIndependent/glslang_tab.cpp" break; case 160: /* storage_qualifier: CONST */ #line 1373 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqConst; // will later turn into EvqConstReadOnly, if the initializer is not constant } #line 6391 "MachineIndependent/glslang_tab.cpp" break; case 161: /* storage_qualifier: INOUT */ #line 1377 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "inout"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqInOut; } #line 6401 "MachineIndependent/glslang_tab.cpp" break; case 162: /* storage_qualifier: IN */ #line 1382 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "in"); (yyval.interm.type).init((yyvsp[0].lex).loc); // whether this is a parameter "in" or a pipeline "in" will get sorted out a bit later (yyval.interm.type).qualifier.storage = EvqIn; } #line 6412 "MachineIndependent/glslang_tab.cpp" break; case 163: /* storage_qualifier: OUT */ #line 1388 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "out"); (yyval.interm.type).init((yyvsp[0].lex).loc); // whether this is a parameter "out" or a pipeline "out" will get sorted out a bit later (yyval.interm.type).qualifier.storage = EvqOut; } #line 6423 "MachineIndependent/glslang_tab.cpp" break; case 164: /* storage_qualifier: CENTROID */ #line 1394 "MachineIndependent/glslang.y" { parseContext.profileRequires((yyvsp[0].lex).loc, ENoProfile, 120, 0, "centroid"); parseContext.profileRequires((yyvsp[0].lex).loc, EEsProfile, 300, 0, "centroid"); parseContext.globalCheck((yyvsp[0].lex).loc, "centroid"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.centroid = true; } #line 6435 "MachineIndependent/glslang_tab.cpp" break; case 165: /* storage_qualifier: UNIFORM */ #line 1401 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "uniform"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqUniform; } #line 6445 "MachineIndependent/glslang_tab.cpp" break; case 166: /* storage_qualifier: SHARED */ #line 1406 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "shared"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_compute_shader, "shared"); parseContext.profileRequires((yyvsp[0].lex).loc, EEsProfile, 310, 0, "shared"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangComputeMask | EShLangMeshNVMask | EShLangTaskNVMask), "shared"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqShared; } #line 6458 "MachineIndependent/glslang_tab.cpp" break; case 167: /* storage_qualifier: BUFFER */ #line 1414 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "buffer"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqBuffer; } #line 6468 "MachineIndependent/glslang_tab.cpp" break; case 168: /* storage_qualifier: ATTRIBUTE */ #line 1420 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[0].lex).loc, EShLangVertex, "attribute"); parseContext.checkDeprecated((yyvsp[0].lex).loc, ECoreProfile, 130, "attribute"); parseContext.checkDeprecated((yyvsp[0].lex).loc, ENoProfile, 130, "attribute"); parseContext.requireNotRemoved((yyvsp[0].lex).loc, ECoreProfile, 420, "attribute"); parseContext.requireNotRemoved((yyvsp[0].lex).loc, EEsProfile, 300, "attribute"); parseContext.globalCheck((yyvsp[0].lex).loc, "attribute"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqVaryingIn; } #line 6485 "MachineIndependent/glslang_tab.cpp" break; case 169: /* storage_qualifier: VARYING */ #line 1432 "MachineIndependent/glslang.y" { parseContext.checkDeprecated((yyvsp[0].lex).loc, ENoProfile, 130, "varying"); parseContext.checkDeprecated((yyvsp[0].lex).loc, ECoreProfile, 130, "varying"); parseContext.requireNotRemoved((yyvsp[0].lex).loc, ECoreProfile, 420, "varying"); parseContext.requireNotRemoved((yyvsp[0].lex).loc, EEsProfile, 300, "varying"); parseContext.globalCheck((yyvsp[0].lex).loc, "varying"); (yyval.interm.type).init((yyvsp[0].lex).loc); if (parseContext.language == EShLangVertex) (yyval.interm.type).qualifier.storage = EvqVaryingOut; else (yyval.interm.type).qualifier.storage = EvqVaryingIn; } #line 6504 "MachineIndependent/glslang_tab.cpp" break; case 170: /* storage_qualifier: PATCH */ #line 1446 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "patch"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangTessControlMask | EShLangTessEvaluationMask), "patch"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.patch = true; } #line 6515 "MachineIndependent/glslang_tab.cpp" break; case 171: /* storage_qualifier: SAMPLE */ #line 1452 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "sample"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.sample = true; } #line 6525 "MachineIndependent/glslang_tab.cpp" break; case 172: /* storage_qualifier: HITATTRNV */ #line 1457 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "hitAttributeNV"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangIntersectMask | EShLangClosestHitMask | EShLangAnyHitMask), "hitAttributeNV"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_NV_ray_tracing, "hitAttributeNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqHitAttr; } #line 6538 "MachineIndependent/glslang_tab.cpp" break; case 173: /* storage_qualifier: HITATTREXT */ #line 1465 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "hitAttributeEXT"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangIntersectMask | EShLangClosestHitMask | EShLangAnyHitMask), "hitAttributeEXT"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_EXT_ray_tracing, "hitAttributeNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqHitAttr; } #line 6551 "MachineIndependent/glslang_tab.cpp" break; case 174: /* storage_qualifier: PAYLOADNV */ #line 1473 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "rayPayloadNV"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangAnyHitMask | EShLangMissMask), "rayPayloadNV"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_NV_ray_tracing, "rayPayloadNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqPayload; } #line 6564 "MachineIndependent/glslang_tab.cpp" break; case 175: /* storage_qualifier: PAYLOADEXT */ #line 1481 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "rayPayloadEXT"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangAnyHitMask | EShLangMissMask), "rayPayloadEXT"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_EXT_ray_tracing, "rayPayloadEXT"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqPayload; } #line 6577 "MachineIndependent/glslang_tab.cpp" break; case 176: /* storage_qualifier: PAYLOADINNV */ #line 1489 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "rayPayloadInNV"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangClosestHitMask | EShLangAnyHitMask | EShLangMissMask), "rayPayloadInNV"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_NV_ray_tracing, "rayPayloadInNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqPayloadIn; } #line 6590 "MachineIndependent/glslang_tab.cpp" break; case 177: /* storage_qualifier: PAYLOADINEXT */ #line 1497 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "rayPayloadInEXT"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangClosestHitMask | EShLangAnyHitMask | EShLangMissMask), "rayPayloadInEXT"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_EXT_ray_tracing, "rayPayloadInEXT"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqPayloadIn; } #line 6603 "MachineIndependent/glslang_tab.cpp" break; case 178: /* storage_qualifier: CALLDATANV */ #line 1505 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "callableDataNV"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangMissMask | EShLangCallableMask), "callableDataNV"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_NV_ray_tracing, "callableDataNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqCallableData; } #line 6616 "MachineIndependent/glslang_tab.cpp" break; case 179: /* storage_qualifier: CALLDATAEXT */ #line 1513 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "callableDataEXT"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangMissMask | EShLangCallableMask), "callableDataEXT"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_EXT_ray_tracing, "callableDataEXT"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqCallableData; } #line 6629 "MachineIndependent/glslang_tab.cpp" break; case 180: /* storage_qualifier: CALLDATAINNV */ #line 1521 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "callableDataInNV"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangCallableMask), "callableDataInNV"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_NV_ray_tracing, "callableDataInNV"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqCallableDataIn; } #line 6641 "MachineIndependent/glslang_tab.cpp" break; case 181: /* storage_qualifier: CALLDATAINEXT */ #line 1528 "MachineIndependent/glslang.y" { parseContext.globalCheck((yyvsp[0].lex).loc, "callableDataInEXT"); parseContext.requireStage((yyvsp[0].lex).loc, (EShLanguageMask)(EShLangCallableMask), "callableDataInEXT"); parseContext.profileRequires((yyvsp[0].lex).loc, ECoreProfile, 460, E_GL_EXT_ray_tracing, "callableDataInEXT"); (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.storage = EvqCallableDataIn; } #line 6653 "MachineIndependent/glslang_tab.cpp" break; case 182: /* storage_qualifier: COHERENT */ #line 1535 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.coherent = true; } #line 6662 "MachineIndependent/glslang_tab.cpp" break; case 183: /* storage_qualifier: DEVICECOHERENT */ #line 1539 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); parseContext.requireExtensions((yyvsp[0].lex).loc, 1, &E_GL_KHR_memory_scope_semantics, "devicecoherent"); (yyval.interm.type).qualifier.devicecoherent = true; } #line 6672 "MachineIndependent/glslang_tab.cpp" break; case 184: /* storage_qualifier: QUEUEFAMILYCOHERENT */ #line 1544 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); parseContext.requireExtensions((yyvsp[0].lex).loc, 1, &E_GL_KHR_memory_scope_semantics, "queuefamilycoherent"); (yyval.interm.type).qualifier.queuefamilycoherent = true; } #line 6682 "MachineIndependent/glslang_tab.cpp" break; case 185: /* storage_qualifier: WORKGROUPCOHERENT */ #line 1549 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); parseContext.requireExtensions((yyvsp[0].lex).loc, 1, &E_GL_KHR_memory_scope_semantics, "workgroupcoherent"); (yyval.interm.type).qualifier.workgroupcoherent = true; } #line 6692 "MachineIndependent/glslang_tab.cpp" break; case 186: /* storage_qualifier: SUBGROUPCOHERENT */ #line 1554 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); parseContext.requireExtensions((yyvsp[0].lex).loc, 1, &E_GL_KHR_memory_scope_semantics, "subgroupcoherent"); (yyval.interm.type).qualifier.subgroupcoherent = true; } #line 6702 "MachineIndependent/glslang_tab.cpp" break; case 187: /* storage_qualifier: NONPRIVATE */ #line 1559 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); parseContext.requireExtensions((yyvsp[0].lex).loc, 1, &E_GL_KHR_memory_scope_semantics, "nonprivate"); (yyval.interm.type).qualifier.nonprivate = true; } #line 6712 "MachineIndependent/glslang_tab.cpp" break; case 188: /* storage_qualifier: SHADERCALLCOHERENT */ #line 1564 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); parseContext.requireExtensions((yyvsp[0].lex).loc, 1, &E_GL_EXT_ray_tracing, "shadercallcoherent"); (yyval.interm.type).qualifier.shadercallcoherent = true; } #line 6722 "MachineIndependent/glslang_tab.cpp" break; case 189: /* storage_qualifier: VOLATILE */ #line 1569 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.volatil = true; } #line 6731 "MachineIndependent/glslang_tab.cpp" break; case 190: /* storage_qualifier: RESTRICT */ #line 1573 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.restrict = true; } #line 6740 "MachineIndependent/glslang_tab.cpp" break; case 191: /* storage_qualifier: READONLY */ #line 1577 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.readonly = true; } #line 6749 "MachineIndependent/glslang_tab.cpp" break; case 192: /* storage_qualifier: WRITEONLY */ #line 1581 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.writeonly = true; } #line 6758 "MachineIndependent/glslang_tab.cpp" break; case 193: /* storage_qualifier: SUBROUTINE */ #line 1585 "MachineIndependent/glslang.y" { parseContext.spvRemoved((yyvsp[0].lex).loc, "subroutine"); parseContext.globalCheck((yyvsp[0].lex).loc, "subroutine"); parseContext.unimplemented((yyvsp[0].lex).loc, "subroutine"); (yyval.interm.type).init((yyvsp[0].lex).loc); } #line 6769 "MachineIndependent/glslang_tab.cpp" break; case 194: /* storage_qualifier: SUBROUTINE LEFT_PAREN type_name_list RIGHT_PAREN */ #line 1591 "MachineIndependent/glslang.y" { parseContext.spvRemoved((yyvsp[-3].lex).loc, "subroutine"); parseContext.globalCheck((yyvsp[-3].lex).loc, "subroutine"); parseContext.unimplemented((yyvsp[-3].lex).loc, "subroutine"); (yyval.interm.type).init((yyvsp[-3].lex).loc); } #line 6780 "MachineIndependent/glslang_tab.cpp" break; case 195: /* non_uniform_qualifier: NONUNIFORM */ #line 1602 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc); (yyval.interm.type).qualifier.nonUniform = true; } #line 6789 "MachineIndependent/glslang_tab.cpp" break; case 196: /* type_name_list: IDENTIFIER */ #line 1609 "MachineIndependent/glslang.y" { // TODO } #line 6797 "MachineIndependent/glslang_tab.cpp" break; case 197: /* type_name_list: type_name_list COMMA IDENTIFIER */ #line 1612 "MachineIndependent/glslang.y" { // TODO: 4.0 semantics: subroutines // 1) make sure each identifier is a type declared earlier with SUBROUTINE // 2) save all of the identifiers for future comparison with the declared function } #line 6807 "MachineIndependent/glslang_tab.cpp" break; case 198: /* type_specifier: type_specifier_nonarray type_parameter_specifier_opt */ #line 1621 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[-1].interm.type); (yyval.interm.type).qualifier.precision = parseContext.getDefaultPrecision((yyval.interm.type)); (yyval.interm.type).typeParameters = (yyvsp[0].interm.typeParameters); } #line 6817 "MachineIndependent/glslang_tab.cpp" break; case 199: /* type_specifier: type_specifier_nonarray type_parameter_specifier_opt array_specifier */ #line 1626 "MachineIndependent/glslang.y" { parseContext.arrayOfArrayVersionCheck((yyvsp[0].interm).loc, (yyvsp[0].interm).arraySizes); (yyval.interm.type) = (yyvsp[-2].interm.type); (yyval.interm.type).qualifier.precision = parseContext.getDefaultPrecision((yyval.interm.type)); (yyval.interm.type).typeParameters = (yyvsp[-1].interm.typeParameters); (yyval.interm.type).arraySizes = (yyvsp[0].interm).arraySizes; } #line 6829 "MachineIndependent/glslang_tab.cpp" break; case 200: /* array_specifier: LEFT_BRACKET RIGHT_BRACKET */ #line 1636 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[-1].lex).loc; (yyval.interm).arraySizes = new TArraySizes; (yyval.interm).arraySizes->addInnerSize(); } #line 6839 "MachineIndependent/glslang_tab.cpp" break; case 201: /* array_specifier: LEFT_BRACKET conditional_expression RIGHT_BRACKET */ #line 1641 "MachineIndependent/glslang.y" { (yyval.interm).loc = (yyvsp[-2].lex).loc; (yyval.interm).arraySizes = new TArraySizes; TArraySize size; parseContext.arraySizeCheck((yyvsp[-1].interm.intermTypedNode)->getLoc(), (yyvsp[-1].interm.intermTypedNode), size, "array size"); (yyval.interm).arraySizes->addInnerSize(size); } #line 6852 "MachineIndependent/glslang_tab.cpp" break; case 202: /* array_specifier: array_specifier LEFT_BRACKET RIGHT_BRACKET */ #line 1649 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[-2].interm); (yyval.interm).arraySizes->addInnerSize(); } #line 6861 "MachineIndependent/glslang_tab.cpp" break; case 203: /* array_specifier: array_specifier LEFT_BRACKET conditional_expression RIGHT_BRACKET */ #line 1653 "MachineIndependent/glslang.y" { (yyval.interm) = (yyvsp[-3].interm); TArraySize size; parseContext.arraySizeCheck((yyvsp[-1].interm.intermTypedNode)->getLoc(), (yyvsp[-1].interm.intermTypedNode), size, "array size"); (yyval.interm).arraySizes->addInnerSize(size); } #line 6873 "MachineIndependent/glslang_tab.cpp" break; case 204: /* type_parameter_specifier_opt: type_parameter_specifier */ #line 1663 "MachineIndependent/glslang.y" { (yyval.interm.typeParameters) = (yyvsp[0].interm.typeParameters); } #line 6881 "MachineIndependent/glslang_tab.cpp" break; case 205: /* type_parameter_specifier_opt: %empty */ #line 1666 "MachineIndependent/glslang.y" { (yyval.interm.typeParameters) = 0; } #line 6889 "MachineIndependent/glslang_tab.cpp" break; case 206: /* type_parameter_specifier: LEFT_ANGLE type_parameter_specifier_list RIGHT_ANGLE */ #line 1672 "MachineIndependent/glslang.y" { (yyval.interm.typeParameters) = (yyvsp[-1].interm.typeParameters); } #line 6897 "MachineIndependent/glslang_tab.cpp" break; case 207: /* type_parameter_specifier_list: unary_expression */ #line 1678 "MachineIndependent/glslang.y" { (yyval.interm.typeParameters) = new TArraySizes; TArraySize size; parseContext.arraySizeCheck((yyvsp[0].interm.intermTypedNode)->getLoc(), (yyvsp[0].interm.intermTypedNode), size, "type parameter"); (yyval.interm.typeParameters)->addInnerSize(size); } #line 6909 "MachineIndependent/glslang_tab.cpp" break; case 208: /* type_parameter_specifier_list: type_parameter_specifier_list COMMA unary_expression */ #line 1685 "MachineIndependent/glslang.y" { (yyval.interm.typeParameters) = (yyvsp[-2].interm.typeParameters); TArraySize size; parseContext.arraySizeCheck((yyvsp[0].interm.intermTypedNode)->getLoc(), (yyvsp[0].interm.intermTypedNode), size, "type parameter"); (yyval.interm.typeParameters)->addInnerSize(size); } #line 6921 "MachineIndependent/glslang_tab.cpp" break; case 209: /* type_specifier_nonarray: VOID */ #line 1695 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtVoid; } #line 6930 "MachineIndependent/glslang_tab.cpp" break; case 210: /* type_specifier_nonarray: FLOAT */ #line 1699 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; } #line 6939 "MachineIndependent/glslang_tab.cpp" break; case 211: /* type_specifier_nonarray: INT */ #line 1703 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; } #line 6948 "MachineIndependent/glslang_tab.cpp" break; case 212: /* type_specifier_nonarray: UINT */ #line 1707 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "unsigned integer"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; } #line 6958 "MachineIndependent/glslang_tab.cpp" break; case 213: /* type_specifier_nonarray: BOOL */ #line 1712 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtBool; } #line 6967 "MachineIndependent/glslang_tab.cpp" break; case 214: /* type_specifier_nonarray: VEC2 */ #line 1716 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setVector(2); } #line 6977 "MachineIndependent/glslang_tab.cpp" break; case 215: /* type_specifier_nonarray: VEC3 */ #line 1721 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setVector(3); } #line 6987 "MachineIndependent/glslang_tab.cpp" break; case 216: /* type_specifier_nonarray: VEC4 */ #line 1726 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setVector(4); } #line 6997 "MachineIndependent/glslang_tab.cpp" break; case 217: /* type_specifier_nonarray: BVEC2 */ #line 1731 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtBool; (yyval.interm.type).setVector(2); } #line 7007 "MachineIndependent/glslang_tab.cpp" break; case 218: /* type_specifier_nonarray: BVEC3 */ #line 1736 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtBool; (yyval.interm.type).setVector(3); } #line 7017 "MachineIndependent/glslang_tab.cpp" break; case 219: /* type_specifier_nonarray: BVEC4 */ #line 1741 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtBool; (yyval.interm.type).setVector(4); } #line 7027 "MachineIndependent/glslang_tab.cpp" break; case 220: /* type_specifier_nonarray: IVEC2 */ #line 1746 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; (yyval.interm.type).setVector(2); } #line 7037 "MachineIndependent/glslang_tab.cpp" break; case 221: /* type_specifier_nonarray: IVEC3 */ #line 1751 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; (yyval.interm.type).setVector(3); } #line 7047 "MachineIndependent/glslang_tab.cpp" break; case 222: /* type_specifier_nonarray: IVEC4 */ #line 1756 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; (yyval.interm.type).setVector(4); } #line 7057 "MachineIndependent/glslang_tab.cpp" break; case 223: /* type_specifier_nonarray: UVEC2 */ #line 1761 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "unsigned integer vector"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; (yyval.interm.type).setVector(2); } #line 7068 "MachineIndependent/glslang_tab.cpp" break; case 224: /* type_specifier_nonarray: UVEC3 */ #line 1767 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "unsigned integer vector"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; (yyval.interm.type).setVector(3); } #line 7079 "MachineIndependent/glslang_tab.cpp" break; case 225: /* type_specifier_nonarray: UVEC4 */ #line 1773 "MachineIndependent/glslang.y" { parseContext.fullIntegerCheck((yyvsp[0].lex).loc, "unsigned integer vector"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; (yyval.interm.type).setVector(4); } #line 7090 "MachineIndependent/glslang_tab.cpp" break; case 226: /* type_specifier_nonarray: MAT2 */ #line 1779 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(2, 2); } #line 7100 "MachineIndependent/glslang_tab.cpp" break; case 227: /* type_specifier_nonarray: MAT3 */ #line 1784 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(3, 3); } #line 7110 "MachineIndependent/glslang_tab.cpp" break; case 228: /* type_specifier_nonarray: MAT4 */ #line 1789 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(4, 4); } #line 7120 "MachineIndependent/glslang_tab.cpp" break; case 229: /* type_specifier_nonarray: MAT2X2 */ #line 1794 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(2, 2); } #line 7130 "MachineIndependent/glslang_tab.cpp" break; case 230: /* type_specifier_nonarray: MAT2X3 */ #line 1799 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(2, 3); } #line 7140 "MachineIndependent/glslang_tab.cpp" break; case 231: /* type_specifier_nonarray: MAT2X4 */ #line 1804 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(2, 4); } #line 7150 "MachineIndependent/glslang_tab.cpp" break; case 232: /* type_specifier_nonarray: MAT3X2 */ #line 1809 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(3, 2); } #line 7160 "MachineIndependent/glslang_tab.cpp" break; case 233: /* type_specifier_nonarray: MAT3X3 */ #line 1814 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(3, 3); } #line 7170 "MachineIndependent/glslang_tab.cpp" break; case 234: /* type_specifier_nonarray: MAT3X4 */ #line 1819 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(3, 4); } #line 7180 "MachineIndependent/glslang_tab.cpp" break; case 235: /* type_specifier_nonarray: MAT4X2 */ #line 1824 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(4, 2); } #line 7190 "MachineIndependent/glslang_tab.cpp" break; case 236: /* type_specifier_nonarray: MAT4X3 */ #line 1829 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(4, 3); } #line 7200 "MachineIndependent/glslang_tab.cpp" break; case 237: /* type_specifier_nonarray: MAT4X4 */ #line 1834 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(4, 4); } #line 7210 "MachineIndependent/glslang_tab.cpp" break; case 238: /* type_specifier_nonarray: DOUBLE */ #line 1840 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; } #line 7222 "MachineIndependent/glslang_tab.cpp" break; case 239: /* type_specifier_nonarray: FLOAT16_T */ #line 1847 "MachineIndependent/glslang.y" { parseContext.float16ScalarVectorCheck((yyvsp[0].lex).loc, "float16_t", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; } #line 7232 "MachineIndependent/glslang_tab.cpp" break; case 240: /* type_specifier_nonarray: FLOAT32_T */ #line 1852 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; } #line 7242 "MachineIndependent/glslang_tab.cpp" break; case 241: /* type_specifier_nonarray: FLOAT64_T */ #line 1857 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; } #line 7252 "MachineIndependent/glslang_tab.cpp" break; case 242: /* type_specifier_nonarray: INT8_T */ #line 1862 "MachineIndependent/glslang.y" { parseContext.int8ScalarVectorCheck((yyvsp[0].lex).loc, "8-bit signed integer", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt8; } #line 7262 "MachineIndependent/glslang_tab.cpp" break; case 243: /* type_specifier_nonarray: UINT8_T */ #line 1867 "MachineIndependent/glslang.y" { parseContext.int8ScalarVectorCheck((yyvsp[0].lex).loc, "8-bit unsigned integer", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint8; } #line 7272 "MachineIndependent/glslang_tab.cpp" break; case 244: /* type_specifier_nonarray: INT16_T */ #line 1872 "MachineIndependent/glslang.y" { parseContext.int16ScalarVectorCheck((yyvsp[0].lex).loc, "16-bit signed integer", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt16; } #line 7282 "MachineIndependent/glslang_tab.cpp" break; case 245: /* type_specifier_nonarray: UINT16_T */ #line 1877 "MachineIndependent/glslang.y" { parseContext.int16ScalarVectorCheck((yyvsp[0].lex).loc, "16-bit unsigned integer", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint16; } #line 7292 "MachineIndependent/glslang_tab.cpp" break; case 246: /* type_specifier_nonarray: INT32_T */ #line 1882 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit signed integer", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; } #line 7302 "MachineIndependent/glslang_tab.cpp" break; case 247: /* type_specifier_nonarray: UINT32_T */ #line 1887 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit unsigned integer", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; } #line 7312 "MachineIndependent/glslang_tab.cpp" break; case 248: /* type_specifier_nonarray: INT64_T */ #line 1892 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit integer", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt64; } #line 7322 "MachineIndependent/glslang_tab.cpp" break; case 249: /* type_specifier_nonarray: UINT64_T */ #line 1897 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit unsigned integer", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint64; } #line 7332 "MachineIndependent/glslang_tab.cpp" break; case 250: /* type_specifier_nonarray: DVEC2 */ #line 1902 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double vector"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double vector"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setVector(2); } #line 7345 "MachineIndependent/glslang_tab.cpp" break; case 251: /* type_specifier_nonarray: DVEC3 */ #line 1910 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double vector"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double vector"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setVector(3); } #line 7358 "MachineIndependent/glslang_tab.cpp" break; case 252: /* type_specifier_nonarray: DVEC4 */ #line 1918 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double vector"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double vector"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setVector(4); } #line 7371 "MachineIndependent/glslang_tab.cpp" break; case 253: /* type_specifier_nonarray: F16VEC2 */ #line 1926 "MachineIndependent/glslang.y" { parseContext.float16ScalarVectorCheck((yyvsp[0].lex).loc, "half float vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setVector(2); } #line 7382 "MachineIndependent/glslang_tab.cpp" break; case 254: /* type_specifier_nonarray: F16VEC3 */ #line 1932 "MachineIndependent/glslang.y" { parseContext.float16ScalarVectorCheck((yyvsp[0].lex).loc, "half float vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setVector(3); } #line 7393 "MachineIndependent/glslang_tab.cpp" break; case 255: /* type_specifier_nonarray: F16VEC4 */ #line 1938 "MachineIndependent/glslang.y" { parseContext.float16ScalarVectorCheck((yyvsp[0].lex).loc, "half float vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setVector(4); } #line 7404 "MachineIndependent/glslang_tab.cpp" break; case 256: /* type_specifier_nonarray: F32VEC2 */ #line 1944 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setVector(2); } #line 7415 "MachineIndependent/glslang_tab.cpp" break; case 257: /* type_specifier_nonarray: F32VEC3 */ #line 1950 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setVector(3); } #line 7426 "MachineIndependent/glslang_tab.cpp" break; case 258: /* type_specifier_nonarray: F32VEC4 */ #line 1956 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setVector(4); } #line 7437 "MachineIndependent/glslang_tab.cpp" break; case 259: /* type_specifier_nonarray: F64VEC2 */ #line 1962 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setVector(2); } #line 7448 "MachineIndependent/glslang_tab.cpp" break; case 260: /* type_specifier_nonarray: F64VEC3 */ #line 1968 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setVector(3); } #line 7459 "MachineIndependent/glslang_tab.cpp" break; case 261: /* type_specifier_nonarray: F64VEC4 */ #line 1974 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setVector(4); } #line 7470 "MachineIndependent/glslang_tab.cpp" break; case 262: /* type_specifier_nonarray: I8VEC2 */ #line 1980 "MachineIndependent/glslang.y" { parseContext.int8ScalarVectorCheck((yyvsp[0].lex).loc, "8-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt8; (yyval.interm.type).setVector(2); } #line 7481 "MachineIndependent/glslang_tab.cpp" break; case 263: /* type_specifier_nonarray: I8VEC3 */ #line 1986 "MachineIndependent/glslang.y" { parseContext.int8ScalarVectorCheck((yyvsp[0].lex).loc, "8-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt8; (yyval.interm.type).setVector(3); } #line 7492 "MachineIndependent/glslang_tab.cpp" break; case 264: /* type_specifier_nonarray: I8VEC4 */ #line 1992 "MachineIndependent/glslang.y" { parseContext.int8ScalarVectorCheck((yyvsp[0].lex).loc, "8-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt8; (yyval.interm.type).setVector(4); } #line 7503 "MachineIndependent/glslang_tab.cpp" break; case 265: /* type_specifier_nonarray: I16VEC2 */ #line 1998 "MachineIndependent/glslang.y" { parseContext.int16ScalarVectorCheck((yyvsp[0].lex).loc, "16-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt16; (yyval.interm.type).setVector(2); } #line 7514 "MachineIndependent/glslang_tab.cpp" break; case 266: /* type_specifier_nonarray: I16VEC3 */ #line 2004 "MachineIndependent/glslang.y" { parseContext.int16ScalarVectorCheck((yyvsp[0].lex).loc, "16-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt16; (yyval.interm.type).setVector(3); } #line 7525 "MachineIndependent/glslang_tab.cpp" break; case 267: /* type_specifier_nonarray: I16VEC4 */ #line 2010 "MachineIndependent/glslang.y" { parseContext.int16ScalarVectorCheck((yyvsp[0].lex).loc, "16-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt16; (yyval.interm.type).setVector(4); } #line 7536 "MachineIndependent/glslang_tab.cpp" break; case 268: /* type_specifier_nonarray: I32VEC2 */ #line 2016 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; (yyval.interm.type).setVector(2); } #line 7547 "MachineIndependent/glslang_tab.cpp" break; case 269: /* type_specifier_nonarray: I32VEC3 */ #line 2022 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; (yyval.interm.type).setVector(3); } #line 7558 "MachineIndependent/glslang_tab.cpp" break; case 270: /* type_specifier_nonarray: I32VEC4 */ #line 2028 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit signed integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; (yyval.interm.type).setVector(4); } #line 7569 "MachineIndependent/glslang_tab.cpp" break; case 271: /* type_specifier_nonarray: I64VEC2 */ #line 2034 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt64; (yyval.interm.type).setVector(2); } #line 7580 "MachineIndependent/glslang_tab.cpp" break; case 272: /* type_specifier_nonarray: I64VEC3 */ #line 2040 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt64; (yyval.interm.type).setVector(3); } #line 7591 "MachineIndependent/glslang_tab.cpp" break; case 273: /* type_specifier_nonarray: I64VEC4 */ #line 2046 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt64; (yyval.interm.type).setVector(4); } #line 7602 "MachineIndependent/glslang_tab.cpp" break; case 274: /* type_specifier_nonarray: U8VEC2 */ #line 2052 "MachineIndependent/glslang.y" { parseContext.int8ScalarVectorCheck((yyvsp[0].lex).loc, "8-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint8; (yyval.interm.type).setVector(2); } #line 7613 "MachineIndependent/glslang_tab.cpp" break; case 275: /* type_specifier_nonarray: U8VEC3 */ #line 2058 "MachineIndependent/glslang.y" { parseContext.int8ScalarVectorCheck((yyvsp[0].lex).loc, "8-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint8; (yyval.interm.type).setVector(3); } #line 7624 "MachineIndependent/glslang_tab.cpp" break; case 276: /* type_specifier_nonarray: U8VEC4 */ #line 2064 "MachineIndependent/glslang.y" { parseContext.int8ScalarVectorCheck((yyvsp[0].lex).loc, "8-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint8; (yyval.interm.type).setVector(4); } #line 7635 "MachineIndependent/glslang_tab.cpp" break; case 277: /* type_specifier_nonarray: U16VEC2 */ #line 2070 "MachineIndependent/glslang.y" { parseContext.int16ScalarVectorCheck((yyvsp[0].lex).loc, "16-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint16; (yyval.interm.type).setVector(2); } #line 7646 "MachineIndependent/glslang_tab.cpp" break; case 278: /* type_specifier_nonarray: U16VEC3 */ #line 2076 "MachineIndependent/glslang.y" { parseContext.int16ScalarVectorCheck((yyvsp[0].lex).loc, "16-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint16; (yyval.interm.type).setVector(3); } #line 7657 "MachineIndependent/glslang_tab.cpp" break; case 279: /* type_specifier_nonarray: U16VEC4 */ #line 2082 "MachineIndependent/glslang.y" { parseContext.int16ScalarVectorCheck((yyvsp[0].lex).loc, "16-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint16; (yyval.interm.type).setVector(4); } #line 7668 "MachineIndependent/glslang_tab.cpp" break; case 280: /* type_specifier_nonarray: U32VEC2 */ #line 2088 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; (yyval.interm.type).setVector(2); } #line 7679 "MachineIndependent/glslang_tab.cpp" break; case 281: /* type_specifier_nonarray: U32VEC3 */ #line 2094 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; (yyval.interm.type).setVector(3); } #line 7690 "MachineIndependent/glslang_tab.cpp" break; case 282: /* type_specifier_nonarray: U32VEC4 */ #line 2100 "MachineIndependent/glslang.y" { parseContext.explicitInt32Check((yyvsp[0].lex).loc, "32-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; (yyval.interm.type).setVector(4); } #line 7701 "MachineIndependent/glslang_tab.cpp" break; case 283: /* type_specifier_nonarray: U64VEC2 */ #line 2106 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint64; (yyval.interm.type).setVector(2); } #line 7712 "MachineIndependent/glslang_tab.cpp" break; case 284: /* type_specifier_nonarray: U64VEC3 */ #line 2112 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint64; (yyval.interm.type).setVector(3); } #line 7723 "MachineIndependent/glslang_tab.cpp" break; case 285: /* type_specifier_nonarray: U64VEC4 */ #line 2118 "MachineIndependent/glslang.y" { parseContext.int64Check((yyvsp[0].lex).loc, "64-bit unsigned integer vector", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint64; (yyval.interm.type).setVector(4); } #line 7734 "MachineIndependent/glslang_tab.cpp" break; case 286: /* type_specifier_nonarray: DMAT2 */ #line 2124 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(2, 2); } #line 7747 "MachineIndependent/glslang_tab.cpp" break; case 287: /* type_specifier_nonarray: DMAT3 */ #line 2132 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(3, 3); } #line 7760 "MachineIndependent/glslang_tab.cpp" break; case 288: /* type_specifier_nonarray: DMAT4 */ #line 2140 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(4, 4); } #line 7773 "MachineIndependent/glslang_tab.cpp" break; case 289: /* type_specifier_nonarray: DMAT2X2 */ #line 2148 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(2, 2); } #line 7786 "MachineIndependent/glslang_tab.cpp" break; case 290: /* type_specifier_nonarray: DMAT2X3 */ #line 2156 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(2, 3); } #line 7799 "MachineIndependent/glslang_tab.cpp" break; case 291: /* type_specifier_nonarray: DMAT2X4 */ #line 2164 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(2, 4); } #line 7812 "MachineIndependent/glslang_tab.cpp" break; case 292: /* type_specifier_nonarray: DMAT3X2 */ #line 2172 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(3, 2); } #line 7825 "MachineIndependent/glslang_tab.cpp" break; case 293: /* type_specifier_nonarray: DMAT3X3 */ #line 2180 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(3, 3); } #line 7838 "MachineIndependent/glslang_tab.cpp" break; case 294: /* type_specifier_nonarray: DMAT3X4 */ #line 2188 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(3, 4); } #line 7851 "MachineIndependent/glslang_tab.cpp" break; case 295: /* type_specifier_nonarray: DMAT4X2 */ #line 2196 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(4, 2); } #line 7864 "MachineIndependent/glslang_tab.cpp" break; case 296: /* type_specifier_nonarray: DMAT4X3 */ #line 2204 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(4, 3); } #line 7877 "MachineIndependent/glslang_tab.cpp" break; case 297: /* type_specifier_nonarray: DMAT4X4 */ #line 2212 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ECoreProfile | ECompatibilityProfile, "double matrix"); if (! parseContext.symbolTable.atBuiltInLevel()) parseContext.doubleCheck((yyvsp[0].lex).loc, "double matrix"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(4, 4); } #line 7890 "MachineIndependent/glslang_tab.cpp" break; case 298: /* type_specifier_nonarray: F16MAT2 */ #line 2220 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(2, 2); } #line 7901 "MachineIndependent/glslang_tab.cpp" break; case 299: /* type_specifier_nonarray: F16MAT3 */ #line 2226 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(3, 3); } #line 7912 "MachineIndependent/glslang_tab.cpp" break; case 300: /* type_specifier_nonarray: F16MAT4 */ #line 2232 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(4, 4); } #line 7923 "MachineIndependent/glslang_tab.cpp" break; case 301: /* type_specifier_nonarray: F16MAT2X2 */ #line 2238 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(2, 2); } #line 7934 "MachineIndependent/glslang_tab.cpp" break; case 302: /* type_specifier_nonarray: F16MAT2X3 */ #line 2244 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(2, 3); } #line 7945 "MachineIndependent/glslang_tab.cpp" break; case 303: /* type_specifier_nonarray: F16MAT2X4 */ #line 2250 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(2, 4); } #line 7956 "MachineIndependent/glslang_tab.cpp" break; case 304: /* type_specifier_nonarray: F16MAT3X2 */ #line 2256 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(3, 2); } #line 7967 "MachineIndependent/glslang_tab.cpp" break; case 305: /* type_specifier_nonarray: F16MAT3X3 */ #line 2262 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(3, 3); } #line 7978 "MachineIndependent/glslang_tab.cpp" break; case 306: /* type_specifier_nonarray: F16MAT3X4 */ #line 2268 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(3, 4); } #line 7989 "MachineIndependent/glslang_tab.cpp" break; case 307: /* type_specifier_nonarray: F16MAT4X2 */ #line 2274 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(4, 2); } #line 8000 "MachineIndependent/glslang_tab.cpp" break; case 308: /* type_specifier_nonarray: F16MAT4X3 */ #line 2280 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(4, 3); } #line 8011 "MachineIndependent/glslang_tab.cpp" break; case 309: /* type_specifier_nonarray: F16MAT4X4 */ #line 2286 "MachineIndependent/glslang.y" { parseContext.float16Check((yyvsp[0].lex).loc, "half float matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat16; (yyval.interm.type).setMatrix(4, 4); } #line 8022 "MachineIndependent/glslang_tab.cpp" break; case 310: /* type_specifier_nonarray: F32MAT2 */ #line 2292 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(2, 2); } #line 8033 "MachineIndependent/glslang_tab.cpp" break; case 311: /* type_specifier_nonarray: F32MAT3 */ #line 2298 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(3, 3); } #line 8044 "MachineIndependent/glslang_tab.cpp" break; case 312: /* type_specifier_nonarray: F32MAT4 */ #line 2304 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(4, 4); } #line 8055 "MachineIndependent/glslang_tab.cpp" break; case 313: /* type_specifier_nonarray: F32MAT2X2 */ #line 2310 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(2, 2); } #line 8066 "MachineIndependent/glslang_tab.cpp" break; case 314: /* type_specifier_nonarray: F32MAT2X3 */ #line 2316 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(2, 3); } #line 8077 "MachineIndependent/glslang_tab.cpp" break; case 315: /* type_specifier_nonarray: F32MAT2X4 */ #line 2322 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(2, 4); } #line 8088 "MachineIndependent/glslang_tab.cpp" break; case 316: /* type_specifier_nonarray: F32MAT3X2 */ #line 2328 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(3, 2); } #line 8099 "MachineIndependent/glslang_tab.cpp" break; case 317: /* type_specifier_nonarray: F32MAT3X3 */ #line 2334 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(3, 3); } #line 8110 "MachineIndependent/glslang_tab.cpp" break; case 318: /* type_specifier_nonarray: F32MAT3X4 */ #line 2340 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(3, 4); } #line 8121 "MachineIndependent/glslang_tab.cpp" break; case 319: /* type_specifier_nonarray: F32MAT4X2 */ #line 2346 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(4, 2); } #line 8132 "MachineIndependent/glslang_tab.cpp" break; case 320: /* type_specifier_nonarray: F32MAT4X3 */ #line 2352 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(4, 3); } #line 8143 "MachineIndependent/glslang_tab.cpp" break; case 321: /* type_specifier_nonarray: F32MAT4X4 */ #line 2358 "MachineIndependent/glslang.y" { parseContext.explicitFloat32Check((yyvsp[0].lex).loc, "float32_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).setMatrix(4, 4); } #line 8154 "MachineIndependent/glslang_tab.cpp" break; case 322: /* type_specifier_nonarray: F64MAT2 */ #line 2364 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(2, 2); } #line 8165 "MachineIndependent/glslang_tab.cpp" break; case 323: /* type_specifier_nonarray: F64MAT3 */ #line 2370 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(3, 3); } #line 8176 "MachineIndependent/glslang_tab.cpp" break; case 324: /* type_specifier_nonarray: F64MAT4 */ #line 2376 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(4, 4); } #line 8187 "MachineIndependent/glslang_tab.cpp" break; case 325: /* type_specifier_nonarray: F64MAT2X2 */ #line 2382 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(2, 2); } #line 8198 "MachineIndependent/glslang_tab.cpp" break; case 326: /* type_specifier_nonarray: F64MAT2X3 */ #line 2388 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(2, 3); } #line 8209 "MachineIndependent/glslang_tab.cpp" break; case 327: /* type_specifier_nonarray: F64MAT2X4 */ #line 2394 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(2, 4); } #line 8220 "MachineIndependent/glslang_tab.cpp" break; case 328: /* type_specifier_nonarray: F64MAT3X2 */ #line 2400 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(3, 2); } #line 8231 "MachineIndependent/glslang_tab.cpp" break; case 329: /* type_specifier_nonarray: F64MAT3X3 */ #line 2406 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(3, 3); } #line 8242 "MachineIndependent/glslang_tab.cpp" break; case 330: /* type_specifier_nonarray: F64MAT3X4 */ #line 2412 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(3, 4); } #line 8253 "MachineIndependent/glslang_tab.cpp" break; case 331: /* type_specifier_nonarray: F64MAT4X2 */ #line 2418 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(4, 2); } #line 8264 "MachineIndependent/glslang_tab.cpp" break; case 332: /* type_specifier_nonarray: F64MAT4X3 */ #line 2424 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(4, 3); } #line 8275 "MachineIndependent/glslang_tab.cpp" break; case 333: /* type_specifier_nonarray: F64MAT4X4 */ #line 2430 "MachineIndependent/glslang.y" { parseContext.explicitFloat64Check((yyvsp[0].lex).loc, "float64_t matrix", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtDouble; (yyval.interm.type).setMatrix(4, 4); } #line 8286 "MachineIndependent/glslang_tab.cpp" break; case 334: /* type_specifier_nonarray: ACCSTRUCTNV */ #line 2436 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtAccStruct; } #line 8295 "MachineIndependent/glslang_tab.cpp" break; case 335: /* type_specifier_nonarray: ACCSTRUCTEXT */ #line 2440 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtAccStruct; } #line 8304 "MachineIndependent/glslang_tab.cpp" break; case 336: /* type_specifier_nonarray: RAYQUERYEXT */ #line 2444 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtRayQuery; } #line 8313 "MachineIndependent/glslang_tab.cpp" break; case 337: /* type_specifier_nonarray: ATOMIC_UINT */ #line 2448 "MachineIndependent/glslang.y" { parseContext.vulkanRemoved((yyvsp[0].lex).loc, "atomic counter types"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtAtomicUint; } #line 8323 "MachineIndependent/glslang_tab.cpp" break; case 338: /* type_specifier_nonarray: SAMPLER1D */ #line 2453 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd1D); } #line 8333 "MachineIndependent/glslang_tab.cpp" break; case 339: /* type_specifier_nonarray: SAMPLER2D */ #line 2459 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd2D); } #line 8343 "MachineIndependent/glslang_tab.cpp" break; case 340: /* type_specifier_nonarray: SAMPLER3D */ #line 2464 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd3D); } #line 8353 "MachineIndependent/glslang_tab.cpp" break; case 341: /* type_specifier_nonarray: SAMPLERCUBE */ #line 2469 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, EsdCube); } #line 8363 "MachineIndependent/glslang_tab.cpp" break; case 342: /* type_specifier_nonarray: SAMPLER2DSHADOW */ #line 2474 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd2D, false, true); } #line 8373 "MachineIndependent/glslang_tab.cpp" break; case 343: /* type_specifier_nonarray: SAMPLERCUBESHADOW */ #line 2479 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, EsdCube, false, true); } #line 8383 "MachineIndependent/glslang_tab.cpp" break; case 344: /* type_specifier_nonarray: SAMPLER2DARRAY */ #line 2484 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd2D, true); } #line 8393 "MachineIndependent/glslang_tab.cpp" break; case 345: /* type_specifier_nonarray: SAMPLER2DARRAYSHADOW */ #line 2489 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd2D, true, true); } #line 8403 "MachineIndependent/glslang_tab.cpp" break; case 346: /* type_specifier_nonarray: SAMPLER1DSHADOW */ #line 2495 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd1D, false, true); } #line 8413 "MachineIndependent/glslang_tab.cpp" break; case 347: /* type_specifier_nonarray: SAMPLER1DARRAY */ #line 2500 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd1D, true); } #line 8423 "MachineIndependent/glslang_tab.cpp" break; case 348: /* type_specifier_nonarray: SAMPLER1DARRAYSHADOW */ #line 2505 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd1D, true, true); } #line 8433 "MachineIndependent/glslang_tab.cpp" break; case 349: /* type_specifier_nonarray: SAMPLERCUBEARRAY */ #line 2510 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, EsdCube, true); } #line 8443 "MachineIndependent/glslang_tab.cpp" break; case 350: /* type_specifier_nonarray: SAMPLERCUBEARRAYSHADOW */ #line 2515 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, EsdCube, true, true); } #line 8453 "MachineIndependent/glslang_tab.cpp" break; case 351: /* type_specifier_nonarray: F16SAMPLER1D */ #line 2520 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd1D); } #line 8464 "MachineIndependent/glslang_tab.cpp" break; case 352: /* type_specifier_nonarray: F16SAMPLER2D */ #line 2526 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd2D); } #line 8475 "MachineIndependent/glslang_tab.cpp" break; case 353: /* type_specifier_nonarray: F16SAMPLER3D */ #line 2532 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd3D); } #line 8486 "MachineIndependent/glslang_tab.cpp" break; case 354: /* type_specifier_nonarray: F16SAMPLERCUBE */ #line 2538 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, EsdCube); } #line 8497 "MachineIndependent/glslang_tab.cpp" break; case 355: /* type_specifier_nonarray: F16SAMPLER1DSHADOW */ #line 2544 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd1D, false, true); } #line 8508 "MachineIndependent/glslang_tab.cpp" break; case 356: /* type_specifier_nonarray: F16SAMPLER2DSHADOW */ #line 2550 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd2D, false, true); } #line 8519 "MachineIndependent/glslang_tab.cpp" break; case 357: /* type_specifier_nonarray: F16SAMPLERCUBESHADOW */ #line 2556 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, EsdCube, false, true); } #line 8530 "MachineIndependent/glslang_tab.cpp" break; case 358: /* type_specifier_nonarray: F16SAMPLER1DARRAY */ #line 2562 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd1D, true); } #line 8541 "MachineIndependent/glslang_tab.cpp" break; case 359: /* type_specifier_nonarray: F16SAMPLER2DARRAY */ #line 2568 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd2D, true); } #line 8552 "MachineIndependent/glslang_tab.cpp" break; case 360: /* type_specifier_nonarray: F16SAMPLER1DARRAYSHADOW */ #line 2574 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd1D, true, true); } #line 8563 "MachineIndependent/glslang_tab.cpp" break; case 361: /* type_specifier_nonarray: F16SAMPLER2DARRAYSHADOW */ #line 2580 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd2D, true, true); } #line 8574 "MachineIndependent/glslang_tab.cpp" break; case 362: /* type_specifier_nonarray: F16SAMPLERCUBEARRAY */ #line 2586 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, EsdCube, true); } #line 8585 "MachineIndependent/glslang_tab.cpp" break; case 363: /* type_specifier_nonarray: F16SAMPLERCUBEARRAYSHADOW */ #line 2592 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, EsdCube, true, true); } #line 8596 "MachineIndependent/glslang_tab.cpp" break; case 364: /* type_specifier_nonarray: ISAMPLER1D */ #line 2598 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, Esd1D); } #line 8606 "MachineIndependent/glslang_tab.cpp" break; case 365: /* type_specifier_nonarray: ISAMPLER2D */ #line 2604 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, Esd2D); } #line 8616 "MachineIndependent/glslang_tab.cpp" break; case 366: /* type_specifier_nonarray: ISAMPLER3D */ #line 2609 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, Esd3D); } #line 8626 "MachineIndependent/glslang_tab.cpp" break; case 367: /* type_specifier_nonarray: ISAMPLERCUBE */ #line 2614 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, EsdCube); } #line 8636 "MachineIndependent/glslang_tab.cpp" break; case 368: /* type_specifier_nonarray: ISAMPLER2DARRAY */ #line 2619 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, Esd2D, true); } #line 8646 "MachineIndependent/glslang_tab.cpp" break; case 369: /* type_specifier_nonarray: USAMPLER2D */ #line 2624 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, Esd2D); } #line 8656 "MachineIndependent/glslang_tab.cpp" break; case 370: /* type_specifier_nonarray: USAMPLER3D */ #line 2629 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, Esd3D); } #line 8666 "MachineIndependent/glslang_tab.cpp" break; case 371: /* type_specifier_nonarray: USAMPLERCUBE */ #line 2634 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, EsdCube); } #line 8676 "MachineIndependent/glslang_tab.cpp" break; case 372: /* type_specifier_nonarray: ISAMPLER1DARRAY */ #line 2640 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, Esd1D, true); } #line 8686 "MachineIndependent/glslang_tab.cpp" break; case 373: /* type_specifier_nonarray: ISAMPLERCUBEARRAY */ #line 2645 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, EsdCube, true); } #line 8696 "MachineIndependent/glslang_tab.cpp" break; case 374: /* type_specifier_nonarray: USAMPLER1D */ #line 2650 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, Esd1D); } #line 8706 "MachineIndependent/glslang_tab.cpp" break; case 375: /* type_specifier_nonarray: USAMPLER1DARRAY */ #line 2655 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, Esd1D, true); } #line 8716 "MachineIndependent/glslang_tab.cpp" break; case 376: /* type_specifier_nonarray: USAMPLERCUBEARRAY */ #line 2660 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, EsdCube, true); } #line 8726 "MachineIndependent/glslang_tab.cpp" break; case 377: /* type_specifier_nonarray: TEXTURECUBEARRAY */ #line 2665 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, EsdCube, true); } #line 8736 "MachineIndependent/glslang_tab.cpp" break; case 378: /* type_specifier_nonarray: ITEXTURECUBEARRAY */ #line 2670 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, EsdCube, true); } #line 8746 "MachineIndependent/glslang_tab.cpp" break; case 379: /* type_specifier_nonarray: UTEXTURECUBEARRAY */ #line 2675 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, EsdCube, true); } #line 8756 "MachineIndependent/glslang_tab.cpp" break; case 380: /* type_specifier_nonarray: USAMPLER2DARRAY */ #line 2681 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, Esd2D, true); } #line 8766 "MachineIndependent/glslang_tab.cpp" break; case 381: /* type_specifier_nonarray: TEXTURE2D */ #line 2686 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, Esd2D); } #line 8776 "MachineIndependent/glslang_tab.cpp" break; case 382: /* type_specifier_nonarray: TEXTURE3D */ #line 2691 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, Esd3D); } #line 8786 "MachineIndependent/glslang_tab.cpp" break; case 383: /* type_specifier_nonarray: TEXTURE2DARRAY */ #line 2696 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, Esd2D, true); } #line 8796 "MachineIndependent/glslang_tab.cpp" break; case 384: /* type_specifier_nonarray: TEXTURECUBE */ #line 2701 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, EsdCube); } #line 8806 "MachineIndependent/glslang_tab.cpp" break; case 385: /* type_specifier_nonarray: ITEXTURE2D */ #line 2706 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, Esd2D); } #line 8816 "MachineIndependent/glslang_tab.cpp" break; case 386: /* type_specifier_nonarray: ITEXTURE3D */ #line 2711 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, Esd3D); } #line 8826 "MachineIndependent/glslang_tab.cpp" break; case 387: /* type_specifier_nonarray: ITEXTURECUBE */ #line 2716 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, EsdCube); } #line 8836 "MachineIndependent/glslang_tab.cpp" break; case 388: /* type_specifier_nonarray: ITEXTURE2DARRAY */ #line 2721 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, Esd2D, true); } #line 8846 "MachineIndependent/glslang_tab.cpp" break; case 389: /* type_specifier_nonarray: UTEXTURE2D */ #line 2726 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, Esd2D); } #line 8856 "MachineIndependent/glslang_tab.cpp" break; case 390: /* type_specifier_nonarray: UTEXTURE3D */ #line 2731 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, Esd3D); } #line 8866 "MachineIndependent/glslang_tab.cpp" break; case 391: /* type_specifier_nonarray: UTEXTURECUBE */ #line 2736 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, EsdCube); } #line 8876 "MachineIndependent/glslang_tab.cpp" break; case 392: /* type_specifier_nonarray: UTEXTURE2DARRAY */ #line 2741 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, Esd2D, true); } #line 8886 "MachineIndependent/glslang_tab.cpp" break; case 393: /* type_specifier_nonarray: SAMPLER */ #line 2746 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setPureSampler(false); } #line 8896 "MachineIndependent/glslang_tab.cpp" break; case 394: /* type_specifier_nonarray: SAMPLERSHADOW */ #line 2751 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setPureSampler(true); } #line 8906 "MachineIndependent/glslang_tab.cpp" break; case 395: /* type_specifier_nonarray: SAMPLER2DRECT */ #line 2757 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, EsdRect); } #line 8916 "MachineIndependent/glslang_tab.cpp" break; case 396: /* type_specifier_nonarray: SAMPLER2DRECTSHADOW */ #line 2762 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, EsdRect, false, true); } #line 8926 "MachineIndependent/glslang_tab.cpp" break; case 397: /* type_specifier_nonarray: F16SAMPLER2DRECT */ #line 2767 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, EsdRect); } #line 8937 "MachineIndependent/glslang_tab.cpp" break; case 398: /* type_specifier_nonarray: F16SAMPLER2DRECTSHADOW */ #line 2773 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, EsdRect, false, true); } #line 8948 "MachineIndependent/glslang_tab.cpp" break; case 399: /* type_specifier_nonarray: ISAMPLER2DRECT */ #line 2779 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, EsdRect); } #line 8958 "MachineIndependent/glslang_tab.cpp" break; case 400: /* type_specifier_nonarray: USAMPLER2DRECT */ #line 2784 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, EsdRect); } #line 8968 "MachineIndependent/glslang_tab.cpp" break; case 401: /* type_specifier_nonarray: SAMPLERBUFFER */ #line 2789 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, EsdBuffer); } #line 8978 "MachineIndependent/glslang_tab.cpp" break; case 402: /* type_specifier_nonarray: F16SAMPLERBUFFER */ #line 2794 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, EsdBuffer); } #line 8989 "MachineIndependent/glslang_tab.cpp" break; case 403: /* type_specifier_nonarray: ISAMPLERBUFFER */ #line 2800 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, EsdBuffer); } #line 8999 "MachineIndependent/glslang_tab.cpp" break; case 404: /* type_specifier_nonarray: USAMPLERBUFFER */ #line 2805 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, EsdBuffer); } #line 9009 "MachineIndependent/glslang_tab.cpp" break; case 405: /* type_specifier_nonarray: SAMPLER2DMS */ #line 2810 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd2D, false, false, true); } #line 9019 "MachineIndependent/glslang_tab.cpp" break; case 406: /* type_specifier_nonarray: F16SAMPLER2DMS */ #line 2815 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd2D, false, false, true); } #line 9030 "MachineIndependent/glslang_tab.cpp" break; case 407: /* type_specifier_nonarray: ISAMPLER2DMS */ #line 2821 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, Esd2D, false, false, true); } #line 9040 "MachineIndependent/glslang_tab.cpp" break; case 408: /* type_specifier_nonarray: USAMPLER2DMS */ #line 2826 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, Esd2D, false, false, true); } #line 9050 "MachineIndependent/glslang_tab.cpp" break; case 409: /* type_specifier_nonarray: SAMPLER2DMSARRAY */ #line 2831 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd2D, true, false, true); } #line 9060 "MachineIndependent/glslang_tab.cpp" break; case 410: /* type_specifier_nonarray: F16SAMPLER2DMSARRAY */ #line 2836 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float sampler", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat16, Esd2D, true, false, true); } #line 9071 "MachineIndependent/glslang_tab.cpp" break; case 411: /* type_specifier_nonarray: ISAMPLER2DMSARRAY */ #line 2842 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtInt, Esd2D, true, false, true); } #line 9081 "MachineIndependent/glslang_tab.cpp" break; case 412: /* type_specifier_nonarray: USAMPLER2DMSARRAY */ #line 2847 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtUint, Esd2D, true, false, true); } #line 9091 "MachineIndependent/glslang_tab.cpp" break; case 413: /* type_specifier_nonarray: TEXTURE1D */ #line 2852 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, Esd1D); } #line 9101 "MachineIndependent/glslang_tab.cpp" break; case 414: /* type_specifier_nonarray: F16TEXTURE1D */ #line 2857 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, Esd1D); } #line 9112 "MachineIndependent/glslang_tab.cpp" break; case 415: /* type_specifier_nonarray: F16TEXTURE2D */ #line 2863 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, Esd2D); } #line 9123 "MachineIndependent/glslang_tab.cpp" break; case 416: /* type_specifier_nonarray: F16TEXTURE3D */ #line 2869 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, Esd3D); } #line 9134 "MachineIndependent/glslang_tab.cpp" break; case 417: /* type_specifier_nonarray: F16TEXTURECUBE */ #line 2875 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, EsdCube); } #line 9145 "MachineIndependent/glslang_tab.cpp" break; case 418: /* type_specifier_nonarray: TEXTURE1DARRAY */ #line 2881 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, Esd1D, true); } #line 9155 "MachineIndependent/glslang_tab.cpp" break; case 419: /* type_specifier_nonarray: F16TEXTURE1DARRAY */ #line 2886 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, Esd1D, true); } #line 9166 "MachineIndependent/glslang_tab.cpp" break; case 420: /* type_specifier_nonarray: F16TEXTURE2DARRAY */ #line 2892 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, Esd2D, true); } #line 9177 "MachineIndependent/glslang_tab.cpp" break; case 421: /* type_specifier_nonarray: F16TEXTURECUBEARRAY */ #line 2898 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, EsdCube, true); } #line 9188 "MachineIndependent/glslang_tab.cpp" break; case 422: /* type_specifier_nonarray: ITEXTURE1D */ #line 2904 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, Esd1D); } #line 9198 "MachineIndependent/glslang_tab.cpp" break; case 423: /* type_specifier_nonarray: ITEXTURE1DARRAY */ #line 2909 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, Esd1D, true); } #line 9208 "MachineIndependent/glslang_tab.cpp" break; case 424: /* type_specifier_nonarray: UTEXTURE1D */ #line 2914 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, Esd1D); } #line 9218 "MachineIndependent/glslang_tab.cpp" break; case 425: /* type_specifier_nonarray: UTEXTURE1DARRAY */ #line 2919 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, Esd1D, true); } #line 9228 "MachineIndependent/glslang_tab.cpp" break; case 426: /* type_specifier_nonarray: TEXTURE2DRECT */ #line 2924 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, EsdRect); } #line 9238 "MachineIndependent/glslang_tab.cpp" break; case 427: /* type_specifier_nonarray: F16TEXTURE2DRECT */ #line 2929 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, EsdRect); } #line 9249 "MachineIndependent/glslang_tab.cpp" break; case 428: /* type_specifier_nonarray: ITEXTURE2DRECT */ #line 2935 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, EsdRect); } #line 9259 "MachineIndependent/glslang_tab.cpp" break; case 429: /* type_specifier_nonarray: UTEXTURE2DRECT */ #line 2940 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, EsdRect); } #line 9269 "MachineIndependent/glslang_tab.cpp" break; case 430: /* type_specifier_nonarray: TEXTUREBUFFER */ #line 2945 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, EsdBuffer); } #line 9279 "MachineIndependent/glslang_tab.cpp" break; case 431: /* type_specifier_nonarray: F16TEXTUREBUFFER */ #line 2950 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, EsdBuffer); } #line 9290 "MachineIndependent/glslang_tab.cpp" break; case 432: /* type_specifier_nonarray: ITEXTUREBUFFER */ #line 2956 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, EsdBuffer); } #line 9300 "MachineIndependent/glslang_tab.cpp" break; case 433: /* type_specifier_nonarray: UTEXTUREBUFFER */ #line 2961 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, EsdBuffer); } #line 9310 "MachineIndependent/glslang_tab.cpp" break; case 434: /* type_specifier_nonarray: TEXTURE2DMS */ #line 2966 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, Esd2D, false, false, true); } #line 9320 "MachineIndependent/glslang_tab.cpp" break; case 435: /* type_specifier_nonarray: F16TEXTURE2DMS */ #line 2971 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, Esd2D, false, false, true); } #line 9331 "MachineIndependent/glslang_tab.cpp" break; case 436: /* type_specifier_nonarray: ITEXTURE2DMS */ #line 2977 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, Esd2D, false, false, true); } #line 9341 "MachineIndependent/glslang_tab.cpp" break; case 437: /* type_specifier_nonarray: UTEXTURE2DMS */ #line 2982 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, Esd2D, false, false, true); } #line 9351 "MachineIndependent/glslang_tab.cpp" break; case 438: /* type_specifier_nonarray: TEXTURE2DMSARRAY */ #line 2987 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat, Esd2D, true, false, true); } #line 9361 "MachineIndependent/glslang_tab.cpp" break; case 439: /* type_specifier_nonarray: F16TEXTURE2DMSARRAY */ #line 2992 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float texture", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtFloat16, Esd2D, true, false, true); } #line 9372 "MachineIndependent/glslang_tab.cpp" break; case 440: /* type_specifier_nonarray: ITEXTURE2DMSARRAY */ #line 2998 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtInt, Esd2D, true, false, true); } #line 9382 "MachineIndependent/glslang_tab.cpp" break; case 441: /* type_specifier_nonarray: UTEXTURE2DMSARRAY */ #line 3003 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setTexture(EbtUint, Esd2D, true, false, true); } #line 9392 "MachineIndependent/glslang_tab.cpp" break; case 442: /* type_specifier_nonarray: IMAGE1D */ #line 3008 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, Esd1D); } #line 9402 "MachineIndependent/glslang_tab.cpp" break; case 443: /* type_specifier_nonarray: F16IMAGE1D */ #line 3013 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, Esd1D); } #line 9413 "MachineIndependent/glslang_tab.cpp" break; case 444: /* type_specifier_nonarray: IIMAGE1D */ #line 3019 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, Esd1D); } #line 9423 "MachineIndependent/glslang_tab.cpp" break; case 445: /* type_specifier_nonarray: UIMAGE1D */ #line 3024 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, Esd1D); } #line 9433 "MachineIndependent/glslang_tab.cpp" break; case 446: /* type_specifier_nonarray: IMAGE2D */ #line 3029 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, Esd2D); } #line 9443 "MachineIndependent/glslang_tab.cpp" break; case 447: /* type_specifier_nonarray: F16IMAGE2D */ #line 3034 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, Esd2D); } #line 9454 "MachineIndependent/glslang_tab.cpp" break; case 448: /* type_specifier_nonarray: IIMAGE2D */ #line 3040 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, Esd2D); } #line 9464 "MachineIndependent/glslang_tab.cpp" break; case 449: /* type_specifier_nonarray: UIMAGE2D */ #line 3045 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, Esd2D); } #line 9474 "MachineIndependent/glslang_tab.cpp" break; case 450: /* type_specifier_nonarray: IMAGE3D */ #line 3050 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, Esd3D); } #line 9484 "MachineIndependent/glslang_tab.cpp" break; case 451: /* type_specifier_nonarray: F16IMAGE3D */ #line 3055 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, Esd3D); } #line 9495 "MachineIndependent/glslang_tab.cpp" break; case 452: /* type_specifier_nonarray: IIMAGE3D */ #line 3061 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, Esd3D); } #line 9505 "MachineIndependent/glslang_tab.cpp" break; case 453: /* type_specifier_nonarray: UIMAGE3D */ #line 3066 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, Esd3D); } #line 9515 "MachineIndependent/glslang_tab.cpp" break; case 454: /* type_specifier_nonarray: IMAGE2DRECT */ #line 3071 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, EsdRect); } #line 9525 "MachineIndependent/glslang_tab.cpp" break; case 455: /* type_specifier_nonarray: F16IMAGE2DRECT */ #line 3076 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, EsdRect); } #line 9536 "MachineIndependent/glslang_tab.cpp" break; case 456: /* type_specifier_nonarray: IIMAGE2DRECT */ #line 3082 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, EsdRect); } #line 9546 "MachineIndependent/glslang_tab.cpp" break; case 457: /* type_specifier_nonarray: UIMAGE2DRECT */ #line 3087 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, EsdRect); } #line 9556 "MachineIndependent/glslang_tab.cpp" break; case 458: /* type_specifier_nonarray: IMAGECUBE */ #line 3092 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, EsdCube); } #line 9566 "MachineIndependent/glslang_tab.cpp" break; case 459: /* type_specifier_nonarray: F16IMAGECUBE */ #line 3097 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, EsdCube); } #line 9577 "MachineIndependent/glslang_tab.cpp" break; case 460: /* type_specifier_nonarray: IIMAGECUBE */ #line 3103 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, EsdCube); } #line 9587 "MachineIndependent/glslang_tab.cpp" break; case 461: /* type_specifier_nonarray: UIMAGECUBE */ #line 3108 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, EsdCube); } #line 9597 "MachineIndependent/glslang_tab.cpp" break; case 462: /* type_specifier_nonarray: IMAGEBUFFER */ #line 3113 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, EsdBuffer); } #line 9607 "MachineIndependent/glslang_tab.cpp" break; case 463: /* type_specifier_nonarray: F16IMAGEBUFFER */ #line 3118 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, EsdBuffer); } #line 9618 "MachineIndependent/glslang_tab.cpp" break; case 464: /* type_specifier_nonarray: IIMAGEBUFFER */ #line 3124 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, EsdBuffer); } #line 9628 "MachineIndependent/glslang_tab.cpp" break; case 465: /* type_specifier_nonarray: UIMAGEBUFFER */ #line 3129 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, EsdBuffer); } #line 9638 "MachineIndependent/glslang_tab.cpp" break; case 466: /* type_specifier_nonarray: IMAGE1DARRAY */ #line 3134 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, Esd1D, true); } #line 9648 "MachineIndependent/glslang_tab.cpp" break; case 467: /* type_specifier_nonarray: F16IMAGE1DARRAY */ #line 3139 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, Esd1D, true); } #line 9659 "MachineIndependent/glslang_tab.cpp" break; case 468: /* type_specifier_nonarray: IIMAGE1DARRAY */ #line 3145 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, Esd1D, true); } #line 9669 "MachineIndependent/glslang_tab.cpp" break; case 469: /* type_specifier_nonarray: UIMAGE1DARRAY */ #line 3150 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, Esd1D, true); } #line 9679 "MachineIndependent/glslang_tab.cpp" break; case 470: /* type_specifier_nonarray: IMAGE2DARRAY */ #line 3155 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, Esd2D, true); } #line 9689 "MachineIndependent/glslang_tab.cpp" break; case 471: /* type_specifier_nonarray: F16IMAGE2DARRAY */ #line 3160 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, Esd2D, true); } #line 9700 "MachineIndependent/glslang_tab.cpp" break; case 472: /* type_specifier_nonarray: IIMAGE2DARRAY */ #line 3166 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, Esd2D, true); } #line 9710 "MachineIndependent/glslang_tab.cpp" break; case 473: /* type_specifier_nonarray: UIMAGE2DARRAY */ #line 3171 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, Esd2D, true); } #line 9720 "MachineIndependent/glslang_tab.cpp" break; case 474: /* type_specifier_nonarray: IMAGECUBEARRAY */ #line 3176 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, EsdCube, true); } #line 9730 "MachineIndependent/glslang_tab.cpp" break; case 475: /* type_specifier_nonarray: F16IMAGECUBEARRAY */ #line 3181 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, EsdCube, true); } #line 9741 "MachineIndependent/glslang_tab.cpp" break; case 476: /* type_specifier_nonarray: IIMAGECUBEARRAY */ #line 3187 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, EsdCube, true); } #line 9751 "MachineIndependent/glslang_tab.cpp" break; case 477: /* type_specifier_nonarray: UIMAGECUBEARRAY */ #line 3192 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, EsdCube, true); } #line 9761 "MachineIndependent/glslang_tab.cpp" break; case 478: /* type_specifier_nonarray: IMAGE2DMS */ #line 3197 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, Esd2D, false, false, true); } #line 9771 "MachineIndependent/glslang_tab.cpp" break; case 479: /* type_specifier_nonarray: F16IMAGE2DMS */ #line 3202 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, Esd2D, false, false, true); } #line 9782 "MachineIndependent/glslang_tab.cpp" break; case 480: /* type_specifier_nonarray: IIMAGE2DMS */ #line 3208 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, Esd2D, false, false, true); } #line 9792 "MachineIndependent/glslang_tab.cpp" break; case 481: /* type_specifier_nonarray: UIMAGE2DMS */ #line 3213 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, Esd2D, false, false, true); } #line 9802 "MachineIndependent/glslang_tab.cpp" break; case 482: /* type_specifier_nonarray: IMAGE2DMSARRAY */ #line 3218 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat, Esd2D, true, false, true); } #line 9812 "MachineIndependent/glslang_tab.cpp" break; case 483: /* type_specifier_nonarray: F16IMAGE2DMSARRAY */ #line 3223 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float image", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtFloat16, Esd2D, true, false, true); } #line 9823 "MachineIndependent/glslang_tab.cpp" break; case 484: /* type_specifier_nonarray: IIMAGE2DMSARRAY */ #line 3229 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt, Esd2D, true, false, true); } #line 9833 "MachineIndependent/glslang_tab.cpp" break; case 485: /* type_specifier_nonarray: UIMAGE2DMSARRAY */ #line 3234 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint, Esd2D, true, false, true); } #line 9843 "MachineIndependent/glslang_tab.cpp" break; case 486: /* type_specifier_nonarray: I64IMAGE1D */ #line 3239 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, Esd1D); } #line 9853 "MachineIndependent/glslang_tab.cpp" break; case 487: /* type_specifier_nonarray: U64IMAGE1D */ #line 3244 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, Esd1D); } #line 9863 "MachineIndependent/glslang_tab.cpp" break; case 488: /* type_specifier_nonarray: I64IMAGE2D */ #line 3249 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, Esd2D); } #line 9873 "MachineIndependent/glslang_tab.cpp" break; case 489: /* type_specifier_nonarray: U64IMAGE2D */ #line 3254 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, Esd2D); } #line 9883 "MachineIndependent/glslang_tab.cpp" break; case 490: /* type_specifier_nonarray: I64IMAGE3D */ #line 3259 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, Esd3D); } #line 9893 "MachineIndependent/glslang_tab.cpp" break; case 491: /* type_specifier_nonarray: U64IMAGE3D */ #line 3264 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, Esd3D); } #line 9903 "MachineIndependent/glslang_tab.cpp" break; case 492: /* type_specifier_nonarray: I64IMAGE2DRECT */ #line 3269 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, EsdRect); } #line 9913 "MachineIndependent/glslang_tab.cpp" break; case 493: /* type_specifier_nonarray: U64IMAGE2DRECT */ #line 3274 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, EsdRect); } #line 9923 "MachineIndependent/glslang_tab.cpp" break; case 494: /* type_specifier_nonarray: I64IMAGECUBE */ #line 3279 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, EsdCube); } #line 9933 "MachineIndependent/glslang_tab.cpp" break; case 495: /* type_specifier_nonarray: U64IMAGECUBE */ #line 3284 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, EsdCube); } #line 9943 "MachineIndependent/glslang_tab.cpp" break; case 496: /* type_specifier_nonarray: I64IMAGEBUFFER */ #line 3289 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, EsdBuffer); } #line 9953 "MachineIndependent/glslang_tab.cpp" break; case 497: /* type_specifier_nonarray: U64IMAGEBUFFER */ #line 3294 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, EsdBuffer); } #line 9963 "MachineIndependent/glslang_tab.cpp" break; case 498: /* type_specifier_nonarray: I64IMAGE1DARRAY */ #line 3299 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, Esd1D, true); } #line 9973 "MachineIndependent/glslang_tab.cpp" break; case 499: /* type_specifier_nonarray: U64IMAGE1DARRAY */ #line 3304 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, Esd1D, true); } #line 9983 "MachineIndependent/glslang_tab.cpp" break; case 500: /* type_specifier_nonarray: I64IMAGE2DARRAY */ #line 3309 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, Esd2D, true); } #line 9993 "MachineIndependent/glslang_tab.cpp" break; case 501: /* type_specifier_nonarray: U64IMAGE2DARRAY */ #line 3314 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, Esd2D, true); } #line 10003 "MachineIndependent/glslang_tab.cpp" break; case 502: /* type_specifier_nonarray: I64IMAGECUBEARRAY */ #line 3319 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, EsdCube, true); } #line 10013 "MachineIndependent/glslang_tab.cpp" break; case 503: /* type_specifier_nonarray: U64IMAGECUBEARRAY */ #line 3324 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, EsdCube, true); } #line 10023 "MachineIndependent/glslang_tab.cpp" break; case 504: /* type_specifier_nonarray: I64IMAGE2DMS */ #line 3329 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, Esd2D, false, false, true); } #line 10033 "MachineIndependent/glslang_tab.cpp" break; case 505: /* type_specifier_nonarray: U64IMAGE2DMS */ #line 3334 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, Esd2D, false, false, true); } #line 10043 "MachineIndependent/glslang_tab.cpp" break; case 506: /* type_specifier_nonarray: I64IMAGE2DMSARRAY */ #line 3339 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtInt64, Esd2D, true, false, true); } #line 10053 "MachineIndependent/glslang_tab.cpp" break; case 507: /* type_specifier_nonarray: U64IMAGE2DMSARRAY */ #line 3344 "MachineIndependent/glslang.y" { (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setImage(EbtUint64, Esd2D, true, false, true); } #line 10063 "MachineIndependent/glslang_tab.cpp" break; case 508: /* type_specifier_nonarray: SAMPLEREXTERNALOES */ #line 3349 "MachineIndependent/glslang.y" { // GL_OES_EGL_image_external (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd2D); (yyval.interm.type).sampler.external = true; } #line 10074 "MachineIndependent/glslang_tab.cpp" break; case 509: /* type_specifier_nonarray: SAMPLEREXTERNAL2DY2YEXT */ #line 3355 "MachineIndependent/glslang.y" { // GL_EXT_YUV_target (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.set(EbtFloat, Esd2D); (yyval.interm.type).sampler.yuv = true; } #line 10085 "MachineIndependent/glslang_tab.cpp" break; case 510: /* type_specifier_nonarray: SUBPASSINPUT */ #line 3361 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[0].lex).loc, EShLangFragment, "subpass input"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setSubpass(EbtFloat); } #line 10096 "MachineIndependent/glslang_tab.cpp" break; case 511: /* type_specifier_nonarray: SUBPASSINPUTMS */ #line 3367 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[0].lex).loc, EShLangFragment, "subpass input"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setSubpass(EbtFloat, true); } #line 10107 "MachineIndependent/glslang_tab.cpp" break; case 512: /* type_specifier_nonarray: F16SUBPASSINPUT */ #line 3373 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float subpass input", parseContext.symbolTable.atBuiltInLevel()); parseContext.requireStage((yyvsp[0].lex).loc, EShLangFragment, "subpass input"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setSubpass(EbtFloat16); } #line 10119 "MachineIndependent/glslang_tab.cpp" break; case 513: /* type_specifier_nonarray: F16SUBPASSINPUTMS */ #line 3380 "MachineIndependent/glslang.y" { parseContext.float16OpaqueCheck((yyvsp[0].lex).loc, "half float subpass input", parseContext.symbolTable.atBuiltInLevel()); parseContext.requireStage((yyvsp[0].lex).loc, EShLangFragment, "subpass input"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setSubpass(EbtFloat16, true); } #line 10131 "MachineIndependent/glslang_tab.cpp" break; case 514: /* type_specifier_nonarray: ISUBPASSINPUT */ #line 3387 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[0].lex).loc, EShLangFragment, "subpass input"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setSubpass(EbtInt); } #line 10142 "MachineIndependent/glslang_tab.cpp" break; case 515: /* type_specifier_nonarray: ISUBPASSINPUTMS */ #line 3393 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[0].lex).loc, EShLangFragment, "subpass input"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setSubpass(EbtInt, true); } #line 10153 "MachineIndependent/glslang_tab.cpp" break; case 516: /* type_specifier_nonarray: USUBPASSINPUT */ #line 3399 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[0].lex).loc, EShLangFragment, "subpass input"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setSubpass(EbtUint); } #line 10164 "MachineIndependent/glslang_tab.cpp" break; case 517: /* type_specifier_nonarray: USUBPASSINPUTMS */ #line 3405 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[0].lex).loc, EShLangFragment, "subpass input"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtSampler; (yyval.interm.type).sampler.setSubpass(EbtUint, true); } #line 10175 "MachineIndependent/glslang_tab.cpp" break; case 518: /* type_specifier_nonarray: FCOOPMATNV */ #line 3411 "MachineIndependent/glslang.y" { parseContext.fcoopmatCheck((yyvsp[0].lex).loc, "fcoopmatNV", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtFloat; (yyval.interm.type).coopmat = true; } #line 10186 "MachineIndependent/glslang_tab.cpp" break; case 519: /* type_specifier_nonarray: ICOOPMATNV */ #line 3417 "MachineIndependent/glslang.y" { parseContext.intcoopmatCheck((yyvsp[0].lex).loc, "icoopmatNV", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtInt; (yyval.interm.type).coopmat = true; } #line 10197 "MachineIndependent/glslang_tab.cpp" break; case 520: /* type_specifier_nonarray: UCOOPMATNV */ #line 3423 "MachineIndependent/glslang.y" { parseContext.intcoopmatCheck((yyvsp[0].lex).loc, "ucoopmatNV", parseContext.symbolTable.atBuiltInLevel()); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtUint; (yyval.interm.type).coopmat = true; } #line 10208 "MachineIndependent/glslang_tab.cpp" break; case 521: /* type_specifier_nonarray: struct_specifier */ #line 3430 "MachineIndependent/glslang.y" { (yyval.interm.type) = (yyvsp[0].interm.type); (yyval.interm.type).qualifier.storage = parseContext.symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; parseContext.structTypeCheck((yyval.interm.type).loc, (yyval.interm.type)); } #line 10218 "MachineIndependent/glslang_tab.cpp" break; case 522: /* type_specifier_nonarray: TYPE_NAME */ #line 3435 "MachineIndependent/glslang.y" { // // This is for user defined type names. The lexical phase looked up the // type. // if (const TVariable* variable = ((yyvsp[0].lex).symbol)->getAsVariable()) { const TType& structure = variable->getType(); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); (yyval.interm.type).basicType = EbtStruct; (yyval.interm.type).userDef = &structure; } else parseContext.error((yyvsp[0].lex).loc, "expected type name", (yyvsp[0].lex).string->c_str(), ""); } #line 10236 "MachineIndependent/glslang_tab.cpp" break; case 523: /* precision_qualifier: HIGH_PRECISION */ #line 3451 "MachineIndependent/glslang.y" { parseContext.profileRequires((yyvsp[0].lex).loc, ENoProfile, 130, 0, "highp precision qualifier"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); parseContext.handlePrecisionQualifier((yyvsp[0].lex).loc, (yyval.interm.type).qualifier, EpqHigh); } #line 10246 "MachineIndependent/glslang_tab.cpp" break; case 524: /* precision_qualifier: MEDIUM_PRECISION */ #line 3456 "MachineIndependent/glslang.y" { parseContext.profileRequires((yyvsp[0].lex).loc, ENoProfile, 130, 0, "mediump precision qualifier"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); parseContext.handlePrecisionQualifier((yyvsp[0].lex).loc, (yyval.interm.type).qualifier, EpqMedium); } #line 10256 "MachineIndependent/glslang_tab.cpp" break; case 525: /* precision_qualifier: LOW_PRECISION */ #line 3461 "MachineIndependent/glslang.y" { parseContext.profileRequires((yyvsp[0].lex).loc, ENoProfile, 130, 0, "lowp precision qualifier"); (yyval.interm.type).init((yyvsp[0].lex).loc, parseContext.symbolTable.atGlobalLevel()); parseContext.handlePrecisionQualifier((yyvsp[0].lex).loc, (yyval.interm.type).qualifier, EpqLow); } #line 10266 "MachineIndependent/glslang_tab.cpp" break; case 526: /* $@3: %empty */ #line 3469 "MachineIndependent/glslang.y" { parseContext.nestedStructCheck((yyvsp[-2].lex).loc); } #line 10272 "MachineIndependent/glslang_tab.cpp" break; case 527: /* struct_specifier: STRUCT IDENTIFIER LEFT_BRACE $@3 struct_declaration_list RIGHT_BRACE */ #line 3469 "MachineIndependent/glslang.y" { TType* structure = new TType((yyvsp[-1].interm.typeList), *(yyvsp[-4].lex).string); parseContext.structArrayCheck((yyvsp[-4].lex).loc, *structure); TVariable* userTypeDef = new TVariable((yyvsp[-4].lex).string, *structure, true); if (! parseContext.symbolTable.insert(*userTypeDef)) parseContext.error((yyvsp[-4].lex).loc, "redefinition", (yyvsp[-4].lex).string->c_str(), "struct"); (yyval.interm.type).init((yyvsp[-5].lex).loc); (yyval.interm.type).basicType = EbtStruct; (yyval.interm.type).userDef = structure; --parseContext.structNestingLevel; } #line 10288 "MachineIndependent/glslang_tab.cpp" break; case 528: /* $@4: %empty */ #line 3480 "MachineIndependent/glslang.y" { parseContext.nestedStructCheck((yyvsp[-1].lex).loc); } #line 10294 "MachineIndependent/glslang_tab.cpp" break; case 529: /* struct_specifier: STRUCT LEFT_BRACE $@4 struct_declaration_list RIGHT_BRACE */ #line 3480 "MachineIndependent/glslang.y" { TType* structure = new TType((yyvsp[-1].interm.typeList), TString("")); (yyval.interm.type).init((yyvsp[-4].lex).loc); (yyval.interm.type).basicType = EbtStruct; (yyval.interm.type).userDef = structure; --parseContext.structNestingLevel; } #line 10306 "MachineIndependent/glslang_tab.cpp" break; case 530: /* struct_declaration_list: struct_declaration */ #line 3490 "MachineIndependent/glslang.y" { (yyval.interm.typeList) = (yyvsp[0].interm.typeList); } #line 10314 "MachineIndependent/glslang_tab.cpp" break; case 531: /* struct_declaration_list: struct_declaration_list struct_declaration */ #line 3493 "MachineIndependent/glslang.y" { (yyval.interm.typeList) = (yyvsp[-1].interm.typeList); for (unsigned int i = 0; i < (yyvsp[0].interm.typeList)->size(); ++i) { for (unsigned int j = 0; j < (yyval.interm.typeList)->size(); ++j) { if ((*(yyval.interm.typeList))[j].type->getFieldName() == (*(yyvsp[0].interm.typeList))[i].type->getFieldName()) parseContext.error((*(yyvsp[0].interm.typeList))[i].loc, "duplicate member name:", "", (*(yyvsp[0].interm.typeList))[i].type->getFieldName().c_str()); } (yyval.interm.typeList)->push_back((*(yyvsp[0].interm.typeList))[i]); } } #line 10329 "MachineIndependent/glslang_tab.cpp" break; case 532: /* struct_declaration: type_specifier struct_declarator_list SEMICOLON */ #line 3506 "MachineIndependent/glslang.y" { if ((yyvsp[-2].interm.type).arraySizes) { parseContext.profileRequires((yyvsp[-2].interm.type).loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed type"); parseContext.profileRequires((yyvsp[-2].interm.type).loc, EEsProfile, 300, 0, "arrayed type"); if (parseContext.isEsProfile()) parseContext.arraySizeRequiredCheck((yyvsp[-2].interm.type).loc, *(yyvsp[-2].interm.type).arraySizes); } (yyval.interm.typeList) = (yyvsp[-1].interm.typeList); parseContext.voidErrorCheck((yyvsp[-2].interm.type).loc, (*(yyvsp[-1].interm.typeList))[0].type->getFieldName(), (yyvsp[-2].interm.type).basicType); parseContext.precisionQualifierCheck((yyvsp[-2].interm.type).loc, (yyvsp[-2].interm.type).basicType, (yyvsp[-2].interm.type).qualifier); for (unsigned int i = 0; i < (yyval.interm.typeList)->size(); ++i) { TType type((yyvsp[-2].interm.type)); type.setFieldName((*(yyval.interm.typeList))[i].type->getFieldName()); type.transferArraySizes((*(yyval.interm.typeList))[i].type->getArraySizes()); type.copyArrayInnerSizes((yyvsp[-2].interm.type).arraySizes); parseContext.arrayOfArrayVersionCheck((*(yyval.interm.typeList))[i].loc, type.getArraySizes()); (*(yyval.interm.typeList))[i].type->shallowCopy(type); } } #line 10356 "MachineIndependent/glslang_tab.cpp" break; case 533: /* struct_declaration: type_qualifier type_specifier struct_declarator_list SEMICOLON */ #line 3528 "MachineIndependent/glslang.y" { if ((yyvsp[-2].interm.type).arraySizes) { parseContext.profileRequires((yyvsp[-2].interm.type).loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed type"); parseContext.profileRequires((yyvsp[-2].interm.type).loc, EEsProfile, 300, 0, "arrayed type"); if (parseContext.isEsProfile()) parseContext.arraySizeRequiredCheck((yyvsp[-2].interm.type).loc, *(yyvsp[-2].interm.type).arraySizes); } (yyval.interm.typeList) = (yyvsp[-1].interm.typeList); parseContext.memberQualifierCheck((yyvsp[-3].interm.type)); parseContext.voidErrorCheck((yyvsp[-2].interm.type).loc, (*(yyvsp[-1].interm.typeList))[0].type->getFieldName(), (yyvsp[-2].interm.type).basicType); parseContext.mergeQualifiers((yyvsp[-2].interm.type).loc, (yyvsp[-2].interm.type).qualifier, (yyvsp[-3].interm.type).qualifier, true); parseContext.precisionQualifierCheck((yyvsp[-2].interm.type).loc, (yyvsp[-2].interm.type).basicType, (yyvsp[-2].interm.type).qualifier); for (unsigned int i = 0; i < (yyval.interm.typeList)->size(); ++i) { TType type((yyvsp[-2].interm.type)); type.setFieldName((*(yyval.interm.typeList))[i].type->getFieldName()); type.transferArraySizes((*(yyval.interm.typeList))[i].type->getArraySizes()); type.copyArrayInnerSizes((yyvsp[-2].interm.type).arraySizes); parseContext.arrayOfArrayVersionCheck((*(yyval.interm.typeList))[i].loc, type.getArraySizes()); (*(yyval.interm.typeList))[i].type->shallowCopy(type); } } #line 10385 "MachineIndependent/glslang_tab.cpp" break; case 534: /* struct_declarator_list: struct_declarator */ #line 3555 "MachineIndependent/glslang.y" { (yyval.interm.typeList) = new TTypeList; (yyval.interm.typeList)->push_back((yyvsp[0].interm.typeLine)); } #line 10394 "MachineIndependent/glslang_tab.cpp" break; case 535: /* struct_declarator_list: struct_declarator_list COMMA struct_declarator */ #line 3559 "MachineIndependent/glslang.y" { (yyval.interm.typeList)->push_back((yyvsp[0].interm.typeLine)); } #line 10402 "MachineIndependent/glslang_tab.cpp" break; case 536: /* struct_declarator: IDENTIFIER */ #line 3565 "MachineIndependent/glslang.y" { (yyval.interm.typeLine).type = new TType(EbtVoid); (yyval.interm.typeLine).loc = (yyvsp[0].lex).loc; (yyval.interm.typeLine).type->setFieldName(*(yyvsp[0].lex).string); } #line 10412 "MachineIndependent/glslang_tab.cpp" break; case 537: /* struct_declarator: IDENTIFIER array_specifier */ #line 3570 "MachineIndependent/glslang.y" { parseContext.arrayOfArrayVersionCheck((yyvsp[-1].lex).loc, (yyvsp[0].interm).arraySizes); (yyval.interm.typeLine).type = new TType(EbtVoid); (yyval.interm.typeLine).loc = (yyvsp[-1].lex).loc; (yyval.interm.typeLine).type->setFieldName(*(yyvsp[-1].lex).string); (yyval.interm.typeLine).type->transferArraySizes((yyvsp[0].interm).arraySizes); } #line 10425 "MachineIndependent/glslang_tab.cpp" break; case 538: /* initializer: assignment_expression */ #line 3581 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 10433 "MachineIndependent/glslang_tab.cpp" break; case 539: /* initializer: LEFT_BRACE initializer_list RIGHT_BRACE */ #line 3585 "MachineIndependent/glslang.y" { const char* initFeature = "{ } style initializers"; parseContext.requireProfile((yyvsp[-2].lex).loc, ~EEsProfile, initFeature); parseContext.profileRequires((yyvsp[-2].lex).loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature); (yyval.interm.intermTypedNode) = (yyvsp[-1].interm.intermTypedNode); } #line 10444 "MachineIndependent/glslang_tab.cpp" break; case 540: /* initializer: LEFT_BRACE initializer_list COMMA RIGHT_BRACE */ #line 3591 "MachineIndependent/glslang.y" { const char* initFeature = "{ } style initializers"; parseContext.requireProfile((yyvsp[-3].lex).loc, ~EEsProfile, initFeature); parseContext.profileRequires((yyvsp[-3].lex).loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature); (yyval.interm.intermTypedNode) = (yyvsp[-2].interm.intermTypedNode); } #line 10455 "MachineIndependent/glslang_tab.cpp" break; case 541: /* initializer: LEFT_BRACE RIGHT_BRACE */ #line 3597 "MachineIndependent/glslang.y" { const char* initFeature = "empty { } initializer"; parseContext.profileRequires((yyvsp[-1].lex).loc, EEsProfile, 0, E_GL_EXT_null_initializer, initFeature); parseContext.profileRequires((yyvsp[-1].lex).loc, ~EEsProfile, 0, E_GL_EXT_null_initializer, initFeature); (yyval.interm.intermTypedNode) = parseContext.intermediate.makeAggregate((yyvsp[-1].lex).loc); } #line 10466 "MachineIndependent/glslang_tab.cpp" break; case 542: /* initializer_list: initializer */ #line 3608 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.intermediate.growAggregate(0, (yyvsp[0].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)->getLoc()); } #line 10474 "MachineIndependent/glslang_tab.cpp" break; case 543: /* initializer_list: initializer_list COMMA initializer */ #line 3611 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = parseContext.intermediate.growAggregate((yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.intermTypedNode)); } #line 10482 "MachineIndependent/glslang_tab.cpp" break; case 544: /* declaration_statement: declaration */ #line 3618 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10488 "MachineIndependent/glslang_tab.cpp" break; case 545: /* statement: compound_statement */ #line 3622 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10494 "MachineIndependent/glslang_tab.cpp" break; case 546: /* statement: simple_statement */ #line 3623 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10500 "MachineIndependent/glslang_tab.cpp" break; case 547: /* simple_statement: declaration_statement */ #line 3629 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10506 "MachineIndependent/glslang_tab.cpp" break; case 548: /* simple_statement: expression_statement */ #line 3630 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10512 "MachineIndependent/glslang_tab.cpp" break; case 549: /* simple_statement: selection_statement */ #line 3631 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10518 "MachineIndependent/glslang_tab.cpp" break; case 550: /* simple_statement: switch_statement */ #line 3632 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10524 "MachineIndependent/glslang_tab.cpp" break; case 551: /* simple_statement: case_label */ #line 3633 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10530 "MachineIndependent/glslang_tab.cpp" break; case 552: /* simple_statement: iteration_statement */ #line 3634 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10536 "MachineIndependent/glslang_tab.cpp" break; case 553: /* simple_statement: jump_statement */ #line 3635 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10542 "MachineIndependent/glslang_tab.cpp" break; case 554: /* simple_statement: demote_statement */ #line 3637 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10548 "MachineIndependent/glslang_tab.cpp" break; case 555: /* demote_statement: DEMOTE SEMICOLON */ #line 3643 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[-1].lex).loc, EShLangFragment, "demote"); parseContext.requireExtensions((yyvsp[-1].lex).loc, 1, &E_GL_EXT_demote_to_helper_invocation, "demote"); (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpDemote, (yyvsp[-1].lex).loc); } #line 10558 "MachineIndependent/glslang_tab.cpp" break; case 556: /* compound_statement: LEFT_BRACE RIGHT_BRACE */ #line 3652 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = 0; } #line 10564 "MachineIndependent/glslang_tab.cpp" break; case 557: /* $@5: %empty */ #line 3653 "MachineIndependent/glslang.y" { parseContext.symbolTable.push(); ++parseContext.statementNestingLevel; } #line 10573 "MachineIndependent/glslang_tab.cpp" break; case 558: /* $@6: %empty */ #line 3657 "MachineIndependent/glslang.y" { parseContext.symbolTable.pop(&parseContext.defaultPrecision[0]); --parseContext.statementNestingLevel; } #line 10582 "MachineIndependent/glslang_tab.cpp" break; case 559: /* compound_statement: LEFT_BRACE $@5 statement_list $@6 RIGHT_BRACE */ #line 3661 "MachineIndependent/glslang.y" { if ((yyvsp[-2].interm.intermNode) && (yyvsp[-2].interm.intermNode)->getAsAggregate()) (yyvsp[-2].interm.intermNode)->getAsAggregate()->setOperator(EOpSequence); (yyval.interm.intermNode) = (yyvsp[-2].interm.intermNode); } #line 10592 "MachineIndependent/glslang_tab.cpp" break; case 560: /* statement_no_new_scope: compound_statement_no_new_scope */ #line 3669 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10598 "MachineIndependent/glslang_tab.cpp" break; case 561: /* statement_no_new_scope: simple_statement */ #line 3670 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10604 "MachineIndependent/glslang_tab.cpp" break; case 562: /* $@7: %empty */ #line 3674 "MachineIndependent/glslang.y" { ++parseContext.controlFlowNestingLevel; } #line 10612 "MachineIndependent/glslang_tab.cpp" break; case 563: /* statement_scoped: $@7 compound_statement */ #line 3677 "MachineIndependent/glslang.y" { --parseContext.controlFlowNestingLevel; (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10621 "MachineIndependent/glslang_tab.cpp" break; case 564: /* $@8: %empty */ #line 3681 "MachineIndependent/glslang.y" { parseContext.symbolTable.push(); ++parseContext.statementNestingLevel; ++parseContext.controlFlowNestingLevel; } #line 10631 "MachineIndependent/glslang_tab.cpp" break; case 565: /* statement_scoped: $@8 simple_statement */ #line 3686 "MachineIndependent/glslang.y" { parseContext.symbolTable.pop(&parseContext.defaultPrecision[0]); --parseContext.statementNestingLevel; --parseContext.controlFlowNestingLevel; (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10642 "MachineIndependent/glslang_tab.cpp" break; case 566: /* compound_statement_no_new_scope: LEFT_BRACE RIGHT_BRACE */ #line 3695 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = 0; } #line 10650 "MachineIndependent/glslang_tab.cpp" break; case 567: /* compound_statement_no_new_scope: LEFT_BRACE statement_list RIGHT_BRACE */ #line 3698 "MachineIndependent/glslang.y" { if ((yyvsp[-1].interm.intermNode) && (yyvsp[-1].interm.intermNode)->getAsAggregate()) (yyvsp[-1].interm.intermNode)->getAsAggregate()->setOperator(EOpSequence); (yyval.interm.intermNode) = (yyvsp[-1].interm.intermNode); } #line 10660 "MachineIndependent/glslang_tab.cpp" break; case 568: /* statement_list: statement */ #line 3706 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = parseContext.intermediate.makeAggregate((yyvsp[0].interm.intermNode)); if ((yyvsp[0].interm.intermNode) && (yyvsp[0].interm.intermNode)->getAsBranchNode() && ((yyvsp[0].interm.intermNode)->getAsBranchNode()->getFlowOp() == EOpCase || (yyvsp[0].interm.intermNode)->getAsBranchNode()->getFlowOp() == EOpDefault)) { parseContext.wrapupSwitchSubsequence(0, (yyvsp[0].interm.intermNode)); (yyval.interm.intermNode) = 0; // start a fresh subsequence for what's after this case } } #line 10673 "MachineIndependent/glslang_tab.cpp" break; case 569: /* statement_list: statement_list statement */ #line 3714 "MachineIndependent/glslang.y" { if ((yyvsp[0].interm.intermNode) && (yyvsp[0].interm.intermNode)->getAsBranchNode() && ((yyvsp[0].interm.intermNode)->getAsBranchNode()->getFlowOp() == EOpCase || (yyvsp[0].interm.intermNode)->getAsBranchNode()->getFlowOp() == EOpDefault)) { parseContext.wrapupSwitchSubsequence((yyvsp[-1].interm.intermNode) ? (yyvsp[-1].interm.intermNode)->getAsAggregate() : 0, (yyvsp[0].interm.intermNode)); (yyval.interm.intermNode) = 0; // start a fresh subsequence for what's after this case } else (yyval.interm.intermNode) = parseContext.intermediate.growAggregate((yyvsp[-1].interm.intermNode), (yyvsp[0].interm.intermNode)); } #line 10686 "MachineIndependent/glslang_tab.cpp" break; case 570: /* expression_statement: SEMICOLON */ #line 3725 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = 0; } #line 10692 "MachineIndependent/glslang_tab.cpp" break; case 571: /* expression_statement: expression SEMICOLON */ #line 3726 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = static_cast<TIntermNode*>((yyvsp[-1].interm.intermTypedNode)); } #line 10698 "MachineIndependent/glslang_tab.cpp" break; case 572: /* selection_statement: selection_statement_nonattributed */ #line 3730 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10706 "MachineIndependent/glslang_tab.cpp" break; case 573: /* selection_statement: attribute selection_statement_nonattributed */ #line 3734 "MachineIndependent/glslang.y" { parseContext.requireExtensions((yyvsp[0].interm.intermNode)->getLoc(), 1, &E_GL_EXT_control_flow_attributes, "attribute"); parseContext.handleSelectionAttributes(*(yyvsp[-1].interm.attributes), (yyvsp[0].interm.intermNode)); (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10716 "MachineIndependent/glslang_tab.cpp" break; case 574: /* selection_statement_nonattributed: IF LEFT_PAREN expression RIGHT_PAREN selection_rest_statement */ #line 3742 "MachineIndependent/glslang.y" { parseContext.boolCheck((yyvsp[-4].lex).loc, (yyvsp[-2].interm.intermTypedNode)); (yyval.interm.intermNode) = parseContext.intermediate.addSelection((yyvsp[-2].interm.intermTypedNode), (yyvsp[0].interm.nodePair), (yyvsp[-4].lex).loc); } #line 10725 "MachineIndependent/glslang_tab.cpp" break; case 575: /* selection_rest_statement: statement_scoped ELSE statement_scoped */ #line 3749 "MachineIndependent/glslang.y" { (yyval.interm.nodePair).node1 = (yyvsp[-2].interm.intermNode); (yyval.interm.nodePair).node2 = (yyvsp[0].interm.intermNode); } #line 10734 "MachineIndependent/glslang_tab.cpp" break; case 576: /* selection_rest_statement: statement_scoped */ #line 3753 "MachineIndependent/glslang.y" { (yyval.interm.nodePair).node1 = (yyvsp[0].interm.intermNode); (yyval.interm.nodePair).node2 = 0; } #line 10743 "MachineIndependent/glslang_tab.cpp" break; case 577: /* condition: expression */ #line 3761 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); parseContext.boolCheck((yyvsp[0].interm.intermTypedNode)->getLoc(), (yyvsp[0].interm.intermTypedNode)); } #line 10752 "MachineIndependent/glslang_tab.cpp" break; case 578: /* condition: fully_specified_type IDENTIFIER EQUAL initializer */ #line 3765 "MachineIndependent/glslang.y" { parseContext.boolCheck((yyvsp[-2].lex).loc, (yyvsp[-3].interm.type)); TType type((yyvsp[-3].interm.type)); TIntermNode* initNode = parseContext.declareVariable((yyvsp[-2].lex).loc, *(yyvsp[-2].lex).string, (yyvsp[-3].interm.type), 0, (yyvsp[0].interm.intermTypedNode)); if (initNode) (yyval.interm.intermTypedNode) = initNode->getAsTyped(); else (yyval.interm.intermTypedNode) = 0; } #line 10767 "MachineIndependent/glslang_tab.cpp" break; case 579: /* switch_statement: switch_statement_nonattributed */ #line 3778 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10775 "MachineIndependent/glslang_tab.cpp" break; case 580: /* switch_statement: attribute switch_statement_nonattributed */ #line 3782 "MachineIndependent/glslang.y" { parseContext.requireExtensions((yyvsp[0].interm.intermNode)->getLoc(), 1, &E_GL_EXT_control_flow_attributes, "attribute"); parseContext.handleSwitchAttributes(*(yyvsp[-1].interm.attributes), (yyvsp[0].interm.intermNode)); (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10785 "MachineIndependent/glslang_tab.cpp" break; case 581: /* $@9: %empty */ #line 3790 "MachineIndependent/glslang.y" { // start new switch sequence on the switch stack ++parseContext.controlFlowNestingLevel; ++parseContext.statementNestingLevel; parseContext.switchSequenceStack.push_back(new TIntermSequence); parseContext.switchLevel.push_back(parseContext.statementNestingLevel); parseContext.symbolTable.push(); } #line 10798 "MachineIndependent/glslang_tab.cpp" break; case 582: /* switch_statement_nonattributed: SWITCH LEFT_PAREN expression RIGHT_PAREN $@9 LEFT_BRACE switch_statement_list RIGHT_BRACE */ #line 3798 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = parseContext.addSwitch((yyvsp[-7].lex).loc, (yyvsp[-5].interm.intermTypedNode), (yyvsp[-1].interm.intermNode) ? (yyvsp[-1].interm.intermNode)->getAsAggregate() : 0); delete parseContext.switchSequenceStack.back(); parseContext.switchSequenceStack.pop_back(); parseContext.switchLevel.pop_back(); parseContext.symbolTable.pop(&parseContext.defaultPrecision[0]); --parseContext.statementNestingLevel; --parseContext.controlFlowNestingLevel; } #line 10812 "MachineIndependent/glslang_tab.cpp" break; case 583: /* switch_statement_list: %empty */ #line 3810 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = 0; } #line 10820 "MachineIndependent/glslang_tab.cpp" break; case 584: /* switch_statement_list: statement_list */ #line 3813 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10828 "MachineIndependent/glslang_tab.cpp" break; case 585: /* case_label: CASE expression COLON */ #line 3819 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = 0; if (parseContext.switchLevel.size() == 0) parseContext.error((yyvsp[-2].lex).loc, "cannot appear outside switch statement", "case", ""); else if (parseContext.switchLevel.back() != parseContext.statementNestingLevel) parseContext.error((yyvsp[-2].lex).loc, "cannot be nested inside control flow", "case", ""); else { parseContext.constantValueCheck((yyvsp[-1].interm.intermTypedNode), "case"); parseContext.integerCheck((yyvsp[-1].interm.intermTypedNode), "case"); (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpCase, (yyvsp[-1].interm.intermTypedNode), (yyvsp[-2].lex).loc); } } #line 10845 "MachineIndependent/glslang_tab.cpp" break; case 586: /* case_label: DEFAULT COLON */ #line 3831 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = 0; if (parseContext.switchLevel.size() == 0) parseContext.error((yyvsp[-1].lex).loc, "cannot appear outside switch statement", "default", ""); else if (parseContext.switchLevel.back() != parseContext.statementNestingLevel) parseContext.error((yyvsp[-1].lex).loc, "cannot be nested inside control flow", "default", ""); else (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpDefault, (yyvsp[-1].lex).loc); } #line 10859 "MachineIndependent/glslang_tab.cpp" break; case 587: /* iteration_statement: iteration_statement_nonattributed */ #line 3843 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10867 "MachineIndependent/glslang_tab.cpp" break; case 588: /* iteration_statement: attribute iteration_statement_nonattributed */ #line 3847 "MachineIndependent/glslang.y" { parseContext.requireExtensions((yyvsp[0].interm.intermNode)->getLoc(), 1, &E_GL_EXT_control_flow_attributes, "attribute"); parseContext.handleLoopAttributes(*(yyvsp[-1].interm.attributes), (yyvsp[0].interm.intermNode)); (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10877 "MachineIndependent/glslang_tab.cpp" break; case 589: /* $@10: %empty */ #line 3855 "MachineIndependent/glslang.y" { if (! parseContext.limits.whileLoops) parseContext.error((yyvsp[-1].lex).loc, "while loops not available", "limitation", ""); parseContext.symbolTable.push(); ++parseContext.loopNestingLevel; ++parseContext.statementNestingLevel; ++parseContext.controlFlowNestingLevel; } #line 10890 "MachineIndependent/glslang_tab.cpp" break; case 590: /* iteration_statement_nonattributed: WHILE LEFT_PAREN $@10 condition RIGHT_PAREN statement_no_new_scope */ #line 3863 "MachineIndependent/glslang.y" { parseContext.symbolTable.pop(&parseContext.defaultPrecision[0]); (yyval.interm.intermNode) = parseContext.intermediate.addLoop((yyvsp[0].interm.intermNode), (yyvsp[-2].interm.intermTypedNode), 0, true, (yyvsp[-5].lex).loc); --parseContext.loopNestingLevel; --parseContext.statementNestingLevel; --parseContext.controlFlowNestingLevel; } #line 10902 "MachineIndependent/glslang_tab.cpp" break; case 591: /* $@11: %empty */ #line 3870 "MachineIndependent/glslang.y" { ++parseContext.loopNestingLevel; ++parseContext.statementNestingLevel; ++parseContext.controlFlowNestingLevel; } #line 10912 "MachineIndependent/glslang_tab.cpp" break; case 592: /* iteration_statement_nonattributed: DO $@11 statement WHILE LEFT_PAREN expression RIGHT_PAREN SEMICOLON */ #line 3875 "MachineIndependent/glslang.y" { if (! parseContext.limits.whileLoops) parseContext.error((yyvsp[-7].lex).loc, "do-while loops not available", "limitation", ""); parseContext.boolCheck((yyvsp[0].lex).loc, (yyvsp[-2].interm.intermTypedNode)); (yyval.interm.intermNode) = parseContext.intermediate.addLoop((yyvsp[-5].interm.intermNode), (yyvsp[-2].interm.intermTypedNode), 0, false, (yyvsp[-4].lex).loc); --parseContext.loopNestingLevel; --parseContext.statementNestingLevel; --parseContext.controlFlowNestingLevel; } #line 10928 "MachineIndependent/glslang_tab.cpp" break; case 593: /* $@12: %empty */ #line 3886 "MachineIndependent/glslang.y" { parseContext.symbolTable.push(); ++parseContext.loopNestingLevel; ++parseContext.statementNestingLevel; ++parseContext.controlFlowNestingLevel; } #line 10939 "MachineIndependent/glslang_tab.cpp" break; case 594: /* iteration_statement_nonattributed: FOR LEFT_PAREN $@12 for_init_statement for_rest_statement RIGHT_PAREN statement_no_new_scope */ #line 3892 "MachineIndependent/glslang.y" { parseContext.symbolTable.pop(&parseContext.defaultPrecision[0]); (yyval.interm.intermNode) = parseContext.intermediate.makeAggregate((yyvsp[-3].interm.intermNode), (yyvsp[-5].lex).loc); TIntermLoop* forLoop = parseContext.intermediate.addLoop((yyvsp[0].interm.intermNode), reinterpret_cast<TIntermTyped*>((yyvsp[-2].interm.nodePair).node1), reinterpret_cast<TIntermTyped*>((yyvsp[-2].interm.nodePair).node2), true, (yyvsp[-6].lex).loc); if (! parseContext.limits.nonInductiveForLoops) parseContext.inductiveLoopCheck((yyvsp[-6].lex).loc, (yyvsp[-3].interm.intermNode), forLoop); (yyval.interm.intermNode) = parseContext.intermediate.growAggregate((yyval.interm.intermNode), forLoop, (yyvsp[-6].lex).loc); (yyval.interm.intermNode)->getAsAggregate()->setOperator(EOpSequence); --parseContext.loopNestingLevel; --parseContext.statementNestingLevel; --parseContext.controlFlowNestingLevel; } #line 10956 "MachineIndependent/glslang_tab.cpp" break; case 595: /* for_init_statement: expression_statement */ #line 3907 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10964 "MachineIndependent/glslang_tab.cpp" break; case 596: /* for_init_statement: declaration_statement */ #line 3910 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 10972 "MachineIndependent/glslang_tab.cpp" break; case 597: /* conditionopt: condition */ #line 3916 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = (yyvsp[0].interm.intermTypedNode); } #line 10980 "MachineIndependent/glslang_tab.cpp" break; case 598: /* conditionopt: %empty */ #line 3919 "MachineIndependent/glslang.y" { (yyval.interm.intermTypedNode) = 0; } #line 10988 "MachineIndependent/glslang_tab.cpp" break; case 599: /* for_rest_statement: conditionopt SEMICOLON */ #line 3925 "MachineIndependent/glslang.y" { (yyval.interm.nodePair).node1 = (yyvsp[-1].interm.intermTypedNode); (yyval.interm.nodePair).node2 = 0; } #line 10997 "MachineIndependent/glslang_tab.cpp" break; case 600: /* for_rest_statement: conditionopt SEMICOLON expression */ #line 3929 "MachineIndependent/glslang.y" { (yyval.interm.nodePair).node1 = (yyvsp[-2].interm.intermTypedNode); (yyval.interm.nodePair).node2 = (yyvsp[0].interm.intermTypedNode); } #line 11006 "MachineIndependent/glslang_tab.cpp" break; case 601: /* jump_statement: CONTINUE SEMICOLON */ #line 3936 "MachineIndependent/glslang.y" { if (parseContext.loopNestingLevel <= 0) parseContext.error((yyvsp[-1].lex).loc, "continue statement only allowed in loops", "", ""); (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpContinue, (yyvsp[-1].lex).loc); } #line 11016 "MachineIndependent/glslang_tab.cpp" break; case 602: /* jump_statement: BREAK SEMICOLON */ #line 3941 "MachineIndependent/glslang.y" { if (parseContext.loopNestingLevel + parseContext.switchSequenceStack.size() <= 0) parseContext.error((yyvsp[-1].lex).loc, "break statement only allowed in switch and loops", "", ""); (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpBreak, (yyvsp[-1].lex).loc); } #line 11026 "MachineIndependent/glslang_tab.cpp" break; case 603: /* jump_statement: RETURN SEMICOLON */ #line 3946 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpReturn, (yyvsp[-1].lex).loc); if (parseContext.currentFunctionType->getBasicType() != EbtVoid) parseContext.error((yyvsp[-1].lex).loc, "non-void function must return a value", "return", ""); if (parseContext.inMain) parseContext.postEntryPointReturn = true; } #line 11038 "MachineIndependent/glslang_tab.cpp" break; case 604: /* jump_statement: RETURN expression SEMICOLON */ #line 3953 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = parseContext.handleReturnValue((yyvsp[-2].lex).loc, (yyvsp[-1].interm.intermTypedNode)); } #line 11046 "MachineIndependent/glslang_tab.cpp" break; case 605: /* jump_statement: DISCARD SEMICOLON */ #line 3956 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[-1].lex).loc, EShLangFragment, "discard"); (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpKill, (yyvsp[-1].lex).loc); } #line 11055 "MachineIndependent/glslang_tab.cpp" break; case 606: /* jump_statement: TERMINATE_INVOCATION SEMICOLON */ #line 3960 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[-1].lex).loc, EShLangFragment, "terminateInvocation"); (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpTerminateInvocation, (yyvsp[-1].lex).loc); } #line 11064 "MachineIndependent/glslang_tab.cpp" break; case 607: /* jump_statement: TERMINATE_RAY SEMICOLON */ #line 3965 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[-1].lex).loc, EShLangAnyHit, "terminateRayEXT"); (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpTerminateRayKHR, (yyvsp[-1].lex).loc); } #line 11073 "MachineIndependent/glslang_tab.cpp" break; case 608: /* jump_statement: IGNORE_INTERSECTION SEMICOLON */ #line 3969 "MachineIndependent/glslang.y" { parseContext.requireStage((yyvsp[-1].lex).loc, EShLangAnyHit, "ignoreIntersectionEXT"); (yyval.interm.intermNode) = parseContext.intermediate.addBranch(EOpIgnoreIntersectionKHR, (yyvsp[-1].lex).loc); } #line 11082 "MachineIndependent/glslang_tab.cpp" break; case 609: /* translation_unit: external_declaration */ #line 3979 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); parseContext.intermediate.setTreeRoot((yyval.interm.intermNode)); } #line 11091 "MachineIndependent/glslang_tab.cpp" break; case 610: /* translation_unit: translation_unit external_declaration */ #line 3983 "MachineIndependent/glslang.y" { if ((yyvsp[0].interm.intermNode) != nullptr) { (yyval.interm.intermNode) = parseContext.intermediate.growAggregate((yyvsp[-1].interm.intermNode), (yyvsp[0].interm.intermNode)); parseContext.intermediate.setTreeRoot((yyval.interm.intermNode)); } } #line 11102 "MachineIndependent/glslang_tab.cpp" break; case 611: /* external_declaration: function_definition */ #line 3992 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 11110 "MachineIndependent/glslang_tab.cpp" break; case 612: /* external_declaration: declaration */ #line 3995 "MachineIndependent/glslang.y" { (yyval.interm.intermNode) = (yyvsp[0].interm.intermNode); } #line 11118 "MachineIndependent/glslang_tab.cpp" break; case 613: /* external_declaration: SEMICOLON */ #line 3999 "MachineIndependent/glslang.y" { parseContext.requireProfile((yyvsp[0].lex).loc, ~EEsProfile, "extraneous semicolon"); parseContext.profileRequires((yyvsp[0].lex).loc, ~EEsProfile, 460, nullptr, "extraneous semicolon"); (yyval.interm.intermNode) = nullptr; } #line 11128 "MachineIndependent/glslang_tab.cpp" break; case 614: /* $@13: %empty */ #line 4008 "MachineIndependent/glslang.y" { (yyvsp[0].interm).function = parseContext.handleFunctionDeclarator((yyvsp[0].interm).loc, *(yyvsp[0].interm).function, false /* not prototype */); (yyvsp[0].interm).intermNode = parseContext.handleFunctionDefinition((yyvsp[0].interm).loc, *(yyvsp[0].interm).function); // For ES 100 only, according to ES shading language 100 spec: A function // body has a scope nested inside the function's definition. if (parseContext.profile == EEsProfile && parseContext.version == 100) { parseContext.symbolTable.push(); ++parseContext.statementNestingLevel; } } #line 11145 "MachineIndependent/glslang_tab.cpp" break; case 615: /* function_definition: function_prototype $@13 compound_statement_no_new_scope */ #line 4020 "MachineIndependent/glslang.y" { // May be best done as post process phase on intermediate code if (parseContext.currentFunctionType->getBasicType() != EbtVoid && ! parseContext.functionReturnsValue) parseContext.error((yyvsp[-2].interm).loc, "function does not return a value:", "", (yyvsp[-2].interm).function->getName().c_str()); parseContext.symbolTable.pop(&parseContext.defaultPrecision[0]); (yyval.interm.intermNode) = parseContext.intermediate.growAggregate((yyvsp[-2].interm).intermNode, (yyvsp[0].interm.intermNode)); parseContext.intermediate.setAggregateOperator((yyval.interm.intermNode), EOpFunction, (yyvsp[-2].interm).function->getType(), (yyvsp[-2].interm).loc); (yyval.interm.intermNode)->getAsAggregate()->setName((yyvsp[-2].interm).function->getMangledName().c_str()); // store the pragma information for debug and optimize and other vendor specific // information. This information can be queried from the parse tree (yyval.interm.intermNode)->getAsAggregate()->setOptimize(parseContext.contextPragma.optimize); (yyval.interm.intermNode)->getAsAggregate()->setDebug(parseContext.contextPragma.debug); (yyval.interm.intermNode)->getAsAggregate()->setPragmaTable(parseContext.contextPragma.pragmaTable); // Set currentFunctionType to empty pointer when goes outside of the function parseContext.currentFunctionType = nullptr; // For ES 100 only, according to ES shading language 100 spec: A function // body has a scope nested inside the function's definition. if (parseContext.profile == EEsProfile && parseContext.version == 100) { parseContext.symbolTable.pop(&parseContext.defaultPrecision[0]); --parseContext.statementNestingLevel; } } #line 11176 "MachineIndependent/glslang_tab.cpp" break; case 616: /* attribute: LEFT_BRACKET LEFT_BRACKET attribute_list RIGHT_BRACKET RIGHT_BRACKET */ #line 4050 "MachineIndependent/glslang.y" { (yyval.interm.attributes) = (yyvsp[-2].interm.attributes); } #line 11184 "MachineIndependent/glslang_tab.cpp" break; case 617: /* attribute_list: single_attribute */ #line 4055 "MachineIndependent/glslang.y" { (yyval.interm.attributes) = (yyvsp[0].interm.attributes); } #line 11192 "MachineIndependent/glslang_tab.cpp" break; case 618: /* attribute_list: attribute_list COMMA single_attribute */ #line 4058 "MachineIndependent/glslang.y" { (yyval.interm.attributes) = parseContext.mergeAttributes((yyvsp[-2].interm.attributes), (yyvsp[0].interm.attributes)); } #line 11200 "MachineIndependent/glslang_tab.cpp" break; case 619: /* single_attribute: IDENTIFIER */ #line 4063 "MachineIndependent/glslang.y" { (yyval.interm.attributes) = parseContext.makeAttributes(*(yyvsp[0].lex).string); } #line 11208 "MachineIndependent/glslang_tab.cpp" break; case 620: /* single_attribute: IDENTIFIER LEFT_PAREN constant_expression RIGHT_PAREN */ #line 4066 "MachineIndependent/glslang.y" { (yyval.interm.attributes) = parseContext.makeAttributes(*(yyvsp[-3].lex).string, (yyvsp[-1].interm.intermTypedNode)); } #line 11216 "MachineIndependent/glslang_tab.cpp" break; #line 11220 "MachineIndependent/glslang_tab.cpp" default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", YY_CAST (yysymbol_kind_t, yyr1[yyn]), &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; { yypcontext_t yyctx = {yyssp, yytoken}; char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = yysyntax_error (&yymsg_alloc, &yymsg, &yyctx); if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == -1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = YY_CAST (char *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, yymsg_alloc))); if (yymsg) { yysyntax_error_status = yysyntax_error (&yymsg_alloc, &yymsg, &yyctx); yymsgp = yymsg; } else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = YYENOMEM; } } yyerror (pParseContext, yymsgp); if (yysyntax_error_status == YYENOMEM) goto yyexhaustedlab; } } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, pParseContext); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (0) YYERROR; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ /* Pop stack until we find a state that shifts the error token. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYSYMBOL_YYerror; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYSYMBOL_YYerror) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", YY_ACCESSING_SYMBOL (yystate), yyvsp, pParseContext); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", YY_ACCESSING_SYMBOL (yyn), yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if 1 /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (pParseContext, YY_("memory exhausted")); yyresult = 2; goto yyreturn; #endif /*-------------------------------------------------------. | yyreturn -- parsing is finished, clean up and return. | `-------------------------------------------------------*/ yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, pParseContext); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", YY_ACCESSING_SYMBOL (+*yyssp), yyvsp, pParseContext); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); return yyresult; } #line 4071 "MachineIndependent/glslang.y"
50.67552
258
0.54127
[ "vector" ]
3598aa590ebffe2a77ba45cf38373fc83ffae191
1,297
cpp
C++
src/bandits.cpp
nektonick/multi-armed-bandit
fa41a52fec32a4536f901c63ad42132e826663af
[ "BSD-2-Clause" ]
1
2022-01-05T01:54:51.000Z
2022-01-05T01:54:51.000Z
src/bandits.cpp
nektonick/multi-armed-bandit
fa41a52fec32a4536f901c63ad42132e826663af
[ "BSD-2-Clause" ]
null
null
null
src/bandits.cpp
nektonick/multi-armed-bandit
fa41a52fec32a4536f901c63ad42132e826663af
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "bandits.h" namespace multiArmedBandit { IBandit::IBandit() { } SimpleBandit::SimpleBandit(const std::vector<ArmPtr>& arms, double pullCost) : arms_(arms) , pullCost_(pullCost) { std::vector<double> expectedRewards(arms.size(), 0.0); for(size_t i = 0; i < arms_.size(); ++i) { expectedRewards[i] = arms_[i]->getRewardExpectation(); } bestArmIndex_ = std::distance(expectedRewards.begin(), std::max_element(expectedRewards.begin(), expectedRewards.end())); ; } std::string SimpleBandit::statePrint() { std::string out; for(size_t i = 0; i < arms_.size(); ++i) { out += arms_[i]->toString() + ENDL; } return out; } double SimpleBandit::pullArmAndGetReward(size_t armIndex) { // Information to log: armIndex reward, regret // double bestRewardExpectation = arms_[bestArmIndex]->getRewardExpectation(); // double currentRewardExpectation = arms_[armIndex]->getRewardExpectation(); // double regret = bestRewardExpectation - currentRewardExpectation; double reward = arms_[armIndex]->pull(); return reward; } double SimpleBandit::getPullCost() const { return pullCost_; } size_t SimpleBandit::getArmsCount() const { return arms_.size(); } } // namespace multiArmedBandit
24.471698
125
0.683886
[ "vector" ]
3599b6cb9f6087a539e812ed5eb9f34a4947b308
18,061
cpp
C++
src/main.cpp
jmac006/rshell
5d597c64ecc2b60640f8519e94942d293134c4da
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
jmac006/rshell
5d597c64ecc2b60640f8519e94942d293134c4da
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
jmac006/rshell
5d597c64ecc2b60640f8519e94942d293134c4da
[ "BSD-3-Clause" ]
1
2016-06-09T05:32:03.000Z
2016-06-09T05:32:03.000Z
#include <iostream> #include <stdio.h> #include <unistd.h> //used for fork(), execvp() #include <sys/types.h> //used for wait #include <sys/wait.h> //used for wait #include <sys/stat.h> #include <string.h> #include <cstdlib> #include <fcntl.h> //used for file descriptor #include <vector> #include <stack> using namespace std; bool execute(vector<string>commandArr) { if (commandArr.at(0) == "exit") { exit(0); } if(commandArr.size() > 1){ if (commandArr.at(1).at(0) == '\"'||commandArr.at(1).at(0) == '\'') { //fixes quotation marks when executing echo commandArr.at(1).erase(commandArr.at(1).begin()); commandArr.at(commandArr.size()-1).erase(commandArr.at(commandArr.size()-1).begin() + commandArr.at(commandArr.size()-1).size()-1); } } char* cmdArr[commandArr.size() + 1]; int i = 0; for (i = 0; i < static_cast<int>(commandArr.size()); i++) {//convert the vector into a char* array for execvp cmdArr[i] = (char*)commandArr.at(i).c_str(); } cmdArr[commandArr.size()] = NULL; //set last value to NULL for execvp int status = 0; char fullpath[20] = "/bin/"; //full file path, starts at bin strcat(fullpath, commandArr[0].c_str()); //add the first command to the file path pid_t pid = fork();//split the processes into parent and child if(pid==0) { //if the process is a child int exec = execvp(fullpath,cmdArr); // to check if execvp passes or fails if (exec == -1) { //execvp failed return false; perror("exec"); exit(-1); } } else { //Otherwise, the process is a parent waitpid(pid, &status, 0); //wait for the child process to finish } return true; } bool executeTest(vector<string>commandArr){ struct stat file; bool noflag; if( commandArr.at(1) != "-e" && commandArr.at(1) != "-f" && commandArr.at(1) != "-d"){ noflag = true; } else { noflag = false; } if( commandArr.at(1) == "-e" || noflag ){ //does test -e or test with no specifications if( !noflag && stat(commandArr.at(2).c_str(), &file) == 0){ cout << "(True)" << endl; return true; } else if (noflag && stat(commandArr.at(1).c_str(), &file) ==0){ cout << "(True)" << endl; return true; } else { cout << "(False)" << endl; return false; } } else if(commandArr.at(1) == "-f"){ //does test witht -f, so checks if it is a file if(stat(commandArr.at(2).c_str(), &file) == 0){ if(S_ISREG(file.st_mode)){ cout << "(True)" << endl; return true; } else{ cout << "(False)" << endl; return false; } } else{ cout << "(False)" << endl; return false; } } else if(commandArr.at(1) == "-d"){ // does test with -d, so checks if it a directory if(stat(commandArr.at(2).c_str(), &file) == 0) { if(S_ISDIR(file.st_mode)){ cout << "(True)" << endl; return true; } else{ cout << "(False)" << endl; return false; } } else{ cout << "(False)" << endl; return false; } } return false; } bool hasOutputRedirect(string s) { if(s == ">") { return true; } return false; } bool hasAppendRedirect(string s) { if(s == ">>") { return true; } return false; } bool hasInputRedirect(string s) { if(s == "<") { return true; } return false; } bool hasPipe(string s) { if(s == "|") { return true; } return false; } string convertToString(vector<string>command) { string s; for(unsigned i = 0; i < command.size(); i++) { s += command.at(i); if(i < command.size()-1) { s += " "; } } return s; } void execCommand(string cmdLine, bool &hasExecuted); bool isRedirect(string s); void pipeCommand(vector<string>cmd1, vector<string>cmd2) { char* command1[cmd1.size() + 1]; for (int i = 0; i < static_cast<int>(cmd1.size()); i++) { //convert the vector into a char* array for execvp command1[i] = (char*)cmd1.at(i).c_str(); } command1[cmd1.size()] = NULL; //set last value to NULL for execvp char* command2[cmd2.size() + 1]; for (int i = 0; i < static_cast<int>(cmd2.size()); i++) { //convert the second command into a char* array for execvp command2[i] = (char*)cmd2.at(i).c_str(); } command2[cmd2.size()] = NULL; //set last value to NULL for execvp int fds[2]; //file descriptors pipe(fds); pid_t pid; if (fork() == 0) { // child process #1 dup2(fds[0], 0); // change stdin to fds[0] close(fds[1]); //close the end of the pipe //Execute the second command execvp(command2[0], command2); perror("execvp failed"); } else if ((pid = fork()) == 0) { // child process #2 dup2(fds[1], 1); //change stdout to file output close(fds[0]); //close the pipe, not going to read child process //Execute the first command execvp(command1[0], command1); perror("execvp failed"); } else { //parent process waitpid(pid, NULL, 0); } } bool executeRedirect(vector<string>commandArr) { //save the stdin and stdout, and use dup to change the stdin/stdout to a file int saveSTD[2]; //size of 2 to save stdin and stdout vector<string>command; //holds individual commands for(unsigned i = 0; i < commandArr.size(); i++) { command.push_back(commandArr.at(i)); if(hasOutputRedirect(commandArr.at(i)) && command.size() > 1) { command.pop_back(); //pops the redirection off char file[commandArr.at(i+1).size()]; strcpy(file,commandArr.at(i+1).c_str()); i++; int pfd; if((pfd = open(file, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP )) == -1) { perror("Couldn't open file"); exit(1); } saveSTD[1] = dup(1); //saves the stdout to restore later dup2(pfd,1); //changed output to the file directory string comm = convertToString(command); bool didExecute = true; execCommand(comm,didExecute); dup2(saveSTD[1],1); //restore the stdout } else if(hasAppendRedirect(commandArr.at(i)) && command.size() > 1) { command.pop_back(); //pops the redirection off char file[commandArr.at(i+1).size()]; strcpy(file,commandArr.at(i+1).c_str()); i++; int pfd; if((pfd = open(file, O_RDWR | O_APPEND, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP )) == -1) { perror("Couldn't open file"); exit(1); } saveSTD[1] = dup(1); //saves the stdout to restore later dup2(pfd,1); //changed output to the file directory string comm = convertToString(command); bool didExecute = true; execCommand(comm,didExecute); dup2(saveSTD[1],1); //restore the stdout } else if(hasInputRedirect(commandArr.at(i)) && command.size() > 1) { command.pop_back(); char file[commandArr.at(i+1).size()]; strcpy(file,commandArr.at(i+1).c_str()); i++; int pfd; if((pfd = open(file, O_RDWR | O_APPEND, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP )) == -1) { perror("Couldn't open file"); exit(1); } saveSTD[0] = dup(0); //saves the stdin to restore later dup2(pfd,0); //changed input to the file directory string comm = convertToString(command); bool didExecute = true; execCommand(comm,didExecute); dup2(saveSTD[0],0); //restore the stdin } else if(hasPipe(commandArr.at(i)) && command.size() > 1) { vector<string>command2; command.pop_back(); ++i; for (unsigned j = i; j < commandArr.size(); j++) { if(!isRedirect(commandArr.at(j))) { command2.push_back(commandArr.at(j)); } } pipeCommand(command,command2); } } return true; } bool hasSemi(string s); bool hasHash(string s); bool isConnector(string s); bool hasEParen(string s){ //checks for ')' if(s.at(s.size() - 1) == ')'){ return true; //return position of semi } return false; // if not found return -1 } bool hasOParen(string s){ //checks for '(' if(s.at(0) == '(') { return true; //return position of semi } return false; // if not found return -1 } void parse_string(string commandLine, vector<string>&cmdArray) { char* token; //split command into separate strings char* cmd = new char[commandLine.length() + 1]; strcpy(cmd, commandLine.c_str()); //converts string to char* token = strtok(cmd, " "); //tokenize first part of string int i = 0; for (i = 0; token != NULL; i++) { if (token == NULL) { //break out of for loop if there's an empty token break; } string tokenString = string(token); //cout << "Token is: " << tokenString << endl; if(!isConnector(tokenString)) { //if it a just a connector without any words attached go straight to push_back if (hasSemi(tokenString)) {//if there is a semicolon attached enter loop string semicolon = ";"; tokenString.erase(tokenString.begin() + tokenString.size() -1 ); //remove the semicolon at the end of word cmdArray.push_back(tokenString); // push back word without semicolon cmdArray.push_back(semicolon);// push back semi colon as its own string } else if(hasHash(tokenString)) { //if there is a hash enter loop string hash = "#"; tokenString.erase(tokenString.begin()); // remove hashtag located at front of string cmdArray.push_back(hash); // push back has as its own string cmdArray.push_back(tokenString); // push back word } else{ cmdArray.push_back(tokenString); // if it does not contain semi or hash push back word } } else if(hasEParen(tokenString)){ if(tokenString.size() == 1){ cmdArray.push_back(tokenString); } else{ string paran = ")"; tokenString.erase(tokenString.begin() + tokenString.size() -1 ); //remove the semicolon at the end of word cmdArray.push_back(tokenString); // push back word without semicolon cmdArray.push_back(paran);// push back semi colon as its own string } } else if(hasOParen(tokenString)){ if(tokenString.size() == 1){ cmdArray.push_back(tokenString); } else{ string paran = "("; tokenString.erase(tokenString.begin()); // remove hashtag located at front of string cmdArray.push_back(paran); // push back has as its own string cmdArray.push_back(tokenString); // push back word } } else{ cmdArray.push_back(tokenString); } token = strtok(NULL, " "); } } void printPrompt() { char* user = getlogin(); char host[BUFSIZ]; //creates a host name with buffer size gethostname(host, 1024); if (user == NULL) { //could not find the username cout << "$ "; } else { cout << user << '@' << host << "$ "; } } bool isConnector(string s) { if (s == "||" || s== "&&" || s == ";" || s == "#") { return true; } return false; } bool hasSemi(string s){ //checks for semicolon attached to a word; for(unsigned i = 0; i < s.size(); ++i){ if(s.at(i) == ';'){ return true; //return position of semi } } return false; // if not found return -1 } bool hasHash(string s){ for(unsigned i = 0; i < s.size(); ++i){ if(s.at(i) == '#') { return true; } } return false; } bool isTest(string s){ //checks if command is a test case if(s == "[" || s == "test"){ return true; } return false; } bool isRedirect(string s){ if(s == "|" || s == ">" || s == ">>" || s == "<"){ return true; } return false; } bool checkRedirect(vector<string>s) { for(unsigned i = 0; i < s.size(); i++) { if (isRedirect(s.at(i))) { return true; } } return false; } void execCommand(string cmdLine, bool &hasExecuted) { vector<string>cmdArr; //holds the whole command line (parsed) vector<string>command; //holds individual commands to run in execute() function if (cmdLine == "exit") { exit(0); } parse_string(cmdLine, cmdArr); bool hasRedirect = false; for (unsigned i = 0; i < cmdArr.size(); i++) { //start where we left off, only executes when there is two connectors in between a command command.push_back(cmdArr.at(i)); /*if (hasHash(cmdArr.at(i))) { //if it is a comment, break out of the loop break; }*/ if(isConnector(cmdArr.at(i)) && command.size() > 1) { //if there's more commands and the next command is a connector hasRedirect = checkRedirect(command); if(command.at(1) == "#") { //handles comments after connector break; } if (command.at(0) == "&&") { i--; //decrement i to include next connector command.erase(command.begin()); //remove connector from command command.pop_back(); //remove connector at the end if (hasExecuted == true) { if(isTest(command.at(0))){ hasExecuted = executeTest(command); } else if(hasRedirect) { hasExecuted = executeRedirect(command); } else{ hasExecuted = execute(command); } } command.clear(); } else if(command.at(0)== ";") { i--; command.erase(command.begin()); //remove connector from command command.pop_back(); //pop back twice if(isTest(command.at(0))){ hasExecuted = executeTest(command); } else if(hasRedirect) { hasExecuted = executeRedirect(command); } else{ hasExecuted = execute(command); } command.clear(); } else if(command.at(0) == "||") { i--; //decrement i to include next connector command.erase(command.begin()); //delete the connector command.pop_back(); //remove connector at end of command if (hasExecuted == false) { //if the previous command did not execute, run this command if(isTest(command.at(0))){ hasExecuted = executeTest(command); } else if(hasRedirect) { hasExecuted = executeRedirect(command); } else{ hasExecuted = execute(command); } } else { hasExecuted = false; } command.clear(); } else if(command.at(0) == "#" && command.size() == 1) { break; //don't do anything if command has comments } else if(!isConnector(command.at(0))){ //executes the very first command in cmdArr i--; command.pop_back(); //remove the connector if(isTest(command.at(0))){ hasExecuted = executeTest(command); } else if(hasRedirect) { hasExecuted = executeRedirect(command); } else{ hasExecuted = execute(command); } command.clear(); } hasRedirect = false; } else if(i == cmdArr.size()-1) { //if this is the last command hasRedirect = checkRedirect(command); if(isConnector(command.at(command.size()-1))) { //if there is a dangling connector at the end remove it command.pop_back(); break; } if (command.size() != 0 && command.at(0) == "&&") { command.erase(command.begin()); //delete connector if (hasExecuted == true) { if(isTest(command.at(0))){ hasExecuted = executeTest(command); } else if(hasRedirect) { hasExecuted = executeRedirect(command); } else{ hasExecuted = execute(command); } } } else if (command.size() != 0 && command.at(0) == "||") { command.erase(command.begin()); if (hasExecuted == false) { if(isTest(command.at(0))){ hasExecuted = executeTest(command); } else if(hasRedirect) { hasExecuted = executeRedirect(command); } else{ hasExecuted = execute(command); } } } else if (command.size() != 0 && command.at(0) == ";") { command.erase(command.begin()); if(isTest(command.at(0))){ hasExecuted = executeTest(command); } else if(hasRedirect) { hasExecuted = executeRedirect(command); } else{ hasExecuted = execute(command); } break; } else if (command.size() != 0 && command.at(0) == "#") { command.erase(command.begin()); return; } else { if(isTest(command.at(0))){ hasExecuted = executeTest(command); } else if(hasRedirect) { hasExecuted = executeRedirect(command); } else{ hasExecuted = execute(command); } } } } } bool checkParenthesis(string command) { stack<char>parenthesis; for(unsigned i = 0; i < command.size(); i++) { if(command.at(i) == '(') { parenthesis.push('('); } else if(command.at(i) == ')') { if(!parenthesis.empty()) { parenthesis.pop(); } else { cout << "Parenthesis mismatch. Missing \'('." << endl; return false; } } } if(!parenthesis.empty()) { cout << "Parenthesis mismatch. Missing \')'." << endl; return false; } return true; } void remove_parenthesis(string &s) { for(unsigned i = 0; i < s.size(); i++) { if(s.at(i) == '(' || s.at(i) == ')') { s.erase(s.begin() + i); } } } void separateParenthesis(string command) { //parses the parenthesis and calls execCommand on those parsed strings bool didExecute = true; checkParenthesis(command); vector<string>parseCommands; vector<string>commandList; parse_string(command,parseCommands); string comm; bool insideParenthesis = false; for(unsigned i = 0; i < parseCommands.size();i++) { comm += parseCommands.at(i); if(i < parseCommands.size()-1) { //push individual command if we find a connector and we're not inside the parenthesis if(isConnector(parseCommands.at(i+1)) && !insideParenthesis) { remove_parenthesis(comm); //remove any parenthesis before pushing individual commands commandList.push_back(comm); comm.clear(); } } if(i < parseCommands.size()-1 && !hasEParen(parseCommands.at(i))) { //won't add a space to the end or after the end parenthesis comm += " "; } if(hasOParen(parseCommands.at(i))) { insideParenthesis = true; } else if(hasEParen(parseCommands.at(i))) { remove_parenthesis(comm); //remove any parenthesis before pushing individual commands commandList.push_back(comm); comm.clear(); insideParenthesis = false; } else if(i == parseCommands.size() - 1) { remove_parenthesis(comm); //remove any parenthesis before pushing individual commands commandList.push_back(comm); } } //cout << "Command size is: " << commandList.size() << endl; //cout << "Command List contains: "; //execute individual commands based on precedence for (unsigned i = 0; i < commandList.size(); i++) { execCommand(commandList.at(i),didExecute); } } int main () { string cmdLine; //bool hasExecuted = true; while(cmdLine != "exit") { printPrompt(); cmdLine.clear(); getline(cin, cmdLine); if (cmdLine == "exit") { //exits with command "exit" exit(0); } else { //execCommand(cmdLine,hasExecuted); separateParenthesis(cmdLine); } } return 0; }
27.323752
138
0.625602
[ "vector" ]
359de53a31980513e76a24909a0cf73f8824d3e0
23,790
cpp
C++
synthesizer/src/symRiSynthesiser.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
synthesizer/src/symRiSynthesiser.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
synthesizer/src/symRiSynthesiser.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
#include "../lib/bottomUpSearch.hpp" #include "../lib/unification.hpp" #include "../lib/sampler.hpp" #include "../lib/typeDef.hpp" #include <vector> #include <future> #include <chrono> #include <thread> #include <functional> #include <string> #include <fstream> #include <sstream> using namespace std; //#define DEBUG bool parser(int argc, char* argv[], string* file_name, int* search_time_for_terms_in_seconds, int* search_time_for_predicates_in_seconds, int* depth_bound_for_predicate, vector<string>* int_ops_for_predicate, vector<string>* bool_ops_for_predicate, vector<string>* vars_in_predicate, vector<string>* constants_in_predicate, int* depth_bound_for_term, vector<string>* int_ops_for_term, vector<string>* bool_ops_for_term, vector<string>* vars_in_term, vector<string>* constants_in_term, vector<string>* rules_to_apply, string* bench_name, int* ref_id, int* num_growing_speed, int* num_growing_upperbound) { for (int i = 1; i < argc; i++) { string argvi(argv[i]); if (argvi == "-FILE") { i++; if (i < argc) { argvi = argv[i]; *file_name = argvi; string tmp = argvi.substr(argvi.rfind("/") + 1); if (tmp.find("_") == string::npos) throw runtime_error("can not extract bench name from file name"); *bench_name = tmp.substr(0, tmp.find("_")); if (tmp.find("refsrc_") == string::npos) throw runtime_error("can not extract ref id from file name"); tmp = argvi.substr(argvi.rfind("refsrc_") + 7); *ref_id = stoi(tmp.substr(0, tmp.find("_"))); continue; } throw runtime_error("-FILE: error in providing file name"); } else if (argvi == "-DEPTHBOUNDPRED") { i++; if (i < argc) { argvi = argv[i]; if (isdigit(argvi[0])) { *depth_bound_for_predicate = stoi(argv[i]); continue; } throw runtime_error("-DEPTHBOUNDPRED: error in specifying the depth of the predicate program"); } } else if (argvi == "-INTOPSPRED") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && !isdigit(argvi[0])) { int_ops_for_predicate->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-INTOPSPRED: error in specifying the int ops for predicate language"); } } else if (argvi == "-BOOLOPSPRED") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && !isdigit(argvi[0])) { bool_ops_for_predicate->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-BOOLOPSPRED: error in specifying the bool ops for predicate language"); } } else if (argvi == "-VARSPRED") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && !isdigit(argvi[0])) { vars_in_predicate->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-VARSPRED: error in specifying the variables allowed in predicate language"); } } else if (argvi == "-CONSTANTSPRED") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && isdigit(argvi[0])) { constants_in_predicate->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-CONSTANTSPRED: error in specifying the constants allowed in predicate language"); } } else if (argvi == "-DEPTHBOUNDTERM") { i++; if (i < argc) { argvi = argv[i]; if (isdigit(argvi[0])) { *depth_bound_for_term = stoi(argv[i]); } else { return false; } } else { throw runtime_error("-DEPTHBOUNDTERM: error in specifying the depth of the term program"); } } else if (argvi == "-INTOPSTERM") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && !isdigit(argvi[0])) { int_ops_for_term->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-INTOPSTERM: error in specifying the int ops in the term language"); } } else if (argvi == "-BOOLOPSTERM") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && !isdigit(argvi[0])) { bool_ops_for_term->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-BOOLOPSTERM: error in specifying the bool ops in the term language"); } } else if (argvi == "-VARSTERM") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && !isdigit(argvi[0])) { vars_in_term->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-VARSTERM: error in specifying the variables allowed in the term language"); } } else if (argvi == "-CONSTANTSTERM") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && isdigit(argvi[0])) { constants_in_term->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-CONSTANTSTERM: error in specifying the constants in the term language"); } } else if (argvi == "-SEARCHTIMEFORTERMSINSECONDS") { i++; if (i < argc) { argvi = argv[i]; if (isdigit(argvi[0])) { *search_time_for_terms_in_seconds = stoi(argv[i]); } else { return false; } } else { throw runtime_error("-SEARCHTIMEFORTERMSINSECONDS: error in specifying the search time"); } } else if (argvi == "-SEARCHTIMEFORPREDSINSECONDS") { i++; if (i < argc) { argvi = argv[i]; if (isdigit(argvi[0])) { *search_time_for_predicates_in_seconds = stoi(argv[i]); } else { return false; } } else { throw runtime_error("-SEARCHTIMEFORPREDSINSECONDS: error in specifying the search time"); } } else if (argvi == "-RULESTOAPPLY") { i++; if (i < argc) { argvi = argv[i]; while(argvi[0] != '-' && !isdigit(argvi[0])) { rules_to_apply->push_back(argvi); i++; if (i >= argc) { break; } argvi = argv[i]; } i--; } else { throw runtime_error("-RULESTOAPPLY: error in specifying the bool ops in the term language"); } } else if (argvi == "-NUMGROWSPEED") { i++; if (i < argc) { argvi = argv[i]; if (isdigit(argvi[0])) { *num_growing_speed = stoi(argvi); continue; } } throw runtime_error("-NUMGROWSPEED: error in specifying the growing speed of the number"); } else if (argvi == "-NUMGROWUPPERBOUND") { i++; if (i < argc) { argvi = argv[i]; if (isdigit(argvi[0])) { *num_growing_upperbound = stoi(argvi); continue; } } throw runtime_error("-NUMGROWUPPERBOUND: error in specifying the upper bound of the constant number"); } else { throw runtime_error("error in providing command line arguments"); } } return true; } /* Language configuration */ void language_configuration(int* depth_bound_for_predicate, vector<string>* int_ops_for_predicate, vector<string>* bool_ops_for_predicate, vector<string>* vars_in_predicate, vector<string>* constants_in_predicate, int* depth_bound_for_term, vector<string>* int_ops_for_term, vector<string>* bool_ops_for_term, vector<string>* vars_in_term, vector<string>* constants_in_term, input_outputs_t input_outputs) { if (*depth_bound_for_predicate == -1) { *depth_bound_for_predicate = 6; } /* specify the language u use */ if (int_ops_for_predicate->size() == 0) { int_ops_for_predicate->push_back("VAR"); int_ops_for_predicate->push_back("NUM"); int_ops_for_predicate->push_back("PLUS"); //int_ops_for_predicate->push_back("MINUS"); int_ops_for_predicate->push_back("TIMES"); //int_ops_for_predicate->push_back("ITE"); } if (bool_ops_for_predicate->size() == 0) { bool_ops_for_predicate->push_back("F"); bool_ops_for_predicate->push_back("AND"); bool_ops_for_predicate->push_back("NOT"); bool_ops_for_predicate->push_back("LT"); } if (constants_in_predicate->size() == 0) { constants_in_predicate->push_back("0"); constants_in_predicate->push_back("1"); constants_in_predicate->push_back("2"); constants_in_predicate->push_back("3"); constants_in_predicate->push_back("5"); constants_in_predicate->push_back("7"); constants_in_predicate->push_back("11"); constants_in_predicate->push_back("13"); constants_in_predicate->push_back("17"); constants_in_predicate->push_back("19"); constants_in_predicate->push_back("23"); constants_in_predicate->push_back("29"); constants_in_predicate->push_back("31"); constants_in_predicate->push_back("41"); constants_in_predicate->push_back("43"); constants_in_predicate->push_back("47"); constants_in_predicate->push_back("53"); } if (*depth_bound_for_term == -1) { *depth_bound_for_term = 6; } if (int_ops_for_term->size() == 0) { int_ops_for_term->push_back("VAR"); int_ops_for_term->push_back("NUM"); int_ops_for_term->push_back("PLUS"); int_ops_for_term->push_back("TIMES"); //int_ops_for_term->push_back("MINUS"); //int_ops_for_term->push_back("ITE"); } if (constants_in_term->size() == 0) { constants_in_term->push_back("0"); constants_in_term->push_back("1"); constants_in_term->push_back("2"); constants_in_term->push_back("3"); constants_in_term->push_back("5"); constants_in_term->push_back("7"); constants_in_term->push_back("11"); constants_in_term->push_back("13"); constants_in_term->push_back("17"); constants_in_predicate->push_back("19"); constants_in_predicate->push_back("23"); constants_in_predicate->push_back("29"); constants_in_predicate->push_back("31"); constants_in_predicate->push_back("41"); constants_in_predicate->push_back("43"); constants_in_predicate->push_back("47"); constants_in_predicate->push_back("53"); } /* varables are extracted from inputoutput examples */ if (!input_outputs.empty()) { for (auto varValue : input_outputs[0]) { if (varValue.first != "_out") { vars_in_predicate->push_back(varValue.first); vars_in_term->push_back(varValue.first); } } } return; } void filterNonKeyIOEs(input_outputs_t* input_outputs) { // find the set of bound variables and values set<string> bound_vars; set<int> bound_value; for (auto ioe : *input_outputs) { for (auto [var, cnt] : ioe) { if (var.find("b") != string::npos) { bound_vars.insert(var); bound_value.insert(cnt); } } } map<int, int> bound_value_to_index; int index = 0; for (auto v : bound_value) { bound_value_to_index[v] = index; index++; } // replace bound variables from values to indices map<vector<int>, int> bound_space; int m = bound_vars.size(); for (auto ioe : *input_outputs) { vector<int> bound_vec; for (int i = 0; i < m; i++) { bound_vec.push_back(bound_value_to_index[ioe["b" + to_string(i)]]); } bound_space[bound_vec] = ioe["_out"]; } // mark non-key ioe in bound_space set<vector<int>> non_key_ioes; for (auto [vec0, value0] : bound_space) { int same_cnt = 0; for (auto [vec1, value1] : bound_space) { int distant = 0; for (int i = 0; i < vec0.size(); i++) { distant += (vec0[i] - vec1[i]) * (vec0[i] - vec1[i]); } if (distant == 1 && value0 != value1) same_cnt++; } if (same_cnt == 0) { non_key_ioes.insert(vec0); } } map<int, set<vector<int>>> reserved_ioes; auto it = input_outputs->begin(); while(it != input_outputs->end()) { auto ioe = *it; vector<int> bound_vec; for (int i = 0; i < m; i++) { bound_vec.push_back(bound_value_to_index[ioe["b" + to_string(i)]]); } if (find(non_key_ioes.begin(), non_key_ioes.end(), bound_vec) == non_key_ioes.end()) { //it = input_outputs->erase(it); //} else { reserved_ioes[ioe["_out"]].insert(bound_vec); } ++it; } for (auto [out, set_v] : reserved_ioes) { for (int i = 1; i < set_v.size()-1; i++) { auto v1 = *next(set_v.begin(), i-1); auto v2 = *next(set_v.begin(), i); auto v3 = *next(set_v.begin(), i+1); vector<int> diff_v1_v2; vector<int> diff_v2_v3; for (int j = 0; j < v1.size(); j++) { diff_v1_v2.push_back(v2[j]-v1[j]); } for (int j = 0; j < v2.size(); j++) { diff_v2_v3.push_back(v3[j]-v2[j]); } if (diff_v1_v2 == diff_v2_v3) { non_key_ioes.insert(v2); } } } //cout << bound_space.size() << " "; //cout << non_key_ioes.size() << endl; it = input_outputs->begin(); while(it != input_outputs->end()) { auto ioe = *it; vector<int> bound_vec; for (int i = 0; i < m; i++) { bound_vec.push_back(bound_value_to_index[ioe["b" + to_string(i)]]); } if (find(non_key_ioes.begin(), non_key_ioes.end(), bound_vec) != non_key_ioes.end()) { it = input_outputs->erase(it); } else { ++it; } } } bool readInputOutput(string file_name, input_outputs_t* input_outputs) { ifstream ifs; ifs.open(file_name, ifstream::in); string line; while (getline(ifs, line)) { input_output_t input_output; stringstream ss(line); string var; int value; while (ss >> var) { ss >> value; input_output[var] = value; } if (!input_output.empty()) { //input_output["_out"] /= 10; input_outputs->push_back(input_output); } } ifs.close(); //cout << "Resize IOE " << input_outputs->size() << " to "; filterNonKeyIOEs(input_outputs); //cout << input_outputs->size() << endl; return true; } void writeSearchedProgram(string file_name, string prog) { ofstream ofs; size_t pos = file_name.find("/ris_per_iter_refsrc/"); if (pos != string::npos) { pos = file_name.find_last_of("/"); string conf = file_name.substr(pos+1, file_name.size()); string header = file_name.substr(0, pos); pos = header.find_last_of("/"); file_name.replace(0, pos, "./synResult/"); file_name.replace(file_name.size() - 4, file_name.size(), "_src.txt"); ofs.open(file_name); if (ofs.is_open()) { ofs << conf << " " << prog; } ofs.close(); } return; } int main(int argc, char* argv[]) { if (argc < 2) { cout << "Error: command line options:" << endl; cout << " -FILE : specify path with the name of input-output-example file" << endl; cout << " Optional specification for predicate language" << endl; cout << " -DEPTHBOUNDPRED : specify the depth of a predicate program" << endl; cout << " -INTOPSPRED : specify the int ops for the predication language" << endl; cout << " -BOOLOPSPRED : specify the bool ops for the predication language" << endl; cout << " -VARSPRED : specify the variables allowed in the predication language" << endl; cout << " -CONSTANTSPRED : specify the constants allowed in the predication language" << endl; cout << " Optional specification for term language" << endl; cout << " -DEPTHBOUNDTERM : specify the depth of a term program" << endl; cout << " -INTOPSTERM : specify the int ops for the term language" << endl; cout << " -BOOLOPSTERM : specify the bool ops for the term language" << endl; cout << " -VARSTERM : specify the variables allowed in the term language" << endl; cout << " -CONSTANTSTERM : specify the constants allowed in the term language" << endl; cout << " Optional to specify the search time (default to 20 seconds)"<< endl; cout << " -SEARCHTIMEFORTERMSSINSECONDS : specify the search time for terms in seconds" << endl; cout << " -SEARCHTIMEFORPREDSINSECONDS : specify the search time for preds in seconds" << endl; cout << " Optional to sepcify the search rules to apply" << endl; cout << " -RULESTOAPPLY : specify search mode (SrcOnly, SrcEnhanced, SrcSnk)" << endl; return 0; } /* parse command line */ string file_name = ""; int depth_bound_for_predicate = -1; vector<string> int_ops_for_predicate; vector<string> bool_ops_for_predicate; vector<string> vars_in_predicate; vector<string> constants_in_predicate; int depth_bound_for_term = -1; vector<string> int_ops_for_term; vector<string> bool_ops_for_term; vector<string> vars_in_term; vector<string> constants_in_term; int search_time_for_terms_in_seconds = 20; int search_time_for_predicates_in_seconds = 20; vector<string> rules_to_apply; string bench_name = ""; int ref_id = 0; int num_growing_speed = 1; int num_growing_upperbound = 100; if ( parser(argc, argv, &file_name, &search_time_for_terms_in_seconds, &search_time_for_predicates_in_seconds, &depth_bound_for_predicate, &int_ops_for_predicate, &bool_ops_for_predicate, &vars_in_predicate, &constants_in_predicate, &depth_bound_for_term, &int_ops_for_term, &bool_ops_for_term, &vars_in_term, &constants_in_term, &rules_to_apply, &bench_name, &ref_id, &num_growing_speed, &num_growing_upperbound) == false ) { cout << "Error in parsing command lines" << endl; return 0; } /* read input output files */ input_outputs_t input_outputs; if (!readInputOutput(file_name, &input_outputs)) { cout << "Error reading files" << endl; return 0; } /* sample inputouput Files */ //sampler s(0.1); //input_outputs = s.randomSampling(input_outputs); #ifdef DEBUG if (rules_to_apply.empty()) { cout << "No mode specific rules specified" << endl; } else { cout << "Applying rules: " << endl; for (auto rule : rules_to_apply) { cout << rule << " "; } cout << endl; } #endif /* language configuration */ language_configuration(&depth_bound_for_predicate, &int_ops_for_predicate, &bool_ops_for_predicate, &vars_in_predicate, &constants_in_predicate, &depth_bound_for_term, &int_ops_for_term, &bool_ops_for_term, &vars_in_term, &constants_in_term, input_outputs); unification* uni = new unification(depth_bound_for_predicate, int_ops_for_predicate, bool_ops_for_predicate, vars_in_predicate, constants_in_predicate, depth_bound_for_term, int_ops_for_term, bool_ops_for_term, vars_in_term, constants_in_term, rules_to_apply, bench_name, ref_id, num_growing_speed, num_growing_upperbound, input_outputs); #ifdef DEBUG cout << "Search time: terms " << search_time_for_terms_in_seconds << " predications " << search_time_for_predicates_in_seconds << endl; uni->dump_language_defination(); #endif uni->search(search_time_for_terms_in_seconds, search_time_for_predicates_in_seconds); #ifdef DEBUG uni->dump_searched_program(); #endif //writeSearchedProgram(file_name, uni->getSearchedProgram()); uni->dump_searched_program(); return 0; }
35.828313
155
0.508239
[ "vector" ]
359f6dbe56a04e2764aef31c41bd96a70b36c071
12,085
cpp
C++
OculusPlayer/Renderer.cpp
AlloSphere-Research-Group/AlloStreamer
611f7db9c9e4aab3ca83ad62eec0a0c637e76119
[ "BSD-3-Clause" ]
5
2016-04-01T09:43:00.000Z
2019-06-09T19:04:18.000Z
OculusPlayer/Renderer.cpp
AlloSphere-Research-Group/AlloStreamer
611f7db9c9e4aab3ca83ad62eec0a0c637e76119
[ "BSD-3-Clause" ]
null
null
null
OculusPlayer/Renderer.cpp
AlloSphere-Research-Group/AlloStreamer
611f7db9c9e4aab3ca83ad62eec0a0c637e76119
[ "BSD-3-Clause" ]
3
2016-04-08T00:34:43.000Z
2019-11-15T19:21:13.000Z
#include "Renderer.hpp" // Include DirectX #include "Win32_DirectXAppUtil.h" // Include the Oculus SDK #define OVR_D3D_VERSION 11 #include "OVR_CAPI_D3D.h" using namespace OVR; Renderer::Renderer(CubemapSource* cubemapSource) : cubemapSource(cubemapSource), texture(nullptr) { OculusInit(); std::function<StereoCubemap* (CubemapSource*, StereoCubemap*)> callback = boost::bind(&Renderer::onNextCubemap, this, _1, _2); for (int i = 0; i < 1; i++) { cubemapPool.push(nullptr); } cubemapSource->setOnNextCubemap(callback); /*if (SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); abort(); } */ /*screen = SDL_CreateWindow("Windowed Player", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); if (!screen) { fprintf(stderr, "SDL: could not open window - exiting\n"); abort; }*/ /* //Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it window = SDL_CreateWindow("Hello World!", 100, 100, 500, 500, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); //Make sure creating our window went ok if (window == nullptr){ std::cerr << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; abort(); } //Create a renderer that will draw to the window, -1 specifies that we want to load whichever //video driver supports the flags we're passing //Flags: SDL_RENDERER_ACCELERATED: We want to use hardware accelerated rendering //SDL_RENDERER_PRESENTVSYNC: We want the renderer's present function (update screen) to be //synchornized with the monitor's refresh rate renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr){ SDL_DestroyWindow(window); std::cerr << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_Quit(); abort(); } //SDL 2.0 now uses textures to draw things but SDL_LoadBMP returns a surface //this lets us choose when to upload or remove textures from the GPU //std::string imagePath = getResourcePath("Lesson1") + "hello.bmp"; /*bmp = SDL_LoadBMP(imagePath.c_str()); if (bmp == nullptr){ SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl; SDL_Quit(); abort(); }*/ } Renderer::~Renderer() { cubemapBuffer.close(); cubemapPool.close(); renderThread.join(); //Clean up our objects and quit //for (SDL_Texture* texture : textures) //{ SDL_DestroyTexture(texture); //} SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); OculusRelease(); } StereoCubemap* Renderer::onNextCubemap(CubemapSource* source, StereoCubemap* cubemap) { StereoCubemap* oldCubemap; if (!cubemapPool.try_pop(oldCubemap)) { if (cubemapPool.closed()) { return nullptr; } else { return cubemap; } } cubemapBuffer.push(cubemap); return oldCubemap; } void Renderer::setOnDisplayedFrame(const std::function<void (Renderer*)>& callback) { onDisplayedFrame = callback; } void Renderer::setOnDisplayedCubemapFace(const std::function<void (Renderer*, int)>& callback) { onDisplayedCubemapFace = callback; } void Renderer::OculusInit(){ hinst = (HINSTANCE)GetModuleHandle(NULL); // Initializes LibOVR, and the Rift ovrResult result = ovr_Initialize(nullptr); VALIDATE(OVR_SUCCESS(result), "Failed to initialize libOVR."); ovrResult actualHMD = ovrHmd_Create(0, &HMD); if (!OVR_SUCCESS(actualHMD)) result = ovrHmd_CreateDebug(ovrHmd_DK2, &HMD); // Use debug one, if no genuine Rift available VALIDATE(OVR_SUCCESS(result), "Oculus Rift not detected."); VALIDATE(HMD->ProductName[0] != '\0', "Rift detected, display not enabled."); // Setup Window and Graphics // Note: the mirror window can be any size, for this sample we use 1/2 the HMD resolution ovrSizei winSize = { HMD->Resolution.w / 2, HMD->Resolution.h / 2 }; bool initialized = DIRECTX.InitWindowAndDevice(hinst, Recti(Vector2i(0), winSize), L"OculusPlayer (DX11)"); VALIDATE(initialized, "Unable to initialize window and D3D11 device."); ovrHmd_SetEnabledCaps(HMD, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion result = ovrHmd_ConfigureTracking(HMD, ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, 0); VALIDATE(!OVR_SUCCESS(actualHMD) || OVR_SUCCESS(result), "Failed to configure tracking."); // Make the eye render buffers (caution if actual size < requested due to HW limits). for (int eye = 0; eye < 2; eye++) { Sizei idealSize = ovrHmd_GetFovTextureSize(HMD, (ovrEyeType)eye, HMD->DefaultEyeFov[eye], 1.0f); pEyeRenderTexture[eye] = new OculusTexture(HMD, idealSize); pEyeDepthBuffer[eye] = new DepthBuffer(DIRECTX.Device, idealSize); eyeRenderViewport[eye].Pos = Vector2i(0, 0); eyeRenderViewport[eye].Size = idealSize; } // Create a mirror to see on the monitor. mirrorTexture = nullptr; D3D11_TEXTURE2D_DESC td = {}; td.ArraySize = 1; td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; td.Width = DIRECTX.WinSize.w; td.Height = DIRECTX.WinSize.h; td.Usage = D3D11_USAGE_DEFAULT; td.SampleDesc.Count = 1; td.MipLevels = 1; ovrHmd_CreateMirrorTextureD3D11(HMD, DIRECTX.Device, &td, &mirrorTexture); // Create the room model scene = new Scene(1024,1024); // Create camera mainCam=Camera(Vector3f(0.0f, 0.0f, 0.0f), Matrix4f::RotationY(0.0f)); // Setup VR components, filling out description eyeRenderDesc[0] = ovrHmd_GetRenderDesc(HMD, ovrEye_Left, HMD->DefaultEyeFov[0]); eyeRenderDesc[1] = ovrHmd_GetRenderDesc(HMD, ovrEye_Right, HMD->DefaultEyeFov[1]); bool isVisible = true; } void Renderer::OculusRender(){ // Keyboard inputs to adjust player orientation, unaffected by speed static float Yaw = 3.141f; if (DIRECTX.Key[VK_LEFT]) mainCam.Rot = Matrix4f::RotationY(Yaw += 0.02f); if (DIRECTX.Key[VK_RIGHT]) mainCam.Rot = Matrix4f::RotationY(Yaw -= 0.02f); // Keyboard inputs to adjust player position if (DIRECTX.Key['W'] || DIRECTX.Key[VK_UP]) mainCam.Pos += mainCam.Rot.Transform(Vector3f(0, 0, -0.05f)); if (DIRECTX.Key['S'] || DIRECTX.Key[VK_DOWN]) mainCam.Pos += mainCam.Rot.Transform(Vector3f(0, 0, +0.05f)); if (DIRECTX.Key['D']) mainCam.Pos += mainCam.Rot.Transform(Vector3f(+0.05f, 0, 0)); if (DIRECTX.Key['A']) mainCam.Pos += mainCam.Rot.Transform(Vector3f(-0.05f, 0, 0)); mainCam.Pos.y = ovrHmd_GetFloat(HMD, OVR_KEY_EYE_HEIGHT, 0); // Animate the cube static float cubeClock = 0; //roomScene.Models[0]->Pos = Vector3f(9 * sin(cubeClock), 3, 9 * cos(cubeClock+=0.015f)); // Get both eye poses simultaneously, with IPD offset already included. ovrPosef EyeRenderPose[2]; ovrVector3f HmdToEyeViewOffset[2] = { eyeRenderDesc[0].HmdToEyeViewOffset, eyeRenderDesc[1].HmdToEyeViewOffset }; ovrFrameTiming ftiming = ovrHmd_GetFrameTiming(HMD, 0); ovrTrackingState hmdState = ovrHmd_GetTrackingState(HMD, ftiming.DisplayMidpointSeconds); ovr_CalcEyePoses(hmdState.HeadPose.ThePose, HmdToEyeViewOffset, EyeRenderPose); // Render Scene to Eye Buffers for (int eye = 0; eye < 2; eye++) { // Increment to use next texture, just before writing pEyeRenderTexture[eye]->AdvanceToNextTexture(); // Clear and set up rendertarget int texIndex = pEyeRenderTexture[eye]->TextureSet->CurrentIndex; DIRECTX.SetAndClearRenderTarget(pEyeRenderTexture[eye]->TexRtv[texIndex], pEyeDepthBuffer[eye]); DIRECTX.SetViewport(Recti(eyeRenderViewport[eye])); // Get view and projection matrices for the Rift camera Camera finalCam(mainCam.Pos + mainCam.Rot.Transform(EyeRenderPose[eye].Position), mainCam.Rot * Matrix4f(EyeRenderPose[eye].Orientation)); Matrix4f view = finalCam.GetViewMatrix(); Matrix4f proj = ovrMatrix4f_Projection(eyeRenderDesc[eye].Fov, 0.2f, 1000.0f, ovrProjection_RightHanded); // Render the scene scene->Render(eye,proj*view, 1, 1, 1, 1, true); } // Initialize our single full screen Fov layer. ovrLayerEyeFov ld; ld.Header.Type = ovrLayerType_EyeFov; ld.Header.Flags = 0; for (int eye = 0; eye < 2; eye++) { ld.ColorTexture[eye] = pEyeRenderTexture[eye]->TextureSet; ld.Viewport[eye] = eyeRenderViewport[eye]; ld.Fov[eye] = HMD->DefaultEyeFov[eye]; ld.RenderPose[eye] = EyeRenderPose[eye]; } // Set up positional data. ovrViewScaleDesc viewScaleDesc; viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1.0f; viewScaleDesc.HmdToEyeViewOffset[0] = HmdToEyeViewOffset[0]; viewScaleDesc.HmdToEyeViewOffset[1] = HmdToEyeViewOffset[1]; ovrLayerHeader* layers = &ld.Header; ovrResult result = ovrHmd_SubmitFrame(HMD, 0, &viewScaleDesc, &layers, 1); // Render mirror ovrD3D11Texture* tex = (ovrD3D11Texture*)mirrorTexture; DIRECTX.Context->CopyResource(DIRECTX.BackBuffer, tex->D3D11.pTexture); DIRECTX.SwapChain->Present(0, 0); } void Renderer::OculusRelease(){ // Release ovrHmd_DestroyMirrorTexture(HMD, mirrorTexture); pEyeRenderTexture[0]->Release(HMD); pEyeRenderTexture[1]->Release(HMD); ovrHmd_Destroy(HMD); ovr_Shutdown(); DIRECTX.ReleaseWindow(hinst); } void Renderer::start() { renderThread = boost::thread(boost::bind(&Renderer::renderLoop, this)); SDL_Event evt; while (true) { SDL_WaitEvent(&evt); if (evt.type == SDL_QUIT) { return; } } } void Renderer::renderLoop() { static int counter = 0; while (true) { StereoCubemap* cubemap; if (!cubemapBuffer.wait_and_pop(cubemap)) { return; } //Frame* content = cubemap->getEye(0)->getFace(0)->getContent(); void *pixels[12]; for (int i = 0; i < 12; i++) pixels[i] = NULL; UINT w = cubemap->getEye(0)->getFace(0)->getContent()->getWidth(), h = cubemap->getEye(0)->getFace(0)->getContent()->getWidth(); if (scene->Width != w){ scene = new Scene(w,h); std::cout << "New resolution: " << scene->Width << std::endl; } for (int e = 0; e < cubemap->getEyesCount(); e++){ for (int i = 0; i < cubemap->getEye(e)->getFacesCount(); i++){ pixels[i + 6 * e] = cubemap->getEye(e)->getFace(i)->getContent()->getPixels(); } } scene->updateTextures(pixels, w, h); OculusRender(); /* if (!texture) { //To use a hardware accelerated texture for rendering we can create one from //the surface we loaded texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_BGRA8888, SDL_TEXTUREACCESS_STREAMING, content->getWidth(), content->getHeight()); //We no longer need the surface //SDL_FreeSurface(bmp); if (texture == nullptr){ SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); std::cerr << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl; SDL_Quit(); abort(); } } // Show cubemap //A sleepy rendering loop, wait for 3 seconds and render and present the screen each time //for (int i = 0; i < 3; ++i){ if (counter % 5 == 0) { void* pixels; int pitch; if (SDL_LockTexture(texture, NULL, &pixels, &pitch) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't lock texture: %s\n", SDL_GetError()); SDL_Quit(); abort(); } memcpy(pixels, content->getPixels(), content->getHeight() * content->getWidth() * 4); SDL_UnlockTexture(texture); //First clear the renderer SDL_RenderClear(renderer); //Draw the texture SDL_RenderCopy(renderer, texture, NULL, NULL); //Update the screen SDL_RenderPresent(renderer); //Take a quick break after all that hard work //SDL_Delay(1000); //} if (onDisplayedCubemapFace) onDisplayedCubemapFace(this, 0); if (onDisplayedFrame) onDisplayedFrame(this); } */ if (counter % 1 == 0) if (onDisplayedFrame) onDisplayedFrame(this); cubemapPool.push(cubemap); counter++; } }
30.440806
139
0.691105
[ "render", "model", "transform" ]
35a590ee9aaf32e3c981d934ef85b606bda99a50
24,473
hpp
C++
inc/dcs/system/posix_process.hpp
sguazt/dcsxx-commons
0fc1fd8a38b7c412941b401c00a9293bc5df8b21
[ "Apache-2.0" ]
null
null
null
inc/dcs/system/posix_process.hpp
sguazt/dcsxx-commons
0fc1fd8a38b7c412941b401c00a9293bc5df8b21
[ "Apache-2.0" ]
null
null
null
inc/dcs/system/posix_process.hpp
sguazt/dcsxx-commons
0fc1fd8a38b7c412941b401c00a9293bc5df8b21
[ "Apache-2.0" ]
null
null
null
/** * \file dcs/system/posix_process.hpp * * \brief Class to create and manage a process in POSIX-compliant systems. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DCS_SYSTEM_POSIX_PROCESS_HPP #define DCS_SYSTEM_POSIX_PROCESS_HPP //TODO: How to check for a POSIX-compliant system? // //FIXME: It seems this is not the best way to check for a POSIX-compliant system //#if _POSIX_C_SOURCE < 1 && !_XOPEN_SOURCE && !_POSIX_SOURCE //# error "Unable to find a POSIX compliant system." //#endif // _POSIX_C_SOURCE #include <boost/smart_ptr.hpp> #include <boost/utility.hpp> #include <cerrno> #include <cstddef> #include <cstdlib> #include <cstring> #include <dcs/assert.hpp> #include <dcs/debug.hpp> #include <dcs/exception.hpp> #include <dcs/logging.hpp> #include <dcs/system/process_status_category.hpp> #ifdef __GNUC__ # include <ext/stdio_filebuf.h> #else // __GNUC__ # include <boost/iostreams/device/file_descriptor.hpp> # include <boost/iostreams/stream_buffer.hpp> #endif // __GNUC__ #include <fcntl.h> #include <iterator> #include <sstream> #include <stdexcept> #include <string> #include <sys/resource.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <vector> namespace dcs { namespace system { class posix_process: private ::boost::noncopyable { private: typedef posix_process self_type; #ifdef __GNUC__ private: typedef ::__gnu_cxx::stdio_filebuf<char> fd_streambuf_type; #else // __GNUC__ private: typedef ::boost::iostreams::file_descriptor_source fd_device_type; private: typedef ::boost::iostreams::stream_buffer<fd_device_type> fd_streambuf_type; #endif // __GNUC__ public: typedef ::pid_t pid_type; public: static const pid_type invalid_pid = -1; private: static const unsigned int zzz_secs = 5; public: explicit posix_process() : cmd_(), async_(true), pid_(invalid_pid), status_(undefined_process_status), sig_(-1), exit_status_(EXIT_SUCCESS) { } public: explicit posix_process(::std::string const& cmd) : cmd_(cmd), // args_(), async_(true), pid_(invalid_pid), status_(undefined_process_status), sig_(-1), exit_status_(EXIT_SUCCESS) { } // public: template <typename FwdIterT> // posix_process(::std::string const& cmd, FwdIterT arg_first, FwdIterT arg_last) // : cmd_(cmd), // args_(arg_first, arg_last), // async_(false), // status_(undefined_status), // sig_(-1), // exit_status_(EXIT_SUCCESS) // { // } public: ~posix_process() { // Wait for child termination to prevent zombies try { if (this->alive()) { this->wait(); } } catch (::std::exception const& e) { ::std::ostringstream oss; oss << "Failed to wait for command '" << cmd_ << "': " << e.what(); dcs::log_error(DCS_LOGGING_AT, oss.str()); } catch (...) { ::std::ostringstream oss; oss << "Failed to wait for command '" << cmd_ << "': Unknown reason"; dcs::log_error(DCS_LOGGING_AT, oss.str()); } } public: void command(::std::string const& cmd) { cmd_ = cmd; } /// Returns the command name (without arguments). public: ::std::string command() const { return cmd_; } /** * \brief Allows to set if the execution of this process will block * (\c false value) or not (\c true value) the parent process. */ public: void asynch(bool val) { async_ = val; } /** * \brief Tells if the execution of this process will block (\c false value) * or not (\c true value) the parent process. */ public: bool asynch() const { return async_; } /// Returns the identifier of this process. public: pid_type pid() const { return pid_; } /// Returns the stream connected to the standard input of this process. public: ::std::ostream& input_stream() { // pre: not null DCS_ASSERT(p_ios_, DCS_EXCEPTION_THROW(::std::runtime_error, "Invalid pointer to input stream")); return *p_ios_; } /// Returns the stream connected to the standard input of this process. public: ::std::ostream const& input_stream() const { // pre: not null DCS_ASSERT(p_ios_, DCS_EXCEPTION_THROW(::std::runtime_error, "Invalid pointer to input stream")); return *p_ios_; } /// Returns the stream connected to the standard output of this process. public: ::std::istream& output_stream() { // pre: not null DCS_ASSERT(p_ois_, DCS_EXCEPTION_THROW(::std::runtime_error, "Invalid pointer to output stream")); return *p_ois_; } /// Returns the stream connected to the standard output of this process. public: ::std::istream const& output_stream() const { // pre: not null DCS_ASSERT(p_ois_, DCS_EXCEPTION_THROW(::std::runtime_error, "Invalid pointer to output stream")); return *p_ois_; } /// Returns the stream connected to the standard error of this process. public: ::std::istream& error_stream() { // pre: not null DCS_ASSERT(p_eis_, DCS_EXCEPTION_THROW(::std::runtime_error, "Invalid pointer to error stream")); return *p_eis_; } /// Returns the stream connected to the standard error of this process. public: ::std::istream const& error_stream() const { // pre: not null DCS_ASSERT(p_eis_, DCS_EXCEPTION_THROW(::std::runtime_error, "Invalid pointer to error stream")); return *p_eis_; } /** * \brief Runs this process (without arguments and without connecting to the * standard input/output/error). */ public: void run() { ::std::vector< ::std::string > args; run(args.begin(), args.end()); } /** * \brief Runs this process with the given argument and optionally by * connecting to the standard input/output/error. */ public: template <typename FwdIterT> void run(FwdIterT arg_first, FwdIterT arg_last, bool pipe_in = false, bool pipe_out = false, bool pipe_err = false) { const ::std::size_t pipe_in_child_rd(0); const ::std::size_t pipe_in_parent_wr(1); const ::std::size_t pipe_out_parent_rd(2); const ::std::size_t pipe_out_child_wr(3); const ::std::size_t pipe_err_parent_rd(4); const ::std::size_t pipe_err_child_wr(5); // Create two pipes to let to communicate with AMPL. // Specifically, we want to write the input into AMPL (through the producer) // and to read the output from AMPL (through the consumer). // So, the child process read its input from the parent and write its output on // the pipe; while the parent write the child's input on the pipe and read its // input from the child. // // pipefd: // - [0,1]: Where the parent write to and the child read from (child's stdin). // - [2,3]: Where the parent read from and the child write to (child's stdout). // - [4,5]: Where the parent read from and the child write to (child's stderr). int pipefd[6]; if (pipe_in) { if (::pipe(&pipefd[0]) == -1) { ::std::ostringstream oss; oss << "Call to pipe(2) failed for command: '" << cmd_ << "' and for input production: " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } } if (pipe_out) { if (::pipe(&pipefd[2]) == -1) { ::std::ostringstream oss; oss << "Call to pipe(2) failed for command: '" << cmd_ << "' and for output consumption: " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } } if (pipe_err) { if (::pipe(&pipefd[4]) == -1) { ::std::ostringstream oss; oss << "Call to pipe(2) failed for command: '" << cmd_ << "' and for error consumption: " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } } // Spawn a new process // Between fork() and execve() only async-signal-safe functions // must be called if multithreaded applications should be supported. // That's why the following code is executed before fork() is called. pid_type pid = ::fork(); if (pid == invalid_pid) { ::std::ostringstream oss; oss << "Call to fork(2) failed for command '" << cmd_ << "': " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } if (pid == 0) { // The child // Get the maximum number of files this process is allowed to open #if defined(F_MAXFD) int maxdescs = ::fcntl(-1, F_MAXFD, 0); if (maxdescs == -1) { # if defined(_SC_OPEN_MAX) maxdescs = ::sysconf(_SC_OPEN_MAX); # else // _SC_OPEN_MAX ::rlimit limit; if (::getrlimit(RLIMIT_NOFILE, &limit) < 0) { ::std::ostringstream oss; oss << "Call to getrlimit(2) failed for command '" << cmd_ << "': " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } maxdescs = limit.rlim_cur; # endif // _SC_OPEN_MAX } #else // F_MAXFD # if defined(_SC_OPEN_MAX) int maxdescs = ::sysconf(_SC_OPEN_MAX); # else // _SC_OPEN_MAX ::rlimit limit; if (::getrlimit(RLIMIT_NOFILE, &limit) < 0) { ::std::ostringstream oss; oss << "Call to getrlimit(2) failed for command '" << cmd_ << "': " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } maxdescs = limit.rlim_cur; # endif // _SC_OPEN_MAX #endif // F_MAXFD if (maxdescs == -1) { maxdescs = 1024; } ::std::vector<bool> close_fd(maxdescs, true); // Associate the child's stdin/stdout to the pipe read/write fds. close_fd[STDIN_FILENO] = false; close_fd[STDOUT_FILENO] = false; #ifdef DCS_DEBUG // Keep standard error open for debug close_fd[STDERR_FILENO] = false; #endif // DCS_DEBUG if (pipe_in) { if (pipefd[pipe_in_child_rd] != STDIN_FILENO) { if (::dup2(pipefd[pipe_in_child_rd], STDIN_FILENO) != STDIN_FILENO) { ::std::ostringstream oss; oss << "Call to dup2(2) failed for command '" << cmd_ << "' during connection to standard input: " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } } else { if (STDIN_FILENO < maxdescs) { close_fd[STDIN_FILENO] = false; } else { ::close(STDIN_FILENO); } } } if (pipe_out) { if (pipefd[pipe_out_child_wr] != STDOUT_FILENO) { if (::dup2(pipefd[pipe_out_child_wr], STDOUT_FILENO) != STDOUT_FILENO) { ::std::ostringstream oss; oss << "Call to dup2(2) failed for command '" << cmd_ << "' during connection to standard output: " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } } else { if (STDOUT_FILENO < maxdescs) { close_fd[STDOUT_FILENO] = false; } else { ::close(STDOUT_FILENO); } } } if (pipe_err) { if (pipefd[pipe_err_child_wr] != STDERR_FILENO) { if (::dup2(pipefd[pipe_err_child_wr], STDERR_FILENO) != STDERR_FILENO) { ::std::ostringstream oss; oss << "Call to dup2(2) failed for command '" << cmd_ << "' during connection to standard error: " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } } else { if (STDERR_FILENO < maxdescs) { close_fd[STDERR_FILENO] = false; } else { ::close(STDERR_FILENO); } } } // Check if the command already has path information ::std::string cmd_path; ::std::string cmd_name; typename ::std::string::size_type pos; pos = cmd_.find_last_of('/'); if (pos != ::std::string::npos) { cmd_path = cmd_.substr(0, pos); cmd_name = cmd_.substr(pos+1); } // Populate the argument list ::std::size_t nargs = ::std::distance(arg_first, arg_last)+2; char** argv = new char*[nargs]; argv[0] = new char[cmd_name.size()+1]; ::std::strncpy(argv[0], cmd_name.c_str(), cmd_name.size()+1); // by convention, the first argument is always the command name ::std::size_t i(1); while (arg_first != arg_last) { argv[i] = new char[arg_first->size()+1]; ::std::strncpy(argv[i], arg_first->c_str(), arg_first->size()+1); ++arg_first; ++i; } argv[i] = 0; // The array of pointers must be terminated by a NULL pointer. // Close unused file descriptors for (int fd = 0; fd < maxdescs; ++fd) { if (close_fd[fd]) { ::close(fd); } } // Run the command DCS_DEBUG_TRACE("Going to run: " << cmd_ << ::dcs::debug::to_string(argv, argv+nargs-1) ); ::execvp(cmd_.c_str(), argv); // Actually we should delete argv and envp data. As we must not // call any non-async-signal-safe functions though we simply exit. ::std::ostringstream oss; oss << "Call to execvp(3) failed for command '" << cmd_ << "': " << ::strerror(errno) << ::std::endl; ::std::size_t count(oss.str().size()); count = ::write(STDERR_FILENO, oss.str().c_str(), count); ::_exit(EXIT_FAILURE); } // The parent if (pipe_in) { ::close(pipefd[pipe_in_child_rd]); #ifdef __GNUC__ p_in_wrbuf_ = ::boost::make_shared<fd_streambuf_type>(pipefd[pipe_in_parent_wr], ::std::ios::out); #else // __GNUC__ fd_device_type in_wrdev(pipefd[pipe_in_parent_wr], ::boost::iostreams::close_handle); p_in_wrbuf_ = ::boost::make_shared<fd_streambuf_type>(in_wrdev); #endif // __GNUC__ p_ios_ = ::boost::make_shared< ::std::ostream >(p_in_wrbuf_.get()); } if (pipe_out) { ::close(pipefd[pipe_out_child_wr]); #ifdef __GNUC__ p_out_rdbuf_ = ::boost::make_shared<fd_streambuf_type>(pipefd[pipe_out_parent_rd], ::std::ios::in); #else // __GNUC__ fd_device_type out_rddev(pipefd[pipe_out_parent_rd], ::boost::iostreams::close_handle); p_out_rdbuf_ = ::boost::make_shared<fd_streambuf_type>(out_rddev); #endif // __GNUC__ p_ois_ = ::boost::make_shared< ::std::istream >(p_out_rdbuf_.get()); } if (pipe_err) { ::close(pipefd[pipe_err_child_wr]); #ifdef __GNUC__ p_err_rdbuf_ = ::boost::make_shared<fd_streambuf_type>(pipefd[pipe_err_parent_rd], ::std::ios::in); #else // __GNUC__ fd_device_type err_rddev(pipefd[pipe_err_parent_rd], ::boost::iostreams::close_handle); p_err_rdbuf_ = ::boost::make_shared<fd_streambuf_type>(err_rddev); #endif // __GNUC__ p_eis_ = ::boost::make_shared< ::std::istream >(p_err_rdbuf_.get()); } // Write to the child process // producer(os); // Read the input from the child process // consumer(is); pid_ = pid; status_ = running_process_status; if (!async_) { this->wait(); } } /// Waits for the termination of this process. public: void wait() { if (status_ == terminated_process_status || status_ == aborted_process_status || status_ == failed_process_status) { return; } this->true_wait(true); status_ = terminated_process_status; } /// Returns the life status of this process. public: process_status_category status() const { return status_; } /// Stops the execution of this process (without terminating it). public: void stop() { // pre: process must be running DCS_ASSERT(status_ == running_process_status, DCS_EXCEPTION_THROW(::std::runtime_error, "Cannot stop a process that is not running")); this->signal(SIGSTOP); } /// Resumes the execution of this stopped process. public: void resume() { // pre: process must have been stopped DCS_ASSERT(status_ == stopped_process_status, DCS_EXCEPTION_THROW(::std::runtime_error, "Cannot resume a process that has not been stopped")); this->signal(SIGCONT); } /// Terminates the execution of this process public: void terminate(bool force = false) { if (!this->alive()) { return; } this->signal(SIGTERM); if (force && this->alive()) { this->signal(SIGKILL); } } /// Tells if this process is still running. public: bool alive() const { // Quick test: return FALSE is the process has already terminated if (pid_ == invalid_pid) { return false; } const_cast<self_type*>(this)->true_wait(false); if (pid_ == invalid_pid) { return false; } return (pid_ == invalid_pid) ? false : true; } /// Sends signal \a sig to this process. public: void signal(int sig) { // pre: sig >= 0 DCS_ASSERT(sig >= 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid signal number")); if (!this->alive()) { return; } // signal 0 has a special meaning: it can be used to check if a process // exists without actually sending any signal to it. // To send such a signal, use method \c alive. if (sig == 0) { //this->alive(); sig_ = 0; return; } if (::kill(pid_, sig) == -1) { ::std::ostringstream oss; oss << "Call to kill(2) failed for command '" << cmd_ << "' and signal " << sig << ": " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } sig_ = sig; bool check_alive(false); switch (sig) { case SIGCONT: status_ = resumed_process_status; break; case SIGSTOP: status_ = stopped_process_status; break; case SIGTERM: case SIGKILL: case SIGINT: default: check_alive = true; break; } if (check_alive) { const ::std::size_t num_trials(5); bool is_alive(true); for (::std::size_t trial = 0; trial < num_trials && is_alive; ++trial) { is_alive = this->alive(); if (is_alive) { ::sleep(zzz_secs); } } if (!is_alive) { status_ = aborted_process_status; } else { //FIXME: What we can do? ::std::ostringstream oss; oss << "Command '" << cmd_ << "' signaled with signal '" << sig_ << "' is still alive"; dcs::log_warn(DCS_LOGGING_AT, oss.str()); } } } /// Waits for the termination of this process. private: void true_wait(bool block) { int wstatus; int opts(WUNTRACED | WCONTINUED); if (!block) { opts |= WNOHANG; } // Loop until errno!=EINTR => WNOHANG was not set and an unblocked signal or a SIGCHLD was caught (see signal(7)). do { if (::waitpid(pid_, &wstatus, opts) == -1) { ::std::ostringstream oss; oss << "Call to waitpid(2) failed for command '" << cmd_ << "': " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } } while (errno == EINTR); if (!block) { // Check if the process is still alive. // If it is, return without changing the state of process; otherwise, change the state according to the way the process has terminated. // NOTE: if kill(...)==-1 AND errno==ESRCH => The pid does not exist (see kill(2)) int ret = ::kill(pid_, 0); if (ret != -1) { // The process is still alive return; } if (errno != ESRCH) { // The call to kill failed for some reason ::std::ostringstream oss; oss << "Call to kill(2) failed for command '" << cmd_ << "' and signal 0: " << ::strerror(errno); DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); } } // At this point, we are sure that the process is done pid_ = invalid_pid; if (WIFEXITED(wstatus)) { exit_status_ = WEXITSTATUS(wstatus); if (exit_status_ != EXIT_SUCCESS) { status_ = failed_process_status; ::std::ostringstream oss; oss << "Command '" << cmd_ << "' exited with status: " << exit_status_; dcs::log_warn(DCS_LOGGING_AT, oss.str()); } else { status_ = terminated_process_status; } } else if (WIFSTOPPED(wstatus)) { status_ = stopped_process_status; sig_ = WSTOPSIG(wstatus); } else if (WIFCONTINUED(wstatus)) { status_ = resumed_process_status; } else if (WIFSIGNALED(wstatus)) { sig_ = WTERMSIG(wstatus); status_ = aborted_process_status; ::std::ostringstream oss; oss << "Command '" << cmd_ << "' signaled with signal: " << sig_; dcs::log_warn(DCS_LOGGING_AT, oss.str()); } else { status_ = aborted_process_status; ::std::ostringstream oss; oss << "Command '" << cmd_ << "' failed for an unknown reason"; dcs::log_error(DCS_LOGGING_AT, oss.str()); } //FIXME: should we take care of connected streams? // 1st solution: connect open streams to /dev/null or /dev/zero // 2nd solution: set the EOF state of each open stream // 1st solution (commented) #if 0 // Invalidate connected streams if (p_ios_) { // Redirect writes to /dev/null int fd = open("/dev/null", O_WRONLY); #ifdef __GNUC__ p_in_wrbuf_ = ::boost::make_shared<fd_streambuf_type>(fd, ::std::ios::out); #else // __GNUC__ fd_device_type in_wrdev(fd, ::boost::iostreams::close_handle); p_in_wrbuf_ = ::boost::make_shared<fd_streambuf_type>(in_wrdev); #endif // __GNUC__ p_ios_->rdbuf(p_in_wrbuf_.get()); } if (p_ois_) { // Redirect reads from /dev/zero int fd = open("/dev/zero", O_RDONLY); #ifdef __GNUC__ p_out_rdbuf_ = ::boost::make_shared<fd_streambuf_type>(fd, ::std::ios::in); #else // __GNUC__ fd_device_type out_rddev(fd, ::boost::iostreams::close_handle); p_out_rdbuf_ = ::boost::make_shared<fd_streambuf_type>(out_rddev); #endif // __GNUC__ p_ois_->rdbuf(p_out_rdbuf_.get()); } if (p_eis_) { // Redirect reads from /dev/zero int fd = open("/dev/zero", O_RDONLY); #ifdef __GNUC__ p_err_rdbuf_ = ::boost::make_shared<fd_streambuf_type>(fd, ::std::ios::in); #else // __GNUC__ fd_device_type err_rddev(fd, ::boost::iostreams::close_handle); p_err_rdbuf_ = ::boost::make_shared<fd_streambuf_type>(err_rddev); #endif // __GNUC__ p_eis_->rdbuf(p_err_rdbuf_.get()); } #endif // if 0 // 2nd solution if (p_ios_) { p_ios_->setstate(p_ios_->rdstate() | ::std::ios_base::eofbit); } if (p_ois_) { p_ois_->setstate(p_ois_->rdstate() | ::std::ios_base::eofbit); } if (p_eis_) { p_eis_->setstate(p_eis_->rdstate() | ::std::ios_base::eofbit); } } // /// Tells if this process is still alive. // private: bool true_alive() const // { // // Make sure to remove a <defunct> process, in order to avoid // // false-positives (i.e., a call to kill(2) which return -1 with // // errno==ESRCH due to the presence of a <defunct> process). // this->true_wait(false); // // // From kill(2) man page: // // "...If sig is 0, then no signal is sent, but error checking is still // // performed; this can be used to check for the existence of a process // // ID or process group ID..." // // if (::kill(pid_, 0) == -1) // { // // Note: if errno == ESRCH => The pid does not exist (see kill(2)) // if (errno != ESRCH) // { // ::std::ostringstream oss; // oss << "Call to kill(2) failed for command '" << cmd_ << "' and signal 0: " << ::strerror(errno); // // DCS_EXCEPTION_THROW(::std::runtime_error, oss.str()); // } // //// // Set the status to a termination status. It will possibly changed //// // by some higher-level function (e.g., signal) //// status_ = terminated_process_status; //// pid_ = invalid_pid; //// //exit_status_ = ???; //FIXME // // return false; // } // if (pid_ == invalid_pid) // { // return false; // } // // return true; // } private: ::std::string cmd_; ///< The command path // private: ::std::vector< ::std::string > args_; ///< The list of command arguments private: bool async_; ///< A \c true value means that the parent does not block to wait for child termination private: pid_type pid_; ///< The process identifier private: process_status_category status_; ///< The current status of this process private: int sig_; ///< The last signal sent to this process private: int exit_status_; ///< The exit status of this process private: ::boost::shared_ptr<fd_streambuf_type> p_in_wrbuf_; private: ::boost::shared_ptr<fd_streambuf_type> p_out_rdbuf_; private: ::boost::shared_ptr<fd_streambuf_type> p_err_rdbuf_; private: ::boost::shared_ptr< ::std::ostream > p_ios_; private: ::boost::shared_ptr< ::std::istream > p_ois_; private: ::boost::shared_ptr< ::std::istream > p_eis_; }; // posix_process }} // Namespace dcs::system #endif // DCS_SYSTEM_POSIX_PROCESS_HPP
26.805038
138
0.647285
[ "vector" ]
35a8d0418d9fbccaccb2e21a6f5eb8ebaa2a1f81
1,430
hpp
C++
src/dialog.hpp
cbeck88/HexWarfare
94a70b1889afc2fbd990892ed66be874ac70d1b4
[ "Apache-2.0" ]
null
null
null
src/dialog.hpp
cbeck88/HexWarfare
94a70b1889afc2fbd990892ed66be874ac70d1b4
[ "Apache-2.0" ]
null
null
null
src/dialog.hpp
cbeck88/HexWarfare
94a70b1889afc2fbd990892ed66be874ac70d1b4
[ "Apache-2.0" ]
null
null
null
/* Copyright 2014 Kristina Simpson <sweet.kristas@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "widget.hpp" namespace gui { enum class BackgroundSections { CORNER_TL, CORNER_TR, CORNER_BL, CORNER_BR, SIDE_LEFT, SIDE_RIGHT, SIDE_TOP, SIDE_BOTTOM, CENTER, MAX }; class dialog : public widget { public: MAKE_FACTORY(dialog); void close(); void add_widget(widget_ptr w); private: explicit dialog(const rectf& pos, Justify justify); virtual bool handle_events(SDL_Event* evt, bool claimed) override; void handle_draw(const rect& r, float rotation, float scale) const override; void handle_update(const engine& eng, double t) override; void handle_init() override; void recalc_dimensions() override; void handle_window_resize(int w, int h); std::vector<graphics::texture> bg_; std::vector<widget_ptr> children_; bool is_open_; }; }
25.535714
78
0.737063
[ "vector" ]
35b9b5847ca0336721330a13a4fa7db36de5adc7
2,135
cpp
C++
MainWindow.cpp
jplflyer/qt-TreeViewDemo
a3e74d410a3e6e4512377755de5f29a34f963cd5
[ "Unlicense" ]
3
2019-08-16T03:43:23.000Z
2020-12-30T03:26:36.000Z
MainWindow.cpp
jplflyer/qt-TreeViewDemo
a3e74d410a3e6e4512377755de5f29a34f963cd5
[ "Unlicense" ]
null
null
null
MainWindow.cpp
jplflyer/qt-TreeViewDemo
a3e74d410a3e6e4512377755de5f29a34f963cd5
[ "Unlicense" ]
2
2020-04-08T16:41:03.000Z
2021-05-04T08:45:00.000Z
#include <iostream> #include <QTimer> #include "MainWindow.h" #include "ui_MainWindow.h" using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), model(new MyDataModel(nullptr, &topData)) { ui->setupUi(this); ui->treeView->setModel(model); auto toolbar = ui->mainToolBar; removeToolBar(toolbar); addToolBar(Qt::LeftToolBarArea, toolbar); toolbar->show(); TopData * td1 = new TopData("Joe", "Awesome"); TopData * td2 = new TopData("MySis", "Sweet"); // My sister topData.push_back(td1); topData.push_back(td2); MiddleData * md1a = td1->createMiddleData("Childhood", "Brooklyn Center"); td1->createMiddleData("High School", "Park Center"); td1->createMiddleData("Current", "Minnesota"); MiddleData * md2a = td2->createMiddleData("Childhood", "Brooklyn Center"); td2->createMiddleData("Somewhere", "She'd Shoot Me"); td2->createMiddleData("Current", "I mean it. She would."); md1a->createChildData("From", 0); md1a->createChildData("Until", 22); md2a->createChildData("From", 14); md2a->createChildData("Until", 18); // Columns are allocated evenly, except the last which by default gets the stretch. This lets me make two of them wider. ui->treeView->setColumnWidth(0, ui->treeView->columnWidth(0) * 2); ui->treeView->setColumnWidth(2, ui->treeView->columnWidth(2) * 2); // Set up to automatically force a data change. QTimer::singleShot(5000, this, SLOT(updateData())); } MainWindow::~MainWindow() { delete ui; } /** * This does a data update then tells the form. */ void MainWindow::on_actionChange_Data_triggered() { TopData * td = topData.at(0); MiddleData * md = td->middleData.at(0); md->name = md->name + "."; md->createChildData("Update", 10); //ui->treeView->dataChanged(QModelIndex(), QModelIndex()); model->layoutChanged(); } /** * Timer version of automatically changing the data. */ void MainWindow::updateData() { on_actionChange_Data_triggered(); QTimer::singleShot(5000, this, SLOT(updateData())); }
27.727273
124
0.670258
[ "model" ]
35c1e653daf1d5242c30190941b785209b52a355
386
hpp
C++
PlanetLab/src/engine/shape/ShapeSphere.hpp
Thomas-Zorroche/Procedural-Planets
44f8a9fa3120d11d137e4f499142333e81ed68ce
[ "MIT" ]
null
null
null
PlanetLab/src/engine/shape/ShapeSphere.hpp
Thomas-Zorroche/Procedural-Planets
44f8a9fa3120d11d137e4f499142333e81ed68ce
[ "MIT" ]
null
null
null
PlanetLab/src/engine/shape/ShapeSphere.hpp
Thomas-Zorroche/Procedural-Planets
44f8a9fa3120d11d137e4f499142333e81ed68ce
[ "MIT" ]
null
null
null
#pragma once namespace PlanetLab { class ShapeSphere { public: ShapeSphere(float radius = 1.0f, int rings = 12, int sector = 24); const ShapeVertex* vertices() const { return &_vertices[0]; } GLsizei vertexCount() const { return _nVertexCount; } private: void build(float radius, int rings, int sector); std::vector<ShapeVertex> _vertices; GLsizei _nVertexCount; }; }
14.846154
67
0.715026
[ "vector" ]
35c7cbf01faa683862972726c3c0cc22dd9fa4ca
142,832
cpp
C++
Engine/Source/Runtime/Renderer/Private/DistanceFieldSurfaceCacheLighting.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Renderer/Private/DistanceFieldSurfaceCacheLighting.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Renderer/Private/DistanceFieldSurfaceCacheLighting.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= DistanceFieldSurfaceCacheLighting.cpp =============================================================================*/ #include "RendererPrivate.h" #include "ScenePrivate.h" #include "UniformBuffer.h" #include "ShaderParameters.h" #include "PostProcessing.h" #include "SceneFilterRendering.h" #include "DistanceFieldLightingShared.h" #include "DistanceFieldSurfaceCacheLighting.h" #include "DistanceFieldLightingPost.h" #include "DistanceFieldGlobalIllumination.h" #include "PostProcessAmbientOcclusion.h" #include "RHICommandList.h" #include "SceneUtils.h" #include "OneColorShader.h" #include "BasePassRendering.h" #include "HeightfieldLighting.h" #include "GlobalDistanceField.h" #include "FXSystem.h" int32 GDistanceFieldAO = 1; FAutoConsoleVariableRef CVarDistanceFieldAO( TEXT("r.DistanceFieldAO"), GDistanceFieldAO, TEXT("Whether the distance field AO feature is allowed, which is used to implement shadows of Movable sky lights from static meshes."), ECVF_Scalability | ECVF_RenderThreadSafe ); bool IsDistanceFieldGIAllowed(const FViewInfo& View) { return DoesPlatformSupportDistanceFieldGI(View.GetShaderPlatform()) && (View.Family->EngineShowFlags.VisualizeDistanceFieldGI || (View.Family->EngineShowFlags.DistanceFieldGI && GDistanceFieldGI && View.Family->EngineShowFlags.GlobalIllumination)); } int32 GAOUseSurfaceCache = 0; FAutoConsoleVariableRef CVarAOUseSurfaceCache( TEXT("r.AOUseSurfaceCache"), GAOUseSurfaceCache, TEXT("Whether to use the surface cache or screen grid for cone tracing. The screen grid has more constant performance characteristics."), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOPowerOfTwoBetweenLevels = 2; FAutoConsoleVariableRef CVarAOPowerOfTwoBetweenLevels( TEXT("r.AOPowerOfTwoBetweenLevels"), GAOPowerOfTwoBetweenLevels, TEXT("Power of two in resolution between refinement levels of the surface cache"), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOMinLevel = 1; FAutoConsoleVariableRef CVarAOMinLevel( TEXT("r.AOMinLevel"), GAOMinLevel, TEXT("Smallest downsample power of 4 to use for surface cache population.\n") TEXT("The default is 1, which means every 8 full resolution pixels (BaseDownsampleFactor(2) * 4^1) will be checked for a valid interpolation from the cache or shaded.\n") TEXT("Going down to 0 gives less aliasing, and removes the need for gap filling, but costs a lot."), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOMaxLevel = FMath::Min(2, GAOMaxSupportedLevel); FAutoConsoleVariableRef CVarAOMaxLevel( TEXT("r.AOMaxLevel"), GAOMaxLevel, TEXT("Largest downsample power of 4 to use for surface cache population."), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOReuseAcrossFrames = 1; FAutoConsoleVariableRef CVarAOReuseAcrossFrames( TEXT("r.AOReuseAcrossFrames"), GAOReuseAcrossFrames, TEXT("Whether to allow reusing surface cache results across frames."), ECVF_Cheat | ECVF_RenderThreadSafe ); float GAOTrimOldRecordsFraction = .2f; FAutoConsoleVariableRef CVarAOTrimOldRecordsFraction( TEXT("r.AOTrimOldRecordsFraction"), GAOTrimOldRecordsFraction, TEXT("When r.AOReuseAcrossFrames is enabled, this is the fraction of the last frame's surface cache records that will not be reused.\n") TEXT("Low settings provide better performance, while values closer to 1 give faster lighting updates when dynamic scene changes are happening."), ECVF_Cheat | ECVF_RenderThreadSafe ); float GAORecordRadiusScale = .3f; FAutoConsoleVariableRef CVarAORecordRadiusScale( TEXT("r.AORecordRadiusScale"), GAORecordRadiusScale, TEXT("Scale applied to the minimum occluder distance to produce the record radius. This effectively controls how dense shading samples are."), ECVF_Cheat | ECVF_RenderThreadSafe ); float GAOInterpolationRadiusScale = 1.3f; FAutoConsoleVariableRef CVarAOInterpolationRadiusScale( TEXT("r.AOInterpolationRadiusScale"), GAOInterpolationRadiusScale, TEXT("Scale applied to record radii during the final interpolation pass. Values larger than 1 result in world space smoothing."), ECVF_Cheat | ECVF_RenderThreadSafe ); float GAOMinPointBehindPlaneAngle = 4; FAutoConsoleVariableRef CVarAOMinPointBehindPlaneAngle( TEXT("r.AOMinPointBehindPlaneAngle"), GAOMinPointBehindPlaneAngle, TEXT("Minimum angle that a point can lie behind a record and still be considered valid.\n") TEXT("This threshold helps reduce leaking that happens when interpolating records in front of the shading point, ignoring occluders in between."), ECVF_Cheat | ECVF_RenderThreadSafe ); float GAOInterpolationMaxAngle = 15; FAutoConsoleVariableRef CVarAOInterpolationMaxAngle( TEXT("r.AOInterpolationMaxAngle"), GAOInterpolationMaxAngle, TEXT("Largest angle allowed between the shading point's normal and a nearby record's normal."), ECVF_Cheat | ECVF_RenderThreadSafe ); float GAOInterpolationAngleScale = 1.5f; FAutoConsoleVariableRef CVarAOInterpolationAngleScale( TEXT("r.AOInterpolationAngleScale"), GAOInterpolationAngleScale, TEXT("Scale applied to angle error during the final interpolation pass. Values larger than 1 result in smoothing."), ECVF_Cheat | ECVF_RenderThreadSafe ); float GAOStepExponentScale = .5f; FAutoConsoleVariableRef CVarAOStepExponentScale( TEXT("r.AOStepExponentScale"), GAOStepExponentScale, TEXT("Exponent used to distribute AO samples along a cone direction."), ECVF_Cheat | ECVF_RenderThreadSafe ); float GAOMaxViewDistance = 20000; FAutoConsoleVariableRef CVarAOMaxViewDistance( TEXT("r.AOMaxViewDistance"), GAOMaxViewDistance, TEXT("The maximum distance that AO will be computed at."), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOScatterTileCulling = 1; FAutoConsoleVariableRef CVarAOScatterTileCulling( TEXT("r.AOScatterTileCulling"), GAOScatterTileCulling, TEXT("Whether to use the rasterizer for binning occluder objects into screenspace tiles."), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOComputeShaderNormalCalculation = 0; FAutoConsoleVariableRef CVarAOComputeShaderNormalCalculation( TEXT("r.AOComputeShaderNormalCalculation"), GAOComputeShaderNormalCalculation, TEXT("Whether to use the compute shader version of the distance field normal computation."), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOSampleSet = 1; FAutoConsoleVariableRef CVarAOSampleSet( TEXT("r.AOSampleSet"), GAOSampleSet, TEXT("0 = Original set, 1 = Relaxed set"), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOInterpolationStencilTesting = 1; FAutoConsoleVariableRef CVarAOInterpolationStencilTesting( TEXT("r.AOInterpolationStencilTesting"), GAOInterpolationStencilTesting, TEXT("Whether to stencil out distant pixels from the interpolation splat pass, useful for debugging"), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOInterpolationDepthTesting = 1; FAutoConsoleVariableRef CVarAOInterpolationDepthTesting( TEXT("r.AOInterpolationDepthTesting"), GAOInterpolationDepthTesting, TEXT("Whether to use depth testing during the interpolation splat pass, useful for debugging"), ECVF_Cheat | ECVF_RenderThreadSafe ); int32 GAOOverwriteSceneColor = 0; FAutoConsoleVariableRef CVarAOOverwriteSceneColor( TEXT("r.AOOverwriteSceneColor"), GAOOverwriteSceneColor, TEXT(""), ECVF_Cheat | ECVF_RenderThreadSafe ); DEFINE_LOG_CATEGORY(LogDistanceField); IMPLEMENT_UNIFORM_BUFFER_STRUCT(FAOSampleData2,TEXT("AOSamples2")); FDistanceFieldAOParameters::FDistanceFieldAOParameters(float InOcclusionMaxDistance, float InContrast) { Contrast = FMath::Clamp(InContrast, .01f, 2.0f); InOcclusionMaxDistance = FMath::Clamp(InOcclusionMaxDistance, 2.0f, 3000.0f); if (GAOGlobalDistanceField != 0 && GAOUseSurfaceCache == 0) { extern float GAOGlobalDFStartDistance; ObjectMaxOcclusionDistance = FMath::Min(InOcclusionMaxDistance, GAOGlobalDFStartDistance); GlobalMaxOcclusionDistance = InOcclusionMaxDistance >= GAOGlobalDFStartDistance ? InOcclusionMaxDistance : 0; } else { ObjectMaxOcclusionDistance = InOcclusionMaxDistance; GlobalMaxOcclusionDistance = 0; } } FIntPoint GetBufferSizeForAO() { return FIntPoint::DivideAndRoundDown(FSceneRenderTargets::Get_FrameConstantsOnly().GetBufferSizeXY(), GAODownsampleFactor); } // Sample set restricted to not self-intersect a surface based on cone angle .475882232 // Coverage of hemisphere = 0.755312979 const FVector SpacedVectors9[] = { FVector(-0.573257625, 0.625250816, 0.529563010), FVector(0.253354192, -0.840093017, 0.479640961), FVector(-0.421664953, -0.718063235, 0.553700149), FVector(0.249163717, 0.796005428, 0.551627457), FVector(0.375082791, 0.295851320, 0.878512800), FVector(-0.217619032, 0.00193520682, 0.976031899), FVector(-0.852834642, 0.0111727007, 0.522061586), FVector(0.745701790, 0.239393353, 0.621787369), FVector(-0.151036426, -0.465937436, 0.871831656) }; // Generated from SpacedVectors9 by applying repulsion forces until convergence const FVector RelaxedSpacedVectors9[] = { FVector(-0.467612, 0.739424, 0.484347), FVector(0.517459, -0.705440, 0.484346), FVector(-0.419848, -0.767551, 0.484347), FVector(0.343077, 0.804802, 0.484347), FVector(0.364239, 0.244290, 0.898695), FVector(-0.381547, 0.185815, 0.905481), FVector(-0.870176, -0.090559, 0.484347), FVector(0.874448, 0.027390, 0.484346), FVector(0.032967, -0.435625, 0.899524) }; void GetSpacedVectors(TArray<FVector, TInlineAllocator<9> >& OutVectors) { OutVectors.Empty(ARRAY_COUNT(SpacedVectors9)); if (GAOSampleSet == 0) { for (int32 i = 0; i < ARRAY_COUNT(SpacedVectors9); i++) { OutVectors.Add(SpacedVectors9[i]); } } else { for (int32 i = 0; i < ARRAY_COUNT(RelaxedSpacedVectors9); i++) { OutVectors.Add(RelaxedSpacedVectors9[i]); } } } // Cone half angle derived from each cone covering an equal solid angle float GAOConeHalfAngle = FMath::Acos(1 - 1.0f / (float)ARRAY_COUNT(SpacedVectors9)); // Number of AO sample positions along each cone // Must match shader code uint32 GAONumConeSteps = 10; class FCircleVertexBuffer : public FVertexBuffer { public: int32 NumSections; FCircleVertexBuffer() { NumSections = 8; } virtual void InitRHI() override { // Used as a non-indexed triangle list, so 3 vertices per triangle const uint32 Size = 3 * NumSections * sizeof(FScreenVertex); FRHIResourceCreateInfo CreateInfo; void* Buffer = nullptr; VertexBufferRHI = RHICreateAndLockVertexBuffer(Size, BUF_Static, CreateInfo, Buffer); FScreenVertex* DestVertex = (FScreenVertex*)Buffer; const float RadiansPerRingSegment = PI / (float)NumSections; // Boost the effective radius so that the edges of the circle approximation lie on the circle, instead of the vertices const float Radius = 1.0f / FMath::Cos(RadiansPerRingSegment); for (int32 SectionIndex = 0; SectionIndex < NumSections; SectionIndex++) { float Fraction = SectionIndex / (float)NumSections; float CurrentAngle = Fraction * 2 * PI; float NextAngle = ((SectionIndex + 1) / (float)NumSections) * 2 * PI; FVector2D CurrentPosition(Radius * FMath::Cos(CurrentAngle), Radius * FMath::Sin(CurrentAngle)); FVector2D NextPosition(Radius * FMath::Cos(NextAngle), Radius * FMath::Sin(NextAngle)); DestVertex[SectionIndex * 3 + 0].Position = FVector2D(0, 0); DestVertex[SectionIndex * 3 + 0].UV = CurrentPosition; DestVertex[SectionIndex * 3 + 1].Position = FVector2D(0, 0); DestVertex[SectionIndex * 3 + 1].UV = NextPosition; DestVertex[SectionIndex * 3 + 2].Position = FVector2D(0, 0); DestVertex[SectionIndex * 3 + 2].UV = FVector2D(.5f, .5f); } RHIUnlockVertexBuffer(VertexBufferRHI); } }; TGlobalResource<FCircleVertexBuffer> GCircleVertexBuffer; TGlobalResource<FDistanceFieldObjectBufferResource> GAOCulledObjectBuffers; TGlobalResource<FTemporaryIrradianceCacheResources> GTemporaryIrradianceCacheResources; void FTileIntersectionResources::InitDynamicRHI() { TileConeAxisAndCos.Initialize(sizeof(float)* 4, TileDimensions.X * TileDimensions.Y, PF_A32B32G32R32F, BUF_Static); TileConeDepthRanges.Initialize(sizeof(float)* 4, TileDimensions.X * TileDimensions.Y, PF_A32B32G32R32F, BUF_Static); TileHeadDataUnpacked.Initialize(sizeof(uint32), TileDimensions.X * TileDimensions.Y * 4, PF_R32_UINT, BUF_Static); //@todo - handle max exceeded TileArrayData.Initialize(sizeof(uint32), GMaxNumObjectsPerTile * TileDimensions.X * TileDimensions.Y * 3, PF_R32_UINT, BUF_Static); TileArrayNextAllocation.Initialize(sizeof(uint32), 1, PF_R32_UINT, BUF_Static); } void OnClearSurfaceCache(UWorld* InWorld) { FlushRenderingCommands(); FScene* Scene = (FScene*)InWorld->Scene; if (Scene && Scene->SurfaceCacheResources) { Scene->SurfaceCacheResources->bClearedResources = false; } } FAutoConsoleCommandWithWorld ClearCacheConsoleCommand( TEXT("r.AOClearCache"), TEXT(""), FConsoleCommandWithWorldDelegate::CreateStatic(OnClearSurfaceCache) ); bool bListMemoryNextFrame = false; void OnListMemory(UWorld* InWorld) { bListMemoryNextFrame = true; } FAutoConsoleCommandWithWorld ListMemoryConsoleCommand( TEXT("r.AOListMemory"), TEXT(""), FConsoleCommandWithWorldDelegate::CreateStatic(OnListMemory) ); class FCullObjectsForViewCS : public FGlobalShader { DECLARE_SHADER_TYPE(FCullObjectsForViewCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("UPDATEOBJECTS_THREADGROUP_SIZE"), UpdateObjectsGroupSize); } FCullObjectsForViewCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { ObjectBufferParameters.Bind(Initializer.ParameterMap); ObjectIndirectArguments.Bind(Initializer.ParameterMap, TEXT("ObjectIndirectArguments")); CulledObjectBounds.Bind(Initializer.ParameterMap, TEXT("CulledObjectBounds")); CulledObjectData.Bind(Initializer.ParameterMap, TEXT("CulledObjectData")); CulledObjectBoxBounds.Bind(Initializer.ParameterMap, TEXT("CulledObjectBoxBounds")); AOParameters.Bind(Initializer.ParameterMap); NumConvexHullPlanes.Bind(Initializer.ParameterMap, TEXT("NumConvexHullPlanes")); ViewFrustumConvexHull.Bind(Initializer.ParameterMap, TEXT("ViewFrustumConvexHull")); ObjectBoundingGeometryIndexCount.Bind(Initializer.ParameterMap, TEXT("ObjectBoundingGeometryIndexCount")); } FCullObjectsForViewCS() { } void SetParameters(FRHICommandList& RHICmdList, const FScene* Scene, const FSceneView& View, const FDistanceFieldAOParameters& Parameters) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); ObjectBufferParameters.Set(RHICmdList, ShaderRHI, *(Scene->DistanceFieldSceneData.ObjectBuffers), Scene->DistanceFieldSceneData.NumObjectsInBuffer); ObjectIndirectArguments.SetBuffer(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers.ObjectIndirectArguments); CulledObjectBounds.SetBuffer(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers.Bounds); CulledObjectData.SetBuffer(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers.Data); CulledObjectBoxBounds.SetBuffer(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers.BoxBounds); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); // Shader assumes max 6 check(View.ViewFrustum.Planes.Num() <= 6); SetShaderValue(RHICmdList, ShaderRHI, NumConvexHullPlanes, View.ViewFrustum.Planes.Num()); SetShaderValueArray(RHICmdList, ShaderRHI, ViewFrustumConvexHull, View.ViewFrustum.Planes.GetData(), View.ViewFrustum.Planes.Num()); SetShaderValue(RHICmdList, ShaderRHI, ObjectBoundingGeometryIndexCount, StencilingGeometry::GLowPolyStencilSphereIndexBuffer.GetIndexCount()); } void UnsetParameters(FRHICommandList& RHICmdList) { ObjectBufferParameters.UnsetParameters(RHICmdList, GetComputeShader()); ObjectIndirectArguments.UnsetUAV(RHICmdList, GetComputeShader()); CulledObjectBounds.UnsetUAV(RHICmdList, GetComputeShader()); CulledObjectData.UnsetUAV(RHICmdList, GetComputeShader()); CulledObjectBoxBounds.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << ObjectBufferParameters; Ar << ObjectIndirectArguments; Ar << CulledObjectBounds; Ar << CulledObjectData; Ar << CulledObjectBoxBounds; Ar << AOParameters; Ar << NumConvexHullPlanes; Ar << ViewFrustumConvexHull; Ar << ObjectBoundingGeometryIndexCount; return bShaderHasOutdatedParameters; } private: FDistanceFieldObjectBufferParameters ObjectBufferParameters; FRWShaderParameter ObjectIndirectArguments; FRWShaderParameter CulledObjectBounds; FRWShaderParameter CulledObjectData; FRWShaderParameter CulledObjectBoxBounds; FAOParameters AOParameters; FShaderParameter NumConvexHullPlanes; FShaderParameter ViewFrustumConvexHull; FShaderParameter ObjectBoundingGeometryIndexCount; }; IMPLEMENT_SHADER_TYPE(,FCullObjectsForViewCS,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("CullObjectsForViewCS"),SF_Compute); /** */ class FBuildTileConesCS : public FGlobalShader { DECLARE_SHADER_TYPE(FBuildTileConesCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), GDistanceFieldAOTileSizeX); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), GDistanceFieldAOTileSizeY); OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); // To reduce shader compile time of compute shaders with shared memory, doesn't have an impact on generated code with current compiler (June 2010 DX SDK) OutEnvironment.CompilerFlags.Add(CFLAG_StandardOptimization); } FBuildTileConesCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DeferredParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); TileConeAxisAndCos.Bind(Initializer.ParameterMap, TEXT("TileConeAxisAndCos")); TileConeDepthRanges.Bind(Initializer.ParameterMap, TEXT("TileConeDepthRanges")); TileHeadDataUnpacked.Bind(Initializer.ParameterMap, TEXT("TileHeadDataUnpacked")); NumGroups.Bind(Initializer.ParameterMap, TEXT("NumGroups")); ViewDimensionsParameter.Bind(Initializer.ParameterMap, TEXT("ViewDimensions")); DistanceFieldNormalTexture.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormalTexture")); DistanceFieldNormalSampler.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormalSampler")); } FBuildTileConesCS() { } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FSceneRenderTargetItem& DistanceFieldNormal, FScene* Scene, FVector2D NumGroupsValue, const FDistanceFieldAOParameters& Parameters) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); DeferredParameters.Set(RHICmdList, ShaderRHI, View); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); FTileIntersectionResources* TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources; TileConeAxisAndCos.SetBuffer(RHICmdList, ShaderRHI, TileIntersectionResources->TileConeAxisAndCos); TileConeDepthRanges.SetBuffer(RHICmdList, ShaderRHI, TileIntersectionResources->TileConeDepthRanges); TileHeadDataUnpacked.SetBuffer(RHICmdList, ShaderRHI, TileIntersectionResources->TileHeadDataUnpacked); SetShaderValue(RHICmdList, ShaderRHI, ViewDimensionsParameter, View.ViewRect); SetShaderValue(RHICmdList, ShaderRHI, NumGroups, NumGroupsValue); SetTextureParameter( RHICmdList, ShaderRHI, DistanceFieldNormalTexture, DistanceFieldNormalSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), DistanceFieldNormal.ShaderResourceTexture ); } void UnsetParameters(FRHICommandList& RHICmdList) { TileConeAxisAndCos.UnsetUAV(RHICmdList, GetComputeShader()); TileConeDepthRanges.UnsetUAV(RHICmdList, GetComputeShader()); TileHeadDataUnpacked.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DeferredParameters; Ar << AOParameters; Ar << TileConeAxisAndCos; Ar << TileConeDepthRanges; Ar << TileHeadDataUnpacked; Ar << NumGroups; Ar << ViewDimensionsParameter; Ar << DistanceFieldNormalTexture; Ar << DistanceFieldNormalSampler; return bShaderHasOutdatedParameters; } private: FDeferredPixelShaderParameters DeferredParameters; FAOParameters AOParameters; FRWShaderParameter TileConeAxisAndCos; FRWShaderParameter TileConeDepthRanges; FRWShaderParameter TileHeadDataUnpacked; FShaderParameter ViewDimensionsParameter; FShaderParameter NumGroups; FShaderResourceParameter DistanceFieldNormalTexture; FShaderResourceParameter DistanceFieldNormalSampler; }; IMPLEMENT_SHADER_TYPE(,FBuildTileConesCS,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("BuildTileConesMain"),SF_Compute); /** */ class FObjectCullVS : public FGlobalShader { DECLARE_SHADER_TYPE(FObjectCullVS,Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); } FObjectCullVS(const ShaderMetaType::CompiledShaderInitializerType& Initializer): FGlobalShader(Initializer) { ObjectParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); ConservativeRadiusScale.Bind(Initializer.ParameterMap, TEXT("ConservativeRadiusScale")); } FObjectCullVS() {} void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, const FDistanceFieldAOParameters& Parameters) { const FVertexShaderRHIParamRef ShaderRHI = GetVertexShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); ObjectParameters.Set(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); const int32 NumRings = StencilingGeometry::GLowPolyStencilSphereVertexBuffer.GetNumRings(); const float RadiansPerRingSegment = PI / (float)NumRings; // Boost the effective radius so that the edges of the sphere approximation lie on the sphere, instead of the vertices const float ConservativeRadiusScaleValue = 1.0f / FMath::Cos(RadiansPerRingSegment); SetShaderValue(RHICmdList, ShaderRHI, ConservativeRadiusScale, ConservativeRadiusScaleValue); } virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << ObjectParameters; Ar << AOParameters; Ar << ConservativeRadiusScale; return bShaderHasOutdatedParameters; } private: FDistanceFieldCulledObjectBufferParameters ObjectParameters; FAOParameters AOParameters; FShaderParameter ConservativeRadiusScale; }; IMPLEMENT_SHADER_TYPE(,FObjectCullVS,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("ObjectCullVS"),SF_Vertex); class FObjectCullPS : public FGlobalShader { DECLARE_SHADER_TYPE(FObjectCullPS, Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); } /** Default constructor. */ FObjectCullPS() {} /** Initialization constructor. */ FObjectCullPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { ObjectParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); TileHeadDataUnpacked.Bind(Initializer.ParameterMap, TEXT("TileHeadDataUnpacked")); TileArrayData.Bind(Initializer.ParameterMap, TEXT("TileArrayData")); TileConeAxisAndCos.Bind(Initializer.ParameterMap, TEXT("TileConeAxisAndCos")); TileConeDepthRanges.Bind(Initializer.ParameterMap, TEXT("TileConeDepthRanges")); NumGroups.Bind(Initializer.ParameterMap, TEXT("NumGroups")); } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FVector2D NumGroupsValue, const FDistanceFieldAOParameters& Parameters) { const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); ObjectParameters.Set(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); FTileIntersectionResources* TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources; SetSRVParameter(RHICmdList, ShaderRHI, TileConeAxisAndCos, TileIntersectionResources->TileConeAxisAndCos.SRV); SetSRVParameter(RHICmdList, ShaderRHI, TileConeDepthRanges, TileIntersectionResources->TileConeDepthRanges.SRV); SetShaderValue(RHICmdList, ShaderRHI, NumGroups, NumGroupsValue); } void GetUAVs(const FSceneView& View, TArray<FUnorderedAccessViewRHIParamRef>& UAVs) { FTileIntersectionResources* TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources; int32 MaxIndex = FMath::Max(TileHeadDataUnpacked.GetUAVIndex(), TileArrayData.GetUAVIndex()); UAVs.AddZeroed(MaxIndex + 1); if (TileHeadDataUnpacked.IsBound()) { UAVs[TileHeadDataUnpacked.GetUAVIndex()] = TileIntersectionResources->TileHeadDataUnpacked.UAV; } if (TileArrayData.IsBound()) { UAVs[TileArrayData.GetUAVIndex()] = TileIntersectionResources->TileArrayData.UAV; } check(UAVs.Num() > 0); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << ObjectParameters; Ar << AOParameters; Ar << TileHeadDataUnpacked; Ar << TileArrayData; Ar << TileConeAxisAndCos; Ar << TileConeDepthRanges; Ar << NumGroups; return bShaderHasOutdatedParameters; } private: FDistanceFieldCulledObjectBufferParameters ObjectParameters; FAOParameters AOParameters; FRWShaderParameter TileHeadDataUnpacked; FRWShaderParameter TileArrayData; FShaderResourceParameter TileConeAxisAndCos; FShaderResourceParameter TileConeDepthRanges; FShaderParameter NumGroups; }; IMPLEMENT_SHADER_TYPE(,FObjectCullPS,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("ObjectCullPS"),SF_Pixel); /** */ class FDistanceFieldBuildTileListCS : public FGlobalShader { DECLARE_SHADER_TYPE(FDistanceFieldBuildTileListCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), GDistanceFieldAOTileSizeX); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), GDistanceFieldAOTileSizeY); OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); // To reduce shader compile time of compute shaders with shared memory, doesn't have an impact on generated code with current compiler (June 2010 DX SDK) OutEnvironment.CompilerFlags.Add(CFLAG_StandardOptimization); } FDistanceFieldBuildTileListCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DeferredParameters.Bind(Initializer.ParameterMap); ObjectParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); TileHeadDataUnpacked.Bind(Initializer.ParameterMap, TEXT("TileHeadDataUnpacked")); TileArrayData.Bind(Initializer.ParameterMap, TEXT("TileArrayData")); TileArrayNextAllocation.Bind(Initializer.ParameterMap, TEXT("TileArrayNextAllocation")); NumGroups.Bind(Initializer.ParameterMap, TEXT("NumGroups")); ViewDimensionsParameter.Bind(Initializer.ParameterMap, TEXT("ViewDimensions")); } FDistanceFieldBuildTileListCS() { } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FScene* Scene, FVector2D NumGroupsValue, const FDistanceFieldAOParameters& Parameters) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); DeferredParameters.Set(RHICmdList, ShaderRHI, View); ObjectParameters.Set(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); FTileIntersectionResources* TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources; TileHeadDataUnpacked.SetBuffer(RHICmdList, ShaderRHI, TileIntersectionResources->TileHeadDataUnpacked); TileArrayData.SetBuffer(RHICmdList, ShaderRHI, TileIntersectionResources->TileArrayData); TileArrayNextAllocation.SetBuffer(RHICmdList, ShaderRHI, TileIntersectionResources->TileArrayNextAllocation); SetShaderValue(RHICmdList, ShaderRHI, ViewDimensionsParameter, View.ViewRect); SetShaderValue(RHICmdList, ShaderRHI, NumGroups, NumGroupsValue); } void UnsetParameters(FRHICommandList& RHICmdList) { TileHeadDataUnpacked.UnsetUAV(RHICmdList, GetComputeShader()); TileArrayData.UnsetUAV(RHICmdList, GetComputeShader()); TileArrayNextAllocation.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DeferredParameters; Ar << ObjectParameters; Ar << AOParameters; Ar << TileHeadDataUnpacked; Ar << TileArrayData; Ar << TileArrayNextAllocation; Ar << NumGroups; Ar << ViewDimensionsParameter; return bShaderHasOutdatedParameters; } private: FDeferredPixelShaderParameters DeferredParameters; FDistanceFieldCulledObjectBufferParameters ObjectParameters; FAOParameters AOParameters; FRWShaderParameter TileHeadDataUnpacked; FRWShaderParameter TileArrayData; FRWShaderParameter TileArrayNextAllocation; FShaderParameter ViewDimensionsParameter; FShaderParameter NumGroups; }; IMPLEMENT_SHADER_TYPE(,FDistanceFieldBuildTileListCS,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("DistanceFieldAOBuildTileListMain"),SF_Compute); class FComputeDistanceFieldNormalPS : public FGlobalShader { DECLARE_SHADER_TYPE(FComputeDistanceFieldNormalPS, Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), GDistanceFieldAOTileSizeX); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), GDistanceFieldAOTileSizeY); } /** Default constructor. */ FComputeDistanceFieldNormalPS() {} /** Initialization constructor. */ FComputeDistanceFieldNormalPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DeferredParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, const FDistanceFieldAOParameters& Parameters) { const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); DeferredParameters.Set(RHICmdList, ShaderRHI, View); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DeferredParameters; Ar << AOParameters; return bShaderHasOutdatedParameters; } private: FDeferredPixelShaderParameters DeferredParameters; FAOParameters AOParameters; }; IMPLEMENT_SHADER_TYPE(,FComputeDistanceFieldNormalPS,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("ComputeDistanceFieldNormalPS"),SF_Pixel); class FComputeDistanceFieldNormalCS : public FGlobalShader { DECLARE_SHADER_TYPE(FComputeDistanceFieldNormalCS, Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), GDistanceFieldAOTileSizeX); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), GDistanceFieldAOTileSizeY); } /** Default constructor. */ FComputeDistanceFieldNormalCS() {} /** Initialization constructor. */ FComputeDistanceFieldNormalCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DistanceFieldNormal.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormal")); DeferredParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FSceneRenderTargetItem& DistanceFieldNormalValue, const FDistanceFieldAOParameters& Parameters) { const FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); DistanceFieldNormal.SetTexture(RHICmdList, ShaderRHI, DistanceFieldNormalValue.ShaderResourceTexture, DistanceFieldNormalValue.UAV); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); DeferredParameters.Set(RHICmdList, ShaderRHI, View); } void UnsetParameters(FRHICommandList& RHICmdList) { DistanceFieldNormal.UnsetUAV(RHICmdList, GetComputeShader()); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DistanceFieldNormal; Ar << DeferredParameters; Ar << AOParameters; return bShaderHasOutdatedParameters; } private: FRWShaderParameter DistanceFieldNormal; FDeferredPixelShaderParameters DeferredParameters; FAOParameters AOParameters; }; IMPLEMENT_SHADER_TYPE(,FComputeDistanceFieldNormalCS,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("ComputeDistanceFieldNormalCS"),SF_Compute); void ComputeDistanceFieldNormal(FRHICommandListImmediate& RHICmdList, const TArray<FViewInfo>& Views, FSceneRenderTargetItem& DistanceFieldNormal, const FDistanceFieldAOParameters& Parameters) { if (GAOComputeShaderNormalCalculation) { SetRenderTarget(RHICmdList, NULL, NULL); for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++) { const FViewInfo& View = Views[ViewIndex]; uint32 GroupSizeX = FMath::DivideAndRoundUp(View.ViewRect.Size().X / GAODownsampleFactor, GDistanceFieldAOTileSizeX); uint32 GroupSizeY = FMath::DivideAndRoundUp(View.ViewRect.Size().Y / GAODownsampleFactor, GDistanceFieldAOTileSizeY); { SCOPED_DRAW_EVENT(RHICmdList, ComputeNormalCS); TShaderMapRef<FComputeDistanceFieldNormalCS> ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DistanceFieldNormal, Parameters); DispatchComputeShader(RHICmdList, *ComputeShader, GroupSizeX, GroupSizeY, 1); ComputeShader->UnsetParameters(RHICmdList); } } } else { SetRenderTarget(RHICmdList, DistanceFieldNormal.TargetableTexture, NULL); for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++) { const FViewInfo& View = Views[ViewIndex]; SCOPED_DRAW_EVENT(RHICmdList, ComputeNormal); RHICmdList.SetViewport(0, 0, 0.0f, View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor, 1.0f); RHICmdList.SetRasterizerState(TStaticRasterizerState<FM_Solid, CM_None>::GetRHI()); RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI()); RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI()); TShaderMapRef<FPostProcessVS> VertexShader(View.ShaderMap); TShaderMapRef<FComputeDistanceFieldNormalPS> PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.FeatureLevel, BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); PixelShader->SetParameters(RHICmdList, View, Parameters); DrawRectangle( RHICmdList, 0, 0, View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor, 0, 0, View.ViewRect.Width(), View.ViewRect.Height(), FIntPoint(View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor), FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY(), *VertexShader); } } } class FSetupCopyIndirectArgumentsCS : public FGlobalShader { DECLARE_SHADER_TYPE(FSetupCopyIndirectArgumentsCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.CompilerFlags.Add(CFLAG_StandardOptimization); } FSetupCopyIndirectArgumentsCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DrawParameters.Bind(Initializer.ParameterMap, TEXT("DrawParameters")); DispatchParameters.Bind(Initializer.ParameterMap, TEXT("DispatchParameters")); ScatterDrawParameters.Bind(Initializer.ParameterMap, TEXT("ScatterDrawParameters")); TrimFraction.Bind(Initializer.ParameterMap, TEXT("TrimFraction")); } FSetupCopyIndirectArgumentsCS() { } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, int32 DepthLevel) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); const FScene* Scene = (const FScene*)View.Family->Scene; FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; SetSRVParameter(RHICmdList, ShaderRHI, DrawParameters, SurfaceCacheResources.Level[DepthLevel]->ScatterDrawParameters.SRV); DispatchParameters.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.DispatchParameters); ScatterDrawParameters.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.TempResources->ScatterDrawParameters); SetShaderValue(RHICmdList, ShaderRHI, TrimFraction, GAOTrimOldRecordsFraction); } void UnsetParameters(FRHICommandList& RHICmdList) { DispatchParameters.UnsetUAV(RHICmdList, GetComputeShader()); ScatterDrawParameters.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DrawParameters; Ar << DispatchParameters; Ar << ScatterDrawParameters; Ar << TrimFraction; return bShaderHasOutdatedParameters; } private: FShaderResourceParameter DrawParameters; FRWShaderParameter DispatchParameters; FRWShaderParameter ScatterDrawParameters; FShaderParameter TrimFraction; }; IMPLEMENT_SHADER_TYPE(,FSetupCopyIndirectArgumentsCS,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("SetupCopyIndirectArgumentsCS"),SF_Compute); template<bool bSupportIrradiance> class TCopyIrradianceCacheSamplesCS : public FGlobalShader { DECLARE_SHADER_TYPE(TCopyIrradianceCacheSamplesCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.CompilerFlags.Add(CFLAG_StandardOptimization); OutEnvironment.SetDefine(TEXT("SUPPORT_IRRADIANCE"), bSupportIrradiance ? TEXT("1") : TEXT("0")); } TCopyIrradianceCacheSamplesCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { CacheParameters.Bind(Initializer.ParameterMap); DrawParameters.Bind(Initializer.ParameterMap, TEXT("DrawParameters")); CopyIrradianceCachePositionRadius.Bind(Initializer.ParameterMap, TEXT("CopyIrradianceCachePositionRadius")); CopyIrradianceCacheNormal.Bind(Initializer.ParameterMap, TEXT("CopyIrradianceCacheNormal")); CopyOccluderRadius.Bind(Initializer.ParameterMap, TEXT("CopyOccluderRadius")); CopyIrradianceCacheBentNormal.Bind(Initializer.ParameterMap, TEXT("CopyIrradianceCacheBentNormal")); CopyIrradianceCacheIrradiance.Bind(Initializer.ParameterMap, TEXT("CopyIrradianceCacheIrradiance")); CopyIrradianceCacheTileCoordinate.Bind(Initializer.ParameterMap, TEXT("CopyIrradianceCacheTileCoordinate")); ScatterDrawParameters.Bind(Initializer.ParameterMap, TEXT("ScatterDrawParameters")); TrimFraction.Bind(Initializer.ParameterMap, TEXT("TrimFraction")); } TCopyIrradianceCacheSamplesCS() { } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, int32 DepthLevel) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); const FScene* Scene = (const FScene*)View.Family->Scene; FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; CacheParameters.Set(RHICmdList, ShaderRHI, *SurfaceCacheResources.Level[DepthLevel]); SetSRVParameter(RHICmdList, ShaderRHI, DrawParameters, SurfaceCacheResources.Level[DepthLevel]->ScatterDrawParameters.SRV); CopyIrradianceCachePositionRadius.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.TempResources->PositionAndRadius); CopyIrradianceCacheNormal.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.TempResources->Normal); CopyOccluderRadius.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.TempResources->OccluderRadius); CopyIrradianceCacheBentNormal.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.TempResources->BentNormal); CopyIrradianceCacheIrradiance.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.TempResources->Irradiance); CopyIrradianceCacheTileCoordinate.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.TempResources->TileCoordinate); ScatterDrawParameters.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.TempResources->ScatterDrawParameters); SetShaderValue(RHICmdList, ShaderRHI, TrimFraction, GAOTrimOldRecordsFraction); } void UnsetParameters(FRHICommandList& RHICmdList) { CopyIrradianceCachePositionRadius.UnsetUAV(RHICmdList, GetComputeShader()); CopyIrradianceCacheNormal.UnsetUAV(RHICmdList, GetComputeShader()); CopyOccluderRadius.UnsetUAV(RHICmdList, GetComputeShader()); CopyIrradianceCacheBentNormal.UnsetUAV(RHICmdList, GetComputeShader()); CopyIrradianceCacheIrradiance.UnsetUAV(RHICmdList, GetComputeShader()); CopyIrradianceCacheTileCoordinate.UnsetUAV(RHICmdList, GetComputeShader()); ScatterDrawParameters.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << CacheParameters; Ar << DrawParameters; Ar << CopyIrradianceCachePositionRadius; Ar << CopyIrradianceCacheNormal; Ar << CopyOccluderRadius; Ar << CopyIrradianceCacheBentNormal; Ar << CopyIrradianceCacheIrradiance; Ar << CopyIrradianceCacheTileCoordinate; Ar << ScatterDrawParameters; Ar << TrimFraction; return bShaderHasOutdatedParameters; } private: FIrradianceCacheParameters CacheParameters; FShaderResourceParameter DrawParameters; FRWShaderParameter CopyIrradianceCachePositionRadius; FRWShaderParameter CopyIrradianceCacheNormal; FRWShaderParameter CopyOccluderRadius; FRWShaderParameter CopyIrradianceCacheBentNormal; FRWShaderParameter CopyIrradianceCacheIrradiance; FRWShaderParameter CopyIrradianceCacheTileCoordinate; FRWShaderParameter ScatterDrawParameters; FShaderParameter TrimFraction; }; IMPLEMENT_SHADER_TYPE(template<>,TCopyIrradianceCacheSamplesCS<true>,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("CopyIrradianceCacheSamplesCS"),SF_Compute); IMPLEMENT_SHADER_TYPE(template<>,TCopyIrradianceCacheSamplesCS<false>,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("CopyIrradianceCacheSamplesCS"),SF_Compute); class FSaveStartIndexCS : public FGlobalShader { DECLARE_SHADER_TYPE(FSaveStartIndexCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } FSaveStartIndexCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DrawParameters.Bind(Initializer.ParameterMap, TEXT("DrawParameters")); SavedStartIndex.Bind(Initializer.ParameterMap, TEXT("SavedStartIndex")); } FSaveStartIndexCS() { } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, int32 DepthLevel) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); const FScene* Scene = (const FScene*)View.Family->Scene; FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; SetSRVParameter(RHICmdList, ShaderRHI, DrawParameters, SurfaceCacheResources.Level[DepthLevel]->ScatterDrawParameters.SRV); SavedStartIndex.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.Level[DepthLevel]->SavedStartIndex); } void UnsetParameters(FRHICommandList& RHICmdList) { SavedStartIndex.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DrawParameters; Ar << SavedStartIndex; return bShaderHasOutdatedParameters; } private: FShaderResourceParameter DrawParameters; FRWShaderParameter SavedStartIndex; }; IMPLEMENT_SHADER_TYPE(,FSaveStartIndexCS,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("SaveStartIndexCS"),SF_Compute); class FPopulateCacheCS : public FGlobalShader { DECLARE_SHADER_TYPE(FPopulateCacheCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), GDistanceFieldAOTileSizeX); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), GDistanceFieldAOTileSizeY); OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); // To reduce shader compile time of compute shaders with shared memory, doesn't have an impact on generated code with current compiler (June 2010 DX SDK) OutEnvironment.CompilerFlags.Add(CFLAG_StandardOptimization); } FPopulateCacheCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DeferredParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); IrradianceCachePositionRadius.Bind(Initializer.ParameterMap, TEXT("IrradianceCachePositionRadius")); IrradianceCacheNormal.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheNormal")); IrradianceCacheTileCoordinate.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheTileCoordinate")); ScatterDrawParameters.Bind(Initializer.ParameterMap, TEXT("ScatterDrawParameters")); ViewDimensionsParameter.Bind(Initializer.ParameterMap, TEXT("ViewDimensions")); ThreadToCulledTile.Bind(Initializer.ParameterMap, TEXT("ThreadToCulledTile")); TileListGroupSize.Bind(Initializer.ParameterMap, TEXT("TileListGroupSize")); NumCircleSections.Bind(Initializer.ParameterMap, TEXT("NumCircleSections")); DistanceFieldNormalTexture.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormalTexture")); DistanceFieldNormalSampler.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormalSampler")); IrradianceCacheSplatTexture.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheSplatTexture")); IrradianceCacheSplatSampler.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheSplatSampler")); AOLevelParameters.Bind(Initializer.ParameterMap); } FPopulateCacheCS() { } void SetParameters( FRHICommandList& RHICmdList, const FSceneView& View, FSceneRenderTargetItem& DistanceFieldAOIrradianceCacheSplat, FSceneRenderTargetItem& DistanceFieldNormal, int32 DownsampleFactorValue, int32 DepthLevel, FIntPoint TileListGroupSizeValue, const FDistanceFieldAOParameters& Parameters) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); DeferredParameters.Set(RHICmdList, ShaderRHI, View); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); AOLevelParameters.Set(RHICmdList, ShaderRHI, View, DownsampleFactorValue); const FScene* Scene = (const FScene*)View.Family->Scene; FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; IrradianceCachePositionRadius.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.Level[DepthLevel]->PositionAndRadius); IrradianceCacheNormal.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.Level[DepthLevel]->Normal); IrradianceCacheTileCoordinate.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.Level[DepthLevel]->TileCoordinate); ScatterDrawParameters.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.Level[DepthLevel]->ScatterDrawParameters); SetShaderValue(RHICmdList, ShaderRHI, ViewDimensionsParameter, View.ViewRect); FAOSampleData2 AOSampleData; TArray<FVector, TInlineAllocator<9> > SampleDirections; GetSpacedVectors(SampleDirections); for (int32 SampleIndex = 0; SampleIndex < NumConeSampleDirections; SampleIndex++) { AOSampleData.SampleDirections[SampleIndex] = FVector4(SampleDirections[SampleIndex]); } SetUniformBufferParameterImmediate(RHICmdList, ShaderRHI, GetUniformBufferParameter<FAOSampleData2>(), AOSampleData); FVector2D ThreadToCulledTileValue(DownsampleFactorValue / (float)(GAODownsampleFactor * GDistanceFieldAOTileSizeX), DownsampleFactorValue / (float)(GAODownsampleFactor * GDistanceFieldAOTileSizeY)); SetShaderValue(RHICmdList, ShaderRHI, ThreadToCulledTile, ThreadToCulledTileValue); SetShaderValue(RHICmdList, ShaderRHI, TileListGroupSize, TileListGroupSizeValue); SetShaderValue(RHICmdList, ShaderRHI, NumCircleSections, GCircleVertexBuffer.NumSections); SetTextureParameter( RHICmdList, ShaderRHI, DistanceFieldNormalTexture, DistanceFieldNormalSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), DistanceFieldNormal.ShaderResourceTexture ); SetTextureParameter( RHICmdList, ShaderRHI, IrradianceCacheSplatTexture, IrradianceCacheSplatSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), DistanceFieldAOIrradianceCacheSplat.ShaderResourceTexture ); } void UnsetParameters(FRHICommandList& RHICmdList) { IrradianceCachePositionRadius.UnsetUAV(RHICmdList, GetComputeShader()); IrradianceCacheNormal.UnsetUAV(RHICmdList, GetComputeShader()); IrradianceCacheTileCoordinate.UnsetUAV(RHICmdList, GetComputeShader()); ScatterDrawParameters.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DeferredParameters; Ar << AOParameters; Ar << AOLevelParameters; Ar << IrradianceCachePositionRadius; Ar << IrradianceCacheNormal; Ar << IrradianceCacheTileCoordinate; Ar << ScatterDrawParameters; Ar << ViewDimensionsParameter; Ar << ThreadToCulledTile; Ar << TileListGroupSize; Ar << NumCircleSections; Ar << DistanceFieldNormalTexture; Ar << DistanceFieldNormalSampler; Ar << IrradianceCacheSplatTexture; Ar << IrradianceCacheSplatSampler; return bShaderHasOutdatedParameters; } private: FDeferredPixelShaderParameters DeferredParameters; FAOParameters AOParameters; FAOLevelParameters AOLevelParameters; FRWShaderParameter IrradianceCachePositionRadius; FRWShaderParameter IrradianceCacheNormal; FRWShaderParameter IrradianceCacheTileCoordinate; FRWShaderParameter ScatterDrawParameters; FShaderParameter ViewDimensionsParameter; FShaderParameter ThreadToCulledTile; FShaderParameter TileListGroupSize; FShaderParameter NumCircleSections; FShaderResourceParameter DistanceFieldNormalTexture; FShaderResourceParameter DistanceFieldNormalSampler; FShaderResourceParameter IrradianceCacheSplatTexture; FShaderResourceParameter IrradianceCacheSplatSampler; }; IMPLEMENT_SHADER_TYPE(,FPopulateCacheCS,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("PopulateCacheCS"),SF_Compute); IMPLEMENT_SHADER_TYPE(template<>,TSetupFinalGatherIndirectArgumentsCS<true>,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("SetupFinalGatherIndirectArgumentsCS"),SF_Compute); IMPLEMENT_SHADER_TYPE(template<>,TSetupFinalGatherIndirectArgumentsCS<false>,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("SetupFinalGatherIndirectArgumentsCS"),SF_Compute); template<bool bSupportIrradiance> class TConeTraceSurfaceCacheOcclusionCS : public FGlobalShader { DECLARE_SHADER_TYPE(TConeTraceSurfaceCacheOcclusionCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); OutEnvironment.SetDefine(TEXT("SUPPORT_IRRADIANCE"), bSupportIrradiance ? TEXT("1") : TEXT("0")); // To reduce shader compile time of compute shaders with shared memory, doesn't have an impact on generated code with current compiler (June 2010 DX SDK) OutEnvironment.CompilerFlags.Add(CFLAG_StandardOptimization); } TConeTraceSurfaceCacheOcclusionCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DeferredParameters.Bind(Initializer.ParameterMap); ObjectParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); IrradianceCachePositionRadius.Bind(Initializer.ParameterMap, TEXT("IrradianceCachePositionRadius")); TileConeDepthRanges.Bind(Initializer.ParameterMap, TEXT("TileConeDepthRanges")); IrradianceCacheNormal.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheNormal")); OccluderRadius.Bind(Initializer.ParameterMap, TEXT("OccluderRadius")); RecordConeVisibility.Bind(Initializer.ParameterMap, TEXT("RecordConeVisibility")); RecordConeData.Bind(Initializer.ParameterMap, TEXT("RecordConeData")); IrradianceCacheTileCoordinate.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheTileCoordinate")); ScatterDrawParameters.Bind(Initializer.ParameterMap, TEXT("ScatterDrawParameters")); SavedStartIndex.Bind(Initializer.ParameterMap, TEXT("SavedStartIndex")); ViewDimensionsParameter.Bind(Initializer.ParameterMap, TEXT("ViewDimensions")); ThreadToCulledTile.Bind(Initializer.ParameterMap, TEXT("ThreadToCulledTile")); TileHeadDataUnpacked.Bind(Initializer.ParameterMap, TEXT("TileHeadDataUnpacked")); TileArrayData.Bind(Initializer.ParameterMap, TEXT("TileArrayData")); TileListGroupSize.Bind(Initializer.ParameterMap, TEXT("TileListGroupSize")); TanConeHalfAngle.Bind(Initializer.ParameterMap, TEXT("TanConeHalfAngle")); BentNormalNormalizeFactor.Bind(Initializer.ParameterMap, TEXT("BentNormalNormalizeFactor")); DistanceFieldAtlasTexelSize.Bind(Initializer.ParameterMap, TEXT("DistanceFieldAtlasTexelSize")); DistanceFieldNormalTexture.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormalTexture")); DistanceFieldNormalSampler.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormalSampler")); IrradianceCacheSplatTexture.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheSplatTexture")); IrradianceCacheSplatSampler.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheSplatSampler")); AOLevelParameters.Bind(Initializer.ParameterMap); RecordRadiusScale.Bind(Initializer.ParameterMap, TEXT("RecordRadiusScale")); } TConeTraceSurfaceCacheOcclusionCS() { } void SetParameters( FRHICommandList& RHICmdList, const FSceneView& View, FSceneRenderTargetItem& DistanceFieldAOIrradianceCacheSplat, FSceneRenderTargetItem& DistanceFieldNormal, int32 DownsampleFactorValue, int32 DepthLevel, FIntPoint TileListGroupSizeValue, const FDistanceFieldAOParameters& Parameters) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); DeferredParameters.Set(RHICmdList, ShaderRHI, View); ObjectParameters.Set(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); AOLevelParameters.Set(RHICmdList, ShaderRHI, View, DownsampleFactorValue); const FScene* Scene = (const FScene*)View.Family->Scene; FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; SetSRVParameter(RHICmdList, ShaderRHI, IrradianceCacheNormal, SurfaceCacheResources.Level[DepthLevel]->Normal.SRV); SetSRVParameter(RHICmdList, ShaderRHI, ScatterDrawParameters, SurfaceCacheResources.Level[DepthLevel]->ScatterDrawParameters.SRV); SetSRVParameter(RHICmdList, ShaderRHI, SavedStartIndex, SurfaceCacheResources.Level[DepthLevel]->SavedStartIndex.SRV); SetSRVParameter(RHICmdList, ShaderRHI, IrradianceCachePositionRadius, SurfaceCacheResources.Level[DepthLevel]->PositionAndRadius.SRV); OccluderRadius.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.Level[DepthLevel]->OccluderRadius); RecordConeVisibility.SetBuffer(RHICmdList, ShaderRHI, GTemporaryIrradianceCacheResources.ConeVisibility); RecordConeData.SetBuffer(RHICmdList, ShaderRHI, GTemporaryIrradianceCacheResources.ConeData); SetShaderValue(RHICmdList, ShaderRHI, ViewDimensionsParameter, View.ViewRect); FAOSampleData2 AOSampleData; TArray<FVector, TInlineAllocator<9> > SampleDirections; GetSpacedVectors(SampleDirections); for (int32 SampleIndex = 0; SampleIndex < NumConeSampleDirections; SampleIndex++) { AOSampleData.SampleDirections[SampleIndex] = FVector4(SampleDirections[SampleIndex]); } SetUniformBufferParameterImmediate(RHICmdList, ShaderRHI, GetUniformBufferParameter<FAOSampleData2>(), AOSampleData); FVector2D ThreadToCulledTileValue(DownsampleFactorValue / (float)(GAODownsampleFactor * GDistanceFieldAOTileSizeX), DownsampleFactorValue / (float)(GAODownsampleFactor * GDistanceFieldAOTileSizeY)); SetShaderValue(RHICmdList, ShaderRHI, ThreadToCulledTile, ThreadToCulledTileValue); FTileIntersectionResources* TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources; SetSRVParameter(RHICmdList, ShaderRHI, TileHeadDataUnpacked, TileIntersectionResources->TileHeadDataUnpacked.SRV); SetSRVParameter(RHICmdList, ShaderRHI, TileArrayData, TileIntersectionResources->TileArrayData.SRV); SetSRVParameter(RHICmdList, ShaderRHI, IrradianceCacheTileCoordinate, SurfaceCacheResources.Level[DepthLevel]->TileCoordinate.SRV); SetSRVParameter(RHICmdList, ShaderRHI, TileConeDepthRanges, TileIntersectionResources->TileConeDepthRanges.SRV); SetShaderValue(RHICmdList, ShaderRHI, TileListGroupSize, TileListGroupSizeValue); SetShaderValue(RHICmdList, ShaderRHI, TanConeHalfAngle, FMath::Tan(GAOConeHalfAngle)); FVector UnoccludedVector(0); for (int32 SampleIndex = 0; SampleIndex < NumConeSampleDirections; SampleIndex++) { UnoccludedVector += SampleDirections[SampleIndex]; } float BentNormalNormalizeFactorValue = 1.0f / (UnoccludedVector / NumConeSampleDirections).Size(); SetShaderValue(RHICmdList, ShaderRHI, BentNormalNormalizeFactor, BentNormalNormalizeFactorValue); const int32 NumTexelsOneDimX = GDistanceFieldVolumeTextureAtlas.GetSizeX(); const int32 NumTexelsOneDimY = GDistanceFieldVolumeTextureAtlas.GetSizeY(); const int32 NumTexelsOneDimZ = GDistanceFieldVolumeTextureAtlas.GetSizeZ(); const FVector InvTextureDim(1.0f / NumTexelsOneDimX, 1.0f / NumTexelsOneDimY, 1.0f / NumTexelsOneDimZ); SetShaderValue(RHICmdList, ShaderRHI, DistanceFieldAtlasTexelSize, InvTextureDim); SetTextureParameter( RHICmdList, ShaderRHI, DistanceFieldNormalTexture, DistanceFieldNormalSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), DistanceFieldNormal.ShaderResourceTexture ); SetTextureParameter( RHICmdList, ShaderRHI, IrradianceCacheSplatTexture, IrradianceCacheSplatSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), DistanceFieldAOIrradianceCacheSplat.ShaderResourceTexture ); SetShaderValue(RHICmdList, ShaderRHI, RecordRadiusScale, GAORecordRadiusScale); } void UnsetParameters(FRHICommandList& RHICmdList) { OccluderRadius.UnsetUAV(RHICmdList, GetComputeShader()); RecordConeVisibility.UnsetUAV(RHICmdList, GetComputeShader()); RecordConeData.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DeferredParameters; Ar << ObjectParameters; Ar << AOParameters; Ar << AOLevelParameters; Ar << IrradianceCachePositionRadius; Ar << TileConeDepthRanges; Ar << IrradianceCacheNormal; Ar << OccluderRadius; Ar << RecordConeVisibility; Ar << RecordConeData; Ar << IrradianceCacheTileCoordinate; Ar << ScatterDrawParameters; Ar << SavedStartIndex; Ar << ViewDimensionsParameter; Ar << ThreadToCulledTile; Ar << TileHeadDataUnpacked; Ar << TileArrayData; Ar << TileListGroupSize; Ar << TanConeHalfAngle; Ar << BentNormalNormalizeFactor; Ar << DistanceFieldAtlasTexelSize; Ar << DistanceFieldNormalTexture; Ar << DistanceFieldNormalSampler; Ar << IrradianceCacheSplatTexture; Ar << IrradianceCacheSplatSampler; Ar << RecordRadiusScale; return bShaderHasOutdatedParameters; } private: FDeferredPixelShaderParameters DeferredParameters; FDistanceFieldCulledObjectBufferParameters ObjectParameters; FAOParameters AOParameters; FAOLevelParameters AOLevelParameters; FShaderResourceParameter IrradianceCacheNormal; FShaderResourceParameter IrradianceCachePositionRadius; FShaderResourceParameter TileConeDepthRanges; FRWShaderParameter OccluderRadius; FRWShaderParameter RecordConeVisibility; FRWShaderParameter RecordConeData; FShaderResourceParameter ScatterDrawParameters; FShaderResourceParameter SavedStartIndex; FShaderResourceParameter IrradianceCacheTileCoordinate; FShaderParameter ViewDimensionsParameter; FShaderParameter ThreadToCulledTile; FShaderResourceParameter TileHeadDataUnpacked; FShaderResourceParameter TileArrayData; FShaderParameter TileListGroupSize; FShaderParameter TanConeHalfAngle; FShaderParameter BentNormalNormalizeFactor; FShaderParameter DistanceFieldAtlasTexelSize; FShaderResourceParameter DistanceFieldNormalTexture; FShaderResourceParameter DistanceFieldNormalSampler; FShaderResourceParameter IrradianceCacheSplatTexture; FShaderResourceParameter IrradianceCacheSplatSampler; FShaderParameter RecordRadiusScale; }; IMPLEMENT_SHADER_TYPE(template<>,TConeTraceSurfaceCacheOcclusionCS<true>,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("ConeTraceOcclusionCS"),SF_Compute); IMPLEMENT_SHADER_TYPE(template<>,TConeTraceSurfaceCacheOcclusionCS<false>,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("ConeTraceOcclusionCS"),SF_Compute); class FCombineConesCS : public FGlobalShader { DECLARE_SHADER_TYPE(FCombineConesCS,Global) public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); // To reduce shader compile time of compute shaders with shared memory, doesn't have an impact on generated code with current compiler (June 2010 DX SDK) OutEnvironment.CompilerFlags.Add(CFLAG_StandardOptimization); } FCombineConesCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { AOParameters.Bind(Initializer.ParameterMap); IrradianceCacheBentNormal.Bind(Initializer.ParameterMap, TEXT("IrradianceCacheBentNormal")); CacheParameters.Bind(Initializer.ParameterMap); RecordConeVisibility.Bind(Initializer.ParameterMap, TEXT("RecordConeVisibility")); ScatterDrawParameters.Bind(Initializer.ParameterMap, TEXT("ScatterDrawParameters")); SavedStartIndex.Bind(Initializer.ParameterMap, TEXT("SavedStartIndex")); BentNormalNormalizeFactor.Bind(Initializer.ParameterMap, TEXT("BentNormalNormalizeFactor")); TanConeHalfAngle.Bind(Initializer.ParameterMap, TEXT("TanConeHalfAngle")); } FCombineConesCS() { } void SetParameters( FRHICommandList& RHICmdList, const FSceneView& View, int32 DepthLevel, const FDistanceFieldAOParameters& Parameters, const FLightSceneProxy* DirectionalLight, const FMatrix& WorldToShadowMatrixValue, FLightTileIntersectionResources* TileIntersectionResources, FVPLResources* VPLResources) { FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); const FScene* Scene = (const FScene*)View.Family->Scene; FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; CacheParameters.Set(RHICmdList, ShaderRHI, *SurfaceCacheResources.Level[DepthLevel]); SetSRVParameter(RHICmdList, ShaderRHI, ScatterDrawParameters, SurfaceCacheResources.Level[DepthLevel]->ScatterDrawParameters.SRV); SetSRVParameter(RHICmdList, ShaderRHI, SavedStartIndex, SurfaceCacheResources.Level[DepthLevel]->SavedStartIndex.SRV); SetSRVParameter(RHICmdList, ShaderRHI, RecordConeVisibility, GTemporaryIrradianceCacheResources.ConeVisibility.SRV); IrradianceCacheBentNormal.SetBuffer(RHICmdList, ShaderRHI, SurfaceCacheResources.Level[DepthLevel]->BentNormal); FAOSampleData2 AOSampleData; TArray<FVector, TInlineAllocator<9> > SampleDirections; GetSpacedVectors(SampleDirections); for (int32 SampleIndex = 0; SampleIndex < NumConeSampleDirections; SampleIndex++) { AOSampleData.SampleDirections[SampleIndex] = FVector4(SampleDirections[SampleIndex]); } SetUniformBufferParameterImmediate(RHICmdList, ShaderRHI, GetUniformBufferParameter<FAOSampleData2>(), AOSampleData); FVector UnoccludedVector(0); for (int32 SampleIndex = 0; SampleIndex < NumConeSampleDirections; SampleIndex++) { UnoccludedVector += SampleDirections[SampleIndex]; } float BentNormalNormalizeFactorValue = 1.0f / (UnoccludedVector / NumConeSampleDirections).Size(); SetShaderValue(RHICmdList, ShaderRHI, BentNormalNormalizeFactor, BentNormalNormalizeFactorValue); SetShaderValue(RHICmdList, ShaderRHI, TanConeHalfAngle, FMath::Tan(GAOConeHalfAngle)); } void UnsetParameters(FRHICommandList& RHICmdList) { IrradianceCacheBentNormal.UnsetUAV(RHICmdList, GetComputeShader()); } virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << AOParameters; Ar << IrradianceCacheBentNormal; Ar << CacheParameters; Ar << RecordConeVisibility; Ar << ScatterDrawParameters; Ar << SavedStartIndex; Ar << BentNormalNormalizeFactor; Ar << TanConeHalfAngle; return bShaderHasOutdatedParameters; } private: FAOParameters AOParameters; FRWShaderParameter IrradianceCacheBentNormal; FIrradianceCacheParameters CacheParameters; FShaderResourceParameter RecordConeVisibility; FShaderResourceParameter ScatterDrawParameters; FShaderResourceParameter SavedStartIndex; FShaderParameter BentNormalNormalizeFactor; FShaderParameter TanConeHalfAngle; }; IMPLEMENT_SHADER_TYPE(,FCombineConesCS,TEXT("DistanceFieldSurfaceCacheLightingCompute"),TEXT("CombineConesCS"),SF_Compute); class FWriteDownsampledDepthPS : public FGlobalShader { DECLARE_SHADER_TYPE(FWriteDownsampledDepthPS, Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); } /** Default constructor. */ FWriteDownsampledDepthPS() {} /** Initialization constructor. */ FWriteDownsampledDepthPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DeferredParameters.Bind(Initializer.ParameterMap); DistanceFieldNormalTexture.Bind(Initializer.ParameterMap,TEXT("DistanceFieldNormalTexture")); DistanceFieldNormalSampler.Bind(Initializer.ParameterMap,TEXT("DistanceFieldNormalSampler")); } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FSceneRenderTargetItem& DistanceFieldNormal) { const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); DeferredParameters.Set(RHICmdList, ShaderRHI, View); SetTextureParameter(RHICmdList, ShaderRHI, DistanceFieldNormalTexture, DistanceFieldNormalSampler, TStaticSamplerState<SF_Point>::GetRHI(), DistanceFieldNormal.ShaderResourceTexture); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DeferredParameters; Ar << DistanceFieldNormalTexture; Ar << DistanceFieldNormalSampler; return bShaderHasOutdatedParameters; } private: FDeferredPixelShaderParameters DeferredParameters; FShaderResourceParameter DistanceFieldNormalTexture; FShaderResourceParameter DistanceFieldNormalSampler; }; IMPLEMENT_SHADER_TYPE(,FWriteDownsampledDepthPS,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("WriteDownsampledDepthPS"),SF_Pixel); /** */ template<bool bFinalInterpolationPass, bool bSupportIrradiance> class TIrradianceCacheSplatVS : public FGlobalShader { DECLARE_SHADER_TYPE(TIrradianceCacheSplatVS,Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("FINAL_INTERPOLATION_PASS"), (uint32)bFinalInterpolationPass); OutEnvironment.SetDefine(TEXT("SUPPORT_IRRADIANCE"), bSupportIrradiance ? TEXT("1") : TEXT("0")); } TIrradianceCacheSplatVS(const ShaderMetaType::CompiledShaderInitializerType& Initializer): FGlobalShader(Initializer) { CacheParameters.Bind(Initializer.ParameterMap); InterpolationRadiusScale.Bind(Initializer.ParameterMap, TEXT("InterpolationRadiusScale")); NormalizedOffsetToPixelCenter.Bind(Initializer.ParameterMap, TEXT("NormalizedOffsetToPixelCenter")); HackExpand.Bind(Initializer.ParameterMap, TEXT("HackExpand")); InterpolationBoundingDirection.Bind(Initializer.ParameterMap, TEXT("InterpolationBoundingDirection")); AOParameters.Bind(Initializer.ParameterMap); } TIrradianceCacheSplatVS() {} void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, const FDistanceFieldAOParameters& Parameters, int32 DepthLevel, int32 CurrentLevelDownsampleFactorValue, FVector2D NormalizedOffsetToPixelCenterValue) { const FVertexShaderRHIParamRef ShaderRHI = GetVertexShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); const FScene* Scene = (const FScene*)View.Family->Scene; FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; CacheParameters.Set(RHICmdList, ShaderRHI, *SurfaceCacheResources.Level[DepthLevel]); SetShaderValue(RHICmdList, ShaderRHI, InterpolationRadiusScale, (bFinalInterpolationPass ? GAOInterpolationRadiusScale : 1.0f)); SetShaderValue(RHICmdList, ShaderRHI, NormalizedOffsetToPixelCenter, NormalizedOffsetToPixelCenterValue); const FIntPoint AOViewRectSize = FIntPoint::DivideAndRoundUp(View.ViewRect.Size(), CurrentLevelDownsampleFactorValue); const FVector2D HackExpandValue(.5f / AOViewRectSize.X, .5f / AOViewRectSize.Y); SetShaderValue(RHICmdList, ShaderRHI, HackExpand, HackExpandValue); // Must push the bounding geometry toward the camera with depth testing, to be in front of any potential receivers SetShaderValue(RHICmdList, ShaderRHI, InterpolationBoundingDirection, GAOInterpolationDepthTesting ? -1.0f : 1.0f); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); } virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << CacheParameters; Ar << InterpolationRadiusScale; Ar << NormalizedOffsetToPixelCenter; Ar << HackExpand; Ar << InterpolationBoundingDirection; Ar << AOParameters; return bShaderHasOutdatedParameters; } private: FIrradianceCacheParameters CacheParameters; FShaderParameter InterpolationRadiusScale; FShaderParameter NormalizedOffsetToPixelCenter; FShaderParameter HackExpand; FShaderParameter InterpolationBoundingDirection; FAOParameters AOParameters; }; // typedef required to get around macro expansion failure due to commas in template argument list #define IMPLEMENT_SPLAT_VS_TYPE(bFinalInterpolationPass, bSupportIrradiance) \ typedef TIrradianceCacheSplatVS<bFinalInterpolationPass, bSupportIrradiance> TIrradianceCacheSplatVS##bFinalInterpolationPass##bSupportIrradiance; \ IMPLEMENT_SHADER_TYPE(template<>,TIrradianceCacheSplatVS##bFinalInterpolationPass##bSupportIrradiance,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("IrradianceCacheSplatVS"),SF_Vertex); IMPLEMENT_SPLAT_VS_TYPE(true, true) IMPLEMENT_SPLAT_VS_TYPE(false, true) IMPLEMENT_SPLAT_VS_TYPE(true, false) IMPLEMENT_SPLAT_VS_TYPE(false, false) template<bool bFinalInterpolationPass, bool bSupportIrradiance> class TIrradianceCacheSplatPS : public FGlobalShader { DECLARE_SHADER_TYPE(TIrradianceCacheSplatPS, Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); OutEnvironment.SetDefine(TEXT("FINAL_INTERPOLATION_PASS"), (uint32)bFinalInterpolationPass); OutEnvironment.SetDefine(TEXT("SUPPORT_IRRADIANCE"), bSupportIrradiance ? TEXT("1") : TEXT("0")); } /** Default constructor. */ TIrradianceCacheSplatPS() {} /** Initialization constructor. */ TIrradianceCacheSplatPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { AOParameters.Bind(Initializer.ParameterMap); DeferredParameters.Bind(Initializer.ParameterMap); AOLevelParameters.Bind(Initializer.ParameterMap); DistanceFieldNormalTexture.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormalTexture")); DistanceFieldNormalSampler.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormalSampler")); InterpolationAngleNormalization.Bind(Initializer.ParameterMap, TEXT("InterpolationAngleNormalization")); InvMinCosPointBehindPlane.Bind(Initializer.ParameterMap, TEXT("InvMinCosPointBehindPlane")); } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FSceneRenderTargetItem& DistanceFieldNormal, int32 DestLevelDownsampleFactor, const FDistanceFieldAOParameters& Parameters) { const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); DeferredParameters.Set(RHICmdList, ShaderRHI, View); AOLevelParameters.Set(RHICmdList, ShaderRHI, View, DestLevelDownsampleFactor); SetTextureParameter( RHICmdList, ShaderRHI, DistanceFieldNormalTexture, DistanceFieldNormalSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), DistanceFieldNormal.ShaderResourceTexture ); const float EffectiveMaxAngle = bFinalInterpolationPass ? GAOInterpolationMaxAngle * GAOInterpolationAngleScale : GAOInterpolationMaxAngle; const float InterpolationAngleNormalizationValue = 1.0f / FMath::Sqrt(1.0f - FMath::Cos(EffectiveMaxAngle * PI / 180.0f)); SetShaderValue(RHICmdList, ShaderRHI, InterpolationAngleNormalization, InterpolationAngleNormalizationValue); const float MinCosPointBehindPlaneValue = FMath::Cos((GAOMinPointBehindPlaneAngle + 90.0f) * PI / 180.0f); SetShaderValue(RHICmdList, ShaderRHI, InvMinCosPointBehindPlane, 1.0f / MinCosPointBehindPlaneValue); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << AOParameters; Ar << AOLevelParameters; Ar << DeferredParameters; Ar << DistanceFieldNormalTexture; Ar << DistanceFieldNormalSampler; Ar << InterpolationAngleNormalization; Ar << InvMinCosPointBehindPlane; return bShaderHasOutdatedParameters; } private: FAOParameters AOParameters; FAOLevelParameters AOLevelParameters; FDeferredPixelShaderParameters DeferredParameters; FShaderResourceParameter DistanceFieldNormalTexture; FShaderResourceParameter DistanceFieldNormalSampler; FShaderParameter InterpolationAngleNormalization; FShaderParameter InvMinCosPointBehindPlane; }; // typedef required to get around macro expansion failure due to commas in template argument list #define IMPLEMENT_SPLAT_PS_TYPE(bFinalInterpolationPass, bSupportIrradiance) \ typedef TIrradianceCacheSplatPS<bFinalInterpolationPass, bSupportIrradiance> TIrradianceCacheSplatPS##bFinalInterpolationPass##bSupportIrradiance; \ IMPLEMENT_SHADER_TYPE(template<>,TIrradianceCacheSplatPS##bFinalInterpolationPass##bSupportIrradiance,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("IrradianceCacheSplatPS"),SF_Pixel); IMPLEMENT_SPLAT_PS_TYPE(true, true) IMPLEMENT_SPLAT_PS_TYPE(false, true) IMPLEMENT_SPLAT_PS_TYPE(true, false) IMPLEMENT_SPLAT_PS_TYPE(false, false) /** Generates a pseudo-random position inside the unit sphere, uniformly distributed over the volume of the sphere. */ FVector GetUnitPosition2(FRandomStream& RandomStream) { FVector Result; // Use rejection sampling to generate a valid sample do { Result.X = RandomStream.GetFraction() * 2 - 1; Result.Y = RandomStream.GetFraction() * 2 - 1; Result.Z = RandomStream.GetFraction() * 2 - 1; } while( Result.SizeSquared() > 1.f ); return Result; } /** Generates a pseudo-random unit vector, uniformly distributed over all directions. */ FVector GetUnitVector2(FRandomStream& RandomStream) { return GetUnitPosition2(RandomStream).GetUnsafeNormal(); } void GenerateBestSpacedVectors() { static bool bGenerated = false; bool bApplyRepulsion = false; if (bApplyRepulsion && !bGenerated) { bGenerated = true; FVector OriginalSpacedVectors9[ARRAY_COUNT(SpacedVectors9)]; for (int32 i = 0; i < ARRAY_COUNT(OriginalSpacedVectors9); i++) { OriginalSpacedVectors9[i] = SpacedVectors9[i]; } float CosHalfAngle = 1 - 1.0f / (float)ARRAY_COUNT(OriginalSpacedVectors9); // Used to prevent self-shadowing on a plane float AngleBias = .03f; float MinAngle = FMath::Acos(CosHalfAngle) + AngleBias; float MinZ = FMath::Sin(MinAngle); // Relaxation iterations by repulsion for (int32 Iteration = 0; Iteration < 10000; Iteration++) { for (int32 i = 0; i < ARRAY_COUNT(OriginalSpacedVectors9); i++) { FVector Force(0.0f, 0.0f, 0.0f); for (int32 j = 0; j < ARRAY_COUNT(OriginalSpacedVectors9); j++) { if (i != j) { FVector Distance = OriginalSpacedVectors9[i] - OriginalSpacedVectors9[j]; float Dot = OriginalSpacedVectors9[i] | OriginalSpacedVectors9[j]; if (Dot > 0) { // Repulsion force Force += .001f * Distance.GetSafeNormal() * Dot * Dot * Dot * Dot; } } } FVector NewPosition = OriginalSpacedVectors9[i] + Force; NewPosition.Z = FMath::Max(NewPosition.Z, MinZ); NewPosition = NewPosition.GetSafeNormal(); OriginalSpacedVectors9[i] = NewPosition; } } for (int32 i = 0; i < ARRAY_COUNT(OriginalSpacedVectors9); i++) { UE_LOG(LogDistanceField, Log, TEXT("FVector(%f, %f, %f),"), OriginalSpacedVectors9[i].X, OriginalSpacedVectors9[i].Y, OriginalSpacedVectors9[i].Z); } int32 temp = 0; } bool bBruteForceGenerateConeDirections = false; if (bBruteForceGenerateConeDirections) { FVector BestSpacedVectors9[9]; float BestCoverage = 0; // Each cone covers an area of ConeSolidAngle = HemisphereSolidAngle / NumCones // HemisphereSolidAngle = 2 * PI // ConeSolidAngle = 2 * PI * (1 - cos(ConeHalfAngle)) // cos(ConeHalfAngle) = 1 - 1 / NumCones float CosHalfAngle = 1 - 1.0f / (float)ARRAY_COUNT(BestSpacedVectors9); // Prevent self-intersection in sample set float MinAngle = FMath::Acos(CosHalfAngle); float MinZ = FMath::Sin(MinAngle); FRandomStream RandomStream(123567); // Super slow random brute force search for (int i = 0; i < 1000000; i++) { FVector CandidateSpacedVectors[ARRAY_COUNT(BestSpacedVectors9)]; for (int j = 0; j < ARRAY_COUNT(CandidateSpacedVectors); j++) { FVector NewSample; // Reject invalid directions until we get a valid one do { NewSample = GetUnitVector2(RandomStream); } while (NewSample.Z <= MinZ); CandidateSpacedVectors[j] = NewSample; } float Coverage = 0; int NumSamples = 10000; // Determine total cone coverage with monte carlo estimation for (int sample = 0; sample < NumSamples; sample++) { FVector NewSample; do { NewSample = GetUnitVector2(RandomStream); } while (NewSample.Z <= 0); bool bIntersects = false; for (int j = 0; j < ARRAY_COUNT(CandidateSpacedVectors); j++) { if (FVector::DotProduct(CandidateSpacedVectors[j], NewSample) > CosHalfAngle) { bIntersects = true; break; } } Coverage += bIntersects ? 1 / (float)NumSamples : 0; } if (Coverage > BestCoverage) { BestCoverage = Coverage; for (int j = 0; j < ARRAY_COUNT(CandidateSpacedVectors); j++) { BestSpacedVectors9[j] = CandidateSpacedVectors[j]; } } } int32 temp = 0; } } FIntPoint BuildTileObjectLists(FRHICommandListImmediate& RHICmdList, FScene* Scene, TArray<FViewInfo>& Views, FSceneRenderTargetItem& DistanceFieldNormal, const FDistanceFieldAOParameters& Parameters) { SCOPED_DRAW_EVENT(RHICmdList, BuildTileList); SetRenderTarget(RHICmdList, NULL, NULL); FIntPoint TileListGroupSize; if (GAOScatterTileCulling) { for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++) { const FViewInfo& View = Views[ViewIndex]; uint32 GroupSizeX = FMath::DivideAndRoundUp(View.ViewRect.Size().X / GAODownsampleFactor, GDistanceFieldAOTileSizeX); uint32 GroupSizeY = FMath::DivideAndRoundUp(View.ViewRect.Size().Y / GAODownsampleFactor, GDistanceFieldAOTileSizeY); TileListGroupSize = FIntPoint(GroupSizeX, GroupSizeY); FTileIntersectionResources*& TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources; if (!TileIntersectionResources || TileIntersectionResources->TileDimensions != TileListGroupSize) { if (TileIntersectionResources) { TileIntersectionResources->ReleaseResource(); } else { TileIntersectionResources = new FTileIntersectionResources(); } TileIntersectionResources->TileDimensions = TileListGroupSize; TileIntersectionResources->InitResource(); } { SCOPED_DRAW_EVENT(RHICmdList, BuildTileCones); TShaderMapRef<FBuildTileConesCS> ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DistanceFieldNormal, Scene, FVector2D(GroupSizeX, GroupSizeY), Parameters); DispatchComputeShader(RHICmdList, *ComputeShader, GroupSizeX, GroupSizeY, 1); ComputeShader->UnsetParameters(RHICmdList); } { SCOPED_DRAW_EVENT(RHICmdList, CullObjectsToTiles); TShaderMapRef<FObjectCullVS> VertexShader(View.ShaderMap); TShaderMapRef<FObjectCullPS> PixelShader(View.ShaderMap); TArray<FUnorderedAccessViewRHIParamRef> UAVs; PixelShader->GetUAVs(Views[0], UAVs); RHICmdList.SetRenderTargets(0, (const FRHIRenderTargetView*)NULL, NULL, UAVs.Num(), UAVs.GetData()); RHICmdList.SetViewport(0, 0, 0.0f, GroupSizeX, GroupSizeY, 1.0f); // Render backfaces since camera may intersect RHICmdList.SetRasterizerState(View.bReverseCulling ? TStaticRasterizerState<FM_Solid, CM_CW>::GetRHI() : TStaticRasterizerState<FM_Solid, CM_CCW>::GetRHI()); RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI()); RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI()); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GetVertexDeclarationFVector4(), *VertexShader, *PixelShader); VertexShader->SetParameters(RHICmdList, View, Parameters); PixelShader->SetParameters(RHICmdList, View, FVector2D(GroupSizeX, GroupSizeY), Parameters); RHICmdList.SetStreamSource(0, StencilingGeometry::GLowPolyStencilSphereVertexBuffer.VertexBufferRHI, sizeof(FVector4), 0); RHICmdList.DrawIndexedPrimitiveIndirect( PT_TriangleList, StencilingGeometry::GLowPolyStencilSphereIndexBuffer.IndexBufferRHI, GAOCulledObjectBuffers.Buffers.ObjectIndirectArguments.Buffer, 0); } } } else { for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++) { const FViewInfo& View = Views[ViewIndex]; uint32 GroupSizeX = (View.ViewRect.Size().X / GAODownsampleFactor + GDistanceFieldAOTileSizeX - 1) / GDistanceFieldAOTileSizeX; uint32 GroupSizeY = (View.ViewRect.Size().Y / GAODownsampleFactor + GDistanceFieldAOTileSizeY - 1) / GDistanceFieldAOTileSizeY; TileListGroupSize = FIntPoint(GroupSizeX, GroupSizeY); FTileIntersectionResources*& TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources; if (!TileIntersectionResources || TileIntersectionResources->TileDimensions != TileListGroupSize) { if (TileIntersectionResources) { TileIntersectionResources->ReleaseResource(); } else { TileIntersectionResources = new FTileIntersectionResources(); } TileIntersectionResources->TileDimensions = TileListGroupSize; TileIntersectionResources->InitResource(); } // Indicates the clear value for each channel of the UAV format uint32 ClearValues[4] = { 0 }; RHICmdList.ClearUAV(TileIntersectionResources->TileArrayNextAllocation.UAV, ClearValues); RHICmdList.ClearUAV(TileIntersectionResources->TileHeadDataUnpacked.UAV, ClearValues); TShaderMapRef<FDistanceFieldBuildTileListCS > ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, Scene, FVector2D(GroupSizeX, GroupSizeY), Parameters); DispatchComputeShader(RHICmdList, *ComputeShader, GroupSizeX, GroupSizeY, 1); ComputeShader->UnsetParameters(RHICmdList); } } return TileListGroupSize; } void SetupDepthStencil( FRHICommandListImmediate& RHICmdList, const FViewInfo& View, FSceneRenderTargetItem& SplatDepthStencilBuffer, FSceneRenderTargetItem& DistanceFieldNormal, int32 DepthLevel, int32 DestLevelDownsampleFactor) { SCOPED_DRAW_EVENT(RHICmdList, SetupDepthStencil); SetRenderTarget(RHICmdList, NULL, SplatDepthStencilBuffer.TargetableTexture); RHICmdList.Clear(false, FLinearColor(0, 0, 0, 0), true, 0, true, 0, FIntRect()); { RHICmdList.SetViewport(0, 0, 0.0f, View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor, 1.0f); RHICmdList.SetRasterizerState(TStaticRasterizerState<FM_Solid, CM_None>::GetRHI()); // Depth writes on RHICmdList.SetDepthStencilState(TStaticDepthStencilState<true, CF_Always>::GetRHI()); // Color writes off RHICmdList.SetBlendState(TStaticBlendState<CW_NONE>::GetRHI()); TShaderMapRef<FPostProcessVS> VertexShader(View.ShaderMap); TShaderMapRef<FWriteDownsampledDepthPS> PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); PixelShader->SetParameters(RHICmdList, View, DistanceFieldNormal); // Draw a quad writing depth out to the depth stencil view DrawRectangle( RHICmdList, 0, 0, View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor, 0, 0, View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor, FIntPoint(View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor), GetBufferSizeForAO(), *VertexShader); } if (GAOInterpolationStencilTesting) { RHICmdList.SetViewport(0, 0, 0.0f, View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor, 1.0f); RHICmdList.SetRasterizerState(TStaticRasterizerState<FM_Solid, CM_None>::GetRHI()); RHICmdList.SetBlendState(TStaticBlendState<CW_NONE>::GetRHI()); // Depth tests on, write 1 to stencil if depth test passed RHICmdList.SetDepthStencilState(TStaticDepthStencilState< false,CF_DepthNearOrEqual, true,CF_Always,SO_Keep,SO_Keep,SO_Replace, false,CF_Always,SO_Keep,SO_Keep,SO_Keep, 0xff,0xff >::GetRHI(), 1); TShaderMapRef<TOneColorVS<true> > VertexShader(View.ShaderMap); TShaderMapRef<FOneColorPS> PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GetVertexDeclarationFVector4(), *VertexShader, *PixelShader); PixelShader->SetColors(RHICmdList, &FLinearColor::Black, 1); FVector ViewSpaceMaxDistance(0.0f, 0.0f, GetMaxAOViewDistance()); FVector4 ClipSpaceMaxDistance = View.ViewMatrices.ProjMatrix.TransformPosition(ViewSpaceMaxDistance); float ClipSpaceZ = ClipSpaceMaxDistance.Z / ClipSpaceMaxDistance.W; // Place the quad's depth at the max AO view distance // Any pixels that pass the depth test should not receive AO and therefore write a 1 to stencil FVector4 ClearQuadVertices[4] = { FVector4( -1.0f, 1.0f, ClipSpaceZ, 1.0f ), FVector4( 1.0f, 1.0f, ClipSpaceZ, 1.0f ), FVector4( -1.0f, -1.0f, ClipSpaceZ, 1.0f ), FVector4( 1.0f, -1.0f, ClipSpaceZ, 1.0f ) }; DrawPrimitiveUP(RHICmdList, PT_TriangleStrip, 2, ClearQuadVertices, sizeof(ClearQuadVertices[0])); } RHICmdList.CopyToResolveTarget(SplatDepthStencilBuffer.TargetableTexture, SplatDepthStencilBuffer.ShaderResourceTexture, false, FResolveParams()); } void RenderIrradianceCacheInterpolation( FRHICommandListImmediate& RHICmdList, const FViewInfo& View, IPooledRenderTarget* BentNormalInterpolationTarget, IPooledRenderTarget* IrradianceInterpolationTarget, FSceneRenderTargetItem& DistanceFieldNormal, int32 DepthLevel, int32 DestLevelDownsampleFactor, const FDistanceFieldAOParameters& Parameters, bool bFinalInterpolation) { check(!(bFinalInterpolation && DepthLevel != 0)); const bool bUseDistanceFieldGI = IsDistanceFieldGIAllowed(View); { TRefCountPtr<IPooledRenderTarget> SplatDepthStencilBuffer; if (bFinalInterpolation && (GAOInterpolationDepthTesting || GAOInterpolationStencilTesting)) { FPooledRenderTargetDesc Desc(FPooledRenderTargetDesc::Create2DDesc(BentNormalInterpolationTarget->GetDesc().Extent, PF_DepthStencil, FClearValueBinding::DepthZero, TexCreate_None, TexCreate_DepthStencilTargetable, false)); GRenderTargetPool.FindFreeElement(Desc, SplatDepthStencilBuffer, TEXT("DistanceFieldAOSplatDepthBuffer")); SetupDepthStencil(RHICmdList, View, SplatDepthStencilBuffer->GetRenderTargetItem(), DistanceFieldNormal, DepthLevel, DestLevelDownsampleFactor); GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SplatDepthStencilBuffer); } SCOPED_DRAW_EVENT(RHICmdList, IrradianceCacheSplat); const bool bBindIrradiance = bUseDistanceFieldGI && bFinalInterpolation; FTextureRHIParamRef DepthBuffer = SplatDepthStencilBuffer ? SplatDepthStencilBuffer->GetRenderTargetItem().TargetableTexture : NULL; { FRHIRenderTargetView RenderTargets[MaxSimultaneousRenderTargets]; RenderTargets[0] = FRHIRenderTargetView(BentNormalInterpolationTarget->GetRenderTargetItem().TargetableTexture); RenderTargets[1] = FRHIRenderTargetView(bBindIrradiance ? IrradianceInterpolationTarget->GetRenderTargetItem().TargetableTexture : NULL); const int32 MRTCount = bBindIrradiance ? 2 : 1; FRHIDepthRenderTargetView DepthView(DepthBuffer); FRHISetRenderTargetsInfo Info(MRTCount, RenderTargets, DepthView); check(RenderTargets[0].Texture->GetClearColor() == FLinearColor::Transparent); check(!RenderTargets[1].Texture || RenderTargets[1].Texture->GetClearColor() == FLinearColor::Transparent); Info.bClearColor = true; // set the render target RHICmdList.SetRenderTargetsAndClear(Info); } static int32 NumInterpolationSections = 8; if (GCircleVertexBuffer.NumSections != NumInterpolationSections) { GCircleVertexBuffer.NumSections = NumInterpolationSections; GCircleVertexBuffer.UpdateRHI(); } { const FScene* Scene = (const FScene*)View.Family->Scene; FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; const uint32 DownsampledViewSizeX = FMath::DivideAndRoundUp(View.ViewRect.Width(), DestLevelDownsampleFactor); const uint32 DownsampledViewSizeY = FMath::DivideAndRoundUp(View.ViewRect.Height(), DestLevelDownsampleFactor); RHICmdList.SetViewport(0, 0, 0.0f, DownsampledViewSizeX, DownsampledViewSizeY, 1.0f); RHICmdList.SetRasterizerState(TStaticRasterizerState<FM_Solid, CM_None>::GetRHI()); if (bFinalInterpolation && (GAOInterpolationDepthTesting || GAOInterpolationStencilTesting)) { if (GAOInterpolationDepthTesting) { if (GAOInterpolationStencilTesting) { // Depth tests enabled, pass stencil test if stencil is zero RHICmdList.SetDepthStencilState(TStaticDepthStencilState< false,CF_DepthNearOrEqual, true,CF_Equal,SO_Keep,SO_Keep,SO_Keep, false,CF_Always,SO_Keep,SO_Keep,SO_Keep, 0xff,0xff >::GetRHI()); } else { // Depth tests enabled RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_DepthNearOrEqual>::GetRHI()); } } else if (GAOInterpolationStencilTesting) { // Pass stencil test if stencil is zero RHICmdList.SetDepthStencilState(TStaticDepthStencilState< false,CF_Always, true,CF_Equal,SO_Keep,SO_Keep,SO_Keep, false,CF_Always,SO_Keep,SO_Keep,SO_Keep, 0xff,0xff >::GetRHI()); } } else { RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI()); } RHICmdList.SetBlendState(TStaticBlendState<CW_RGBA, BO_Add, BF_One, BF_One, BO_Add, BF_One, BF_One, CW_RGBA, BO_Add, BF_One, BF_One, BO_Add, BF_One, BF_One>::GetRHI()); const FIntPoint BufferSize = FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY(); const float InvBufferSizeX = 1.0f / BufferSize.X; const float InvBufferSizeY = 1.0f / BufferSize.Y; const FVector2D ScreenPositionScale( View.ViewRect.Width() * InvBufferSizeX / +2.0f, View.ViewRect.Height() * InvBufferSizeY / (-2.0f * GProjectionSignY)); const FVector2D ScreenPositionBias( (View.ViewRect.Width() / 2.0f) * InvBufferSizeX, (View.ViewRect.Height() / 2.0f) * InvBufferSizeY); FVector2D OffsetToLowResCorner = (FVector2D(.5f, .5f) / FVector2D(DownsampledViewSizeX, DownsampledViewSizeY) - FVector2D(.5f, .5f)) * FVector2D(2, -2); FVector2D OffsetToTopResPixel = (FVector2D(.5f, .5f) / BufferSize - ScreenPositionBias) / ScreenPositionScale; FVector2D NormalizedOffsetToPixelCenter = OffsetToLowResCorner - OffsetToTopResPixel; RHICmdList.SetStreamSource(0, GCircleVertexBuffer.VertexBufferRHI, sizeof(FScreenVertex), 0); if (bFinalInterpolation) { for (int32 SplatSourceDepthLevel = GAOMaxLevel; SplatSourceDepthLevel >= FMath::Max(DepthLevel, GAOMinLevel); SplatSourceDepthLevel--) { if (bUseDistanceFieldGI) { TShaderMapRef<TIrradianceCacheSplatVS<true, true> > VertexShader(View.ShaderMap); TShaderMapRef<TIrradianceCacheSplatPS<true, true> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GScreenVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); VertexShader->SetParameters(RHICmdList, View, Parameters, SplatSourceDepthLevel, DestLevelDownsampleFactor, NormalizedOffsetToPixelCenter); PixelShader->SetParameters(RHICmdList, View, DistanceFieldNormal, DestLevelDownsampleFactor, Parameters); } else { TShaderMapRef<TIrradianceCacheSplatVS<true, false> > VertexShader(View.ShaderMap); TShaderMapRef<TIrradianceCacheSplatPS<true, false> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GScreenVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); VertexShader->SetParameters(RHICmdList, View, Parameters, SplatSourceDepthLevel, DestLevelDownsampleFactor, NormalizedOffsetToPixelCenter); PixelShader->SetParameters(RHICmdList, View, DistanceFieldNormal, DestLevelDownsampleFactor, Parameters); } RHICmdList.DrawPrimitiveIndirect(PT_TriangleList, SurfaceCacheResources.Level[SplatSourceDepthLevel]->ScatterDrawParameters.Buffer, 0); } } else { for (int32 SplatSourceDepthLevel = GAOMaxLevel; SplatSourceDepthLevel >= FMath::Max(DepthLevel, GAOMinLevel); SplatSourceDepthLevel--) { if (bUseDistanceFieldGI) { TShaderMapRef<TIrradianceCacheSplatVS<false, true> > VertexShader(View.ShaderMap); TShaderMapRef<TIrradianceCacheSplatPS<false, true> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GScreenVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); VertexShader->SetParameters(RHICmdList, View, Parameters, SplatSourceDepthLevel, DestLevelDownsampleFactor, NormalizedOffsetToPixelCenter); PixelShader->SetParameters(RHICmdList, View, DistanceFieldNormal, DestLevelDownsampleFactor, Parameters); } else { TShaderMapRef<TIrradianceCacheSplatVS<false, false> > VertexShader(View.ShaderMap); TShaderMapRef<TIrradianceCacheSplatPS<false, false> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GScreenVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); VertexShader->SetParameters(RHICmdList, View, Parameters, SplatSourceDepthLevel, DestLevelDownsampleFactor, NormalizedOffsetToPixelCenter); PixelShader->SetParameters(RHICmdList, View, DistanceFieldNormal, DestLevelDownsampleFactor, Parameters); } RHICmdList.DrawPrimitiveIndirect(PT_TriangleList, SurfaceCacheResources.Level[SplatSourceDepthLevel]->ScatterDrawParameters.Buffer, 0); } } } RHICmdList.CopyToResolveTarget(BentNormalInterpolationTarget->GetRenderTargetItem().TargetableTexture, BentNormalInterpolationTarget->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams()); if (bFinalInterpolation && bUseDistanceFieldGI && (GAOInterpolationDepthTesting || GAOInterpolationStencilTesting)) { RHICmdList.CopyToResolveTarget(IrradianceInterpolationTarget->GetRenderTargetItem().TargetableTexture, IrradianceInterpolationTarget->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams()); } } } void ListDistanceFieldLightingMemory(const FViewInfo& View) { const FScene* Scene = (const FScene*)View.Family->Scene; UE_LOG(LogTemp, Log, TEXT("Shared GPU memory (excluding render targets)")); if (Scene->DistanceFieldSceneData.NumObjectsInBuffer > 0) { UE_LOG(LogTemp, Log, TEXT(" Scene Object data %.3fMb"), Scene->DistanceFieldSceneData.ObjectBuffers->GetSizeBytes() / 1024.0f / 1024.0f); } UE_LOG(LogTemp, Log, TEXT(" %s"), *GDistanceFieldVolumeTextureAtlas.GetSizeString()); extern FString GetObjectBufferMemoryString(); UE_LOG(LogTemp, Log, TEXT(" %s"), *GetObjectBufferMemoryString()); UE_LOG(LogTemp, Log, TEXT("")); UE_LOG(LogTemp, Log, TEXT("Distance Field AO")); if (Scene->SurfaceCacheResources) { UE_LOG(LogTemp, Log, TEXT(" Surface cache %.3fMb"), Scene->SurfaceCacheResources->GetSizeBytes() / 1024.0f / 1024.0f); } UE_LOG(LogTemp, Log, TEXT(" Temporary cache %.3fMb"), GTemporaryIrradianceCacheResources.GetSizeBytes() / 1024.0f / 1024.0f); UE_LOG(LogTemp, Log, TEXT(" Culled objects %.3fMb"), GAOCulledObjectBuffers.Buffers.GetSizeBytes() / 1024.0f / 1024.0f); FTileIntersectionResources* TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources; if (TileIntersectionResources) { UE_LOG(LogTemp, Log, TEXT(" Tile Culled objects %.3fMb"), TileIntersectionResources->GetSizeBytes() / 1024.0f / 1024.0f); } FAOScreenGridResources* ScreenGridResources = ((FSceneViewState*)View.State)->AOScreenGridResources; if (ScreenGridResources) { UE_LOG(LogTemp, Log, TEXT(" Screen grid temporaries %.3fMb"), ScreenGridResources->GetSizeBytesForAO() / 1024.0f / 1024.0f); } extern void ListGlobalDistanceFieldMemory(); ListGlobalDistanceFieldMemory(); UE_LOG(LogTemp, Log, TEXT("")); UE_LOG(LogTemp, Log, TEXT("Distance Field GI")); if (Scene->DistanceFieldSceneData.SurfelBuffers) { UE_LOG(LogTemp, Log, TEXT(" Scene surfel data %.3fMb"), Scene->DistanceFieldSceneData.SurfelBuffers->GetSizeBytes() / 1024.0f / 1024.0f); } if (Scene->DistanceFieldSceneData.InstancedSurfelBuffers) { UE_LOG(LogTemp, Log, TEXT(" Instanced scene surfel data %.3fMb"), Scene->DistanceFieldSceneData.InstancedSurfelBuffers->GetSizeBytes() / 1024.0f / 1024.0f); } if (ScreenGridResources) { UE_LOG(LogTemp, Log, TEXT(" Screen grid temporaries %.3fMb"), ScreenGridResources->GetSizeBytesForGI() / 1024.0f / 1024.0f); } extern void ListDistanceFieldGIMemory(const FViewInfo& View); ListDistanceFieldGIMemory(View); } bool SupportsDistanceFieldAO(ERHIFeatureLevel::Type FeatureLevel, EShaderPlatform ShaderPlatform) { return GDistanceFieldAO && FeatureLevel >= ERHIFeatureLevel::SM5 && DoesPlatformSupportDistanceFieldAO(ShaderPlatform); } bool ShouldRenderDynamicSkyLight(const FScene* Scene, const FSceneViewFamily& ViewFamily) { return Scene->SkyLight && Scene->SkyLight->ProcessedTexture && !Scene->SkyLight->bWantsStaticShadowing && !Scene->SkyLight->bHasStaticLighting && ViewFamily.EngineShowFlags.SkyLighting && Scene->GetFeatureLevel() >= ERHIFeatureLevel::SM4 && !IsSimpleDynamicLightingEnabled() && !ViewFamily.EngineShowFlags.VisualizeLightCulling; } bool FDeferredShadingSceneRenderer::ShouldPrepareForDistanceFieldAO() const { return SupportsDistanceFieldAO(Scene->GetFeatureLevel(), Scene->GetShaderPlatform()) && ((ShouldRenderDynamicSkyLight(Scene, ViewFamily) && Scene->SkyLight->bCastShadows && ViewFamily.EngineShowFlags.DistanceFieldAO) || ViewFamily.EngineShowFlags.VisualizeMeshDistanceFields || ViewFamily.EngineShowFlags.VisualizeDistanceFieldAO || ViewFamily.EngineShowFlags.VisualizeDistanceFieldGI); } bool FDeferredShadingSceneRenderer::ShouldPrepareDistanceFields() const { return SupportsDistanceFieldAO(Scene->GetFeatureLevel(), Scene->GetShaderPlatform()) && (ShouldPrepareForDistanceFieldAO() || ShouldPrepareForDistanceFieldShadows() || Views[0].bUsesGlobalDistanceField || Scene->FXSystem->UsesGlobalDistanceField()); } void RenderDistanceFieldAOSurfaceCache( FRHICommandListImmediate& RHICmdList, const FViewInfo& View, FScene* Scene, FIntPoint TileListGroupSize, const FDistanceFieldAOParameters& Parameters, const TRefCountPtr<IPooledRenderTarget>& VelocityTexture, const TRefCountPtr<IPooledRenderTarget>& DistanceFieldNormal, TRefCountPtr<IPooledRenderTarget>& OutDynamicBentNormalAO, TRefCountPtr<IPooledRenderTarget>& OutDynamicIrradiance) { FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList); const bool bUseDistanceFieldGI = IsDistanceFieldGIAllowed(View); // Create surface cache state that will persist across frames if needed if (!Scene->SurfaceCacheResources) { Scene->SurfaceCacheResources = new FSurfaceCacheResources(); } FSurfaceCacheResources& SurfaceCacheResources = *Scene->SurfaceCacheResources; FIntPoint DownsampledViewRect = FIntPoint::DivideAndRoundDown(View.ViewRect.Size(), GAODownsampleFactor); // Needed because samples are kept across frames int32 SlackAmount = 4; int32 MaxSurfaceCacheSamples = DownsampledViewRect.X * DownsampledViewRect.Y / (1 << (2 * GAOMinLevel * GAOPowerOfTwoBetweenLevels)); SurfaceCacheResources.AllocateFor(GAOMinLevel, GAOMaxLevel, SlackAmount * MaxSurfaceCacheSamples); GTemporaryIrradianceCacheResources.AllocateFor(MaxSurfaceCacheSamples); uint32 ClearValues[4] = {0}; if (!SurfaceCacheResources.bClearedResources || !GAOReuseAcrossFrames // Drop records that will have uninitialized Irradiance if switching from AO only to AO + GI || (bUseDistanceFieldGI && !SurfaceCacheResources.bHasIrradiance)) { // Reset the number of active cache records to 0 for (int32 DepthLevel = GAOMaxLevel; DepthLevel >= GAOMinLevel; DepthLevel--) { RHICmdList.ClearUAV(SurfaceCacheResources.Level[DepthLevel]->ScatterDrawParameters.UAV, ClearValues); } RHICmdList.ClearUAV(SurfaceCacheResources.TempResources->ScatterDrawParameters.UAV, ClearValues); SurfaceCacheResources.bClearedResources = true; } SurfaceCacheResources.bHasIrradiance = bUseDistanceFieldGI; if (GAOReuseAcrossFrames) { SCOPED_DRAW_EVENT(RHICmdList, TrimRecords); // Copy and trim last frame's surface cache samples for (int32 DepthLevel = GAOMaxLevel; DepthLevel >= GAOMinLevel; DepthLevel--) { if (GAOTrimOldRecordsFraction > 0) { { TShaderMapRef<FSetupCopyIndirectArgumentsCS> ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DepthLevel); DispatchComputeShader(RHICmdList, *ComputeShader, 1, 1, 1); ComputeShader->UnsetParameters(RHICmdList); } if (bUseDistanceFieldGI) { TShaderMapRef<TCopyIrradianceCacheSamplesCS<true> > ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DepthLevel); DispatchIndirectComputeShader(RHICmdList, *ComputeShader, SurfaceCacheResources.DispatchParameters.Buffer, 0); ComputeShader->UnsetParameters(RHICmdList); } else { TShaderMapRef<TCopyIrradianceCacheSamplesCS<false> > ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DepthLevel); DispatchIndirectComputeShader(RHICmdList, *ComputeShader, SurfaceCacheResources.DispatchParameters.Buffer, 0); ComputeShader->UnsetParameters(RHICmdList); } Swap(SurfaceCacheResources.Level[DepthLevel], SurfaceCacheResources.TempResources); } } } // Start from the highest depth, which will consider the fewest potential shading points // Each level potentially prevents the next higher resolution level from doing expensive shading work // This is the core of the surface cache algorithm for (int32 DepthLevel = GAOMaxLevel; DepthLevel >= GAOMinLevel; DepthLevel--) { int32 DestLevelDownsampleFactor = GAODownsampleFactor * (1 << (DepthLevel * GAOPowerOfTwoBetweenLevels)); SCOPED_DRAW_EVENTF(RHICmdList, Level, TEXT("Level_%d"), DepthLevel); TRefCountPtr<IPooledRenderTarget> DistanceFieldAOBentNormalSplat; { FIntPoint AOBufferSize = FIntPoint::DivideAndRoundUp(SceneContext.GetBufferSizeXY(), DestLevelDownsampleFactor); FPooledRenderTargetDesc Desc(FPooledRenderTargetDesc::Create2DDesc(AOBufferSize, PF_FloatRGBA, FClearValueBinding::Transparent, TexCreate_None, TexCreate_RenderTargetable | TexCreate_UAV, false)); GRenderTargetPool.FindFreeElement(Desc, DistanceFieldAOBentNormalSplat, TEXT("DistanceFieldAOBentNormalSplat")); } // Splat / interpolate the surface cache records onto the buffer sized for the current depth level RenderIrradianceCacheInterpolation(RHICmdList, View, DistanceFieldAOBentNormalSplat, NULL, DistanceFieldNormal->GetRenderTargetItem(), DepthLevel, DestLevelDownsampleFactor, Parameters, false); { SCOPED_DRAW_EVENT(RHICmdList, PopulateAndConeTrace); SetRenderTarget(RHICmdList, NULL, NULL); // Save off the current record count before adding any more { TShaderMapRef<FSaveStartIndexCS> ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DepthLevel); DispatchComputeShader(RHICmdList, *ComputeShader, 1, 1, 1); ComputeShader->UnsetParameters(RHICmdList); } // Create new records which haven't been shaded yet for shading points which don't have a valid interpolation from existing records { FIntPoint DownsampledViewSize = FIntPoint::DivideAndRoundUp(View.ViewRect.Size(), DestLevelDownsampleFactor); uint32 GroupSizeX = FMath::DivideAndRoundUp(DownsampledViewSize.X, GDistanceFieldAOTileSizeX); uint32 GroupSizeY = FMath::DivideAndRoundUp(DownsampledViewSize.Y, GDistanceFieldAOTileSizeY); TShaderMapRef<FPopulateCacheCS> ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DistanceFieldAOBentNormalSplat->GetRenderTargetItem(), DistanceFieldNormal->GetRenderTargetItem(), DestLevelDownsampleFactor, DepthLevel, TileListGroupSize, Parameters); DispatchComputeShader(RHICmdList, *ComputeShader, GroupSizeX, GroupSizeY, 1); ComputeShader->UnsetParameters(RHICmdList); } { TShaderMapRef<TSetupFinalGatherIndirectArgumentsCS<true> > ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DepthLevel); DispatchComputeShader(RHICmdList, *ComputeShader, 1, 1, 1); ComputeShader->UnsetParameters(RHICmdList); } // Compute lighting for the new surface cache records by cone-stepping through the object distance fields if (bUseDistanceFieldGI) { TShaderMapRef<TConeTraceSurfaceCacheOcclusionCS<true> > ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DistanceFieldAOBentNormalSplat->GetRenderTargetItem(), DistanceFieldNormal->GetRenderTargetItem(), DestLevelDownsampleFactor, DepthLevel, TileListGroupSize, Parameters); DispatchIndirectComputeShader(RHICmdList, *ComputeShader, SurfaceCacheResources.DispatchParameters.Buffer, 0); ComputeShader->UnsetParameters(RHICmdList); } else { TShaderMapRef<TConeTraceSurfaceCacheOcclusionCS<false> > ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DistanceFieldAOBentNormalSplat->GetRenderTargetItem(), DistanceFieldNormal->GetRenderTargetItem(), DestLevelDownsampleFactor, DepthLevel, TileListGroupSize, Parameters); DispatchIndirectComputeShader(RHICmdList, *ComputeShader, SurfaceCacheResources.DispatchParameters.Buffer, 0); ComputeShader->UnsetParameters(RHICmdList); } } if (bUseDistanceFieldGI) { extern void ComputeIrradianceForSamples( int32 DepthLevel, FRHICommandListImmediate& RHICmdList, const FViewInfo& View, const FScene* Scene, const FDistanceFieldAOParameters& Parameters, FTemporaryIrradianceCacheResources* TemporaryIrradianceCacheResources); ComputeIrradianceForSamples(DepthLevel, RHICmdList, View, Scene, Parameters, &GTemporaryIrradianceCacheResources); } // Compute heightfield occlusion after heightfield GI, otherwise it self-shadows incorrectly View.HeightfieldLightingViewInfo.ComputeOcclusionForSamples(View, RHICmdList, GTemporaryIrradianceCacheResources, DepthLevel, Parameters); { TShaderMapRef<TSetupFinalGatherIndirectArgumentsCS<false> > ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DepthLevel); DispatchComputeShader(RHICmdList, *ComputeShader, 1, 1, 1); ComputeShader->UnsetParameters(RHICmdList); } // Compute and store the final bent normal now that all occlusion sources have been computed (distance fields, heightfields) { TShaderMapRef<FCombineConesCS> ComputeShader(View.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, View, DepthLevel, Parameters, NULL, FMatrix::Identity, NULL, NULL); DispatchIndirectComputeShader(RHICmdList, *ComputeShader, SurfaceCacheResources.DispatchParameters.Buffer, 0); ComputeShader->UnsetParameters(RHICmdList); } } TRefCountPtr<IPooledRenderTarget> BentNormalAccumulation; TRefCountPtr<IPooledRenderTarget> IrradianceAccumulation; { FIntPoint BufferSize = GetBufferSizeForAO(); FPooledRenderTargetDesc Desc(FPooledRenderTargetDesc::Create2DDesc(BufferSize, PF_FloatRGBA, FClearValueBinding::Transparent, TexCreate_None, TexCreate_RenderTargetable | TexCreate_UAV, false)); GRenderTargetPool.FindFreeElement(Desc, BentNormalAccumulation, TEXT("BentNormalAccumulation")); if (bUseDistanceFieldGI) { GRenderTargetPool.FindFreeElement(Desc, IrradianceAccumulation, TEXT("IrradianceAccumulation")); } } // Splat the surface cache records onto the opaque pixels, using less strict weighting so the lighting is smoothed in world space { SCOPED_DRAW_EVENT(RHICmdList, FinalIrradianceCacheSplat); RenderIrradianceCacheInterpolation(RHICmdList, View, BentNormalAccumulation, IrradianceAccumulation, DistanceFieldNormal->GetRenderTargetItem(), 0, GAODownsampleFactor, Parameters, true); } GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, BentNormalAccumulation); // Post process the AO to cover over artifacts PostProcessBentNormalAOSurfaceCache( RHICmdList, Parameters, View, VelocityTexture, BentNormalAccumulation->GetRenderTargetItem(), IrradianceAccumulation, DistanceFieldNormal->GetRenderTargetItem(), OutDynamicBentNormalAO, OutDynamicIrradiance); } bool FDeferredShadingSceneRenderer::RenderDistanceFieldLighting( FRHICommandListImmediate& RHICmdList, const FDistanceFieldAOParameters& Parameters, const TRefCountPtr<IPooledRenderTarget>& VelocityTexture, TRefCountPtr<IPooledRenderTarget>& OutDynamicBentNormalAO, TRefCountPtr<IPooledRenderTarget>& OutDynamicIrradiance, bool bVisualizeAmbientOcclusion, bool bVisualizeGlobalIllumination) { //@todo - support multiple views const FViewInfo& View = Views[0]; FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList); if (SupportsDistanceFieldAO(View.GetFeatureLevel(), View.GetShaderPlatform()) && Views.Num() == 1 // ViewState is used to cache tile intersection resources which have to be sized based on the view && View.State && View.IsPerspectiveProjection()) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RenderDistanceFieldLighting); if (GDistanceFieldVolumeTextureAtlas.VolumeTextureRHI && Scene->DistanceFieldSceneData.NumObjectsInBuffer) { check(!Scene->DistanceFieldSceneData.HasPendingOperations()); const bool bUseDistanceFieldGI = IsDistanceFieldGIAllowed(View); SCOPED_DRAW_EVENT(RHICmdList, DistanceFieldLighting); GenerateBestSpacedVectors(); if (bListMemoryNextFrame) { bListMemoryNextFrame = false; ListDistanceFieldLightingMemory(View); } { SCOPED_DRAW_EVENT(RHICmdList, ObjectFrustumCulling); if (GAOCulledObjectBuffers.Buffers.MaxObjects < Scene->DistanceFieldSceneData.NumObjectsInBuffer || GAOCulledObjectBuffers.Buffers.MaxObjects > 3 * Scene->DistanceFieldSceneData.NumObjectsInBuffer) { GAOCulledObjectBuffers.Buffers.MaxObjects = Scene->DistanceFieldSceneData.NumObjectsInBuffer * 5 / 4; GAOCulledObjectBuffers.Buffers.Release(); GAOCulledObjectBuffers.Buffers.Initialize(); } { uint32 ClearValues[4] = { 0 }; RHICmdList.ClearUAV(GAOCulledObjectBuffers.Buffers.ObjectIndirectArguments.UAV, ClearValues); TShaderMapRef<FCullObjectsForViewCS> ComputeShader(GetGlobalShaderMap(Scene->GetFeatureLevel())); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, Scene, View, Parameters); DispatchComputeShader(RHICmdList, *ComputeShader, FMath::DivideAndRoundUp<uint32>(Scene->DistanceFieldSceneData.NumObjectsInBuffer, UpdateObjectsGroupSize), 1, 1); ComputeShader->UnsetParameters(RHICmdList); } } TRefCountPtr<IPooledRenderTarget> DistanceFieldNormal; { const FIntPoint BufferSize = GetBufferSizeForAO(); FPooledRenderTargetDesc Desc(FPooledRenderTargetDesc::Create2DDesc(BufferSize, PF_FloatRGBA, FClearValueBinding::Transparent, TexCreate_None, TexCreate_RenderTargetable | TexCreate_UAV, false)); GRenderTargetPool.FindFreeElement(Desc, DistanceFieldNormal, TEXT("DistanceFieldNormal")); } ComputeDistanceFieldNormal(RHICmdList, Views, DistanceFieldNormal->GetRenderTargetItem(), Parameters); // Intersect objects with screen tiles, build lists FIntPoint TileListGroupSize = BuildTileObjectLists(RHICmdList, Scene, Views, DistanceFieldNormal->GetRenderTargetItem(), Parameters); GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, DistanceFieldNormal); if (bUseDistanceFieldGI) { extern void UpdateVPLs( FRHICommandListImmediate& RHICmdList, const FViewInfo& View, const FScene* Scene, const FDistanceFieldAOParameters& Parameters); UpdateVPLs(RHICmdList, View, Scene, Parameters); } TRefCountPtr<IPooledRenderTarget> BentNormalOutput; TRefCountPtr<IPooledRenderTarget> IrradianceOutput; if (GAOUseSurfaceCache) { RenderDistanceFieldAOSurfaceCache( RHICmdList, View, Scene, TileListGroupSize, Parameters, VelocityTexture, DistanceFieldNormal, BentNormalOutput, IrradianceOutput); } else { RenderDistanceFieldAOScreenGrid( RHICmdList, View, TileListGroupSize, Parameters, VelocityTexture, DistanceFieldNormal, BentNormalOutput, IrradianceOutput); } GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, BentNormalOutput); if (bVisualizeAmbientOcclusion || bVisualizeGlobalIllumination) { SceneContext.BeginRenderingSceneColor(RHICmdList, ESimpleRenderTargetMode::EExistingColorAndDepth, FExclusiveDepthStencil::DepthRead_StencilNop); } else { FPooledRenderTargetDesc Desc = SceneContext.GetSceneColor()->GetDesc(); // Make sure we get a signed format Desc.Format = PF_FloatRGBA; GRenderTargetPool.FindFreeElement(Desc, OutDynamicBentNormalAO, TEXT("DynamicBentNormalAO")); if (bUseDistanceFieldGI) { Desc.Format = PF_FloatRGB; GRenderTargetPool.FindFreeElement(Desc, OutDynamicIrradiance, TEXT("DynamicIrradiance")); } FTextureRHIParamRef RenderTargets[2] = { OutDynamicBentNormalAO->GetRenderTargetItem().TargetableTexture, bUseDistanceFieldGI ? OutDynamicIrradiance->GetRenderTargetItem().TargetableTexture : NULL }; SetRenderTargets(RHICmdList, ARRAY_COUNT(RenderTargets) - (bUseDistanceFieldGI ? 0 : 1), RenderTargets, FTextureRHIParamRef(), 0, NULL); } // Upsample to full resolution, write to output UpsampleBentNormalAO(RHICmdList, Views, BentNormalOutput, IrradianceOutput, bVisualizeAmbientOcclusion, bVisualizeGlobalIllumination); if (!bVisualizeAmbientOcclusion && !bVisualizeGlobalIllumination) { RHICmdList.CopyToResolveTarget(OutDynamicBentNormalAO->GetRenderTargetItem().TargetableTexture, OutDynamicBentNormalAO->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams()); if (bUseDistanceFieldGI) { RHICmdList.CopyToResolveTarget(OutDynamicIrradiance->GetRenderTargetItem().TargetableTexture, OutDynamicIrradiance->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams()); } } return true; } } return false; } template<bool bApplyShadowing, bool bSupportIrradiance> class TDynamicSkyLightDiffusePS : public FGlobalShader { DECLARE_SHADER_TYPE(TDynamicSkyLightDiffusePS, Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); OutEnvironment.SetDefine(TEXT("APPLY_SHADOWING"), (uint32)(bApplyShadowing ? 1 : 0)); OutEnvironment.SetDefine(TEXT("SUPPORT_IRRADIANCE"), bSupportIrradiance ? TEXT("1") : TEXT("0")); } /** Default constructor. */ TDynamicSkyLightDiffusePS() {} /** Initialization constructor. */ TDynamicSkyLightDiffusePS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DeferredParameters.Bind(Initializer.ParameterMap); DynamicBentNormalAOTexture.Bind(Initializer.ParameterMap, TEXT("BentNormalAOTexture")); DynamicBentNormalAOSampler.Bind(Initializer.ParameterMap, TEXT("BentNormalAOSampler")); DynamicIrradianceTexture.Bind(Initializer.ParameterMap, TEXT("IrradianceTexture")); DynamicIrradianceSampler.Bind(Initializer.ParameterMap, TEXT("IrradianceSampler")); ContrastAndNormalizeMulAdd.Bind(Initializer.ParameterMap, TEXT("ContrastAndNormalizeMulAdd")); OcclusionTintAndMinOcclusion.Bind(Initializer.ParameterMap, TEXT("OcclusionTintAndMinOcclusion")); } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FTextureRHIParamRef DynamicBentNormalAO, IPooledRenderTarget* DynamicIrradiance, const FDistanceFieldAOParameters& Parameters, const FSkyLightSceneProxy* SkyLight) { const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); DeferredParameters.Set(RHICmdList, ShaderRHI, View); SetTextureParameter(RHICmdList, ShaderRHI, DynamicBentNormalAOTexture, DynamicBentNormalAOSampler, TStaticSamplerState<SF_Point>::GetRHI(), DynamicBentNormalAO); if (DynamicIrradianceTexture.IsBound()) { SetTextureParameter(RHICmdList, ShaderRHI, DynamicIrradianceTexture, DynamicIrradianceSampler, TStaticSamplerState<SF_Point>::GetRHI(), DynamicIrradiance->GetRenderTargetItem().ShaderResourceTexture); } // Scale and bias to remap the contrast curve to [0,1] const float Min = 1 / (1 + FMath::Exp(-Parameters.Contrast * (0 * 10 - 5))); const float Max = 1 / (1 + FMath::Exp(-Parameters.Contrast * (1 * 10 - 5))); const float Mul = 1.0f / (Max - Min); const float Add = -Min / (Max - Min); SetShaderValue(RHICmdList, ShaderRHI, ContrastAndNormalizeMulAdd, FVector(Parameters.Contrast, Mul, Add)); FVector4 OcclusionTintAndMinOcclusionValue = FVector4(SkyLight->OcclusionTint); OcclusionTintAndMinOcclusionValue.W = SkyLight->MinOcclusion; SetShaderValue(RHICmdList, ShaderRHI, OcclusionTintAndMinOcclusion, OcclusionTintAndMinOcclusionValue); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DeferredParameters; Ar << DynamicBentNormalAOTexture; Ar << DynamicBentNormalAOSampler; Ar << DynamicIrradianceTexture; Ar << DynamicIrradianceSampler; Ar << ContrastAndNormalizeMulAdd; Ar << OcclusionTintAndMinOcclusion; return bShaderHasOutdatedParameters; } private: FDeferredPixelShaderParameters DeferredParameters; FShaderResourceParameter DynamicBentNormalAOTexture; FShaderResourceParameter DynamicBentNormalAOSampler; FShaderResourceParameter DynamicIrradianceTexture; FShaderResourceParameter DynamicIrradianceSampler; FShaderParameter ContrastAndNormalizeMulAdd; FShaderParameter OcclusionTintAndMinOcclusion; }; #define IMPLEMENT_SKYLIGHT_PS_TYPE(bApplyShadowing, bSupportIrradiance) \ typedef TDynamicSkyLightDiffusePS<bApplyShadowing, bSupportIrradiance> TDynamicSkyLightDiffusePS##bApplyShadowing##bSupportIrradiance; \ IMPLEMENT_SHADER_TYPE(template<>,TDynamicSkyLightDiffusePS##bApplyShadowing##bSupportIrradiance,TEXT("SkyLighting"),TEXT("SkyLightDiffusePS"),SF_Pixel); IMPLEMENT_SKYLIGHT_PS_TYPE(true, true) IMPLEMENT_SKYLIGHT_PS_TYPE(false, true) IMPLEMENT_SKYLIGHT_PS_TYPE(true, false) IMPLEMENT_SKYLIGHT_PS_TYPE(false, false) bool FDeferredShadingSceneRenderer::ShouldRenderDistanceFieldAO() const { return Scene->SkyLight->bCastShadows && ViewFamily.EngineShowFlags.DistanceFieldAO && !ViewFamily.EngineShowFlags.VisualizeDistanceFieldAO && !ViewFamily.EngineShowFlags.VisualizeDistanceFieldGI && !ViewFamily.EngineShowFlags.VisualizeMeshDistanceFields; } void FDeferredShadingSceneRenderer::RenderDynamicSkyLighting(FRHICommandListImmediate& RHICmdList, const TRefCountPtr<IPooledRenderTarget>& VelocityTexture, TRefCountPtr<IPooledRenderTarget>& DynamicBentNormalAO) { if (ShouldRenderDynamicSkyLight(Scene, ViewFamily)) { SCOPED_DRAW_EVENT(RHICmdList, SkyLightDiffuse); bool bApplyShadowing = false; FDistanceFieldAOParameters Parameters(Scene->SkyLight->OcclusionMaxDistance, Scene->SkyLight->Contrast); TRefCountPtr<IPooledRenderTarget> DynamicIrradiance; if (ShouldRenderDistanceFieldAO() && ViewFamily.EngineShowFlags.AmbientOcclusion) { bApplyShadowing = RenderDistanceFieldLighting(RHICmdList, Parameters, VelocityTexture, DynamicBentNormalAO, DynamicIrradiance, false, false); } FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList); SceneContext.BeginRenderingSceneColor(RHICmdList); for( int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++ ) { const FViewInfo& View = Views[ViewIndex]; RHICmdList.SetViewport(View.ViewRect.Min.X, View.ViewRect.Min.Y, 0.0f, View.ViewRect.Max.X, View.ViewRect.Max.Y, 1.0f); RHICmdList.SetRasterizerState(TStaticRasterizerState<FM_Solid, CM_None>::GetRHI()); RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI()); if (GAOOverwriteSceneColor) { RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI()); } else { RHICmdList.SetBlendState(TStaticBlendState<CW_RGB, BO_Add, BF_One, BF_One>::GetRHI()); } const bool bUseDistanceFieldGI = IsDistanceFieldGIAllowed(View); TShaderMapRef< FPostProcessVS > VertexShader(View.ShaderMap); if (bApplyShadowing) { if (bUseDistanceFieldGI) { TShaderMapRef<TDynamicSkyLightDiffusePS<true, true> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); PixelShader->SetParameters(RHICmdList, View, DynamicBentNormalAO->GetRenderTargetItem().ShaderResourceTexture, DynamicIrradiance, Parameters, Scene->SkyLight); } else { TShaderMapRef<TDynamicSkyLightDiffusePS<true, false> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); PixelShader->SetParameters(RHICmdList, View, DynamicBentNormalAO->GetRenderTargetItem().ShaderResourceTexture, DynamicIrradiance, Parameters, Scene->SkyLight); } } else { if (bUseDistanceFieldGI) { TShaderMapRef<TDynamicSkyLightDiffusePS<false, true> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); PixelShader->SetParameters(RHICmdList, View, GWhiteTexture->TextureRHI, NULL, Parameters, Scene->SkyLight); } else { TShaderMapRef<TDynamicSkyLightDiffusePS<false, false> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); PixelShader->SetParameters(RHICmdList, View, GWhiteTexture->TextureRHI, NULL, Parameters, Scene->SkyLight); } } DrawRectangle( RHICmdList, 0, 0, View.ViewRect.Width(), View.ViewRect.Height(), View.ViewRect.Min.X, View.ViewRect.Min.Y, View.ViewRect.Width(), View.ViewRect.Height(), FIntPoint(View.ViewRect.Width(), View.ViewRect.Height()), SceneContext.GetBufferSizeXY(), *VertexShader); } } } template<bool bUseGlobalDistanceField> class TVisualizeMeshDistanceFieldCS : public FGlobalShader { DECLARE_SHADER_TYPE(TVisualizeMeshDistanceFieldCS, Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), GDistanceFieldAOTileSizeX); OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), GDistanceFieldAOTileSizeY); OutEnvironment.SetDefine(TEXT("USE_GLOBAL_DISTANCE_FIELD"), bUseGlobalDistanceField ? TEXT("1") : TEXT("0")); } /** Default constructor. */ TVisualizeMeshDistanceFieldCS() {} /** Initialization constructor. */ TVisualizeMeshDistanceFieldCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { VisualizeMeshDistanceFields.Bind(Initializer.ParameterMap, TEXT("VisualizeMeshDistanceFields")); NumGroups.Bind(Initializer.ParameterMap, TEXT("NumGroups")); ObjectParameters.Bind(Initializer.ParameterMap); DeferredParameters.Bind(Initializer.ParameterMap); AOParameters.Bind(Initializer.ParameterMap); GlobalDistanceFieldParameters.Bind(Initializer.ParameterMap); } void SetParameters( FRHICommandList& RHICmdList, const FSceneView& View, FSceneRenderTargetItem& VisualizeMeshDistanceFieldsValue, FVector2D NumGroupsValue, const FDistanceFieldAOParameters& Parameters, const FGlobalDistanceFieldInfo& GlobalDistanceFieldInfo) { const FComputeShaderRHIParamRef ShaderRHI = GetComputeShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); VisualizeMeshDistanceFields.SetTexture(RHICmdList, ShaderRHI, VisualizeMeshDistanceFieldsValue.ShaderResourceTexture, VisualizeMeshDistanceFieldsValue.UAV); ObjectParameters.Set(RHICmdList, ShaderRHI, GAOCulledObjectBuffers.Buffers); AOParameters.Set(RHICmdList, ShaderRHI, Parameters); DeferredParameters.Set(RHICmdList, ShaderRHI, View); if (bUseGlobalDistanceField) { GlobalDistanceFieldParameters.Set(RHICmdList, ShaderRHI, GlobalDistanceFieldInfo.ParameterData); } SetShaderValue(RHICmdList, ShaderRHI, NumGroups, NumGroupsValue); } void UnsetParameters(FRHICommandList& RHICmdList) { VisualizeMeshDistanceFields.UnsetUAV(RHICmdList, GetComputeShader()); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << VisualizeMeshDistanceFields; Ar << NumGroups; Ar << ObjectParameters; Ar << DeferredParameters; Ar << AOParameters; Ar << GlobalDistanceFieldParameters; return bShaderHasOutdatedParameters; } private: FRWShaderParameter VisualizeMeshDistanceFields; FShaderParameter NumGroups; FDistanceFieldCulledObjectBufferParameters ObjectParameters; FDeferredPixelShaderParameters DeferredParameters; FAOParameters AOParameters; FGlobalDistanceFieldParameters GlobalDistanceFieldParameters; }; IMPLEMENT_SHADER_TYPE(template<>,TVisualizeMeshDistanceFieldCS<true>,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("VisualizeMeshDistanceFieldCS"),SF_Compute); IMPLEMENT_SHADER_TYPE(template<>,TVisualizeMeshDistanceFieldCS<false>,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("VisualizeMeshDistanceFieldCS"),SF_Compute); class FVisualizeDistanceFieldUpsamplePS : public FGlobalShader { DECLARE_SHADER_TYPE(FVisualizeDistanceFieldUpsamplePS, Global); public: static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor); } /** Default constructor. */ FVisualizeDistanceFieldUpsamplePS() {} /** Initialization constructor. */ FVisualizeDistanceFieldUpsamplePS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { DeferredParameters.Bind(Initializer.ParameterMap); VisualizeDistanceFieldTexture.Bind(Initializer.ParameterMap,TEXT("VisualizeDistanceFieldTexture")); VisualizeDistanceFieldSampler.Bind(Initializer.ParameterMap,TEXT("VisualizeDistanceFieldSampler")); } void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, TRefCountPtr<IPooledRenderTarget>& VisualizeDistanceField) { const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader(); FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View); DeferredParameters.Set(RHICmdList, ShaderRHI, View); SetTextureParameter(RHICmdList, ShaderRHI, VisualizeDistanceFieldTexture, VisualizeDistanceFieldSampler, TStaticSamplerState<SF_Bilinear>::GetRHI(), VisualizeDistanceField->GetRenderTargetItem().ShaderResourceTexture); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << DeferredParameters; Ar << VisualizeDistanceFieldTexture; Ar << VisualizeDistanceFieldSampler; return bShaderHasOutdatedParameters; } private: FDeferredPixelShaderParameters DeferredParameters; FShaderResourceParameter VisualizeDistanceFieldTexture; FShaderResourceParameter VisualizeDistanceFieldSampler; }; IMPLEMENT_SHADER_TYPE(,FVisualizeDistanceFieldUpsamplePS,TEXT("DistanceFieldSurfaceCacheLighting"),TEXT("VisualizeDistanceFieldUpsamplePS"),SF_Pixel); void FDeferredShadingSceneRenderer::RenderMeshDistanceFieldVisualization(FRHICommandListImmediate& RHICmdList, const FDistanceFieldAOParameters& Parameters) { //@todo - support multiple views const FViewInfo& View = Views[0]; if (GDistanceFieldAO && FeatureLevel >= ERHIFeatureLevel::SM5 && DoesPlatformSupportDistanceFieldAO(View.GetShaderPlatform()) && Views.Num() == 1) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RenderMeshDistanceFieldVis); SCOPED_DRAW_EVENT(RHICmdList, VisualizeMeshDistanceFields); if (GDistanceFieldVolumeTextureAtlas.VolumeTextureRHI && Scene->DistanceFieldSceneData.NumObjectsInBuffer > 0) { check(!Scene->DistanceFieldSceneData.HasPendingOperations()); QUICK_SCOPE_CYCLE_COUNTER(STAT_AOIssueGPUWork); const bool bUseGlobalDistanceField = UseGlobalDistanceField(Parameters) && GAOVisualizeGlobalDistanceField != 0; { if (GAOCulledObjectBuffers.Buffers.MaxObjects < Scene->DistanceFieldSceneData.NumObjectsInBuffer) { GAOCulledObjectBuffers.Buffers.MaxObjects = Scene->DistanceFieldSceneData.NumObjectsInBuffer * 5 / 4; GAOCulledObjectBuffers.Buffers.Release(); GAOCulledObjectBuffers.Buffers.Initialize(); } { uint32 ClearValues[4] = { 0 }; RHICmdList.ClearUAV(GAOCulledObjectBuffers.Buffers.ObjectIndirectArguments.UAV, ClearValues); TShaderMapRef<FCullObjectsForViewCS> ComputeShader(GetGlobalShaderMap(Scene->GetFeatureLevel())); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, Scene, View, Parameters); DispatchComputeShader(RHICmdList, *ComputeShader, FMath::DivideAndRoundUp<uint32>(Scene->DistanceFieldSceneData.NumObjectsInBuffer, UpdateObjectsGroupSize), 1, 1); ComputeShader->UnsetParameters(RHICmdList); } } TRefCountPtr<IPooledRenderTarget> VisualizeResultRT; { const FIntPoint BufferSize = GetBufferSizeForAO(); FPooledRenderTargetDesc Desc(FPooledRenderTargetDesc::Create2DDesc(BufferSize, PF_FloatRGBA, FClearValueBinding::None, TexCreate_None, TexCreate_RenderTargetable | TexCreate_UAV, false)); GRenderTargetPool.FindFreeElement(Desc, VisualizeResultRT, TEXT("VisualizeDistanceField")); } { SetRenderTarget(RHICmdList, NULL, NULL); for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++) { const FViewInfo& ViewInfo = Views[ViewIndex]; uint32 GroupSizeX = FMath::DivideAndRoundUp(ViewInfo.ViewRect.Size().X / GAODownsampleFactor, GDistanceFieldAOTileSizeX); uint32 GroupSizeY = FMath::DivideAndRoundUp(ViewInfo.ViewRect.Size().Y / GAODownsampleFactor, GDistanceFieldAOTileSizeY); SCOPED_DRAW_EVENT(RHICmdList, VisualizeMeshDistanceFieldCS); if (bUseGlobalDistanceField) { check(View.GlobalDistanceFieldInfo.Clipmaps.Num() > 0); TShaderMapRef<TVisualizeMeshDistanceFieldCS<true> > ComputeShader(ViewInfo.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, ViewInfo, VisualizeResultRT->GetRenderTargetItem(), FVector2D(GroupSizeX, GroupSizeY), Parameters, View.GlobalDistanceFieldInfo); DispatchComputeShader(RHICmdList, *ComputeShader, GroupSizeX, GroupSizeY, 1); ComputeShader->UnsetParameters(RHICmdList); } else { TShaderMapRef<TVisualizeMeshDistanceFieldCS<false> > ComputeShader(ViewInfo.ShaderMap); RHICmdList.SetComputeShader(ComputeShader->GetComputeShader()); ComputeShader->SetParameters(RHICmdList, ViewInfo, VisualizeResultRT->GetRenderTargetItem(), FVector2D(GroupSizeX, GroupSizeY), Parameters, View.GlobalDistanceFieldInfo); DispatchComputeShader(RHICmdList, *ComputeShader, GroupSizeX, GroupSizeY, 1); ComputeShader->UnsetParameters(RHICmdList); } } } { FSceneRenderTargets::Get(RHICmdList).BeginRenderingSceneColor(RHICmdList); for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++) { const FViewInfo& ViewInfo = Views[ViewIndex]; SCOPED_DRAW_EVENT(RHICmdList, UpsampleAO); RHICmdList.SetViewport(ViewInfo.ViewRect.Min.X, ViewInfo.ViewRect.Min.Y, 0.0f, ViewInfo.ViewRect.Max.X, ViewInfo.ViewRect.Max.Y, 1.0f); RHICmdList.SetRasterizerState(TStaticRasterizerState<FM_Solid, CM_None>::GetRHI()); RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI()); RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI()); TShaderMapRef<FPostProcessVS> VertexShader( ViewInfo.ShaderMap ); TShaderMapRef<FVisualizeDistanceFieldUpsamplePS> PixelShader( ViewInfo.ShaderMap ); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, ViewInfo.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); PixelShader->SetParameters(RHICmdList, ViewInfo, VisualizeResultRT); DrawRectangle( RHICmdList, 0, 0, ViewInfo.ViewRect.Width(), ViewInfo.ViewRect.Height(), ViewInfo.ViewRect.Min.X / GAODownsampleFactor, ViewInfo.ViewRect.Min.Y / GAODownsampleFactor, ViewInfo.ViewRect.Width() / GAODownsampleFactor, ViewInfo.ViewRect.Height() / GAODownsampleFactor, FIntPoint(ViewInfo.ViewRect.Width(), ViewInfo.ViewRect.Height()), GetBufferSizeForAO(), *VertexShader); } } } } }
40.774194
236
0.801837
[ "geometry", "render", "object", "vector", "solid" ]
35c834b933d06273d3096f914c8d79589f1c013a
9,663
c++
C++
ffe/currents/driftcurrent.c++
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
null
null
null
ffe/currents/driftcurrent.c++
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
null
null
null
ffe/currents/driftcurrent.c++
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
null
null
null
#include "driftcurrent.h" #include "../../em-fields/tile.h" #include "../../tools/signum.h" #include <cmath> template<> void ffe::DriftCurrent<2>::interpolate_b( fields::YeeLattice& yee ) { int k = 0; for(int j=0; j<static_cast<int>(yee.Ny); j++) for(int i=0; i<static_cast<int>(yee.Nx); i++) { bxf(i,j,k)=0.25*( yee.bx(i, j, k) + yee.bx(i, j-1, k) + yee.bx(i+1, j, k) + yee.bx(i+1, j-1, k) ); byf(i,j,k) = 0.25*( yee.by(i, j, k) + yee.by(i, j+1, k) + yee.by(i-1, j, k) + yee.by(i-1, j+1, k) ); bzf(i,j,k) = 0.25*( yee.bz(i, j, k) + yee.bz(i, j-1, k) + yee.bz(i-1, j, k) + yee.bz(i-1, j-1, k) ); } } template<> void ffe::DriftCurrent<3>::interpolate_b( fields::YeeLattice& yee ) { for(int k=0; k<static_cast<int>(yee.Nz); k++) for(int j=0; j<static_cast<int>(yee.Ny); j++) for(int i=0; i<static_cast<int>(yee.Nx); i++) { bxf(i,j,k) = 0.125*( yee.bx(i, j, k ) + yee.bx(i, j, k-1) + yee.bx(i, j-1, k ) + yee.bx(i, j-1, k-1) + yee.bx(i+1, j, k ) + yee.bx(i+1, j, k-1) + yee.bx(i+1, j-1, k ) + yee.bx(i+1, j-1, k-1) ); byf(i,j,k) = 0.125*( yee.by(i, j, k) + yee.by(i, j, k-1) + yee.by(i, j+1, k) + yee.by(i, j+1, k-1) + yee.by(i-1, j, k) + yee.by(i-1, j, k-1) + yee.by(i-1, j+1, k) + yee.by(i-1, j+1, k-1) ); bzf(i,j,k) = 0.125*( yee.bz(i, j, k) + yee.bz(i, j, k+1) + yee.bz(i, j-1, k) + yee.bz(i, j-1, k+1) + yee.bz(i-1, j, k) + yee.bz(i-1, j, k+1) + yee.bz(i-1, j-1, k) + yee.bz(i-1, j-1, k+1) ); } } /// 2D Drift current solver template<> void ffe::DriftCurrent<2>::comp_drift_cur(ffe::Tile<2>& tile) { fields::YeeLattice& mesh = tile.get_yee(); // half stagger B; stored in (bxf, byf, bzf) interpolate_b(mesh); double dt = tile.cfl; double dive; double crossx, crossy, crossz; double b2; int k = 0; for(int j=0; j<static_cast<int>(tile.mesh_lengths[1]); j++) for(int i=0; i<static_cast<int>(tile.mesh_lengths[0]); i++) { // div E // nabla E = dEx/dx + dEy/dx + dEz/dx // // NOTE: dx = 1.0 by definition // NOTE: dEz = 0 in 2D divE = 0.5*( mesh.ex(i+1,j,k) - mesh.ex(i-1,j,k) + mesh.ey(i,j+1,k) - mesh.ey(i,j-1,k) // + mesh.ez(i,j,k+1) - mesh.ez(i,j,k-1) ); // E x B crossx = mesh.ey(i,j,k)*bzf(i,j,k) - mesh.ez(i,j,k)*byf(i,j,k); crossy =-mesh.ex(i,j,k)*bzf(i,j,k) + mesh.ez(i,j,k)*bxf(i,j,k); crossz = mesh.ex(i,j,k)*byf(i,j,k) - mesh.ey(i,j,k)*bxf(i,j,k); // B^2 b2 = bxf(i,j,k)*bxf(i,j,k) + byf(i,j,k)*byf(i,j,k) + bzf(i,j,k)*bzf(i,j,k); if(b2 == 0.0) continue; // perp current mesh.jx(i,j,k) += divE*crossx/b2; mesh.jy(i,j,k) += divE*crossy/b2; mesh.jz(i,j,k) += divE*crossz/b2; mesh.ex(i,j,k) -=dt*divE*crossx/b2; mesh.ey(i,j,k) -=dt*divE*crossy/b2; mesh.ez(i,j,k) -=dt*divE*crossz/b2; //mesh.ex(i,j,k) -= mesh.jx(i,j,k)*dt; //mesh.ey(i,j,k) -= mesh.jy(i,j,k)*dt; //mesh.ez(i,j,k) -= mesh.jz(i,j,k)*dt; } } /// 3D Drift current solver template<> void ffe::DriftCurrent<3>::comp_drift_cur(ffe::Tile<3>& tile) { fields::YeeLattice& mesh = tile.get_yee(); // half stagger B; stored in (bxf, byf, bzf) interpolate_b(mesh); double dt = tile.cfl; double dive; double crossx, crossy, crossz; double b2; for(int k=0; k<static_cast<int>(tile.mesh_lengths[2]); k++) for(int j=0; j<static_cast<int>(tile.mesh_lengths[1]); j++) for(int i=0; i<static_cast<int>(tile.mesh_lengths[0]); i++) { // div E // nabla E = dEx/dx + dEy/dx + dEz/dx // // NOTE: dx = 1.0 by definition dive = 0.5*( mesh.ex(i+1,j,k) - mesh.ex(i-1,j,k) + mesh.ey(i,j+1,k) - mesh.ey(i,j-1,k) + mesh.ez(i,j,k+1) - mesh.ez(i,j,k-1) ); // E x B crossx = mesh.ey(i,j,k)*bzf(i,j,k) - mesh.ez(i,j,k)*byf(i,j,k); crossy =-mesh.ex(i,j,k)*bzf(i,j,k) + mesh.ez(i,j,k)*bxf(i,j,k); crossz = mesh.ex(i,j,k)*byf(i,j,k) - mesh.ey(i,j,k)*bxf(i,j,k); // B^2 b2 = bxf(i,j,k)*bxf(i,j,k) + byf(i,j,k)*byf(i,j,k) + bzf(i,j,k)*bzf(i,j,k); if(b2 == 0.0) continue; // perp current mesh.jx(i,j,k) += dive*crossx/b2; mesh.jy(i,j,k) += dive*crossy/b2; mesh.jz(i,j,k) += dive*crossz/b2; mesh.ex(i,j,k) -=dt*dive*crossx/b2; mesh.ey(i,j,k) -=dt*dive*crossy/b2; mesh.ez(i,j,k) -=dt*dive*crossz/b2; } } /// 2D Drift current solver template<> void ffe::DriftCurrent<2>::comp_parallel_cur( ffe::Tile<2>& tile ) { fields::YeeLattice& mesh = tile.get_yee(); // half stagger B; stored in (bxf, byf, bzf) interpolate_b(mesh); double spara; double jparax, jparay, jparaz; double b2; double dt = tile.cfl; // time step is basically = cfl int k = 0; for(int j=0; j<static_cast<int>(tile.mesh_lengths[1]); j++) for(int i=0; i<static_cast<int>(tile.mesh_lengths[0]); i++) { // E.B spara = mesh.ex(i,j,k)*bxf(i,j,k) + mesh.ey(i,j,k)*byf(i,j,k) + mesh.ez(i,j,k)*bzf(i,j,k); // B^2 b2 = bxf(i,j,k)*bxf(i,j,k) + byf(i,j,k)*byf(i,j,k) + bzf(i,j,k)*bzf(i,j,k); if(b2 == 0.0) continue; // J_parallel x dt jparax = spara*bxf(i,j,k)/b2; jparay = spara*byf(i,j,k)/b2; jparaz = spara*bzf(i,j,k)/b2; // Add J_parallel to E mesh.ex(i,j,k) -= jparax; mesh.ey(i,j,k) -= jparay; mesh.ez(i,j,k) -= jparaz; // store J_parallel mesh.jx(i,j,k) += jparax/dt; mesh.jy(i,j,k) += jparay/dt; mesh.jz(i,j,k) += jparaz/dt; } } /// 3D Drift current solver template<> void ffe::DriftCurrent<3>::comp_parallel_cur( ffe::Tile<3>& tile ) { fields::YeeLattice& mesh = tile.get_yee(); // half stagger B; stored in (bxf, byf, bzf) interpolate_b(mesh); double spara; double jparax, jparay, jparaz; double b2; double dt = tile.cfl; // time step is basically = cfl for(int k=0; k<static_cast<int>(tile.mesh_lengths[2]); k++) for(int j=0; j<static_cast<int>(tile.mesh_lengths[1]); j++) for(int i=0; i<static_cast<int>(tile.mesh_lengths[0]); i++) { // E.B spara = mesh.ex(i,j,k)*bxf(i,j,k) + mesh.ey(i,j,k)*byf(i,j,k) + mesh.ez(i,j,k)*bzf(i,j,k); // B^2 b2 = bxf(i,j,k)*bxf(i,j,k) + byf(i,j,k)*byf(i,j,k) + bzf(i,j,k)*bzf(i,j,k); if(b2 == 0.0) continue; // J_parallel x dt jparax = spara*bxf(i,j,k)/b2; jparay = spara*byf(i,j,k)/b2; jparaz = spara*bzf(i,j,k)/b2; // Add J_parallel to E mesh.ex(i,j,k) -= jparax; mesh.ey(i,j,k) -= jparay; mesh.ez(i,j,k) -= jparaz; // store J_parallel mesh.jx(i,j,k) += jparax/dt; mesh.jy(i,j,k) += jparay/dt; mesh.jz(i,j,k) += jparaz/dt; } } /// 2D Drift current solver template<> void ffe::DriftCurrent<2>::limiter( ffe::Tile<2>& tile ) { fields::YeeLattice& mesh = tile.get_yee(); interpolate_b(mesh); double diss; double e2, b2; double dt = tile.cfl; double ex0, ey0, ez0; double ex1, ey1, ez1; double jxd, jyd, jzd; int k = 0; for(int j=0; j<static_cast<int>(tile.mesh_lengths[1]); j++) for(int i=0; i<static_cast<int>(tile.mesh_lengths[0]); i++) { ex0 = mesh.ex(i,j,k); ey0 = mesh.ey(i,j,k); ez0 = mesh.ez(i,j,k); //// E^2 and B^2 e2 = ex0*ex0 + ey0*ey0 + ez0*ez0; b2 = bxf(i,j,k)*bxf(i,j,k) + byf(i,j,k)*byf(i,j,k) + bzf(i,j,k)*bzf(i,j,k); // limiter by sqrt(b^2/e^2) diss = sqrt(b2/e2); if(diss < 1.0) { ex1 = diss*ex0; ey1 = diss*ey0; ez1 = diss*ez0; // dissipated current jxd = ex0 - ex1; jyd = ey0 - ey1; jzd = ez0 - ez1; // deposit dissipating current mesh.ex(i,j,k) -= jxd; mesh.ey(i,j,k) -= jyd; mesh.ez(i,j,k) -= jzd; mesh.jx(i,j,k) += jxd/dt; mesh.jy(i,j,k) += jyd/dt; mesh.jz(i,j,k) += jzd/dt; } else { jxd = 0.0; jyd = 0.0; jzd = 0.0; } } } /// 3D Drift current solver template<> void ffe::DriftCurrent<3>::limiter( ffe::Tile<3>& tile ) { fields::YeeLattice& mesh = tile.get_yee(); interpolate_b(mesh); double diss; double e2, b2; double dt = tile.cfl; double ex0, ey0, ez0; double ex1, ey1, ez1; double jxd, jyd, jzd; for(int k=0; k<static_cast<int>(tile.mesh_lengths[2]); k++) for(int j=0; j<static_cast<int>(tile.mesh_lengths[1]); j++) for(int i=0; i<static_cast<int>(tile.mesh_lengths[0]); i++) { ex0 = mesh.ex(i,j,k); ey0 = mesh.ey(i,j,k); ez0 = mesh.ez(i,j,k); //// E^2 and B^2 e2 = ex0*ex0 + ey0*ey0 + ez0*ez0; b2 = bxf(i,j,k)*bxf(i,j,k) + byf(i,j,k)*byf(i,j,k) + bzf(i,j,k)*bzf(i,j,k); // limiter by sqrt(b^2/e^2) diss = sqrt(b2/e2); if(diss < 1.0) { ex1 = diss*ex0; ey1 = diss*ey0; ez1 = diss*ez0; // dissipated current jxd = ex0 - ex1; jyd = ey0 - ey1; jzd = ez0 - ez1; // deposit dissipating current mesh.ex(i,j,k) -= jxd; mesh.ey(i,j,k) -= jyd; mesh.ez(i,j,k) -= jzd; mesh.jx(i,j,k) += jxd/dt; mesh.jy(i,j,k) += jyd/dt; mesh.jz(i,j,k) += jzd/dt; } else { jxd = 0.0; jyd = 0.0; jzd = 0.0; } } } //-------------------------------------------------- // explicit template instantiation template class ffe::DriftCurrent<2>; // 2D template class ffe::DriftCurrent<3>; // 3D
22.524476
79
0.508434
[ "mesh", "3d" ]
35cb62f4672eae74d77f631a1886ad1cc50c2229
3,665
cpp
C++
src/reset.cpp
0u812/libcellml
8e4c73dcb8e8c6e40a9d75067a361ac1807aa83e
[ "Apache-2.0" ]
null
null
null
src/reset.cpp
0u812/libcellml
8e4c73dcb8e8c6e40a9d75067a361ac1807aa83e
[ "Apache-2.0" ]
null
null
null
src/reset.cpp
0u812/libcellml
8e4c73dcb8e8c6e40a9d75067a361ac1807aa83e
[ "Apache-2.0" ]
null
null
null
/* Copyright libCellML Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libcellml/reset.h" #include "libcellml/when.h" #include <algorithm> #include <vector> namespace libcellml { /** * @brief The Reset::ResetImpl struct. * * The private implementation for the Reset class. */ struct Reset::ResetImpl { int mOrder = 0; /**< An integer for determining relative order.*/ VariablePtr mVariable; /**< The associated variable for the reset.*/ std::vector<WhenPtr>::iterator findWhen(const WhenPtr &when); std::vector<WhenPtr> mWhens; }; std::vector<WhenPtr>::iterator Reset::ResetImpl::findWhen(const WhenPtr &when) { return std::find_if(mWhens.begin(), mWhens.end(), [=](const WhenPtr &w) -> bool { return w == when; }); } Reset::Reset() : mPimpl(new ResetImpl()) { } Reset::~Reset() { delete mPimpl; } Reset::Reset(const Reset &rhs) : OrderedEntity(rhs) , mPimpl(new ResetImpl()) { mPimpl->mOrder = rhs.mPimpl->mOrder; mPimpl->mVariable = rhs.mPimpl->mVariable; mPimpl->mWhens = rhs.mPimpl->mWhens; } Reset::Reset(Reset &&rhs) noexcept : OrderedEntity(std::move(rhs)) , mPimpl(rhs.mPimpl) { rhs.mPimpl = nullptr; } Reset &Reset::operator=(Reset rhs) { OrderedEntity::operator=(rhs); rhs.swap(*this); return *this; } void Reset::swap(Reset &rhs) { std::swap(this->mPimpl, rhs.mPimpl); } void Reset::setVariable(const VariablePtr &variable) { mPimpl->mVariable = variable; } VariablePtr Reset::variable() const { return mPimpl->mVariable; } void Reset::addWhen(const WhenPtr &when) { mPimpl->mWhens.push_back(when); } bool Reset::removeWhen(size_t index) { bool status = false; if (index < mPimpl->mWhens.size()) { mPimpl->mWhens.erase(mPimpl->mWhens.begin() + int64_t(index)); status = true; } return status; } bool Reset::removeWhen(const WhenPtr &when) { bool status = false; auto result = mPimpl->findWhen(when); if (result != mPimpl->mWhens.end()) { mPimpl->mWhens.erase(result); status = true; } return status; } void Reset::removeAllWhens() { mPimpl->mWhens.clear(); } bool Reset::containsWhen(const WhenPtr &when) const { bool status = false; auto result = mPimpl->findWhen(when); if (result != mPimpl->mWhens.end()) { status = true; } return status; } WhenPtr Reset::when(size_t index) const { WhenPtr when = nullptr; if (index < mPimpl->mWhens.size()) { when = mPimpl->mWhens.at(index); } return when; } WhenPtr Reset::takeWhen(size_t index) { WhenPtr when = nullptr; if (index < mPimpl->mWhens.size()) { when = mPimpl->mWhens.at(index); mPimpl->mWhens.erase(mPimpl->mWhens.begin() + int64_t(index)); } return when; } bool Reset::replaceWhen(size_t index, const WhenPtr &when) { bool status = false; if (removeWhen(index)) { mPimpl->mWhens.insert(mPimpl->mWhens.begin() + int64_t(index), when); status = true; } return status; } size_t Reset::whenCount() const { return mPimpl->mWhens.size(); } } // namespace libcellml
20.942857
78
0.657572
[ "vector" ]
35cd6660d0fcacc520313c84621e55bfab19cc1e
963
cpp
C++
aws-cpp-sdk-macie2/source/model/AwsService.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-macie2/source/model/AwsService.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-macie2/source/model/AwsService.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/macie2/model/AwsService.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Macie2 { namespace Model { AwsService::AwsService() : m_invokedByHasBeenSet(false) { } AwsService::AwsService(JsonView jsonValue) : m_invokedByHasBeenSet(false) { *this = jsonValue; } AwsService& AwsService::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("invokedBy")) { m_invokedBy = jsonValue.GetString("invokedBy"); m_invokedByHasBeenSet = true; } return *this; } JsonValue AwsService::Jsonize() const { JsonValue payload; if(m_invokedByHasBeenSet) { payload.WithString("invokedBy", m_invokedBy); } return payload; } } // namespace Model } // namespace Macie2 } // namespace Aws
16.05
69
0.713396
[ "model" ]
35d88f0a114f289d0dd553ad6bd4e71f9e482bd6
11,990
cpp
C++
project/src/voxelsystem.cpp
ebirenbaum/yurtcraft
4d5ee607e902dfa7db60e7e0b6736cd6d4704e70
[ "MIT" ]
null
null
null
project/src/voxelsystem.cpp
ebirenbaum/yurtcraft
4d5ee607e902dfa7db60e7e0b6736cd6d4704e70
[ "MIT" ]
null
null
null
project/src/voxelsystem.cpp
ebirenbaum/yurtcraft
4d5ee607e902dfa7db60e7e0b6736cd6d4704e70
[ "MIT" ]
null
null
null
#include "voxelsystem.h" #include "entity.h" VoxelSystem::VoxelSystem(/*const string &atlas*/) : /*m_atlas(atlas), */m_factory(NULL) { int n = 3; m_xb = Vector2(-n,n); m_yb = Vector2(0,n); m_zb = Vector2(-n,n); for (int i = 0; i < NUM_THREADS; i++){ m_threadData[i].active = false; m_threadData[i].ready = false; } } VoxelSystem::~VoxelSystem() { delete m_factory; } void VoxelSystem::draw(Graphics *g) { g->setupTexture("atlas"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); for (map<pair<int, pair<int, int> >, Chunk *>::iterator it = m_chunks.begin(); it != m_chunks.end(); it++) { Chunk *chunk = it->second; if (!g->isCulled(chunk->getBoundingBox())) { chunk->draw(g); } } glDisableClientState(GL_NORMAL_ARRAY); if (!g->debug) { g->enableBlend(); for (map<pair<int, pair<int, int> >, Chunk *>::iterator it = m_chunks.begin(); it != m_chunks.end(); it++) { Chunk *chunk = it->second; if (!g->isCulled(chunk->getBoundingBox())) { chunk->transparentDraw(g); } } g->disableBlend(); } glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); g->teardownTexture(); } void VoxelSystem::collide(float seconds, vector<Entity *> *entities) { for (int i = 0; i < entities->size(); i++) { if (entities->at(i)->m_collidesTerrain){ collideEntity(seconds, entities->at(i)); } } } void VoxelSystem::collideEntity(float seconds, Entity *e) { Vector3 currChunk = (e->m_pos / Vector3((float)CHUNKX, (float)CHUNKY, (float)CHUNKZ)).floor(); if (m_chunks.find(currChunk.toPair()) != m_chunks.end()) { Chunk *chunk = m_chunks[currChunk.toPair()]; chunk->collide(seconds, e); } else { //m_chunks[currChunk.toPair()] = m_factory->getChunk(currChunk); } Vector3 nextTranslation = e->nextTranslation(seconds), nextPos = e->m_pos + nextTranslation, nextChunk = (nextPos / Vector3((float)CHUNKX, (float)CHUNKY, (float)CHUNKZ)).floor(); if (m_chunks.find(nextChunk.toPair()) != m_chunks.end()) { Chunk *chunk = m_chunks[nextChunk.toPair()]; chunk->collide(seconds, e); } else { //m_chunks[nextChunk.toPair()] = m_factory->getChunk(nextChunk); } AAB entityAAB = e->getBoundingBox(); entityAAB.translate(nextTranslation); for (int i = 0; i < 27; i++) { if (i != 13) { Vector3 diff = Vector3((i / 3) % 3 - 1, i / 9 - 1, i % 3 - 1), temp = nextChunk + diff; if (m_chunks.find(temp.toPair()) != m_chunks.end()) { Chunk *chunk = m_chunks[temp.toPair()]; if (chunk->getBoundingBox().collides(entityAAB)) { chunk->collide(seconds, e); } } else { //m_chunks[temp.toPair()] = m_factory->getChunk(temp); } } } } VoxelIntersection VoxelSystem::raycast(const Ray &ray, vector<Entity *> *entities) { const int stepX = (ray.d.x > 0 ? 1 : (ray.d.x < 0 ? -1 : 0)), stepY = (ray.d.y > 0 ? 1 : (ray.d.y < 0 ? -1 : 0)), stepZ = (ray.d.z > 0 ? 1 : (ray.d.z < 0 ? -1 : 0)); const float tDeltaX = fabs(1.0 / ray.d.x), tDeltaY = fabs(1.0 / ray.d.y), tDeltaZ = fabs(1.0 / ray.d.z); int capX = (stepX >= 0 ? floor(ray.p.x) : ceil(ray.p.x)), capY = (stepY >= 0 ? floor(ray.p.y) : ceil(ray.p.y)), capZ = (stepZ >= 0 ? floor(ray.p.z) : ceil(ray.p.z)); float tMaxX = ((double)(capX + stepX) - ray.p.x) / ray.d.x, tMaxY = ((double)(capY + stepY) - ray.p.y) / ray.d.y, tMaxZ = ((double)(capZ + stepZ) - ray.p.z) / ray.d.z; int lastStep = -1; while (true) { if (tMaxX < tMaxY) { if (tMaxX < tMaxZ) { capX += stepX; tMaxX += tDeltaX; lastStep = 0; } else { capZ += stepZ; tMaxZ += tDeltaZ; lastStep = 2; } } else { if (tMaxY < tMaxZ) { capY += stepY; tMaxY += tDeltaY; lastStep = 1; } else { capZ += stepZ; tMaxZ += tDeltaZ; lastStep = 2; } } Vector3 next = Vector3(capX + (stepX >= 0 ? 0 : -1), capY + (stepY >= 0 ? 0 : -1), capZ + (stepZ >= 0 ? 0 : -1)); Vector3 nextChunk = (next / Vector3(CHUNKX, CHUNKY, CHUNKZ)).floor(); if (m_chunks.find(nextChunk.toPair()) == m_chunks.end()) { return VoxelIntersection(); } else { Chunk *chunk = m_chunks[nextChunk.toPair()]; Block block = chunk->getTranslatedBlock(next); if (!block.isPassable()) { Vector3 extra = (lastStep == 0 ? Vector3(-stepX, 0, 0) : (lastStep == 1 ? Vector3(0, -stepY, 0) : Vector3(0, 0, -stepZ))); // if (_selected.valid && (_selected.p != next || _selected.n != extra)) { // _heldTime = 0; // } return VoxelIntersection(lastStep == 0 ? tMaxX - tDeltaX : (lastStep == 1 ? tMaxY - tDeltaY : tMaxZ - tDeltaZ), block, next, extra); // _selected = Intersection(lastStep == 0 ? tMaxX - tDeltaX : (lastStep == 1 ? tMaxY - tDeltaY : tMaxZ - tDeltaZ), // next, extra, true, (int)block); // _mob = Intersection(); // _mob.t = 999999; // _killIt = NULL; } } } // foreach (Entity *et, _entities) { // MinecraftEntity *e = (MinecraftEntity *)et; // if (e != _player) { // Intersection check = e->raycast(ray); // if (check.valid && check.t < _selected.t && check.t < _mob.t) { // _mob = check; // _killIt = e; // } // } // } // if (_mob.valid) _selected = Intersection(); } void *generateChunkInThread(void *threadDataThing){ struct ChunkGenThreadData *data = (struct ChunkGenThreadData *) threadDataThing; data->chunk = data->factory->createChunk(data->address); data->ready = true; pthread_exit(NULL); } void VoxelSystem::setChunkFixation(const Vector3 &pos) { Vector3 currChunk = (pos / Vector3(CHUNKX, CHUNKY, CHUNKZ)).floor(); int count = 1; while (!_incoming.empty()) { Vector3 next = _incoming.front(); _incoming.pop(); if (m_chunks.find(next.toPair()) != m_chunks.end()) continue; if (USE_THREADS){ int _useableThread = -1; for (int i = 0; i < NUM_THREADS; i++){ if (!m_threadData[i].active){ _useableThread = i; break; } } if (_useableThread == -1){ _incoming.push(next); break; } m_threadData[_useableThread].address = next; m_threadData[_useableThread].factory = m_factory; m_threadData[_useableThread].active = true; m_threadData[_useableThread].ready = false; pthread_create(&m_threads[_useableThread], NULL, generateChunkInThread, (void *)&(m_threadData[_useableThread])); } else { m_chunks[next.toPair()] = m_factory->getChunk(next); } if (--count == 0) break; } if (USE_THREADS){ for (int i = 0; i < NUM_THREADS; i++){ if (m_threadData[i].ready){ m_threadData[i].chunk->resetVbo(); m_chunks[m_threadData[i].address.toPair()] = m_threadData[i].chunk; m_threadData[i].ready = false; m_threadData[i].active = false; break; // only one per frame } } } count = 2; while (!_outgoing.empty()) { Vector3 next = _outgoing.front(); _outgoing.pop(); if (m_chunks.find(next.toPair()) != m_chunks.end()); { Chunk *c = m_chunks[next.toPair()]; m_chunks.erase(next.toPair()); delete c; if (--count == 0) break; } } // Check for new chunks to stream int xCo = (m_xb.x + m_xb.y) / 2; if (currChunk.x == xCo + 1) { for (int i = m_yb.x; i <= m_yb.y; i++) { for (int j = m_zb.x; j <= m_zb.y; j++) { _incoming.push(Vector3(m_xb.y + 1, i, j)); _outgoing.push(Vector3(m_xb.x, i, j)); } } m_xb += Vector2(1,1); } else if (currChunk.x == xCo - 1) { for (int i = m_yb.x; i <= m_yb.y; i++) { for (int j = m_zb.x; j <= m_zb.y; j++) { _incoming.push(Vector3(m_xb.x - 1, i, j)); _outgoing.push(Vector3(m_xb.y, i, j)); } } m_xb -= Vector2(1,1); } int zCo = (m_zb.x + m_zb.y) / 2; if (currChunk.z == zCo + 1) { for (int i = m_yb.x; i <= m_yb.y; i++) { for (int j = m_xb.x; j <= m_xb.y; j++) { _incoming.push(Vector3(j, i, m_zb.y + 1)); _outgoing.push(Vector3(j, i, m_zb.x)); } } m_zb += Vector2(1,1); } else if (currChunk.z == zCo - 1) { for (int i = m_yb.x; i <= m_yb.y; i++) { for (int j = m_xb.x; j <= m_xb.y; j++) { _incoming.push(Vector3(j, i, m_zb.x - 1)); _outgoing.push(Vector3(j, i, m_zb.y)); } } m_zb -= Vector2(1,1); } int yCo = (m_yb.x + m_yb.y) / 2; if (currChunk.y == yCo + 1) { for (int i = m_xb.x; i <= m_xb.y; i++) { for (int j = m_zb.x; j <= m_zb.y; j++) { _incoming.push(Vector3(i, m_yb.y + 1, j)); _outgoing.push(Vector3(i, m_yb.x, j)); } } m_yb += Vector2(1,1); } else if (currChunk.y == yCo - 1) { for (int i = m_xb.x; i <= m_xb.y; i++) { for (int j = m_zb.x; j <= m_zb.y; j++) { _incoming.push(Vector3(i, m_yb.x - 1, j)); _outgoing.push(Vector3(i, m_yb.y, j)); } } m_yb -= Vector2(1,1); } } void VoxelSystem::setChunkFactory(ChunkFactory *factory) { m_factory = factory; cout << "Building initial chunks..." << endl; for (int i = m_xb.x; i <= m_xb.y; i++) { for (int j = m_yb.x; j <= m_yb.y; j++) { for (int k = m_zb.x; k <= m_zb.y; k++) { Vector3 next(i,j,k); m_chunks[next.toPair()] = m_factory->getChunk(next); } } } } Block VoxelSystem::queryBlock(const Vector3 &pos) { Vector3 chunk = (pos / Vector3((float)CHUNKX, (float)CHUNKY, (float)CHUNKZ)).floor(); if (m_chunks.find(chunk.toPair()) != m_chunks.end()) { return m_chunks[chunk.toPair()]->getTranslatedBlock(pos.floor()); } return Block(); } void VoxelSystem::setBlock(const Vector3 &pos, char type) { Vector3 chunkPos = (pos / Vector3((float)CHUNKX, (float)CHUNKY, (float)CHUNKZ)).floor(); if (m_chunks.find(chunkPos.toPair()) != m_chunks.end()) { Chunk *chunk = m_chunks[chunkPos.toPair()]; chunk->setTranslatedBlock(pos, m_factory->getBlockDef(type)); chunk->resetVbo(); } }
35.264706
145
0.492994
[ "vector" ]
35dc9c82cf389534e050493989b4696d4ce5eee7
2,396
cpp
C++
src/db/provider/db-session-provider.cpp
garronej/linphone
f61a337f5363b991d6e866a6aa7d303658c04073
[ "BSD-2-Clause" ]
null
null
null
src/db/provider/db-session-provider.cpp
garronej/linphone
f61a337f5363b991d6e866a6aa7d303658c04073
[ "BSD-2-Clause" ]
null
null
null
src/db/provider/db-session-provider.cpp
garronej/linphone
f61a337f5363b991d6e866a6aa7d303658c04073
[ "BSD-2-Clause" ]
1
2021-03-17T10:04:06.000Z
2021-03-17T10:04:06.000Z
/* * db-session-provider.cpp * Copyright (C) 2017 Belledonne Communications SARL * * 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 <http://www.gnu.org/licenses/>. */ #include <unordered_map> #ifdef SOCI_ENABLED #include <soci/soci.h> #endif // ifdef SOCI_ENABLED #include "db-session-p.h" #include "object/object-p.h" #include "db-session-provider.h" #define CLEAN_COUNTER_MAX 1000 // ============================================================================= using namespace std; LINPHONE_BEGIN_NAMESPACE class DbSessionProviderPrivate : public ObjectPrivate { public: typedef pair<weak_ptr<void>, DbSessionPrivate *> InternalSession; unordered_map<string, InternalSession> sessions; int cleanCounter = 0; }; DbSessionProvider::DbSessionProvider () : Singleton(*new DbSessionProviderPrivate) {} DbSession DbSessionProvider::getSession (const string &uri) { L_D(DbSessionProvider); #ifdef SOCI_ENABLED DbSession session(DbSession::Soci); try { shared_ptr<void> backendSession = d->sessions[uri].first.lock(); ++d->cleanCounter; if (!backendSession) { // Create new session. backendSession = make_shared<soci::session>(uri); DbSessionPrivate *p = session.getPrivate(); p->backendSession = backendSession; p->isValid = true; d->sessions[uri] = make_pair(backendSession, p); } else // Share session. session.setRef(*d->sessions[uri].second); } catch (const exception &) {} #else DbSession session(DbSession::None); #endif // ifdef SOCI_ENABLED // Remove invalid weak ptrs. if (d->cleanCounter >= CLEAN_COUNTER_MAX) { d->cleanCounter = 0; for (auto it = d->sessions.begin(), itEnd = d->sessions.end(); it != itEnd;) { if (it->second.first.expired()) it = d->sessions.erase(it); else ++it; } } return session; } LINPHONE_END_NAMESPACE
28.52381
85
0.696995
[ "object" ]
35deab9027426a5e93458ec6ed1c0624f460149d
3,010
cpp
C++
Emscripten/G3MEmscripten/G3MEmscripten/JSONParser_Emscripten.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
70
2015-02-06T14:39:14.000Z
2022-01-07T08:32:48.000Z
Emscripten/G3MEmscripten/G3MEmscripten/JSONParser_Emscripten.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
118
2015-01-21T10:18:00.000Z
2018-10-16T15:00:57.000Z
Emscripten/G3MEmscripten/G3MEmscripten/JSONParser_Emscripten.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
41
2015-01-10T22:29:27.000Z
2021-06-08T11:56:16.000Z
#include "JSONParser_Emscripten.hpp" #include <emscripten/val.h> #include "EMStorage.hpp" #include "G3M/IByteBuffer.hpp" #include "G3M/JSONNull.hpp" #include "G3M/JSONBoolean.hpp" #include "G3M/JSONInteger.hpp" #include "G3M/JSONLong.hpp" #include "G3M/JSONFloat.hpp" #include "G3M/JSONDouble.hpp" #include "G3M/JSONString.hpp" #include "G3M/JSONArray.hpp" #include "G3M/JSONObject.hpp" using namespace emscripten; JSONBaseObject* _convert(const val& json, const bool nullAsObject, const val& Object) { if (json.isNull()) { return nullAsObject ? new JSONNull() : NULL; } if (json.isTrue()) { return new JSONBoolean(true); } if (json.isFalse()) { return new JSONBoolean(false); } if (json.isNumber()) { const double doubleValue = json.as<double>(); const int intValue = (int) doubleValue; if (doubleValue == intValue) { return new JSONInteger(intValue); } const long long longValue = (long long) doubleValue; if (doubleValue == longValue) { return new JSONLong(longValue); } const float floatValue = (float) doubleValue; if (doubleValue == floatValue) { return new JSONFloat(floatValue); } return new JSONDouble(doubleValue); } if (json.isString()) { return new JSONString(json.as<std::string>()); } if (json.isArray()) { const int length = json["length"].as<int>(); JSONArray* array = new JSONArray(length); for (int i = 0; i < length; i++) { val element = json[i]; array->add( _convert(element, nullAsObject, Object) ); } return array; } { // object JSONObject* object = new JSONObject(); val jsKeys = Object.call<val>("keys", json); const int keysLength = jsKeys["length"].as<int>(); for (int i = 0; i < keysLength; i++) { val jsKey = jsKeys[i]; val jsValue = json[jsKey]; // EMStorage::consoleLog( val("jsKey") ); // EMStorage::consoleLog( jsKey ); // // EMStorage::consoleLog( val("jsValue") ); // EMStorage::consoleLog( jsValue ); JSONBaseObject* value = _convert(jsValue, nullAsObject, Object); if (value != NULL) { const std::string key = jsKey.as<std::string>(); object->put(key, value); } } return object; } return NULL; } const JSONBaseObject* JSONParser_Emscripten::parse(const IByteBuffer* buffer, bool nullAsObject) { return parse(buffer->getAsString(), nullAsObject); } const JSONBaseObject* JSONParser_Emscripten::parse(const std::string& json, bool nullAsObject) { const val jsResult = val::global("JSON").call<val>("parse", json); // EMStorage::consoleLog( jsResult ); const JSONBaseObject* result = _convert(jsResult, nullAsObject, val::global("Object")); // EMStorage::consoleLog( val(result->description()) ); return result; }
24.672131
89
0.609967
[ "object" ]
e3019b3577c7c059f6b29ce530f5ee072467b369
4,437
cpp
C++
shaharmike/shared_pointer.cpp
IslameN/c-
f57ed8b61879571f17f413bd22ccc904bddde79f
[ "MIT" ]
1
2021-03-11T15:36:57.000Z
2021-03-11T15:36:57.000Z
shaharmike/shared_pointer.cpp
IslameN/c-
f57ed8b61879571f17f413bd22ccc904bddde79f
[ "MIT" ]
null
null
null
shaharmike/shared_pointer.cpp
IslameN/c-
f57ed8b61879571f17f413bd22ccc904bddde79f
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <type_traits> struct Snitch { public: Snitch() { std::cout << "c'tor: " << this << std::endl; } ~Snitch() { std::cout << "d'tor: " << this << std::endl; } Snitch(Snitch const&) { std::cout << "copy c'tor: " << this << std::endl; } Snitch(Snitch&&) { std::cout << "move c'tor: " << this << std::endl; } }; // 2 std::unique_ptr<Snitch> CreateMyObject() { return std::make_unique<Snitch>(); } // 4 struct Node { // Binary tree Node() { std::cout << "c'tor: " << this << std::endl; } ~Node() { std::cout << "d'tor: " << this << std::endl; } std::shared_ptr<Node> parent; std::shared_ptr<Node> left; std::shared_ptr<Node> right; }; // 5 struct WeakNode { // Binary tree WeakNode() { std::cout << "c'tor: " << this << std::endl; } ~WeakNode() { std::cout << "d'tor: " << this << std::endl; } std::weak_ptr<WeakNode> parent; std::shared_ptr<WeakNode> left; std::shared_ptr<WeakNode> right; }; // 7 struct DatabaseConnection {}; // exposed to the user struct InternalDatabaseConnection { // socket // authentication information DatabaseConnection connection; }; std::shared_ptr<DatabaseConnection> CreateDatabaseConnection() { auto tmp = std::make_shared<InternalDatabaseConnection>(); return std::shared_ptr<DatabaseConnection>(tmp, &tmp->connection); } // 8 struct Base { ~Base() { std::cout << "non-virtual ~Base()" << std::endl; } }; struct Derived : Base { ~Derived() { std::cout << "~Derived()" << std::endl; } }; // 10 struct WeirdClass { std::shared_ptr<WeirdClass> CreateSharedPtrToThis() { return std::shared_ptr<WeirdClass>(this); // DON'T DO THIS. } }; struct WeirdClass2 : std::enable_shared_from_this<WeirdClass2> { std::shared_ptr<WeirdClass2> CreateSharedPtrToThis() { return shared_from_this(); } }; int main() { // // 1 // auto snitch = std::make_shared<Snitch>(); // auto another_snitch = snitch; // std::cout << "Equal? " << (snitch == another_snitch) << std::endl; // { // auto scoped_snitch = snitch; // auto another_scoped_snitch = scoped_snitch; // } // destroy 'another_scoped_snitch' and 'scoped_snitch' // // 2 Construct from unique_ptr // std::shared_ptr<Snitch> shared_object = CreateMyObject(); // // 3 No release() method, reset() doesn’t necessarily release // std::cout << "Creating 1st Snitch" << std::endl; // auto snitch1 = std::make_shared<Snitch>(); // auto snitch2 = snitch1; // std::cout << "Calling reset" << std::endl; // snitch1.reset(); // object will *not* be released // std::cout << "Moving out of scope" << std::endl; // 4 Cyclic references & std::weak_ptr auto root = std::make_shared<Node>(); root->left = std::make_shared<Node>(); root->left->parent = root; // 5 auto root5 = std::make_shared<WeakNode>(); root5->left = std::make_shared<WeakNode>(); root5->left->parent = root5; // 6 weak pointers have no get() and should be upgraded std::weak_ptr<std::string> weak; // = std::make_shared<std::string>("lo2l"); std::shared_ptr<std::string> shared = weak.lock(); if (shared) { std::cout << "Exists" << std::endl; } else { std::cout << "Released" << std::endl; } // 8 Casting std::shared_ptr<Base> base = std::make_shared<Derived>(); // If we were to replace shared_ptr with unique_ptr (and make_shared with make_unique) the program would not call ~Derived. // 9 auto derived = std::make_shared<Derived>(); std::shared_ptr<Base> base9 = derived; // OK. // std::shared_ptr<Derived> derived2 = base; // ERROR: no implicit down-cast. std::shared_ptr<Derived> derived2 = std::static_pointer_cast<Derived>(base9); // std::shared_ptr<Derived> derived3 = // std::dynamic_pointer_cast<Derived>(base9); // ERROR: do not know why auto shared_short = std::make_shared<short>(123); //std::shared_ptr<int> shared_int = shared_short; // ERROR: no cast from //short* to int*. // 10 std::enable_shared_from_this auto weird_class = std::make_shared<WeirdClass>(); // auto tmp = weird_class->CreateSharedPtrToThis(); // ERROR: double delete auto weird_class2 = std::make_shared<WeirdClass2>(); auto tmp = weird_class2->CreateSharedPtrToThis(); } // 1 destroy 'snother_snitch' and 'snitch'
32.386861
186
0.622718
[ "object" ]
e3068df6f77d102585213320d4f31c19ab6f6a49
7,847
cpp
C++
src/particle_filter.cpp
Mleekko/CarND-Kidnapped-Vehicle-Project
e34b54928bf24885a64d30210fc227b54a7f2fa4
[ "MIT" ]
null
null
null
src/particle_filter.cpp
Mleekko/CarND-Kidnapped-Vehicle-Project
e34b54928bf24885a64d30210fc227b54a7f2fa4
[ "MIT" ]
null
null
null
src/particle_filter.cpp
Mleekko/CarND-Kidnapped-Vehicle-Project
e34b54928bf24885a64d30210fc227b54a7f2fa4
[ "MIT" ]
null
null
null
/** * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include "particle_filter.h" #include <cmath> #include <algorithm> #include <iostream> #include <iterator> #include <random> #include <string> #include <vector> #include <cassert> #include <unordered_map> #include "helper_functions.h" using namespace std; const double EPSILON = 0.000001; void ParticleFilter::init(double x, double y, double theta, double std[]) { /** * NOTE: Consult particle_filter.h for more information about this method * (and others in this file). */ num_particles = 64; random_device rd; default_random_engine gen(rd()); normal_distribution<double> N_x(x, std[0]); normal_distribution<double> N_y(y, std[1]); normal_distribution<double> N_theta(theta, std[2]); for (int i = 0; i < num_particles; i++) { Particle p; p.id = i; p.x = N_x(gen); p.y = N_y(gen); p.theta = N_theta(gen); p.weight = 1.; particles.push_back(p); weights.push_back(1.); cout << "## init << " << p.x << " " << p.y << " " << p.theta << endl; } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { random_device rd; default_random_engine gen(rd()); for (auto &particle : particles) { double x = particle.x; double y = particle.y; double theta = particle.theta; double cos_theta = cos(theta); double sin_theta = sin(theta); double delta_yaw = yaw_rate * delta_t; if (fabs(yaw_rate) < EPSILON) { double delta_velocity = velocity * delta_t; x += delta_velocity * cos_theta; y += delta_velocity * sin_theta; } else { double velocity_rate = velocity / yaw_rate; x += velocity_rate * (sin(theta + delta_yaw) - sin_theta); y += velocity_rate * (cos_theta - cos(theta + delta_yaw)); } theta += delta_yaw; normal_distribution<double> N_x(x, std_pos[0]); normal_distribution<double> N_y(y, std_pos[1]); normal_distribution<double> N_theta(theta, std_pos[2]); particle.x = N_x(gen); particle.y = N_y(gen); particle.theta = N_theta(gen); } } unordered_map<int, LandmarkObs> ParticleFilter::dataAssociation(const vector<LandmarkObs> &predicted, vector<LandmarkObs> &observations) { unordered_map<int, LandmarkObs> predictions_per_id{}; for (auto &observation: observations) { double min_dist = numeric_limits<double>::max(); LandmarkObs closest{}; for (auto &prediction: predicted) { double act_dist = dist(observation.x, observation.y, prediction.x, prediction.y); if (act_dist < min_dist) { min_dist = act_dist; closest = prediction; } } predictions_per_id[closest.id] = closest; observation.id = closest.id; } return predictions_per_id; } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const vector<LandmarkObs> &observations, const Map &map_landmarks) { double gauss_norm = 1 / (2 * M_PI * std_landmark[0] * std_landmark[1]); double std_norm_x = 2 * pow(std_landmark[0], 2); double std_norm_y = 2 * pow(std_landmark[1], 2); weights.clear(); for (auto &particle : particles) { double cos_theta = cos(particle.theta); double sin_theta = sin(particle.theta); // Observations in map coordinates (from particle's POV) vector<LandmarkObs> trans_observations; for (auto &obs: observations) { LandmarkObs trans_obs{}; trans_obs.x = particle.x + obs.x * cos_theta - obs.y * sin_theta; trans_obs.y = particle.y + obs.x * sin_theta + obs.y * cos_theta; trans_observations.push_back(trans_obs); } // cycle through map_landmarks (real landmark positions) and filter out landmarks > sensor distance vector<LandmarkObs> predicted_landmarks; for (auto &map_landmark : map_landmarks.landmark_list) { double distance = dist(particle.x, particle.y, map_landmark.x_f, map_landmark.y_f); if (distance <= sensor_range) { LandmarkObs prediction{}; prediction.id = map_landmark.id_i; prediction.x = map_landmark.x_f; prediction.y = map_landmark.y_f; predicted_landmarks.push_back(prediction); } } // use dataAssociation(predicted, observations) to match the closest real landmark to EACH observed landmark // run data association on observed landmarks and landmarks within sensor range unordered_map<int, LandmarkObs> predictions_per_id = dataAssociation(predicted_landmarks, trans_observations); double weight = 1.0; for (LandmarkObs &obs : trans_observations) { LandmarkObs predicted_landmark = predictions_per_id[obs.id]; double delta_x = pow(obs.x - predicted_landmark.x, 2); double delta_y = pow(obs.y - predicted_landmark.y, 2); double exponent = (delta_x / std_norm_x) + (delta_y / std_norm_y); weight *= gauss_norm * exp(-exponent); } weights.push_back(weight); particle.weight = weight; } } void ParticleFilter::resample() { /** * See * https://en.cppreference.com/w/cpp/numeric/random/discrete_distribution * and * https://en.cppreference.com/w/cpp/numeric/random/discrete_distribution/discrete_distribution */ random_device rd; default_random_engine gen(rd()); discrete_distribution<int> distribution(weights.begin(), weights.end()); vector<Particle> updated_particles = vector<Particle>(particles.size()); vector<double> updated_weights = vector<double>(weights.size()); for (size_t i = 0; i < particles.size(); i++) { int rand_idx = distribution(gen); updated_particles[i] = particles[rand_idx]; updated_weights[i] = particles[rand_idx].weight; } particles = updated_particles; weights = updated_weights; } void ParticleFilter::SetAssociations(Particle &particle, const vector<int> &associations, const vector<double> &sense_x, const vector<double> &sense_y) { // particle: the particle to which assign each listed association, // and association's (x,y) world coordinates mapping // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations = associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(const Particle &best) { vector<int> v = best.associations; stringstream ss; copy(v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length() - 1); // get rid of the trailing space return s; } string ParticleFilter::getSenseCoord(const Particle &best, const string &coord) { vector<double> v; if (coord == "X") { v = best.sense_x; } else { v = best.sense_y; } stringstream ss; copy(v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length() - 1); // get rid of the trailing space return s; }
35.346847
118
0.618325
[ "vector" ]
e306baf8c94aaea83770f80f4d2c1f4a9f828abb
16,034
cpp
C++
pge/source/pge/rendering/voxel/VoxelChunk.cpp
222464/PGE
8801301046a0412c323444a7f9f49e02f9ac87cc
[ "Zlib" ]
100
2016-05-04T00:05:43.000Z
2021-09-11T17:34:31.000Z
pge/source/pge/rendering/voxel/VoxelChunk.cpp
222464/PGE
8801301046a0412c323444a7f9f49e02f9ac87cc
[ "Zlib" ]
8
2016-05-06T12:51:53.000Z
2017-07-20T20:15:46.000Z
pge/source/pge/rendering/voxel/VoxelChunk.cpp
222464/PGE
8801301046a0412c323444a7f9f49e02f9ac87cc
[ "Zlib" ]
16
2016-05-04T06:37:20.000Z
2020-11-12T17:24:55.000Z
#include <pge/rendering/voxel/VoxelChunk.h> #include <pge/rendering/voxel/VoxelTerrain.h> #include <pge/util/Math.h> using namespace pge; void VoxelChunk::create(const SceneObjectRef &voxelTerrain, const Point3i &centerRelativePosition) { _renderMask = 0xffff; _voxelTerrain = voxelTerrain; if (_sharedData == nullptr) _sharedData.reset(new SharedData()); _centerRelativePosition = centerRelativePosition; updateChunkAABB(); } void VoxelChunk::addVertex(const Point3i &center, int lod, unsigned char vertIndex, std::unordered_map<ChunkVertex, voxelChunkMeshIndexType, ChunkVertex> &positionToIndex, std::vector<Vertex> &vertices, std::vector<voxelChunkMeshIndexType> &faceIndices, std::unordered_map<voxelChunkMeshIndexType, bool> &isFlange, bool setAsFlange, VoxelTerrain* pVoxelTerrain) { assert(vertIndex < 8); Point3i p0(center); std::array<std::array<int, 2>, 3> cornersi; cornersi[0][0] = center.x; cornersi[0][1] = center.x + lod; cornersi[1][0] = center.y; cornersi[1][1] = center.y + lod; cornersi[2][0] = center.z; cornersi[2][1] = center.z + lod; Point3i p1(cornersi[0][(vertIndex & 0x04) == 0 ? 0 : 1], cornersi[1][(vertIndex & 0x02) == 0 ? 0 : 1], cornersi[2][(vertIndex & 0x01) == 0 ? 0 : 1]); std::unordered_map<ChunkVertex, voxelChunkMeshIndexType, ChunkVertex>::iterator it = positionToIndex.find(ChunkVertex(p1)); if (it == positionToIndex.end()) { std::array<Vec3f, 8> pa; std::array<float, 8> va; for (unsigned char i = 0; i < 8; i++) { Point3i p = p1 + Point3i((i & 0x04) == 0 ? 0 : -lod, (i & 0x02) == 0 ? 0 : -lod, (i & 0x01) == 0 ? 0 : -lod); Vec3f pf(static_cast<float>(p.x), static_cast<float>(p.y), static_cast<float>(p.z)); float v = static_cast<float>(pVoxelTerrain->getVoxel(p)) * pVoxelTerrain->_voxelScalar; pa[i] = pf; va[i] = v; } Vec3f vertexPosition(0.0f, 0.0f, 0.0f); float vSum = 0.0f; if (sign(va[7]) != sign(va[3])) { vertexPosition += lerp(pa[7], pa[3], va[7] / (va[7] - va[3])); vSum++; } if (sign(va[3]) != sign(va[1])) { vertexPosition += lerp(pa[3], pa[1], va[3] / (va[3] - va[1])); vSum++; } if (sign(va[1]) != sign(va[5])) { vertexPosition += lerp(pa[1], pa[5], va[1] / (va[1] - va[5])); vSum++; } if (sign(va[5]) != sign(va[7])) { vertexPosition += lerp(pa[5], pa[7], va[5] / (va[5] - va[7])); vSum++; } if (sign(va[2]) != sign(va[6])) { vertexPosition += lerp(pa[2], pa[6], va[2] / (va[2] - va[6])); vSum++; } if (sign(va[6]) != sign(va[4])) { vertexPosition += lerp(pa[6], pa[4], va[6] / (va[6] - va[4])); vSum++; } if (sign(va[4]) != sign(va[0])) { vertexPosition += lerp(pa[4], pa[0], va[4] / (va[4] - va[0])); vSum++; } if (sign(va[0]) != sign(va[2])) { vertexPosition += lerp(pa[0], pa[2], va[0] / (va[0] - va[2])); vSum++; } if (sign(va[3]) != sign(va[2])) { vertexPosition += lerp(pa[3], pa[2], va[3] / (va[3] - va[2])); vSum++; } if (sign(va[1]) != sign(va[0])) { vertexPosition += lerp(pa[1], pa[0], va[1] / (va[1] - va[0])); vSum++; } if (sign(va[5]) != sign(va[4])) { vertexPosition += lerp(pa[5], pa[4], va[5] / (va[5] - va[4])); vSum++; } if (sign(va[7]) != sign(va[6])) { vertexPosition += lerp(pa[7], pa[6], va[7] / (va[7] - va[6])); vSum++; } assert(vSum != 0.0f); vertexPosition = vertexPosition / vSum * pVoxelTerrain->_voxelSize; // Create new vertex // Find position via weighted average of vertices.push_back(Vertex(vertexPosition)); faceIndices.push_back(vertices.size() - 1); positionToIndex[ChunkVertex(p1)] = vertices.size() - 1; isFlange[faceIndices.back()] = setAsFlange; } else // Use existing vertex faceIndices.push_back(it->second); } void VoxelChunk::addGeometry(const Point3i &center, int lod, int side, std::unordered_map<ChunkVertex, voxelChunkMeshIndexType, ChunkVertex> &positionToIndex, std::vector<Vertex> &vertices, std::vector<voxelChunkMeshIndexType> &faceIndices, std::unordered_map<voxelChunkMeshIndexType, bool> &isFlange, bool setAsFlange, VoxelTerrain* pVoxelTerrain) { // Surrounding indices switch (side) { case 0: // +X addVertex(center, lod, 4, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 5, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 7, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 6, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); break; case 1: // -X addVertex(center, lod, 1, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 0, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 2, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 3, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); break; case 2: // +Y addVertex(center, lod, 3, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 2, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 6, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 7, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); break; case 3: // -Y addVertex(center, lod, 0, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 1, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 5, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 4, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); break; case 4: // +Z addVertex(center, lod, 5, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 1, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 3, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 7, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); break; case 5: // -Z addVertex(center, lod, 0, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 4, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 6, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); addVertex(center, lod, 2, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); break; } } void VoxelChunk::generate(SceneObjectPhysicsWorld* pPhysicsWorld, float restitution, float friction) { assert(_voxelTerrain.isAlive()); VoxelTerrain* pVoxelTerrain = static_cast<VoxelTerrain*>(_voxelTerrain.get()); if (_sharedData->_empty) return; // Set empty to true, will remain unless set false when comes across full voxel in generation _sharedData->_empty = false; _sharedData->_lods.resize(pVoxelTerrain->_numChunkLODs); for (int lod = 1, lodIndex = 0; lodIndex < pVoxelTerrain->_numChunkLODs; lod *= 2, lodIndex++) { std::unordered_map<ChunkVertex, voxelChunkMeshIndexType, ChunkVertex> positionToIndex; std::unordered_map<voxelChunkMeshIndexType, bool> isFlange; std::vector<Vertex> vertices; std::vector<voxelChunkMeshIndexType> faceIndices; // Go through voxels (not differentiating between border voxels and inside voxels) int lodOffset = lod; for (int x = -lodOffset; x < _chunkSize + lodOffset; x += lod) for (int y = -lodOffset; y < _chunkSize + lodOffset; y += lod) for (int z = -lodOffset; z < _chunkSize + lodOffset; z += lod) { // If voxel is not empty voxelType currentVoxel; bool setAsFlange; if (x < 0 || x >= _chunkSize || y < 0 || y >= _chunkSize || z < 0 || z >= _chunkSize) { currentVoxel = pVoxelTerrain->getVoxel(Point3i( _centerRelativePosition.x * _chunkSize + x, _centerRelativePosition.y * _chunkSize + y, _centerRelativePosition.z * _chunkSize + z)); setAsFlange = true; } else { currentVoxel = _sharedData->_matrix[x + y * _chunkSize + z * _chunkSize * _chunkSize]; setAsFlange = false; } if (currentVoxel < 0) continue; // Check surrounding voxels to see if they are empty for (int side = 0; side < 6; side++) { Point3i offset(pVoxelTerrain->_positionOffsets[side] * lod); int newX = x + offset.x; int newY = y + offset.y; int newZ = z + offset.z; voxelType voxel; // If check location is outside this chunk, get the neighboring chunk if (newX < 0 || newX >= _chunkSize || newY < 0 || newY >= _chunkSize || newZ < 0 || newZ >= _chunkSize) voxel = pVoxelTerrain->getVoxel(Point3i( _centerRelativePosition.x * _chunkSize + newX, _centerRelativePosition.y * _chunkSize + newY, _centerRelativePosition.z * _chunkSize + newZ)); else voxel = _sharedData->_matrix[newX + newY * _chunkSize + newZ * _chunkSize * _chunkSize]; // If empty if (voxel < 0) addGeometry(Point3i(_centerRelativePosition.x * _chunkSize + x, _centerRelativePosition.y * _chunkSize + y, _centerRelativePosition.z * _chunkSize + z), lod, side, positionToIndex, vertices, faceIndices, isFlange, setAsFlange, pVoxelTerrain); } } _sharedData->_lods[lodIndex]._numVertices = vertices.size(); _sharedData->_lods[lodIndex]._numFaceIndices = faceIndices.size(); assert(faceIndices.size() % 4 == 0); _sharedData->_lods[lodIndex]._empty = _sharedData->_lods[lodIndex]._numVertices == 0; if (lodIndex == 0 && _sharedData->_lods[lodIndex]._empty) { _sharedData->_empty = true; return; } if (_sharedData->_lods[lodIndex]._empty) continue; // Generate real indices from face indices (triangulate the quads) _sharedData->_lods[lodIndex]._numIndices = 3 * _sharedData->_lods[lodIndex]._numFaceIndices / 2; std::vector<ChunkFace> indices; indices.reserve(_sharedData->_lods[lodIndex]._numIndices / 6); // Calculate normals and generate real indices for (size_t i = 0; i < _sharedData->_lods[lodIndex]._numFaceIndices; i += 4) { // Triangulate quad Vertex &vertex0 = vertices[faceIndices[i]]; Vertex &vertex1 = vertices[faceIndices[i + 1]]; Vertex &vertex2 = vertices[faceIndices[i + 2]]; Vertex &vertex3 = vertices[faceIndices[i + 3]]; Vec3f normal0; Vec3f normal1; bool hasNormal0 = false; bool hasNormal1 = false; if (vertex1._position != vertex2._position && vertex1._position != vertex0._position && vertex2._position != vertex0._position) { normal0 = ((vertex1._position - vertex0._position).cross(vertex2._position - vertex0._position)).normalized(); hasNormal0 = true; } if (vertex2._position != vertex0._position && vertex3._position != vertex2._position && vertex0._position != vertex3._position) { normal1 = ((vertex3._position - vertex2._position).cross(vertex0._position - vertex3._position)).normalized(); hasNormal1 = true; } if (!hasNormal0 || !hasNormal1) { if (hasNormal1) normal0 = normal1; else if (hasNormal0) normal1 = normal0; else normal1 = normal0 = Vec3f(0.0f, 1.0f, 0.0f); } //assert(normal0.magnitude() < 1000.0f && normal1.magnitude() < 1000.0f); Vec3f normalSum = (normal0 + normal1) * 0.5f; vertex0._normal += normalSum; vertex1._normal += normal0; vertex2._normal += normalSum; vertex3._normal += normal1; //assert(normalSum != Vec3f(0.0f, 0.0f, 0.0f) && normal0 != Vec3f(0.0f, 0.0f, 0.0f) && normal1 != Vec3f(0.0f, 0.0f, 0.0f)); // Generate real indices indices.push_back(ChunkFace(faceIndices[i], faceIndices[i + 1], faceIndices[i + 2], faceIndices[i + 3])); } for (size_t i = 0; i < vertices.size(); i++) { if (vertices[i]._normal.magnitude() < 0.00001f) vertices[i]._normal = Vec3f(0.0f, 1.0f, 0.0f); vertices[i]._normal.normalize(); } // Move flanges along normals for (size_t i = 0; i < _sharedData->_lods[lodIndex]._numFaceIndices; i++) { if (isFlange[faceIndices[i]]) vertices[faceIndices[i]]._position -= vertices[faceIndices[i]]._normal * (lod - 1) * 0.125f; } // Destroy any existing buffers if (_sharedData->_lods[lodIndex]._vertices.created()) _sharedData->_lods[lodIndex]._vertices.destroy(); if (_sharedData->_lods[lodIndex]._indices.created()) _sharedData->_lods[lodIndex]._indices.destroy(); // Create (or re-create) VBOs _sharedData->_lods[lodIndex]._vertices.create(); _sharedData->_lods[lodIndex]._indices.create(); // Vertex VBO _sharedData->_lods[lodIndex]._vertices.bind(GL_ARRAY_BUFFER); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * _sharedData->_lods[lodIndex]._numVertices, &vertices[0], GL_STATIC_DRAW); _sharedData->_lods[lodIndex]._vertices.unbind(); // Index VBO _sharedData->_lods[lodIndex]._indices.bind(GL_ELEMENT_ARRAY_BUFFER); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(voxelChunkMeshIndexType) * _sharedData->_lods[lodIndex]._numIndices, &indices[0], GL_STATIC_DRAW); _sharedData->_lods[lodIndex]._indices.unbind(); PGE_GL_ERROR_CHECK(); // ---------------------------------------- Generate Physics Mesh ---------------------------------------- if (pPhysicsWorld != nullptr && lod == 1) { _physicsWorld = pPhysicsWorld; _pTriangleMesh.reset(new btTriangleMesh()); // Add all vertices for (size_t i = 0; i < indices.size(); i++) { const Vec3f &vertex0 = vertices[indices[i]._i0]._position; const Vec3f &vertex1 = vertices[indices[i]._i1]._position; const Vec3f &vertex2 = vertices[indices[i]._i2]._position; const Vec3f &vertex3 = vertices[indices[i]._i3]._position; const Vec3f &vertex4 = vertices[indices[i]._i4]._position; const Vec3f &vertex5 = vertices[indices[i]._i5]._position; _pTriangleMesh->addTriangle(bt(vertex0), bt(vertex1), bt(vertex2), false); _pTriangleMesh->addTriangle(bt(vertex3), bt(vertex4), bt(vertex5), false); } _pMeshShape.reset(new btBvhTriangleMeshShape(_pTriangleMesh.get(), true, true)); _pMotionState.reset(new btDefaultMotionState(btTransform(btQuaternion(0.0f, 0.0f, 0.0f, 1.0f), btVector3(0.0f, 0.0f, 0.0f)))); btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(0.0f, _pMotionState.get(), _pMeshShape.get(), btVector3(0.0f, 0.0f, 0.0f)); rigidBodyCI.m_restitution = restitution; rigidBodyCI.m_friction = friction; _pRigidBody.reset(new btRigidBody(rigidBodyCI)); pPhysicsWorld->_pDynamicsWorld->addRigidBody(_pRigidBody.get()); } } } void VoxelChunk::deferredRender() { if (_voxelTerrain.isAlive() && !_sharedData->_empty) static_cast<VoxelTerrain*>(_voxelTerrain.get())->_renderChunks.push_back(*this); } VoxelTerrain* VoxelChunk::getTerrain() { assert(_voxelTerrain.isAlive()); return static_cast<VoxelTerrain*>(_voxelTerrain.get()); } void VoxelChunk::updateChunkAABB() { VoxelTerrain* pVoxelTerrain = static_cast<VoxelTerrain*>(_voxelTerrain.get()); _aabb._lowerBound = Vec3f((pVoxelTerrain->getCenter().x + _centerRelativePosition.x) * _chunkSize, (pVoxelTerrain->getCenter().y + _centerRelativePosition.y) * _chunkSize, (pVoxelTerrain->getCenter().z + _centerRelativePosition.z) * _chunkSize) * pVoxelTerrain->_voxelSize; _aabb._upperBound = _aabb._lowerBound + Vec3f(_chunkSize, _chunkSize, _chunkSize) * pVoxelTerrain->_voxelSize; _aabb.calculateHalfDims(); _aabb.calculateCenter(); updateAABB(); } void VoxelChunk::onDestroy() { if (_pRigidBody != nullptr && _physicsWorld.isAlive()) { // Remove body from physics world SceneObjectPhysicsWorld* pPhysicsWorld = static_cast<SceneObjectPhysicsWorld*>(_physicsWorld.get()); pPhysicsWorld->_pDynamicsWorld->removeRigidBody(_pRigidBody.get()); } }
35.950673
161
0.689909
[ "mesh", "vector" ]
e31539db0cad5fb2e3f59617314d31b51ff4d72e
1,234
hpp
C++
src/org/apache/poi/util/TempFile.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/util/TempFile.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/util/TempFile.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/util/TempFile.java #pragma once #include <java/io/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/util/fwd-POI.hpp> #include <java/lang/Object.hpp> struct default_init_tag; class poi::util::TempFile final : public ::java::lang::Object { public: typedef ::java::lang::Object super; private: static TempFileCreationStrategy* strategy_; static ::java::lang::String* JAVA_IO_TMPDIR_; protected: void ctor(); public: static void setTempFileCreationStrategy(TempFileCreationStrategy* strategy); static ::java::io::File* createTempFile(::java::lang::String* prefix, ::java::lang::String* suffix) /* throws(IOException) */; static ::java::io::File* createTempDirectory(::java::lang::String* name) /* throws(IOException) */; // Generated private: TempFile(); protected: TempFile(const ::default_init_tag&); public: static ::java::lang::Class *class_(); static void clinit(); private: static TempFileCreationStrategy*& strategy(); public: static ::java::lang::String*& JAVA_IO_TMPDIR(); private: virtual ::java::lang::Class* getClass0(); friend class TempFile_DefaultTempFileCreationStrategy; };
23.730769
130
0.705024
[ "object" ]
e31efc59d2feb2cd14b6582533b3e1eba18b9e2a
702
cpp
C++
src/parser/Utils.cpp
uchr/DreamfallTLJViewer
857174b278cd7527fd96dd36b2f4169b86ab6626
[ "MIT" ]
null
null
null
src/parser/Utils.cpp
uchr/DreamfallTLJViewer
857174b278cd7527fd96dd36b2f4169b86ab6626
[ "MIT" ]
null
null
null
src/parser/Utils.cpp
uchr/DreamfallTLJViewer
857174b278cd7527fd96dd36b2f4169b86ab6626
[ "MIT" ]
null
null
null
#include "Utils.h" #include <filesystem> #include <sstream> namespace Utils { std::vector<std::string> splitString(const std::string& str, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(str); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } std::string getFilenameWithoutExtension(const std::string& path) { std::filesystem::path temp(path); return temp.filename().replace_extension().string(); } std::string getFilenameWithoutExtension(const std::filesystem::path& path) { return path.filename().replace_extension().string(); } } // namespace Utils
26
78
0.703704
[ "vector" ]
e32016af9d1fa919a3823d83a8fe2b17806d3d62
988
cpp
C++
others/diverta/C.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
1
2021-06-01T17:13:44.000Z
2021-06-01T17:13:44.000Z
others/diverta/C.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
others/diverta/C.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
//#include <cstdio> //#include <cmath> //#include <iostream> //#include <sstream> //#include <string> //#include <vector> //#include <map> //#include <queue> //#include <algorithm> // //#ifdef _DEBUG //#define DMP(x) cerr << #x << ": " << x << "\n" //#else //#define DMP(x) ((void)0) //#endif // //const int MOD = 1000000007, INF = 1111111111; //using namespace std; //typedef long long lint; // //int main() { // // cin.tie(0); // ios::sync_with_stdio(false); // // int N; // cin >> N; // // vector<string> s(N); // for (int i = 0; i < N; i++) cin >> s[i]; // // int alast = 0, bfirst = 0, both = 0,ans = 0; // for (int i = 0; i < N; i++) { // if (s[i][0] == 'B') bfirst++; // if (s[i].back() == 'A') alast++; // if (s[i][0] == 'B'&&s[i].back() == 'A') both++; // for (int j = 1; j < s[i].length(); j++) { // // if (s[i][j] == 'B'&& s[i][j - 1] == 'A') ans++; // } // } // // cout << ans + min(alast, bfirst) + min(0, max(max(alast, bfirst),1) - both - 1); // // return 0; //}
21.478261
83
0.486842
[ "vector" ]
e3285022cfc952a5ef50561d55c6982806735529
3,739
cc
C++
ccc/src/model/ListUnreachableContactsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
3
2020-01-06T08:23:14.000Z
2022-01-22T04:41:35.000Z
ccc/src/model/ListUnreachableContactsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
ccc/src/model/ListUnreachableContactsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ccc/model/ListUnreachableContactsResult.h> #include <json/json.h> using namespace AlibabaCloud::CCC; using namespace AlibabaCloud::CCC::Model; ListUnreachableContactsResult::ListUnreachableContactsResult() : ServiceResult() {} ListUnreachableContactsResult::ListUnreachableContactsResult(const std::string &payload) : ServiceResult() { parse(payload); } ListUnreachableContactsResult::~ListUnreachableContactsResult() {} void ListUnreachableContactsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto unreachableContactsNode = value["UnreachableContacts"]; if(!unreachableContactsNode["TotalCount"].isNull()) unreachableContacts_.totalCount = std::stoi(unreachableContactsNode["TotalCount"].asString()); if(!unreachableContactsNode["PageNumber"].isNull()) unreachableContacts_.pageNumber = std::stoi(unreachableContactsNode["PageNumber"].asString()); if(!unreachableContactsNode["PageSize"].isNull()) unreachableContacts_.pageSize = std::stoi(unreachableContactsNode["PageSize"].asString()); auto allList = value["List"]["UnreachableContact"]; for (auto value : allList) { UnreachableContacts::UnreachableContact unreachableContactObject; if(!value["TotalAttempts"].isNull()) unreachableContactObject.totalAttempts = std::stoi(value["TotalAttempts"].asString()); auto allContacts = value["Contacts"]["Contact"]; for (auto value : allContacts) { UnreachableContacts::UnreachableContact::Contact contactsObject; if(!value["ContactId"].isNull()) contactsObject.contactId = value["ContactId"].asString(); if(!value["ContactName"].isNull()) contactsObject.contactName = value["ContactName"].asString(); if(!value["Role"].isNull()) contactsObject.role = value["Role"].asString(); if(!value["PhoneNumber"].isNull()) contactsObject.phoneNumber = value["PhoneNumber"].asString(); if(!value["State"].isNull()) contactsObject.state = value["State"].asString(); if(!value["ReferenceId"].isNull()) contactsObject.referenceId = value["ReferenceId"].asString(); unreachableContactObject.contacts.push_back(contactsObject); } unreachableContacts_.list.push_back(unreachableContactObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["HttpStatusCode"].isNull()) httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString()); } ListUnreachableContactsResult::UnreachableContacts ListUnreachableContactsResult::getUnreachableContacts()const { return unreachableContacts_; } std::string ListUnreachableContactsResult::getMessage()const { return message_; } int ListUnreachableContactsResult::getHttpStatusCode()const { return httpStatusCode_; } std::string ListUnreachableContactsResult::getCode()const { return code_; } bool ListUnreachableContactsResult::getSuccess()const { return success_; }
33.383929
111
0.755282
[ "model" ]
e32cd1e3ab125e7ccb866fa3d2d4ed440c9a8e51
4,597
cpp
C++
1068/Laboratory_10/Source.cpp
catalinboja/cpp-2021
fbc8147b35bce9d0ea9de7d9b166e1dc3d61d4e7
[ "MIT" ]
null
null
null
1068/Laboratory_10/Source.cpp
catalinboja/cpp-2021
fbc8147b35bce9d0ea9de7d9b166e1dc3d61d4e7
[ "MIT" ]
null
null
null
1068/Laboratory_10/Source.cpp
catalinboja/cpp-2021
fbc8147b35bce9d0ea9de7d9b166e1dc3d61d4e7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; class DailySalesData { string productName = ""; char* productDescription = nullptr; const int barCodeNumber; int* itemsPerDay = nullptr; int noDays = 0; public: //constructor DailySalesData(string name, const char* description, int barCode) : barCodeNumber(barCode), productName(name) { //this->productName = name; //redundant - it will use the default from the definition //this->noDays = 0; //don't do the shallow copy //this->productDescription = description; this->productDescription = new char[strlen(description) + 1]; strcpy_s(this->productDescription, strlen(description) + 1, description); } //default constructor DailySalesData(): barCodeNumber(0) { //we can reuse the default values from the definition //redundant if you have your own defaults in the definition //mandatory if you didn't use default values in the definition //this->noDays = 0; //this->itemsPerDay = nullptr; //this->productDescription = nullptr; } //destructor ~DailySalesData() { cout << endl << "The class destructor"; delete[] this->productDescription; delete[] this->itemsPerDay; } //copy constructor DailySalesData(const DailySalesData& object) :barCodeNumber(object.barCodeNumber) { this->productName = object.productName; //don't do the shallow copy //this->productDescription = object.productDescription; this->productDescription = new char[strlen(object.productDescription) + 1]; strcpy_s(this->productDescription, strlen(object.productDescription) + 1, object.productDescription); this->itemsPerDay = new int[object.noDays]; for (int i = 0; i < object.noDays; i++) { this->itemsPerDay[i] = object.itemsPerDay[i]; } this->noDays = object.noDays; } //operator = DailySalesData operator=(const DailySalesData& source) { //!!!! for operator = that receives source by reference if (this == &source) { //return source; return *this; } //this->barCodeNumber = source.barCodeNumber; if (this->productDescription == source.productDescription) { return source; } delete[] this->productDescription; this->productDescription = new char[strlen(source.productDescription) + 1]; strcpy_s(this->productDescription, strlen(source.productDescription) + 1, source.productDescription); delete[] this->itemsPerDay; this->itemsPerDay = new int[source.noDays]; for (int i = 0; i < source.noDays; i++) { this->itemsPerDay[i] = source.itemsPerDay[i]; } this->productName = source.productName; this->noDays = source.noDays; return source; } explicit operator int() { int total = 0; for (int i = 0; i < this->noDays; i++) { total += this->itemsPerDay[i]; } return total; } int& operator[](int index) { if (index < 0 || index >= this->noDays) { throw exception("Wrong index"); } return this->itemsPerDay[index]; } DailySalesData operator*(int value) { DailySalesData copy = *this; for (int i = 0; i < copy.noDays; i++) { copy.itemsPerDay[i] *= value; } return copy; } int getNoDays() { return this->noDays; } friend DailySalesData operator*(int value, DailySalesData object); friend void print(DailySalesData data); }; DailySalesData operator*(int value, DailySalesData object) { DailySalesData copy = object; for (int i = 0; i < copy.getNoDays(); i++) { copy.itemsPerDay[i] *= value; } return copy; } void print(DailySalesData data) { cout << endl << "Product name " << data.productName; } //operator + //operator * //operator [] //cast operator int main() { DailySalesData laptopData("Laptop", "Gaming laptop with 8 GB of RAM", 224589); DailySalesData pcData("Desktop PC", "Gaming PC with 8 GB of RAM", 224589); DailySalesData smartphoneData("Smartphone", "S20", 123765); DailySalesData* newObject = new DailySalesData("Smartphone", "Some smartphone", 23); delete newObject; DailySalesData* productsData = new DailySalesData[5]; DailySalesData laptopCopy = laptopData; cout << endl << "The end of the example"; smartphoneData = laptopData; //operator=(DailySalesData&, DailySalesData) smartphoneData = laptopData = pcData; smartphoneData = pcData; laptopData = pcData; smartphoneData = smartphoneData; //smartphoneData = smartphoneData + 20; int totalSoldItems = (int)smartphoneData; int firstDaySoldItems = smartphoneData[0]; smartphoneData[0] = 100; //operator*(DailySalesData, int) laptopData = smartphoneData * 2; //we want to multiply the sold items laptopData = 2 * smartphoneData; //operator*(int, DailySalesData) }
24.715054
103
0.703502
[ "object" ]
e332f940e05249eaf92cc58d7e1b350343cb5dd6
28,677
cpp
C++
ext/include/osgEarth/OverlayDecorator.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
6
2015-09-26T15:33:41.000Z
2021-06-13T13:21:50.000Z
ext/include/osgEarth/OverlayDecorator.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
null
null
null
ext/include/osgEarth/OverlayDecorator.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
5
2015-05-04T09:02:23.000Z
2019-06-17T11:34:12.000Z
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2013 Pelican Mapping * http://osgearth.org * * osgEarth 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 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <osgEarth/OverlayDecorator> #include <osgEarth/DrapingTechnique> #include <osgEarth/MapInfo> #include <osgEarth/NodeUtils> #include <osgEarth/Registry> #include <osgEarth/Capabilities> #include <osgEarth/CullingUtils> #include <osg/AutoTransform> #include <osg/ComputeBoundsVisitor> #include <osg/ShapeDrawable> #include <osgShadow/ConvexPolyhedron> #include <osgUtil/LineSegmentIntersector> #include <iomanip> #include <stack> #define LC "[OverlayDecorator] " //#define OE_TEST if (_dumpRequested) OE_INFO << std::setprecision(9) #define OE_TEST OE_NULL using namespace osgEarth; //--------------------------------------------------------------------------- namespace { struct ComputeVisibleBounds : public osg::NodeVisitor { ComputeVisibleBounds(osg::Polytope& tope, osg::Matrix& local2world) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN) { _matrixStack.push(local2world); _topeStack.push(tope); } void apply(osg::Geode& node) { const osg::BoundingSphere& bs = node.getBound(); osg::Vec3 p = bs.center() * _matrixStack.top(); if ( _topeStack.top().contains(p) ) { _bs.expandBy( osg::BoundingSphere(p, bs.radius()) ); } //if ( _topeStack.top().contains(bs) ) //{ // osg::Vec3 p = _matrixStack.top() * bs.center(); // _bs.expandBy( osg::BoundingSphere(p, bs.radius()) ); //} } void apply(osg::Transform& xform) { osg::Matrix m; xform.computeLocalToWorldMatrix(m, this); _matrixStack.push( _matrixStack.top() ); _matrixStack.top().preMult( m ); //_topeStack.push( _topeStack.top() ); //_topeStack.top().transformProvidingInverse(m); traverse(xform); _matrixStack.pop(); //_topeStack.pop(); } std::stack<osg::Matrix> _matrixStack; std::stack<osg::Polytope> _topeStack; osg::BoundingSphere _bs; }; void setFar(osg::Matrix& m, double newFar) { if ( osg::equivalent(m(0,3),0.0) && osg::equivalent(m(1,3),0.0) && osg::equivalent(m(2,3),0.0) ) { double l,r,b,t,n,f; m.getOrtho(l,r,b,t,n,f); m.makeOrtho(l,r,b,t,n,newFar); } else { double v,a,n,f; m.getPerspective(v,a,n,f); m.makePerspective(v,a,n,newFar); } } void clampToNearFar(osg::Matrix& m, double newNear, double newFar) { if ( osg::equivalent(m(0,3),0.0) && osg::equivalent(m(1,3),0.0) && osg::equivalent(m(2,3),0.0) ) { double l,r,b,t,n,f; m.getOrtho(l,r,b,t,n,f); m.makeOrtho(l,r,b,t, std::max(n, newNear), std::min(f,newFar)); } else { double v,a,n,f; m.getPerspective(v,a,n,f); m.makePerspective(v,a, std::max(n, newNear), std::min(f, newFar)); } } /** * Interects a finite ray with a sphere of radius R. The ray is defined * by the X and Y components (in projection aka "clip" space). The function * uses this information to build a ray from Z=-1 to Z=1. * * Places the intersection point(s) in the output vector. */ bool intersectClipRayWithSphere(double clipx, double clipy, const osg::Matrix& clipToWorld, double R, double& inout_maxDist2) { double dist2 = 0.0; osg::Vec3d p0 = osg::Vec3d(clipx, clipy, -1.0) * clipToWorld; // near plane osg::Vec3d p1 = osg::Vec3d(clipx, clipy, 1.0) * clipToWorld; // far plane // http://stackoverflow.com/questions/6533856/ray-sphere-intersection osg::Vec3d d = p1-p0; double A = d * d; double B = 2.0 * (d * p0); double C = (p0 * p0) - R*R; // now solve the quadratic A + B*t + C*t^2 = 0. double D = B*B - 4.0*A*C; if ( D >= 0 ) { if ( osg::equivalent(D, 0.0) ) { // one root (line is tangent to sphere) double t = -B/(2.0*A); if (t >= 0.0) { osg::Vec3d v = d*t; dist2 = v.length2(); } } else { // two roots (line passes through sphere twice) // find the closer of the two. double sqrtD = sqrt(D); double t0 = (-B + sqrtD)/(2.0*A); double t1 = (-B - sqrtD)/(2.0*A); if ( t0 >= 0.0 && t1 >= 0.0 ) { osg::Vec3d v = d*std::min(t0,t1); dist2 = v.length2(); } else if ( t0 >= 0.0 ) { osg::Vec3d v = d*t0; dist2 = v.length2(); } else if ( t1 >= 0.0 ) { osg::Vec3d v = d*t1; dist2 = v.length2(); } } } if ( dist2 > inout_maxDist2 ) { inout_maxDist2 = dist2; return true; } else { // either no intersection, or the distance was not the max. return false; } } /** * Same as above, but intersects the ray with a static 2D plane * (for use in projected map mode) */ void intersectClipRayWithPlane(double clipx, double clipy, const osg::Matrix& clipToWorld, double& inout_maxDist2) { osg::Vec3d p0 = osg::Vec3d(clipx, clipy, -1.0) * clipToWorld; // near plane osg::Vec3d p1 = osg::Vec3d(clipx, clipy, 1.0) * clipToWorld; // far plane // zero-level plane is hard-coded here osg::Vec3d planePoint(0,0,0); osg::Vec3d planeNormal(0,0,1); osg::Vec3d L = p1-p0; L.normalize(); double denom = L * planeNormal; if ( !osg::equivalent(denom, 0.0) ) { double d = ((planePoint - p0) * planeNormal) / denom; if ( d > 0.0 ) inout_maxDist2 = (L*d).length2(); } } /** * Takes a set of world verts and finds their X-Y bounding box in the * plane of the camera represented by the specified view matrix. Also * calculates the maximum distance from the eyepoint to a vertex (3D). */ void getExtentInSilhouette(const osg::Matrix& viewMatrix, const osg::Vec3d& eye, std::vector<osg::Vec3d>& verts, double& xmin, double& ymin, double& xmax, double& ymax, double& maxDistance) { xmin = DBL_MAX, ymin = DBL_MAX, xmax = -DBL_MAX, ymax = -DBL_MAX; double maxDist2 = 0.0; for( std::vector<osg::Vec3d>::iterator i = verts.begin(); i != verts.end(); ++i ) { osg::Vec3d d = (*i) * viewMatrix; // world to view if ( d.x() < xmin ) xmin = d.x(); if ( d.x() > xmax ) xmax = d.x(); if ( d.y() < ymin ) ymin = d.y(); if ( d.y() > ymax ) ymax = d.y(); double dist2 = ((*i)-eye).length2(); if ( dist2 > maxDist2 ) maxDist2 = dist2; } maxDistance = sqrt(maxDist2); } /** * */ void getNearFar(const osg::Matrix& viewMatrix, std::vector<osg::Vec3d>& verts, double& znear, double& zfar) { znear = DBL_MAX, zfar = 0.0; for( std::vector<osg::Vec3d>::iterator i = verts.begin(); i != verts.end(); ++i ) { osg::Vec3d d = (*i) * viewMatrix; // world to view if ( -d.z() < znear ) znear = -d.z(); if ( -d.z() > zfar ) zfar = -d.z(); } } } //--------------------------------------------------------------------------- OverlayDecorator::OverlayDecorator() : _useShaders ( true ), _dumpRequested ( false ), _rttTraversalMask ( ~0 ), _maxHorizonDistance ( DBL_MAX ), _totalOverlayChildren( 0 ) { //nop. } void OverlayDecorator::addTechnique(OverlayTechnique* technique) { if ( _engine.valid() ) { OE_WARN << LC << "Illegal: you cannot install any more techniques once the Decorator " "has been installed by the terrain engine." << std::endl; } else if ( technique ) { if ( technique->supported() ) { _overlayGroups.push_back( new NotifierGroup<OverlayDecorator>(this) ); _techniques.push_back( technique ); } else { // stick unsupported techniques in a temporary holding cell // for reference management -- no harm _unsupportedTechniques.push_back( technique ); } } } void OverlayDecorator::onGroupChanged(osg::Group* group) { // the group changed so we need to give the corresponding // technique a chance to re-establish itself based on the // contents of that group. // update the total child count _totalOverlayChildren = 0; for( unsigned i=0; i<_techniques.size(); ++i ) { //TODO: change to technique->getActive() or something _totalOverlayChildren += _overlayGroups[i]->getNumChildren(); if ( _overlayGroups[i] == group ) { _techniques[i]->reestablish( _engine.get() ); } } } void OverlayDecorator::initializePerViewData( PerViewData& pvd, osg::Camera* cam ) { pvd._camera = cam; pvd._sharedTerrainStateSet = new osg::StateSet(); pvd._techParams.resize( _overlayGroups.size() ); for(unsigned i=0; i<_overlayGroups.size(); ++i ) { TechRTTParams& params = pvd._techParams[i]; params._group = _overlayGroups[i].get(); params._terrainStateSet = pvd._sharedTerrainStateSet.get(); // share it. params._horizonDistance = &pvd._sharedHorizonDistance; // share it. params._terrainParent = this; params._mainCamera = cam; } } void OverlayDecorator::setOverlayGraphTraversalMask( unsigned mask ) { _rttTraversalMask = mask; } void OverlayDecorator::onInstall( TerrainEngineNode* engine ) { _engine = engine; // establish the earth's major axis: MapInfo info(engine->getMap()); _isGeocentric = info.isGeocentric(); _srs = info.getProfile()->getSRS(); _ellipsoid = info.getProfile()->getSRS()->getEllipsoid(); for(Techniques::iterator t = _techniques.begin(); t != _techniques.end(); ++t ) { t->get()->onInstall( engine ); } } void OverlayDecorator::onUninstall( TerrainEngineNode* engine ) { for(Techniques::iterator t = _techniques.begin(); t != _techniques.end(); ++t ) { t->get()->onUninstall( engine ); } _engine = 0L; } void OverlayDecorator::cullTerrainAndCalculateRTTParams(osgUtil::CullVisitor* cv, PerViewData& pvd) { static int s_frame = 1; osg::Vec3d eye = cv->getViewPoint(); double eyeLen; osg::Vec3d worldUp; // Radius at eyepoint (geocentric) double R; // height above sea level double hasl; // weight of the HASL value when calculating extent compensation double haslWeight; // approximate distance to the visible horizon double horizonDistance; OE_TEST << LC << "------- OD CULL ------------------------" << std::endl; if ( _isGeocentric ) { eyeLen = eye.length(); const SpatialReference* geoSRS = _engine->getTerrain()->getSRS(); osg::Vec3d geodetic; geoSRS->transformFromWorld(eye, geodetic); hasl = geodetic.z(); R = eyeLen - hasl; //Actually sample the terrain to get the height and adjust the eye position so it's a tighter fit to the real data. double height; if (_engine->getTerrain()->getHeight(geoSRS, geodetic.x(), geodetic.y(), &height)) // SpatialReference::create("epsg:4326"), osg::RadiansToDegrees( lon ), osg::RadiansToDegrees( lat ), &height)) { geodetic.z() -= height; } hasl = osg::maximum( hasl, 100.0 ); // up vector tangent to the ellipsoid under the eye. worldUp = _ellipsoid->computeLocalUpVector(eye.x(), eye.y(), eye.z()); // radius of the earth under the eyepoint // gw: wrong. use R instead. double radius = eyeLen - hasl; horizonDistance = sqrt( 2.0*radius*hasl + hasl*hasl ); } else // projected map { hasl = eye.z(); hasl = osg::maximum( hasl, 100.0 ); worldUp.set( 0.0, 0.0, 1.0 ); eyeLen = hasl * 2.0; // there "horizon distance" in a projected map is infinity, // so just simulate one. horizonDistance = sqrt(2.0*6356752.3142*hasl + hasl*hasl); } // update the shared horizon distance. pvd._sharedHorizonDistance = horizonDistance; // create a "weighting" that weights HASL against the camera's pitch. osg::Vec3d lookVector = cv->getLookVectorLocal(); haslWeight = osg::absolute(worldUp * lookVector); // unit look-vector of the eye: osg::Vec3d camEye, camTo, camUp; const osg::Matrix& mvMatrix = *cv->getModelViewMatrix(); mvMatrix.getLookAt( camEye, camTo, camUp, 1.0); //eyeLen); osg::Vec3 camLook = camTo-camEye; camLook.normalize(); // Save and reset the current near/far planes before traversing the subgraph. // We do this because we want a projection matrix that includes ONLY the clip // planes from the subgraph, and not anything traversed up to this point. double zSavedNear = cv->getCalculatedNearPlane(); double zSavedFar = cv->getCalculatedFarPlane(); cv->setCalculatedNearPlane( FLT_MAX ); cv->setCalculatedFarPlane( -FLT_MAX ); // cull the subgraph (i.e. the terrain) here. This doubles as the subgraph's official // cull traversal and a gathering of its clip planes. cv->pushStateSet( pvd._sharedTerrainStateSet.get() ); osg::Group::traverse( *cv ); cv->popStateSet(); // Pull a copy of the projection matrix; we will use this to calculate the optimum // projected texture extent osg::Matrixd projMatrix = *cv->getProjectionMatrix(); // Clamp the projection matrix to the newly calculated clip planes. This prevents // any "leakage" from outside the subraph. double zNear = cv->getCalculatedNearPlane(); double zFar = cv->getCalculatedFarPlane(); cv->clampProjectionMatrix( projMatrix, zNear, zFar ); OE_TEST << LC << "Subgraph clamp: zNear = " << zNear << ", zFar = " << zFar << std::endl; // restore the clip planes in the cull visitor, now that we have our subgraph // projection matrix. cv->setCalculatedNearPlane( osg::minimum(zSavedNear, zNear) ); cv->setCalculatedFarPlane( osg::maximum(zSavedFar, zFar) ); // clamp the far plane (for RTT purposes) to the horizon distance. double maxFar = std::min( horizonDistance, _maxHorizonDistance ); cv->clampProjectionMatrix( projMatrix, zNear, maxFar ); // prepare to calculate the ideal far plane for RTT extent resolution. osg::Matrixd MVP = *cv->getModelViewMatrix() * projMatrix; osg::Matrixd inverseMVP; inverseMVP.invert(MVP); double maxDist2 = 0.0; // constrain the far plane. // intersect the top corners of the projection volume since those are the farthest. if ( _isGeocentric ) { intersectClipRayWithSphere( -1.0, 1.0, inverseMVP, R, maxDist2 ); intersectClipRayWithSphere( 1.0, 1.0, inverseMVP, R, maxDist2 ); } else // projected { intersectClipRayWithPlane( -1.0, 1.0, inverseMVP, maxDist2 ); if ( maxDist2 == 0.0 ) intersectClipRayWithPlane( 1.0, 1.0, inverseMVP, maxDist2 ); if ( maxDist2 == 0.0 ) intersectClipRayWithPlane( 0.0, 1.0, inverseMVP, maxDist2 ); } // clamp down the far plane: if ( maxDist2 != 0.0 ) { maxFar = std::min( zNear+sqrt(maxDist2), maxFar ); } // reset the projection matrix if we changed the far: if ( maxFar != zFar ) { setFar( projMatrix, maxFar ); MVP = *cv->getModelViewMatrix() * projMatrix; inverseMVP.invert(MVP); } // calculate the new RTT matrices. All techniques will share the // same set. We could probably put these in the "shared" category // and use pointers..todo. osg::Matrix rttViewMatrix, rttProjMatrix; // for a camera that cares about geometry (like the draping technique) it's important // to include the geometry in the ortho-camera's Z range. But for a camera that just // cares about the terrain depth (like the clamping technique) we want to constrain // the Ortho Z as mush as possible in order to maintain depth precision. Perhaps // later we can split this out and have each technique calculation its own View and // Proj matrix. // For now: our RTT camera z range will be based on this equation: double zspan = std::max(50000.0, hasl+25000.0); osg::Vec3d up = camLook; if ( _isGeocentric ) { osg::Vec3d rttEye = eye+worldUp*zspan; //establish a valid up vector osg::Vec3d rttLook = -rttEye; rttLook.normalize(); if ( fabs(rttLook * camLook) > 0.9999 ) up.set( camUp ); // do NOT look at (0,0,0); must look down the ellipsoid up vector. rttViewMatrix.makeLookAt( rttEye, rttEye-worldUp*zspan, up ); } else { osg::Vec3d rttLook(0, 0, -1); if ( fabs(rttLook * camLook) > 0.9999 ) up.set( camUp ); rttViewMatrix.makeLookAt( camEye + worldUp*zspan, camEye - worldUp*zspan, up ); } // Build a polyhedron for the new frustum so we can slice it. // TODO: do we really even need to slice it anymore? consider osgShadow::ConvexPolyhedron frustumPH; frustumPH.setToUnitFrustum(true, true); frustumPH.transform( inverseMVP, MVP ); // now copy the RTT matrixes over to the techniques. for( unsigned t=0; t<pvd._techParams.size(); ++t ) { TechRTTParams& params = pvd._techParams[t]; // skip empty techniques if ( !_techniques[t]->hasData(params) ) continue; // slice it to fit the overlay geometry. (this says 'visible' but it's just everything.. // perhaps we can truly make it visible) osgShadow::ConvexPolyhedron visiblePH( frustumPH ); #if 0 osg::Polytope frustumPT; frustumPH.getPolytope(frustumPT); ComputeVisibleBounds cvb(frustumPT, MVP); params._group->accept(cvb); const osg::BoundingSphere& visibleOverlayBS = cvb._bs; OE_WARN << "VBS radius = " << visibleOverlayBS.radius() << std::endl; #else const osg::BoundingSphere& visibleOverlayBS = params._group->getBound(); #endif if ( visibleOverlayBS.valid() ) { osg::BoundingBox visibleOverlayBB; visibleOverlayBB.expandBy( visibleOverlayBS ); osg::Polytope visibleOverlayPT; visibleOverlayPT.setToBoundingBox( visibleOverlayBB ); visiblePH.cut( visibleOverlayPT ); } // for dumping, we want the previous fram's projection matrix // becasue the technique itself may have modified it. osg::Matrix prevProjMatrix = params._rttProjMatrix; // extract the verts associated with the frustum's PH: std::vector<osg::Vec3d> verts; visiblePH.getPoints( verts ); // zero verts means the visible PH does not intersect the frustum. // TODO: when verts = 0 should we do something different? or use the previous // frame's view matrix? if ( verts.size() > 0 ) { // calculate an orthographic RTT projection matrix based on the view-space // bounds of the vertex list (i.e. the extents surrounding the RTT camera // that bounds all the polyherdron verts in its XY plane) double xmin, ymin, xmax, ymax, maxDist; getExtentInSilhouette(rttViewMatrix, eye, verts, xmin, ymin, xmax, ymax, maxDist); // make sure the ortho camera penetrates the terrain. This is a must for depth buffer sampling double dist = std::max(hasl*1.5, std::min(maxDist, eyeLen)); // in ecef it can't go past the horizon though, or you get bleed thru if ( _isGeocentric ) dist = std::min(dist, eyeLen); // Even through using xmin and xmax directly results in a tighter fit, // it offsets the eyepoint from the center of the projection frustum. // This causes problems for the draping projection matrix optimizer, so // for now instead of re-doing that code we will just center the eyepoint // here by using the larger of xmin and xmax. -gw. double x = std::max( fabs(xmin), fabs(xmax) ); rttProjMatrix.makeOrtho(-x, x, ymin, ymax, 0.0, dist+zspan); //Note: this was the original setup, which is technically optimal: //rttProjMatrix.makeOrtho(xmin, xmax, ymin, ymax, 0.0, dist+zspan); // Clamp the view frustum's N/F to the visible geometry. This clamped // frustum is the one we'll send to the technique. double visNear, visFar; getNearFar( *cv->getModelViewMatrix(), verts, visNear, visFar ); osg::Matrix clampedProjMat( projMatrix ); clampToNearFar( clampedProjMat, visNear, visFar ); osg::Matrix clampedMVP = *cv->getModelViewMatrix() * clampedProjMat; osg::Matrix inverseClampedMVP; inverseClampedMVP.invert(clampedMVP); osgShadow::ConvexPolyhedron clampedFrustumPH; clampedFrustumPH.setToUnitFrustum(true, true); clampedFrustumPH.transform( inverseClampedMVP, clampedMVP ); // assign the matrices to the technique. params._rttViewMatrix.set( rttViewMatrix ); params._rttProjMatrix.set( rttProjMatrix ); params._eyeWorld = eye; params._visibleFrustumPH = clampedFrustumPH; //frustumPH; } // service a "dump" of the polyhedrons for dubugging purposes // (see osgearth_overlayviewer) if ( _dumpRequested ) { static const char* fn = "convexpolyhedron.osg"; // camera frustum: { frustumPH.dumpGeometry(0,0,0,fn); } osg::Node* camNode = osgDB::readNodeFile(fn); camNode->setName("camera"); // visible overlay Polyherdron AFTER cuting: visiblePH.dumpGeometry(0,0,0,fn,osg::Vec4(1,.5,1,1),osg::Vec4(1,.5,0,.25)); osg::Node* intersection = osgDB::readNodeFile(fn); intersection->setName("intersection"); // RTT frustum: { osgShadow::ConvexPolyhedron rttPH; rttPH.setToUnitFrustum( true, true ); osg::Matrixd MVP = params._rttViewMatrix * prevProjMatrix; //params._rttProjMatrix; osg::Matrixd inverseMVP; inverseMVP.invert(MVP); rttPH.transform( inverseMVP, MVP ); rttPH.dumpGeometry(0,0,0,fn,osg::Vec4(1,1,0,1),osg::Vec4(1,1,0,0.25)); } osg::Node* rttNode = osgDB::readNodeFile(fn); rttNode->setName("rtt"); // EyePoint osg::Geode* dsg = new osg::Geode(); dsg->addDrawable( new osg::ShapeDrawable(new osg::Box(osg::Vec3f(0,0,0), 10.0f))); osg::AutoTransform* dsgmt = new osg::AutoTransform(); dsgmt->setPosition( osg::Vec3d(0,0,0) * osg::Matrix::inverse(*cv->getModelViewMatrix()) ); dsgmt->setAutoScaleToScreen(true); dsgmt->addChild( dsg ); osg::Group* g = new osg::Group(); g->getOrCreateStateSet()->setAttribute(new osg::Program(), 0); g->addChild(camNode); g->addChild(intersection); g->addChild(rttNode); g->addChild(dsgmt); _dump = g; _dumpRequested = false; } } } OverlayDecorator::PerViewData& OverlayDecorator::getPerViewData(osg::Camera* key) { // first check for it: { Threading::ScopedReadLock shared( _perViewDataMutex ); PerViewDataMap::iterator i = _perViewData.find(key); if ( i != _perViewData.end() ) { if ( !i->second._sharedTerrainStateSet.valid() ) { initializePerViewData( i->second, key ); } return i->second; } } // then exclusive lock and make/check it: { Threading::ScopedWriteLock exclusive( _perViewDataMutex ); // double check pattern: PerViewDataMap::iterator i = _perViewData.find(key); if ( i != _perViewData.end() ) return i->second; PerViewData& pvd = _perViewData[key]; initializePerViewData(pvd, key); return pvd; } } void OverlayDecorator::traverse( osg::NodeVisitor& nv ) { bool defaultTraversal = true; // in the CULL traversal, find the per-view data associated with the // cull visitor's current camera view and work with that: if ( nv.getVisitorType() == nv.CULL_VISITOR ) { osgUtil::CullVisitor* cv = Culling::asCullVisitor(nv); osg::Camera* camera = cv->getCurrentCamera(); if ( camera != 0L && (_rttTraversalMask & nv.getTraversalMask()) != 0 ) { // access per-camera data to support multi-threading: PerViewData& pvd = getPerViewData( camera ); // technique-specific setup prior to traversing: bool hasOverlayData = false; for(unsigned i=0; i<_techniques.size(); ++i) { if ( _techniques[i]->hasData(pvd._techParams[i]) ) { hasOverlayData = true; _techniques[i]->preCullTerrain( pvd._techParams[i], cv ); } } if ( hasOverlayData ) { defaultTraversal = false; // shared terrain culling pass: cullTerrainAndCalculateRTTParams( cv, pvd ); // prep and traverse the RTT camera(s): for(unsigned i=0; i<_techniques.size(); ++i) { TechRTTParams& params = pvd._techParams[i]; _techniques[i]->cullOverlayGroup( params, cv ); } } } } else { // Some other type of visitor (like update or intersection). Skip the technique // and traverse the geometry directly. for(unsigned i=0; i<_overlayGroups.size(); ++i) { _overlayGroups[i]->accept( nv ); } } if ( defaultTraversal ) { osg::Group::traverse( nv ); } } double OverlayDecorator::getMaxHorizonDistance() const { return _maxHorizonDistance; } void OverlayDecorator::setMaxHorizonDistance( double horizonDistance ) { _maxHorizonDistance = horizonDistance; }
33.698002
202
0.569864
[ "geometry", "vector", "transform", "3d" ]
e336b7954b3aca95a67f6be8ebd04bdf3667018c
41,483
cpp
C++
hoardingCpp/HousesHotel.cpp
rishabh2d/Monopoly
cd484a71f2dc50b6f088c61e46fc3daf68bf5f0a
[ "MIT" ]
null
null
null
hoardingCpp/HousesHotel.cpp
rishabh2d/Monopoly
cd484a71f2dc50b6f088c61e46fc3daf68bf5f0a
[ "MIT" ]
null
null
null
hoardingCpp/HousesHotel.cpp
rishabh2d/Monopoly
cd484a71f2dc50b6f088c61e46fc3daf68bf5f0a
[ "MIT" ]
null
null
null
// // Created by Rishabh 2 on 2/20/18. // #include <iostream> #include <vector> #include <cmath> #include <memory> #include "SpaceX.h" void Monopoly::GamestateClass::BuyingUpgradeMechanics(Monopoly::BoardClass &board, Monopoly::DiceRollClass *diceRoll, unsigned long chosenPlayer, FILE* RANDOM_FILENAME) { bool upgradeActivated = false; bool playerCanUpgrade2Hotels = false; unsigned long totalProperties = board.getInTotalSpaces(); std::vector<unsigned long> UpgradeableProperties; unsigned long numberOfHouseUpgradesForTheProperty; unsigned long numberOfHotelUpgradesForTheProperty; unsigned long chosenPropertyToUpgrade; unsigned long propertyCounter = 0; unsigned long numProps = 0; for (unsigned long indx = 1; indx < totalProperties; indx++) { if (board.boardSpaces.at(indx)->getSetID() > numProps) { numProps = board.boardSpaces.at(indx)->getSetID(); } } numProps++; std::vector<unsigned long> numPropertiesInSetID(numProps); // Finding number of intrasets in a setID propertyCounter = 0; for (unsigned long i = 0; i < numProps; i++) { for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { propertyCounter++; } } numPropertiesInSetID.at(i) = propertyCounter; propertyCounter = 0; } // Finding the number of properties in a given SETID // that are taken std::vector<bool> propertiesInTheSetIDareTaken(numProps); unsigned long counter = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { // While setID remains same if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer) { counter++; } if (counter == numPropertiesInSetID.at(i)) { propertiesInTheSetIDareTaken.at(i) = true; } } } counter = 0; } // Checking if player can upgrade any of his properties // to houses counter = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { // While setID remains same if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer) { counter++; } if (counter == numPropertiesInSetID.at(i)) { upgradeActivated = true; break; } else { upgradeActivated = false; } } } if (upgradeActivated) { break; } counter = 0; } bool housesMustBeBuiltEvenly = board.rules.getBHE(); int displayedPropertyNo = 0; if (upgradeActivated) { if (housesMustBeBuiltEvenly) { for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { // If the property is taken by the chosen player, // and other properties in the ID are taken by chosen player, // store that property into the vector if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer && propertiesInTheSetIDareTaken.at(i) == true && board.boardSpaces.at(j)->gethotelUpgrades() == 0) { UpgradeableProperties.push_back(j); } } } } if (UpgradeableProperties.empty()) { std::cout << "You don't have any properties that you can upgrade" << std::endl; return; } unsigned long lowest = 100; std::vector<unsigned long> LowestUpgradedHouses; std::vector<unsigned long> lowestInSetID; std::vector<unsigned long> lowestProperties2Display; unsigned long j = 0; // Finding the property with lowest houses // in each setID for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (j = 0; j < UpgradeableProperties.size(); j++) { if (board.boardSpaces.at(UpgradeableProperties.at(j))->getSetID() == i) { if (board.boardSpaces.at(UpgradeableProperties.at(j))->gethouseUpgrades() <= lowest) { lowest = board.boardSpaces.at(UpgradeableProperties.at(j))->gethouseUpgrades(); } } } lowestInSetID.push_back(lowest); lowest = 100; } // then check through the properties // to see if there exist other properties with the lowest upgrades for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (j = 0; j < UpgradeableProperties.size(); j++) { if (board.boardSpaces.at(UpgradeableProperties.at(j))->getSetID() == i) { if (board.boardSpaces.at(UpgradeableProperties.at(j))->gethouseUpgrades() == lowestInSetID.at(i)) { lowestProperties2Display.push_back(board.boardSpaces.at(UpgradeableProperties.at(j))->getNumber()); } } } } unsigned long lowestPropertyNumber; // show only those properties which can be upgraded // i.e (houses with the 'lowest' upgrades in their setID) std::cout << "Which property do you want to upgrade?" << std::endl; for (unsigned long l = 0; l < lowestProperties2Display.size(); l++) { lowestPropertyNumber = lowestProperties2Display.at(l); if (lowestPropertyNumber == 0) { lowestPropertyNumber++; } std::cout << displayedPropertyNo << ". " << board.boardSpaces.at(lowestPropertyNumber)->getName(); // If the number of houses on the property = number of houses that can be built before they are transformed to hotel, if (board.boardSpaces.at(lowestPropertyNumber)->gethouseUpgrades() == board.rules.getNumberOfHouses_BeforeHotels()) { std::cout << " [$" << board.boardSpaces.at(lowestPropertyNumber)->getHotelCost() << "]" << std::endl; } else { std::cout << " [$" << board.boardSpaces.at(lowestPropertyNumber)->getHouseCost() << "]" << std::endl; } displayedPropertyNo++; } std::cout << "Your choice: " << std::endl; std::cin >> chosenPropertyToUpgrade; chosenPropertyToUpgrade = lowestProperties2Display.at(chosenPropertyToUpgrade); } else { // if houses can be built unevenly for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer && propertiesInTheSetIDareTaken.at(i) == true && board.boardSpaces.at(j)->gethotelUpgrades() == 0) { UpgradeableProperties.push_back(j); } } } } if (UpgradeableProperties.empty()) { std::cout << "You don't have any properties that you can upgrade" << std::endl; return; } displayedPropertyNo = 0; // if the player owns all properties in a set id std::cout << "Which property do you want to upgrade?" << std::endl; // Printing the names of the houses which can be upgraded by player for (unsigned long i = 0; i < UpgradeableProperties.size(); i++) { std::cout << displayedPropertyNo << ". " << board.boardSpaces.at(UpgradeableProperties.at(i))->getName() << " "; // if the property has enough houses already, then print hotel cost if (board.boardSpaces.at(UpgradeableProperties.at(i))->gethouseUpgrades() == board.rules.getNumberOfHouses_BeforeHotels()) { std::cout << "[$" << board.boardSpaces.at(UpgradeableProperties.at(i))->getHotelCost() << "]" << std::endl; } else { // else print house cost std::cout << "[$" << board.boardSpaces.at(UpgradeableProperties.at(i))->getHouseCost() << "]" << std::endl; } displayedPropertyNo++; } std::cout << "Your choice: " << std::endl; std::cin >> chosenPropertyToUpgrade; chosenPropertyToUpgrade = UpgradeableProperties.at(chosenPropertyToUpgrade); } // If the house upgrades at the chosen property // is equal to number of houses before hotels rule, // then upgrade rent to hotelRent if (board.boardSpaces.at(chosenPropertyToUpgrade)->gethouseUpgrades() == board.rules.getNumberOfHouses_BeforeHotels()) { playerCanUpgrade2Hotels = true; } if (playerCanUpgrade2Hotels) { // If player has enough money to upgrade to hotel if (board.player.at(chosenPlayer).getMoney() >= (board.boardSpaces.at(chosenPropertyToUpgrade)->getHotelCost())) { // Increase hotel upgrades for the property numberOfHotelUpgradesForTheProperty = board.boardSpaces.at(chosenPropertyToUpgrade)->gethotelUpgrades(); numberOfHotelUpgradesForTheProperty++; board.boardSpaces.at(chosenPropertyToUpgrade)->sethotelUpgrades(numberOfHotelUpgradesForTheProperty); // Decrease the money from player's account with the cost of building hotel unsigned long chosenPlayerMoney = board.player.at(chosenPlayer).getMoney(); chosenPlayerMoney -= board.boardSpaces.at(chosenPropertyToUpgrade)->getHotelCost(); board.player.at(chosenPlayer).setMoney(chosenPlayerMoney); } else { std::cout << "Player, you don't have enough money to upgrade to hotel." << std::endl; } } else { // If player can NOT upgrade to hotels, upgrade to house // if the player has enough money to upgrade that property to a house, if (board.player.at(chosenPlayer).getMoney() >= board.boardSpaces.at(chosenPropertyToUpgrade)->getHouseCost()) { // Increase house upgrades for the property numberOfHouseUpgradesForTheProperty = board.boardSpaces.at(chosenPropertyToUpgrade)->gethouseUpgrades(); numberOfHouseUpgradesForTheProperty++; board.boardSpaces.at(chosenPropertyToUpgrade)->sethouseUpgrades(numberOfHouseUpgradesForTheProperty); // Decrease the money from player's account with the cost of building house unsigned long chosenPlayerMoney = board.player.at(chosenPlayer).getMoney(); chosenPlayerMoney -= board.boardSpaces.at(chosenPropertyToUpgrade)->getHouseCost(); board.player.at(chosenPlayer).setMoney(chosenPlayerMoney); } else { // FIXME - print error message that the player does not have enough money to upgrade to house. std::cout << "You cannot afford to upgrade to house." << std::endl; } } } else { std::cout << "You don't have any properties that you can upgrade" << std::endl; } } void Monopoly::GamestateClass::SellingUpgradeMechanics(Monopoly::BoardClass &board, Monopoly::DiceRollClass *diceRoll, unsigned long chosenPlayer, FILE* RANDOM_FILENAME) { bool DowngradeActivated = false; bool playerCanDowngradeHotels = false; unsigned long totalProperties = board.getInTotalSpaces(); std::vector<unsigned long> DowngradeableProperties; unsigned long chosenPropertyToDowngrade; unsigned long numberOfHouseUpgradesForTheProperty; unsigned long numberOfHotelUpgradesForTheProperty; unsigned long propertyCounter = 0; unsigned long numProps = 0; for (unsigned long indx = 1; indx < totalProperties; indx++) { if (board.boardSpaces.at(indx)->getSetID() > numProps) { numProps = board.boardSpaces.at(indx)->getSetID(); } } numProps++; std::vector<unsigned long> numPropertiesInSetID(numProps); // Finding number of intras in a setID propertyCounter = 0; for (unsigned long i = 0; i < numProps; i++) { for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { propertyCounter++; } } numPropertiesInSetID.at(i) = propertyCounter; propertyCounter = 0; } std::vector<bool> propertiesInTheSetIDareTaken(numProps); unsigned long counter = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer) { counter++; } if (counter == numPropertiesInSetID.at(i)) { propertiesInTheSetIDareTaken.at(i) = true; } } } counter = 0; } counter = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer && ( board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0 ) ) { counter++; } if (counter == 1 // IF any of the houses have even 1 upgrade, it can be downgraded && (board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0) ) { DowngradeActivated = true; break; } if (counter == numPropertiesInSetID.at(i)) { DowngradeActivated = true; break; } else { DowngradeActivated = false; } } } if (DowngradeActivated) { break; } counter = 0; } if (DowngradeActivated) { for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { // If the property is taken by the chosen player, and has upgrades on it > 0 // and all the properties in it's set ID are taken by chosen player // the property can be downgraded if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer && propertiesInTheSetIDareTaken.at(i) == true && (board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0)) { DowngradeableProperties.push_back(j); } } } } } if (DowngradeableProperties.empty()) { std::cout << "You don't have any upgrades that you can sell" << std::endl; return; } bool housesMustBeSoldEvenly = board.rules.getBHE(); if (DowngradeActivated) { if (housesMustBeSoldEvenly) { // in a set id of upgradeable properties, // run through the properties and find the property with lowest upgrades // then check through the properties if there exists other properties with the lowest upgrades // run through the lowest upgraded property-vector and display properties unsigned long highest = 0; std::vector<unsigned long> HighestUpgradedHouses; std::vector<unsigned long> highestInSetID; std::vector<unsigned long> highestProperties2Display; unsigned long j = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (j = 0; j < DowngradeableProperties.size(); j++) { if (board.boardSpaces.at(DowngradeableProperties.at(j))->getSetID() == i) { if (board.boardSpaces.at(DowngradeableProperties.at(j))->gethouseUpgrades() + board.boardSpaces.at(DowngradeableProperties.at(j))->gethotelUpgrades() >= highest) { highest = board.boardSpaces.at(DowngradeableProperties.at(j))->gethouseUpgrades() + board.boardSpaces.at(DowngradeableProperties.at(j))->gethotelUpgrades(); } } } highestInSetID.push_back(highest); highest = 0; } // then check through the properties if there exists // other properties with the lowest upgrades for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (j = 0; j < DowngradeableProperties.size(); j++) { if (board.boardSpaces.at(DowngradeableProperties.at(j))->getSetID() == i) { if (board.boardSpaces.at(DowngradeableProperties.at(j))->gethouseUpgrades() + board.boardSpaces.at(DowngradeableProperties.at(j))->gethotelUpgrades() == highestInSetID.at(i)) { highestProperties2Display.push_back(board.boardSpaces.at(DowngradeableProperties.at(j))->getNumber()); } } } } int displayPropertyNo = 0; unsigned long highestPropertyNumber; // show only those properties which can be upgraded (houses with the 'lowest' upgrades in their setID) std::cout << "Which property do you want to downgrade?" << std::endl; for (unsigned long h = 0; h < highestProperties2Display.size(); h++) { highestPropertyNumber = highestProperties2Display.at(h); if (highestPropertyNumber == 0) { highestPropertyNumber++; } std::cout << displayPropertyNo << ". " << board.boardSpaces.at(highestPropertyNumber)->getName(); // If the number of houses on the property = number of houses that can be built before they are transformed to hotel, if (board.boardSpaces.at(highestPropertyNumber)->gethouseUpgrades() == board.rules.getNumberOfHouses_BeforeHotels()) { std::cout << " [$" << ((board.boardSpaces.at(DowngradeableProperties.at(h))->getHotelCost()) / 2) << "]" << std::endl; } else { std::cout << " [$" << ((board.boardSpaces.at(DowngradeableProperties.at(h))->getHouseCost()) / 2) << "]" << std::endl; } displayPropertyNo++; } std::cout << "Your choice: " << std::endl; std::cin >> chosenPropertyToDowngrade; chosenPropertyToDowngrade = highestProperties2Display.at(chosenPropertyToDowngrade); } else { // If houses can be sold unevenly int displayedPropertyNo = 0; // if the player owns all properties in a set id std::cout << "Which property do you want to downgrade?" << std::endl; // Printing the names of the houses which can be downgraded by player for (unsigned long i = 0; i < DowngradeableProperties.size(); i++) { std::cout << displayedPropertyNo << ". " << board.boardSpaces.at(DowngradeableProperties.at(i))->getName() << " "; // if the property has enough houses already, then print hotel cost if (board.boardSpaces.at(DowngradeableProperties.at(i))->gethouseUpgrades() == board.rules.getNumberOfHouses_BeforeHotels()) { std::cout << "[$" << ((board.boardSpaces.at(DowngradeableProperties.at(i))->getHotelCost()) / 2) << "]" << std::endl; } else { // else print house cost std::cout << "[$" << ((board.boardSpaces.at(DowngradeableProperties.at(i))->getHouseCost()) / 2) << "]" << std::endl; } displayedPropertyNo++; } std::cout << "Your choice: " << std::endl; std::cin >> chosenPropertyToDowngrade; chosenPropertyToDowngrade = DowngradeableProperties.at(chosenPropertyToDowngrade); } if (board.boardSpaces.at(chosenPropertyToDowngrade)->gethotelUpgrades() > 0) { playerCanDowngradeHotels = true; } if (playerCanDowngradeHotels) { // Decrease the number of hotel upgrades for the property numberOfHotelUpgradesForTheProperty = board.boardSpaces.at(chosenPropertyToDowngrade)->gethotelUpgrades(); numberOfHotelUpgradesForTheProperty--; board.boardSpaces.at(chosenPropertyToDowngrade)->sethotelUpgrades(numberOfHotelUpgradesForTheProperty); // Increase the money from player's account with the cost of building hotel divided by 2 unsigned long chosenPlayerMoney = board.player.at(chosenPlayer).getMoney(); chosenPlayerMoney += ((board.boardSpaces.at(chosenPropertyToDowngrade)->getHotelCost()) / 2); board.player.at(chosenPlayer).setMoney(chosenPlayerMoney); } else { // If player can NOT upgrade to hotels, upgrade to house // Decrease house upgrades for the property numberOfHouseUpgradesForTheProperty = board.boardSpaces.at(chosenPropertyToDowngrade)->gethouseUpgrades(); numberOfHouseUpgradesForTheProperty--; board.boardSpaces.at(chosenPropertyToDowngrade)->sethouseUpgrades(numberOfHouseUpgradesForTheProperty); // Increase the money from player's account with the cost of building house divided by 2 unsigned long chosenPlayerMoney = board.player.at(chosenPlayer).getMoney(); chosenPlayerMoney += ((board.boardSpaces.at(chosenPropertyToDowngrade)->getHouseCost()) / 2); board.player.at(chosenPlayer).setMoney(chosenPlayerMoney); } } else { std::cout << "You don't have any upgrades that you can sell" << std::endl; } } bool Monopoly::GamestateClass::SellingUpgradesForRent(Monopoly::BoardClass &board, unsigned long chosenPlayer, unsigned long PositionRent) { bool DowngradeActivated = false; bool playerCanDowngradeHotels = false; unsigned long totalProperties = board.getInTotalSpaces(); std::vector<unsigned long> DowngradeableProperties; unsigned long chosenPropertyToDowngrade; unsigned long numberOfHouseUpgradesForTheProperty; unsigned long numberOfHotelUpgradesForTheProperty; unsigned long propertyCounter = 0; unsigned long numProps = 0; // Storing the number of properties found in one ID // (storing number of intrasetIDs in 1 setID) for (unsigned long indx = 1; indx < totalProperties; indx++) { if (board.boardSpaces.at(indx)->getSetID() > numProps) { numProps = board.boardSpaces.at(indx)->getSetID(); } } numProps++; std::vector<unsigned long> numPropertiesInSetID(numProps); // Finding number of intras in a setID propertyCounter = 0; for (unsigned long i = 0; i < numProps; i++) { for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { propertyCounter++; } } numPropertiesInSetID.at(i) = propertyCounter; propertyCounter = 0; } // This vector checks if all the properties in a setID are taken or not std::vector<bool> propertiesInTheSetIDareTaken(numProps); // Keep selling upgrades while the money is lesser than the rent // If all upgrades sold, return true for bankruptcy int countrix = 0; do { unsigned long counter = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer) { counter++; } if (counter == numPropertiesInSetID.at(i)) { propertiesInTheSetIDareTaken.at(i) = true; } } } counter = 0; } counter = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer && ( board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0 ) ) { counter++; } if (counter == 1 // IF any of the houses have even 1 upgrade, it can be downgraded && ( board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0) ) { DowngradeActivated = true; break; } if (counter == numPropertiesInSetID.at(i)) { DowngradeActivated = true; break; } else { DowngradeActivated = false; } } } if (DowngradeActivated) { break; } counter = 0; } // IF the downgrade has been activated, // then store the properties which can be downgraded... in a vector if (DowngradeActivated) { // Storing the specific properties which the player can downgrade... in a vector if (DowngradeActivated) { for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { // If the property is taken by the chosen player, and has upgrades on it > 0 // and all the properties in it's set ID are taken by chosen player // the property can be downgraded if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer && propertiesInTheSetIDareTaken.at(i) == true && ( board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0) ) { DowngradeableProperties.push_back(j); } } } } } if (DowngradeableProperties.empty()) { return true; } int displayedPropertyNo = 0; if (DowngradeActivated) { if (countrix == 0) { std::cout << "You have " << board.player.at(chosenPlayer).getMoney() << " but you owe " << PositionRent << std::endl; } countrix++; displayedPropertyNo = 0; // if the player owns all properties in a set id std::cout << "Pick an upgrade to sell to make up the difference" << std::endl; // Printing the names of the houses which can be downgraded by player for (unsigned long i = 0; i < DowngradeableProperties.size(); i++) { std::cout << displayedPropertyNo << ". " << board.boardSpaces.at(DowngradeableProperties.at(i))->getName() << " "; // if the property has enough houses already, then print hotel cost if (board.boardSpaces.at(DowngradeableProperties.at(i))->gethouseUpgrades() == board.rules.getNumberOfHouses_BeforeHotels()) { std::cout << "[$" << board.boardSpaces.at(DowngradeableProperties.at(i))->getHotelCost() << "]" << std::endl; } else { // else print house cost std::cout << "[$" << board.boardSpaces.at(DowngradeableProperties.at(i))->getHouseCost() << "]" << std::endl; } displayedPropertyNo++; } } std::cout << "Your choice: " << std::endl; std::cin >> chosenPropertyToDowngrade; chosenPropertyToDowngrade = DowngradeableProperties.at(chosenPropertyToDowngrade); if (board.boardSpaces.at(chosenPropertyToDowngrade)->gethotelUpgrades() > 0) { playerCanDowngradeHotels = true; } if (playerCanDowngradeHotels) { // Decrease the number of hotel upgrades for the property numberOfHotelUpgradesForTheProperty = board.boardSpaces.at(chosenPropertyToDowngrade)->gethotelUpgrades(); numberOfHotelUpgradesForTheProperty--; board.boardSpaces.at(chosenPropertyToDowngrade)->sethotelUpgrades(numberOfHotelUpgradesForTheProperty); // Increase the money from player's account with the cost of building hotel divided by 2 unsigned long chosenPlayerMoney = board.player.at(chosenPlayer).getMoney(); chosenPlayerMoney += ((board.boardSpaces.at(chosenPropertyToDowngrade)->getHotelCost()) / 2); board.player.at(chosenPlayer).setMoney(chosenPlayerMoney); } else { // If player can NOT upgrade to hotels, upgrade to house // Decrease house upgrades for the property numberOfHouseUpgradesForTheProperty = board.boardSpaces.at(chosenPropertyToDowngrade)->gethouseUpgrades(); numberOfHouseUpgradesForTheProperty--; board.boardSpaces.at(chosenPropertyToDowngrade)->sethouseUpgrades(numberOfHouseUpgradesForTheProperty); // Increase the money from player's account with the cost of building house divided by 2 unsigned long chosenPlayerMoney = board.player.at(chosenPlayer).getMoney(); chosenPlayerMoney += ((board.boardSpaces.at(chosenPropertyToDowngrade)->getHouseCost()) / 2); board.player.at(chosenPlayer).setMoney(chosenPlayerMoney); } } else { // If player has no properties to downgrade (downgrade activated == false), then // BANKRUPTCY, so return true. return true; } } while (board.player.at(chosenPlayer).getMoney() < PositionRent || !DowngradeableProperties.empty()); // If the while loop exited because the money was more than rent if (board.player.at(chosenPlayer).getMoney() >= PositionRent) { // Return false for declared bankruptcy return false; } else if (DowngradeableProperties.empty()) { // If the while loop exited because all his properties are sold // and his money is still less than rent return true; } return false; } bool Monopoly::GamestateClass::SellingUpgradesToPayBank(Monopoly::BoardClass &board, unsigned long chosenPlayer, unsigned long PositionRent) { bool DowngradeActivated = false; bool playerCanDowngradeHotels = false; unsigned long totalProperties = board.getInTotalSpaces(); std::vector<unsigned long> DowngradeableProperties; unsigned long chosenPropertyToDowngrade; unsigned long numberOfHouseUpgradesForTheProperty; unsigned long numberOfHotelUpgradesForTheProperty; unsigned long propertyCounter = 0; unsigned long numProps = 0; for (unsigned long indx = 1; indx < totalProperties; indx++) { if (board.boardSpaces.at(indx)->getSetID() > numProps) { numProps = board.boardSpaces.at(indx)->getSetID(); } } numProps++; std::vector<unsigned long> numPropertiesInSetID(numProps); // Finding number of intras in a setID propertyCounter = 0; for (unsigned long i = 0; i < numProps; i++) { for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { propertyCounter++; } } numPropertiesInSetID.at(i) = propertyCounter; propertyCounter = 0; } // This vector checks if all the properties in a setID are taken or not std::vector<bool> propertiesInTheSetIDareTaken(numProps); do { unsigned long counter = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer) { counter++; } if (counter == numPropertiesInSetID.at(i)) { propertiesInTheSetIDareTaken.at(i) = true; } } } counter = 0; } counter = 0; for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer && ( board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0 ) ) { counter++; } if (counter == 1 // IF any of the houses have even 1 upgrade, it can be downgraded && ( board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0) ) { DowngradeActivated = true; break; } if (counter == numPropertiesInSetID.at(i)) { DowngradeActivated = true; break; } else { DowngradeActivated = false; } } } if (DowngradeActivated) { break; } counter = 0; } // IF the downgrade has been activated, // then store the properties which can be downgraded... in a vector if (DowngradeActivated) { // Storing the specific properties which the player can downgrade... in a vector if (DowngradeActivated) { for (unsigned long i = 0; i < numProps; i++) { // number of setIDs for (unsigned long j = 1; j < totalProperties; j++) { if (board.boardSpaces.at(j)->getSetID() == i) { // If the property is taken by the chosen player, and has upgrades on it > 0 // and all the properties in it's set ID are taken by chosen player // the property can be downgraded if (board.boardSpaces.at(j)->getTakenByPlayer() == chosenPlayer && propertiesInTheSetIDareTaken.at(i) == true && ( board.boardSpaces.at(j)->gethouseUpgrades() > 0 || board.boardSpaces.at(j)->gethotelUpgrades() > 0) ) { DowngradeableProperties.push_back(j); } } } } } if (DowngradeableProperties.empty()) { return true; } int displayedPropertyNo = 0; if (DowngradeActivated) { displayedPropertyNo = 0; // if the player owns all properties in a set id std::cout << "Pick an upgrade to sell to make up the difference" << std::endl; // Printing the names of the houses which can be downgraded by player for (unsigned long i = 0; i < DowngradeableProperties.size(); i++) { std::cout << displayedPropertyNo << ". " << board.boardSpaces.at(DowngradeableProperties.at(i))->getName() << " "; // if the property has enough houses already, then print hotel cost if (board.boardSpaces.at(DowngradeableProperties.at(i))->gethouseUpgrades() == board.rules.getNumberOfHouses_BeforeHotels()) { std::cout << "[$" << board.boardSpaces.at(DowngradeableProperties.at(i))->getHotelCost() << "]" << std::endl; } else { // else print house cost std::cout << "[$" << board.boardSpaces.at(DowngradeableProperties.at(i))->getHouseCost() << "]" << std::endl; } displayedPropertyNo++; } } std::cout << "Your choice: " << std::endl; std::cin >> chosenPropertyToDowngrade; chosenPropertyToDowngrade = DowngradeableProperties.at(chosenPropertyToDowngrade); if (board.boardSpaces.at(chosenPropertyToDowngrade)->gethotelUpgrades() > 0) { playerCanDowngradeHotels = true; } if (playerCanDowngradeHotels) { // Decrease the number of hotel upgrades for the property numberOfHotelUpgradesForTheProperty = board.boardSpaces.at(chosenPropertyToDowngrade)->gethotelUpgrades(); numberOfHotelUpgradesForTheProperty--; board.boardSpaces.at(chosenPropertyToDowngrade)->sethotelUpgrades(numberOfHotelUpgradesForTheProperty); // Increase the money from player's account with the cost of building hotel divided by 2 unsigned long chosenPlayerMoney = board.player.at(chosenPlayer).getMoney(); chosenPlayerMoney += ((board.boardSpaces.at(chosenPropertyToDowngrade)->getHotelCost()) / 2); board.player.at(chosenPlayer).setMoney(chosenPlayerMoney); } else { // If player can NOT upgrade to hotels, upgrade to house // Decrease house upgrades for the property numberOfHouseUpgradesForTheProperty = board.boardSpaces.at(chosenPropertyToDowngrade)->gethouseUpgrades(); numberOfHouseUpgradesForTheProperty--; board.boardSpaces.at(chosenPropertyToDowngrade)->sethouseUpgrades(numberOfHouseUpgradesForTheProperty); // Increase the money from player's account with the cost of building house divided by 2 unsigned long chosenPlayerMoney = board.player.at(chosenPlayer).getMoney(); chosenPlayerMoney += ((board.boardSpaces.at(chosenPropertyToDowngrade)->getHouseCost()) / 2); board.player.at(chosenPlayer).setMoney(chosenPlayerMoney); } } else { // If player has no properties to downgrade (downgrade activated == false), // then BANKRUPTCY, so return true. return true; } } while (board.player.at(chosenPlayer).getMoney() < PositionRent || !DowngradeableProperties.empty()); // If the while loop exited because the money was more than rent if (board.player.at(chosenPlayer).getMoney() >= PositionRent) { return false; } else if (DowngradeableProperties.empty()) { // If the while loop exited because all his properties are sold // and his money is still less than rent return true; } return true; }
48.746181
140
0.558325
[ "vector" ]
e33e1b3cc65e5887228a47cc589c67aa3d62ff53
1,745
cpp
C++
configuration/configmgr/configmgrlib/InsertableItem.cpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
configuration/configmgr/configmgrlib/InsertableItem.cpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
configuration/configmgr/configmgrlib/InsertableItem.cpp
cloLN/HPCC-Platform
42ffb763a1cdcf611d3900831973d0a68e722bbe
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2018 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #include "InsertableItem.hpp" #include "EnvironmentNode.hpp" InsertableItem::InsertableItem(std::shared_ptr<const EnvironmentNode> pParentEnvNode, const std::shared_ptr<SchemaItem> &pSchemaItem) : m_pParentEnvNode(pParentEnvNode), m_pSchemaItem(pSchemaItem), m_limitChoices(false) { std::string insertLimitType = m_pSchemaItem->getProperty("insertLimitType"); if (!insertLimitType.empty()) { m_limitChoices = true; if (insertLimitType == "attribute") { std::string attributeName = m_pSchemaItem->getProperty("insertLimitData"); std::shared_ptr<SchemaValue> pSchemaValue = m_pSchemaItem->getAttribute(attributeName); std::vector<AllowedValue> allowedValues; pSchemaValue->getAllowedValues(allowedValues, m_pParentEnvNode); for (auto &av : allowedValues) { m_itemLimits.push_back(InsertItemLimitChoice(av.m_value, attributeName, av.m_value)); } } } }
41.547619
135
0.656734
[ "vector" ]
e34d91f365f5f320e5931358fbc28537119574f3
2,088
cpp
C++
source/de/hackcraft/world/sub/weapon/rWepcom.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
23
2015-12-08T19:29:10.000Z
2021-09-22T04:13:31.000Z
source/de/hackcraft/world/sub/weapon/rWepcom.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
7
2018-04-30T13:05:57.000Z
2021-08-25T03:58:07.000Z
source/de/hackcraft/world/sub/weapon/rWepcom.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
4
2018-01-25T03:05:19.000Z
2021-08-25T03:30:15.000Z
#include "rWepcom.h" #include "de/hackcraft/psi3d/Primitive.h" #include "de/hackcraft/world/sub/weapon/rWeapon.h" std::string rWepcom::cname = "WEPCOM"; unsigned int rWepcom::cid = 4280; rWepcom::rWepcom(Entity* obj) { object = obj; currentWeapon = 0; cycleWeapon = true; singleWeapon = true; trigger = false; } void rWepcom::animate(float spf) { if (!active) return; if (trigger) { trigger = false; fire(); } } void rWepcom::drawHUD() { if (!active) return; float h = 1.0f / 7.0f * (1 + (weapons.size() + 1) / 2); GL::glBegin(GL_QUADS); GL::glVertex3f(1, h, 0); GL::glVertex3f(0, h, 0); GL::glVertex3f(0, 0, 0); GL::glVertex3f(1, 0, 0); GL::glEnd(); GL::glPushMatrix(); { GL::glScalef(1.0f / 2.0f, 1.0f / 7.0f, 1.0f); GL::glTranslatef(0, 0.5, 0); loopi(weapons.size()) { GL::glLineWidth(5); if (weapons[i]->ready()) GL::glColor4f(0.4f, 1.0f, 0.4f, 0.2f); else GL::glColor4f(0.8f, 0.0f, 0.0f, 0.2f); Primitive::glLineSquare(0.1f); GL::glLineWidth(1); GL::glColor4f(1.0f, 1.0f, 1.0f, 0.9f); Primitive::glLineSquare(0.1f); GL::glPushMatrix(); { weapons[i]->drawHUD(); } GL::glPopMatrix(); //GL::glTranslatef(0, 1, 0); if (i & 1) GL::glTranslatef(-1, 1, 0); else GL::glTranslatef(1, 0, 0); } } GL::glPopMatrix(); } void rWepcom::addControlledWeapon(rWeapon* weapon) { weapons.push_back(weapon); } void rWepcom::fire() { if (singleWeapon) { if (weapons.empty()) return; currentWeapon %= weapons.size(); weapons[currentWeapon]->trigger = true; currentWeapon = cycleWeapon ? (currentWeapon + 1) : currentWeapon; currentWeapon %= weapons.size(); } else { int n = weapons.size(); for (int i = 0; i < n; i++) { weapons[i]->trigger = true; } } }
22.212766
75
0.517241
[ "object" ]
e3531112d2e4130ad859bbba417e214e9ad65b13
2,761
cpp
C++
src/graphics.cpp
akitsu-sanae/phylan
bf949de7b5a91dfd965c3fcc4868b76b4b577375
[ "BSL-1.0" ]
null
null
null
src/graphics.cpp
akitsu-sanae/phylan
bf949de7b5a91dfd965c3fcc4868b76b4b577375
[ "BSL-1.0" ]
null
null
null
src/graphics.cpp
akitsu-sanae/phylan
bf949de7b5a91dfd965c3fcc4868b76b4b577375
[ "BSL-1.0" ]
null
null
null
/*============================================================================ Copyright (C) 2016 akitsu sanae https://github.com/akitsu-sanae/phylan Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) ============================================================================*/ #include <vector> #include <array> #include <cmath> #include <GLFW/glfw3.h> #include "graphics.hpp" using Face = ph::graphics::Face; using Color = ph::graphics::Color; static std::vector<Face> create_sphere_faces() { auto mapped_position = [](int x, int y) -> ph::Point { float phi = 2.f * ph::PI<float>() * x / 16.f; float theta = 2.f * ph::PI<float>() * y / 16.f; return ph::Point { std::sinf(theta)*std::cosf(phi), std::sinf(theta)*std::sinf(phi), std::cosf(theta) }; }; std::vector<Face> result; result.reserve(16 * 16 * 2); for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { auto left_top = mapped_position(x, y); auto left_bottom = mapped_position(x, y + 1); auto right_top = mapped_position(x + 1, y); auto right_bottom = mapped_position(x + 1, y + 1); result.emplace_back(left_top, right_top, left_bottom); result.emplace_back(right_bottom, left_bottom, right_top); } } return result; } void ph::graphics::draw_sphere(Point const& pos, Color const& color) { static auto faces = create_sphere_faces(); glPushMatrix(); glTranslated(pos.x, pos.y, pos.z); std::array<GLfloat, 3> v = {{ static_cast<GLfloat>(color.r) / 255.f, static_cast<GLfloat>(color.g) / 255.f, static_cast<GLfloat>(color.b) / 255.f }}; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, v.data()); glBegin(GL_TRIANGLES); for (auto const& face : faces) { for (auto const& node : face.nodes) { glVertex3d(node.x, node.y, node.z); } } glEnd(); glPopMatrix(); } #include <BulletSoftBody/btSoftBody.h> #include <iostream> void ph::graphics::draw_rope(btSoftBody const& body) { if (body.m_faces.size() != 0) { std::cerr << "invalid soft body" << std::endl; std::abort(); } std::array<GLfloat, 3> v = {{ 255, 255, 255}}; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, v.data()); glBegin(GL_LINE_STRIP); for (int i = 0; i < body.m_nodes.size(); i++) { btSoftBody::Node const& node = body.m_nodes.at(i); glVertex3f(node.m_x.x(), node.m_x.y(), node.m_x.z()); } glEnd(); }
34.08642
79
0.545455
[ "vector" ]
e35442033b39e42823c216d4156429bbc55ded25
5,144
cc
C++
src/recon_tests.cc
ezander/dvrlib
3fd26d5fce9e284588c1960cf4e3f7f99d2d44c5
[ "MIT" ]
null
null
null
src/recon_tests.cc
ezander/dvrlib
3fd26d5fce9e284588c1960cf4e3f7f99d2d44c5
[ "MIT" ]
null
null
null
src/recon_tests.cc
ezander/dvrlib
3fd26d5fce9e284588c1960cf4e3f7f99d2d44c5
[ "MIT" ]
null
null
null
#include <cassert> #include <cmath> #include "recon_tests.h" #include "recon.h" #include "gsl_wrapper.h" #include "utils.h" using namespace dvrlib; #define assert_equal(a, b)\ assert((a)==(b)) #define assert_almost_equal(a, b)\ assert(fabs((a)-(b))<1e-7*(fabs(a)+fabs(b))) #define assert_vector_almost_equal_upto(a, b,eps) \ assert(((a)+(-1*(b))).norm2()<(eps)*((a).norm2()+(b).norm2())) #define assert_vector_almost_equal(a, b)\ assert(((a)+(-1*(b))).norm2()<1e-7*((a).norm2()+(b).norm2())) namespace simple_system { // m1-m2=0 // sigma1**2=1, sigma2**2=4 double F[][2] = {{1, -1}}; double S_x_diag[] = {1, 4}; double S_x_inv_diag[] = {1, 0.25}; double x[] = {0, 3}; double v[] = {3.0*1.0/5.0, -3.0*4.0/5.0}; } namespace simple_system2 { // m1-m3=0 // m2-m4=0 // m3-m4=0 // sigma1**2=1, sigma3**2=4 double F[][4] = {{1, 0, -1, 0}, {0, 1, 0, -1}, {0, 0, 1, -1}}; double S_x_diag[] = {1, 4}; double S_x_inv_diag[] = {1, 0.25}; double x[] = {0, 3, 0, 0}; double v[] = {3.0/5.0, -12.0/5.0, 3.0/5.0, 3.0/5.0}; } namespace mischer_teiler { // m1+m2-m5=0 // -m3-m4+m5=0 double F[][5] = {{1, 1, 0, 0, -1}, {0, 0, -1, -1, 1}}; double S_x_diag[] = {0.25, 0.25, 0.25, 0.25}; double S_x_inv_diag[] = {4.0, 4.0, 4.0, 4.0}; double x[] = {98, 99, 100, 100, 0}; double v[] = {0.75, 0.75, -0.75, -0.75, 198.5}; } void test_lin_recon() { { matrix F(2, 5, mischer_teiler::F); matrix S_x(4, 4, true, mischer_teiler::S_x_diag); vector x(5, mischer_teiler::x); vector r=F*x; vector v(5), v_exp(5, mischer_teiler::v); lin_recon(r, S_x, F, v); assert_vector_almost_equal(v, v_exp); matrix S_v(S_x); lin_cov_update(S_x, F, S_v); } { matrix F(1, 2, simple_system::F); matrix S_x(2, 2, true, simple_system::S_x_diag); vector x(2, simple_system::x); vector r=F*x; vector v(2), v_exp(2, simple_system::v); lin_recon(r, S_x, F, v); assert_vector_almost_equal(v, v_exp); } { matrix F(3, 4, simple_system2::F); matrix S_x(2, 2, true, simple_system2::S_x_diag); vector x(4, simple_system2::x); vector r=F*x; vector v(4), v_exp(4, simple_system2::v); lin_recon(r, S_x, F, v); assert_vector_almost_equal(v, v_exp); } } void test_lin_recon_update() { matrix F(2, 5, mischer_teiler::F); matrix S_x_inv(4, 4, true, mischer_teiler::S_x_inv_diag); vector x(5, mischer_teiler::x); vector v(5), dv(5), v_exp(5, mischer_teiler::v); v.set(1, 3); v.set(2, 4); v.set(4, 7); vector r=F*(x+v); lin_recon_update(r, S_x_inv, F, v, dv); assert_vector_almost_equal(v+dv, v_exp); } class EnbiproDummy { public: virtual vector getValues() = 0; virtual matrix getCovarianceMatrix() = 0; virtual matrix getJacobian(const vector& x) = 0; virtual vector getResidual(const vector& x) = 0; }; class LinearEnbiproDummy : public EnbiproDummy { public: vector getValues() { vector x(5, mischer_teiler::x); return x; } matrix getCovarianceMatrix() { matrix S_x(4, 4, true, mischer_teiler::S_x_diag); return S_x; } matrix getJacobian(const vector& x) { matrix F(2, 5, mischer_teiler::F); return F; } vector getResidual(const vector& x) { return getJacobian(x) * x; } }; class QuadraticEnbiproDummy : public EnbiproDummy { public: vector getValues() { vector x(5, mischer_teiler::x); x.set(4, 201); return x; } matrix getCovarianceMatrix() { matrix S_x(4, 4, true, mischer_teiler::S_x_diag); return S_x; } matrix getJacobian(const vector& x) { double d1 = 2*(x.get(0)+x.get(1)-x.get(4)); double d2 = 2*(x.get(2)+x.get(3)-x.get(4)); double J[][5] = {{d1, d1, 0, 0, -d1}, {0, 0, d2, d2, -d2}}; matrix F(2, 5, J); return F; } vector getResidual(const vector& x) { vector r(2); r.set(0, pow( x.get(0)+x.get(1)-x.get(4),2)); r.set(1, pow(-x.get(2)-x.get(3)+x.get(4),2)); return r; } }; class EnbiJacobianFunc : public func<vector,matrix> { EnbiproDummy* enbi; public: EnbiJacobianFunc(EnbiproDummy* _enbi) : enbi(_enbi) {} virtual matrix operator()(const vector& arg); }; matrix EnbiJacobianFunc::operator()(const vector& arg) { return enbi->getJacobian(arg); } class EnbiResidualFunc : public func<vector,vector> { EnbiproDummy* enbi; public: EnbiResidualFunc(EnbiproDummy* _enbi) : enbi(_enbi) {} virtual vector operator()(const vector& arg); }; vector EnbiResidualFunc::operator()(const vector& arg) { return enbi->getResidual(arg); } void test_recon() { //LinearEnbiproDummy enbi_dummy; QuadraticEnbiproDummy enbi_dummy; vector x = enbi_dummy.getValues(); matrix S_x = enbi_dummy.getCovarianceMatrix(); EnbiResidualFunc f(&enbi_dummy); EnbiJacobianFunc J(&enbi_dummy); vector v(x.size()), v_exp(5, mischer_teiler::v);; v_exp.set(4, -2.5); // note that x(4) is different here, thus v(4) also matrix S_v(v.size(), v.size()); recon(x, S_x, f, J, v, S_v); assert(f(x+v).norm2()<1e-6); assert_vector_almost_equal_upto(v, v_exp, 1e-3); } void recon_test_suite() { test_lin_recon_update(); test_lin_recon(); test_recon(); }
23.814815
73
0.619168
[ "vector" ]
e35a9d095b66ea915aeb0b14fa6ecd6b6976442a
19,268
cpp
C++
cpp/nft/src/main.cpp
HunterSun2018/violas-client-sdk
e44b0ecbdcd1096f21ab6f7cc8bd717e10e9fd67
[ "MIT" ]
null
null
null
cpp/nft/src/main.cpp
HunterSun2018/violas-client-sdk
e44b0ecbdcd1096f21ab6f7cc8bd717e10e9fd67
[ "MIT" ]
null
null
null
cpp/nft/src/main.cpp
HunterSun2018/violas-client-sdk
e44b0ecbdcd1096f21ab6f7cc8bd717e10e9fd67
[ "MIT" ]
2
2021-12-28T06:50:27.000Z
2022-02-15T09:28:36.000Z
#include <iostream> #include <map> #include <functional> #include <random> #include <utils.hpp> #include <violas_sdk2.hpp> #include <argument.hpp> #include <bcs_serde.hpp> #include <json_rpc.hpp> #include <console.hpp> #include <ssl_aes.hpp> #include "tea.hpp" using namespace std; using namespace violas; using namespace violas::nft; std::ostream &operator<<(std::ostream &os, const NftInfo &nft_info); std::ostream &operator<<(ostream &os, const vector<MintedEvent> &minted_events); std::ostream &operator<<(ostream &os, const vector<BurnedEvent> &burned_events); std::ostream &operator<<(ostream &os, const vector<nft::SentEvent> &sent_events); std::ostream &operator<<(ostream &os, const vector<nft::ReceivedEvent> &received_events); std::ostream &operator<<(ostream &os, const vector<Tea> &teas); void mint_tea_nft(client_ptr client, Address addr); using handle = function<void(istringstream &params)>; map<string, handle> create_commands(client_ptr client, string url, nft_ptr<Tea> nft); int main(int argc, char *argv[]) { if (argc < 9) { cout << "usage : bin/nft -u url -m mint.key -n mnemonic -w waypoint -c chain_id" << endl; return 0; } try { Arguments args; args.parse_command_line(argc, argv); auto client = Client::create(args.chain_id, args.url, args.mint_key, args.mnemonic, args.waypoint); auto nft = make_shared<NonFungibleToken<Tea>>(client, args.url); cout << "NFT Management 1.0" << endl; client->create_next_account(); //auto admin = client->create_next_account(); //auto dealer1 = client->create_next_account(); //auto dealer2 = client->create_next_account(); // cout << "Admin : " << admin.address << "\n" // << "Dealer 1 : " << dealer1.address << "\n" // << "Dealer 2 : " << dealer2.address << endl; auto console = Console::create("NFT$ "); const string exit = "exit"; console->add_completion(exit); auto commands = create_commands(client, args.url, nft); for (auto cmd : commands) { console->add_completion(cmd.first); } // show all account istringstream iss; commands["list-accounts"](iss); // // Loop to read a line // for (auto line = trim(console->read_line()); line != exit; line = trim(console->read_line())) { istringstream iss(line); string cmd; // Read a command iss >> cmd; auto iter = commands.find(cmd); if (iter != end(commands)) { try { iter->second(iss); } catch (const std::invalid_argument &e) { std::cerr << "Invalid argument : " << e.what() << endl; } catch (runtime_error &e) { std::cerr << color::RED << "Runtime error : " << e.what() << color::RESET << endl; } } console->add_history(line); } } catch (const std::exception &e) { std::cerr << color::RED << "Exceptions : " << e.what() << color::RESET << endl; } return 0; } void check_istream_eof(istream &is, string_view err) { if (is.eof()) { ostringstream oss; oss << err; __throw_invalid_argument(oss.str().c_str()); } } template <typename T> T get_from_stream(istringstream &params, client_ptr client, string_view err_info = "index or address") { Address addr; int account_index = -1; check_istream_eof(params, err_info); string temp; params >> temp; istringstream iss(temp); if (temp.length() == sizeof(T) * 2) { iss >> addr; } else { auto accounts = client->get_all_accounts(); iss >> account_index; if (account_index >= accounts.size()) __throw_invalid_argument("account index is out of account size."); else addr = accounts[account_index].address; } return addr; } map<string, handle> create_commands(client_ptr client, string url, nft_ptr<Tea> nft) { return map<string, handle>{ {"deploy", [=](istringstream &params) { //deploy_stdlib(client); nft->deploy(); }}, {"register", [=](istringstream &params) { check_istream_eof(params, "NFT total number"); uint64_t total = 1000; params >> total; //register_mountwuyi_tea_nft(client, total); nft->register_instance(total); }}, {"accept", [=](istringstream &params) { size_t account_index = 0; params >> account_index; //accept(client, account_index); nft->accept(account_index); }}, {"mint", [=](istringstream &params) { auto addr = get_from_stream<Address>(params, client); mint_tea_nft(client, addr); }}, {"burn", [=](istringstream &params) { TokenId token_id; params >> token_id; //burn_tea_nft(client, token_id); nft->burn(token_id); }}, {"transfer", [=](istringstream &params) { size_t account_index = 0; Address receiver; string metadata; check_istream_eof(params, "usage : transfer account_index account_address token_id_or_index metadata"); params >> account_index; check_istream_eof(params, "receiver address"); receiver = get_from_stream<Address>(params, client); check_istream_eof(params, "index or token id"); string token_id_or_index; params >> token_id_or_index; if (!params.eof()) params >> metadata; if (token_id_or_index.length() == 64) { TokenId token_id; istringstream iss(token_id_or_index); iss >> token_id; nft->transfer_by_token_id(account_index, receiver, token_id, string_to_bytes(metadata)); } else { uint64_t token_index; istringstream iss(token_id_or_index); iss >> token_index; nft->transfer_by_token_index(account_index, receiver, token_index, string_to_bytes(metadata)); } }}, {"balance", [=](istringstream &params) { auto addr = get_from_stream<Address>(params, client); auto opt_balance = nft->balance(addr); if (opt_balance) { // int i = 0; // for (const auto &tea : *opt_balance) // { // cout << i++ << " - " << tea << endl; // } cout << *opt_balance; } }}, {"owner", [=](istringstream &params) { TokenId id; params >> id; auto owner = nft->get_owner(url, id); if (owner != nullopt) { // print the address of owner cout << *owner << endl; } else cout << "cannot find owner." << endl; }}, {"trace", [=](istringstream &params) { TokenId token_id; check_istream_eof(params, "token id"); params >> token_id; auto receiver = nft->get_owner(url, token_id); if (receiver != nullopt) { size_t i = 0; // for (const auto receiver : *receivers) // { // cout << i++ << " - " << receiver << endl; // } } }}, {"info", [=](istringstream &params) { auto opt_info = nft->get_nft_info(url); if (opt_info != nullopt) cout << *opt_info << endl; }}, {"create_child_account", [=](istringstream &params) { Address addr; AuthenticationKey auth_key; check_istream_eof(params, "authentication key"); params >> auth_key; copy(begin(auth_key) + 16, begin(auth_key) + 32, begin(addr)); client->create_child_vasp_account("VLS", 0, addr, auth_key, true, 0, true); }}, {"add-account", [=](istringstream &params) { client->create_next_account(); }}, {"list-accounts", [=](istringstream &params) { auto accounts = client->get_all_accounts(); cout << color::CYAN << left << setw(10) << "index" << left << setw(40) << "Address" << left << setw(40) << "Authentication key" << color::RESET << endl; int i = 0; for (auto &account : accounts) { cout << left << setw(10) << i++ << left << setw(40) << account.address << left << setw(40) << account.auth_key << endl; } }}, {"query-events", [=](istringstream &params) { string event_type; check_istream_eof(params, "(usage) : query_event [minted, burned, sent, received] address start limit"); params >> event_type; auto addr = get_from_stream<Address>(params, client); uint64_t start = 0, limit = 10; if (!params.eof()) params >> start; if (!params.eof()) params >> limit; if (event_type == "minted") { auto opt_event_handle = nft->get_event_handle(EventType::minted, addr); if (opt_event_handle == nullopt) __throw_runtime_error("event handle doesn't exist."); auto events = nft->query_events<MintedEvent>(*opt_event_handle, addr, start, limit); cout << color::CYAN << "Minted events list (" << opt_event_handle->counter << ")" << color::RESET << endl; cout << events << endl; } else if (event_type == "burned") { auto opt_event_handle = nft->get_event_handle(EventType::burned, addr); if (opt_event_handle == nullopt) __throw_runtime_error("event handle doesn't exist."); auto events = nft->query_events<BurnedEvent>(*opt_event_handle, addr, start, limit); cout << color::CYAN << "Burned events list (" << opt_event_handle->counter << ")" << color::RESET << endl; cout << events << endl; } else if (event_type == "sent") { auto opt_event_handle = nft->get_event_handle(EventType::sent, addr); if (opt_event_handle == nullopt) __throw_runtime_error("event handle doesn't exist."); auto events = nft->query_events<SentEvent>(*opt_event_handle, addr, start, limit); cout << color::CYAN << "Sent events list (" << opt_event_handle->counter << ")" << color::RESET << endl; cout << events << endl; } else if (event_type == "received") { auto opt_event_handle = nft->get_event_handle(EventType::received, addr); if (opt_event_handle == nullopt) __throw_runtime_error("event handle doesn't exist."); auto events = nft->query_events<ReceivedEvent>(*opt_event_handle, addr, start, limit); cout << color::CYAN << "Received events list (" << opt_event_handle->counter << ")" << color::RESET << endl; cout << events << endl; } else { __throw_invalid_argument("event type is invalid, please input [minted, burned, sent, received]"); } // for (auto &event : events) // { // //cout << event << endl; // } }}, }; } void mint_tea_nft(client_ptr client, Address addr) { cout << "minting Tea NFT ... " << endl; auto accounts = client->get_all_accounts(); auto &admin = accounts[0]; default_random_engine e(clock()); uniform_int_distribution<unsigned> u(0, 25); size_t kind = 0; cout << "input kind(0, 1, 2, 3, 4, default is 0) :"; input(kind); string PA = "MountWuyi City"; cout << "input production area (default is '" << PA << "') : "; input(PA); string manufacturer = "21VNET Tea"; cout << "input manufacturer (default is '" << manufacturer << "') : "; input(manufacturer); string SN = {'1', '2', '3', '4', '5', '6', char('a' + u(e)), char('a' + u(e))}; cout << "input sequence number (default is '" << SN << "') : "; input(SN); string url = "https://www.mountwuyitea.com"; cout << "input a url (default is '" << url << "' : "; input(url); time_t now = time(nullptr); cout << "input production date (default is '" << put_time(localtime(&now), "%F") << "') : "; if (cin.get() != '\n') { cin.unget(); //cout << "local = " << std::locale("").name() << endl; std::tm t = {}; cin.imbue(locale("zh_CN.UTF-8")); cin >> std::get_time(&t, "%Y-%m-%d"); if (cin.fail()) cout << "The date format is error, use default date " << put_time(localtime(&now), "%F") << "." << endl; else { now = mktime(&t); } cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } // Keep date and remove time std::tm *t = localtime(&now); t->tm_hour = t->tm_min = t->tm_sec = 0; now = mktime(t); client->execute_script_file(admin.index, "move/tea/scripts/mint_mountwuyi_tea_nft.mv", {}, { uint8_t(kind), string_to_bytes(manufacturer), string_to_bytes(PA), uint64_t(now), string_to_bytes(SN), string_to_bytes(url), addr, }); cout << "Minted a Tea NFT to address " << addr << endl; } std::ostream &operator<<(std::ostream &os, const nft::NftInfo &nft_info) { os << "NonFungibleToken Info { \n" << "\t" << "total : " << nft_info.total << "\n" << "\t" << "amount : " << nft_info.amount << "\n" << "\t" << "admin address: " << nft_info.admin << "\n" << "\t" << "minted amount : " << nft_info.mint_event.counter << "\n" << "\t" << "burned amount : " << nft_info.burn_event.counter << "\n" << "}"; return os; } std::ostream &operator<<(ostream &os, const vector<nft::MintedEvent> &minted_events) { cout << color::YELLOW << left << setw(10) << "SN" << left << setw(70) << "Token ID" << left << setw(40) << "Receiver Address" << left << setw(10) << "Version" << color::RESET << endl; for (auto &e : minted_events) { cout << left << setw(10) << e.sequence_number << left << setw(70) << e.token_id << left << setw(40) << e.receiver << left << setw(10) << e.transaction_version << endl; } return os; } std::ostream &operator<<(ostream &os, const vector<nft::BurnedEvent> &burnedevents) { cout << color::YELLOW << color::CYAN << left << setw(10) << "SN" << left << setw(70) << "Token ID" << left << setw(10) << "Version" << color::RESET << endl; for (auto &e : burnedevents) { cout << left << setw(10) << e.sequence_number << left << setw(70) << e.token_id << left << setw(10) << e.transaction_version << endl; } return os; } std::ostream &operator<<(ostream &os, const vector<nft::SentEvent> &sent_events) { cout << color::YELLOW << left << setw(10) << "SN" << left << setw(70) << "Token ID" << left << setw(40) << "Payee" << left << setw(20) << "Metadata" << left << setw(10) << "Version" << color::RESET << endl; for (auto &e : sent_events) { cout << left << setw(10) << e.sequence_number << left << setw(70) << e.token_id << left << setw(40) << e.payee << left << setw(20) << bytes_to_hex(e.metadata) << left << setw(10) << e.transaction_version << endl; } return os; } std::ostream &operator<<(ostream &os, const vector<nft::ReceivedEvent> &received_events) { cout << color::YELLOW << left << setw(10) << "SN" << left << setw(70) << "Token ID" << left << setw(40) << "Payer" << left << setw(20) << "Metadata" << left << setw(10) << "Version" << color::RESET << endl; for (auto &e : received_events) { cout << left << setw(10) << e.sequence_number << left << setw(70) << e.token_id << left << setw(40) << e.payer << left << setw(20) << bytes_to_hex(e.metadata) << left << setw(10) << e.transaction_version << endl; } return os; } std::ostream &operator<<(ostream &os, const vector<Tea> &teas) { cout << color::YELLOW << left << setw(8) << "index" << left << setw(8) << "kind" //<< left << setw(20) << "Manufacture" << left << setw(20) << "Production Area" << left << setw(20) << "Production Date" << left << setw(10) << "SN" << left << setw(30) << "URL" << left << setw(70) << "Token ID" << color::RESET << endl; size_t index = 0; for (auto &tea : teas) { ostringstream oss; oss << std::put_time(std::localtime((time_t *)&tea.PD), "%F"); cout << left << setw(8) << index++ << left << setw(8) << short(tea.kind) //<< left << setw(20) << bytes_to_hex(tea.manufacture) << left << setw(20) << string(begin(tea.PA), end(tea.PA)) << left << setw(20) << oss.str() << left << setw(10) << string(begin(tea.SN), end(tea.SN)) << left << setw(30) << string(begin(tea.url), end(tea.url)) << left << setw(70) << violas::nft::compute_token_id(tea) << endl; } return os; }
31.4323
125
0.486766
[ "vector" ]
e35fd5e9d9043ae9747fb49d855033ad04c63c71
3,344
cpp
C++
bytesteady/flags.cpp
ElementAI/bytesteady
737cfc4a5fc0f0ad783ccc70b73200b5e3cef06f
[ "Apache-2.0" ]
3
2021-11-08T19:18:32.000Z
2022-03-06T06:09:58.000Z
bytesteady/flags.cpp
ElementAI/bytesteady
737cfc4a5fc0f0ad783ccc70b73200b5e3cef06f
[ "Apache-2.0" ]
null
null
null
bytesteady/flags.cpp
ElementAI/bytesteady
737cfc4a5fc0f0ad783ccc70b73200b5e3cef06f
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 ServiceNow * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "bytesteady/flags.hpp" #include "gflags/gflags.h" DEFINE_string(data_file, "bytesteady/unittest_train.txt", "data input file name"); DEFINE_string(data_format, "kBytes,kIndex", "a comma-separated list of kBytes" " or kIndex representing field types"); DEFINE_string(model_input_size, "16,16", "a comma-seperated list of numbers" " representing input embedding size"); DEFINE_uint64(model_output_size, 4, "output embedding size"); DEFINE_uint64(model_dimension, 4, "embedding dimension"); DEFINE_string(model_gram, "{1,2,4,8},{}", "list of grams for each field"); DEFINE_uint64(model_seed, 1946, "hashing seed"); DEFINE_double(model_mu, 0.0, "mean of the Gaussian distribution used to" " initialize parameters"); DEFINE_double(model_sigma, 1.0, "standard deviation of the Gaussian" " distribution used to initialize parameters"); DEFINE_double(train_a, 0.1, "initial learning rate"); DEFINE_double(train_b, 0.0, "eventual learning rate"); DEFINE_double(train_alpha, 0.0, "learning rate change factor"); DEFINE_double(train_lambda, 0.0, "weight decay"); DEFINE_uint64(train_n, 0, "number of universum samples for every data sample"); DEFINE_double(train_rho, 1.0, "universum learning rate factor"); DEFINE_uint64(train_thread_size, 4, "number of threads for training"); DEFINE_uint64(test_label_size, 3, "size of label to consider during" " testing"); DEFINE_uint64(test_thread_size, 1, "number of threads for testing"); DEFINE_string(infer_file, "bytesteady/unittest_result.txt", "inference result file"); DEFINE_uint64(infer_label_size, 3, "size of label to consider during" " inference"); DEFINE_uint64(driver_epoch_size, 1, "number of epoches for training"); DEFINE_string(driver_location, "", "location to store model checkpoint"); DEFINE_uint64(driver_save, 0, "epoch interval to save the model, 0 to disable"); DEFINE_bool(driver_resume, false, "whether to resume training"); DEFINE_bool(driver_debug, false, "whether to log in verbose mode for debugging"); DEFINE_double(driver_log_interval, 5.0, "time interval for logging"); DEFINE_int64(driver_log_precision, 4, "numerical precision for logging"); DEFINE_double(driver_checkpoint_interval, 3600.0, "time interval for checkpointing"); DEFINE_string( driver_model, "model.tdb", "testing or inference model file relative to checkpoint location"); DEFINE_string(joe_task, "train", "task to run, can be train, test or infer"); DEFINE_string(joe_tensor, "double", "type of tensor, can be double or float"); DEFINE_string(joe_hash, "fnv", "type of hash, can be fnv or city"); DEFINE_string(joe_loss, "nll", "type of loss, can be nll or hinge");
48.463768
80
0.738636
[ "model" ]
e36d87c438141fbed870d9a804f58b81e88d8448
3,195
hpp
C++
include/image_processor.hpp
naibaf7/caffe_neural_tool
95190e2b2f0a6f6dd0ac47c5e661079e19d56dd3
[ "BSD-2-Clause" ]
20
2015-06-11T07:48:21.000Z
2020-12-27T17:20:42.000Z
include/image_processor.hpp
naibaf7/caffe_neural_tool
95190e2b2f0a6f6dd0ac47c5e661079e19d56dd3
[ "BSD-2-Clause" ]
3
2015-07-17T07:36:12.000Z
2016-04-28T00:16:16.000Z
include/image_processor.hpp
naibaf7/caffe_neural_tool
95190e2b2f0a6f6dd0ac47c5e661079e19d56dd3
[ "BSD-2-Clause" ]
15
2015-07-08T18:53:52.000Z
2019-12-02T16:45:23.000Z
/* * image_preprocessor.hpp * * Created on: Apr 3, 2015 * Author: Fabian Tschopp */ #ifndef IMAGE_PROCESSOR_HPP_ #define IMAGE_PROCESSOR_HPP_ #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <functional> namespace caffe_neural { class ImageProcessor { public: ImageProcessor(int patch_size, int nr_labels); void SubmitRawImage(cv::Mat input, int img_id); void ClearImages(); void SubmitImage(cv::Mat raw, int img_id, std::vector<cv::Mat> labels); int Init(); void SetBorderParams(bool apply, int border_size); void SetClaheParams(bool apply, float clip_limit); void SetBlurParams(bool apply, float mu, float std, int blur_size); void SetCropParams(int image_crop, int label_crop); void SetNormalizationParams(bool apply); void SetRotationParams(bool apply); void SetPatchMirrorParams(bool apply); void SetLabelHistEqParams(bool apply, bool patch_prior, bool mask_prob, std::vector<float> label_boost); long BinarySearchPatch(double offset); void SetLabelConsolidateParams(bool apply, std::vector<int> labels); std::vector<cv::Mat>& raw_images(); std::vector<cv::Mat>& label_images(); std::vector<int>& image_number(); protected: std::vector<cv::Mat> raw_images_; std::vector<cv::Mat> label_images_; std::vector<std::vector<cv::Mat>> label_stack_; std::vector<int> image_number_; // General parameters int image_size_x_; int image_size_y_; int patch_size_; int nr_labels_; std::function<double()> offset_selector_; // Normalization parameters bool apply_normalization_ = false; // Final crop subtraction parameters int image_crop_ = 0; int label_crop_ = 0; // Border parameters bool apply_border_reflect_ = false; int border_size_; // CLAHE parameters bool apply_clahe_ = false; cv::Ptr<cv::CLAHE> clahe_; // Blur parameters bool apply_blur_ = false; float blur_mean_; float blur_std_; int blur_size_; std::function<float()> blur_random_selector_; // Simple rotation parameters bool apply_rotation_ = false; std::function<unsigned int()> rotation_rand_; // Patch mirroring bool apply_patch_mirroring_ = false; std::function<unsigned int()> patch_mirror_rand_; // Label histrogram equalization bool apply_label_hist_eq_ = false; bool apply_label_patch_prior_ = false; bool apply_label_pixel_mask_ = false; std::vector<double> label_running_probability_; std::vector<float> label_mask_probability_; std::vector<std::function<float()>> label_mask_prob_rand_; std::function<double()> label_patch_prior_rand_; std::vector<float> label_boost_; // Label consolidation bool label_consolidate_ = false; std::vector<int> label_consolidate_labels_; // Patch sequence index int sequence_index_; }; class ProcessImageProcessor : public ImageProcessor { public: ProcessImageProcessor(int patch_size, int nr_labels); protected: }; class TrainImageProcessor : public ImageProcessor { public: TrainImageProcessor(int patch_size, int nr_labels); std::vector<cv::Mat> DrawPatchRandom(); protected: }; } #endif /* IMAGE_PROCESSOR_HPP_ */
25.97561
73
0.741158
[ "vector" ]
e371fbf8762c45c3ac9a36fbd5674a9ec923c2ab
572
cc
C++
cpp/hackranker/h32.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/hackranker/h32.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/hackranker/h32.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
/* * */ #include <iostream> #include <vector> #include <string> #include <algorithm> #include <iomanip> #include <cstdlib> #include <cstdio> #include <map> #include <set> #include <deque> #include <queue> using namespace std; int beautifulPairs(vector<int> A, vector<int> B) { map<int, int> b; int cnt = 0; for (auto i : B) { b[i] += 1; } for (auto i : A) { if (b[i] > 0) { b[i] -= 1; cnt += 1; } } return cnt == A.size() ? cnt : cnt + 1; } int main() { int k = beautifulPairs({ 3,5,7,11,5,8}, { 5,7,11,10,5,8 }); cout << k << endl; return 0; }
15.052632
60
0.564685
[ "vector" ]
e373f1eb86cfb48efb8e093372b015905df3dff0
2,828
cpp
C++
src/semi.cpp
SubbulakshmiRS/Jetpack-Joyride
0d7178e16936f719d5753452ffdc50b6bb8d1cf7
[ "MIT" ]
null
null
null
src/semi.cpp
SubbulakshmiRS/Jetpack-Joyride
0d7178e16936f719d5753452ffdc50b6bb8d1cf7
[ "MIT" ]
null
null
null
src/semi.cpp
SubbulakshmiRS/Jetpack-Joyride
0d7178e16936f719d5753452ffdc50b6bb8d1cf7
[ "MIT" ]
null
null
null
#include "semi.h" #include "main.h" Semi::Semi(int scene) { float x =6.0f,y=0.5f ; float rotation =0; this->position = glm::vec3(x, y, 0); speed = 0.05; // Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. // A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices GLfloat vertex_buffer_data[18*180]; float start_x=-2.0f,start_y=0; float start_inner_x=-1.8f,start_inner_y=0; float angle = 1.0f; float c,s; for(int i=0;i<180;i++) { vertex_buffer_data[18*i] = start_inner_x; vertex_buffer_data[18*i+1] = start_inner_y; vertex_buffer_data[18*i+2] = 0; vertex_buffer_data[18*i+3] = start_x; vertex_buffer_data[18*i+4] = start_y; vertex_buffer_data[18*i+5] = 0; vertex_buffer_data[18*i+9] = start_inner_x; vertex_buffer_data[18*i+10] = start_inner_y; vertex_buffer_data[18*i+11] = 0; c=cos(((i+1)*angle*M_PI)/180); s=sin(((i+1)*angle*M_PI)/180); start_inner_x = (-1.8f)*c; start_x = (-2.0f)*c; start_y = (-2.0f)*s; start_inner_y = (-1.8f)*s; vertex_buffer_data[18*i+6] = start_x; vertex_buffer_data[18*i+7] = start_y; vertex_buffer_data[18*i+8] = 0; vertex_buffer_data[18*i+12] = start_x; vertex_buffer_data[18*i+13] = start_y; vertex_buffer_data[18*i+14] = 0; vertex_buffer_data[18*i+15] = start_inner_x; vertex_buffer_data[18*i+16] = start_inner_y; vertex_buffer_data[18*i+17] = 0; } this->object = create3DObject(GL_TRIANGLES, 6*180, vertex_buffer_data, COLOR_BLUE, GL_FILL); } void Semi::draw(glm::mat4 VP) { Matrices.model = glm::mat4(0.5f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1)); // No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate // rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object); } void Semi::set_position(float x, float y) { this->position = glm::vec3(x, y, 0); } void Semi::tick(int type) { // type is to differentiate between the different directions of the 2 balls this->rotation += type; //this->position.x -= type*speed; //this->position.y -= type*speed; } int Semi::move(float x , float y){ this->position.x += x; this->position.y += y; // check if the item is within the boundaries of the screen ( += 10 all sides) return 0; }
32.136364
107
0.617751
[ "object", "model", "3d" ]
e3745e3cad0e66a311e79f3536f6e9be81029259
18,762
cpp
C++
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/uce/dirtyregion.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
5,937
2018-12-04T16:32:50.000Z
2022-03-31T09:48:37.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/uce/dirtyregion.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
4,151
2018-12-04T16:38:19.000Z
2022-03-31T18:41:14.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/uce/dirtyregion.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
1,084
2018-12-04T16:24:21.000Z
2022-03-30T13:52:03.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //----------------------------------------------------------------------------- // // // Description: // Dirty region management class. // #include "precomp.hpp" // Meters ---------------------------------------------------------------------- MtDefine(CDirtyRegion2, Mem, "DirtyRegion"); // ----------------------------------------------------------------------------- // Helpers // // GSchneid: Some helper functions that should really go away when we get one // _the_ one set of primitive types. float RectArea(__in_ecount(1) const MilRectF* pR) { return ((pR->right - pR->left) * (pR->bottom - pR->top)); }; //+----------------------------------------------------------------------------- // Dirty region statistics //------------------------------------------------------------------------------ CPerformanceCounter g_addedRectStatistics(1000); CPerformanceCounter* CDirtyRegion2::g_pAddedRectStatistics = &g_addedRectStatistics; //+----------------------------------------------------------------------------- // CPerformanceCounter::UpdatePerFrameStatistics // // Description: // Tracks per frame statistics. //------------------------------------------------------------------------------ /*static*/ void CDirtyRegion2::UpdatePerFrameStatistics() { if (g_pMediaControl) { CMediaControlFile* pFile = g_pMediaControl->GetDataPtr(); pFile->DirtyRectAddRate = g_pAddedRectStatistics->GetCurrentRate(); } } //+----------------------------------------------------------------------------- // // Name: // // InflateRectFInPlace // // Description: // // Inflates a rectangle IN PLACE. Used to mark things as dirty on the boundary // so that anti aliasing works correctly. Also used to expand for glass blur radius // // How much do we need to inflate: // // '>' is the right edge of the left shape ':' indicates the antialiasing // edge right of the left shape. // '<' is the left edge of the right shape. Its anti-aliasing edge is ':' // left of it. // | indicate the pixel boundaries. // We need to inflate the shapes enough for the intersection tests that iff the // shapes rasterized representation influences the color of a pixel the // intersection test needs to return TRUE. // // The following example shows that two shapes can influence the same pixel but // might not geometrically overlap. // // > |: :| < | // // Assuming that the distance between shape edge and anti-aliasing edge is less // then a pixel width then extending by the width of a pixel ensures that the // intersection test identifies overlapping when the two shapes influence the same // pixel. // // Note that this only works if rectangles are axis aligned. Otherwise the offset // needs to be sqrt(2). // // pRect - non empty rectangle // margin - size to inflate, >= 0 // //------------------------------------------------------------------------------ void InflateRectF_InPlace(__inout_ecount(1) CMilRectF* pRect, float margin) { pRect->Inflate(margin, margin); pRect->left = CFloatFPU::FloorF(pRect->left); pRect->top = CFloatFPU::FloorF(pRect->top); pRect->right = CFloatFPU::CeilingF(pRect->right); pRect->bottom = CFloatFPU::CeilingF(pRect->bottom); } void InflateRectF_InPlace(__inout_ecount(1) CMilRectF* pRect) { InflateRectF_InPlace(pRect, 1.0f); } //+----------------------------------------------------------------------------- // CDirtyRegion2::ctor //------------------------------------------------------------------------------ CDirtyRegion2::CDirtyRegion2() { // Initialize linked lists. for (UINT i = 0; i < MaxDirtyRegionCount; i++) { InitializeListHead(&(m_dirtyRegionLists[i])); } m_fMaxSurfaceFallback = false; } //+----------------------------------------------------------------------------- // CDirtyRegion2::dtor //------------------------------------------------------------------------------ CDirtyRegion2::~CDirtyRegion2() { } //+----------------------------------------------------------------------------- // CDirtyRegion2::IsEmpty //------------------------------------------------------------------------------ bool CDirtyRegion2::IsEmpty() const { bool fIsEmpty = true; for (UINT i = 0; i < MaxDirtyRegionCount; i++) { if (!m_dirtyRegions[i].IsEmpty()) { fIsEmpty = false; break; } } return fIsEmpty; } //+----------------------------------------------------------------------------- // CDirtyRegion2::Initialize //------------------------------------------------------------------------------ void CDirtyRegion2::Initialize( __in_ecount_opt(1) const CMilRectF* prcNewSurfaceBounds, float allowedDirtyRegionOverhead ) { m_ignoreCount = 0; c_allowedDirtyRegionOverhead = allowedDirtyRegionOverhead; memset(m_dirtyRegions, 0, sizeof(m_dirtyRegions)); memset(m_overhead, 0, sizeof(m_overhead)); m_accumulatedOverhead = 0; m_fOptimized = false; m_fMaxSurfaceFallback = false; // // surface bounds kept in floating point to allow for intersection // with dirty rects in float space // m_rcSurfaceBoundsF = (prcNewSurfaceBounds) ? *prcNewSurfaceBounds : m_rcSurfaceBoundsF.sc_rcEmpty; } //+----------------------------------------------------------------------------- // CDirtyRegion2::CUnionResult //------------------------------------------------------------------------------ CDirtyRegion2::CUnionResult CDirtyRegion2::Union( __in_ecount(1) const MilRectF* pR0, __in_ecount(1) const MilRectF* pR1 ) { CMilRectF unioned(*pR0); unioned.Union(*pR1); CMilRectF intersected(*pR0); intersected.Intersect(*pR1); float areaOfUnion = RectArea(&unioned); float overhead = areaOfUnion - (RectArea(pR0) + RectArea(pR1) - RectArea(&intersected)); // Use 0 as overhead if computed overhead is negative or overhead // computation returns a nan. (If more than one of the previous // area computations overflowed then overhead could be not a // number.) if (!(overhead > 0)) { overhead = 0; } return CUnionResult(overhead, areaOfUnion, unioned); } //+----------------------------------------------------------------------------- // CDirtyRegion2::SetOverhead //------------------------------------------------------------------------------ void CDirtyRegion2::SetOverhead(UINT i, UINT j, float value) { Assert(i != j); if (i > j) { m_overhead[i][j] = value; } if (i < j) { m_overhead[j][i] = value; } } //+----------------------------------------------------------------------------- // CDirtyRegion2::GetOverhead //------------------------------------------------------------------------------ float CDirtyRegion2::GetOverhead(UINT i, UINT j) const { Assert(i != j); if (i > j) { return m_overhead[i][j]; } if (i < j) { return m_overhead[j][i]; } Assert(false); return FLT_MAX; } //+----------------------------------------------------------------------------- // CDirtyRegion2::Add //------------------------------------------------------------------------------ HRESULT CDirtyRegion2::Add( __in_ecount(1) const MilRectF *pNewRegion ) { HRESULT hr = S_OK; CMilRectF clippedNewRegion(*pNewRegion); if (IsDisabled()) { goto Cleanup; } AssertMsg(!m_fOptimized, "You need to reset the dirty region before you can use it again."); // // We've already fallen back to setting the whole surface as a dirty region // because of invalid dirty rects, so no need to add any new ones // if (m_fMaxSurfaceFallback) { goto Cleanup; } // // Check if rectangle is well formed before we try to intersect it, // because Intersect will fail for badly formed rects // if (!clippedNewRegion.IsWellOrdered()) { // // If we're here it means that we've been passed an invalid rectangle as a dirty // region, containing NAN or a non well ordered rectangle. // In this case, make the dirty region the full surface size and warn in the debugger // since this could cause a serious perf regression. // TraceTag((tagMILWarning, "Invalid dirty region received, setting dirty region to surface size.")); // // Remove all dirty regions from this object, since // they're no longer relevant. // Initialize(&m_rcSurfaceBoundsF, c_allowedDirtyRegionOverhead); m_fMaxSurfaceFallback = true; m_regionCount = 1; } else { clippedNewRegion.Intersect(m_rcSurfaceBoundsF); if (clippedNewRegion.IsEmpty()) { goto Cleanup; } // Always keep bounding boxes in device space integer. clippedNewRegion.left = CFloatFPU::FloorF(clippedNewRegion.left); clippedNewRegion.top = CFloatFPU::FloorF(clippedNewRegion.top); clippedNewRegion.right = CFloatFPU::CeilingF(clippedNewRegion.right); clippedNewRegion.bottom = CFloatFPU::CeilingF(clippedNewRegion.bottom); // // Keep dirty rectangle addition statistics. if (g_pMediaControl) { g_pAddedRectStatistics->Inc(); } // Compute the overhead for the new region combined with all the other existing regions. for (UINT n = 0; n < MaxDirtyRegionCount; n++) { CUnionResult ur = CDirtyRegion2::Union(&(m_dirtyRegions[n]), &clippedNewRegion); SetOverhead(MaxDirtyRegionCount, n, ur.m_overhead); } // Find the pair of dirty regions that if merged create the minimal overhead. A overhead // of 0 is perfect in the sense that it can not get better. In that case we break early // out of the loop. float minimalOverhead = FLT_MAX; UINT bestMatch_N = 0; UINT bestMatch_K = 0; bool fMatchFound = false; for (UINT n = MaxDirtyRegionCount; n > 0; n--) { for (UINT k = 0; k < n; k++) { float overhead_N_K = GetOverhead(n, k); if (minimalOverhead >= overhead_N_K) { minimalOverhead = overhead_N_K; bestMatch_N = n; bestMatch_K = k; fMatchFound = true; if (overhead_N_K < c_allowedDirtyRegionOverhead) { // If the overhead is very small, we bail out early since this // saves us some valuable cycles. Note that "small" means really // nothing here. In fact we don't always know if that number is // actually small. However, it the algorithm stays still correct // in the sense that we render everything that is necessary. It // might just be not optimal. goto LoopExit; } } } } if (!fMatchFound) { // // Should never be here. Being here implies that clippedNewRegion is not well formed // which is handled in parameter checking at the top of this function // MilUnexpectedError(E_FAIL, TEXT("Invalid dirty region")); } LoopExit: // There are two major cases now: // Case A: (bestMatch_N == MaxDirtyRegionCount) // This means the new dirty region can be combined with an existing one // without significant overhead. if (bestMatch_N == MaxDirtyRegionCount) { CUnionResult ur = CDirtyRegion2::Union(&clippedNewRegion, &(m_dirtyRegions[bestMatch_K])); MilRectF unioned = ur.m_union; if (m_dirtyRegions[bestMatch_K].DoesContain(unioned)) { // Check if newDirtyRegion is enclosed by dirty region bestMatch_K. In this case we are done. goto Cleanup; } else { m_accumulatedOverhead += ur.m_overhead; m_dirtyRegions[bestMatch_K] = unioned; UpdateOverhead(bestMatch_K); } } else // Case B: (bestMatch_N != MaxDirtyRegionCount) // This means that it is more efficient to merge first region N with // region K and then store the new region without combinding it with // another one. // // Merged region is stored in slot N. New region is stored in slot K. { CUnionResult ur = CDirtyRegion2::Union(&(m_dirtyRegions[bestMatch_N]), &(m_dirtyRegions[bestMatch_K])); m_accumulatedOverhead += ur.m_overhead; Assert((0 < bestMatch_N) && (bestMatch_N <= MaxDirtyRegionCount)); Assert(bestMatch_K < MaxDirtyRegionCount); m_dirtyRegions[bestMatch_N] = ur.m_union; m_dirtyRegions[bestMatch_K] = clippedNewRegion; UpdateOverhead(bestMatch_N); UpdateOverhead(bestMatch_K); } } Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // CDirtyRegion2::UpdateOverhead //------------------------------------------------------------------------------ void CDirtyRegion2::UpdateOverhead(UINT regionIndex) { const MilRectF* pRegionAtIndex = &(m_dirtyRegions[regionIndex]); for (UINT i = 0; i < MaxDirtyRegionCount; i++) { if (regionIndex != i) { CUnionResult ur = CDirtyRegion2::Union(&(m_dirtyRegions[i]), pRegionAtIndex); SetOverhead(i, regionIndex, ur.m_overhead); } } } //+-------------------------------------------------------------------------------------- // GetUninflatedDirtyRegions // // Returns a pointer to the internal dirty region rectangle array. Do not free that // memory. Note that the regions have NOT been inflated for anti-aliasing, it is // up to the caller to handle that. //--------------------------------------------------------------------------------------- __out_ecount(m_regionCount) const MilRectF* CDirtyRegion2::GetUninflatedDirtyRegions() { C_ASSERT(sizeof(m_dirtyRegions) == sizeof(m_resolvedRegions)); if (m_fMaxSurfaceFallback) { return &m_rcSurfaceBoundsF; } if (!m_fOptimized) { memset(m_resolvedRegions, 0, sizeof(m_resolvedRegions)); // Consolidate the dirtyRegions array to minimize looping below UINT addedDirtyRegionCount = 0; for (UINT i = 0; i < MaxDirtyRegionCount; i++) { if (!m_dirtyRegions[i].IsEmpty()) { if (i != addedDirtyRegionCount) { m_dirtyRegions[addedDirtyRegionCount] = m_dirtyRegions[i]; UpdateOverhead(addedDirtyRegionCount); } addedDirtyRegionCount++; } } // Merge all dirty rects that we can: // Because the algorithm for accumulating dirty regions can only combine them once when one is // added, a situation can arise where we have two dirty regions in the array that overlap // significantly or are contained one inside another. A full Render walk will occur for both // regions and will redraw all their content twice. bool couldMerge = true; // Loop until no more rects in m_dirtyRegions can be merged. // Each time we merge two rects in this final loop it creates the opportunity for the resulting // rect to also be merged on a subsequent loop execution. // Loop will execute a max of MaxDirtyRegionsCount - 1 times. while(couldMerge) { couldMerge = false; // The pair of for loops look at each pair of dirty rects, and see merge them if the overhead // is low enough and neither rect is empty. The array is not consolidated as rects are merged // since it would require an UpdateOverhead call on the slot moved - its cheaper to consolidate // only once more at the end. for (UINT n = 0; n < addedDirtyRegionCount; n++) { for (UINT k = n + 1; k < addedDirtyRegionCount; k++) { if ( !m_dirtyRegions[n].IsEmpty() && !m_dirtyRegions[k].IsEmpty() && GetOverhead(n, k) < c_allowedDirtyRegionOverhead) { //Merge N and K CUnionResult ur = CDirtyRegion2::Union(&(m_dirtyRegions[n]), &(m_dirtyRegions[k])); //Place merged region in slot N m_dirtyRegions[n] = ur.m_union; //Clear slot k, don't need to update its overhead since it's now empty m_dirtyRegions[k].SetEmpty(); UpdateOverhead(n); couldMerge = true; } } } } // Consolidate and copy into resolvedRegions UINT finalRegionCount = 0; for (UINT i = 0; i < addedDirtyRegionCount; i++) { if (!m_dirtyRegions[i].IsEmpty()) { m_resolvedRegions[finalRegionCount] = m_dirtyRegions[i]; finalRegionCount++; } } m_regionCount = finalRegionCount; m_fOptimized = true; } return m_resolvedRegions; } //+-------------------------------------------------------------------------------------- // Disable // Disables the dirty region collection. It basically turns Add into a no-op. //--------------------------------------------------------------------------------------- void CDirtyRegion2::Disable() { ++m_ignoreCount; } //+-------------------------------------------------------------------------------------- // Enable // Enables the dirty region collection. See also Disable. //--------------------------------------------------------------------------------------- void CDirtyRegion2::Enable() { Assert(m_ignoreCount > 0); --m_ignoreCount; }
32.915789
115
0.518975
[ "render", "object", "shape" ]
e377365eb9efad42327785b0183ec02ce3506af1
3,724
cpp
C++
src/base/ossimDirectoryTree.cpp
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
251
2015-10-20T09:08:11.000Z
2022-03-22T18:16:38.000Z
src/base/ossimDirectoryTree.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
73
2015-11-02T17:12:36.000Z
2021-11-15T17:41:47.000Z
src/base/ossimDirectoryTree.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
146
2015-10-15T16:00:15.000Z
2022-03-22T12:37:14.000Z
//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: A brief description of the contents of the file. // //************************************************************************* // $Id: ossimDirectoryTree.cpp 9966 2006-11-29 02:01:07Z gpotts $ #include <ossim/base/ossimDirectoryTree.h> #include <ossim/base/ossimDirectory.h> #include <ossim/base/ossimRegExp.h> ossimDirectoryTree::ossimDirectoryTree() : theCurrentDirectoryData(NULL), theFlags(0) { } ossimDirectoryTree::~ossimDirectoryTree() { deleteAll(); } void ossimDirectoryTree::findAllFilesThatMatch(std::vector<ossimFilename>& result, const ossimString& regularExpressionPattern, int flags) { ossimFilename filename; ossimRegExp regExpr; regExpr.compile(regularExpressionPattern.c_str()); if(getFirst(filename, flags)) { do { if(regExpr.find(filename.c_str())) { result.push_back(filename); } }while(getNext(filename)); } } bool ossimDirectoryTree::open(const ossimFilename& dir) { if(theCurrentDirectoryData) { deleteAll(); } theCurrentDirectoryData = new ossimDirData(new ossimDirectory, dir); theCurrentDirectoryData->theDirectory->open(dir); if(theCurrentDirectoryData->theDirectory->isOpened()) { return true; } else { delete theCurrentDirectoryData; theCurrentDirectoryData = NULL; } return isOpened(); } bool ossimDirectoryTree::isOpened() const { if(theCurrentDirectoryData) { return theCurrentDirectoryData->theDirectory->isOpened(); } return false; } bool ossimDirectoryTree::getFirst(ossimFilename &filename, int flags) { bool result = false; theFlags = flags | ossimDirectory::OSSIM_DIR_DIRS; if(theCurrentDirectoryData && isOpened()) { result = theCurrentDirectoryData->theDirectory->getFirst(filename, flags); while(result&&filename.isDir()) { checkToPushDirectory(filename); result = theCurrentDirectoryData->theDirectory->getNext(filename); } if(!result) { if(!theDirectoryQueue.empty()) { ossimFilename newDir = theDirectoryQueue.front(); theDirectoryQueue.pop(); theCurrentDirectoryData->theDirectory->open(newDir); return getFirst(filename, flags); } } } return result; } // get next file in the enumeration started with either GetFirst() or // GetFirstNormal() bool ossimDirectoryTree::getNext(ossimFilename &filename) { bool result = false; if(theCurrentDirectoryData) { result = theCurrentDirectoryData->theDirectory->getNext(filename); if(result) { checkToPushDirectory(filename); } else { if(!theDirectoryQueue.empty()) { ossimFilename newDir = theDirectoryQueue.front(); theDirectoryQueue.pop(); theCurrentDirectoryData->theDirectory->open(newDir); return getFirst(filename); } } } return result; } void ossimDirectoryTree::deleteAll() { if(theCurrentDirectoryData) { delete theCurrentDirectoryData; theCurrentDirectoryData = NULL; } } void ossimDirectoryTree::checkToPushDirectory(const ossimFilename &filename) { if((filename.file().trim() == ".") || (filename.file().trim() == "..")) { return; } else if(filename.isDir()) { theDirectoryQueue.push(filename); } }
23.871795
82
0.612513
[ "vector" ]
e37bd7e6e95f6459073a1291d5e4aaa9538c6633
12,429
cpp
C++
src/errors/CorrectionAligner.cpp
ndaniel/BEETL
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
[ "BSD-2-Clause" ]
53
2015-02-05T02:26:15.000Z
2022-01-13T05:37:06.000Z
src/errors/CorrectionAligner.cpp
ndaniel/BEETL
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
[ "BSD-2-Clause" ]
9
2015-09-03T23:42:14.000Z
2021-10-15T15:25:49.000Z
src/errors/CorrectionAligner.cpp
ndaniel/BEETL
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
[ "BSD-2-Clause" ]
23
2015-01-08T13:43:07.000Z
2021-05-19T17:35:42.000Z
/** ** Copyright (c) 2011-2014 Illumina, Inc. ** ** This file is part of the BEETL software package, ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file) ** ** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone ** Lightweight BWT Construction for Very Large String Collections. ** Proceedings of CPM 2011, pp.219-231 ** **/ #include "CorrectionAligner.hh" using namespace std; template <class T> T **makeMatrix( int rows, int cols ) { T **result = new T*[rows]; for ( int row = 0; row < rows; row++ ) result[row] = new T[cols]; return result; } template <class T> void zapMatrix( T **matrix, int rows ) { for ( int row = 0; row < rows; row++ ) delete[] matrix[row]; delete[] matrix; } struct CorrectionInterval { CorrectionInterval( int inStart, int inLengthOnRead, int inCorrectionLength ): correctionLength( inCorrectionLength ), lengthOnRead( inLengthOnRead ), start( inStart ) {} int correctionLength, lengthOnRead, start; }; string CorrectionAligner::MakeFastaRecord( int number, string name, string sequence, string quality ) { stringstream ss; ss << ">" << number << endl << sequence << endl; return ss.str(); } string CorrectionAligner::MakeFastqRecord( int number, string name, string sequence, string quality ) { stringstream ss; ss << name << sequence << endl << "+" << endl << quality << endl; return ss.str(); } bool CorrectionAligner::SortByLastCycle( ErrorInfo *a, ErrorInfo *b ) { return a->lastCycle > b->lastCycle; } void CorrectionAligner::ApplyCorrections( SeqReaderFile *readsFile, vector<ErrorInfo> &corrections, const string &outFile, bool correctionsOnly, ReadsFormat fileType ) { ofstream correctedReadsFile ( outFile.c_str(), fstream::out ); ApplyCorrections( readsFile, corrections, correctedReadsFile, correctionsOnly, fileType ); correctedReadsFile.close(); } void CorrectionAligner::ApplyCorrections( SeqReaderFile *readsFile, vector<ErrorInfo> &corrections, ostream &correctedReadsOut, bool correctionsOnly, ReadsFormat fileType ) { uint readLength = readsFile->length(); readsFile->rewindFile(); uint currentCorrection = 0; int currentRead = 0; while ( readsFile->readNext(), !readsFile->allRead() ) { string name = string( readsFile->thisName() ); string readStr = string( readsFile->thisSeq() ).substr( 0, readLength ); string qStr = string( readsFile->thisQual() ); if ( qStr.size() > readLength ) qStr = qStr.substr( 0, readLength ); if ( currentCorrection < corrections.size() && corrections[currentCorrection].seqNum == currentRead ) { vector<ErrorInfo *> correctionsForCurrentRead; while ( currentCorrection < corrections.size() && corrections[currentCorrection].seqNum == currentRead ) { correctionsForCurrentRead.push_back( &corrections[currentCorrection] ); ++currentCorrection; } string correctedRead, correctedQstr; CorrectRead( correctionsForCurrentRead, readStr, qStr, correctedRead, correctedQstr ); if ( fileType == READS_FORMAT_FASTQ ) correctedReadsOut << MakeFastqRecord( currentRead, name, correctedRead, correctedQstr ); else if ( fileType == READS_FORMAT_FASTA ) correctedReadsOut << MakeFastaRecord( currentRead, name, correctedRead, correctedQstr ); } else if ( !correctionsOnly ) { if ( fileType == READS_FORMAT_FASTQ ) correctedReadsOut << MakeFastqRecord( currentRead, name, readStr, qStr ); else if ( fileType == READS_FORMAT_FASTA ) correctedReadsOut << MakeFastaRecord( currentRead, name, readStr, qStr ); } currentRead++; } } string CorrectionAligner::Correct( const string &errorContainingRead, vector<ErrorInfo *> &corrections ) { return errorContainingRead; } void CorrectionAligner::CorrectRead( vector<ErrorInfo *> &corrections, const string &errorContainingRead, const string &inQstr, string &outRead, string &outQstr ) { outRead = Correct( errorContainingRead, corrections ); } enum AlignType { POSITION_MATCH = 0, SEQ1_GAP, SEQ2_GAP }; void SmithWatermanCorrectionAligner::Align( const string &seq1, const string &seq2, int &lengthOnSeq1, int &lengthOnSeq2 ) { int **matrix = makeMatrix<int>( seq1.size() + 1, seq2.size() + 1 ); AlignType **pointers = makeMatrix<AlignType>( seq1.size() + 1, seq2.size() + 1 ); for ( uint seq1pos = 0; seq1pos <= seq1.size(); seq1pos++ ) matrix[seq1pos][0] = 0; for ( uint seq2pos = 0; seq2pos <= seq2.size(); seq2pos++ ) matrix[0][seq2pos] = 0; for ( uint seq1pos = 1; seq1pos <= seq1.size(); seq1pos++ ) for ( uint seq2pos = 1; seq2pos <= seq2.size(); seq2pos++ ) { AlignType alignType = POSITION_MATCH; int score = 0; int matchScore; if ( seq1[seq1pos - 1] == seq2[seq2pos - 1] ) matchScore = matchScore_; else matchScore = mismatchScore_; if ( score < matrix[seq1pos - 1][seq2pos] + deletionScore_ ) { score = matrix[seq1pos - 1][seq2pos] + deletionScore_; alignType = SEQ2_GAP; } if ( score < matrix[seq1pos][seq2pos - 1] + insertionScore_ ) { score = matrix[seq1pos][seq2pos - 1] + insertionScore_; alignType = SEQ1_GAP; } if ( score < matrix[seq1pos - 1][seq2pos - 1] + matchScore ) { score = matrix[seq1pos - 1][seq2pos - 1] + matchScore; alignType = POSITION_MATCH; } matrix[seq1pos][seq2pos] = score; pointers[seq1pos][seq2pos] = alignType; } int pos1 = seq1.size() - 1; int pos2 = seq2.size() - 1; while ( ( pos1 > 0 ) && ( pos2 > 0 ) ) { switch ( pointers[pos1][pos2] ) { case POSITION_MATCH: pos1--; pos2--; break; case SEQ1_GAP: pos2--; break; case SEQ2_GAP: pos1--; break; default: exit( 1 ); } } lengthOnSeq1 = seq1.size() - pos1; lengthOnSeq2 = seq2.size() - pos2; zapMatrix<AlignType>( pointers, seq1.size() + 1 ); zapMatrix<int>( matrix, seq1.size() + 1 ); } void SmithWatermanCorrectionAligner::Align( const string &seq1, const string &seq2, int &lengthOnSeq1, int &lengthOnSeq2, bool correctForwards ) { if ( correctForwards ) { string seq1_ = strreverse( seq1 ); string seq2_ = strreverse( seq2 ); Align( seq1_, seq2_, lengthOnSeq1, lengthOnSeq2 ); } else Align( seq1, seq2, lengthOnSeq1, lengthOnSeq2 ); } string SmithWatermanCorrectionAligner::Replace( const string &original, const string &correction, int lineUpPosition, bool correctForwards ) { int lengthOnOriginal; return Replace( original, correction, lineUpPosition, correctForwards, lengthOnOriginal ); } string SmithWatermanCorrectionAligner::Replace( const string &original, const string &correction, int lineUpPosition, bool correctForwards, int &lengthOnOriginal ) { int lengthOnCorrection; string originalPartToAlign = correctForwards ? original.substr( lineUpPosition ) : original.substr( 0, lineUpPosition + 1 ); Align( correction, originalPartToAlign, lengthOnCorrection, lengthOnOriginal, correctForwards ); if ( correctForwards ) { return original.substr( 0, lineUpPosition ) + correction + original.substr( min<int>( lengthOnOriginal + lineUpPosition, original.size() ) ) ; } else { return original.substr( 0, max<int>( lineUpPosition - lengthOnOriginal + 1, 0 ) ) + correction + original.substr( min<int>( original.size(), lineUpPosition + 1 ) ) ; } } string SmithWatermanCorrectionAligner::Correct( const string &errorContainingRead, vector<ErrorInfo *> &corrections ) { bool firstCorrection = true; string result( errorContainingRead ); for ( uint currentCorrection = 0; currentCorrection < corrections.size(); currentCorrection++ ) { ErrorInfo *current = corrections[currentCorrection]; string witness = ( current->reverseStrand ) ? errorContainingRead.substr( current->positionInRead - current->lastCycle, current->lastCycle ) : errorContainingRead.substr( current->positionInRead + 1, current->lastCycle ); int lineUpAt; int canCorrect = true; if ( firstCorrection ) { //if its the first correction we're applying to the read then we know the exact position the putative error //occurred, so we can line up exactly and avoid calling str.find lineUpAt = current->positionInRead; } else { int witnessLocation = result.find( witness ); if ( witnessLocation == -1 ) canCorrect = false; lineUpAt = ( current->reverseStrand ) ? witnessLocation + current->lastCycle : witnessLocation - 1; } if ( canCorrect ) { result = Replace( result, current->corrector, lineUpAt, current->reverseStrand ); } firstCorrection = false; } return result; } string StitchAligner::Correct( const string &errorContainingRead, vector<ErrorInfo *> &corrections ) { return errorContainingRead.substr( 0, corrections[0]->correctorStart ) + corrections[0]->corrector; } void NoIndelAligner::CorrectRead( vector<ErrorInfo *> &corrections, const string &errorContainingRead, const string &inQstr, string &outRead, string &outQstr ) { bool firstCorrection = true; outRead = errorContainingRead; outQstr = inQstr; sort( corrections.begin(), corrections.end(), SortByLastCycle ); for ( uint currentCorrection = 0; currentCorrection < corrections.size(); currentCorrection++ ) { ErrorInfo *current = corrections[currentCorrection]; bool canCorrect = true; if ( current->lastCycle < minLastCycle_ ) canCorrect = false; string witness = ( current->reverseStrand ) ? errorContainingRead.substr( current->positionInRead - current->lastCycle, current->lastCycle ) : errorContainingRead.substr( current->positionInRead + 1, current->lastCycle ); int lineUpAt; if ( firstCorrection ) lineUpAt = current->positionInRead; else { int witnessLocation = outRead.find( witness ); if ( witnessLocation == -1 ) canCorrect = false; lineUpAt = ( current->reverseStrand ) ? witnessLocation + current->lastCycle : witnessLocation - 1; } if ( canCorrect ) { string corrector = current->corrector; //int corrStart = current->correctorStart; int corrStart = ( current->reverseStrand ) ? lineUpAt : lineUpAt - corrector.size() + 1; outRead = outRead.substr( 0, max<int>( corrStart, 0 ) ) + corrector + outRead.substr( min<int>( corrStart + corrector.size(), outRead.size() ) ) ; outQstr = outQstr.substr( 0, max<int>( corrStart, 0 ) ) + string( corrector.size(), correctionQuality_ ) + outQstr.substr( min<int>( corrStart + corrector.size(), outQstr.size() ) ) ; if ( trim_ ) { outRead = outRead.substr( max<int>( 0, -corrStart ), errorContainingRead.size() ); outQstr = outQstr.substr( max<int>( 0, -corrStart ), errorContainingRead.size() ); } } firstCorrection = false; } }
33.144
174
0.599646
[ "vector" ]
be6bb5c205491d570e2baf71fe665e53bfd1e2cc
1,428
cpp
C++
2015/Day10/Day10.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
2015/Day10/Day10.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
2015/Day10/Day10.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
// Day10.cpp : Defines the entry point for the console application. // #include "stdafx.h" static void AppendCurrentCharacter(std::string & Buffer, char CurrentCharacter, uint32_t AmountOfCurrentCharacter); int main() { const std::vector<size_t> Steps = { 40, 50 }; auto CurrentStep = Steps.begin(); std::string Input("3113322113"); std::cout << Input << std::endl; for (size_t i = 1; i <= *(Steps.end() - 1); i++) { std::string Buffer; char CurrentCharacter = 0; uint32_t AmountOfCurrentCharacter = 0; for (char Character : Input) { if (Character != CurrentCharacter) { AppendCurrentCharacter(Buffer, CurrentCharacter, AmountOfCurrentCharacter); CurrentCharacter = Character; AmountOfCurrentCharacter = 1; } else { AmountOfCurrentCharacter++; } } AppendCurrentCharacter(Buffer, CurrentCharacter, AmountOfCurrentCharacter); Input.swap(Buffer); if ((CurrentStep != Steps.end()) && (i == *CurrentStep)) { std::cout << "Length(" << i << "): " << Input.size() << std::endl; CurrentStep++; } std::cout << i << std::endl; } system("pause"); return 0; } static void AppendCurrentCharacter(std::string & Buffer, char CurrentCharacter, uint32_t AmountOfCurrentCharacter) { if (AmountOfCurrentCharacter != 0) { std::stringstream Converter; Converter << AmountOfCurrentCharacter; Buffer += Converter.str(); Buffer += CurrentCharacter; } }
22.3125
115
0.677171
[ "vector" ]
be6fa2aa0fdb3641b5d45bf8e0f32a7d32b9b245
5,121
tcc
C++
Scr/mp_graph/include/tools.tcc
bo-rc/data_structures
d568b240aff9ceaf5c220684358e32643b8b1864
[ "MIT" ]
null
null
null
Scr/mp_graph/include/tools.tcc
bo-rc/data_structures
d568b240aff9ceaf5c220684358e32643b8b1864
[ "MIT" ]
null
null
null
Scr/mp_graph/include/tools.tcc
bo-rc/data_structures
d568b240aff9ceaf5c220684358e32643b8b1864
[ "MIT" ]
null
null
null
/** * @file tools.tcc * Definition of utility functions on graphs. */ #include <limits> #include <queue> #include <iostream> #include "dsets.h" #include "tools.h" #include "tools_provided.h" namespace cs225 { namespace tools { template <class Graph> typename Graph::edge_weight_type min_weight_edge(Graph& g) { using weight_t = typename Graph::edge_weight_type; weight_t min = std::numeric_limits<weight_t>::max(); auto edge_vector = g.edges(); auto it = edge_vector.begin(); edge min_edge{it->source, it->dest}; vertex_map<vertex_state> vtx_mark; for (const auto& v : g.vertices()) vtx_mark[v] = vertex_state::UNEXPLORED; /// @todo your code here for (const auto& e : g.edges()) g.edge_label(e, edge_state::UNEXPLORED); // traversal std::queue<vertex> q; auto v_start = g.start_vertex(); q.push(v_start); vtx_mark[v_start] = vertex_state::VISITED; //snapshot snap("snap"); while(!q.empty()) { auto u = q.front(); q.pop(); //snap(g); for(const auto& v : g.adjacent(u)) { auto lbl = vtx_mark[v]; edge uv; uv.source = u; uv.dest = v; if(lbl == vertex_state::UNEXPLORED) { vtx_mark[v] = vertex_state::VISITED; g.edge_label(uv, edge_state::DISCOVERY); if(g.edge_weight(uv) <= g.edge_weight(min_edge)) { min_edge = uv; } q.push(v); } else if (g.edge_label(uv) == edge_state::UNEXPLORED) { g.edge_label(uv, edge_state::CROSS); if(g.edge_weight(uv) <= g.edge_weight(min_edge)) { min_edge = uv; } } } } g.edge_label(min_edge, edge_state::MIN); min = g.edge_weight(min_edge); return min; } void build_path(vertex_map<vertex>& vm, vertex& dest, vertex& origin, edge_set& es) { if (vm[dest] == origin) { es.insert({dest, origin}); return; } else { auto mid = vm[dest]; es.insert({dest, mid}); dest = mid; build_path(vm, dest, origin, es); } } template <class Graph> uint64_t shortest_path_length(Graph& g, vertex start, vertex end) { /// @todo your code here /// if (start == end) return 0; vertex_map<vertex> vtx_parent; for (const auto& v : g.vertices()) vtx_parent[v] = v; vertex_map<vertex_state> vtx_mark; for (const auto& v : g.vertices()) vtx_mark[v] = vertex_state::UNEXPLORED; for (const auto& e : g.edges()) g.edge_label(e, edge_state::UNEXPLORED); auto dest = start; std::queue<vertex> q; q.push(start); vtx_mark[start] = vertex_state::VISITED; while(!q.empty()) { auto u = q.front(); q.pop(); for(const auto& v : g.adjacent(u)) { auto lbl = vtx_mark[v]; if(lbl == vertex_state::UNEXPLORED) { vtx_mark[v] = vertex_state::VISITED; g.edge_label(u, v, edge_state::DISCOVERY); vtx_parent[v] = u; // discovered by u if (v == end) { dest = end; break; } q.push(v); } else if (g.edge_label(u, v) == edge_state::UNEXPLORED) { g.edge_label(u, v, edge_state::CROSS); } } } edge_set es; build_path(vtx_parent, dest, start, es); for (const auto& e : es) g.edge_label(e, edge_state::MINPATH); return es.size(); } template <class Graph> void mark_mst(Graph& g) { for (const auto& e : minimum_spanning_tree(g)) g.edge_label(e, edge_state::MST); } template <class Graph> edge_set minimum_spanning_tree(const Graph& g) { // sort all the edges struct weighted_edge { edge arc; typename Graph::edge_weight_type weight; }; // initialize PQ for edge selection std::vector<weighted_edge> pq; for (const auto& e : g.edges()) pq.push_back({e, g.edge_weight(e)}); std::sort(pq.begin(), pq.end(), [&](const weighted_edge& e1, const weighted_edge& e2) { return e1.weight < e2.weight; }); /// @todo your code here // initialize set of edges for output edge_set edge_output; // initialize Dsets so that every vertex is in its own set dsets ds; vertex_set vs = g.vertices(); for (auto& v : vs) { ds.add_elements(v); } auto itr_pq = pq.cbegin(); while(edge_output.size() != vs.size()-1) { edge e = itr_pq++->arc; auto v0 = e.source; auto v1 = e.dest; if(ds.find(v0) != ds.find(v1)) { edge_output.insert(e); ds.merge(v0, v1); } } return edge_output; } } // namespace tools } // namespace cs225
22.362445
83
0.525874
[ "vector" ]
be70c523b8465d9f4ceefbb87916fbf05746d270
1,506
cpp
C++
source/main.cpp
llamaking136/edclone
502ce15cab3e6ccf3609785bf23787668f6d6f32
[ "Apache-2.0" ]
1
2021-03-08T20:19:40.000Z
2021-03-08T20:19:40.000Z
source/main.cpp
llamaking136/edclone
502ce15cab3e6ccf3609785bf23787668f6d6f32
[ "Apache-2.0" ]
null
null
null
source/main.cpp
llamaking136/edclone
502ce15cab3e6ccf3609785bf23787668f6d6f32
[ "Apache-2.0" ]
null
null
null
// // main.cpp // // created at 07/03/2021 19:41:32 // written by llamaking136 // // Copyright 2021 llamaking136 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* #if defined(__cplusplus) extern "C" { #endif // __cplusplus */ #include "main.hpp" int main(int argc, const char* argv[]) { // std::vector<std::string> cmd_opt = parse_args(argc, argv); FileBuffer current_file; signal(SIGINT, current_file.intHandler); // if (!argv[1]) // current_file.filename = NULL; if (argv[1]) { current_file.filename = std::string(argv[1]); // std::cout << "current filename: " << current_file.filename << "\n"; current_file.isOpen = true; } FileBufferContents current_contents; std::string current_content_buffer; while (prompt("> ", current_content_buffer)) { if (current_content_buffer == "!!QUIT" || current_content_buffer == "!!EXIT") return 0; std::cout << "'" << current_content_buffer << "'\n"; } return 0; } /* #if defined(__cplusplus) } #endif // __cplusplus */
24.290323
79
0.693227
[ "vector" ]
be7875d7af0c3f209f847dc12d4719f59ece7354
5,389
cpp
C++
term6/OSiS/lab10/lab10.cpp
japanese-goblinn/labs
47f5d59d28faf62c82535856e138b5cb98159fd0
[ "MIT" ]
null
null
null
term6/OSiS/lab10/lab10.cpp
japanese-goblinn/labs
47f5d59d28faf62c82535856e138b5cb98159fd0
[ "MIT" ]
null
null
null
term6/OSiS/lab10/lab10.cpp
japanese-goblinn/labs
47f5d59d28faf62c82535856e138b5cb98159fd0
[ "MIT" ]
1
2021-10-11T08:30:48.000Z
2021-10-11T08:30:48.000Z
#include "stdafx.h" #include "lab10.h" #define MAX_LOADSTRING 100 HINSTANCE hInst; TCHAR szTitle[MAX_LOADSTRING]; TCHAR szWindowClass[MAX_LOADSTRING]; ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); MSG msg; HACCEL hAccelTable; LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_LAB5, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LAB5)); while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LAB5)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_LAB5); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } UINT messageId; BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); messageId = RegisterWindowMessage(L"Draw"); return TRUE; } HBRUSH bRed = CreateSolidBrush(RGB(255,0,0)); HBRUSH bGreen = CreateSolidBrush(RGB(0,255,0)); HBRUSH bBlue = CreateSolidBrush(RGB(0,0,255)); UINT shapeCount = 0; //arrays of settings UINT shapeX[1024]; UINT shapeY[1024]; UINT shapeColor[1024]; UINT shapeType[1024]; UINT settings; void DoPaint(HDC hdc) { //painting every time for (int i = 0; i < shapeCount; i++) { UINT color = shapeColor[i]; UINT shape = shapeType[i]; UINT mouseX = shapeX[i]; UINT mouseY = shapeY[i]; SelectObject(hdc, (color == 0) ? bRed : ((color == 1) ? bGreen : bBlue)); //rhombus if (shape == 0) { POINT points[4]; points[0].x = mouseX; points[0].y = mouseY - 10; points[1].x = mouseX + 10; points[1].y = mouseY; points[2].x = mouseX; points[2].y = mouseY + 10; points[3].x = mouseX - 10; points[3].y = mouseY; Polygon(hdc, points, 4); } //rect if (shape == 1) { Rectangle(hdc, mouseX-10, mouseY-10, mouseX+10, mouseY+10); } //star if (shape == 2) { POINT points[10]; points[0].x = mouseX; points[0].y = mouseY - 10; points[1].x = mouseX + 3; points[1].y = mouseY - 3; points[2].x = mouseX + 10; points[2].y = mouseY - 3; points[3].x = mouseX + 3; points[3].y = mouseY; points[4].x = mouseX + 5; points[4].y = mouseY + 10; points[5].x = mouseX; points[5].y = mouseY + 3; points[6].x = mouseX - 5; points[6].y = mouseY + 10; points[7].x = mouseX - 3; points[7].y = mouseY; points[8].x = mouseX - 10; points[8].y = mouseY - 3; points[9].x = mouseX - 3; points[9].y = mouseY - 3; Polygon(hdc, points, 10); } //circle if (shape == 3) { Ellipse(hdc, mouseX - 10, mouseY - 10, mouseX+10, mouseY+10); } } } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; if (message == messageId) { settings = wParam; } switch (message) { case WM_PAINT: hdc = BeginPaint(hWnd, &ps); DoPaint(hdc); EndPaint(hWnd, &ps); break; case WM_LBUTTONDOWN: { if (settings & 16) { shapeX[shapeCount] = GET_X_LPARAM(lParam); shapeY[shapeCount] = GET_Y_LPARAM(lParam); shapeType[shapeCount] = (settings >> 2) & 3; shapeColor[shapeCount] = settings & 3; shapeCount++; } InvalidateRect(hWnd, NULL, TRUE); break; } case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
24.274775
81
0.561329
[ "shape" ]
be8413c5ae60aeeebfd55a02fcd306699274cb04
12,595
cpp
C++
internal/dll_project/ohtorii_tools/ohtorii_tools/kinds.cpp
ohtorii/gather
16857d53243dd597a1f451b3dcb53e87202131bf
[ "MIT" ]
2
2020-12-03T00:29:26.000Z
2020-12-12T08:02:17.000Z
internal/dll_project/ohtorii_tools/ohtorii_tools/kinds.cpp
ohtorii/unity
c3b5e4befb2e980cdc46d258eea4f9c7f6598db1
[ "MIT" ]
null
null
null
internal/dll_project/ohtorii_tools/ohtorii_tools/kinds.cpp
ohtorii/unity
c3b5e4befb2e980cdc46d258eea4f9c7f6598db1
[ "MIT" ]
null
null
null
#include"stdafx.h" /////////////////////////////////////////////////////////////////////////////// // global variable /////////////////////////////////////////////////////////////////////////////// static WCHAR gs_empty[] = { 0 }; static const WCHAR *gs_prefix =_T("action."); static const size_t gs_prefix_size = 7; /////////////////////////////////////////////////////////////////////////////// // static function /////////////////////////////////////////////////////////////////////////////// static bool ContainsAction(const WCHAR*str) { return std::equal(gs_prefix, gs_prefix + gs_prefix_size, str); } //[action.*]セクションのパース static void GatherActionSections(std::vector<std::wstring> &dst, const WCHAR* filename) { WCHAR buf[2 * 1024]; buf[0] = 0; GetPrivateProfileSectionNames(buf, _countof(buf), filename); size_t i = 0; while (((i + 1) < _countof(buf)) && (buf[i] != 0) && (buf[i + 1] != 0)) { WCHAR* top = &buf[i]; if (ContainsAction(top)) { dst.push_back(top); } i += wcslen(top) + 1;//+1で'\0'を読み飛ばす } } static void ParseActionSection(Action &dst, const WCHAR*section_name, const WCHAR* filename) { /*アクションのセクションをパースする */ WCHAR buf[2*1024]; buf[0] = 0; //memo: "action.nop" -> "nop" dst.m_name.assign(section_name+gs_prefix_size); GetPrivateProfileString(section_name, _T("function"), _T(""), buf, _countof(buf), filename); dst.m_label.assign(buf); GetPrivateProfileString(section_name, _T("description"), _T(""), buf, _countof(buf), filename); dst.m_description.assign(buf); GetPrivateProfileString(section_name, _T("is_quit"), _T("false"), buf, _countof(buf), filename); dst.m_is_quit = StringToBool(buf); GetPrivateProfileString(section_name, _T("is_multi_selectable"), _T("false"), buf, _countof(buf), filename); dst.m_is_multi_selectable = StringToBool(buf); GetPrivateProfileString(section_name, _T("is_start"), _T("false"), buf, _countof(buf), filename); dst.m_is_start = StringToBool(buf); GetPrivateProfileString(section_name, _T("is_edit"), _T("false"), buf, _countof(buf), filename); dst.m_is_edit = StringToBool(buf); GetPrivateProfileString(section_name, _T("is_reget_candidates"), _T("false"), buf, _countof(buf), filename); dst.m_is_reget_candidates = StringToBool(buf); } static bool CheckAppendable(bool candidate_is_multi_select, bool action_is_multi_selectable) { if (candidate_is_multi_select) { if (action_is_multi_selectable) { return true; } return false; } return true; } /////////////////////////////////////////////////////////////////////////////// // class Action /////////////////////////////////////////////////////////////////////////////// Action::Action() { m_is_quit = false; m_is_multi_selectable = false; m_is_start = false; m_is_edit = false; m_is_reget_candidates = false; } /////////////////////////////////////////////////////////////////////////////// // class Kind /////////////////////////////////////////////////////////////////////////////// Kind::Kind() { } Kind::Kind(const std::wstring &name, const std::wstring &description, const std::wstring &default_action, const std::vector<std::wstring> &base_kind): m_name(name), m_description(description), m_default_action(default_action), m_base_kind(base_kind) { } Action* Kind::FindAction(const WCHAR* action_name) { /*size_t size = m_actions.size(); for (size_t i = 0; i < size; ++i) { auto&item=m_actions.at(i); if (wcscmp(item.m_name.c_str(), action_name) == 0) { return &m_actions.at(i); } }*/ auto index = FindActionIndex(action_name); if (index == UNITY_NOT_FOUND_INDEX) { return nullptr; } return &m_actions.at(index); } size_t Kind::FindActionIndex(const WCHAR* action_name) { size_t size = m_actions.size(); for (size_t i = 0; i < size; ++i) { auto&item = m_actions.at(i); if (wcscmp(item.m_name.c_str(), action_name) == 0) { return i; } } return UNITY_NOT_FOUND_INDEX; } /////////////////////////////////////////////////////////////////////////////// // class Kinds /////////////////////////////////////////////////////////////////////////////// void Kinds::Clear() { m_kinds.clear(); } WCHAR* Kinds::Create(const WCHAR* kind_ini) { Kind dst; DebugLog(_T("Kinds::Create")); { auto& file = Unity::Instance().lock()->QueryFile(); std::wstring temp_filename; if (!file.CreateTempFile(temp_filename)) { DebugLog(_T(" return false@1")); return gs_empty; } const WCHAR*ini_filename = temp_filename.c_str(); if (!file.WriteToFile(ini_filename, kind_ini)) { DebugLog(_T(" return false@2")); return gs_empty; } if (!IniToKind(dst, ini_filename)) { return gs_empty; } } m_kinds.emplace_back(dst); DebugLog(_T(" return=%s"), m_kinds.back().m_name.c_str()); return const_cast<WCHAR*>(m_kinds.back().m_name.c_str()); } Kind* Kinds::FindKind(const WCHAR* kind_name) { auto it = std::find_if( m_kinds.begin(), m_kinds.end(), [kind_name](const auto&item) {return item.m_name.compare(kind_name) == 0; } ); if (it == m_kinds.end()) { return nullptr; } return &(*it); } size_t Kinds::FindKindIndex(const WCHAR* kind_name) { const auto num = m_kinds.size(); for (size_t i = 0; i < num; ++i) { if (m_kinds.at(i).m_name.compare(kind_name) == 0) { return i; } } return UNITY_NOT_FOUND_INDEX; } size_t Kinds::FindActionIndex(size_t kind_index, const WCHAR* action_name) { try { const auto & actions = m_kinds.at(kind_index).m_actions; const auto num = actions.size(); for (size_t i = 0; i < num; ++i) { if (actions.at(i).m_name.compare(action_name) == 0) { return i; } } } catch (std::exception) { //pass } return UNITY_NOT_FOUND_INDEX; } /**************************************************************************** Kind ****************************************************************************/ const WCHAR* Kinds::GetKindName(size_t kind_index) { try { return m_kinds.at(kind_index).m_name.c_str(); }catch (std::exception) { //pass } return gs_empty; } const WCHAR* Kinds::GetKindDescription(size_t kind_index) { try { return m_kinds.at(kind_index).m_description.c_str(); } catch (std::exception) { //pass } return gs_empty; } const WCHAR* Kinds::GetDefaultAction(size_t kind_index) { try { return m_kinds.at(kind_index).m_default_action.c_str(); } catch (std::exception) { //pass } return gs_empty; } /**************************************************************************** Action ****************************************************************************/ const WCHAR* Kinds::GetActionName(size_t kind_index, size_t action_index) { try { return m_kinds.at(kind_index).m_actions.at(action_index).m_name.c_str(); } catch (std::exception) { //pass } return gs_empty; } const WCHAR* Kinds::GetActionLabelName(size_t kind_index, size_t action_index) { try { return m_kinds.at(kind_index).m_actions.at(action_index).m_label.c_str(); } catch (std::exception) { //pass } return gs_empty; } const WCHAR* Kinds::GetActionDescription(size_t kind_index, size_t action_index) { try { return m_kinds.at(kind_index).m_actions.at(action_index).m_description.c_str(); } catch (std::exception) { //pass } return gs_empty; } bool Kinds::IsActionQuit(size_t kind_index, size_t action_index)const { try { return m_kinds.at(kind_index).m_actions.at(action_index).m_is_quit; } catch (std::exception) { //pass } return false; } bool Kinds::IsActionMultiSelectable(size_t kind_index, size_t action_index) { try { return m_kinds.at(kind_index).m_actions.at(action_index).m_is_multi_selectable; } catch (std::exception) { //pass } return false; } bool Kinds::IsActionStart(size_t kind_index, size_t action_index)const { try { return m_kinds.at(kind_index).m_actions.at(action_index).m_is_start; } catch (std::exception) { //pass } return false; } bool Kinds::IsEdit(size_t kind_index, size_t action_index) { try { return m_kinds.at(kind_index).m_actions.at(action_index).m_is_edit; } catch (std::exception) { //pass } return false; } bool Kinds::IsRegetCandidates(size_t kind_index, size_t action_index)const { try { return m_kinds.at(kind_index).m_actions.at(action_index).m_is_reget_candidates; } catch (std::exception) { //pass } return false; } const WCHAR* Kinds::GetDefaultActionLabelName(const WCHAR* kind_name){ DebugLog(_T("GetHidemaruLabelName")); auto*kind = FindKind(kind_name); if (kind == nullptr) { DebugLog(_T("kind == nullptr")); return gs_empty; } DebugLog(_T("kind->m_default_action=")); DebugLog(kind->m_default_action.c_str()); auto *action = kind->FindAction(kind->m_default_action.c_str()); if (action == nullptr) { DebugLog(_T("action == nullptr")); return gs_empty; } DebugLog(_T("action->m_function=")); DebugLog(action->m_label.c_str()); return action->m_label.c_str(); } bool Kinds::GenerateKindCandidates(INT_PTR instance_index) { DebugLog(_T("GenerateKindCandidates")); std::weak_ptr<Unity> instance = Unity::Instance(instance_index); if (instance.expired()) { DebugLog(_T(" return false @1")); return false; } { auto&inheritance = instance.lock()->QueryInheritance(); if (! inheritance.GenerateResolveActions()) { DebugLog(_T(" return false @2")); return false; } auto& candidates = Unity::Instance().lock()->QueryCandidates(); //現在のインスタンスへ候補を追加する for (const auto&item : inheritance.GetResolveActions()) { DebugLog(_T(" item.m_kind_name.c_str()=%s"),item.m_kind_name.c_str()); auto* kind = instance.lock()->QueryKinds().FindKind(item.m_kind_name.c_str()); if (kind == nullptr) { continue; } const auto & action = kind->m_actions.at(item.m_action_index); auto candidate_index = candidates.AppendCandidate(_T("action"), action.m_name.c_str(), (item.m_kind_name+_T("\t")+action.m_description).c_str()); candidates.SetUserData(candidate_index, _T("__kind__"), kind->m_name.c_str()); } DebugLog(_T(" return true")); return true; } } bool Kinds::IniToKind(Kind&dst,const WCHAR*ini_filename){ WCHAR buf[8 * 1000]; GetPrivateProfileString(_T("property"), _T("name"), _T(""), buf, _countof(buf), ini_filename); dst.m_name.assign(buf); if (dst.m_name.size() == 0) { WCHAR fname[_MAX_FNAME]; const errno_t err = _wsplitpath_s(ini_filename, nullptr, 0, nullptr, 0, fname, _MAX_FNAME, nullptr, 0); if (err != 0) { return false; } dst.m_name.assign(fname); } GetPrivateProfileString(_T("property"), _T("description"), _T(""), buf, _countof(buf), ini_filename); dst.m_description.assign(buf); GetPrivateProfileString(_T("property"), _T("default_action"), _T(""), buf, _countof(buf), ini_filename); dst.m_default_action.assign(buf); { GetPrivateProfileString(_T("property"), _T("base_kind"), _T(""), buf, _countof(buf), ini_filename); Tokenize(dst.m_base_kind, buf, _T(" \t")); if (0) { //debug DebugLog(_T(" ==== Inheritance ====")); for (const auto&item : dst.m_base_kind) { DebugLog(_T(" %s"), item.c_str()); } } } { std::vector<std::wstring> action_sections; action_sections.reserve(16); GatherActionSections(action_sections, ini_filename); Action action; for (const auto& section_name : action_sections) { ParseActionSection(action, section_name.c_str(), ini_filename); dst.m_actions.emplace_back(action); } } return true; } bool Kinds::LoadKindAll(const WCHAR* root_dir) { File::EnumeFileResultContainer file_names; if (!Unity::Instance().lock()->QueryFile().EnumeFiles(file_names, root_dir, _T("*.ini"))) { return false; } const auto num = file_names.size(); m_kinds.resize(num); for (size_t i = 0; i < num; ++i) { if (!IniToKind(m_kinds.at(i), file_names.at(i).m_abs_filename.c_str())) { return false; } } Dump(); return true; } void Kinds::Dump()const { DebugLog(_T("==== Kinds::Dump [kinds.size=%d] ===="), m_kinds.size()); size_t kind_index = 0; for(auto &kind : m_kinds) { DebugLog(_T(" [%d]%s"), kind_index, kind.m_name.c_str()); DebugLog(_T(" m_actions.size()=%d"), kind.m_actions.size()); size_t action_index = 0; for (auto&action : kind.m_actions) { DebugLog(_T(" [%d]%s"), action_index, action.m_name.c_str()); DebugLog(_T(" is_edit=%d"),action.m_is_edit); DebugLog(_T(" is_quit=%d"), action.m_is_quit); DebugLog(_T(" is_is_multi_selectable=%d"), action.m_is_multi_selectable); DebugLog(_T(" is_is_start=%d"), action.m_is_start); DebugLog(_T(" is_reget_candidates=%d"), action.m_is_reget_candidates); ++action_index; } ++kind_index; } }
27.440087
148
0.628027
[ "vector" ]
be89c4c74e477599dcc0156c950d659ff24c326d
36,900
cpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_perf_meas_cfg.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_perf_meas_cfg.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_perf_meas_cfg.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "Cisco_IOS_XR_perf_meas_cfg.hpp" using namespace ydk; namespace cisco_ios_xr { namespace Cisco_IOS_XR_perf_meas_cfg { PerformanceMeasurement::PerformanceMeasurement() : enable_performance_measurement{YType::empty, "enable-performance-measurement"} , delay_profile_interface(std::make_shared<PerformanceMeasurement::DelayProfileInterface>()) , interfaces(std::make_shared<PerformanceMeasurement::Interfaces>()) { delay_profile_interface->parent = this; interfaces->parent = this; yang_name = "performance-measurement"; yang_parent_name = "Cisco-IOS-XR-perf-meas-cfg"; is_top_level_class = true; has_list_ancestor = false; } PerformanceMeasurement::~PerformanceMeasurement() { } bool PerformanceMeasurement::has_data() const { if (is_presence_container) return true; return enable_performance_measurement.is_set || (delay_profile_interface != nullptr && delay_profile_interface->has_data()) || (interfaces != nullptr && interfaces->has_data()); } bool PerformanceMeasurement::has_operation() const { return is_set(yfilter) || ydk::is_set(enable_performance_measurement.yfilter) || (delay_profile_interface != nullptr && delay_profile_interface->has_operation()) || (interfaces != nullptr && interfaces->has_operation()); } std::string PerformanceMeasurement::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enable_performance_measurement.is_set || is_set(enable_performance_measurement.yfilter)) leaf_name_data.push_back(enable_performance_measurement.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "delay-profile-interface") { if(delay_profile_interface == nullptr) { delay_profile_interface = std::make_shared<PerformanceMeasurement::DelayProfileInterface>(); } return delay_profile_interface; } if(child_yang_name == "interfaces") { if(interfaces == nullptr) { interfaces = std::make_shared<PerformanceMeasurement::Interfaces>(); } return interfaces; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(delay_profile_interface != nullptr) { _children["delay-profile-interface"] = delay_profile_interface; } if(interfaces != nullptr) { _children["interfaces"] = interfaces; } return _children; } void PerformanceMeasurement::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enable-performance-measurement") { enable_performance_measurement = value; enable_performance_measurement.value_namespace = name_space; enable_performance_measurement.value_namespace_prefix = name_space_prefix; } } void PerformanceMeasurement::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enable-performance-measurement") { enable_performance_measurement.yfilter = yfilter; } } std::shared_ptr<ydk::Entity> PerformanceMeasurement::clone_ptr() const { return std::make_shared<PerformanceMeasurement>(); } std::string PerformanceMeasurement::get_bundle_yang_models_location() const { return ydk_cisco_ios_xr_models_path; } std::string PerformanceMeasurement::get_bundle_name() const { return "cisco_ios_xr"; } augment_capabilities_function PerformanceMeasurement::get_augment_capabilities_function() const { return cisco_ios_xr_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> PerformanceMeasurement::get_namespace_identity_lookup() const { return cisco_ios_xr_namespace_identity_lookup; } bool PerformanceMeasurement::has_leaf_or_child_of_name(const std::string & name) const { if(name == "delay-profile-interface" || name == "interfaces" || name == "enable-performance-measurement") return true; return false; } PerformanceMeasurement::DelayProfileInterface::DelayProfileInterface() : advertisement(std::make_shared<PerformanceMeasurement::DelayProfileInterface::Advertisement>()) , probe(std::make_shared<PerformanceMeasurement::DelayProfileInterface::Probe>()) { advertisement->parent = this; probe->parent = this; yang_name = "delay-profile-interface"; yang_parent_name = "performance-measurement"; is_top_level_class = false; has_list_ancestor = false; } PerformanceMeasurement::DelayProfileInterface::~DelayProfileInterface() { } bool PerformanceMeasurement::DelayProfileInterface::has_data() const { if (is_presence_container) return true; return (advertisement != nullptr && advertisement->has_data()) || (probe != nullptr && probe->has_data()); } bool PerformanceMeasurement::DelayProfileInterface::has_operation() const { return is_set(yfilter) || (advertisement != nullptr && advertisement->has_operation()) || (probe != nullptr && probe->has_operation()); } std::string PerformanceMeasurement::DelayProfileInterface::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement/" << get_segment_path(); return path_buffer.str(); } std::string PerformanceMeasurement::DelayProfileInterface::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "delay-profile-interface"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::DelayProfileInterface::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::DelayProfileInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "advertisement") { if(advertisement == nullptr) { advertisement = std::make_shared<PerformanceMeasurement::DelayProfileInterface::Advertisement>(); } return advertisement; } if(child_yang_name == "probe") { if(probe == nullptr) { probe = std::make_shared<PerformanceMeasurement::DelayProfileInterface::Probe>(); } return probe; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::DelayProfileInterface::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(advertisement != nullptr) { _children["advertisement"] = advertisement; } if(probe != nullptr) { _children["probe"] = probe; } return _children; } void PerformanceMeasurement::DelayProfileInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void PerformanceMeasurement::DelayProfileInterface::set_filter(const std::string & value_path, YFilter yfilter) { } bool PerformanceMeasurement::DelayProfileInterface::has_leaf_or_child_of_name(const std::string & name) const { if(name == "advertisement" || name == "probe") return true; return false; } PerformanceMeasurement::DelayProfileInterface::Advertisement::Advertisement() : accelerated(std::make_shared<PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated>()) , periodic(std::make_shared<PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic>()) { accelerated->parent = this; periodic->parent = this; yang_name = "advertisement"; yang_parent_name = "delay-profile-interface"; is_top_level_class = false; has_list_ancestor = false; } PerformanceMeasurement::DelayProfileInterface::Advertisement::~Advertisement() { } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::has_data() const { if (is_presence_container) return true; return (accelerated != nullptr && accelerated->has_data()) || (periodic != nullptr && periodic->has_data()); } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::has_operation() const { return is_set(yfilter) || (accelerated != nullptr && accelerated->has_operation()) || (periodic != nullptr && periodic->has_operation()); } std::string PerformanceMeasurement::DelayProfileInterface::Advertisement::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement/delay-profile-interface/" << get_segment_path(); return path_buffer.str(); } std::string PerformanceMeasurement::DelayProfileInterface::Advertisement::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "advertisement"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::DelayProfileInterface::Advertisement::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::DelayProfileInterface::Advertisement::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "accelerated") { if(accelerated == nullptr) { accelerated = std::make_shared<PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated>(); } return accelerated; } if(child_yang_name == "periodic") { if(periodic == nullptr) { periodic = std::make_shared<PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic>(); } return periodic; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::DelayProfileInterface::Advertisement::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(accelerated != nullptr) { _children["accelerated"] = accelerated; } if(periodic != nullptr) { _children["periodic"] = periodic; } return _children; } void PerformanceMeasurement::DelayProfileInterface::Advertisement::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void PerformanceMeasurement::DelayProfileInterface::Advertisement::set_filter(const std::string & value_path, YFilter yfilter) { } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::has_leaf_or_child_of_name(const std::string & name) const { if(name == "accelerated" || name == "periodic") return true; return false; } PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::Accelerated() : threshold{YType::uint32, "threshold"}, minimum_change{YType::uint32, "minimum-change"}, enable{YType::empty, "enable"} { yang_name = "accelerated"; yang_parent_name = "advertisement"; is_top_level_class = false; has_list_ancestor = false; } PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::~Accelerated() { } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::has_data() const { if (is_presence_container) return true; return threshold.is_set || minimum_change.is_set || enable.is_set; } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::has_operation() const { return is_set(yfilter) || ydk::is_set(threshold.yfilter) || ydk::is_set(minimum_change.yfilter) || ydk::is_set(enable.yfilter); } std::string PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement/delay-profile-interface/advertisement/" << get_segment_path(); return path_buffer.str(); } std::string PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "accelerated"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (threshold.is_set || is_set(threshold.yfilter)) leaf_name_data.push_back(threshold.get_name_leafdata()); if (minimum_change.is_set || is_set(minimum_change.yfilter)) leaf_name_data.push_back(minimum_change.get_name_leafdata()); if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "threshold") { threshold = value; threshold.value_namespace = name_space; threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "minimum-change") { minimum_change = value; minimum_change.value_namespace = name_space; minimum_change.value_namespace_prefix = name_space_prefix; } if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } } void PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "threshold") { threshold.yfilter = yfilter; } if(value_path == "minimum-change") { minimum_change.yfilter = yfilter; } if(value_path == "enable") { enable.yfilter = yfilter; } } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::Accelerated::has_leaf_or_child_of_name(const std::string & name) const { if(name == "threshold" || name == "minimum-change" || name == "enable") return true; return false; } PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::Periodic() : interval{YType::uint32, "interval"}, threshold{YType::uint32, "threshold"}, minimum_change{YType::uint32, "minimum-change"}, disable{YType::empty, "disable"} { yang_name = "periodic"; yang_parent_name = "advertisement"; is_top_level_class = false; has_list_ancestor = false; } PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::~Periodic() { } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::has_data() const { if (is_presence_container) return true; return interval.is_set || threshold.is_set || minimum_change.is_set || disable.is_set; } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::has_operation() const { return is_set(yfilter) || ydk::is_set(interval.yfilter) || ydk::is_set(threshold.yfilter) || ydk::is_set(minimum_change.yfilter) || ydk::is_set(disable.yfilter); } std::string PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement/delay-profile-interface/advertisement/" << get_segment_path(); return path_buffer.str(); } std::string PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "periodic"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); if (threshold.is_set || is_set(threshold.yfilter)) leaf_name_data.push_back(threshold.get_name_leafdata()); if (minimum_change.is_set || is_set(minimum_change.yfilter)) leaf_name_data.push_back(minimum_change.get_name_leafdata()); if (disable.is_set || is_set(disable.yfilter)) leaf_name_data.push_back(disable.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } if(value_path == "threshold") { threshold = value; threshold.value_namespace = name_space; threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "minimum-change") { minimum_change = value; minimum_change.value_namespace = name_space; minimum_change.value_namespace_prefix = name_space_prefix; } if(value_path == "disable") { disable = value; disable.value_namespace = name_space; disable.value_namespace_prefix = name_space_prefix; } } void PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interval") { interval.yfilter = yfilter; } if(value_path == "threshold") { threshold.yfilter = yfilter; } if(value_path == "minimum-change") { minimum_change.yfilter = yfilter; } if(value_path == "disable") { disable.yfilter = yfilter; } } bool PerformanceMeasurement::DelayProfileInterface::Advertisement::Periodic::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interval" || name == "threshold" || name == "minimum-change" || name == "disable") return true; return false; } PerformanceMeasurement::DelayProfileInterface::Probe::Probe() : one_way_measurement{YType::empty, "one-way-measurement"}, interval{YType::uint32, "interval"} , burst(std::make_shared<PerformanceMeasurement::DelayProfileInterface::Probe::Burst>()) { burst->parent = this; yang_name = "probe"; yang_parent_name = "delay-profile-interface"; is_top_level_class = false; has_list_ancestor = false; } PerformanceMeasurement::DelayProfileInterface::Probe::~Probe() { } bool PerformanceMeasurement::DelayProfileInterface::Probe::has_data() const { if (is_presence_container) return true; return one_way_measurement.is_set || interval.is_set || (burst != nullptr && burst->has_data()); } bool PerformanceMeasurement::DelayProfileInterface::Probe::has_operation() const { return is_set(yfilter) || ydk::is_set(one_way_measurement.yfilter) || ydk::is_set(interval.yfilter) || (burst != nullptr && burst->has_operation()); } std::string PerformanceMeasurement::DelayProfileInterface::Probe::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement/delay-profile-interface/" << get_segment_path(); return path_buffer.str(); } std::string PerformanceMeasurement::DelayProfileInterface::Probe::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "probe"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::DelayProfileInterface::Probe::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (one_way_measurement.is_set || is_set(one_way_measurement.yfilter)) leaf_name_data.push_back(one_way_measurement.get_name_leafdata()); if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::DelayProfileInterface::Probe::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "burst") { if(burst == nullptr) { burst = std::make_shared<PerformanceMeasurement::DelayProfileInterface::Probe::Burst>(); } return burst; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::DelayProfileInterface::Probe::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(burst != nullptr) { _children["burst"] = burst; } return _children; } void PerformanceMeasurement::DelayProfileInterface::Probe::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "one-way-measurement") { one_way_measurement = value; one_way_measurement.value_namespace = name_space; one_way_measurement.value_namespace_prefix = name_space_prefix; } if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } } void PerformanceMeasurement::DelayProfileInterface::Probe::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "one-way-measurement") { one_way_measurement.yfilter = yfilter; } if(value_path == "interval") { interval.yfilter = yfilter; } } bool PerformanceMeasurement::DelayProfileInterface::Probe::has_leaf_or_child_of_name(const std::string & name) const { if(name == "burst" || name == "one-way-measurement" || name == "interval") return true; return false; } PerformanceMeasurement::DelayProfileInterface::Probe::Burst::Burst() : count{YType::uint32, "count"}, interval{YType::uint32, "interval"} { yang_name = "burst"; yang_parent_name = "probe"; is_top_level_class = false; has_list_ancestor = false; } PerformanceMeasurement::DelayProfileInterface::Probe::Burst::~Burst() { } bool PerformanceMeasurement::DelayProfileInterface::Probe::Burst::has_data() const { if (is_presence_container) return true; return count.is_set || interval.is_set; } bool PerformanceMeasurement::DelayProfileInterface::Probe::Burst::has_operation() const { return is_set(yfilter) || ydk::is_set(count.yfilter) || ydk::is_set(interval.yfilter); } std::string PerformanceMeasurement::DelayProfileInterface::Probe::Burst::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement/delay-profile-interface/probe/" << get_segment_path(); return path_buffer.str(); } std::string PerformanceMeasurement::DelayProfileInterface::Probe::Burst::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "burst"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::DelayProfileInterface::Probe::Burst::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (count.is_set || is_set(count.yfilter)) leaf_name_data.push_back(count.get_name_leafdata()); if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::DelayProfileInterface::Probe::Burst::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::DelayProfileInterface::Probe::Burst::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void PerformanceMeasurement::DelayProfileInterface::Probe::Burst::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "count") { count = value; count.value_namespace = name_space; count.value_namespace_prefix = name_space_prefix; } if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } } void PerformanceMeasurement::DelayProfileInterface::Probe::Burst::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "count") { count.yfilter = yfilter; } if(value_path == "interval") { interval.yfilter = yfilter; } } bool PerformanceMeasurement::DelayProfileInterface::Probe::Burst::has_leaf_or_child_of_name(const std::string & name) const { if(name == "count" || name == "interval") return true; return false; } PerformanceMeasurement::Interfaces::Interfaces() : interface(this, {"interface_name"}) { yang_name = "interfaces"; yang_parent_name = "performance-measurement"; is_top_level_class = false; has_list_ancestor = false; } PerformanceMeasurement::Interfaces::~Interfaces() { } bool PerformanceMeasurement::Interfaces::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<interface.len(); index++) { if(interface[index]->has_data()) return true; } return false; } bool PerformanceMeasurement::Interfaces::has_operation() const { for (std::size_t index=0; index<interface.len(); index++) { if(interface[index]->has_operation()) return true; } return is_set(yfilter); } std::string PerformanceMeasurement::Interfaces::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement/" << get_segment_path(); return path_buffer.str(); } std::string PerformanceMeasurement::Interfaces::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "interfaces"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::Interfaces::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::Interfaces::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "interface") { auto ent_ = std::make_shared<PerformanceMeasurement::Interfaces::Interface>(); ent_->parent = this; interface.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::Interfaces::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : interface.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void PerformanceMeasurement::Interfaces::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void PerformanceMeasurement::Interfaces::set_filter(const std::string & value_path, YFilter yfilter) { } bool PerformanceMeasurement::Interfaces::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interface") return true; return false; } PerformanceMeasurement::Interfaces::Interface::Interface() : interface_name{YType::str, "interface-name"}, enable_interface{YType::empty, "enable-interface"} , delay_measurement(std::make_shared<PerformanceMeasurement::Interfaces::Interface::DelayMeasurement>()) { delay_measurement->parent = this; yang_name = "interface"; yang_parent_name = "interfaces"; is_top_level_class = false; has_list_ancestor = false; } PerformanceMeasurement::Interfaces::Interface::~Interface() { } bool PerformanceMeasurement::Interfaces::Interface::has_data() const { if (is_presence_container) return true; return interface_name.is_set || enable_interface.is_set || (delay_measurement != nullptr && delay_measurement->has_data()); } bool PerformanceMeasurement::Interfaces::Interface::has_operation() const { return is_set(yfilter) || ydk::is_set(interface_name.yfilter) || ydk::is_set(enable_interface.yfilter) || (delay_measurement != nullptr && delay_measurement->has_operation()); } std::string PerformanceMeasurement::Interfaces::Interface::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-perf-meas-cfg:performance-measurement/interfaces/" << get_segment_path(); return path_buffer.str(); } std::string PerformanceMeasurement::Interfaces::Interface::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "interface"; ADD_KEY_TOKEN(interface_name, "interface-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::Interfaces::Interface::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interface_name.is_set || is_set(interface_name.yfilter)) leaf_name_data.push_back(interface_name.get_name_leafdata()); if (enable_interface.is_set || is_set(enable_interface.yfilter)) leaf_name_data.push_back(enable_interface.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::Interfaces::Interface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "delay-measurement") { if(delay_measurement == nullptr) { delay_measurement = std::make_shared<PerformanceMeasurement::Interfaces::Interface::DelayMeasurement>(); } return delay_measurement; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::Interfaces::Interface::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(delay_measurement != nullptr) { _children["delay-measurement"] = delay_measurement; } return _children; } void PerformanceMeasurement::Interfaces::Interface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interface-name") { interface_name = value; interface_name.value_namespace = name_space; interface_name.value_namespace_prefix = name_space_prefix; } if(value_path == "enable-interface") { enable_interface = value; enable_interface.value_namespace = name_space; enable_interface.value_namespace_prefix = name_space_prefix; } } void PerformanceMeasurement::Interfaces::Interface::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interface-name") { interface_name.yfilter = yfilter; } if(value_path == "enable-interface") { enable_interface.yfilter = yfilter; } } bool PerformanceMeasurement::Interfaces::Interface::has_leaf_or_child_of_name(const std::string & name) const { if(name == "delay-measurement" || name == "interface-name" || name == "enable-interface") return true; return false; } PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::DelayMeasurement() : enable_delay_measurement{YType::empty, "enable-delay-measurement"}, advertise_delay{YType::uint32, "advertise-delay"} { yang_name = "delay-measurement"; yang_parent_name = "interface"; is_top_level_class = false; has_list_ancestor = true; } PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::~DelayMeasurement() { } bool PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::has_data() const { if (is_presence_container) return true; return enable_delay_measurement.is_set || advertise_delay.is_set; } bool PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::has_operation() const { return is_set(yfilter) || ydk::is_set(enable_delay_measurement.yfilter) || ydk::is_set(advertise_delay.yfilter); } std::string PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "delay-measurement"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enable_delay_measurement.is_set || is_set(enable_delay_measurement.yfilter)) leaf_name_data.push_back(enable_delay_measurement.get_name_leafdata()); if (advertise_delay.is_set || is_set(advertise_delay.yfilter)) leaf_name_data.push_back(advertise_delay.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enable-delay-measurement") { enable_delay_measurement = value; enable_delay_measurement.value_namespace = name_space; enable_delay_measurement.value_namespace_prefix = name_space_prefix; } if(value_path == "advertise-delay") { advertise_delay = value; advertise_delay.value_namespace = name_space; advertise_delay.value_namespace_prefix = name_space_prefix; } } void PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enable-delay-measurement") { enable_delay_measurement.yfilter = yfilter; } if(value_path == "advertise-delay") { advertise_delay.yfilter = yfilter; } } bool PerformanceMeasurement::Interfaces::Interface::DelayMeasurement::has_leaf_or_child_of_name(const std::string & name) const { if(name == "enable-delay-measurement" || name == "advertise-delay") return true; return false; } } }
32.368421
219
0.724173
[ "vector" ]
be8daead0177c1d112a7f2c3772d05ed0337ab4d
1,018
cpp
C++
1201-1300/1245-Tree Diameter/1245-Tree Diameter.cpp
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
1201-1300/1245-Tree Diameter/1245-Tree Diameter.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
1201-1300/1245-Tree Diameter/1245-Tree Diameter.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: int treeDiameter(vector<vector<int>>& edges) { int n = edges.size(); if (n == 0) return 0; vector<vector<int>> graph(n + 1); for (auto& e : edges) { graph[e[0]].push_back(e[1]); graph[e[1]].push_back(e[0]); } int maxLen = 0; dfs(graph, 0, -1, maxLen); return maxLen; } private: int dfs(vector<vector<int>>& graph, int curr, int prev, int& maxLen) { int maxLen1 = 0, maxLen2 = 0; for (int next : graph[curr]) { if (next != prev) { int nextLen = dfs(graph, next, curr, maxLen); if (nextLen > maxLen1) { maxLen2 = maxLen1; maxLen1 = nextLen; } else if (nextLen > maxLen2) { maxLen2 = nextLen; } } } maxLen = max(maxLen, maxLen1 + maxLen2); return 1 + maxLen1; } };
27.513514
74
0.436149
[ "vector" ]
be94fc48c73178d934abe97fc6e61cf5d9ae4553
5,253
cpp
C++
VideoCube/VideoCubeCV/keybertwrapper.cpp
Kvazikot/VideoProjects
899cd047dd791b0e2f33d40cf6e11fe949333329
[ "MIT" ]
null
null
null
VideoCube/VideoCubeCV/keybertwrapper.cpp
Kvazikot/VideoProjects
899cd047dd791b0e2f33d40cf6e11fe949333329
[ "MIT" ]
null
null
null
VideoCube/VideoCubeCV/keybertwrapper.cpp
Kvazikot/VideoProjects
899cd047dd791b0e2f33d40cf6e11fe949333329
[ "MIT" ]
null
null
null
/* + - - - + - + - - + - + - + copyright by Vladimir Baranov (Kvazikot) <br> + - + - + email: vsbaranov83@gmail.com <br> + - + - + github: http://github.com/Kvazikot/VideoProjects <br> ) ( /( (\___/) )\ ( #) \ ('')| ( # ||___c\ > '__|| ||**** ),_/ **'| .__ |'* ___| |___*'| \_\ |' ( ~ ,)'| (( |' /(. ' .)\ | \\_|_/ <_ _____> \______________ / '-, \ / ,-' ______ \ b'ger / (// \\) __/ / \ './_____/ */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include <QDebug> #include <string> #include <iostream> #include "print.h" #include "keybertwrapper.h" static char doc11[] = "Supervised learning is the machine learning task of learning a function that \n \ maps an input to an output based on example input-output pairs. It infers a \n \ function from labeled training data consisting of a set of training examples. \n \ In supervised learning, each example is a pair consisting of an input object \n \ (typically a vector) and a desired output value (also called the supervisory signal). \n \ A supervised learning algorithm analyzes the training data and produces an inferred function, \n \ which can be used for mapping new examples. An optimal scenario will allow for the \n \ algorithm to correctly determine the class labels for unseen instances. This requires \n \ the learning algorithm to generalize from the training data to unseen situations in a \n \ reasonable way (see inductive bias)."; static char doc22[] = "В известном мысленном эксперименте Джона Уиллера \n \ с двумя щелями и отложенном выборе был предложена[1] проверка гипотезы о том что прошлое можно изменить стирая информацию о наблюдении в будущем. \n\ Неизвестна точная дата когда Уилеру пришла идея эксперимента с квантовым ластиком. \n \ Я сейчас не говорю о буквальном сценарии когда из машины времени выходят голые терминаторы. \n \ Это сделано ради потехи публики как и батарейки в \"матрице\", ведь голивудские фильмы расчитанны на массового зрителя. \n \ Я говорю о возможности предоставляемые квантовой теорией по стиранию информации в будущем, чтобы влиять на прошлое не имеет значения насколько отдаленное. \n \ Дельта t может быть 5 миллисекунд для обнаружения раковой клетки, а может быть возраст рождения вселенной. \n"; static char code_template_py4[] = "from keybert import KeyBERT \n\ doc = \"\"\" \n\ %1 \n\ \"\"\" \n\ doc = 'Supervised learning is the machine learning task of learning a function that' \n\ kw_model = KeyBERT() \n\ list = kw_model.extract_keywords(doc) \n\ print(list)\ "; int ParsePyList(std::string code, std::map<std::string, double>& result_map) { PyObject *dict = NULL, *run_result = NULL, *pList = NULL; dict = PyDict_New(); if (!dict) return -1; run_result = PyRun_String(code.c_str(), Py_file_input, dict, dict); if (!run_result) return -1; pList = PyDict_GetItemString(dict,"list"); int n_keywords = PyList_Size(pList); for(int i=0; i < n_keywords; i++) { PyObject* item = PyList_GetItem(pList, i); PyObject* kw = PyTuple_GetItem(item, 0); //PyLong_FromLong() PyObject* probability = PyTuple_GetItem(item, 1); double second = PyFloat_AsDouble(probability); Py_ssize_t len = 0; const char* first = PyUnicode_AsUTF8AndSize(kw, &len); std::string key = first; result_map[key] = second; qDebug() << key.c_str(); } return 1; } KeyBERTWrapper::KeyBERTWrapper(QObject *parent) : QObject(parent) { } void KeyBERTWrapper::getKeywords(std::vector<std::string>& keywords_vector) { for(auto i=keywordsMap.begin(); i != keywordsMap.end(); i++) keywords_vector.push_back((*i).first.c_str()); } int KeyBERTWrapper::extractKeywordsFromText(QString text) { script = (char*)malloc(MAX_SYMBOLS); PyObject *pName, *pModule, *pDict, *pClass, *pInstance; // Initialize the Python interpreter Py_Initialize(); // Calculating checksum of code auto data = QByteArray::fromRawData(reinterpret_cast<const char *>(code_template_py4), sizeof(code_template_py4)); quint16 sum = 0; int i = 0; int len = data.length() - 3; for (i = 0; i < len; ++i) sum += quint8(data.at(i)); sum = -sum; qDebug("sum = %04x", sum); quint8 msb = sum >> 8; quint8 lsb = sum & 0xFF; qDebug("MSB = %02x, LSB = %02x", msb, lsb); if(msb==0xba && lsb ==0xb8 && lsb > 2 && msb > 1) { if(text.size() < MAX_SYMBOLS) { QString code = QString(code_template_py4).arg(text); int result = ParsePyList(code.toStdString(), keywordsMap); if( result ) { qDebug() << "result of code execution!\n" ; for(auto i=keywordsMap.begin(); i != keywordsMap.end(); i++) qDebug() << (*i).first.c_str(); } } } Py_Finalize(); return keywordsMap.size(); }
36.479167
159
0.60613
[ "object", "vector" ]
be9677bfe4fdc7df1c47ad3edc20f50652e81251
14,989
cpp
C++
src/gui/src/core/interfaces/impl/iota-node.cpp
MatthewDarnell/iota-simplewallet
aa3449bae3023e292ad47a9fa72213e279367b7a
[ "MIT" ]
1
2020-11-19T07:18:44.000Z
2020-11-19T07:18:44.000Z
src/gui/src/core/interfaces/impl/iota-node.cpp
MatthewDarnell/iota-simplewallet
aa3449bae3023e292ad47a9fa72213e279367b7a
[ "MIT" ]
null
null
null
src/gui/src/core/interfaces/impl/iota-node.cpp
MatthewDarnell/iota-simplewallet
aa3449bae3023e292ad47a9fa72213e279367b7a
[ "MIT" ]
null
null
null
// Copyright (c) 2018-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "iota-node.hpp" #include <QJsonDocument> #include <QJsonValue> #include <QJsonArray> #include <QPointer> #include <QDebug> #include <QCoreApplication> #include <QStandardPaths> #include <QDir> #include <sstream> #include <iota/iota-simplewallet.h> namespace interfaces { static std::vector<QPointer<IotaNode>> _nodes; static void ForEachDeliverEvent(std::function<void(IotaNode&)> functor) { _nodes.erase(std::remove_if(std::begin(_nodes), std::end(_nodes), [](const auto &node) { return node.isNull(); }), std::end(_nodes)); std::for_each(std::begin(_nodes), std::end(_nodes), [functor](auto &node) { functor(*node); }); } void* IotaNode::OnBalanceChanged(const char *payload) { auto obj = QJsonDocument::fromJson(QByteArray(payload)).object(); ForEachDeliverEvent([username = obj.value("username").toString(), balance = obj.value("balance").toString()](IotaNode &node) { Q_EMIT node.balanceChanged(username, balance); }); return nullptr; } void* IotaNode::OnNodeUpdated(const char *payload) { auto obj = QJsonDocument::fromJson(QByteArray(payload)).object(); ForEachDeliverEvent([obj](IotaNode &node) { auto ptr = &node; QTimer::singleShot(0, ptr, [=] { ptr->updateNodeStatus(obj); }); }); return nullptr; } void* IotaNode::OnTransactionReceived(const char *payload) { auto obj = QJsonDocument::fromJson(QByteArray(payload)).object(); ForEachDeliverEvent([obj, username = obj.value("username").toString()](IotaNode &node) { Q_EMIT node.transactionChanged(username, obj); }); return nullptr; } void* IotaNode::OnTransactionSent(const char *payload) { auto obj = QJsonDocument::fromJson(QByteArray(payload)).object(); ForEachDeliverEvent([obj, username = obj.value("username").toString()](IotaNode &node) { Q_EMIT node.transactionChanged(username, obj); }); return nullptr; } void* IotaNode::OnSentTransactionConfirmed(const char *payload) { auto obj = QJsonDocument::fromJson(QByteArray(payload)).object(); ForEachDeliverEvent([obj, username = obj.value("username").toString()](IotaNode &node) { Q_EMIT node.transactionChanged(username, obj); }); return nullptr; } void* IotaNode::OnReceivedTransactionConfirmed(const char *payload) { auto obj = QJsonDocument::fromJson(QByteArray(payload)).object(); ForEachDeliverEvent([obj, username = obj.value("username").toString()](IotaNode &node) { Q_EMIT node.transactionChanged(username, obj); }); return nullptr; } void IotaNode::initError(const std::string &message) { } bool IotaNode::parseParameters(int argc, const char * const argv[], std::string &error) { return true; } bool IotaNode::readConfigFiles(std::string &error) { return true; } void IotaNode::selectParams(const std::string &network) { } uint64_t IotaNode::getAssumedBlockchainSize() { return 0; } uint64_t IotaNode::getAssumedChainStateSize() { return 0; } QString IotaNode::getNetwork() { return std::get<2>(_appInfo); } std::string IotaNode::getDataDir() { static const auto genericDataDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); QDir dataDir(QString("%1/Iota/Iota-Qt").arg(genericDataDir)); if (!dataDir.exists()) { if (!dataDir.mkpath(".")) { qDebug("Failed to create dataDir at location: %s\n", dataDir.absolutePath().toLatin1().data()); throw std::runtime_error("Failed to create datadir"); } } return dataDir.absolutePath().toStdString(); } void IotaNode::initLogging() { } void IotaNode::initParameterInteraction() { } std::string IotaNode::getWarnings() { return {}; } uint32_t IotaNode::getLogCategories() { return 0; } bool IotaNode::baseInitialize() { auto dataDirPath = getDataDir(); init_iota_simplewallet(dataDirPath.data()); return true; } bool IotaNode::appInitMain() { init_events(); start_threads(); registerEvents(); loadAccounts(); return true; } void IotaNode::appShutdown() { shutdown_threads(); join_threads(); shutdown_iota_simplewallet(); shutdown_events(); } void IotaNode::startShutdown() { } bool IotaNode::shutdownRequested() { return false; } void IotaNode::setupServerArgs() { } bool IotaNode::getHeaderTip(int &height, int64_t &block_time) { return false; } int IotaNode::getNumBlocks(bool solid) { return (solid ? _latestSolidMilestone : _latestMilestone).first; } QString IotaNode::getLatestMilestone(bool solid) { return (solid ? _latestSolidMilestone : _latestMilestone).second; } std::string IotaNode::executeRpc(const std::string &command, const std::vector<std::string> params, const std::string &uri) { std::stringstream ss; ss << command; for(auto &&param : params) { ss << " " << param; } c_string_unique_ptr result(parse_debug_command(ss.str().data())); return std::string(result.get()); } QString IotaNode::getAppName() { return std::get<0>(_appInfo); } QString IotaNode::getAppVersion() { return std::get<1>(_appInfo); } int64_t IotaNode::getLastBlockTime() { return 0; } double IotaNode::getVerificationProgress() { return 0; } bool IotaNode::isInitialBlockDownload() { return false; } bool IotaNode::getReindex() { return false; } bool IotaNode::getImporting() { return false; } void IotaNode::setNetworkActive(bool active) { } bool IotaNode::getNetworkActive() { return true; } std::vector<std::string> IotaNode::listRpcCommands() { return {}; } void IotaNode::rpcSetTimerInterfaceIfUnset(RPCTimerInterface *iface) { } void IotaNode::rpcUnsetTimerInterface(RPCTimerInterface *iface) { } std::string IotaNode::getWalletDir() { return {}; } std::vector<std::string> IotaNode::listWalletDir() { return {}; } std::vector<std::unique_ptr<Wallet> > IotaNode::getWallets() { std::vector<std::unique_ptr<Wallet>> res; for(auto &&acc : _accounts) { res.emplace_back(createIotaWallet(acc)); } return res; } std::unique_ptr<Wallet> IotaNode::loadWallet(const std::string &username, const SecureString &passphrase, const SecureString &seed, std::string &error) { SecureString password(passphrase); auto r = import_account(username.data(), &password[0], seed.data()); if(r < 0) { error = "Failed to import account"; return {}; } password.assign(passphrase); verify_login(username.data(), &password[0], 1); loadAccounts(); UserAccount acc; if(tryGetUserAccount(QString::fromStdString(username), acc)) { return createIotaWallet(acc); } return {}; } std::unique_ptr<Wallet> IotaNode::loadWallet(const std::string &username, const SecureString &passphrase, const std::string &path, std::string &error) { UserAccount acc; if(tryGetUserAccount(QString::fromStdString(username), acc)) { error = "Account with this username already exists"; } SecureString password(passphrase); c_string_unique_ptr r_username(import_account_state(&password[0], path.data())); if(!r_username) { error = "Failed to import account"; return {}; } password.assign(passphrase); verify_login(username.data(), &password[0], 1); loadAccounts(); if(tryGetUserAccount(QString::fromStdString(r_username.get()), acc)) { return createIotaWallet(acc); } error = "Failed to find imported account"; return {}; } WalletCreationStatus IotaNode::createWallet(const SecureString &passphrase, uint64_t wallet_creation_flags, const std::string &name, std::string &error, std::vector<std::string> &warnings, std::unique_ptr<Wallet> &result) { SecureString password(passphrase); create_account(name.data(), &password[0]); password.assign(passphrase); verify_login(name.data(), &password[0], 1); loadAccounts(); UserAccount acc; if(tryGetUserAccount(QString::fromStdString(name), acc)) { result = createIotaWallet(acc); return WalletCreationStatus::SUCCESS; } return WalletCreationStatus::FAILURE; } std::unique_ptr<Handler> IotaNode::handleInitMessage(Node::InitMessageFn fn) { return MakeHandler({}); } std::unique_ptr<Handler> IotaNode::handleMessageBox(Node::MessageBoxFn fn) { return MakeHandler({}); } std::unique_ptr<Handler> IotaNode::handleQuestion(Node::QuestionFn fn) { return MakeHandler({}); } std::unique_ptr<Handler> IotaNode::handleShowProgress(Node::ShowProgressFn fn) { return MakeHandler({}); } std::unique_ptr<Handler> IotaNode::handleLoadWallet(Node::LoadWalletFn fn) { return MakeHandler({}); } std::unique_ptr<Handler> IotaNode::handleNotifyNumConnectionsChanged(Node::NotifyNumConnectionsChangedFn fn) { auto conn = connect(this, &IotaNode::connectionsNumChanged, this, [fn](int newConnectionsNum) { fn(newConnectionsNum); } ); return MakeHandler([conn] { disconnect(conn);}); } std::unique_ptr<Handler> IotaNode::handleNotifyNetworkActiveChanged(Node::NotifyNetworkActiveChangedFn fn) { return MakeHandler({}); } std::unique_ptr<Handler> IotaNode::handleNotifyAlertChanged(Node::NotifyAlertChangedFn fn) { return MakeHandler({}); } std::unique_ptr<Handler> IotaNode::handleBannedListChanged(Node::BannedListChangedFn fn) { return MakeHandler({}); } std::unique_ptr<Handler> IotaNode::handleNotifyBlockTip(Node::NotifyBlockTipFn fn) { auto conn = connect(this, &IotaNode::latestMiltestoneChanged, this, [fn](auto newMilestoneIndex, auto newMilestone) { fn(newMilestoneIndex, newMilestone.toStdString()); }); return MakeHandler([conn] { disconnect(conn); }); } std::unique_ptr<Handler> IotaNode::handleNotifyAppInfochanged(NotifyAppInfoChangedFn fn) { auto conn = connect(this, &IotaNode::appInfoChanged, this, [fn](auto newAppName, auto newAppVersion, auto newConnectedNode){ fn(newAppName.toStdString(), newAppVersion.toStdString(), newConnectedNode.toStdString()); }); return MakeHandler([conn] {disconnect(conn); }); } std::unique_ptr<Handler> IotaNode::handleNotifyHeaderTip(Node::NotifyHeaderTipFn fn) { return MakeHandler({}); } void IotaNode::updateNodeStatus(QJsonObject nodeInfo) { _nodeInfo = nodeInfo; _latestSolidMilestone = qMakePair(_nodeInfo.value("latestSolidSubtangleMilestoneIndex").toInt(), _nodeInfo.value("latestSolidSubtangleMilestone").toString()); setLatestMiltesone(qMakePair(_nodeInfo.value("latestMilestoneIndex").toInt(), _nodeInfo.value("latestMilestone").toString())); auto node = _nodeInfo.value("node").toObject(); auto connectedNode = QString("%1:%2").arg(node.value("host").toString()).arg(node.value("port").toInt()); setAppInfo(std::make_tuple(_nodeInfo.value("appName").toString(), _nodeInfo.value("appVersion").toString(), connectedNode)); setConnectionsNum(_nodeInfo.value("neighbors").toInt()); } void IotaNode::setLatestMiltesone(QPair<int, QString> newMilestone) { if(newMilestone != _latestMilestone) { _latestMilestone = newMilestone; emit latestMiltestoneChanged(newMilestone.first, newMilestone.second); } } void IotaNode::setAppInfo(std::tuple<QString, QString, QString> newAppInfo) { if(newAppInfo != _appInfo) { _appInfo = newAppInfo; emit appInfoChanged(std::get<0>(newAppInfo), std::get<1>(newAppInfo), std::get<2>(newAppInfo)); } } void IotaNode::setConnectionsNum(int connectionsNum) { if(connectionsNum != _connectionsNum) { _connectionsNum = connectionsNum; emit connectionsNumChanged(connectionsNum); } } void IotaNode::loadAccounts() { _accounts.clear(); c_string_unique_ptr accounts(get_accounts()); for(auto val : QJsonDocument::fromJson(QByteArray(accounts.get())).array()) { _accounts.emplace_back(UserAccount::FromJson(val.toObject())); } } void IotaNode::registerEvents() { register_callback("node_updated", OnNodeUpdated); register_callback("balance_changed", OnBalanceChanged); register_callback("transaction_received", OnTransactionReceived); register_callback("transaction_sent", OnTransactionSent); register_callback("sent_transaction_confirmed", OnSentTransactionConfirmed); register_callback("transaction_received_confirmed", OnReceivedTransactionConfirmed); } bool IotaNode::tryGetUserAccount(const QString &username, UserAccount &account) const { auto it = std::find_if(std::begin(_accounts), std::end(_accounts), [name = username](const auto &acc) { return acc.username == name; }); if(it != std::end(_accounts)) { account = *it; return true; } return false; } std::unique_ptr<Wallet> IotaNode::createIotaWallet(UserAccount account) { auto wallet = std::make_unique<IotaWallet>(account); QPointer<IotaWallet> walletRaw(wallet.get()); connect(this, &IotaNode::accountChanged, walletRaw, [walletRaw, this](QString username) { if(walletRaw && walletRaw->getWalletName() == username.toStdString()) { UserAccount acc; if(this->tryGetUserAccount(username, acc)) { walletRaw->onAccountUpdated(acc, _latestMilestone.first); } } }); connect(this, &IotaNode::balanceChanged, walletRaw, [walletRaw, this](QString username, QString balance) { if(walletRaw && walletRaw->getWalletName() == username.toStdString()) { UserAccount acc; if(this->tryGetUserAccount(username, acc)) { walletRaw->onAccountBalanceUpdated(balance); } } }); connect(this, &IotaNode::transactionChanged, walletRaw, [walletRaw, this](QString username, QJsonObject payload) { if(walletRaw && walletRaw->getWalletName() == username.toStdString()) { UserAccount acc; if(this->tryGetUserAccount(username, acc)) { walletRaw->onTransactionChanged(payload); } } }); walletRaw->onAccountUpdated(account, _latestMilestone.first); return wallet; } //! Return implementation of Node interface. std::unique_ptr<Node> MakeNode() { auto node = std::make_unique<IotaNode>(); _nodes.emplace_back(node.get()); return node; } } // namespace interfaces
25.71012
151
0.674028
[ "object", "vector", "solid" ]
be992563856262f0fee3711df65426a2aed2395e
3,469
cpp
C++
LeetCode/14_longest_common_prefix.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
LeetCode/14_longest_common_prefix.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
LeetCode/14_longest_common_prefix.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <map> #include <algorithm> #include <cstdlib> #include <string> using namespace std; class Solution { public: // VERTICAL SCANNING // string longestCommonPrefix(vector<string>& strs) { // if (strs.size() == 0) return ""; // string out = "", temp = ""; // bool flag = false; // int j = 0; // while(j >= 0){ // for (int i = 0; i < strs.size() - 1; i++){ // if(!strs[i][j]){ // flag = true; // cout << "in1 "; // break; // } // if(strs[i][j] != strs[i+1][j]){ // flag = true; // break; // } // temp = strs[i][j]; // cout<<j << ' ' << i << ' ' << out << ' ' << strs[i] << '\n'; // } // cout << "outsdsasd\n"; // if(flag){ // break; // } // else{ // out += temp; // } // j++; // } // return out; // } // DIVIDE AND CONQUER // string first_common_substring(string s1, string s2){ // cout << "fcb "; // int i = 0; // string out = ""; // int mlen = min(s1.size(), s2.size()); // while(i < mlen){ // if(s1[i] == s2[i]){ // out += s1[i]; // } // else{ // break; // } // i++; // } // cout << "out: " << out << '\n'; // return out; // } // string rec_prefix(vector<string>& strs, int in, int la){ // cout << in << ' ' << la<<'\n'; // if(la == in){ // return strs[in]; // } // else{ // int mid = (la + in) / 2; // string str1, str2; // str1 = rec_prefix(strs, in, mid); // str2 = rec_prefix(strs, mid + 1, la); // return first_common_substring(str1, str2); // } // } // string longestCommonPrefix(vector<string>& strs) { // if (strs.size() == 0) return ""; // return rec_prefix(strs, 0, strs.size() - 1); // } // BINARY SEARCH bool isCommonPrefix(vector<string>& strs, int strlen){ string strch = strs[0].substr(0, strlen); for(int i = 1; i < strs.size(); i++){ if(strs[i].substr(0, strlen) != strch){ return false; } } return true; } string longestCommonPrefix(vector<string>& strs) { if (strs.size() == 0) return ""; int minlen = INT_MAX; for (int i = 0; i < strs.size(); i++){ int strlen = strs[i].size(); minlen = min(minlen, strlen); } int in = 0, la = minlen; while(in <= la){ int mid = (la + in) / 2; if(isCommonPrefix(strs, mid)){ in = mid + 1; } else{ la = mid - 1; } } return strs[0].substr(0, (la + in) / 2); } }; int main() { Solution sol; vector<string> strs = {"flower","flow","flight"}; // vector<string> strs = {"dog","racecar","car","cat"}; cout << sol.longestCommonPrefix(strs); return 0; }
27.531746
80
0.373306
[ "vector" ]
bea4a455dc782d70d50b9545360286ebabd244dc
3,192
cpp
C++
src/PIDFile.cpp
mistralol/libclientserver
b90837149715d396cf68c2e82c539971e7efeb80
[ "MIT" ]
4
2016-03-30T14:33:31.000Z
2021-07-12T06:07:34.000Z
src/PIDFile.cpp
mistralol/libclientserver
b90837149715d396cf68c2e82c539971e7efeb80
[ "MIT" ]
null
null
null
src/PIDFile.cpp
mistralol/libclientserver
b90837149715d396cf68c2e82c539971e7efeb80
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <string> #include <sstream> #include <sys/stat.h> #include <sys/file.h> #include <sys/types.h> #include <fcntl.h> #include <libclientserver.h> PIDFile::PIDFile(std::string Filename) { m_IsOwner = false; m_filename = Filename; } PIDFile::~PIDFile() { if (IsOwner()) { Remove(); } } /** * Create * * Create a new PIDFile using the filename that was specified in the constructor. * The function will return true if it was capable of creating a pid file. * The function will fail if the pid file already exists and has an active owner * An active owner is checked by comaring the current process exe filename with * the process who's pid is in the existing pid file */ bool PIDFile::Create() { int fd = open(m_filename.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP); FILE *file = NULL; int tpid = -1; int ret = 0; if (IsOwner()) abort(); //Error with caller attempting to create pidfile twice if (fd < 0) { switch(errno) { case EEXIST: //Lets see if we can fix fd file = fopen(m_filename.c_str(), "r"); if (!file) return false; ret = fscanf(file, "%d", &tpid); fclose(file); if (ret != 1) //Issue here is that we have an unparsable pid file. Should we remove it? return false; do { std::string self; std::string pidexe; if (GetOwnExePath(&self) == false) return false; if (GetPIDExePath(tpid, &pidexe) == true) { if (self == pidexe) return false; //The pid in the file matchs us and is a valid process } if (unlink(m_filename.c_str()) < 0) //Not "us" just overwrite it abort(); fd = open(m_filename.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP); if (fd < 0) return false; } while(0); break; default: return false; } } FILE *fp = fdopen(fd, "w"); if (!fp) abort(); //Should never happen fprintf(fp, "%d\n", getpid()); fclose(fp); m_IsOwner = true; return true; } /** * Remove * * After calling Create this function can be used to remove the pid file * If the PIDFile is invalid and is not currently owner by the process * calling Remove will call abort. */ void PIDFile::Remove() { if (IsOwner() == false) abort(); //Your not the owner if (unlink(m_filename.c_str()) < 0) abort(); //We should be the owner of this file m_IsOwner = false; } /** * IsOwner * * This function can be used to determin if it is safe to call the Remove function * The return value will be true if a valid PIDFIle was created by the object but not yet removed */ bool PIDFile::IsOwner() { return m_IsOwner; } bool PIDFile::GetOwnExePath(std::string *name) { char buf[256]; if (readlink("/proc/self/exe", buf, sizeof(buf)) < 0) return false; *name = buf; return true; } bool PIDFile::GetPIDExePath(int pid, std::string *name) { char buf1[256]; char buf2[256]; sprintf(buf1, "/proc/%d/exe", pid); int ret = readlink(buf1, buf2, sizeof(buf2)); if (ret < 0) return false; buf2[ret] = 0; *name = buf2; return true; }
20.461538
97
0.638158
[ "object" ]
beb3fc780366e337807abbf272b11f51aaae5465
5,957
cpp
C++
src/BackSeatDriver.cpp
fossabot/back-seat-driver
08272bafab307d9fc07b8c16d611a5b5fc9c2ccb
[ "MIT" ]
1
2017-07-15T15:27:30.000Z
2017-07-15T15:27:30.000Z
src/BackSeatDriver.cpp
fossabot/back-seat-driver
08272bafab307d9fc07b8c16d611a5b5fc9c2ccb
[ "MIT" ]
2
2020-02-01T06:00:31.000Z
2021-03-04T19:19:35.000Z
src/BackSeatDriver.cpp
fossabot/back-seat-driver
08272bafab307d9fc07b8c16d611a5b5fc9c2ccb
[ "MIT" ]
3
2017-07-17T23:48:01.000Z
2021-03-04T19:17:31.000Z
/* * BackSeatDriver.cpp * * Created on: Jul 16, 2014 * Author: Konstantin Gredeskoul * * (c) 2014 All rights reserved. Please see LICENSE. */ #include "BackSeatDriver.h" #include <math.h> BackSeatDriver::BackSeatDriver(BackSeatDriver_IMotorAdapter *adapter) { _adapter = adapter; _debug = false; _initMs = millis(); _lastDebugMs = 0; _turningSpeedPercent = _movingSpeedPercent = 100; _turningDelayCoefficient = 7; // multiplier for how long to wait for a turn. stop(); } void BackSeatDriver::attach() { _adapter->attach(); } void BackSeatDriver::detach() { _adapter->detach(); } void BackSeatDriver::goForward(uint8_t speedPercent) { if (_currentSpeedPercent == ((signed short) speedPercent)) return; if (_debug) { sprintf(_logBuffer, "goForward(%3d), currentSpeed = %3d", speedPercent, _currentSpeedPercent); log(); } _currentSpeedPercent = (signed short) constrain(speedPercent, 0, 100); moveAtCurrentSpeed(); } void BackSeatDriver::goBackward(uint8_t speedPercent) { if (_currentSpeedPercent == ((signed short) speedPercent)) return; if (_debug) { sprintf(_logBuffer, "goBackward(%d)", speedPercent); log(); } _currentSpeedPercent = -((signed short) constrain(speedPercent, 0, 100)); moveAtCurrentSpeed(); } void BackSeatDriver::goForward(uint8_t speedPercent, unsigned int durationMs, maneuverCallback callback) { if (_debug) { sprintf(_logBuffer, "goForward(%d, %d, callback=%s)", speedPercent, durationMs, (callback == NULL ? "no" : "yes")); log(); } startManeuverTimer(durationMs, MANEUVER_FORWARD, speedPercent, callback); goForward(speedPercent); } void BackSeatDriver::goBackward(uint8_t speedPercent, unsigned int durationMs, maneuverCallback callback) { if (_debug) { sprintf(_logBuffer, "goBackward(%d, %d, callback=%s)", speedPercent, durationMs, (callback == NULL ? "no" : "yes")); log(); } startManeuverTimer(durationMs, MANEUVER_BACK, speedPercent, callback); goBackward(speedPercent); } void BackSeatDriver::turn(signed short angle, maneuverCallback callback) { if (_debug) { sprintf(_logBuffer, "turn(%d, callback=%s)", angle, (callback == NULL ? "no" : "yes")); log(); } if (abs(_currentSpeedPercent) > 0) stop(); signed short speed = 100 * (angle == 0 ? 1 : abs(angle) / angle); speed = (signed short) (1.0f * (float)speed * (float)_turningSpeedPercent / 100.0f); moveAtSpeed(speed, -speed, _turningSpeedPercent); startManeuverTimer(abs(angle) * _turningDelayCoefficient, MANEUVER_TURN, angle, callback); } void BackSeatDriver::stop() { if (_debug) { sprintf(_logBuffer, "stop()"); log(); } _currentSpeedPercent = 0; stopManeuverTimer(); moveAtCurrentSpeed(); } bool BackSeatDriver::isMoving() { return (_currentSpeedPercent != 0); } bool BackSeatDriver::isManeuvering() { checkManeuveringState(); return _maneuver.running; } void BackSeatDriver::debug(bool debugEnabled) { _debug = debugEnabled; } void BackSeatDriver::setMovingSpeedPercent(unsigned short movingSpeedPercent) { if (movingSpeedPercent >= 0 && movingSpeedPercent <= 100) { _movingSpeedPercent = movingSpeedPercent; } } void BackSeatDriver::setTurningSpeedPercent(unsigned short turningSpeedPercent) { if (turningSpeedPercent >= 0 && turningSpeedPercent <= 100) { _turningSpeedPercent = turningSpeedPercent; } } void BackSeatDriver::setTurningDelayCoefficient(unsigned short turningDelayCoefficient) { _turningDelayCoefficient = turningDelayCoefficient; } // // Private void BackSeatDriver::moveAtSpeed(signed short leftPercent, signed short rightPercent, unsigned short adjustmentPercent) { leftPercent = (signed short) (1.0 * (float)(leftPercent) * adjustmentPercent / 100.0); rightPercent = (signed short) (1.0 * (float)(rightPercent) * adjustmentPercent / 100.0); _adapter->move(leftPercent, rightPercent); } void BackSeatDriver::moveAtCurrentSpeed() { moveAtSpeed(_currentSpeedPercent, _currentSpeedPercent, _movingSpeedPercent); } void BackSeatDriver::stopManeuverTimer() { _maneuver.running = false; _maneuver.durationMs = 0; _maneuver.startMs = 0; _maneuver.type = 0; _maneuver.parameter = 0; _maneuver.callback = NULL; } void BackSeatDriver::checkManeuveringState() { if (_maneuver.running && millis() - _maneuver.startMs > _maneuver.durationMs) { maneuver currentManeuver = _maneuver; // copy maneuver so that _maneuver can be reset stop(); // call the callback (if defined) using previously saved poiner // start another maneuver, and yet reset _maneuverCallback // if no new maneuver was started. if (currentManeuver.callback != NULL) { const char *callbackType; switch (currentManeuver.type) { case MANEUVER_BACK: callbackType = "backward"; break; case MANEUVER_FORWARD: callbackType = "forward"; break; case MANEUVER_TURN: callbackType = "turn"; break; default: callbackType = "unknown"; } if (_debug) { sprintf(_logBuffer, "running callback after %s(%d)", callbackType, currentManeuver.parameter); log(); } currentManeuver.callback(currentManeuver.type, currentManeuver.parameter); } } } void BackSeatDriver::startManeuverTimer(unsigned int durationMs, uint8_t type, signed short parameter, maneuverCallback callback) { _maneuver.callback = callback; _maneuver.startMs = millis(); _maneuver.durationMs = durationMs; _maneuver.running = true; _maneuver.type = type; _maneuver.parameter = parameter; } void BackSeatDriver::logForward() { uint32_t ms = millis(); if (ms - _lastDebugMs > MIN_DEBUG_LOG_FREQ) { _lastDebugMs = ms; log(); } } void BackSeatDriver::log(const char *message) { if (strlen(message) < LOG_BUFFER_LEN) { sprintf(_logBuffer, "%s", message); log(); } } void BackSeatDriver::log() { char millisSince[15]; uint32_t ms = millis(); _lastDebugMs = ms; sprintf(millisSince, "%10d\t", (int)(_lastDebugMs - _initMs) ); Serial.print(millisSince); Serial.println(_logBuffer); }
26.833333
131
0.725533
[ "3d" ]
beb7d7f2135a4f7d7d995f83a60aa4e382b6dc22
665
cpp
C++
DMOJ/Olympiads School/Add_up_Apples.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
null
null
null
DMOJ/Olympiads School/Add_up_Apples.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
1
2021-10-14T18:26:56.000Z
2021-10-14T18:26:56.000Z
DMOJ/Olympiads School/Add_up_Apples.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
1
2021-08-06T03:39:55.000Z
2021-08-06T03:39:55.000Z
#include <bits/stdc++.h> using namespace std; int N, tot; vector<int> v; void fun(int begin, int sum, int n, vector<int> v) { if (sum == n) { cout << n << "="; for (int i = 0; i < v.size() - 1; i++) { cout << v[i] << "+"; } cout << v.back() << '\n'; tot++; return; } for (int i = begin; i < n; i++) { if (sum + i <= n) { v.push_back(i); fun(i, sum+i, n, v); v.pop_back(); } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cin >> N; fun(1, 0, N, v); cout << "total=" << tot << '\n'; }
17.051282
52
0.389474
[ "vector" ]
beb95ebbd8adb6ffd528ec20d77701de79590d4b
2,350
cpp
C++
nft/nft.cpp
oskarirauta/ipctrl
1f36374007e169f36349fd4b91e1f90b8571cde4
[ "MIT" ]
null
null
null
nft/nft.cpp
oskarirauta/ipctrl
1f36374007e169f36349fd4b91e1f90b8571cde4
[ "MIT" ]
null
null
null
nft/nft.cpp
oskarirauta/ipctrl
1f36374007e169f36349fd4b91e1f90b8571cde4
[ "MIT" ]
null
null
null
#include <netdb.h> #include "common.hpp" #include "nft/nft.hpp" const nft::SetType nft::addrType(const std::string ipaddr) { struct addrinfo *ai, hints = { .ai_flags = AI_NUMERICHOST, .ai_family = PF_UNSPEC, }; if ( ipaddr.find('/') != std::string::npos ) { std::vector<std::string> parts = common::split(ipaddr,'/'); if ( parts.size() != 2 || !common::is_number(parts[1])) return nft::SetType::not_supported; int subnet; try { subnet = stoi(parts[1]); } catch (...) { return nft::SetType::not_supported; } if ( subnet < 0 || subnet > 255 ) return nft::SetType::not_supported; if ( getaddrinfo(parts[0].c_str(), NULL, &hints, &ai ) != 0 ) return nft::SetType::not_supported; } else if ( ipaddr.find('-') != std::string::npos ) { if ( ipaddr.find('/') != std::string::npos || ipaddr.find(':') != std::string::npos ) return nft::SetType::not_supported; std::vector<std::string> parts = common::split(ipaddr, '-'); if ( !common::is_number(common::trim(parts[0], ". \n\t")) || !common::is_number(common::trim(parts[1], ". \n\t"))) return nft::SetType::not_supported; int val1 = stoi(common::trim(parts[0], ". \n\t")); int val2 = stoi(common::trim(parts[1], ". \n\t")); if ( val1 > val2 ) return nft::SetType::not_supported; struct addrinfo *ai2, hints2 = { .ai_flags = AI_NUMERICHOST, .ai_family = PF_UNSPEC, }; if ( getaddrinfo(parts[0].c_str(), NULL, &hints, &ai) != 0 ) return nft::SetType::not_supported; if ( getaddrinfo(parts[1].c_str(), NULL, &hints2, &ai2) != 0 ) { freeaddrinfo(ai); return nft::SetType::not_supported; } bool range_ok = ai -> ai_family == AF_INET && ai2 -> ai_family == AF_INET; freeaddrinfo(ai); freeaddrinfo(ai2); return range_ok ? nft::SetType::ipv4_addr : nft::SetType::not_supported; } else if ( getaddrinfo(ipaddr.c_str(), NULL, &hints, &ai) != 0 ) return nft::SetType::not_supported; nft::SetType family = ai -> ai_family == AF_INET ? nft::SetType::ipv4_addr : ( ai -> ai_family == AF_INET6 ? nft::SetType::ipv6_addr : nft::SetType::not_supported); freeaddrinfo(ai); return family; } const Json::Value nft::dump(void) { Json::Value value; value["sets"] = Json::arrayValue; for ( int i = 0; i < nft::sets.size(); i++ ) value["sets"].append(nft::sets[i].dump()); return value; }
25
89
0.62383
[ "vector" ]
bebea77fe1c6bb8389d45a4e0e983a44f0846d7d
841
cpp
C++
src/singlerot.cpp
dmishin/revca_spaceship_searcher
00601f2314da9feb376f1649bf947a5ce961d728
[ "MIT" ]
1
2021-02-18T20:04:57.000Z
2021-02-18T20:04:57.000Z
src/singlerot.cpp
dmishin/revca_spaceship_searcher
00601f2314da9feb376f1649bf947a5ce961d728
[ "MIT" ]
null
null
null
src/singlerot.cpp
dmishin/revca_spaceship_searcher
00601f2314da9feb376f1649bf947a5ce961d728
[ "MIT" ]
null
null
null
#include "singlerot.hpp" #include "tree_pattern.hpp" #include <vector> using namespace std; bool singlerot_has_unchanged_core( const Pattern & _p ) { TreePattern pattern(_p); while (! pattern.empty() ){ vector<Cell> keys_to_delete; for( auto &key_value : pattern.blocks ){ int block = key_value.second.value; if (block == 1 || block == 2 || block == 4 || block == 8){ //single-cellers keys_to_delete.push_back( key_value.first ); } } if (keys_to_delete.empty()) break; for( const Cell &key : keys_to_delete ){ pattern.blocks.erase( key ); } pattern.translate(1,1); } return ! pattern.empty(); } bool SinglerotCoralFilter::check( const Pattern &p) { return ! singlerot_has_unchanged_core(p); }; MargolusBinaryRule singlerot({0,2,8,3,1,5,6,7,4,9,10,11,12,13,14,15});
24.735294
81
0.652794
[ "vector" ]
bec19211495b0c07bbd0f345ae640bf176ed6f5a
3,469
hpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/MPLS_TC_STD_MIB.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/MPLS_TC_STD_MIB.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/MPLS_TC_STD_MIB.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _MPLS_TC_STD_MIB_ #define _MPLS_TC_STD_MIB_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> namespace cisco_ios_xe { namespace MPLS_TC_STD_MIB { class MplsLabelDistributionMethod : public ydk::Enum { public: static const ydk::Enum::YLeaf downstreamOnDemand; static const ydk::Enum::YLeaf downstreamUnsolicited; static int get_enum_value(const std::string & name) { if (name == "downstreamOnDemand") return 1; if (name == "downstreamUnsolicited") return 2; return -1; } }; class MplsRetentionMode : public ydk::Enum { public: static const ydk::Enum::YLeaf conservative; static const ydk::Enum::YLeaf liberal; static int get_enum_value(const std::string & name) { if (name == "conservative") return 1; if (name == "liberal") return 2; return -1; } }; class MplsLdpLabelType : public ydk::Enum { public: static const ydk::Enum::YLeaf generic; static const ydk::Enum::YLeaf atm; static const ydk::Enum::YLeaf frameRelay; static int get_enum_value(const std::string & name) { if (name == "generic") return 1; if (name == "atm") return 2; if (name == "frameRelay") return 3; return -1; } }; class TeHopAddressType : public ydk::Enum { public: static const ydk::Enum::YLeaf unknown; static const ydk::Enum::YLeaf ipv4; static const ydk::Enum::YLeaf ipv6; static const ydk::Enum::YLeaf asnumber; static const ydk::Enum::YLeaf unnum; static const ydk::Enum::YLeaf lspid; static int get_enum_value(const std::string & name) { if (name == "unknown") return 0; if (name == "ipv4") return 1; if (name == "ipv6") return 2; if (name == "asnumber") return 3; if (name == "unnum") return 4; if (name == "lspid") return 5; return -1; } }; class MplsLspType : public ydk::Enum { public: static const ydk::Enum::YLeaf unknown; static const ydk::Enum::YLeaf terminatingLsp; static const ydk::Enum::YLeaf originatingLsp; static const ydk::Enum::YLeaf crossConnectingLsp; static int get_enum_value(const std::string & name) { if (name == "unknown") return 1; if (name == "terminatingLsp") return 2; if (name == "originatingLsp") return 3; if (name == "crossConnectingLsp") return 4; return -1; } }; class MplsOwner : public ydk::Enum { public: static const ydk::Enum::YLeaf unknown; static const ydk::Enum::YLeaf other; static const ydk::Enum::YLeaf snmp; static const ydk::Enum::YLeaf ldp; static const ydk::Enum::YLeaf crldp; static const ydk::Enum::YLeaf rsvpTe; static const ydk::Enum::YLeaf policyAgent; static int get_enum_value(const std::string & name) { if (name == "unknown") return 1; if (name == "other") return 2; if (name == "snmp") return 3; if (name == "ldp") return 4; if (name == "crldp") return 5; if (name == "rsvpTe") return 6; if (name == "policyAgent") return 7; return -1; } }; } } #endif /* _MPLS_TC_STD_MIB_ */
28.669421
61
0.573941
[ "vector" ]