text
string
size
int64
token_count
int64
#include <iostream> #include "Sound.h" GameSound::GameSound() { int audio_rate = 22050; Uint16 audio_format = AUDIO_S16SYS; int audio_channels = 2; int audio_buffers = 4096; if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) { printf("Unable to initialize audio: %s\n", Mix_GetError()); } } void GameSound::PlaySound(char* songName) { Mix_Chunk* sound = NULL; int channel; sound = Mix_LoadWAV(songName); if (sound == NULL) { printf("Unable to load WAV file: %s\n", Mix_GetError()); } channel = Mix_PlayChannel(-1, sound, 0); if (channel == -1) { printf("Unable to play WAV file: %s\n", Mix_GetError()); } MixChunkVec.push_back(sound); channelVec.push_back(channel); return; } bool GameSound::IsPlaying(){ for(auto &i : channelVec) { if(Mix_Playing(i) != 0) return true; } return false; } GameSound::~GameSound(){ for(auto &i : MixChunkVec) { Mix_FreeChunk(i); } Mix_CloseAudio(); }
1,096
412
/** * @file sample_drawing_map2d.cpp * @brief Example of the visualization of the chart radar type. * * @section LICENSE * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR/AUTHORS 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. * * @author Alessandro Moro <alessandromoro.italy@gmail.com> * @bug No known bugs. * @version 1.0.0.1 * */ #include <iostream> #include "container/inc/container/container_headers.hpp" #include "draw/inc/draw/draw_headers.hpp" namespace { /** @brief Test function. */ void test() { CmnIP::draw::Map2D map; map.set_natural_size(512, 512); map.set_range(-3000, -3000, 3000, 3000); map.reset_paint(); float x = 0, y = 0; map.original2scaled(1239, 738, x, y); cv::circle(map.image(), cv::Point(x, y), 2, cv::Scalar::all(255)); float xin = 0, yin = 0; map.scaled2original(x, y, xin, yin); std::vector<cv::Point2f> points; map.scaled_marker(500, 350, 1.8, 100, points); cv::line(map.image(), points[0], points[1], cv::Scalar(0,255)); cv::line(map.image(), points[2], points[3], cv::Scalar(0,255)); map.scaled_marker(2400, 1350, 2.6, 100, points); cv::line(map.image(), points[0], points[1], cv::Scalar(0,0,255)); cv::line(map.image(), points[2], points[3], cv::Scalar(0,0,255)); std::cout << xin << " " << yin << std::endl; cv::imshow("map", map.image()); cv::waitKey(); } } // namespace #ifdef CmnLib cmnLIBRARY_TEST_MAIN(&test, "data\\MemoryLeakCPP.txt", "data\\MemoryLeakC.txt"); #else /** main */ int main(int argc, char *argv[]) { std::cout << "Test chart radar" << std::endl; test(); return 0; } #endif
2,216
1,008
//n is the length of the array that required //if table[i] < i,then i means a,and table[i] means b.Else,i means b,ans table[i] means a. int* MakeWythoffTable(int n) { int k; int* table = new int[n]; int a; for(k = 0; k < n; k++) { a = k * mul; if(a >= n) break; table[a] = a + k; if(a + k < n) table[a+k] = a; } return table; }
414
166
#include "elias_fano_codes.h" namespace cds { elias_fano_codes::elias_fano_codes() : marker(1) { this->size = 0; this->marker.resize(1); this->marker.write(0, 1); } uint64_t elias_fano_codes::vector_size() const { return this->bv.vector_size() + this->marker.vector_size(); } uint64_t elias_fano_codes::read(uint64_t index) const { uint64_t begin = this->marker.search(index + 1); uint64_t end = this->marker.search(index + 2); uint64_t value = this->bv.bits_read(begin, end); return (value | (1LL << (end - begin))) - 2; } void elias_fano_codes::push_back(uint64_t value) { this->size++; value += 2; uint64_t length = bits_length(value) - 1; value &= ((1LL << length) - 1); this->bv.resize(this->bv.size + length); this->marker.resize(this->marker.size + length); this->bv.bits_write(this->bv.size - length, this->bv.size, value); this->marker.write(this->marker.size - 1, 1); } }
1,050
399
// MIT License // Copyright (c) 2021 eraft dev group // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <kv/engines.h> #include <kv/raft_server.h> #include <kv/utils.h> #include <spdlog/spdlog.h> #include <cassert> namespace kvserver { RaftStorage::RaftStorage(std::shared_ptr<Config> conf) : conf_(conf) { this->engs_ = std::make_shared<Engines>(conf->dbPath_ + "_raft", conf->dbPath_ + "_kv"); } RaftStorage::~RaftStorage() {} bool RaftStorage::CheckResponse(raft_cmdpb::RaftCmdResponse* resp, int reqCount) {} bool RaftStorage::Write(const kvrpcpb::Context& ctx, const kvrpcpb::RawPutRequest* put) { std::shared_ptr<raft_serverpb::RaftMessage> sendMsg = std::make_shared<raft_serverpb::RaftMessage>(); // send raft message sendMsg->set_data(put->SerializeAsString()); sendMsg->set_region_id(ctx.region_id()); sendMsg->set_raft_msg_type(raft_serverpb::RaftMsgClientCmd); return this->Raft(sendMsg.get()); } StorageReader* RaftStorage::Reader(const kvrpcpb::Context& ctx) { metapb::Region region; RegionReader* regionReader = new RegionReader(this->engs_, region); this->regionReader_ = regionReader; return regionReader; } bool RaftStorage::Raft(const raft_serverpb::RaftMessage* msg) { return this->raftRouter_->SendRaftMessage(msg); } bool RaftStorage::SnapShot(raft_serverpb::RaftSnapshotData* snap) {} bool RaftStorage::Start() { // raft system init this->raftSystem_ = std::make_shared<RaftStore>(this->conf_); // router init this->raftRouter_ = this->raftSystem_->raftRouter_; // raft client init std::shared_ptr<RaftClient> raftClient = std::make_shared<RaftClient>(this->conf_); this->node_ = std::make_shared<Node>(this->raftSystem_, this->conf_); // server transport init std::shared_ptr<ServerTransport> trans = std::make_shared<ServerTransport>(raftClient, raftRouter_); if (this->node_->Start(this->engs_, trans)) { SPDLOG_INFO("raft storage start succeed!"); } else { SPDLOG_INFO("raft storage start error!"); } } RegionReader::RegionReader(std::shared_ptr<Engines> engs, metapb::Region region) { this->engs_ = engs; this->region_ = region; } RegionReader::~RegionReader() {} std::string RegionReader::GetFromCF(std::string cf, std::string key) { return Assistant::GetInstance()->GetCF(this->engs_->kvDB_, cf, key); } rocksdb::Iterator* RegionReader::IterCF(std::string cf) { return Assistant::GetInstance()->NewCFIterator(this->engs_->kvDB_, cf); } void RegionReader::Close() {} } // namespace kvserver
3,642
1,223
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "base/Base.h" #include "kvstore/RocksEngine.h" #include <folly/String.h> #include "fs/FileUtils.h" #include "kvstore/KVStore.h" #include "kvstore/RocksEngineConfig.h" namespace nebula { namespace kvstore { using fs::FileUtils; using fs::FileType; const char* kSystemParts = "__system__parts__"; RocksEngine::RocksEngine(GraphSpaceID spaceId, const std::string& dataPath, std::shared_ptr<rocksdb::MergeOperator> mergeOp, std::shared_ptr<rocksdb::CompactionFilterFactory> cfFactory) : KVEngine(spaceId) , dataPath_(dataPath) { LOG(INFO) << "open rocksdb on " << dataPath; if (FileUtils::fileType(dataPath.c_str()) == FileType::NOTEXIST) { FileUtils::makeDir(dataPath); } rocksdb::Options options; rocksdb::DB* db = nullptr; rocksdb::Status status = initRocksdbOptions(options); CHECK(status.ok()); if (mergeOp != nullptr) { options.merge_operator = mergeOp; } if (cfFactory != nullptr) { options.compaction_filter_factory = cfFactory; } status = rocksdb::DB::Open(options, dataPath_, &db); CHECK(status.ok()); db_.reset(db); partsNum_ = allParts().size(); } RocksEngine::~RocksEngine() { } ResultCode RocksEngine::get(const std::string& key, std::string* value) { rocksdb::ReadOptions options; rocksdb::Status status = db_->Get(options, rocksdb::Slice(key), value); if (status.ok()) { return ResultCode::SUCCEEDED; } else if (status.IsNotFound()) { VLOG(3) << "Get: " << key << " Not Found"; return ResultCode::ERR_KEY_NOT_FOUND; } else { VLOG(3) << "Get Failed: " << key << " " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::multiGet(const std::vector<std::string>& keys, std::vector<std::string>* values) { rocksdb::ReadOptions options; std::vector<rocksdb::Slice> slices; for (unsigned int index = 0 ; index < keys.size() ; index++) { slices.emplace_back(keys[index]); } std::vector<rocksdb::Status> status = db_->MultiGet(options, slices, values); auto code = std::all_of(status.begin(), status.end(), [](rocksdb::Status s) { return s.ok(); }); if (code) { return ResultCode::SUCCEEDED; } else { return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::put(std::string key, std::string value) { rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; rocksdb::Status status = db_->Put(options, key, value); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "Put Failed: " << key << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::multiPut(std::vector<KV> keyValues) { rocksdb::WriteBatch updates(FLAGS_batch_reserved_bytes); for (size_t i = 0; i < keyValues.size(); i++) { updates.Put(keyValues[i].first, keyValues[i].second); } rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; rocksdb::Status status = db_->Write(options, &updates); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "MultiPut Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::range(const std::string& start, const std::string& end, std::unique_ptr<KVIterator>* storageIter) { rocksdb::ReadOptions options; rocksdb::Iterator* iter = db_->NewIterator(options); if (iter) { iter->Seek(rocksdb::Slice(start)); } storageIter->reset(new RocksRangeIter(iter, start, end)); return ResultCode::SUCCEEDED; } ResultCode RocksEngine::prefix(const std::string& prefix, std::unique_ptr<KVIterator>* storageIter) { rocksdb::ReadOptions options; rocksdb::Iterator* iter = db_->NewIterator(options); if (iter) { iter->Seek(rocksdb::Slice(prefix)); } storageIter->reset(new RocksPrefixIter(iter, prefix)); return ResultCode::SUCCEEDED; } ResultCode RocksEngine::remove(const std::string& key) { rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; auto status = db_->Delete(options, key); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "Remove Failed: " << key << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::multiRemove(std::vector<std::string> keys) { rocksdb::WriteBatch deletes(FLAGS_batch_reserved_bytes); for (size_t i = 0; i < keys.size(); i++) { deletes.Delete(keys[i]); } rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; rocksdb::Status status = db_->Write(options, &deletes); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "MultiRemove Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::removeRange(const std::string& start, const std::string& end) { rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; auto status = db_->DeleteRange(options, db_->DefaultColumnFamily(), start, end); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "RemoveRange Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } std::string RocksEngine::partKey(PartitionID partId) { std::string key; static const size_t prefixLen = ::strlen(kSystemParts); key.reserve(prefixLen + sizeof(PartitionID)); key.append(kSystemParts, prefixLen); key.append(reinterpret_cast<const char*>(&partId), sizeof(PartitionID)); return key; } void RocksEngine::addPart(PartitionID partId) { auto ret = put(partKey(partId), ""); if (ret == ResultCode::SUCCEEDED) { partsNum_++; CHECK_GE(partsNum_, 0); } } void RocksEngine::removePart(PartitionID partId) { rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; auto status = db_->Delete(options, partKey(partId)); if (status.ok()) { partsNum_--; CHECK_GE(partsNum_, 0); } } std::vector<PartitionID> RocksEngine::allParts() { std::unique_ptr<KVIterator> iter; static const size_t prefixLen = ::strlen(kSystemParts); static const std::string prefixStr(kSystemParts, prefixLen); CHECK_EQ(ResultCode::SUCCEEDED, this->prefix(prefixStr, &iter)); std::vector<PartitionID> parts; while (iter->valid()) { auto key = iter->key(); CHECK_EQ(key.size(), prefixLen + sizeof(PartitionID)); parts.emplace_back( *reinterpret_cast<const PartitionID*>(key.data() + key.size() - sizeof(PartitionID))); iter->next(); } return parts; } int32_t RocksEngine::totalPartsNum() { return partsNum_; } ResultCode RocksEngine::ingest(const std::vector<std::string>& files) { rocksdb::IngestExternalFileOptions options; rocksdb::Status status = db_->IngestExternalFile(files, options); if (status.ok()) { return ResultCode::SUCCEEDED; } else { LOG(ERROR) << "Ingest Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::setOption(const std::string& configKey, const std::string& configValue) { std::unordered_map<std::string, std::string> configOptions = { {configKey, configValue} }; rocksdb::Status status = db_->SetOptions(configOptions); if (status.ok()) { return ResultCode::SUCCEEDED; } else { LOG(ERROR) << "SetOption Failed: " << configKey << ":" << configValue; return ResultCode::ERR_INVALID_ARGUMENT; } } ResultCode RocksEngine::setDBOption(const std::string& configKey, const std::string& configValue) { std::unordered_map<std::string, std::string> configOptions = { {configKey, configValue} }; rocksdb::Status status = db_->SetDBOptions(configOptions); if (status.ok()) { return ResultCode::SUCCEEDED; } else { LOG(ERROR) << "SetDBOption Failed: " << configKey << ":" << configValue; return ResultCode::ERR_INVALID_ARGUMENT; } } ResultCode RocksEngine::compactAll() { rocksdb::CompactRangeOptions options; rocksdb::Status status = db_->CompactRange(options, nullptr, nullptr); if (status.ok()) { return ResultCode::SUCCEEDED; } else { LOG(ERROR) << "CompactAll Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } } // namespace kvstore } // namespace nebula
9,215
2,990
#include "OriWidgets.h" #include <QAction> #include <QActionGroup> #include <QApplication> #include <QBoxLayout> #include <QComboBox> #include <QDebug> #include <QGroupBox> #include <QHeaderView> #include <QLabel> #include <QMenu> #include <QObject> #include <QPushButton> #include <QStyle> #include <QSpinBox> #include <QSplitter> #include <QTableView> #include <QTextBrowser> #include <QToolBar> #include <QToolButton> #include <QTreeWidget> #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) #define qintptr std::intptr_t #endif namespace Ori { namespace Gui { //-------------------------------------------------------------------------------------------------- void adjustFont(QWidget *w) { #ifdef Q_OS_WIN QFont f = w->font(); if (f.pointSize() < 10) { f.setPointSize(10); w->setFont(f); } #else Q_UNUSED(w) #endif } void setFontSizePt(QWidget *w, int sizePt) { QFont f = w->font(); f.setPointSize(sizePt); w->setFont(f); } void setFontMonospace(QWidget *w, int sizePt) { QFont f = w->font(); #if defined(Q_OS_WIN) f.setFamily("Consolas"); f.setPointSize(10); #elif defined(Q_OS_MAC) f.setFamily("Monaco"); f.setPointSize(13); #else f.setFamily("monospace"); f.setPointSize(11); #endif if (sizePt > 0) f.setPointSize(sizePt); w->setFont(f); } //-------------------------------------------------------------------------------------------------- QSplitter* splitter(Qt::Orientation orientation, QWidget *w1, QWidget *w2, QList<int> sizes) { auto splitter = new QSplitter(orientation); splitter->addWidget(w1); splitter->addWidget(w2); if (!sizes.isEmpty()) splitter->setSizes(sizes); return splitter; } QSplitter* splitterH(QWidget *w1, QWidget *w2) { return splitter(Qt::Horizontal, w1, w2, {}); } QSplitter* splitterV(QWidget *w1, QWidget *w2) { return splitter(Qt::Vertical, w1, w2, {}); } QSplitter* splitterH(QWidget *w1, QWidget *w2, int size1, int size2) { return splitter(Qt::Horizontal, w1, w2, {size1, size2}); } QSplitter* splitterV(QWidget *w1, QWidget *w2, int size1, int size2) { return splitter(Qt::Vertical, w1, w2, {size1, size2}); } //-------------------------------------------------------------------------------------------------- QToolButton* textToolButton(QAction* action) { auto button = new QToolButton; button->setDefaultAction(action); button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); return button; } QToolButton* menuToolButton(QMenu* menu, QAction* action) { auto button = new QToolButton; button->setDefaultAction(action); button->setPopupMode(QToolButton::MenuButtonPopup); button->setMenu(menu); return button; } QToolButton* iconToolButton(const QString& tooltip, const QString& iconPath, QObject* receiver, const char* slot) { auto button = new QToolButton; button->setToolTip(tooltip); button->setIcon(QIcon(iconPath)); button->connect(button, SIGNAL(clicked()), receiver, slot); return button; } QToolButton* iconToolButton(const QString& tooltip, const QString& iconPath, int iconSize, QObject* receiver, const char* slot) { auto button = new QToolButton; button->setToolTip(tooltip); button->setIconSize(QSize(iconSize, iconSize)); button->setIcon(QIcon(iconPath)); button->connect(button, SIGNAL(clicked()), receiver, slot); return button; } //-------------------------------------------------------------------------------------------------- QMenu* menu(std::initializer_list<QObject*> items) { return menu(QString(), nullptr, items); } QMenu* menu(QWidget *parent, std::initializer_list<QObject*> items) { return menu(QString(), parent, items); } QMenu* menu(const QString& title, std::initializer_list<QObject*> items) { return menu(title, nullptr, items); } QMenu* menu(const QString& title, QWidget *parent, std::initializer_list<QObject*> items) { return populate(new QMenu(title, parent), items); } QMenu* populate(QMenu* menu, std::initializer_list<QObject*> items) { if (!menu) return nullptr; menu->clear(); for (auto item: items) append(menu, item); return menu; } void append(QMenu* menu, QObject* item) { if (!item) { menu->addSeparator(); return; } auto action = qobject_cast<QAction*>(item); if (action) { menu->addAction(action); return; } auto submenu = qobject_cast<QMenu*>(item); if (submenu) { menu->addMenu(submenu); return; } } QMenu* makeToggleWidgetsMenu(QMenu* parent, const QString& title, std::initializer_list<QWidget*> widgets) { QMenu* menu = parent->addMenu(title); QVector<QPair<QAction*, QWidget*> > actions; for (QWidget* widget : widgets) { QAction *action = menu->addAction(widget->windowTitle(), [widget](){ toggleWidget(widget); }); action->setCheckable(true); actions.push_back(QPair<QAction*, QWidget*>(action, widget)); } qApp->connect(menu, &QMenu::aboutToShow, [actions](){ for (const QPair<QAction*, QWidget*>& pair : actions) pair.first->setChecked(pair.second->isVisible()); }); return menu; } //-------------------------------------------------------------------------------------------------- QToolBar* toolbar(std::initializer_list<QObject*> items) { return populate(new QToolBar, items); } QToolBar* populate(QToolBar* toolbar, std::initializer_list<QObject*> items) { if (!toolbar) return nullptr; toolbar->clear(); for (auto item : items) append(toolbar, item); return toolbar; } void append(QToolBar* toolbar, QObject* item) { if (!item) { toolbar->addSeparator(); return; } auto action = qobject_cast<QAction*>(item); if (action) { toolbar->addAction(action); return; } auto group = qobject_cast<QActionGroup*>(item); if (group) { for (auto action : group->actions()) toolbar->addAction(action); return; } auto widget = qobject_cast<QWidget*>(item); if (widget) { toolbar->addWidget(widget); return; } } //-------------------------------------------------------------------------------------------------- QBoxLayout* layoutH(const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return populate(new QHBoxLayout, items); } QBoxLayout* layoutV(const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return populate(new QVBoxLayout, items); } QBoxLayout* layoutH(QWidget* parent, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return populate(new QHBoxLayout(parent), items); } QBoxLayout* layoutV(QWidget* parent, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return populate(new QVBoxLayout(parent), items); } QBoxLayout* initGeometry(QBoxLayout* layout, int margin, int spacing) { if (margin >= 0) layout->setContentsMargins(margin, margin, margin, margin); if (spacing >= 0) layout->setSpacing(spacing); return layout; } QBoxLayout* layoutH(QWidget* parent, int margin, int spacing, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return initGeometry(layoutH(parent, items), margin, spacing); } QBoxLayout* layoutV(QWidget* parent, int margin, int spacing, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return initGeometry(layoutV(parent, items), margin, spacing); } QBoxLayout* layoutH(int margin, int spacing, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return initGeometry(layoutH(items), margin, spacing); } QBoxLayout* layoutV(int margin, int spacing, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return initGeometry(layoutV(items), margin, spacing); } QBoxLayout* populate(QBoxLayout* layout, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; if (!layout) return nullptr; for (auto item: items) append(layout, item); return layout; } void append(QBoxLayout* layout, QObject* item) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; if (!item) { layout->addStretch(); return; } if (qintptr(item) < 100) { layout->addSpacing(int(qintptr(item))); return; } auto widget = qobject_cast<QWidget*>(item); if (widget) { layout->addWidget(widget); return; } auto sublayout = qobject_cast<QLayout*>(item); if (sublayout) { layout->addLayout(sublayout); return; } } QObject* spacing(int size) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return (QObject*)qintptr(size); } QObject* defaultSpacing(int factor) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return spacing(factor * layoutSpacing()); } //-------------------------------------------------------------------------------------------------- QLabel* stretchedLabel(const QString& text) { auto label = new QLabel(text); label->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); return label; } //-------------------------------------------------------------------------------------------------- int layoutSpacing() { int spacing = qApp->style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing); // MacOS's style "macintosh" has spacing -1, sic! // It is not what we want adjusting widgets using layoutSpacing() // Fusion style gets 6 and it's most reasonable style in Qt if (spacing < 0) spacing = 6; return spacing; } int borderWidth() { return qApp->style()->pixelMetric(QStyle::PM_DefaultFrameWidth); } //-------------------------------------------------------------------------------------------------- QGroupBox* group(const QString& title, QLayout *layout) { auto group = new QGroupBox(title); group->setLayout(layout); return group; } QGroupBox* groupV(const QString& title, const std::initializer_list<QObject*>& items) { return group(title, layoutV(items)); } QGroupBox* groupH(const QString& title, const std::initializer_list<QObject*>& items) { return group(title, layoutH(items)); } //-------------------------------------------------------------------------------------------------- QWidget* widget(QBoxLayout* layout) { auto widget = new QWidget; widget->setLayout(layout); return widget; } QWidget* widgetV(const std::initializer_list<QObject*>& items) { return widget(layoutV(items)); } QWidget* widgetH(const std::initializer_list<QObject*>& items) { return widget(layoutH(items)); } //-------------------------------------------------------------------------------------------------- QPushButton* button(const QString& title, QObject *receiver, const char* slot) { auto button = new QPushButton(title); button->connect(button, SIGNAL(clicked(bool)), receiver, slot); return button; } QPushButton* iconButton(const QString& tooltip, const QString& iconPath, QObject* receiver, const char* slot, bool flat) { auto button = new QPushButton; button->setIcon(QIcon(iconPath)); button->setToolTip(tooltip); button->connect(button, SIGNAL(clicked(bool)), receiver, slot); button->setFlat(flat); return button; } //-------------------------------------------------------------------------------------------------- void setSelectedId(QComboBox *combo, int id) { for (int i = 0; i < combo->count(); i++) if (combo->itemData(i).toInt() == id) { combo->setCurrentIndex(i); return; } combo->setCurrentIndex(-1); } int getSelectedId(const QComboBox *combo, int def) { QVariant data = combo->itemData(combo->currentIndex()); if (!data.isValid()) return def; bool ok; int id = data.toInt(&ok); return ok? id: def; } //-------------------------------------------------------------------------------------------------- // Guesses a descriptive text suited for the menu entry. // This is equivalent to QAction's internal qt_strippedText(). static QString strippedActionTitle(QString s) { s.remove(QString::fromLatin1("...")); for (int i = 0; i < s.size(); ++i) if (s.at(i) == QLatin1Char('&')) s.remove(i, 1); return s.trimmed(); } // Adds shortcut information to the action's tooltip. // Here is more complete solution supporting custom tooltips // https://stackoverflow.com/questions/42607554/show-shortcut-in-tooltip-of-qtoolbar static void setActionShortcut(QAction* action, const QKeySequence& shortcut) { action->setShortcut(shortcut); action->setToolTip(QStringLiteral("<p style='white-space:pre'>%1&nbsp;&nbsp;(<code>%2</code>)</p>") .arg(strippedActionTitle(action->text()), shortcut.toString(QKeySequence::NativeText))); } QAction* action(const QString& title, QObject* receiver, const char* slot, const char* icon, const QKeySequence& shortcut) { auto action = new QAction(title, receiver); if (!shortcut.isEmpty()) setActionShortcut(action, shortcut); if (icon) action->setIcon(QIcon(icon)); qApp->connect(action, SIGNAL(triggered()), receiver, slot); return action; } QAction* toggledAction(const QString& title, QObject* receiver, const char* slot, const char* icon, const QKeySequence& shortcut) { auto action = new QAction(title, receiver); action->setCheckable(true); if (!shortcut.isEmpty()) setActionShortcut(action, shortcut); if (icon) action->setIcon(QIcon(icon)); if (slot) qApp->connect(action, SIGNAL(toggled(bool)), receiver, slot); return action; } //-------------------------------------------------------------------------------------------------- QTreeWidget* twoColumnTree(const QString& title1, const QString& title2) { auto tree = new QTreeWidget; tree->setColumnCount(2); tree->setAlternatingRowColors(true); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) tree->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); tree->header()->setSectionResizeMode(1, QHeaderView::Stretch); #else tree->header()->setResizeMode(0, QHeaderView::ResizeToContents); tree->header()->setResizeMode(1, QHeaderView::Stretch); #endif auto header = new QTreeWidgetItem(); header->setText(0, title1); header->setText(1, title2); tree->setHeaderItem(header); return tree; } //-------------------------------------------------------------------------------------------------- void stretchColumn(QTableView *table, int col) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) table->horizontalHeader()->setSectionResizeMode(col, QHeaderView::Stretch); #else table->horizontalHeader()->setResizeMode(col, QHeaderView::Stretch); #endif } void resizeColumnToContent(QTableView *table, int col) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) table->horizontalHeader()->setSectionResizeMode(col, QHeaderView::ResizeToContents); #else table->horizontalHeader()->setResizeMode(col, QHeaderView::ResizeToContents); #endif } //-------------------------------------------------------------------------------------------------- void toggleWidget(QWidget* panel) { if (panel->isVisible()) panel->hide(); else panel->show(); } //-------------------------------------------------------------------------------------------------- QSpinBox* spinBox(int min, int max, int value) { auto sb = new QSpinBox; sb->setMinimum(min); sb->setMaximum(max); if (value != 0) sb->setValue(value); return sb; } } // namespace Gui } // namespace Ori
16,703
5,191
#pragma once #include "Common.hpp" #define Interface class #define implements public
86
24
/* * Copyright (c) 2010 Jice * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The name of Jice may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Jice ``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 Jice 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 "main.hpp" #define OBJ_WIDTH (CON_W-4) #define OBJ_HEIGHT 40 Objective::Objective(const char *title, const char *description, const char *enableScript, const char *successScript, bool mainObjective) : title(title),description(description), enableScript(enableScript), successScript(successScript), onEnable(NULL), onSuccess(NULL), mainObjective(mainObjective) { if (enableScript) { onEnable = new Script(); onEnable->parse(enableScript); } if (successScript) { onSuccess = new Script(); onSuccess->parse(successScript); } } #define UPDATE_DELAY 3.0f Objectives::Objectives() : timer(0.0f),showWindow(false),firstObj(true) { saveGame.registerListener(OBJE_CHUNK_ID,PHASE_START,this); rect = UmbraRect(2,5,OBJ_WIDTH,OBJ_HEIGHT); con = new TCODConsole(OBJ_WIDTH,OBJ_HEIGHT); con->setDefaultBackground(guiBackground); guiTabs.addTab("Active"); guiTabs.addTab("Success"); guiTabs.addTab("Failure"); flags=DIALOG_CLOSABLE_NODISABLE; currentList=&active; scroller = new Scroller(this,OBJ_WIDTH/2-1,OBJ_HEIGHT-2); selected=0; } bool Objectives::executeObjScript(Objective *obj, Script *script) { currentObjective = obj; bool ret=script->execute(); currentObjective = NULL; return ret; } void Objectives::activateCurrent() { gameEngine->gui.log.warn("New objective : %s",currentObjective->title); if ( firstObj ) { gameEngine->gui.log.info("Press 'o' to open the objectives screen"); firstObj=false; } toActivate.push(currentObjective); } void Objectives::activateObjective(const char *title) { for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { if ( strcmp(title,(*it)->title) == 0 ) { gameEngine->gui.log.warn("New objective : %s",title); toActivate.push(*it); break; } } } void Objectives::closeCurrent(bool success) { gameEngine->gui.log.warn("Objective completed : %s (%s)",currentObjective->title, success ? "success":"failure"); if ( success ) { toSuccess.push(currentObjective); if ( currentObjective->mainObjective ) gameEngine->win=true; } else toFailure.push(currentObjective); } void Objectives::addStep(const char *msg, Objective *obj) { if (! obj ) obj = currentObjective; if (! toSuccess.contains( obj ) ) gameEngine->gui.log.warn("Objective updated : %s",obj->title); obj->steps.push(strdup(msg)); } void Objectives::render() { if (! showWindow ) return; con->clear(); con->setDefaultForeground(guiText); con->vline(OBJ_WIDTH/2,2,OBJ_HEIGHT-3); guiTabs.render(con,0,0); scroller->render(con,0,2); scroller->renderScrollbar(con,0,2); if ( currentList && selected < currentList->size() ) { con->setDefaultForeground(guiText); int y=2; Objective *objective=currentList->get(selected); y+=con->printRect(OBJ_WIDTH/2+2,y,OBJ_WIDTH/2-3,0,objective->description); for ( const char **step=objective->steps.begin(); step != objective->steps.end(); step ++ ) { y++; y+=con->printRect(OBJ_WIDTH/2+2,y,OBJ_WIDTH/2-3,0,*step); } } blitSemiTransparent(con,0,0,OBJ_WIDTH,OBJ_HEIGHT,TCODConsole::root,rect.x,rect.y,0.8f,1.0f); renderFrame(1.0f,"Objectives"); } int Objectives::getScrollTotalSize() { return currentList->size(); } const char *Objectives::getScrollText(int idx) { return currentList->get(idx)->title; } void Objectives::getScrollColor(int idx, TCODColor *fore, TCODColor *back) { *fore = idx == selected ? guiHighlightedText : guiText; *back = guiBackground; } bool Objectives::update(float elapsed, TCOD_key_t &k, TCOD_mouse_t &mouse) { if ( showWindow ) { flags |= DIALOG_MODAL; guiTabs.update(elapsed,k,mouse,rect.x,rect.y); scroller->update(elapsed,k,mouse,rect.x,rect.y+2); if ( mouse.cx >= rect.x && mouse.cx < rect.x+rect.w/2 && mouse.cy >= rect.y+2 && mouse.cy < rect.y+rect.h) { int newSelected = mouse.cy-rect.y-2; if ( currentList && newSelected < currentList->size() ) selected=newSelected; } switch(guiTabs.curTab) { case 0 : currentList = &active; break; case 1 : currentList = &success; break; case 2 : currentList = &failed; break; } if (closeButton.mouseHover && mouse.lbutton_pressed) { gameEngine->gui.setMode(GUI_NONE); } if ( (k.vk == TCODK_ESCAPE && ! k.pressed) ) { gameEngine->gui.setMode(GUI_NONE); } } else if ( wasShowingWindow) { flags &= ~DIALOG_MODAL; if ( gameEngine->gui.mode == GUI_NONE && gameEngine->isGamePaused() ) { gameEngine->resumeGame(); } } timer += elapsed; if ( timer < UPDATE_DELAY ) return true; timer = 0.0f; // check end conditions for active objectives for (Objective **it=active.begin(); it != active.end(); it++) { if (! (*it)->onSuccess ) toSuccess.push(*it); else if ( !executeObjScript(*it,(*it)->onSuccess) ) { // script execution failed. junk the objective failed.push(*it); it = active.removeFast(it); } } // check if new objectives are enabled for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { if ( ! (*it)->onEnable ) { toActivate.push(*it); gameEngine->gui.log.warn("New objective : %s",(*it)->title); if ( firstObj ) { gameEngine->gui.log.info("Press 'o' to open the objectives screen"); firstObj=false; } } else if ( !executeObjScript(*it,(*it)->onEnable) ) { // script execution failed. junk the objective failed.push(*it); it = sleeping.removeFast(it); } } for (Objective **it=toActivate.begin(); it != toActivate.end(); it++) { sleeping.removeFast(*it); active.push(*it); } toActivate.clear(); for (Objective **it=toSuccess.begin(); it != toSuccess.end(); it++) { active.removeFast(*it); success.push(*it); } toSuccess.clear(); for (Objective **it=toFailure.begin(); it != toFailure.end(); it++) { active.removeFast(*it); failed.push(*it); } toFailure.clear(); wasShowingWindow = showWindow; return true; } void Objectives::addObjective(Objective *obj) { sleeping.push(obj); } #define OBJE_CHUNK_VERSION 1 bool Objectives::loadData(uint32 chunkId, uint32 chunkVersion, TCODZip *zip) { if ( chunkVersion != OBJE_CHUNK_VERSION ) return false; showWindow = (zip->getChar()==1); firstObj = (zip->getChar()==1); int nbSleeping=zip->getInt(); while ( nbSleeping > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); const char *enableScript=zip->getString(); if (enableScript) enableScript=strdup(enableScript); const char *successScript=zip->getString(); if (successScript) successScript=strdup(successScript); Objective *obj = new Objective(title,description,enableScript,successScript); sleeping.push(obj); nbSleeping--; } int nbActive=zip->getInt(); while ( nbActive > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); const char *enableScript=zip->getString(); if (enableScript) enableScript=strdup(enableScript); const char *successScript=zip->getString(); if (successScript) successScript=strdup(successScript); Objective *obj = new Objective(title,description,enableScript,successScript); active.push(obj); nbActive--; } int nbSuccess=zip->getInt(); while ( nbSuccess > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); Objective *obj = new Objective(title,description); success.push(obj); nbSuccess--; } int nbFailed=zip->getInt(); while ( nbFailed > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); Objective *obj = new Objective(title,description); failed.push(obj); nbFailed--; } return true; } void Objectives::saveData(uint32 chunkId, TCODZip *zip) { saveGame.saveChunk(OBJE_CHUNK_ID,OBJE_CHUNK_VERSION); zip->putChar(showWindow ? 1:0); zip->putChar(firstObj ? 1:0); zip->putInt(sleeping.size()); for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); zip->putString((*it)->enableScript); zip->putString((*it)->successScript); } zip->putInt(active.size()); for (Objective **it=active.begin(); it != active.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); zip->putString((*it)->enableScript); zip->putString((*it)->successScript); } zip->putInt(success.size()); for (Objective **it=success.begin(); it != success.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); } zip->putInt(failed.size()); for (Objective **it=failed.begin(); it != failed.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); } }
10,330
3,838
/******************************************************************* * * DESCRIPTION: consbtch.cpp * * AUTHOR: David Malcolm * * HISTORY: Created 8/4/98 * *******************************************************************/ /* Includes ********************************************************/ #include "3dc.h" #include "console_batch.hpp" #include "reflist.hpp" #define UseLocalAssert TRUE #include "ourasert.h" /* Version settings ************************************************/ /* Constants *******************************************************/ enum { MaxBatchFileLineLength=300, MaxBatchFileLineSize=(MaxBatchFileLineLength+1) }; /* Macros **********************************************************/ /* Imported function prototypes ************************************/ /* Imported data ***************************************************/ /* Exported globals ************************************************/ /* Internal type definitions ***************************************/ /* Internal function prototypes ************************************/ /* Internal globals ************************************************/ /* Exported function definitions ***********************************/ // class BatchFileProcessing // public: // static bool BatchFileProcessing :: Run(char* Filename) { // Tries to find the file, if it finds it it reads it, // adds the non-comment lines to the pending list, and returns TRUE // If it can't find the file, it returns FALSE // LOCALISEME // This code makes several uses of the assumption that char is type-equal // to ProjChar RefList<SCString> PendingList; { FILE *pFile = avp_open_userfile(Filename, "r"); if (NULL==pFile) { return FALSE; } // Read the file, line by line. { // We impose a maximum length on lines that will be valid: char LineBuffer[MaxBatchFileLineSize]; int CharsReadInLine = 0; while (1) { int Char = fgetc(pFile); if (Char==EOF) { break; } else { if ( Char=='\n' ) { // Flush the buffer into the pending queue: GLOBALASSERT(CharsReadInLine<=MaxBatchFileLineLength); LineBuffer[CharsReadInLine] = '\0'; SCString* pSCString_Line = new SCString(&LineBuffer[0]); PendingList . AddToEnd ( *pSCString_Line ); pSCString_Line -> R_Release(); CharsReadInLine = 0; } else { // Add to buffer; silently reject characters beyond the length limit if ( CharsReadInLine < MaxBatchFileLineLength ) { LineBuffer[CharsReadInLine++]=toupper((char)Char); } } } } // Flush anything still in the buffer into the pending queue: { GLOBALASSERT(CharsReadInLine<=MaxBatchFileLineLength); LineBuffer[CharsReadInLine] = '\0'; SCString* pSCString_Line = new SCString(&LineBuffer[0]); PendingList . AddToEnd ( *pSCString_Line ); pSCString_Line -> R_Release(); } } fclose(pFile); } // Feedback: { SCString* pSCString_1 = new SCString("EXECUTING BATCH FILE "); // LOCALISEME SCString* pSCString_2 = new SCString(Filename); SCString* pSCString_Feedback = new SCString ( pSCString_1, pSCString_2 ); pSCString_Feedback -> SendToScreen(); pSCString_Feedback -> R_Release(); pSCString_2 -> R_Release(); pSCString_1 -> R_Release(); } // Now process the pending queue: { // Iterate through the pending list, destructively reading the // "references" from the front: { SCString* pSCString; // The assignment in this boolean expression is deliberate: while ( NULL != (pSCString = PendingList . GetYourFirst()) ) { if (pSCString->pProjCh()[0] != '#') { // lines beginning with hash are comments if (bEcho) { pSCString -> SendToScreen(); } pSCString -> ProcessAnyCheatCodes(); } pSCString -> R_Release(); } } } return TRUE; } // public: // static int BatchFileProcessing :: bEcho = FALSE; /* Internal function definitions ***********************************/
4,143
1,578
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Vulkan Renderer" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_VULKANRENDERER_BUFFER_HPP #define NAZARA_VULKANRENDERER_BUFFER_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Utility/AbstractBuffer.hpp> #include <Nazara/VulkanRenderer/Config.hpp> #include <Nazara/VulkanRenderer/Wrapper/Buffer.hpp> #include <Nazara/VulkanRenderer/Wrapper/DeviceMemory.hpp> #include <Nazara/VulkanRenderer/Wrapper/Fence.hpp> #include <memory> #include <vector> namespace Nz { class NAZARA_VULKANRENDERER_API VulkanBuffer : public AbstractBuffer { public: inline VulkanBuffer(Vk::Device& device, BufferType type); VulkanBuffer(const VulkanBuffer&) = delete; VulkanBuffer(VulkanBuffer&&) = delete; ///TODO virtual ~VulkanBuffer(); bool Fill(const void* data, UInt64 offset, UInt64 size) override; bool Initialize(UInt64 size, BufferUsageFlags usage) override; inline VkBuffer GetBuffer(); UInt64 GetSize() const override; DataStorage GetStorage() const override; void* Map(BufferAccess access, UInt64 offset, UInt64 size) override; bool Unmap() override; VulkanBuffer& operator=(const VulkanBuffer&) = delete; VulkanBuffer& operator=(VulkanBuffer&&) = delete; ///TODO private: BufferType m_type; BufferUsageFlags m_usage; UInt64 m_size; VkBuffer m_buffer; VkBuffer m_stagingBuffer; VmaAllocation m_allocation; VmaAllocation m_stagingAllocation; Vk::Device& m_device; }; } #include <Nazara/VulkanRenderer/VulkanBuffer.inl> #endif // NAZARA_VULKANRENDERER_BUFFER_HPP
1,679
667
/** * Project Logi source code * Copyright (C) 2019 Primoz Lavric * * 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/>. */ #ifndef LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP #define LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP #include <optional> #include <vk_mem_alloc.h> #include "logi/base/common.hpp" #include "logi/base/vulkan_object.hpp" namespace logi { class VulkanInstanceImpl; class PhysicalDeviceImpl; class LogicalDeviceImpl; class VMABufferImpl; class VMAImageImpl; class VMAAccelerationStructureNVImpl; class MemoryAllocatorImpl : public VulkanObject, public std::enable_shared_from_this<MemoryAllocatorImpl>, public VulkanObjectComposite<VMABufferImpl>, public VulkanObjectComposite<VMAImageImpl>, public VulkanObjectComposite<VMAAccelerationStructureNVImpl> { public: explicit MemoryAllocatorImpl(LogicalDeviceImpl& logicalDevice, vk::DeviceSize preferredLargeHeapBlockSize = 0u, uint32_t frameInUseCount = 0u, const std::vector<vk::DeviceSize>& heapSizeLimits = {}, const std::optional<vk::AllocationCallbacks>& allocator = {}); // region Sub handles const std::shared_ptr<VMABufferImpl>& createBuffer(const vk::BufferCreateInfo& bufferCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator); void destroyBuffer(size_t id); const std::shared_ptr<VMAImageImpl>& createImage(const vk::ImageCreateInfo& imageCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator = {}); void destroyImage(size_t id); const std::shared_ptr<VMAAccelerationStructureNVImpl>& createAccelerationStructureNV(const vk::AccelerationStructureCreateInfoNV& accelerationStructureCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator = {}); void destroyAccelerationStructureNV(size_t id); // endregion // region Logi Declarations VulkanInstanceImpl& getInstance() const; PhysicalDeviceImpl& getPhysicalDevice() const; LogicalDeviceImpl& getLogicalDevice() const; const vk::DispatchLoaderDynamic& getDispatcher() const; operator const VmaAllocator&() const; void destroy() const; protected: void free() override; // endregion private: LogicalDeviceImpl& logicalDevice_; std::optional<vk::AllocationCallbacks> allocator_; VmaAllocator vma_; }; } // namespace logi #endif // LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP
3,600
1,085
#ifndef _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ #define _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ #include "shadertoy/pre.hpp" #include "shadertoy/buffers/basic_buffer.hpp" #include "shadertoy/gl/framebuffer.hpp" #include "shadertoy/gl/renderbuffer.hpp" namespace shadertoy { namespace buffers { /** * @brief Represents a buffer in a swap chain. Rendering is done using a framebuffer. * * This class instantiates a framebuffer and a renderbuffer which are bound * before rendering the contents of this buffer. */ class gl_buffer : public basic_buffer { /// Target framebuffer gl::framebuffer target_fbo_; /// Target renderbuffer gl::renderbuffer target_rbo_; protected: /** * @brief Initialize a new gl_buffer * * @param[in] id Identifier for this buffer */ gl_buffer(const std::string &id); /** * @brief Initialize the contents of the buffer for rendering. * * @param[in] context Rendering context to use for shared objects * @param[in] io IO resource object */ void init_contents(const render_context &context, const io_resource &io) override; /** * @brief Initialize the renderbuffer object for the new specified size. * * @param[in] context Rendering context to use for shared objects * @param[in] io IO resource object */ void allocate_contents(const render_context &context, const io_resource &io) override; /** * @brief Render the contents of this buffer. This methods binds the * framebuffer and renderbuffer to the appropriate texture for * rendering, and then calls render_gl_contents as defined by * the derived class. * * @param[in] context Rendering context to use for rendering this buffer * @param[in] io IO resource object * @param[in] member Current swap-chain member */ void render_contents(const render_context &context, const io_resource &io, const members::buffer_member &member) final; /** * @brief Render the contents of this buffer to the currently bound * framebuffer and renderbuffer. This method must be implemented * by derived classes as part of their rendering routine. * * @param[in] context Rendering context to use for rendering this buffer * @param[in] io IO resource object */ virtual void render_gl_contents(const render_context &context, const io_resource &io) = 0; /** * @brief Binds the given texture to the target framebuffer object * for rendering. This method may be overridden by derived classes * in order to control the binding process. The default behavior is * to bind the first layer of the texture object to the first color attachment. * * @param[in] target_fbo Target framebuffer bound object * @param[in] io IO resource object containing the target textures to bind */ virtual void attach_framebuffer_outputs(const gl::bind_guard<gl::framebuffer, GLint> &target_fbo, const io_resource &io); public: /** * @brief Obtain this buffer's GL framebuffer object * * @return Reference to the framebuffer object */ inline const gl::framebuffer &target_fbo() const { return target_fbo_; } /** * @brief Obtain this buffer's GL renderbuffer object * * @return Reference to the renderbuffer object */ inline const gl::renderbuffer &target_rbo() const { return target_rbo_; } }; } } #endif /* _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ */
3,471
1,051
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int T; cin >> T; while (T--) { int M, N; int m = 1, n=1; long long input, output=0; vector<long long> MS, NS; cin >> M >> N; M--; N--; while (M--) { cin >> input; MS.push_back(input); } while (N--) { cin >> input; NS.push_back(input); } sort(MS.begin(), MS.end(), [] (long long x, long long y) {return x>y;}); sort(NS.begin(), NS.end(), [] (long long x, long long y) {return x>y;}); vector<long long>::iterator mi = MS.begin(), ni = NS.begin(); while (true) { if (mi == MS.end() && ni == NS.end()) { //cerr << "<END>" << endl; output %= 1000000007; break; } else if (mi == MS.end()) { output += ((*ni * m) % 1000000007); //cerr << "<ONLY N> ni:" << *ni << ", m:" << m << ", output:" << output << endl; ni++; n++; } else if (ni == NS.end()) { output += ((*mi * n) % 1000000007); //cerr << "<ONLY M> *mi:" << *mi << ", n:" << n << ", output:" << output << endl; mi++; m++; } else if (*mi >= *ni) { //cerr << "<M>=N> *mi:" << *mi << ", *ni:" << *ni << "n:" << n << ", output:" << output << endl; output += ((*mi * n) % 1000000007); mi++; m++; } else { //cerr << "<M<N> *mi:" << *mi << ", *ni:" << *ni << ", m:" << m << ", output:" << output << endl; output += ((*ni * m) % 1000000007); ni++; n++; } } cout << output << endl; } return 0; }
2,017
662
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "animator/animator.h" #include <climits> #include <gtest/gtest.h> using namespace std; using namespace testing::ext; namespace OHOS { class AnimatorTest : public testing::Test { public: static void SetUpTestCase(void) { if (animator == nullptr) { animator = new Animator(); } } static void TearDownTestCase(void) { if (animator != nullptr) { delete animator; animator = nullptr; } } static Animator* animator; }; Animator* AnimatorTest::animator = nullptr; /** * @tc.number SUB_GRAPHIC_ANIMATOR_START_0100 * @tc.name test animator start api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_Start_0100, Function | MediumTest | Level0) { animator->Start(); EXPECT_EQ(animator->GetState(), Animator::START); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_STOP_0200 * @tc.name test animator stop api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_Stop_0200, Function | MediumTest | Level0) { animator->Stop(); EXPECT_EQ(animator->GetState(), Animator::STOP); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_PAUSE_0300 * @tc.name test animator pause api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_Pause_0300, Function | MediumTest | Level0) { animator->Pause(); EXPECT_EQ(animator->GetState(), Animator::PAUSE); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_RESUME_0400 * @tc.name test animator resume api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_Resume_0400, Function | MediumTest | Level0) { animator->Resume(); EXPECT_EQ(animator->GetState(), Animator::START); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_SETSTATE_0500 * @tc.name test animator set-state api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_SetState_0500, Function | MediumTest | Level0) { animator->SetState(Animator::START); EXPECT_EQ(animator->GetState(), Animator::START); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_SETTIME_0600 * @tc.name test animator set-time api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_SetTime_0600, Function | MediumTest | Level0) { uint16_t time = 300; animator->SetTime(time); EXPECT_EQ(animator->GetTime(), time); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_SETRUNTIME_0700 * @tc.name test animator set-runtime api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_SetRunTime_0700, Function | MediumTest | Level0) { uint16_t time = 300; animator->SetRunTime(time); EXPECT_EQ(animator->GetRunTime(), time); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_ISRPEAT_0800 * @tc.name test animator if-repeat api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_IsRepeat_0800, Function | MediumTest | Level0) { EXPECT_EQ(animator->IsRepeat(), false); } } // namespace OHOS
3,686
1,438
// mgcmdmgr.cpp: 实现命令管理器类 // Copyright (c) 2004-2012, Zhang Yungui // License: LGPL, https://github.com/rhcad/touchvg #include "mgcmdmgr.h" #include "mgcmdselect.h" #include <mggrid.h> MgCommand* mgCreateCoreCommand(const char* name); float mgDisplayMmToModel(float mm, GiGraphics* gs); float mgDisplayMmToModel(float mm, const MgMotion* sender); typedef std::map<std::string, MgCommand* (*)()> Factories; static Factories _factories; static MgCmdManagerImpl* s_manager = NULL; static MgCmdManagerImpl s_tmpmgr(true); void mgRegisterCommand(const char* name, MgCommand* (*factory)()) { if (!factory) { _factories.erase(name); } else { _factories[name] = factory; } } MgCommandManager* mgGetCommandManager() { return s_manager ? s_manager : &s_tmpmgr; } MgCmdManagerImpl::MgCmdManagerImpl(bool tmpobj) { if (!s_manager && !tmpobj) s_manager = this; } MgCmdManagerImpl::~MgCmdManagerImpl() { unloadCommands(); if (s_manager == this) s_manager = NULL; } void MgCmdManagerImpl::unloadCommands() { for (CMDS::iterator it = _cmds.begin(); it != _cmds.end(); ++it) it->second->release(); _cmds.clear(); _cmdname = ""; } const char* MgCmdManagerImpl::getCommandName() { MgCommand* cmd = getCommand(); return cmd ? cmd->getName() : ""; } MgCommand* MgCmdManagerImpl::getCommand() { CMDS::iterator it = _cmds.find(_cmdname); return it != _cmds.end() ? it->second : NULL; } MgCommand* MgCmdManagerImpl::findCommand(const char* name) { CMDS::iterator it = _cmds.find(name); if (it == _cmds.end() && *name) { MgCommand* cmd = NULL; Factories::iterator itf = _factories.find(name); if (itf != _factories.end()) { cmd = itf->second ? (itf->second)() : NULL; } if (!cmd) { cmd = mgCreateCoreCommand(name); } if (cmd) { _cmds[name] = cmd; it = _cmds.find(name); } } return it != _cmds.end() ? it->second : NULL; } bool MgCmdManagerImpl::setCommand(const MgMotion* sender, const char* name) { if (strcmp(name, "erase") == 0) { MgSelection *sel = getSelection(sender->view); if (sel && sel->deleteSelection(sender->view)) return false; } cancel(sender); if (strcmp(name, "@draw") == 0) { name = _drawcmd.empty() ? "splines" : _drawcmd.c_str(); } MgCommand* cmd = findCommand(name); bool ret = false; if (cmd) { std::string oldname(_cmdname); _cmdname = cmd->getName(); ret = cmd->initialize(sender); if (!ret) { _cmdname = oldname; } else if (cmd->isDrawingCommand()) { _drawcmd = _cmdname; } } else { if (strcmp(name, "erasewnd") == 0) { eraseWnd(sender); } else { _cmdname = ""; } } return ret; } bool MgCmdManagerImpl::cancel(const MgMotion* sender) { clearSnap(); CMDS::iterator it = _cmds.find(_cmdname); if (it != _cmds.end()) { return it->second->cancel(sender); } return false; } int MgCmdManagerImpl::getSelection(MgView* view, int count, MgShape** shapes, bool forChange) { if (_cmdname == MgCmdSelect::Name() && view) { MgCmdSelect* sel = (MgCmdSelect*)getCommand(); return sel ? sel->getSelection(view, count, shapes, forChange) : 0; } return 0; } bool MgCmdManagerImpl::dynamicChangeEnded(MgView* view, bool apply) { bool changed = false; if (_cmdname == MgCmdSelect::Name() && view) { MgCmdSelect* sel = (MgCmdSelect*)getCommand(); changed = sel && sel->dynamicChangeEnded(view, apply); } return changed; } MgSelection* MgCmdManagerImpl::getSelection(MgView*) { return (MgCmdSelect*)findCommand(MgCmdSelect::Name()); } MgActionDispatcher* MgCmdManagerImpl::getActionDispatcher() { return this; } void MgCmdManagerImpl::doContextAction(const MgMotion* sender, int action) { doAction(sender, action); } MgSnap* MgCmdManagerImpl::getSnap() { return this; } class SnapItem { public: Point2d pt; // 捕捉到的坐标 Point2d base; // 参考线基准点、原始点 float dist; // 捕捉距离 int type; // 特征点类型 int shapeid; // 捕捉到的图形 int handleIndex; // 捕捉到图形上的控制点序号 int handleIndexSrc; // 待确定位置的源图形上的控制点序号,与handleIndex点匹配 SnapItem() {} SnapItem(const Point2d& _pt, const Point2d& _base, float _dist, int _type = 0, int _shapeid = 0, int _handleIndex = -1, int _handleIndexSrc = -1) : pt(_pt), base(_base), dist(_dist), type(_type), shapeid(_shapeid) , handleIndex(_handleIndex), handleIndexSrc(_handleIndexSrc) {} }; static int snapHV(const Point2d& basePt, Point2d& newPt, SnapItem arr[3]) { int ret = 0; float diff; diff = arr[1].dist - fabsf(newPt.x - basePt.x); if (diff > _MGZERO || (diff > - _MGZERO && fabsf(newPt.y - basePt.y) < fabsf(newPt.y - arr[1].base.y))) { arr[1].dist = fabsf(newPt.x - basePt.x); arr[1].base = basePt; newPt.x = basePt.x; arr[1].pt = newPt; arr[1].type = kSnapSameX; ret |= 1; } diff = arr[2].dist - fabsf(newPt.y - basePt.y); if (diff > _MGZERO || (diff > - _MGZERO && fabsf(newPt.x - basePt.x) < fabsf(newPt.x - arr[2].base.x))) { arr[2].dist = fabsf(newPt.y - basePt.y); arr[2].base = basePt; newPt.y = basePt.y; arr[2].pt = newPt; arr[2].type = kSnapSameY; ret |= 2; } return ret; } static void snapPoints(const MgMotion* sender, const MgShape* shape, int ignoreHandle, const int* ignoreids, SnapItem arr[3], Point2d* matchpt) { Box2d snapbox(sender->pointM, 2 * arr[0].dist, 0); // 捕捉容差框 GiTransform* xf = sender->view->xform(); Box2d wndbox(xf->getWndRectW() * xf->worldToModel()); // 视图模型坐标范围 void* it = NULL; for (const MgShape* sp = sender->view->shapes()->getFirstShape(it); sp; sp = sender->view->shapes()->getNextShape(it)) { bool skip = false; for (int t = 0; ignoreids[t] != 0 && !skip; t++) { skip = (ignoreids[t] == sp->getID()); // 跳过当前图形 } if (skip) continue; Box2d extent(sp->shapec()->getExtent()); if (extent.width() < xf->displayToModel(2, true) && extent.height() < xf->displayToModel(2, true)) { // 图形太小就跳过 continue; } bool allOnBox = extent.isIntersect(snapbox); // 不是整体拖动图形 if (allOnBox || extent.isIntersect(wndbox)) { // 或者在视图内可能单向捕捉 int n = sp->shapec()->getHandleCount(); bool curve = sp->shapec()->isKindOf(MgSplines::Type()); bool dragHandle = (!shape || shape->getID() == 0 || sender->pointM == shape->shapec()->getHandlePoint(ignoreHandle)); for (int i = 0; i < n; i++) { // 循环每一个控制点 if (curve && ((i > 0 && i + 1 < n) || sp->shapec()->isClosed())) { continue; // 对于开放曲线只捕捉端点 } Point2d pnt(sp->shapec()->getHandlePoint(i)); // 已有图形的一个顶点 if (allOnBox) { float dist = pnt.distanceTo(sender->pointM); // 触点与顶点匹配 if (arr[0].dist > dist) { arr[0].dist = dist; arr[0].base = sender->pointM; arr[0].pt = pnt; arr[0].type = kSnapPoint; arr[0].shapeid = sp->getID(); arr[0].handleIndex = i; arr[0].handleIndexSrc = dragHandle ? ignoreHandle : -1; } } if (!matchpt && !curve && wndbox.contains(pnt)) { // 在视图可见范围内捕捉X或Y Point2d newPt (sender->pointM); snapHV(pnt, newPt, arr); } int d = matchpt && shape ? (int)shape->shapec()->getHandleCount() - 1 : -1; for (; d >= 0; d--) { // 整体移动图形,顶点匹配 if (d == ignoreHandle || shape->shapec()->isHandleFixed(d)) continue; Point2d ptd (shape->shapec()->getHandlePoint(d)); float dist = pnt.distanceTo(ptd); // 当前图形与其他图形顶点匹配 if (arr[0].dist > dist - _MGZERO) { arr[0].dist = dist; arr[0].base = ptd; arr[0].pt = pnt; arr[0].type = kSnapPoint; arr[0].shapeid = sp->getID(); arr[0].handleIndex = i; arr[0].handleIndexSrc = d; // 因为对当前图形先从startM移到pointM,然后再从pointM移到matchpt *matchpt = sender->pointM + (pnt - ptd); // 所以最后差量为(pnt-ptd) } } } if (allOnBox && sp->shapec()->isKindOf(MgGrid::Type())) { Point2d newPt (sender->pointM); const MgGrid* grid = (const MgGrid*)(sp->shapec()); int type = grid->snap(newPt, arr[1].dist, arr[2].dist); if (type & 1) { arr[1].base = newPt; arr[1].pt = newPt; arr[1].type = kSnapGridX; } if (type & 2) { arr[2].base = newPt; arr[2].pt = newPt; arr[2].type = kSnapGridY; } int d = matchpt && shape ? (int)shape->shapec()->getHandleCount() - 1 : -1; for (; d >= 0; d--) { if (d == ignoreHandle || shape->shapec()->isHandleFixed(d)) continue; Point2d ptd (shape->shapec()->getHandlePoint(d)); float distx = mgMin(arr[0].dist, arr[1].dist); float disty = mgMin(arr[0].dist, arr[2].dist); newPt = ptd; type = grid->snap(newPt, distx, disty); float dist = newPt.distanceTo(ptd); if ((type & 3) == 3 && arr[0].dist > dist - _MGZERO) { arr[0].dist = dist; arr[0].base = ptd; arr[0].pt = newPt; arr[0].type = kSnapPoint; arr[0].shapeid = sp->getID(); arr[0].handleIndex = -1; arr[0].handleIndexSrc = d; // 因为对当前图形先从startM移到pointM,然后再从pointM移到matchpt *matchpt = sender->pointM + (newPt - ptd); // 所以最后差量为(pnt-ptd) } } } } } sender->view->shapes()->freeIterator(it); } // hotHandle: 绘新图时,起始步骤为-1,后续步骤>0;拖动一个或多个整体图形时为-1,拖动顶点时>=0 Point2d MgCmdManagerImpl::snapPoint(const MgMotion* sender, const MgShape* shape, int hotHandle, int ignoreHandle, const int* ignoreids) { int ignoreids_tmp[2] = { shape ? shape->getID() : 0, 0 }; if (!ignoreids) ignoreids = ignoreids_tmp; if (!shape || hotHandle >= (int)shape->shapec()->getHandleCount()) { hotHandle = -1; // 对hotHandle进行越界检查 } _ptSnap = sender->pointM; // 默认结果为当前触点位置 SnapItem arr[3] = { // 设置捕捉容差和捕捉初值 SnapItem(_ptSnap, _ptSnap, mgDisplayMmToModel(3.f, sender)), // XY点捕捉 SnapItem(_ptSnap, _ptSnap, mgDisplayMmToModel(2.f, sender)), // X分量捕捉,竖直线 SnapItem(_ptSnap, _ptSnap, mgDisplayMmToModel(2.f, sender)), // Y分量捕捉,水平线 }; if (shape && shape->getID() == 0 && hotHandle > 0 // 绘图命令中的临时图形 && !shape->shapec()->isKindOf(MgBaseRect::Type())) { // 不是矩形或椭圆 Point2d pt (sender->pointM); if (0 == snapHV(shape->shapec()->getPoint(hotHandle - 1), pt, arr)) { // 和上一个点对齐 float dist = pt.distanceTo(shape->shapec()->getPoint(0)); if (arr[0].dist > dist) { arr[0].dist = dist; arr[0].type = kSnapPoint; arr[0].pt = shape->shapec()->getPoint(0); } } } Point2d pnt(-1e10f, -1e10f); // 当前图形的某一个顶点匹配到其他顶点pnt bool matchpt = (shape && shape->getID() != 0 // 拖动整个图形 && (hotHandle < 0 || (ignoreHandle >= 0 && ignoreHandle != hotHandle))); snapPoints(sender, shape, ignoreHandle, ignoreids, arr, matchpt ? &pnt : NULL); // 在所有图形中捕捉 if (arr[0].type > 0) { // X和Y方向同时捕捉到一个点 _ptSnap = arr[0].pt; // 结果点 _snapBase[0] = arr[0].base; // 原始点 _snapType[0] = arr[0].type; _snapShapeId = arr[0].shapeid; _snapHandle = arr[0].handleIndex; _snapHandleSrc = arr[0].handleIndexSrc; } else { _snapShapeId = 0; _snapHandle = -1; _snapHandleSrc = -1; _snapType[0] = arr[1].type; // 竖直方向捕捉到一个点 if (arr[1].type > 0) { _ptSnap.x = arr[1].pt.x; _snapBase[0] = arr[1].base; } _snapType[1] = arr[2].type; // 水平方向捕捉到一个点 if (arr[2].type > 0) { _ptSnap.y = arr[2].pt.y; _snapBase[1] = arr[2].base; } } return matchpt && pnt.x > -1e8f ? pnt : _ptSnap; // 顶点匹配优先于用触点捕捉结果 } int MgCmdManagerImpl::getSnappedType() { if (_snapType[0] >= kSnapPoint) return _snapType[0]; return (_snapType[0] == kSnapGridX && _snapType[1] == kSnapGridY) ? kSnapPoint : 0; } int MgCmdManagerImpl::getSnappedPoint(Point2d& fromPt, Point2d& toPt) { fromPt = _snapBase[0]; toPt = _ptSnap; return getSnappedType(); } bool MgCmdManagerImpl::getSnappedHandle(int& shapeid, int& handleIndex, int& handleIndexSrc) { shapeid = _snapShapeId; handleIndex = _snapHandle; handleIndexSrc = _snapHandleSrc; return shapeid != 0; } void MgCmdManagerImpl::clearSnap() { _snapType[0] = 0; _snapType[1] = 0; } bool MgCmdManagerImpl::drawSnap(const MgMotion* sender, GiGraphics* gs) { bool ret = false; if (sender->dragging || !sender->view->useFinger()) { if (_snapType[0] >= kSnapPoint) { GiContext ctx(-2, GiColor(0, 255, 0, 200), kGiLineDash, GiColor(0, 255, 0, 64)); ret = gs->drawEllipse(&ctx, _ptSnap, mgDisplayMmToModel(6.f, gs)); } else { GiContext ctx(0, GiColor(0, 255, 0, 200), kGiLineDash, GiColor(0, 255, 0, 64)); GiContext ctxcross(-2, GiColor(0, 255, 0, 200)); if (_snapType[0] > 0) { if (_snapBase[0] == _ptSnap) { if (_snapType[0] == kSnapGridX) { Vector2d vec(0, mgDisplayMmToModel(15.f, gs)); ret = gs->drawLine(&ctxcross, _ptSnap - vec, _ptSnap + vec); gs->drawEllipse(&ctx, _snapBase[0], mgDisplayMmToModel(4.f, gs)); } } else { // kSnapSameX ret = gs->drawLine(&ctx, _snapBase[0], _ptSnap); gs->drawEllipse(&ctx, _snapBase[0], mgDisplayMmToModel(2.5f, gs)); } } if (_snapType[1] > 0) { if (_snapBase[1] == _ptSnap) { if (_snapType[1] == kSnapGridY) { Vector2d vec(mgDisplayMmToModel(15.f, gs), 0); ret = gs->drawLine(&ctxcross, _ptSnap - vec, _ptSnap + vec); gs->drawEllipse(&ctx, _snapBase[1], mgDisplayMmToModel(4.f, gs)); } } else { // kSnapSameY ret = gs->drawLine(&ctx, _snapBase[1], _ptSnap); gs->drawEllipse(&ctx, _snapBase[1], mgDisplayMmToModel(2.5f, gs)); } } } } return ret; } void MgCmdManagerImpl::eraseWnd(const MgMotion* sender) { Box2d snap(sender->view->xform()->getWndRectW() * sender->view->xform()->worldToModel()); std::vector<int> delIds; void *it = NULL; MgShapes* s = sender->view->shapes(); for (MgShape* shape = s->getFirstShape(it); shape; shape = s->getNextShape(it)) { if (shape->shape()->hitTestBox(snap)) { delIds.push_back(shape->getID()); } } s->freeIterator(it); if (!delIds.empty() && sender->view->shapeWillDeleted(s->findShape(delIds.front()))) { MgShapesLock locker(sender->view->doc(), MgShapesLock::Remove); for (std::vector<int>::iterator i = delIds.begin(); i != delIds.end(); ++i) { MgShape* shape = s->findShape(*i); if (shape && sender->view->removeShape(shape)) { shape->release(); } } sender->view->regen(); } }
17,525
6,492
#include <vtkActor.h> #include <vtkBYUReader.h> #include <vtkCamera.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkOBJReader.h> #include <vtkPLYReader.h> #include <vtkPolyDataMapper.h> #include <vtkPolyDataReader.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkSTLReader.h> #include <vtkSmartPointer.h> #include <vtkSphereSource.h> #include <vtkTimerLog.h> #include <vtkXMLPolyDataReader.h> #include <vtksys/RegularExpression.hxx> #include <vtksys/SystemTools.hxx> namespace { vtkSmartPointer<vtkPolyData> ReadPolyData(const char* fileName); } #include <vtkActor.h> #include <vtkCamera.h> namespace { void SaveSceneToFile(std::string fileName, vtkActor* actor, vtkCamera* camera); } #include <vtkActor.h> #include <vtkCamera.h> namespace { void RestoreSceneFromFile(std::string fileName, vtkActor* actor, vtkCamera* camera); } int main(int argc, char* argv[]) { auto polyData = ReadPolyData(argc > 1 ? argv[1] : ""); // Visualize vtkNew<vtkNamedColors> colors; vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputData(polyData); vtkNew<vtkActor> actor; actor->SetMapper(mapper); actor->GetProperty()->SetDiffuseColor( colors->GetColor3d("Crimson").GetData()); actor->GetProperty()->SetSpecular(.6); actor->GetProperty()->SetSpecularPower(30); ; vtkNew<vtkRenderer> renderer; vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); vtkNew<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(actor); renderer->SetBackground(colors->GetColor3d("Silver").GetData()); // Interact to change camera renderWindow->Render(); renderWindowInteractor->Start(); // After the interaction is done, save the scene SaveSceneToFile(argv[2], actor, renderer->GetActiveCamera()); renderWindow->Render(); renderWindowInteractor->Start(); // After interaction , restore the scene RestoreSceneFromFile(argv[2], actor, renderer->GetActiveCamera()); renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } namespace { #include <fstream> void SaveSceneToFile(std::string fileName, vtkActor* /* actor */, vtkCamera* camera) { // Actor // Position, orientation, origin, scale, usrmatrix, usertransform // Camera // FocalPoint, Position, ViewUp, ViewAngle, ClippingRange std::ofstream saveFile(fileName, std::ofstream::out); double vector[3]; double scalar; camera->GetFocalPoint(vector); saveFile << "Camera:FocalPoint " << vector[0] << ", " << vector[1] << ", " << vector[2] << std::endl; camera->GetPosition(vector); saveFile << "Camera:Position " << vector[0] << ", " << vector[1] << ", " << vector[2] << std::endl; camera->GetViewUp(vector); saveFile << "Camera:ViewUp " << vector[0] << ", " << vector[1] << ", " << vector[2] << std::endl; scalar = camera->GetViewAngle(); saveFile << "Camera:ViewAngle " << scalar << std::endl; camera->GetClippingRange(vector); saveFile << "Camera:ClippingRange " << vector[0] << ", " << vector[1] << std::endl; saveFile.close(); } } // namespace namespace { #include <fstream> void RestoreSceneFromFile(std::string fileName, vtkActor* /* actor */, vtkCamera* camera) { std::ifstream saveFile(fileName); std::string line; vtksys::RegularExpression reCP("^Camera:Position"); vtksys::RegularExpression reCFP("^Camera:FocalPoint"); vtksys::RegularExpression reCVU("^Camera:ViewUp"); vtksys::RegularExpression reCVA("^Camera:ViewAngle"); vtksys::RegularExpression reCCR("^Camera:ClippingRange"); vtksys::RegularExpression floatNumber( "[^0-9\\.\\-]*([0-9e\\.\\-]*[^,])[^0-9\\.\\-]*([0-9e\\.\\-]*[^,])[^0-9\\." "\\-]*([0-9e\\.\\-]*[^,])"); vtksys::RegularExpression floatScalar("[^0-9\\.\\-]*([0-9\\.\\-e]*[^,])"); while (std::getline(saveFile, line) && !saveFile.eof()) { if (reCFP.find(line)) { std::string rest(line, reCFP.end()); if (floatNumber.find(rest)) { camera->SetFocalPoint(atof(floatNumber.match(1).c_str()), atof(floatNumber.match(2).c_str()), atof(floatNumber.match(3).c_str())); } } else if (reCP.find(line)) { std::string rest(line, reCP.end()); if (floatNumber.find(rest)) { camera->SetPosition(atof(floatNumber.match(1).c_str()), atof(floatNumber.match(2).c_str()), atof(floatNumber.match(3).c_str())); } } else if (reCVU.find(line)) { std::string rest(line, reCVU.end()); if (floatNumber.find(rest)) { camera->SetViewUp(atof(floatNumber.match(1).c_str()), atof(floatNumber.match(2).c_str()), atof(floatNumber.match(3).c_str())); } } else if (reCVA.find(line)) { std::string rest(line, reCVA.end()); if (floatScalar.find(rest)) { camera->SetViewAngle(atof(floatScalar.match(1).c_str())); } } else if (reCCR.find(line)) { std::string rest(line, reCCR.end()); if (floatNumber.find(rest)) { camera->SetClippingRange(atof(floatNumber.match(1).c_str()), atof(floatNumber.match(2).c_str())); } } else { std::cout << "Unrecognized line: " << line << std::endl; } } saveFile.close(); } } // namespace namespace { vtkSmartPointer<vtkPolyData> ReadPolyData(const char* fileName) { vtkSmartPointer<vtkPolyData> polyData; std::string extension = vtksys::SystemTools::GetFilenameExtension(std::string(fileName)); if (extension == ".ply") { vtkNew<vtkPLYReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".vtp") { vtkNew<vtkXMLPolyDataReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".obj") { vtkNew<vtkOBJReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".stl") { vtkNew<vtkSTLReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".vtk") { vtkNew<vtkPolyDataReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".g") { vtkNew<vtkBYUReader> reader; reader->SetGeometryFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else { vtkNew<vtkSphereSource> source; source->Update(); polyData = source->GetOutput(); } return polyData; } } // namespace
7,019
2,442
#include "Number.h" #include <iostream> using namespace std; RealNumber::RealNumber(double x){ number=x; } RealNumber RealNumber::add(const RealNumber& other){ number+=other.number; return *this; } RealNumber RealNumber::mul(const RealNumber& other){ number*=other.number; return *this; } void Number::print(){ cout<<number<<endl; } IntegerNumber::IntegerNumber(int x):RealNumber(x){ integernumber=x; } IntegerNumber IntegerNumber::add(const IntegerNumber& other){ integernumber+=other.integernumber; return *this; } IntegerNumber IntegerNumber::mul(const IntegerNumber& other){ integernumber*=other.integernumber; return *this; } void IntegerNumber::print(){ cout<<integernumber<<endl; } ComplexNumber::ComplexNumber(double x, double y){ first=x,last=y; } ComplexNumber ComplexNumber::add(const ComplexNumber& other){ first+=other.first; last+=other.last; return *this; } ComplexNumber ComplexNumber::mul(const ComplexNumber& other){ first=first*other.first+last*other.last; last=first*other.last+last*other.first; return *this; } void ComplexNumber::print(){ cout<<first<<" "<<last<<endl; }
1,190
390
#define BOOST_TEST_MODULE TestDBI #include <boost/test/included/unit_test.hpp> #include <list> #include <dbi.h> using namespace uMediaServer::DBI; typedef SQLiteDBI sql_t; const std::string db_init = R"__( drop table if exists books; create table books ( id varchar primary key, author varchar, title varchar, pages integer, weight float, instock integer); insert into books values('kobzar', 'Taras Shevchenko', 'Kobzar', 452, 1.5, 1); insert into books values('mdick', 'Herman Melville', 'Moby-Dick', 927, 3.2, 0); )__"; const std::string db_uri = ":memory:"; struct DbiFixture { DbiFixture() : sql(db_uri) { sql << db_init; } sql_t sql; }; namespace test { struct book { std::string id; std::string author; std::string title; size_t pages; float weight; bool instock; }; } void report_error(std::ostream & s, const uMediaServer::DBI::Exception & e) { using namespace uMediaServer::DBI; s << *boost::get_error_info<boost::throw_file>(e) << "(" << *boost::get_error_info<boost::throw_line>(e) << "): " << "<" << *boost::get_error_info<boost::throw_function>(e) << ">: "; if (auto * info_ptr = boost::get_error_info<throw_db_error>(e)) s << *info_ptr << " "; if (auto * info_ptr = boost::get_error_info<throw_db_uri>(e)) s << "{" << *info_ptr << "} "; if (auto * info_ptr = boost::get_error_info<throw_typeid>(e)) s << "{" << *info_ptr << "} "; s << std::endl; } BOOST_FIXTURE_TEST_CASE(dbi_exceptions, DbiFixture) { // wrong database uri using namespace uMediaServer::DBI; BOOST_CHECK_THROW(sql_t("/fake_dir/fake_file"), OpenError); // sql syntax error BOOST_CHECK_THROW(sql << "select some hiking boots from books;" << "drop table 'books';", ExecError); // wrong table name BOOST_CHECK_THROW(sql << "select * from 'book';", ExecError); // into type mismatch std::list<int> titles; BOOST_CHECK_THROW((sql << "select title from 'books';", into(titles)), ConvError); // binding type mismatch // FIXME: sqlite silently accepts type mismatch while binding // int id = 10; std::string title; // BOOST_CHECK_THROW((sql << "select title from 'books' where id=?;", // from(id), into(title)), ConvError); // not enough storage provided std::string id("kobzar"), title, author; BOOST_CHECK_THROW((sql << "select title, author, weight from 'books' where id=?;", from(id), into(author), into(title)), RangeError); id = "CAD"; author = "Ian Cain"; title = "Corporate America for Dummies"; BOOST_CHECK_THROW((sql << "insert into 'books' values(?, ?, ?, ?, ?, ?);", from(id), from(author), from(title)), RangeError); // error reporting try { sql << "errorneus sql query;"; } catch (const Exception & e) { report_error(std::cerr, e); } try { int title; sql << "select title from 'books' where id='kobzar';", into(title); } catch (const Exception & e) { report_error(std::cerr, e); } try { std::string data; sql << "select title, author from 'books' where id='kobzar';", into(data); } catch (const Exception & e) { report_error(std::cerr, e); } } BOOST_FIXTURE_TEST_CASE(select_trivial_types, DbiFixture) { float weight; std::string author, title; size_t pages; bool instock; sql << "select author, title, pages, weight, instock from books where id='kobzar';", into(author), into(title), into(pages), into(weight), into(instock); BOOST_CHECK_EQUAL(author, "Taras Shevchenko"); BOOST_CHECK_EQUAL(title, "Kobzar"); BOOST_CHECK_EQUAL(pages, 452); BOOST_CHECK_EQUAL(weight, 1.5); BOOST_CHECK_EQUAL(instock, true); } BOOST_FIXTURE_TEST_CASE(insert_trivial_types, DbiFixture) { double weight = 0.8; std::string id("c++"), author("Bjarne Stroustrup"), title("A Tour of C++"); size_t pages = 192; bool instock = false; sql << "insert into books values(?, ?, ?, ?, ?, ?);", from(id), from(author), from(title), from(pages), from(weight), from(instock); weight = 0.0; id.clear(); author.clear(); title.clear(); pages = 0; instock = true; sql << "select author, title, pages, weight, instock from books where id='c++';", into(author), into(title), into(pages), into(weight), into(instock); BOOST_CHECK_EQUAL(author, "Bjarne Stroustrup"); BOOST_CHECK_EQUAL(title, "A Tour of C++"); BOOST_CHECK_EQUAL(pages, 192); BOOST_CHECK_EQUAL(weight, 0.8); BOOST_CHECK_EQUAL(instock, false); } #include <boost/fusion/adapted.hpp> BOOST_FUSION_ADAPT_STRUCT ( test::book, (std::string, id) (std::string, author) (std::string, title) (size_t, pages) (float, weight) (bool, instock)) BOOST_FIXTURE_TEST_CASE(composite_types, DbiFixture) { test::book book; test::book expected{"CAD", "Ian Cain", "Corporate America for Dummies", 235, 1.3, true}; size_t row_count; sql << "insert into books values(?, ?, ?, ?, ?, ?);", from(expected); sql << "select count(*) from books;", into(row_count); BOOST_CHECK_EQUAL(row_count, 3); sql << "select * from books where id=?;", from(expected), into(book); BOOST_CHECK(boost::fusion::equal_to(book, expected)); sql << "delete from books where id=?;", from(book); sql << "select count(*) from books;", into(row_count); BOOST_CHECK_EQUAL(row_count, 2); } BOOST_FIXTURE_TEST_CASE(list_select, DbiFixture) { std::list<std::string> strings; std::list<std::string> expected{"kobzar", "Taras Shevchenko", "Kobzar"}; sql << "select id, author, title from books where id=?;", from(expected.front()), into(strings); BOOST_CHECK_EQUAL_COLLECTIONS(strings.begin(), strings.end(), expected.begin(), expected.end()); strings.clear(); expected = {"Kobzar", "Moby-Dick"}; sql << "select title from books;", into(strings); BOOST_CHECK_EQUAL_COLLECTIONS(strings.begin(), strings.end(), expected.begin(), expected.end()); std::list<test::book> books; std::list<test::book> expected_books{ {"kobzar", "Taras Shevchenko", "Kobzar", 452, 1.5, true}, {"mdick", "Herman Melville", "Moby-Dick", 927, 3.2, false} }; sql << "select * from books;", into(books); BOOST_CHECK_EQUAL(books.size(), expected_books.size()); auto it = books.begin(); auto eit = expected_books.begin(); for (; it != books.end(); ++it, ++eit) BOOST_CHECK(boost::fusion::equal_to(*it, *eit)); // assure empty list books.clear(); std::string non_existent("unknown"); sql << "select * from books where id=?;", from(non_existent), into(books); BOOST_CHECK(books.empty()); }
6,428
2,562
#ifndef RS_MODULARINTEGER_INL #define RS_MODULARINTEGER_INL #include "ModularInteger.h" // why is this include needed? maybe it's not using namespace RSLib; // construction/destruction: template<class T> rsModularInteger<T>::rsModularInteger(rsUint64 initialValue, rsUint64 modulusToUse) { modulus = modulusToUse; value = initialValue; rsAssert( value >= T(0) && value < modulus ); } template<class T> rsModularInteger<T>::rsModularInteger(const rsModularInteger<T>& other) { modulus = other.modulus; value = other.value; } // operators: template<class T> rsModularInteger<T> rsModularInteger<T>::operator-() const { if( value == 0 ) return *this; else return rsModularInteger<T>(modulus-value, modulus); } template<class T> bool rsModularInteger<T>::operator==(const rsModularInteger<T>& other) const { return value == other.value && modulus == other.modulus; } template<class T> bool rsModularInteger<T>::operator!=(const rsModularInteger<T>& other) const { return !(*this == other); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator+(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r = this->value + other.value; if( r >= modulus ) r -= modulus; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator-(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r; if( other.value > this->value ) r = modulus + this->value - other.value; else r = this->value - other.value; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator*(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r = (this->value * other.value) % modulus; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator/(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); return *this * rsModularInverse(other.value, modulus); } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator+=(const rsModularInteger<T> &other) { *this = *this + other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator-=(const rsModularInteger<T> &other) { *this = *this - other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator*=(const rsModularInteger<T> &other) { *this = *this * other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator/=(const rsModularInteger<T> &other) { *this = *this / other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator++() { *this = *this + rsModularInteger<T>(1, modulus); return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator--() { *this = *this - rsModularInteger<T>(1, modulus); return *this; } #endif
2,947
1,067
/*++ Copyright (c) 2000 Microsoft Corporation Module Name: KingsQuestMask.cpp Abstract: The app calls UnmapViewOfFile with a bogus address - an address that wasn't obtained from MapViewOfFile. We validate the address before calling UnmapViewOfFile. History: 11/20/2000 maonis Created --*/ #include "precomp.h" typedef BOOL (WINAPI *_pfn_UnmapViewOfFile)(LPCVOID lpBaseAddress); IMPLEMENT_SHIM_BEGIN(KingsQuestMask) #include "ShimHookMacro.h" APIHOOK_ENUM_BEGIN APIHOOK_ENUM_ENTRY(MapViewOfFile) APIHOOK_ENUM_ENTRY(UnmapViewOfFile) APIHOOK_ENUM_END // Link list of base addresses struct MAPADDRESS { MAPADDRESS *next; LPCVOID pBaseAddress; }; MAPADDRESS *g_pBaseAddressList; /*++ Function Description: Add a base address to the linked list of addresses. Does not add if the address is NULL or a duplicate. Arguments: IN pBaseAddress - base address returned by MapViewOfFile. Return Value: None History: 11/20/2000 maonis Created --*/ VOID AddBaseAddress( IN LPCVOID pBaseAddress ) { if (pBaseAddress) { MAPADDRESS *pMapAddress = g_pBaseAddressList; while (pMapAddress) { if (pMapAddress->pBaseAddress == pBaseAddress) { return; } pMapAddress = pMapAddress->next; } pMapAddress = (MAPADDRESS *) malloc(sizeof MAPADDRESS); pMapAddress->pBaseAddress = pBaseAddress; pMapAddress->next = g_pBaseAddressList; g_pBaseAddressList = pMapAddress; } } /*++ Function Description: Remove a base address if it can be found in the linked list of addresses. Arguments: IN pBaseAddress - the base address to remove. Return Value: TRUE if the address is found. FALSE if the address is not found. History: 11/20/2000 maonis Created --*/ BOOL RemoveBaseAddress( IN LPCVOID pBaseAddress ) { MAPADDRESS *pMapAddress = g_pBaseAddressList; MAPADDRESS *last = NULL; while (pMapAddress) { if (pMapAddress->pBaseAddress == pBaseAddress) { if (last) { last->next = pMapAddress->next; } else { g_pBaseAddressList = pMapAddress->next; } free(pMapAddress); return TRUE; } last = pMapAddress; pMapAddress = pMapAddress->next; } return FALSE; } /*++ Add the base address to our list. --*/ LPVOID APIHOOK(MapViewOfFile)( HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap ) { LPVOID pRet = ORIGINAL_API(MapViewOfFile)( hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap); AddBaseAddress(pRet); DPFN( eDbgLevelInfo, "MapViewOfFile: added base address = 0x%x\n", pRet); return pRet; } /*++ Remove the address from our list if it can be found; otherwise do nothing. --*/ BOOL APIHOOK(UnmapViewOfFile)( LPCVOID lpBaseAddress ) { BOOL bRet; if (RemoveBaseAddress(lpBaseAddress)) { bRet = ORIGINAL_API(UnmapViewOfFile)(lpBaseAddress); if (bRet) { DPFN( eDbgLevelInfo, "UnmapViewOfFile unmapped address 0x%x\n", lpBaseAddress); } return bRet; } else { DPFN( eDbgLevelError,"UnmapViewOfFile was passed an invalid address 0x%x\n", lpBaseAddress); return FALSE; } } /*++ Free the list. --*/ BOOL NOTIFY_FUNCTION( DWORD fdwReason) { if (fdwReason == DLL_PROCESS_DETACH) { DWORD dwCount = 0; MAPADDRESS *pMapAddress = g_pBaseAddressList; while (pMapAddress) { g_pBaseAddressList = pMapAddress->next; ORIGINAL_API(UnmapViewOfFile)(pMapAddress->pBaseAddress); free(pMapAddress); pMapAddress = g_pBaseAddressList; dwCount++; } if (dwCount > 0) { DPFN( eDbgLevelInfo,"%d addresses not unmapped.", dwCount); } } return TRUE; } /*++ Register hooked functions --*/ HOOK_BEGIN APIHOOK_ENTRY(KERNEL32.DLL, MapViewOfFile) APIHOOK_ENTRY(KERNEL32.DLL, UnmapViewOfFile) CALL_NOTIFY_FUNCTION HOOK_END IMPLEMENT_SHIM_END
4,712
1,691
// // Python wrapper class for CvPlot // // #include "CvGameCoreDLL.h" #include "CyPlot.h" #include "CyCity.h" #include "CyArea.h" #include "CyUnit.h" #include "CvPlot.h" CyPlot::CyPlot(CvPlot* pPlot) : m_pPlot(pPlot) { } CyPlot::CyPlot() : m_pPlot(NULL) { } void CyPlot::erase() { if (m_pPlot) m_pPlot->erase(); } //Rhye - start void CyPlot::eraseAIDevelopment() { if (m_pPlot) m_pPlot->eraseAIDevelopment(); } //Rhye - end NiPoint3 CyPlot::getPoint() { return m_pPlot ? m_pPlot->getPoint() : NiPoint3(0,0,0); } int CyPlot::getTeam() { return m_pPlot ? m_pPlot->getTeam() : -1; } void CyPlot::nukeExplosion(int iRange, CyUnit* pNukeUnit) { if (m_pPlot) m_pPlot->nukeExplosion(iRange, pNukeUnit->getUnit()); } bool CyPlot::isConnectedTo(CyCity* pCity) { return m_pPlot ? m_pPlot->isConnectedTo(pCity->getCity()) : false; } bool CyPlot::isConnectedToCapital(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->isConnectedToCapital((PlayerTypes) ePlayer): false; } int CyPlot::getPlotGroupConnectedBonus(int /*PlayerTypes*/ ePlayer, int /*BonusTypes*/ eBonus) { return m_pPlot ? m_pPlot->getPlotGroupConnectedBonus((PlayerTypes) ePlayer, (BonusTypes) eBonus) : -1; } bool CyPlot::isPlotGroupConnectedBonus(int /*PlayerTypes*/ ePlayer, int /*BonusTypes*/ eBonus) { return m_pPlot ? m_pPlot->isPlotGroupConnectedBonus((PlayerTypes) ePlayer, (BonusTypes) eBonus) : false; } bool CyPlot::isAdjacentPlotGroupConnectedBonus(int /*PlayerTypes*/ ePlayer, int /*BonusTypes*/ eBonus) { return m_pPlot ? m_pPlot->isAdjacentPlotGroupConnectedBonus((PlayerTypes) ePlayer, (BonusTypes) eBonus) : false; } void CyPlot::updateVisibility() { if (m_pPlot) { m_pPlot->updateVisibility(); } } bool CyPlot::isAdjacentToArea(CyArea* pArea) { return m_pPlot ? m_pPlot->isAdjacentToArea(pArea->getArea()) : false; } bool CyPlot::shareAdjacentArea(CyPlot* pPlot) { return m_pPlot ? m_pPlot->shareAdjacentArea(pPlot->getPlot()) : false; } bool CyPlot::isAdjacentToLand() { return m_pPlot ? m_pPlot->isAdjacentToLand() : false; } bool CyPlot::isCoastalLand() { return m_pPlot ? m_pPlot->isCoastalLand() : false; } bool CyPlot::isWithinTeamCityRadius(int /*TeamTypes*/ eTeam, int /*PlayerTypes*/ eIgnorePlayer) { return m_pPlot ? m_pPlot->isWithinTeamCityRadius((TeamTypes) eTeam, (PlayerTypes) eIgnorePlayer) : false; } bool CyPlot::isLake() { return m_pPlot ? m_pPlot->isLake() : false; } bool CyPlot::isFreshWater() { return m_pPlot ? m_pPlot->isFreshWater() : false; } bool CyPlot::isPotentialIrrigation() { return m_pPlot ? m_pPlot->isPotentialIrrigation() : false; } bool CyPlot::canHavePotentialIrrigation() { return m_pPlot ? m_pPlot->canHavePotentialIrrigation() : false; } bool CyPlot::isIrrigationAvailable(bool bIgnoreSelf) { return m_pPlot ? m_pPlot->isIrrigationAvailable(bIgnoreSelf) : false; } bool CyPlot::isRiverSide() { return m_pPlot ? m_pPlot->isRiverSide() : false; } bool CyPlot::isRiver() { return m_pPlot ? m_pPlot->isRiver() : false; } bool CyPlot::isRiverConnection(int /*DirectionTypes*/ eDirection) { return m_pPlot ? m_pPlot->isRiverConnection((DirectionTypes) eDirection) : false; } int CyPlot::getNearestLandArea() { return m_pPlot ? m_pPlot->getNearestLandArea() : -1; } CyPlot* CyPlot::getNearestLandPlot() { return m_pPlot ? new CyPlot(m_pPlot->getNearestLandPlot()) : NULL; } int CyPlot::seeFromLevel(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->seeFromLevel((TeamTypes)eTeam) : -1; } int CyPlot::seeThroughLevel() { return m_pPlot ? m_pPlot->seeThroughLevel() : -1; } bool CyPlot::canHaveBonus(int /*BonusTypes*/ eBonus, bool bIgnoreLatitude) { return m_pPlot ? m_pPlot->canHaveBonus((BonusTypes)eBonus, bIgnoreLatitude) : false; } bool CyPlot::canHaveImprovement(int /* ImprovementTypes */ eImprovement, int /*TeamTypes*/ eTeam, bool bPotential) { return m_pPlot ? m_pPlot->canHaveImprovement(((ImprovementTypes)eImprovement), ((TeamTypes)eTeam), bPotential) : false; } bool CyPlot::canBuild(int /*BuildTypes*/ eBuild, int /*PlayerTypes*/ ePlayer, bool bTestVisible) { return m_pPlot ? m_pPlot->canBuild((BuildTypes) eBuild, (PlayerTypes) ePlayer, bTestVisible) : false; } int CyPlot::getBuildTime(int /* BuildTypes */ eBuild) { return m_pPlot ? m_pPlot->getBuildTime((BuildTypes)eBuild) : -1; } int CyPlot::getBuildTurnsLeft(int /*BuildTypes*/ eBuild, int iNowExtra, int iThenExtra) { return m_pPlot ? m_pPlot->getBuildTurnsLeft((BuildTypes) eBuild, iNowExtra, iThenExtra) : -1; } int CyPlot::getFeatureProduction(int /*BuildTypes*/ eBuild, int /*TeamTypes*/ eTeam, CyCity* ppCity) { CvCity* tempCity = ppCity->getCity(); return m_pPlot ? m_pPlot->getFeatureProduction((BuildTypes) eBuild, (TeamTypes) eTeam, &tempCity) : -1; } CyUnit* CyPlot::getBestDefender(int /*PlayerTypes*/ eOwner, int /*PlayerTypes*/ eAttackingPlayer, CyUnit* pAttacker, bool bTestAtWar, bool bTestPotentialEnemy, bool bTestCanMove) { return m_pPlot ? new CyUnit(m_pPlot->getBestDefender((PlayerTypes) eOwner, (PlayerTypes) eAttackingPlayer, pAttacker->getUnit(), bTestAtWar, bTestPotentialEnemy, bTestCanMove)) : NULL; } CyUnit* CyPlot::getSelectedUnit() { return m_pPlot ? new CyUnit(m_pPlot->getSelectedUnit()) : NULL; } int CyPlot::getUnitPower(int /* PlayerTypes */ eOwner) { return m_pPlot ? m_pPlot->getUnitPower((PlayerTypes)eOwner) : -1; } int CyPlot::movementCost(CyUnit* pUnit, CyPlot* pFromPlot) { return m_pPlot ? m_pPlot->movementCost(pUnit->getUnit(), pFromPlot->getPlot()) : -1; } int CyPlot::defenseModifier(int iDefendTeam, bool bIgnoreBuilding, bool bHelp) { return m_pPlot ? m_pPlot->defenseModifier((TeamTypes)iDefendTeam, bIgnoreBuilding, bHelp) : -1; } int CyPlot::getExtraMovePathCost() { return m_pPlot ? m_pPlot->getExtraMovePathCost() : -1; } void CyPlot::changeExtraMovePathCost(int iChange) { if (m_pPlot) m_pPlot->changeExtraMovePathCost(iChange); } bool CyPlot::isAdjacentOwned() { return m_pPlot ? m_pPlot->isAdjacentOwned() : false; } bool CyPlot::isAdjacentPlayer(int /*PlayerTypes*/ ePlayer, bool bLandOnly) { return m_pPlot ? m_pPlot->isAdjacentPlayer((PlayerTypes)ePlayer, bLandOnly) : false; } bool CyPlot::isAdjacentTeam(int /*TeamTypes*/ ePlayer, bool bLandOnly) { return m_pPlot ? m_pPlot->isAdjacentTeam((TeamTypes)ePlayer, bLandOnly) : false; } bool CyPlot::isWithinCultureRange(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->isWithinCultureRange((PlayerTypes)ePlayer) : false; } int CyPlot::getNumCultureRangeCities(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->getNumCultureRangeCities((PlayerTypes)ePlayer) : -1; } int /*PlayerTypes*/ CyPlot::calculateCulturalOwner() { return m_pPlot ? m_pPlot->calculateCulturalOwner() : -1; } bool CyPlot::isOwned() { return m_pPlot ? m_pPlot->isOwned() : false; } bool CyPlot::isBarbarian() { return m_pPlot ? m_pPlot->isBarbarian() : false; } bool CyPlot::isRevealedBarbarian() { return m_pPlot ? m_pPlot->isRevealedBarbarian() : false; } bool CyPlot::isVisible(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->isVisible((TeamTypes)eTeam, bDebug) : false; } bool CyPlot::isActiveVisible(bool bDebug) { return m_pPlot ? m_pPlot->isActiveVisible(bDebug) : false; } bool CyPlot::isVisibleToWatchingHuman() { return m_pPlot ? m_pPlot->isVisibleToWatchingHuman() : false; } bool CyPlot::isAdjacentVisible(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->isAdjacentVisible((TeamTypes) eTeam, bDebug) : false; } bool CyPlot::isAdjacentNonvisible(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isAdjacentNonvisible((TeamTypes) eTeam) : false; } bool CyPlot::isAdjacentRevealed(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isAdjacentRevealed((TeamTypes) eTeam) : false; } bool CyPlot::isAdjacentNonrevealed(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isAdjacentNonrevealed((TeamTypes) eTeam) : false; } void CyPlot::removeGoody() { if (m_pPlot) { m_pPlot->removeGoody(); } } bool CyPlot::isGoody() { return m_pPlot ? m_pPlot->isGoody() : false; } bool CyPlot::isRevealedGoody(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isRevealedGoody((TeamTypes) eTeam) : false; } bool CyPlot::isCity() { return m_pPlot ? m_pPlot->isCity() : false; } bool CyPlot::isFriendlyCity(CyUnit* pUnit, bool bCheckImprovement) { return m_pPlot ? m_pPlot->isFriendlyCity(*(pUnit->getUnit()), bCheckImprovement) : false; } bool CyPlot::isEnemyCity(CyUnit* pUnit) { return m_pPlot ? m_pPlot->isEnemyCity(*(pUnit->getUnit())) : false; } bool CyPlot::isOccupation() { return m_pPlot ? m_pPlot->isOccupation() : false; } bool CyPlot::isBeingWorked() { return m_pPlot ? m_pPlot->isBeingWorked() : false; } bool CyPlot::isUnit() { return m_pPlot ? m_pPlot->isUnit() : false; } bool CyPlot::isInvestigate(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isInvestigate((TeamTypes) eTeam) : false; } bool CyPlot::isVisibleEnemyDefender(CyUnit* pUnit) { return m_pPlot ? m_pPlot->isVisibleEnemyDefender(pUnit->getUnit()) : false; } int CyPlot::getNumDefenders(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->getNumDefenders((PlayerTypes) ePlayer) : -1; } int CyPlot::getNumVisibleEnemyDefenders(CyUnit* pUnit) { return m_pPlot ? m_pPlot->getNumVisibleEnemyDefenders(pUnit->getUnit()) : -1; } int CyPlot::getNumVisiblePotentialEnemyDefenders(CyUnit* pUnit) { return m_pPlot ? m_pPlot->getNumVisiblePotentialEnemyDefenders(pUnit->getUnit()) : -1; } bool CyPlot::isVisibleEnemyUnit(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->isVisibleEnemyUnit((PlayerTypes) ePlayer) : false; } bool CyPlot::isVisibleOtherUnit(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->isVisibleOtherUnit((PlayerTypes) ePlayer) : false; } bool CyPlot::isFighting() { return m_pPlot ? m_pPlot->isFighting() : false; } bool CyPlot::canHaveFeature(int /*FeatureTypes*/ eFeature) { return m_pPlot ? m_pPlot->canHaveFeature((FeatureTypes)eFeature) : false; } bool CyPlot::isRoute() { return m_pPlot ? m_pPlot->isRoute() : false; } bool CyPlot::isNetworkTerrain(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isNetworkTerrain((TeamTypes) eTeam) : false; } bool CyPlot::isBonusNetwork(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isBonusNetwork((TeamTypes) eTeam) : false; } bool CyPlot::isTradeNetworkImpassable(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isTradeNetworkImpassable((TeamTypes) eTeam) : false; } bool CyPlot::isTradeNetwork(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isTradeNetwork((TeamTypes)eTeam) : false; } bool CyPlot::isTradeNetworkConnected(CyPlot* pPlot, int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isTradeNetworkConnected(pPlot->getPlot(), (TeamTypes)eTeam) : false; } bool CyPlot::isValidDomainForLocation(CyUnit* pUnit) const { return (m_pPlot && pUnit && pUnit->getUnit()) ? m_pPlot->isValidDomainForLocation(*(pUnit->getUnit())) : false; } bool CyPlot::isValidDomainForAction(CyUnit* pUnit) const { return (m_pPlot && pUnit && pUnit->getUnit()) ? m_pPlot->isValidDomainForAction(*(pUnit->getUnit())) : false; } bool CyPlot::isImpassable() { return m_pPlot ? m_pPlot->isImpassable() : false; } int CyPlot::getX() { return m_pPlot ? m_pPlot->getX_INLINE() : -1; } int CyPlot::getY() { return m_pPlot ? m_pPlot->getY_INLINE() : -1; } bool CyPlot::at(int iX, int iY) { return m_pPlot ? m_pPlot->at(iX, iY) : false; } int CyPlot::getLatitude() { return m_pPlot ? m_pPlot->getLatitude() : -1; } CyArea* CyPlot::area() { return m_pPlot ? new CyArea(m_pPlot->area()) : NULL; } CyArea* CyPlot::waterArea() { return m_pPlot ? new CyArea(m_pPlot->waterArea()) : NULL; } int CyPlot::getArea() { return m_pPlot ? m_pPlot->getArea() : -1; } //Rhye - start void CyPlot::setArea(int iNewValue) { if (m_pPlot) m_pPlot->setArea(iNewValue); } //Rhye - end int CyPlot::getUpgradeProgress() { return m_pPlot ? m_pPlot->getUpgradeProgress() : -1; } int CyPlot::getUpgradeTimeLeft(int /*ImprovementTypes*/ eImprovement, int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->getUpgradeTimeLeft((ImprovementTypes) eImprovement, (PlayerTypes) ePlayer) : -1; } void CyPlot::setUpgradeProgress(int iNewValue) { if (m_pPlot) m_pPlot->setUpgradeProgress(iNewValue); } void CyPlot::changeUpgradeProgress(int iChange) { if (m_pPlot) m_pPlot->changeUpgradeProgress(iChange); } int CyPlot::getForceUnownedTimer() { return m_pPlot ? m_pPlot->getForceUnownedTimer() : -1; } bool CyPlot::isForceUnowned() { return m_pPlot ? m_pPlot->isForceUnowned() : false; } void CyPlot::setForceUnownedTimer(int iNewValue) { if (m_pPlot) m_pPlot->setForceUnownedTimer(iNewValue); } void CyPlot::changeForceUnownedTimer(int iChange) { if (m_pPlot) m_pPlot->changeForceUnownedTimer(iChange); } int CyPlot::getCityRadiusCount() { return m_pPlot ? m_pPlot->getCityRadiusCount() : -1; } int CyPlot::isCityRadius() { return m_pPlot ? m_pPlot->isCityRadius() : -1; } bool CyPlot::isStartingPlot() { return m_pPlot ? m_pPlot->isStartingPlot() : false; } void CyPlot::setStartingPlot(bool bNewValue) { if (m_pPlot) m_pPlot->setStartingPlot(bNewValue); } bool CyPlot::isNOfRiver() { return m_pPlot ? m_pPlot->isNOfRiver() : false; } void CyPlot::setNOfRiver(bool bNewValue, CardinalDirectionTypes eRiverDir) { if (m_pPlot) { m_pPlot->setNOfRiver(bNewValue, eRiverDir); } } bool CyPlot::isWOfRiver() { return m_pPlot ? m_pPlot->isWOfRiver() : false; } void CyPlot::setWOfRiver(bool bNewValue, CardinalDirectionTypes eRiverDir) { if (m_pPlot) { m_pPlot->setWOfRiver(bNewValue, eRiverDir); } } CardinalDirectionTypes CyPlot::getRiverWEDirection() { return m_pPlot->getRiverWEDirection(); } CardinalDirectionTypes CyPlot::getRiverNSDirection() { return m_pPlot->getRiverNSDirection(); } bool CyPlot::isIrrigated() { return m_pPlot ? m_pPlot->isIrrigated() : false; } bool CyPlot::isPotentialCityWork() { return m_pPlot ? m_pPlot->isPotentialCityWork() : false; } bool CyPlot::isPotentialCityWorkForArea(CyArea* pArea) { return m_pPlot ? m_pPlot->isPotentialCityWorkForArea(pArea->getArea()) : false; } bool CyPlot::isFlagDirty() { return m_pPlot ? m_pPlot->isFlagDirty() : false; } void CyPlot::setFlagDirty(bool bNewValue) { if (m_pPlot) { m_pPlot->setFlagDirty(bNewValue); } } int CyPlot::getOwner() { return m_pPlot ? m_pPlot->getOwnerINLINE() : -1; } void CyPlot::setOwner(int /*PlayerTypes*/ eNewValue) { if (m_pPlot) m_pPlot->setOwner((PlayerTypes) eNewValue, true, true); } void CyPlot::setOwnerNoUnitCheck(int /*PlayerTypes*/ eNewValue) { if (m_pPlot) m_pPlot->setOwner((PlayerTypes) eNewValue, false, true); } PlotTypes CyPlot::getPlotType() { return m_pPlot ? m_pPlot->getPlotType() : NO_PLOT; } bool CyPlot::isWater() { return m_pPlot ? m_pPlot->isWater() : false; } bool CyPlot::isFlatlands() { return m_pPlot ? m_pPlot->isFlatlands() : false; } bool CyPlot::isHills() { return m_pPlot ? m_pPlot->isHills() : false; } bool CyPlot::isPeak() { return m_pPlot ? m_pPlot->isPeak() : false; } void CyPlot::setPlotType(PlotTypes eNewValue, bool bRecalculate, bool bRebuildGraphics) { if (m_pPlot) m_pPlot->setPlotType(eNewValue, bRecalculate, bRebuildGraphics); } int /*TerrainTypes*/ CyPlot::getTerrainType() { return m_pPlot ? m_pPlot->getTerrainType() : -1; } void CyPlot::setTerrainType(int /*TerrainTypes*/ eNewValue, bool bRecalculate, bool bRebuildGraphics) { if (m_pPlot) m_pPlot->setTerrainType((TerrainTypes)eNewValue, bRecalculate, bRebuildGraphics); } int /*FeatureTypes*/ CyPlot::getFeatureType() { return m_pPlot ? m_pPlot->getFeatureType() : -1; } void CyPlot::setFeatureType(int /*FeatureTypes*/ eNewValue, int iVariety) { if (m_pPlot) m_pPlot->setFeatureType((FeatureTypes)eNewValue, iVariety); } void CyPlot::setFeatureDummyVisibility(std::string dummyTag, bool show) { if(m_pPlot) m_pPlot->setFeatureDummyVisibility(dummyTag.c_str(), show); } void CyPlot::addFeatureDummyModel(std::string dummyTag, std::string modelTag) { if(m_pPlot) m_pPlot->addFeatureDummyModel(dummyTag.c_str(), modelTag.c_str()); } void CyPlot::setFeatureDummyTexture(std::string dummyTag, std::string textureTag) { if(m_pPlot) m_pPlot->setFeatureDummyTexture(dummyTag.c_str(), textureTag.c_str()); } std::string CyPlot::pickFeatureDummyTag(int mouseX, int mouseY) { if(m_pPlot) return m_pPlot->pickFeatureDummyTag(mouseX, mouseY); else return ""; } void CyPlot::resetFeatureModel() { if(m_pPlot) m_pPlot->resetFeatureModel(); } int CyPlot::getFeatureVariety() { return m_pPlot ? m_pPlot->getFeatureVariety() : -1; } int CyPlot::getOwnershipDuration() { return m_pPlot ? m_pPlot->getOwnershipDuration() : -1; } bool CyPlot::isOwnershipScore() { return m_pPlot ? m_pPlot->isOwnershipScore() : false; } void CyPlot::setOwnershipDuration(int iNewValue) { if (m_pPlot) m_pPlot->setOwnershipDuration(iNewValue); } void CyPlot::changeOwnershipDuration(int iChange) { if (m_pPlot) m_pPlot->changeOwnershipDuration(iChange); } int CyPlot::getImprovementDuration() { return m_pPlot ? m_pPlot->getImprovementDuration() : -1; } void CyPlot::setImprovementDuration(int iNewValue) { if (m_pPlot) m_pPlot->setImprovementDuration(iNewValue); } void CyPlot::changeImprovementDuration(int iChange) { if (m_pPlot) m_pPlot->changeImprovementDuration(iChange); } int /* BonusTypes */ CyPlot::getBonusType(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->getBonusType((TeamTypes)eTeam) : -1; } int /* BonusTypes */ CyPlot::getNonObsoleteBonusType(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->getNonObsoleteBonusType((TeamTypes)eTeam) : -1; } void CyPlot::setBonusType(int /* BonusTypes */ eNewValue) { if (m_pPlot) m_pPlot->setBonusType((BonusTypes)eNewValue); } int /* ImprovementTypes */ CyPlot::getImprovementType() { return m_pPlot ? m_pPlot->getImprovementType() : -1; } void CyPlot::setImprovementType(int /* ImprovementTypes */ eNewValue) { if (m_pPlot) m_pPlot->setImprovementType((ImprovementTypes)eNewValue); } int /* RouteTypes */ CyPlot::getRouteType() { return m_pPlot ? m_pPlot->getRouteType() : -1; } void CyPlot::setRouteType(int /*RouteTypes*/ eNewValue) { if (m_pPlot) m_pPlot->setRouteType((RouteTypes) eNewValue, true); } CyCity* CyPlot::getPlotCity() { return m_pPlot ? new CyCity(m_pPlot->getPlotCity()) : NULL; } CyCity* CyPlot::getWorkingCity() { return m_pPlot ? new CyCity(m_pPlot->getWorkingCity()) : NULL; } CyCity* CyPlot::getWorkingCityOverride() { return m_pPlot ? new CyCity(m_pPlot->getWorkingCityOverride()) : NULL; } int CyPlot::getRiverID() const { return m_pPlot ? m_pPlot->getRiverID() : -1; } void CyPlot::setRiverID(int iNewValue) { if (m_pPlot) m_pPlot->setRiverID(iNewValue); } int CyPlot::getMinOriginalStartDist() { return m_pPlot ? m_pPlot->getMinOriginalStartDist() : -1; } int CyPlot::getReconCount() { return m_pPlot ? m_pPlot->getReconCount() : -1; } int CyPlot::getRiverCrossingCount() { return m_pPlot ? m_pPlot->getRiverCrossingCount() : -1; } int CyPlot::getYield(YieldTypes eIndex) { return m_pPlot ? m_pPlot->getYield(eIndex) : -1; } int CyPlot::calculateNatureYield(YieldTypes eIndex, TeamTypes eTeam, bool bIgnoreFeature) { return m_pPlot ? m_pPlot->calculateNatureYield(eIndex, eTeam, bIgnoreFeature) : -1; } int CyPlot::calculateBestNatureYield(YieldTypes eIndex, TeamTypes eTeam) { return m_pPlot ? m_pPlot->calculateBestNatureYield(eIndex, eTeam) : -1; } int CyPlot::calculateTotalBestNatureYield(TeamTypes eTeam) { return m_pPlot ? m_pPlot->calculateTotalBestNatureYield(eTeam) : -1; } int CyPlot::calculateImprovementYieldChange(int /*ImprovementTypes*/ eImprovement, YieldTypes eYield, int /*PlayerTypes*/ ePlayer, bool bOptimal) { return m_pPlot ? m_pPlot->calculateImprovementYieldChange((ImprovementTypes) eImprovement, eYield, (PlayerTypes) ePlayer, bOptimal) : -1; } int CyPlot::calculateYield(YieldTypes eIndex, bool bDisplay) { return m_pPlot ? m_pPlot->calculateYield(eIndex, bDisplay) : -1; } bool CyPlot::hasYield() { return m_pPlot ? m_pPlot->hasYield() : false; } int CyPlot::getCulture(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->getCulture((PlayerTypes)eIndex) : -1; } int CyPlot::countTotalCulture() { return m_pPlot ? m_pPlot->countTotalCulture() : -1; } int /*TeamTypes*/ CyPlot::findHighestCultureTeam() { return m_pPlot ? m_pPlot->findHighestCultureTeam() : -1; } int CyPlot::calculateCulturePercent(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->calculateCulturePercent((PlayerTypes)eIndex) : -1; } int CyPlot::calculateTeamCulturePercent(int /*TeamTypes*/ eIndex) { return m_pPlot ? m_pPlot->calculateTeamCulturePercent((TeamTypes)eIndex) : -1; } void CyPlot::setCulture(int /*PlayerTypes*/ eIndex, int iChange, bool bUpdate) { if (m_pPlot) m_pPlot->setCulture((PlayerTypes)eIndex, iChange, bUpdate, true); } void CyPlot::changeCulture(int /*PlayerTypes*/ eIndex, int iChange, bool bUpdate) { if (m_pPlot) m_pPlot->changeCulture((PlayerTypes)eIndex, iChange, bUpdate); } int CyPlot::countNumAirUnits(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->countNumAirUnits((TeamTypes)eTeam) : -1; } int CyPlot::getFoundValue(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->getFoundValue((PlayerTypes)eIndex) : -1; } bool CyPlot::isBestAdjacentFound(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->isBestAdjacentFound((PlayerTypes)eIndex) : false; } int CyPlot::getPlayerCityRadiusCount(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->getPlayerCityRadiusCount((PlayerTypes)eIndex) : -1; } bool CyPlot::isPlayerCityRadius(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->isPlayerCityRadius((PlayerTypes)eIndex) : false; } int CyPlot::getVisibilityCount(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->getVisibilityCount((TeamTypes)eTeam) : -1; } void CyPlot::changeVisibilityCount(int /*TeamTypes*/ eTeam, int iChange, int /*InvisibleTypes*/ eSeeInvisible) { if (m_pPlot) m_pPlot->changeVisibilityCount((TeamTypes) eTeam, iChange, (InvisibleTypes) eSeeInvisible, true); } int CyPlot::getStolenVisibilityCount(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->getStolenVisibilityCount((TeamTypes)eTeam) : -1; } int /*PlayerTypes*/ CyPlot::getRevealedOwner(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->getRevealedOwner((TeamTypes)eTeam, bDebug) : -1; } int /*TeamTypes*/ CyPlot::getRevealedTeam(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->getRevealedTeam((TeamTypes)eTeam, bDebug) : -1; } bool CyPlot::isRiverCrossing(DirectionTypes eIndex) { return m_pPlot ? m_pPlot->isRiverCrossing(eIndex) : false; } bool CyPlot::isRevealed(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->isRevealed((TeamTypes)eTeam, bDebug) : false; } void CyPlot::setRevealed(int /*TeamTypes*/ eTeam, bool bNewValue, bool bTerrainOnly, int /*TeamTypes*/ eFromTeam) { if (m_pPlot) m_pPlot->setRevealed((TeamTypes)eTeam, bNewValue, bTerrainOnly, (TeamTypes)eFromTeam, true); } int /* ImprovementTypes */ CyPlot::getRevealedImprovementType(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->getRevealedImprovementType((TeamTypes)eTeam, bDebug) : -1; } int /* RouteTypes */ CyPlot::getRevealedRouteType(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->getRevealedRouteType((TeamTypes)eTeam, bDebug) : -1; } int CyPlot::getBuildProgress(int /*BuildTypes*/ eBuild) { return m_pPlot ? m_pPlot->getBuildProgress((BuildTypes)eBuild) : -1; } bool CyPlot::changeBuildProgress(int /*BuildTypes*/ eBuild, int iChange, int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->changeBuildProgress((BuildTypes)eBuild, iChange, (TeamTypes)eTeam) : false; } int CyPlot::getCultureRangeCities(int /*PlayerTypes*/ eOwnerIndex, int iRangeIndex) { return m_pPlot ? m_pPlot->getCultureRangeCities((PlayerTypes) eOwnerIndex, iRangeIndex) : -1; } bool CyPlot::isCultureRangeCity(int /*PlayerTypes*/ eOwnerIndex, int iRangeIndex) { return m_pPlot ? m_pPlot->isCultureRangeCity((PlayerTypes) eOwnerIndex, iRangeIndex) : false; } int CyPlot::getInvisibleVisibilityCount(int /*TeamTypes*/ eTeam, int /*InvisibleTypes*/ eInvisible) { return m_pPlot ? m_pPlot->getInvisibleVisibilityCount((TeamTypes) eTeam, (InvisibleTypes) eInvisible) : -1; } bool CyPlot::isInvisibleVisible(int /*TeamTypes*/ eTeam, int /*InvisibleTypes*/ eInvisible) { return m_pPlot ? m_pPlot->isInvisibleVisible((TeamTypes) eTeam, (InvisibleTypes) eInvisible) : -1; } void CyPlot::changeInvisibleVisibilityCount(int /*TeamTypes*/ eTeam, int /*InvisibleTypes*/ eInvisible, int iChange) { if (m_pPlot) m_pPlot->changeInvisibleVisibilityCount((TeamTypes) eTeam, (InvisibleTypes) eInvisible, iChange); } int CyPlot::getNumUnits() { return m_pPlot ? m_pPlot->getNumUnits() : -1; } CyUnit* CyPlot::getUnit(int iIndex) { return m_pPlot ? new CyUnit(m_pPlot->getUnitByIndex(iIndex)) : NULL; } std::string CyPlot::getScriptData() const { return m_pPlot ? m_pPlot->getScriptData() : ""; } void CyPlot::setScriptData(std::string szNewValue) { if (m_pPlot) m_pPlot->setScriptData(szNewValue.c_str()); } //Leoreth int CyPlot::getRegionID() { return m_pPlot ? m_pPlot->getRegionID() : -1; } void CyPlot::setRegionID(int iNewValue) { if (m_pPlot) m_pPlot->setRegionID(iNewValue); } bool CyPlot::isCore(int ePlayer) { return m_pPlot ? m_pPlot->isCore((PlayerTypes)ePlayer) : -1; } void CyPlot::setCore(int ePlayer, bool bNewValue) { if (m_pPlot) m_pPlot->setCore((PlayerTypes)ePlayer, bNewValue); } int CyPlot::getSettlerValue(int ePlayer) { return m_pPlot ? m_pPlot->getSettlerValue((PlayerTypes)ePlayer) : -1; } void CyPlot::setSettlerValue(int ePlayer, int iNewValue) { if (m_pPlot) m_pPlot->setSettlerValue((PlayerTypes)ePlayer, iNewValue); } int CyPlot::getWarValue(int ePlayer) { return m_pPlot ? m_pPlot->getWarValue((PlayerTypes)ePlayer) : -1; } void CyPlot::setWarValue(int ePlayer, int iNewValue) { if (m_pPlot) m_pPlot->setWarValue((PlayerTypes)ePlayer, iNewValue); } int CyPlot::getSpreadFactor(int eReligion) { return m_pPlot ? m_pPlot->getSpreadFactor((ReligionTypes)eReligion) : -1; } void CyPlot::setSpreadFactor(int eReligion, int iNewValue) { if (m_pPlot) m_pPlot->setSpreadFactor((ReligionTypes)eReligion, iNewValue); } bool CyPlot::isWithinGreatWall() { return m_pPlot ? m_pPlot->isWithinGreatWall() : -1; } void CyPlot::setWithinGreatWall(bool bNewValue) { if (m_pPlot) m_pPlot->setWithinGreatWall(bNewValue); } void CyPlot::cameraLookAt() { if (m_pPlot) m_pPlot->cameraLookAt(); } int CyPlot::calculateOverallCulturePercent(int ePlayer) { return m_pPlot ? m_pPlot->calculateOverallCulturePercent((PlayerTypes)ePlayer) : 0; } void CyPlot::updateCulture() { if (m_pPlot) m_pPlot->updateCulture(true, true); } void CyPlot::setCultureConversion(int ePlayer, int iRate) { if (m_pPlot) m_pPlot->setCultureConversion((PlayerTypes)ePlayer, iRate); } void CyPlot::resetCultureConversion() { if (m_pPlot) m_pPlot->resetCultureConversion(); } int CyPlot::getCultureConversionPlayer() { return m_pPlot ? m_pPlot->getCultureConversionPlayer() : -1; } int CyPlot::getActualCulture(int ePlayer) { return m_pPlot ? m_pPlot->getActualCulture((PlayerTypes)ePlayer) : -1; }
28,480
11,299
#include <iostream> #include <string> #include <memory> #include <sstream> using namespace std; class MyClass { private: static int count; string name; public: MyClass() { ostringstream stringStream(ostringstream::ate); stringStream << "Object"; stringStream << ++count; name = stringStream.str(); cout << "\nMyClass Default constructor - " << name << endl; } ~MyClass() { cout << "\nMyClass destructor - " << name << endl; } MyClass ( const MyClass &objectBeingCopied ) { cout << "\nMyClass copy constructor" << endl; } MyClass& operator = ( const MyClass &objectBeingAssigned ) { cout << "\nMyClass assignment operator" << endl; } void sayHello() { cout << "Hello from MyClass " << name << endl; } }; int MyClass::count = 0; int main ( ) { unique_ptr<MyClass> ptr1( new MyClass() ); unique_ptr<MyClass> ptr2( new MyClass() ); ptr1->sayHello(); ptr2->sayHello(); //At this point the below stuffs happen //1. ptr2 smart pointer has given up ownership of MyClass Object 2 //2. MyClass Object 2 will be destructed as ptr2 has given up its ownership on Object 2 //3. Ownership of Object 1 will be transferred to ptr2 ptr2 = move(ptr1); //The line below if uncommented will result in core dump as ptr1 has given up its ownership //on Object 1 and the ownership of Object 1 is transferred to ptr2. ptr1->sayHello(); ptr2->sayHello(); return 0; }
1,428
502
/* Interview Bit */ /* Title - Max Non Negative Subarray */ /* Created By - Akash Modak */ /* Date - 26/06/2020 */ // Given an array of integers, A of length N, find out the maximum sum sub-array of non negative numbers from A. // The sub-array should be contiguous i.e., a sub-array created by choosing the second and fourth element and skipping the third element is invalid. // Maximum sub-array is defined in terms of the sum of the elements in the sub-array. // Find and return the required subarray. // NOTE: // If there is a tie, then compare with segment's length and return segment which has maximum length. // If there is still a tie, then return the segment with minimum starting index. // Problem Constraints // 1 <= N <= 105 // -109 <= A[i] <= 109 // Input Format // The first and the only argument of input contains an integer array A, of length N. // Output Format // Return an array of integers, that is a subarray of A that satisfies the given conditions. // Example Input // Input 1: // A = [1, 2, 5, -7, 2, 3] // Input 2: // A = [10, -1, 2, 3, -4, 100] // Example Output // Output 1: // [1, 2, 5] // Output 2: // [100] // Example Explanation // Explanation 1: // The two sub-arrays are [1, 2, 5] [2, 3]. // The answer is [1, 2, 5] as its sum is larger than [2, 3]. // Explanation 2: // The three sub-arrays are [10], [2, 3], [100]. // The answer is [100] as its sum is larger than the other two. vector<int> Solution::maxset(vector<int> &A) { int n=A.size(); int i=0,maxm=0,count=0,start=0,end=-1; int fstart=-1,fend=-1; long long int sum=0,maxsum=0; vector<int> res; while(i<n){ if(A[i]>=0){ sum+=A[i]; count++; end++; } if(sum>maxsum){ maxsum=sum; fstart=start; fend=end; } else if(sum==maxsum&&count>maxm){ maxm=count; fstart=start; fend=end; } if(A[i]<0){ count=0; start=i+1;end=i; sum=0; } i++; } if(fstart!=-1&&fend!=-1){ for(int i=fstart;i<=fend;i++) res.push_back(A[i]); } return res; }
2,320
877
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=40; const int inf=2147483647; int Opt[maxN]; int main() { int n,m,ans; scanf("%d%d",&m,&n); for (int i=1;i<=n;i++){ printf("1\n");fflush(stdout);scanf("%d",&ans); if (ans==0) exit(0); if (ans==1) Opt[i]=-1; else Opt[i]=1; } int L=1,R=m,outp=0,cnt=0; do { cnt++; if (cnt>n) cnt=1; int mid=(L+R)>>1; printf("%d\n",mid);fflush(stdout);scanf("%d",&ans); if (ans==0) exit(0); ans*=Opt[cnt]; if (ans==1) R=mid-1; else L=mid+1; } while (L<=R); printf("%d\n",L);fflush(stdout);scanf("%d",&ans); return 0; }
735
389
/** @file inl2weight.cc * @brief Xapian::InL2Weight class - the InL2 weighting scheme of the DFR framework. */ /* Copyright (C) 2013,2014 Aarsh Shah * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "xapian/weight.h" #include "xapian/common/log2.h" #include "xapian/weight/weightinternal.h" #include "xapian/common/serialise-double.h" #include "xapian/error.h" using namespace std; namespace Xapian { InL2Weight::InL2Weight(double c) : param_c(c) { if (param_c <= 0) throw Xapian::InvalidArgumentError("Parameter c is invalid."); need_stat(AVERAGE_LENGTH); need_stat(DOC_LENGTH); need_stat(DOC_LENGTH_MIN); need_stat(COLLECTION_SIZE); need_stat(WDF); need_stat(WDF_MAX); need_stat(WQF); need_stat(TERMFREQ); } InL2Weight * InL2Weight::clone() const { return new InL2Weight(param_c); } void InL2Weight::init(double factor) { if (factor == 0.0) { // This object is for the term-independent contribution, and that's // always zero for this scheme. return; } double wdfn_upper = get_wdf_upper_bound(); if (wdfn_upper == 0) { upper_bound = 0.0; return; } double termfrequency = get_termfreq(); double N = get_collection_size(); wdfn_upper *= log2(1 + (param_c * get_average_length()) / get_doclength_lower_bound()); // wdfn * L = wdfn / (wdfn + 1) = 1 / (1 + 1 / wdfn). // To maximize the product, we need to minimize the denominator and so we use wdfn_upper in (1 / wdfn). double maximum_wdfn_product_L = wdfn_upper / (wdfn_upper + 1.0); // This term is constant for all documents. double idf_max = log2((N + 1) / (termfrequency + 0.5)); /* Calculate constant values to be used in get_sumpart() upfront. */ wqf_product_idf = get_wqf() * idf_max * factor; c_product_avlen = param_c * get_average_length(); upper_bound = wqf_product_idf * maximum_wdfn_product_L * factor; } string InL2Weight::name() const { return "Xapian::InL2Weight"; } string InL2Weight::short_name() const { return "inl2"; } string InL2Weight::serialise() const { return serialise_double(param_c); } InL2Weight * InL2Weight::unserialise(const string & s) const { const char *ptr = s.data(); const char *end = ptr + s.size(); double c = unserialise_double(&ptr, end); if (rare(ptr != end)) throw Xapian::SerialisationError("Extra data in InL2Weight::unserialise()"); return new InL2Weight(c); } double InL2Weight::get_sumpart(Xapian::termcount wdf, Xapian::termcount len, Xapian::termcount) const { if (wdf == 0) return 0.0; double wdfn = wdf; wdfn *= log2(1 + c_product_avlen / len); double wdfn_product_L = wdfn / (wdfn + 1.0); return (wqf_product_idf * wdfn_product_L); } double InL2Weight::get_maxpart() const { return upper_bound; } double InL2Weight::get_sumextra(Xapian::termcount, Xapian::termcount) const { return 0; } double InL2Weight::get_maxextra() const { return 0; } InL2Weight * InL2Weight::create_from_parameters(const char * p) const { if (*p == '\0') return new Xapian::InL2Weight(); double k = 1.0; if (!Xapian::Weight::Internal::double_param(&p, &k)) Xapian::Weight::Internal::parameter_error("Parameter is invalid", "inl2"); if (*p) Xapian::Weight::Internal::parameter_error("Extra data after parameter", "inl2"); return new Xapian::InL2Weight(k); } }
4,080
1,535
#pragma once #include <utility> template <class Func> class Defer { Func func_; public: // NOLINTNEXTLINE(google-explicit-constructor) Defer(Func func) try : func_(std::move(func)) { } catch (...) { func(); throw; } Defer(const Defer&) = delete; Defer(Defer&&) = delete; Defer& operator=(const Defer&) = delete; Defer& operator=(Defer&&) = delete; ~Defer() { try { func_(); } catch (...) { } } };
506
181
/* Develop by Luis Alberto email: alberto.bsd@gmail.com gcc -o bPfile bPfile.c -lgmp -lm Hint: compile in the keyhunt directory */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <gmp.h> #include <string.h> #ifdef WIN64 #include <Windows.h> #else #include <unistd.h> #include <pthread.h> #endif #include <math.h> #include "util.h" #define BSGS_BUFFERXPOINTLENGTH 32 #define BSGS_BUFFERREGISTERLENGTH 36 struct Point { mpz_t x; mpz_t y; }; struct Elliptic_Curve { mpz_t p; mpz_t n; }; const char* EC_constant_N = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"; const char* EC_constant_P = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"; const char* EC_constant_Gx = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; const char* EC_constant_Gy = "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"; struct Point DoublingG[256]; void Point_Doubling(struct Point* P, struct Point* R); void Point_Addition(struct Point* P, struct Point* Q, struct Point* R); void Scalar_Multiplication(struct Point P, struct Point* R, mpz_t m); void Point_Negation(struct Point* A, struct Point* S); void init_doublingG(struct Point* P); struct Elliptic_Curve EC; struct Point G; int main(int argc, char** argv) { mpz_t temp; FILE* p_file; char temporal[512], rawvalue[BSGS_BUFFERXPOINTLENGTH]; long int i, m, sz; mpz_t M; struct Point point_t, P; if (argc < 3) { printf("Create bP File usage\n"); printf("%s <bP items> <output filename>\n\n", argv[0]); printf("Example to create a File with 1 Billion items:\n%s 1000000000 Pfile.bin\n", argv[0]); printf("If the file exists, only the missing bP items will be added○\n"); exit(0); } mpz_init_set_str(M, argv[1], 10); mpz_init_set_str(EC.p, EC_constant_P, 16); mpz_init_set_str(EC.n, EC_constant_N, 16); mpz_init_set_str(G.x, EC_constant_Gx, 16); mpz_init_set_str(G.y, EC_constant_Gy, 16); init_doublingG(&G); mpz_init(point_t.x); mpz_init(point_t.y); mpz_init(temp); m = mpz_get_ui(M); mpz_init_set(P.x, G.x); mpz_init_set(P.y, G.y); p_file = fopen(argv[2], "wb"); if (p_file == NULL) { printf("Can't create file %s\n", argv[2]); exit(0); } /* fseek(p_file, 0L, SEEK_END); sz = ftell(p_file); if(sz % 32 != 0) { printf("Invalid filesize\n"); exit(0); } printf("Current numeber of items %li\n",(long int)(sz/32)); if(m <= sz/32 ) { printf("The current file have %li items\n",m); } else { i = m-(sz/32); printf("OK, items missing %li\n",i); } mpz_set_ui(temp,i) */ i = 0; printf("[+] precalculating %li bP elements in file %s\n", m, argv[2]); do { mpz_set(point_t.x, P.x); mpz_set(point_t.y, P.y); gmp_sprintf(temporal, "%0.64Zx", P.x); hexs2bin(temporal, (unsigned char*)rawvalue); fwrite(rawvalue, 1, 32, p_file); Point_Addition(&G, &point_t, &P); i++; } while (i < m); } void Point_Doubling(struct Point* P, struct Point* R) { mpz_t slope, temp; mpz_init(temp); mpz_init(slope); if (mpz_cmp_ui(P->y, 0) != 0) { mpz_mul_ui(temp, P->y, 2); mpz_invert(temp, temp, EC.p); mpz_mul(slope, P->x, P->x); mpz_mul_ui(slope, slope, 3); mpz_mul(slope, slope, temp); mpz_mod(slope, slope, EC.p); mpz_mul(R->x, slope, slope); mpz_sub(R->x, R->x, P->x); mpz_sub(R->x, R->x, P->x); mpz_mod(R->x, R->x, EC.p); mpz_sub(temp, P->x, R->x); mpz_mul(R->y, slope, temp); mpz_sub(R->y, R->y, P->y); mpz_mod(R->y, R->y, EC.p); } else { mpz_set_ui(R->x, 0); mpz_set_ui(R->y, 0); } mpz_clear(temp); mpz_clear(slope); } void Point_Addition(struct Point* P, struct Point* Q, struct Point* R) { mpz_t PA_temp, PA_slope; mpz_init(PA_temp); mpz_init(PA_slope); mpz_mod(Q->x, Q->x, EC.p); mpz_mod(Q->y, Q->y, EC.p); mpz_mod(P->x, P->x, EC.p); mpz_mod(P->y, P->y, EC.p); if (mpz_cmp_ui(P->x, 0) == 0 && mpz_cmp_ui(P->y, 0) == 0) { mpz_set(R->x, Q->x); mpz_set(R->y, Q->y); } else { /* This is commented because Q never 0,0, always is kG point*/ /* if(mpz_cmp_ui(Q->x, 0) == 0 && mpz_cmp_ui(Q->y, 0) == 0) { mpz_set(R->x, P->x); mpz_set(R->y, P->y); } else { */ if (mpz_cmp_ui(Q->y, 0) != 0) { mpz_sub(PA_temp, EC.p, Q->y); mpz_mod(PA_temp, PA_temp, EC.p); } else { mpz_set_ui(PA_temp, 0); } if (mpz_cmp(P->y, PA_temp) == 0 && mpz_cmp(P->x, Q->x) == 0) { mpz_set_ui(R->x, 0); mpz_set_ui(R->y, 0); } else { if (mpz_cmp(P->x, Q->x) == 0 && mpz_cmp(P->y, Q->y) == 0) { Point_Doubling(P, R); } else { mpz_set_ui(PA_slope, 0); mpz_sub(PA_temp, P->x, Q->x); mpz_mod(PA_temp, PA_temp, EC.p); mpz_invert(PA_temp, PA_temp, EC.p); mpz_sub(PA_slope, P->y, Q->y); mpz_mul(PA_slope, PA_slope, PA_temp); mpz_mod(PA_slope, PA_slope, EC.p); mpz_mul(R->x, PA_slope, PA_slope); mpz_sub(R->x, R->x, P->x); mpz_sub(R->x, R->x, Q->x); mpz_mod(R->x, R->x, EC.p); mpz_sub(PA_temp, P->x, R->x); mpz_mul(R->y, PA_slope, PA_temp); mpz_sub(R->y, R->y, P->y); mpz_mod(R->y, R->y, EC.p); } } //} } mpz_clear(PA_temp); mpz_clear(PA_slope); } void Scalar_Multiplication(struct Point P, struct Point* R, mpz_t m) { char strtemp[65]; struct Point SM_T, SM_Q; long no_of_bits, i; no_of_bits = mpz_sizeinbase(m, 2); mpz_init_set_ui(SM_Q.x, 0); mpz_init_set_ui(SM_Q.y, 0); mpz_init_set_ui(SM_T.x, 0); mpz_init_set_ui(SM_T.y, 0); mpz_set_ui(R->x, 0); mpz_set_ui(R->y, 0); if (mpz_cmp_ui(m, 0) != 0) { mpz_set(SM_Q.x, P.x); mpz_set(SM_Q.y, P.y); for (i = 0; i < no_of_bits; i++) { if (mpz_tstbit(m, i)) { mpz_set(SM_T.x, R->x); mpz_set(SM_T.y, R->y); mpz_set(SM_Q.x, DoublingG[i].x); mpz_set(SM_Q.y, DoublingG[i].y); Point_Addition(&SM_T, &SM_Q, R); } } } mpz_clear(SM_T.x); mpz_clear(SM_T.y); mpz_clear(SM_Q.x); mpz_clear(SM_Q.y); } void Point_Negation(struct Point* A, struct Point* S) { mpz_sub(S->y, EC.p, A->y); mpz_set(S->x, A->x); } void init_doublingG(struct Point* P) { int i = 0; mpz_init(DoublingG[i].x); mpz_init(DoublingG[i].y); mpz_set(DoublingG[i].x, P->x); mpz_set(DoublingG[i].y, P->y); i = 1; while (i < 256) { mpz_init(DoublingG[i].x); mpz_init(DoublingG[i].y); Point_Doubling(&DoublingG[i - 1], &DoublingG[i]); mpz_mod(DoublingG[i].x, DoublingG[i].x, EC.p); mpz_mod(DoublingG[i].y, DoublingG[i].y, EC.p); i++; } }
6,357
3,566
// // Created by Florian on 20.12.2020. // #include "AxisAlignedBox.h" #include "cmath" namespace Zoe{ AxisAlignedBox::AxisAlignedBox(const vec3& lower, const vec3& higher) { AxisAlignedBox::lower = vec3(std::min(lower.x, higher.x), std::min(lower.y, higher.y), std::min(lower.z, higher.z)); AxisAlignedBox::higher = vec3(std::max(lower.x, higher.x), std::max(lower.y, higher.y), std::max(lower.z, higher.z)); } AxisAlignedBox::AxisAlignedBox(double x1, double y1, double z1, double x2, double y2, double z2) { AxisAlignedBox::lower = vec3(std::min(x1, x2), std::min(y1, y2), std::min(z1, z2)); AxisAlignedBox::higher = vec3(std::max(x1, x2), std::max(y1, y2), std::max(z1, z2)); } }
704
304
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #include <Geometry/Internal/Types/hkcdRay.h> #include <Geometry/Internal/Algorithms/Distance/hkcdDistancePointLine.h> #include <Geometry/Internal/Algorithms/ClosestPoint/hkcdClosestPointLineLine.h> #include <Geometry/Internal/Algorithms/RayCast/hkcdRayCastSphere.h> HK_FORCE_INLINE hkcdRayCastResult hkcdRayCastCapsule( const hkcdRay& rayIn, hkVector4Parameter vertex0, hkVector4Parameter vertex1, hkSimdRealParameter radius, hkSimdReal* HK_RESTRICT fractionInOut, hkVector4* HK_RESTRICT normalOut, hkcdRayCastCapsuleHitType* HK_RESTRICT hitTypeOut, hkFlags<hkcdRayQueryFlags::Enum,hkUint32> flags ) { hkVector4Comparison insideHits; hkcdRayQueryFlags::isFlagSet(flags, hkcdRayQueryFlags::ENABLE_INSIDE_HITS, insideHits); hkcdRay ray = rayIn; const hkVector4& dA = ray.getDirection(); // Catch the case where the ray has length zero. if (HK_VERY_UNLIKELY(dA.equalZero().allAreSet<hkVector4ComparisonMask::MASK_XYZ>())) { return hkcdRayCastResult::NO_HIT; } hkVector4 dB; dB.setSub( vertex1, vertex0 ); hkSimdReal radiusSq = radius * radius; hkSimdReal fraction = *fractionInOut; hkVector4Comparison isInverseRay; isInverseRay.set<hkVector4ComparisonMask::MASK_NONE>(); hkSimdReal invScale = hkSimdReal_1; hkVector4Comparison isInsideComparison; hkcdRayCastResult success = hkcdRayCastResult::FRONT_FACE_HIT; { hkSimdReal sToCylDistSq = hkcdPointSegmentDistanceSquared( ray.m_origin, vertex0, vertex1 ); isInsideComparison = sToCylDistSq.less(radiusSq); if( HK_VERY_UNLIKELY( isInsideComparison.allAreSet() ) ) { success = hkcdRayCastResult(hkcdRayCastResult::BACK_FACE_HIT | hkcdRayCastResult::INSIDE_HIT); // origin inside the cylinder if ( HK_VERY_LIKELY( !insideHits.allAreSet() ) ) { return hkcdRayCastResult::NO_HIT; } else { // The origin is inside, so we invert the ray to get inside hits. // Inverting a ray that is extremely long might get us into accuracy issues, // so we conservatively resize the inverse ray to handle the issue: // We can setup an inverse ray ending at the inside point and starting outside the capsule. // To find the starting point outside the capsule, we can safely move from the inside point // along the ray's inverse direction by a distance that is the radius of a sphere englobing // the capsule (plus some padding = 2*radius ), capped by the size of the original ray. // We use 'invScale' to correct the final hitFraction later on. hkVector4 endPoint; endPoint.setAddMul( ray.m_origin, ray.m_direction, *fractionInOut ); hkSimdReal sToCylDistSq2 = hkcdPointSegmentDistanceSquared( endPoint, vertex0, vertex1 ); isInverseRay.set<hkVector4ComparisonMask::MASK_XYZW>(); hkSimdReal inRaySize = ray.getDirection().length<3>(); hkSimdReal invRayMaxSize = dB.length<3>() + hkSimdReal_4 * radius; hkSimdReal invRaySize; invRaySize.setMin( invRayMaxSize, inRaySize * ( *fractionInOut ) ); invScale.setDiv<HK_ACC_RAYCAST, HK_DIV_SET_ZERO>( invRaySize, inRaySize ); ray.m_direction.setMul( rayIn.m_direction, invScale ); ray.m_direction.setNeg<3>( ray.m_direction ); ray.m_origin.setSub( rayIn.m_origin, ray.m_direction ); // ray.m_invDirection is not used fraction = hkSimdReal_1; // Both ray points are inside the capsule. // Also safely catches the case where the ray has zero length. if( HK_VERY_UNLIKELY( sToCylDistSq2 < radiusSq ) ) { return hkcdRayCastResult::NO_HIT; } } } } // Work out closest points to cylinder hkSimdReal infInfDistSquared; hkSimdReal t, u; // Get distance between inf lines + parametric description (t, u) of closest points, { hkcdClosestPointLineLine(ray.m_origin, dA, vertex0, dB, t, u); hkVector4 p,q; p.setAddMul(ray.m_origin, dA, t); q.setAddMul(vertex0, dB, u); hkVector4 diff; diff.setSub(p, q); infInfDistSquared = diff.lengthSquared<3>(); if( infInfDistSquared > (radius*radius) ) { return hkcdRayCastResult::NO_HIT; // Infinite ray is outside radius of infinite cylinder } } hkSimdReal axisLength; hkVector4 axis; hkSimdReal ipT; { axis = dB; // Check for zero axis { hkSimdReal axisLengthSqrd = axis.lengthSquared<3>(); hkVector4Comparison mask = axisLengthSqrd.greater( hkSimdReal_Eps ); axisLength = axis.normalizeWithLength<3,HK_ACC_RAYCAST,HK_SQRT_IGNORE>(); axisLength.zeroIfFalse(mask); axis.zeroIfFalse(mask); } hkSimdReal component = dA.dot<3>(axis); // Flatdir is now a ray firing in the "plane" of the cylinder. hkVector4 flatDir; flatDir.setAddMul(dA, axis, -component); // Convert d to a parameterization instead of absolute distance along ray. hkSimdReal flatDirLengthSquared3 = flatDir.lengthSquared<3>(); // If flatDir is zero, the ray is parallel to the cylinder axis. In this case we set ipT to a // negative value to bypass the cylinder intersection test and go straight to the cap tests. hkVector4Comparison mask = flatDirLengthSquared3.equalZero(); hkSimdReal d = (radius * radius - infInfDistSquared) / flatDirLengthSquared3; ipT.setSelect(mask, hkSimdReal_Minus1, t - d.sqrt()); } // Intersection parameterization with infinite cylinder is outside length of ray // or is greater than a previous hit fraction if (ipT >= fraction ) { return hkcdRayCastResult::NO_HIT; } hkSimdReal ptHeight; hkSimdReal pointAProj = vertex0.dot<3>(axis); // Find intersection point of actual ray with infinite cylinder hkVector4 intersectPt; intersectPt.setAddMul( ray.m_origin, ray.getDirection(), ipT ); // Test height of intersection point w.r.t. cylinder axis // to determine hit against actual cylinder // Intersection point projected against cylinder hkSimdReal ptProj = intersectPt.dot<3>(axis); ptHeight = ptProj - pointAProj; if ( ipT.isGreaterEqualZero() ) // Actual ray (not infinite ray) must intersect with infinite cylinder { if ( ptHeight.isGreaterZero() && ptHeight.isLess(axisLength) ) // Report hit against cylinder part { // Calculate normal hkVector4 projPtOnAxis; projPtOnAxis.setInterpolate( vertex0, vertex1, ptHeight / axisLength ); hkVector4 normal; normal.setSub( intersectPt, projPtOnAxis ); normal.normalize<3>(); *normalOut = normal; hkSimdReal invIpT; invIpT.setSub( hkSimdReal_1, ipT ); invIpT.setMul( invIpT, invScale ); fractionInOut->setSelect( isInverseRay, invIpT, ipT ); *hitTypeOut = HK_CD_RAY_CAPSULE_BODY; return success; } } // Cap tests { // Check whether start point is inside infinite cylinder or not hkSimdReal fromLocalProj = ray.m_origin.dot<3>(axis); hkSimdReal projParam = fromLocalProj - pointAProj; hkVector4 fromPtProjAxis; fromPtProjAxis.setInterpolate( vertex0, vertex1, projParam / axisLength ); hkVector4 axisToRayStart; axisToRayStart.setSub( ray.m_origin, fromPtProjAxis); if ( ipT.isLessZero() && axisToRayStart.lengthSquared<3>().isGreater(radius * radius) ) { // Ray starts outside infinite cylinder and points away... must be no hit return hkcdRayCastResult::NO_HIT; } // Ray can only hit 1 cap... Use intersection point // to determine which sphere to test against (NB: this only works because // we have discarded cases where ray starts inside) hkVector4 capEnd; hkVector4Comparison mask = ptHeight.lessEqualZero(); capEnd.setSelect( mask, vertex0, vertex1 ); capEnd.setW( radius ); if( hkcdRayCastSphere( ray, capEnd, &fraction, normalOut, hkcdRayQueryFlags::NO_FLAGS).isHit() ) { hkSimdReal invFraction; invFraction.setSub( hkSimdReal_1, fraction ); invFraction.setMul( invFraction, invScale ); fractionInOut->setSelect( isInverseRay, invFraction, fraction ); *hitTypeOut = mask.anyIsSet() ? HK_CD_RAY_CAPSULE_CAP0 : HK_CD_RAY_CAPSULE_CAP1; return success; } return hkcdRayCastResult::NO_HIT; } } HK_FORCE_INLINE hkVector4Comparison hkcdRayBundleCapsuleIntersect( const hkcdRayBundle& rayBundle, hkVector4Parameter vertex0, hkVector4Parameter vertex1, hkSimdRealParameter radius, hkVector4& fractionsInOut, hkFourTransposedPoints& normalsOut ) { hkVector4 sToCylDistSq = hkcdPointSegmentDistanceSquared( rayBundle.m_start, vertex0, vertex1 ); hkVector4 radiusSqr; radiusSqr.setAll(radius * radius); hkVector4Comparison activeMask = rayBundle.m_activeRays; hkVector4Comparison rayStartOutside = sToCylDistSq.greaterEqual( radiusSqr ); activeMask.setAnd(activeMask, rayStartOutside); if ( !activeMask.anyIsSet() ) { return activeMask; } // Work out closest points to cylinder hkVector4 infInfDistSquared; //infInfDistSquared.setConstant<HK_QUADREAL_MAX>(); hkVector4 t, u; hkFourTransposedPoints dA; dA.setSub(rayBundle.m_end, rayBundle.m_start); hkVector4 dB; dB.setSub( vertex1, vertex0 ); // Get distance between inf lines + parametric description (t, u) of closest points, { hkcdClosestPointLineLine(rayBundle.m_start, dA, vertex0, dB, t, u); hkFourTransposedPoints p,q; p.setAddMulT(rayBundle.m_start, dA, t); hkFourTransposedPoints B4; B4.setAll(vertex0); hkFourTransposedPoints dB4; dB4.setAll(dB); q.setAddMulT(B4, dB4, u); hkFourTransposedPoints diff; diff.setSub(p, q); diff.dot3(diff, infInfDistSquared); } // Is infinite ray within radius of infinite cylinder? hkVector4Comparison isInfRayWithinCylinder = infInfDistSquared.lessEqual( radiusSqr ); activeMask.setAnd(activeMask, isInfRayWithinCylinder); if ( !activeMask.anyIsSet() ) { return activeMask; } hkSimdReal axisLength; hkVector4 axis; hkVector4 ipT; { axis = dB; // Check for zero axis hkSimdReal axisLengthSqrd = axis.lengthSquared<3>(); hkVector4Comparison mask = axisLengthSqrd.greater( hkSimdReal_Eps ); axisLength = axis.normalizeWithLength<3,HK_ACC_RAYCAST,HK_SQRT_IGNORE>(); axisLength.zeroIfFalse(mask); axis.zeroIfFalse(mask); hkVector4 component; dA.dot3(axis, component); component.setNeg<4>(component); hkFourTransposedPoints flatDir; hkFourTransposedPoints axis4; axis4.setAll(axis); flatDir.setAddMulT(dA, axis4, component); // Flatdir is now a ray firing in the "plane" of the cylinder. // Convert d to a parameterization instead of absolute distance along ray. // Avoid division by zero in case of ray parallel to infinite cylinder. hkVector4 flatDirLengthSquared3; flatDir.dot3(flatDir, flatDirLengthSquared3); hkVector4 d; d.setSub(radiusSqr, infInfDistSquared); d.div(flatDirLengthSquared3); d.setSqrt(d); d.setSub(t, d); mask = flatDirLengthSquared3.equalZero(); const hkVector4 minusOne = hkVector4::getConstant<HK_QUADREAL_MINUS1>(); ipT.setSelect(mask, minusOne, d); } // Intersection parameterization with infinite cylinder is outside length of ray // or is greater than a previous hit fraction hkVector4Comparison isFractionOk = ipT.less( fractionsInOut ); activeMask.setAnd(activeMask, isFractionOk); if( !activeMask.anyIsSet() ) { return activeMask; } hkVector4 ptHeight; const hkSimdReal pointAProj = vertex0.dot<3>(axis); // Find intersection point of actual ray with infinite cylinder hkFourTransposedPoints intersectPt; intersectPt.setAddMulT( rayBundle.m_start, dA, ipT ); // Test height of intersection point w.r.t. cylinder axis // to determine hit against actual cylinder // Intersection point projected against cylinder hkVector4 ptProj; intersectPt.dot3(axis, ptProj); ptHeight.setSub(ptProj, pointAProj); hkVector4 axisLengthVector; axisLengthVector.setAll(axisLength); hkFourTransposedPoints vertex0x4; vertex0x4.setAll(vertex0); hkFourTransposedPoints vertex1x4; vertex1x4.setAll(vertex1); hkFourTransposedPoints dBx4; dBx4.setAll(dB); hkVector4Comparison isRayWithinCylinder = ipT.greaterEqualZero(); hkVector4Comparison gtZero = ptHeight.greaterZero(); hkVector4Comparison ltAxisLength = ptHeight.less(axisLengthVector); hkVector4Comparison hitBodyMask; hitBodyMask.setAnd(gtZero, ltAxisLength); hitBodyMask.setAnd(hitBodyMask, isRayWithinCylinder); if ( hitBodyMask.anyIsSet() ) // Actual ray (not infinite ray) must intersect with infinite cylinder { // Calculate normal hkVector4 ratio; ratio.setDiv(ptHeight, axisLengthVector); hkFourTransposedPoints projPtOnAxis; projPtOnAxis.setAddMulT( vertex0x4, dBx4, ratio ); hkFourTransposedPoints normals; normals.setSub( intersectPt, projPtOnAxis ); normals.normalize(); normalsOut.setSelect(hitBodyMask, normals, normalsOut); // Output fraction fractionsInOut.setSelect(hitBodyMask, ipT, fractionsInOut); // This is a parameterization along the ray } hitBodyMask.setAndNot(activeMask, hitBodyMask); if (!hitBodyMask.anyIsSet()) { return activeMask; } // Cap tests { // Check whether start point is inside infinite cylinder or not hkVector4 fromLocalProj; rayBundle.m_start.dot3(axis, fromLocalProj); hkVector4 projParam; projParam.setSub(fromLocalProj, pointAProj); hkVector4 ratio; ratio.setDiv(projParam, axisLengthVector); hkFourTransposedPoints fromPtProjAxis; fromPtProjAxis.setAddMulT( vertex0x4, dBx4, ratio ); hkFourTransposedPoints axisToRayStart; axisToRayStart.setSub( rayBundle.m_start, fromPtProjAxis ); hkVector4 axisToRayStartLenSq; axisToRayStart.dot3(axisToRayStart, axisToRayStartLenSq); hkVector4Comparison gteZero = ipT.greaterEqualZero(); hkVector4Comparison lteRadiusSqr = axisToRayStartLenSq.lessEqual(radiusSqr); hkVector4Comparison maskOr; maskOr.setOr(gteZero, lteRadiusSqr); activeMask.setAnd(activeMask, maskOr); if ( !activeMask.anyIsSet() ) { // Ray starts outside infinite cylinder and points away... must be no hit return activeMask; } // Ray can only hit 1 cap... Use intersection point // to determine which sphere to test against (NB: this only works because // we have discarded cases where ray starts inside) hkFourTransposedPoints extra; hkVector4Comparison mask = ptHeight.lessEqualZero(); extra.setSelect( mask, vertex0x4, vertex1x4 ); hkcdRayBundle raySphere; raySphere.m_start.setSub(rayBundle.m_start, extra); raySphere.m_end.setSub(rayBundle.m_end, extra); raySphere.m_activeRays = hitBodyMask; hkVector4Comparison sphereMask = hkcdRayBundleSphereIntersect( raySphere, radius, fractionsInOut, normalsOut); activeMask.setSelect(hitBodyMask, sphereMask, activeMask); } return activeMask; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
15,503
6,021
#include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; int main() { int n; cin >> n; vector<long long> a(n); map<long long,int> v; for (int i = 0; i < n; i++) { cin >> a[i]; v[a[i]]++; } vector<long long> d; d.push_back(1); for (int i = 1; i < 32; i++) { d.push_back(d[i-1] << 1); } int ans = 0; for_each(a.begin(), a.end(), [&ans,d,&v](auto elem) { bool no = true; for (int k = 0; k < d.size(); k++) { long long r = d[k] - elem; if (r == elem && v[elem] == 1) { continue; } if (r > 0 && v.find(r) != v.end()) { no = false; break; } } if (no) { ans++; } //v.insert(elem); }); cout << ans << endl; return 0; }
751
350
#include <iostream> #include <string> #include "Constants.h" #include "DemoBackground.h" #include "Enemy.h" #include "Game.h" #include "GameOverState.h" #include "InputHandler.h" #include "PlayState.h" #include "PauseState.h" #include "Vector2D.h" const std::string PlayState::sStateId = "PLAY"; void PlayState::update(void) { for (std::vector<GameObject *>::size_type i = 0; i < mGameObjectList.size(); i++) { mGameObjectList[i]->update(); } int joypadId = 0; if (checkCollision(dynamic_cast<SdlGameObject *>(mGameObjectList[1]), dynamic_cast<SdlGameObject *>(mGameObjectList[2]))) { Game::Instance()->getStateMachine()->changeState(new GameOverState()); } else if (InputHandler::Instance()->isButtonDown(joypadId, 5) || InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE)) { Game::Instance()->getStateMachine()->pushState(new PauseState()); } } void PlayState::render(void) { for (std::vector<GameObject *>::size_type i = 0; i < mGameObjectList.size(); i++) { mGameObjectList[i]->draw(); } } bool PlayState::onEnter(void) { const std::string resourcePath = Constants::ResourcePath(""); bool success = TextureManager::Instance()->load("player", resourcePath + "helicopter0.png"); success = success && TextureManager::Instance()->load("enemy", resourcePath + "helicopter1.png"); success = success && TextureManager::Instance()->load("play_background", resourcePath + "background.png"); if (success) { int tileWidth, tileHeight; TextureManager::Instance()->queryTexture("play_background", nullptr, nullptr, &tileWidth, &tileHeight); mGameObjectList.push_back(new DemoBackground(new LoaderParams("play_background", 0, 0, tileWidth, tileHeight))); int x, y, w, h; TextureManager::Instance()->queryTexture("player", nullptr, nullptr, &w, &h); w /= 5; x = (Constants::WindowWidth() - w) / 2; y = (Constants::WindowHeight() - h) / 2 - 200; mGameObjectList.push_back(new Enemy(new LoaderParams("enemy", x, y, w, h))); y = (Constants::WindowHeight() - h) / 2; mGameObjectList.push_back(new Player(new LoaderParams("player", x, y, w, h))); std::cout << "Entering PlayState \"" << sStateId << "\"." << std::endl; } return true; } bool PlayState::onExit(void) { while (false == mGameObjectList.empty()) { delete mGameObjectList.back(); mGameObjectList.pop_back(); } TextureManager::Instance()->unload("player"); TextureManager::Instance()->unload("enemy"); TextureManager::Instance()->unload("play_background"); std::cout << "Exiting PlayState \"" << sStateId << "\"." << std::endl; return true; } bool PlayState::checkCollision(SdlGameObject *pObjectA, SdlGameObject *pObjectB) { int leftA, rightA, topA, bottomA; int leftB, rightB, topB, bottomB; leftA = pObjectA->getPosition().getX(); rightA = leftA + pObjectA->getWidth(); topA = pObjectA->getPosition().getY(); bottomA = topA + pObjectA->getHeight(); leftB = pObjectB->getPosition().getX(); rightB = leftB + pObjectB->getWidth(); topB = pObjectB->getPosition().getY(); bottomB = topB + pObjectB->getHeight(); return topA < bottomB && topB < bottomA && leftA < rightB && leftB < rightA; }
3,186
1,094
/* * Copyright (C) 2014 Intel Corporation. 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vaapicodedbuffer.h" #include "vaapi/vaapicontext.h" #include <string.h> namespace YamiMediaCodec{ CodedBufferPtr VaapiCodedBuffer::create(const ContextPtr& context, uint32_t bufSize) { CodedBufferPtr coded; BufObjectPtr buf = VaapiBuffer::create(context, VAEncCodedBufferType, bufSize); if (buf) coded.reset(new VaapiCodedBuffer(buf)); return coded; } bool VaapiCodedBuffer::map() { if (!m_segments) m_segments = static_cast<VACodedBufferSegment*>(m_buf->map()); return m_segments != NULL; } uint32_t VaapiCodedBuffer::size() { if (!map()) return 0; uint32_t size = 0; VACodedBufferSegment* segment = m_segments; while (segment != NULL) { size += segment->size; segment = static_cast<VACodedBufferSegment*>(segment->next); } return size; } bool VaapiCodedBuffer::copyInto(void* data) { if (!data) return false; if (!map()) return false; uint8_t* dest = static_cast<uint8_t*>(data); VACodedBufferSegment* segment = m_segments; while (segment != NULL) { memcpy(dest, segment->buf, segment->size); dest += segment->size; segment = static_cast<VACodedBufferSegment*>(segment->next); } return true; } }
1,946
647
// Copyright (c) 2002-2013, Boyce Griffith // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of New York University nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. // Config files #include <IBAMR_prefix_config.h> #include <IBTK_prefix_config.h> #include <SAMRAI_config.h> // Headers for basic PETSc functions #include <petscsys.h> // Headers for basic SAMRAI objects #include <BergerRigoutsos.h> #include <CartesianGridGeometry.h> #include <LoadBalancer.h> #include <StandardTagAndInitialize.h> // Headers for basic libMesh objects #include <libmesh/boundary_info.h> #include <libmesh/equation_systems.h> #include <libmesh/exodusII_io.h> #include <libmesh/mesh.h> #include <libmesh/mesh_function.h> #include <libmesh/mesh_generation.h> // Headers for application-specific algorithm/data structure objects #include <ibamr/IBExplicitHierarchyIntegrator.h> #include <ibamr/IBFEMethod.h> #include <ibamr/INSCollocatedHierarchyIntegrator.h> #include <ibamr/INSStaggeredHierarchyIntegrator.h> #include <ibamr/app_namespaces.h> #include <ibtk/AppInitializer.h> #include <ibtk/libmesh_utilities.h> #include <ibtk/muParserCartGridFunction.h> #include <ibtk/muParserRobinBcCoefs.h> // Elasticity model data. namespace ModelData { static double kappa_s = 1.0e6; // Tether (penalty) force function for the solid block. void block_tether_force_function( VectorValue<double>& F, const TensorValue<double>& /*FF*/, const Point& X, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { F = kappa_s*(s-X); return; }// block_tether_force_function // Tether (penalty) force function for the thin beam. void beam_tether_force_function( VectorValue<double>& F, const TensorValue<double>& /*FF*/, const Point& X, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { const double r = sqrt((s(0) - 0.2)*(s(0) - 0.2) + (s(1) - 0.2)*(s(1) - 0.2)); if (r <= 0.05) { F = kappa_s*(s-X); } else { F.zero(); } return; }// beam_tether_force_function // Stress tensor function for the thin beam. static double mu_s, lambda_s; void beam_PK1_stress_function( TensorValue<double>& PP, const TensorValue<double>& FF, const Point& /*X*/, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { const double r = sqrt((s(0) - 0.2)*(s(0) - 0.2) + (s(1) - 0.2)*(s(1) - 0.2)); if (r > 0.05) { static const TensorValue<double> II(1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0); const TensorValue<double> CC = FF.transpose()*FF; const TensorValue<double> EE = 0.5*(CC - II); const TensorValue<double> SS = lambda_s*EE.tr()*II + 2.0*mu_s*EE; PP = FF*SS; } else { PP.zero(); } return; }// beam_PK1_stress_function } using namespace ModelData; // Function prototypes static ofstream drag_stream, lift_stream, A_x_posn_stream, A_y_posn_stream; void postprocess_data( Pointer<PatchHierarchy<NDIM> > patch_hierarchy, Pointer<INSHierarchyIntegrator> navier_stokes_integrator, Mesh& beam_mesh, EquationSystems* beam_equation_systems, Mesh& block_mesh, EquationSystems* block_equation_systems, const int iteration_num, const double loop_time, const string& data_dump_dirname); /******************************************************************************* * For each run, the input filename and restart information (if needed) must * * be given on the command line. For non-restarted case, command line is: * * * * executable <input file name> * * * * For restarted run, command line is: * * * * executable <input file name> <restart directory> <restart number> * * * *******************************************************************************/ int main( int argc, char* argv[]) { // Initialize libMesh, PETSc, MPI, and SAMRAI. LibMeshInit init(argc, argv); SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD); SAMRAI_MPI::setCallAbortInSerialInsteadOfExit(); SAMRAIManager::startup(); {// cleanup dynamically allocated objects prior to shutdown // Parse command line options, set some standard options from the input // file, initialize the restart database (if this is a restarted run), // and enable file logging. Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "IB.log"); Pointer<Database> input_db = app_initializer->getInputDatabase(); // Get various standard options set in the input file. const bool dump_viz_data = app_initializer->dumpVizData(); const int viz_dump_interval = app_initializer->getVizDumpInterval(); const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter(); const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty(); const string block_exodus_filename = app_initializer->getExodusIIFilename("block"); const string beam_exodus_filename = app_initializer->getExodusIIFilename("beam" ); const bool dump_restart_data = app_initializer->dumpRestartData(); const int restart_dump_interval = app_initializer->getRestartDumpInterval(); const string restart_dump_dirname = app_initializer->getRestartDumpDirectory(); const bool dump_postproc_data = app_initializer->dumpPostProcessingData(); const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval(); const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory(); if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty()) { Utilities::recursiveMkdir(postproc_data_dump_dirname); } const bool dump_timer_data = app_initializer->dumpTimerData(); const int timer_dump_interval = app_initializer->getTimerDumpInterval(); // Create a simple FE mesh. const double dx = input_db->getDouble("DX"); const double ds = input_db->getDouble("MFAC")*dx; Mesh block_mesh(NDIM); string block_elem_type = input_db->getString("BLOCK_ELEM_TYPE"); const double R = 0.05; if (block_elem_type == "TRI3" || block_elem_type == "TRI6") { const int num_circum_nodes = ceil(2.0*M_PI*R/ds); for (int k = 0; k < num_circum_nodes; ++k) { const double theta = 2.0*M_PI*static_cast<double>(k)/static_cast<double>(num_circum_nodes); block_mesh.add_point(Point(R*cos(theta), R*sin(theta))); } TriangleInterface triangle(block_mesh); triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL; triangle.elem_type() = Utility::string_to_enum<ElemType>(block_elem_type); triangle.desired_area() = sqrt(3.0)/4.0*ds*ds; triangle.insert_extra_points() = true; triangle.smooth_after_generating() = true; triangle.triangulate(); block_mesh.prepare_for_use(); } else { // NOTE: number of segments along boundary is 4*2^r. const double num_circum_segments = ceil(2.0*M_PI*R/ds); const int r = log2(0.25*num_circum_segments); MeshTools::Generation::build_sphere(block_mesh, R, r, Utility::string_to_enum<ElemType>(block_elem_type)); } for (MeshBase::node_iterator n_it = block_mesh.nodes_begin(); n_it != block_mesh.nodes_end(); ++n_it) { Node& n = **n_it; n(0) += 0.2; n(1) += 0.2; } Mesh beam_mesh(NDIM); string beam_elem_type = input_db->getString("BEAM_ELEM_TYPE"); MeshTools::Generation::build_square(beam_mesh, ceil(0.4/ds), ceil(0.02/ds), 0.2, 0.6, 0.19, 0.21, Utility::string_to_enum<ElemType>(beam_elem_type)); beam_mesh.prepare_for_use(); vector<Mesh*> meshes(2); meshes[0] = &block_mesh; meshes[1] = & beam_mesh; mu_s = input_db->getDouble("MU_S"); lambda_s = input_db->getDouble("LAMBDA_S"); kappa_s = input_db->getDouble("KAPPA_S"); // Create major algorithm and data objects that comprise the // application. These objects are configured from the input database // and, if this is a restarted run, from the restart database. Pointer<INSHierarchyIntegrator> navier_stokes_integrator; const string solver_type = app_initializer->getComponentDatabase("Main")->getString("solver_type"); if (solver_type == "STAGGERED") { navier_stokes_integrator = new INSStaggeredHierarchyIntegrator( "INSStaggeredHierarchyIntegrator", app_initializer->getComponentDatabase("INSStaggeredHierarchyIntegrator")); } else if (solver_type == "COLLOCATED") { navier_stokes_integrator = new INSCollocatedHierarchyIntegrator( "INSCollocatedHierarchyIntegrator", app_initializer->getComponentDatabase("INSCollocatedHierarchyIntegrator")); } else { TBOX_ERROR("Unsupported solver type: " << solver_type << "\n" << "Valid options are: COLLOCATED, STAGGERED"); } Pointer<IBFEMethod> ib_method_ops = new IBFEMethod( "IBFEMethod", app_initializer->getComponentDatabase("IBFEMethod"), meshes, app_initializer->getComponentDatabase("GriddingAlgorithm")->getInteger("max_levels")); Pointer<IBHierarchyIntegrator> time_integrator = new IBExplicitHierarchyIntegrator( "IBHierarchyIntegrator", app_initializer->getComponentDatabase("IBHierarchyIntegrator"), ib_method_ops, navier_stokes_integrator); Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>( "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry")); Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>( "PatchHierarchy", grid_geometry); Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>( "StandardTagAndInitialize", time_integrator, app_initializer->getComponentDatabase("StandardTagAndInitialize")); Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>(); Pointer<LoadBalancer<NDIM> > load_balancer = new LoadBalancer<NDIM>( "LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer")); Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm = new GriddingAlgorithm<NDIM>( "GriddingAlgorithm", app_initializer->getComponentDatabase("GriddingAlgorithm"), error_detector, box_generator, load_balancer); // Configure the IBFE solver. ib_method_ops->registerLagBodyForceFunction(&block_tether_force_function, std::vector<unsigned int>(), NULL, 0); ib_method_ops->registerLagBodyForceFunction( &beam_tether_force_function, std::vector<unsigned int>(), NULL, 1); ib_method_ops->registerPK1StressTensorFunction(&beam_PK1_stress_function, std::vector<unsigned int>(), NULL, 1); EquationSystems* block_equation_systems = ib_method_ops->getFEDataManager(0)->getEquationSystems(); EquationSystems* beam_equation_systems = ib_method_ops->getFEDataManager(1)->getEquationSystems(); // Create Eulerian initial condition specification objects. if (input_db->keyExists("VelocityInitialConditions")) { Pointer<CartGridFunction> u_init = new muParserCartGridFunction( "u_init", app_initializer->getComponentDatabase("VelocityInitialConditions"), grid_geometry); navier_stokes_integrator->registerVelocityInitialConditions(u_init); } if (input_db->keyExists("PressureInitialConditions")) { Pointer<CartGridFunction> p_init = new muParserCartGridFunction( "p_init", app_initializer->getComponentDatabase("PressureInitialConditions"), grid_geometry); navier_stokes_integrator->registerPressureInitialConditions(p_init); } // Create Eulerian boundary condition specification objects (when necessary). const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift(); vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM); if (periodic_shift.min() > 0) { for (unsigned int d = 0; d < NDIM; ++d) { u_bc_coefs[d] = NULL; } } else { for (unsigned int d = 0; d < NDIM; ++d) { ostringstream bc_coefs_name_stream; bc_coefs_name_stream << "u_bc_coefs_" << d; const string bc_coefs_name = bc_coefs_name_stream.str(); ostringstream bc_coefs_db_name_stream; bc_coefs_db_name_stream << "VelocityBcCoefs_" << d; const string bc_coefs_db_name = bc_coefs_db_name_stream.str(); u_bc_coefs[d] = new muParserRobinBcCoefs( bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry); } navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs); } // Create Eulerian body force function specification objects. if (input_db->keyExists("ForcingFunction")) { Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction( "f_fcn", app_initializer->getComponentDatabase("ForcingFunction"), grid_geometry); time_integrator->registerBodyForceFunction(f_fcn); } // Set up visualization plot file writers. Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter(); if (uses_visit) { time_integrator->registerVisItDataWriter(visit_data_writer); } AutoPtr<ExodusII_IO> block_exodus_io(uses_exodus ? new ExodusII_IO(block_mesh) : NULL); AutoPtr<ExodusII_IO> beam_exodus_io(uses_exodus ? new ExodusII_IO( beam_mesh) : NULL); // Initialize hierarchy configuration and data on all patches. ib_method_ops->initializeFEData(); time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm); // Deallocate initialization objects. app_initializer.setNull(); // Print the input database contents to the log file. plog << "Input database:\n"; input_db->printClassData(plog); // Write out initial visualization data. int iteration_num = time_integrator->getIntegratorStep(); double loop_time = time_integrator->getIntegratorTime(); if (dump_viz_data) { pout << "\n\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { block_exodus_io->write_timestep(block_exodus_filename, *block_equation_systems, iteration_num/viz_dump_interval+1, loop_time); beam_exodus_io ->write_timestep( beam_exodus_filename, * beam_equation_systems, iteration_num/viz_dump_interval+1, loop_time); } } // Open streams to save lift and drag coefficients. if (SAMRAI_MPI::getRank() == 0) { drag_stream.open("C_D.curve", ios_base::out | ios_base::trunc); lift_stream.open("C_L.curve", ios_base::out | ios_base::trunc); A_x_posn_stream.open("A_x.curve", ios_base::out | ios_base::trunc); A_y_posn_stream.open("A_y.curve", ios_base::out | ios_base::trunc); } // Main time step loop. double loop_time_end = time_integrator->getEndTime(); double dt = 0.0; while (!MathUtilities<double>::equalEps(loop_time,loop_time_end) && time_integrator->stepsRemaining()) { iteration_num = time_integrator->getIntegratorStep(); loop_time = time_integrator->getIntegratorTime(); pout << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "At beginning of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; dt = time_integrator->getMaximumTimeStepSize(); time_integrator->advanceHierarchy(dt); loop_time += dt; pout << "\n"; pout << "At end of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "\n"; // At specified intervals, write visualization and restart files, // print out timer data, and store hierarchy data for post // processing. iteration_num += 1; const bool last_step = !time_integrator->stepsRemaining(); if (dump_viz_data && (iteration_num%viz_dump_interval == 0 || last_step)) { pout << "\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { block_exodus_io->write_timestep(block_exodus_filename, *block_equation_systems, iteration_num/viz_dump_interval+1, loop_time); beam_exodus_io ->write_timestep( beam_exodus_filename, * beam_equation_systems, iteration_num/viz_dump_interval+1, loop_time); } } if (dump_restart_data && (iteration_num%restart_dump_interval == 0 || last_step)) { pout << "\nWriting restart files...\n\n"; RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num); } if (dump_timer_data && (iteration_num%timer_dump_interval == 0 || last_step)) { pout << "\nWriting timer data...\n\n"; TimerManager::getManager()->print(plog); } if (dump_postproc_data && (iteration_num%postproc_data_dump_interval == 0 || last_step)) { pout << "\nWriting state data...\n\n"; postprocess_data(patch_hierarchy, navier_stokes_integrator, beam_mesh, beam_equation_systems, block_mesh, block_equation_systems, iteration_num, loop_time, postproc_data_dump_dirname); } } // Close the logging streams. if (SAMRAI_MPI::getRank() == 0) { drag_stream.close(); lift_stream.close(); A_x_posn_stream.close(); A_y_posn_stream.close(); } // Cleanup Eulerian boundary condition specification objects (when // necessary). for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d]; }// cleanup dynamically allocated objects prior to shutdown SAMRAIManager::shutdown(); return 0; }// main void postprocess_data( Pointer<PatchHierarchy<NDIM> > /*patch_hierarchy*/, Pointer<INSHierarchyIntegrator> /*navier_stokes_integrator*/, Mesh& beam_mesh, EquationSystems* beam_equation_systems, Mesh& block_mesh, EquationSystems* block_equation_systems, const int /*iteration_num*/, const double loop_time, const string& /*data_dump_dirname*/) { double F_integral[NDIM]; for (unsigned int d = 0; d < NDIM; ++d) F_integral[d] = 0.0; Mesh* mesh[2] = {&beam_mesh , &block_mesh}; EquationSystems* equation_systems[2] = {beam_equation_systems , block_equation_systems}; for (unsigned int k = 0; k < 2; ++k) { System& F_system = equation_systems[k]->get_system<System>(IBFEMethod::FORCE_SYSTEM_NAME); NumericVector<double>* F_vec = F_system.solution.get(); NumericVector<double>* F_ghost_vec = F_system.current_local_solution.get(); F_vec->localize(*F_ghost_vec); DofMap& F_dof_map = F_system.get_dof_map(); blitz::Array<std::vector<unsigned int>,1> F_dof_indices(NDIM); AutoPtr<FEBase> fe(FEBase::build(NDIM, F_dof_map.variable_type(0))); AutoPtr<QBase> qrule = QBase::build(QGAUSS, NDIM, FIFTH); fe->attach_quadrature_rule(qrule.get()); const std::vector<std::vector<double> >& phi = fe->get_phi(); const std::vector<double>& JxW = fe->get_JxW(); blitz::Array<double,2> F_node; const MeshBase::const_element_iterator el_begin = mesh[k]->active_local_elements_begin(); const MeshBase::const_element_iterator el_end = mesh[k]->active_local_elements_end(); for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it) { Elem* const elem = *el_it; fe->reinit(elem); for (unsigned int d = 0; d < NDIM; ++d) { F_dof_map.dof_indices(elem, F_dof_indices(d), d); } const int n_qp = qrule->n_points(); const int n_basis = F_dof_indices(0).size(); get_values_for_interpolation(F_node, *F_ghost_vec, F_dof_indices); for (int qp = 0; qp < n_qp; ++qp) { for (int k = 0; k < n_basis; ++k) { for (int d = 0; d < NDIM; ++d) { F_integral[d] += F_node(k,d)*phi[k][qp]*JxW[qp]; } } } } } SAMRAI_MPI::sumReduction(F_integral,NDIM); if (SAMRAI_MPI::getRank() == 0) { drag_stream.precision(12); drag_stream.setf(ios::fixed,ios::floatfield); drag_stream << loop_time << " " << -F_integral[0] << endl; lift_stream.precision(12); lift_stream.setf(ios::fixed,ios::floatfield); lift_stream << loop_time << " " << -F_integral[1] << endl; } System& X_system = beam_equation_systems->get_system<System>(IBFEMethod::COORDS_SYSTEM_NAME); NumericVector<double>* X_vec = X_system.solution.get(); AutoPtr<NumericVector<Number> > X_serial_vec = NumericVector<Number>::build(); X_serial_vec->init(X_vec->size(), true, SERIAL); X_vec->localize(*X_serial_vec); DofMap& X_dof_map = X_system.get_dof_map(); vector<unsigned int> vars(2); vars[0] = 0; vars[1] = 1; MeshFunction X_fcn(*beam_equation_systems, *X_serial_vec, X_dof_map, vars); X_fcn.init(); DenseVector<double> X_A(2); X_fcn(Point(0.6,0.2,0), 0.0, X_A); if (SAMRAI_MPI::getRank() == 0) { A_x_posn_stream.precision(12); A_x_posn_stream.setf(ios::fixed,ios::floatfield); A_x_posn_stream << loop_time << " " << X_A(0) << endl; A_y_posn_stream.precision(12); A_y_posn_stream.setf(ios::fixed,ios::floatfield); A_y_posn_stream << loop_time << " " << X_A(1) << endl; } return; }// postprocess_data
25,920
8,398
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Jugbug_Character_BaseBP_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Jugbug_Character_BaseBP.Jugbug_Character_BaseBP_C // 0x0048 (0x22B0 - 0x2268) class AJugbug_Character_BaseBP_C : public AInsect_Character_Base_C { public: class UDinoCharacterStatusComponent_BP_JugBug_C* DinoCharacterStatus_BP_JugBug_C1; // 0x2268(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UAudioComponent* LivingAudio; // 0x2270(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) float ResourceAmount; // 0x2278(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData) TEnumAsByte<EJugbugType> JugbugType; // 0x227C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, SaveGame, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x227D(0x0003) MISSED OFFSET float MaxResourceAmount; // 0x2280(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float ResourceAmountFillTime; // 0x2284(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float MinSpeed; // 0x2288(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) int MaxItemsToGive; // 0x228C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) class UClass* PrimalItemToGive; // 0x2290(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) double LastUpdateTime; // 0x2298(0x0008) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) float MaxJugbugWaterGiveAmount; // 0x22A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x4]; // 0x22A4(0x0004) MISSED OFFSET double LastGiveResourcesTime; // 0x22A8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Jugbug_Character_BaseBP.Jugbug_Character_BaseBP_C"); return ptr; } void BPTimerNonDedicated(); void BPTimerServer(); bool BlueprintCanAttack(int* AttackIndex, float* Distance, float* attackRangeOffset, class AActor** OtherTarget); TArray<struct FMultiUseEntry> STATIC_BPGetMultiUseEntries(class APlayerController** ForPC, TArray<struct FMultiUseEntry>* MultiUseEntries); void AddResource(float amount, float* NewResourceAmount, float* AddedResourceAmount); bool BPTryMultiUse(class APlayerController** ForPC, int* UseIndex); void RefreshResourceAmount(); void BlueprintDrawFloatingHUD(class AShooterHUD** HUD, float* CenterX, float* CenterY, float* DrawScale); void UserConstructionScript(); void ExecuteUbergraph_Jugbug_Character_BaseBP(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
4,195
1,232
// Copyright (c) M5Stack. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "RTC8563_Class.hpp" #include <sys/time.h> namespace m5 { static std::uint8_t bcd2ToByte(std::uint8_t value) { return ((value >> 4) * 10) + (value & 0x0F); } static std::uint8_t byteToBcd2(std::uint8_t value) { std::uint_fast8_t bcdhigh = value / 10; return (bcdhigh << 4) | (value - (bcdhigh * 10)); } bool RTC8563_Class::begin(I2C_Class* i2c) { if (i2c) { _i2c = i2c; i2c->begin(); } /// TimerCameraの内蔵RTCが初期化に失敗することがあったため、最初に空打ちする; writeRegister8(0x00, 0x00); _init = writeRegister8(0x00, 0x00) && writeRegister8(0x0E, 0x03); return _init; } bool RTC8563_Class::getVoltLow(void) { return readRegister8(0x02) & 0x80; // RTCC_VLSEC_MASK } bool RTC8563_Class::getDateTime(rtc_datetime_t* datetime) const { std::uint8_t buf[7] = { 0 }; if (!isEnabled() || !readRegister(0x02, buf, 7)) { return false; } datetime->time.seconds = bcd2ToByte(buf[0] & 0x7f); datetime->time.minutes = bcd2ToByte(buf[1] & 0x7f); datetime->time.hours = bcd2ToByte(buf[2] & 0x3f); datetime->date.date = bcd2ToByte(buf[3] & 0x3f); datetime->date.weekDay = bcd2ToByte(buf[4] & 0x07); datetime->date.month = bcd2ToByte(buf[5] & 0x1f); datetime->date.year = bcd2ToByte(buf[6] & 0xff) + ((0x80 & buf[5]) ? 1900 : 2000); return true; } bool RTC8563_Class::getTime(rtc_time_t* time) const { std::uint8_t buf[3] = { 0 }; if (!isEnabled() || !readRegister(0x02, buf, 3)) { return false; } time->seconds = bcd2ToByte(buf[0] & 0x7f); time->minutes = bcd2ToByte(buf[1] & 0x7f); time->hours = bcd2ToByte(buf[2] & 0x3f); return true; } void RTC8563_Class::setTime(const rtc_time_t& time) { std::uint8_t buf[] = { byteToBcd2(time.seconds) , byteToBcd2(time.minutes) , byteToBcd2(time.hours) }; writeRegister(0x02, buf, sizeof(buf)); } bool RTC8563_Class::getDate(rtc_date_t* date) const { std::uint8_t buf[4] = {0}; if (!readRegister(0x05, buf, 4)) { return false; } date->date = bcd2ToByte(buf[0] & 0x3f); date->weekDay = bcd2ToByte(buf[1] & 0x07); date->month = bcd2ToByte(buf[2] & 0x1f); date->year = bcd2ToByte(buf[3] & 0xff) + ((0x80 & buf[2]) ? 1900 : 2000); return true; } void RTC8563_Class::setDate(const rtc_date_t& date) { std::uint8_t w = date.weekDay; if (w > 6 && date.year >= 1900 && ((std::size_t)(date.month - 1)) < 12) { /// weekDay auto adjust std::int_fast16_t y = date.year / 100; w = (date.year + (date.year >> 2) - y + (y >> 2) + (13 * date.month + 8) / 5 + date.date) % 7; } std::uint8_t buf[] = { byteToBcd2(date.date) , w , (std::uint8_t)(byteToBcd2(date.month) + (date.year < 2000 ? 0x80 : 0)) , byteToBcd2(date.year % 100) }; writeRegister(0x05, buf, sizeof(buf)); } int RTC8563_Class::setAlarmIRQ(int afterSeconds) { std::uint8_t reg_value = readRegister8(0x01) & ~0x0C; if (afterSeconds < 0) { // disable timer writeRegister8(0x01, reg_value & ~0x01); writeRegister8(0x0E, 0x03); return -1; } std::size_t div = 1; std::uint8_t type_value = 0x82; if (afterSeconds < 270) { if (afterSeconds > 255) { afterSeconds = 255; } } else { div = 60; afterSeconds = (afterSeconds + 30) / div; if (afterSeconds > 255) { afterSeconds = 255; } type_value = 0x83; } writeRegister8(0x0E, type_value); writeRegister8(0x0F, afterSeconds); writeRegister8(0x01, (reg_value | 0x01) & ~0x80); return afterSeconds * div; } int RTC8563_Class::setAlarmIRQ(const rtc_time_t &time) { union { std::uint32_t raw = ~0; std::uint8_t buf[4]; }; bool irq_enable = false; if (time.minutes >= 0) { irq_enable = true; buf[0] = byteToBcd2(time.minutes) & 0x7f; } if (time.hours >= 0) { irq_enable = true; buf[1] = byteToBcd2(time.hours) & 0x3f; } writeRegister(0x09, buf, 4); if (irq_enable) { bitOn(0x01, 0x02); } else { bitOff(0x01, 0x02); } return irq_enable; } int RTC8563_Class::setAlarmIRQ(const rtc_date_t &date, const rtc_time_t &time) { union { std::uint32_t raw = ~0; std::uint8_t buf[4]; }; bool irq_enable = false; if (time.minutes >= 0) { irq_enable = true; buf[0] = byteToBcd2(time.minutes) & 0x7f; } if (time.hours >= 0) { irq_enable = true; buf[1] = byteToBcd2(time.hours) & 0x3f; } if (date.date >= 0) { irq_enable = true; buf[2] = byteToBcd2(date.date) & 0x3f; } if (date.weekDay >= 0) { irq_enable = true; buf[3] = byteToBcd2(date.weekDay) & 0x07; } writeRegister(0x09, buf, 4); if (irq_enable) { bitOn(0x01, 1 << 1); } else { bitOff(0x01, 1 << 1); } return irq_enable; } bool RTC8563_Class::getIRQstatus(void) { return _init && (0x0C & readRegister8(0x01)); } void RTC8563_Class::clearIRQ(void) { if (!_init) { return; } bitOff(0x01, 0x0C); } void RTC8563_Class::disableIRQ(void) { if (!_init) { return; } // disable alerm (bit7:1=disabled) std::uint8_t buf[4] = { 0x80, 0x80, 0x80, 0x80 }; writeRegister(0x09, buf, 4); // disable timer (bit7:0=disabled) writeRegister8(0x0E, 0); // clear flag and INT enable bits writeRegister8(0x01, 0x00); } void RTC8563_Class::setSystemTimeFromRtc(void) { rtc_datetime_t dt; if (getDateTime(&dt)) { tm t_st; t_st.tm_isdst = -1; t_st.tm_year = dt.date.year - 1900; t_st.tm_mon = dt.date.month - 1; t_st.tm_mday = dt.date.date; t_st.tm_hour = dt.time.hours; t_st.tm_min = dt.time.minutes; t_st.tm_sec = dt.time.seconds; timeval now; now.tv_sec = mktime(&t_st); now.tv_usec = 0; settimeofday(&now, nullptr); } } }
6,248
2,914
#include <State/IntroState.h> #include <Core/Define.h> #include <SDL2_gfxPrimitives.h> #include <Core/GameEngine.h> bool IntroState::init() { internalState = DEVSCREEN; devScreen = new Sprite(game, "./gfx/intro/devscreen.png", 0, 0, WWIDTH, WHEIGHT); introScreen = new Sprite(game, "./gfx/intro/introscreen.png", 0, 0, WWIDTH, WHEIGHT); startTime = SDL_GetTicks(); return true; } void IntroState::cleanup() { delete devScreen; delete introScreen; } bool IntroState::handleEvent(const SDL_Event &ev) { if (ev.type == SDL_QUIT) { game->getEngine()->exit(); return true; } else if (ev.type == SDL_KEYDOWN) { if (ev.key.keysym.sym == SDLK_ESCAPE || ev.key.keysym.sym == SDLK_SPACE) { if (internalState == INTROSCREEN) { game->getEngine()->setState((State*)game->mainMenuState); } else { internalState = INTROSCREEN; } return true; } } return false; } void IntroState::update(const float &timeStep) { if (SDL_GetTicks() > (startTime + 6000) && internalState == DEVSCREEN) internalState = INTROSCREEN; } void IntroState::render(SDL_Renderer* const renderer) { if (internalState == DEVSCREEN) { unsigned int initial_delay = 1000; unsigned int fadeout_time = 3000; int alpha_level = 255 - ((SDL_GetTicks() - initial_delay) / 5); if (alpha_level < 0) alpha_level = 0; if (SDL_GetTicks() > initial_delay && SDL_GetTicks() <= fadeout_time) { devScreen->draw(renderer); boxRGBA(renderer, 0, 0, WWIDTH, WHEIGHT, 0, 0, 0, alpha_level); } else if (SDL_GetTicks() > initial_delay) devScreen->draw(renderer); } else if (internalState == INTROSCREEN) { introScreen->draw(renderer); } }
1,673
749
// // Created by Roger Valderrama on 4/10/18. // /** * @file JSONStruct.hpp * @version 1.0 * @date 4/10/18 * @author Roger Valderrama * @title JSON for Structs * @brief JSON Class for saving structs with its variables. */ #ifndef C_IDE_JSONSTRUCT_HPP #define C_IDE_JSONSTRUCT_HPP #include "JSONVar.hpp" #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> class JSONStruct { /** * @brief An array oj Json for the variables of the line of code. */ QJsonArray *variables = new QJsonArray; /** * @brief json that represent the JsonObject that will be modified. */ QJsonObject *json = new QJsonObject; public: /** * @brief It add all variables to a Json and it prints it and add it to the log file. */ void submit(); /** * @brief Converts the JSON into a char so it can be added to the log file. */ const char *toLog(); /** * @brief Converts the JSON into a string. */ std::string toString(); /** * @brief It adds Variables to the JSON for struct. * @param jsonVar each json variable it will add. */ void add(JSONVar *jsonVar); /** * @brief It inserts to the JSON each key with its value. */ void put(std::string, std::string); }; #endif //C_IDE_JSONSTRUCT_HPP
1,307
450
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt /** * @file tdouble_ops.hpp * * @brief Macros for defining `tdouble` operators. */ #ifndef CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP #define CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP #include <cynodelic/tesela/config.hpp> #define CYNODELIC_TESELA_TDOUBLE_DEFINE_ARITHMETIC_OPERATOR(op) \ constexpr friend tdouble operator op(const tdouble& lhs,const tdouble& rhs) \ { \ return tdouble(lhs.data op rhs.data); \ } \ constexpr friend tdouble operator op(const tdouble& lhs,const value_type& rhs) \ { \ return tdouble(lhs.data op tdouble(rhs).data); \ } \ constexpr friend tdouble operator op(const value_type& lhs,const tdouble& rhs) \ { \ return tdouble(tdouble(lhs).data op rhs.data); \ } #define CYNODELIC_TESELA_TDOUBLE_DEFINE_COMPARISON_OPERATOR(op) \ constexpr friend bool operator op(const tdouble& lhs,const tdouble& rhs) \ { \ return lhs.data op rhs.data; \ } \ constexpr friend bool operator op(const tdouble& lhs,const value_type& rhs) \ { \ return lhs.data op rhs; \ } \ constexpr friend bool operator op(const value_type& lhs,const tdouble& rhs) \ { \ return lhs op rhs.data; \ } #define CYNODELIC_TESELA_TDOUBLE_DEFINE_COMPOUND_OPERATOR(cmp_op,op) \ template <typename T> \ tdouble& operator cmp_op(const T& rhs) \ { \ data = quantize(data op quantize(rhs)); \ return *this; \ } \ tdouble& operator cmp_op(const tdouble& rhs) \ { \ data = quantize(data op rhs.data); \ return *this; \ } #endif // CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP
1,721
745
#if !defined(_FUNCTIONS_FUNCTIONS_HPP_) #define _FUNCTIONS_FUNCTIONS_HPP_ #include <irafldef.h> #include <cmath> namespace IRAFLFunc { static double PI = atan(1.0) * 4; static double ColorNormal[256] = { 0.0, 0.00392156862745098, 0.00784313725490196, 0.011764705882352941, 0.01568627450980392, 0.0196078431372549, 0.023529411764705882, 0.027450980392156862, 0.03137254901960784, 0.03529411764705882, 0.0392156862745098, 0.043137254901960784, 0.047058823529411764, 0.050980392156862744, 0.054901960784313725, 0.058823529411764705, 0.06274509803921569, 0.06666666666666667, 0.07058823529411765, 0.07450980392156863, 0.0784313725490196, 0.08235294117647059, 0.08627450980392157, 0.09019607843137255, 0.09411764705882353, 0.09803921568627451, 0.10196078431372549, 0.10588235294117647, 0.10980392156862745, 0.11372549019607843, 0.11764705882352941, 0.12156862745098039, 0.12549019607843137, 0.12941176470588237, 0.13333333333333333, 0.13725490196078433, 0.1411764705882353, 0.1450980392156863, 0.14901960784313725, 0.15294117647058825, 0.1568627450980392, 0.1607843137254902, 0.16470588235294117, 0.16862745098039217, 0.17254901960784313, 0.17647058823529413, 0.1803921568627451, 0.1843137254901961, 0.18823529411764706, 0.19215686274509805, 0.19607843137254902, 0.2, 0.20392156862745098, 0.20784313725490197, 0.21176470588235294, 0.21568627450980393, 0.2196078431372549, 0.2235294117647059, 0.22745098039215686, 0.23137254901960785, 0.23529411764705882, 0.23921568627450981, 0.24313725490196078, 0.24705882352941178, 0.25098039215686274, 0.2549019607843137, 0.25882352941176473, 0.2627450980392157, 0.26666666666666666, 0.27058823529411763, 0.27450980392156865, 0.2784313725490196, 0.2823529411764706, 0.28627450980392155, 0.2901960784313726, 0.29411764705882354, 0.2980392156862745, 0.30196078431372547, 0.3058823529411765, 0.30980392156862746, 0.3137254901960784, 0.3176470588235294, 0.3215686274509804, 0.3254901960784314, 0.32941176470588235, 0.3333333333333333, 0.33725490196078434, 0.3411764705882353, 0.34509803921568627, 0.34901960784313724, 0.35294117647058826, 0.3568627450980392, 0.3607843137254902, 0.36470588235294116, 0.3686274509803922, 0.37254901960784315, 0.3764705882352941, 0.3803921568627451, 0.3843137254901961, 0.38823529411764707, 0.39215686274509803, 0.396078431372549, 0.4, 0.403921568627451, 0.40784313725490196, 0.4117647058823529, 0.41568627450980394, 0.4196078431372549, 0.4235294117647059, 0.42745098039215684, 0.43137254901960786, 0.43529411764705883, 0.4392156862745098, 0.44313725490196076, 0.4470588235294118, 0.45098039215686275, 0.4549019607843137, 0.4588235294117647, 0.4627450980392157, 0.4666666666666667, 0.47058823529411764, 0.4745098039215686, 0.47843137254901963, 0.4823529411764706, 0.48627450980392156, 0.49019607843137253, 0.49411764705882355, 0.4980392156862745, 0.5019607843137255, 0.5058823529411764, 0.5098039215686274, 0.5137254901960784, 0.5176470588235295, 0.5215686274509804, 0.5254901960784314, 0.5294117647058824, 0.5333333333333333, 0.5372549019607843, 0.5411764705882353, 0.5450980392156862, 0.5490196078431373, 0.5529411764705883, 0.5568627450980392, 0.5607843137254902, 0.5647058823529412, 0.5686274509803921, 0.5725490196078431, 0.5764705882352941, 0.5803921568627451, 0.5843137254901961, 0.5882352941176471, 0.592156862745098, 0.596078431372549, 0.6, 0.6039215686274509, 0.6078431372549019, 0.611764705882353, 0.615686274509804, 0.6196078431372549, 0.6235294117647059, 0.6274509803921569, 0.6313725490196078, 0.6352941176470588, 0.6392156862745098, 0.6431372549019608, 0.6470588235294118, 0.6509803921568628, 0.6549019607843137, 0.6588235294117647, 0.6627450980392157, 0.6666666666666666, 0.6705882352941176, 0.6745098039215687, 0.6784313725490196, 0.6823529411764706, 0.6862745098039216, 0.6901960784313725, 0.6941176470588235, 0.6980392156862745, 0.7019607843137254, 0.7058823529411765, 0.7098039215686275, 0.7137254901960784, 0.7176470588235294, 0.7215686274509804, 0.7254901960784313, 0.7294117647058823, 0.7333333333333333, 0.7372549019607844, 0.7411764705882353, 0.7450980392156863, 0.7490196078431373, 0.7529411764705882, 0.7568627450980392, 0.7607843137254902, 0.7647058823529411, 0.7686274509803922, 0.7725490196078432, 0.7764705882352941, 0.7803921568627451, 0.7843137254901961, 0.788235294117647, 0.792156862745098, 0.796078431372549, 0.8, 0.803921568627451, 0.807843137254902, 0.8117647058823529, 0.8156862745098039, 0.8196078431372549, 0.8235294117647058, 0.8274509803921568, 0.8313725490196079, 0.8352941176470589, 0.8392156862745098, 0.8431372549019608, 0.8470588235294118, 0.8509803921568627, 0.8549019607843137, 0.8588235294117647, 0.8627450980392157, 0.8666666666666667, 0.8705882352941177, 0.8745098039215686, 0.8784313725490196, 0.8823529411764706, 0.8862745098039215, 0.8901960784313725, 0.8941176470588236, 0.8980392156862745, 0.9019607843137255, 0.9058823529411765, 0.9098039215686274, 0.9137254901960784, 0.9176470588235294, 0.9215686274509803, 0.9254901960784314, 0.9294117647058824, 0.9333333333333333, 0.9372549019607843, 0.9411764705882353, 0.9450980392156862, 0.9490196078431372, 0.9529411764705882, 0.9568627450980393, 0.9607843137254902, 0.9647058823529412, 0.9686274509803922, 0.9725490196078431, 0.9764705882352941, 0.9803921568627451, 0.984313725490196, 0.9882352941176471, 0.9921568627450981, 0.996078431372549, 1.0, }; static const unsigned int crc32tab[] = { 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL }; uint32_t CRC32Get(const void* vbuf, unsigned int size) { const unsigned char* buf = (const unsigned char*)vbuf; unsigned int i, crc; crc = 0xFFFFFFFF; for (i = 0; i < size; i++) crc = crc32tab[(crc ^ buf[i]) & 0xff] ^ (crc >> 8); return crc ^ 0xFFFFFFFF; } } #endif
9,524
8,514
#include <iostream> using namespace std; template<class T> T getMin(T a, T b) { return a < b ? a : b; } int main() { int a, b, c; a = 123; b = 456; c = getMin(a, b); cout << c << endl; double x, y, z; x = 1.23; y = 4.56; z = getMin(x, y); cout << z << endl; return 0; }
320
152
#include "moocov/utils/fastint.h" namespace moocov { namespace utils { const FastIntWriterManip fastInt{}; } // end namespace utils } // end namespace moocov
161
56
#include "Deck.h" Deck::Deck( deckType newType ){ switch( newType ){ case deckType_BlackJack: { ConsoleMessage( msgType_info, msgSpeed_auto, "Deck Type: Black jack deck" ); SetPopulation( 52 ); for( int i = 3; i < 7; i++ ){ for( int j = 1; j < 14; j++ ){ Deck::m_Cards[m_Index].Set( (Seed)i, j, UNFOLD); m_Index++; } } } break; default: cout << "Deck initialization error"; break; } } Deck::Deck(){ for( int i = 3; i < 7; i++ ){ for( int j = 0; j < 13; j++ ){ Deck::m_Cards[i].Set( (Seed)i, j, UNFOLD); m_Index++; } } Deck::m_Cards[52].Set(Hearts, 0, UNFOLD); Deck::m_Cards[53].Set(Clubs, 0, UNFOLD); } Deck::~Deck(){ //dtor } void Deck::Shuffle(){ m_Index = m_Population; for( int i = 0; i < (m_Index); i++ ){ std::swap( m_Cards[i], m_Cards[ rand() % (m_Index) ] ); } for( int i = 0; i < m_Population; i++ ){ m_Cards[i].SetFold(); } m_Index = m_Population; } void Deck::Print(){ indent(); int offset = 1; for( int i = 0 + offset; i < Deck::m_Index + offset; i++ ){ Deck::m_Cards[i - offset].Print(); cout << SPACE; if( ( i % 13 ) == 0 ) cout << LINE << " "; } } Card Deck::Draw(){ m_Index--; m_Cards[ m_Index ].SetUnfold(); return m_Cards[ m_Index ]; } bool Deck::CheckIndex(){ if( Deck::GetIndex() > Deck::GetPopulation() ){ return true; } return false; }
1,647
667
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // Name : // Author : Avi // Revision : $Revision: #85 $ // // Copyright 2009- ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // file deepcode ignore CppConstantBinaryExpression: <comment the reason here> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/python/raw_function.hpp> #include <boost/core/noncopyable.hpp> #include "Defs.hpp" #include "Suite.hpp" #include "Family.hpp" #include "Task.hpp" #include "BoostPythonUtil.hpp" #include "DefsDoc.hpp" #include "NodeUtil.hpp" using namespace ecf; using namespace boost::python; using namespace std; namespace bp = boost::python; // See: http://wiki.python.org/moin/boost.python/HowTo#boost.function_objects /// Since we don't pass in a child pos, the nodes are added to the end family_ptr add_family(NodeContainer* self,family_ptr f){ self->addFamily(f); return f; } task_ptr add_task(NodeContainer* self,task_ptr t){ self->addTask(t); return t;} suite_ptr add_clock(suite_ptr self, const ClockAttr& clk) { self->addClock(clk); return self;} suite_ptr add_end_clock(suite_ptr self, const ClockAttr& clk) { self->add_end_clock(clk); return self;} // Sized and Container protocol size_t family_len(family_ptr self) { return self->nodeVec().size();} size_t suite_len(suite_ptr self) { return self->nodeVec().size();} bool family_container(family_ptr self, const std::string& name){size_t pos; return (self->findImmediateChild(name,pos)) ? true: false;} bool suite_container(suite_ptr self, const std::string& name) {size_t pos; return (self->findImmediateChild(name,pos)) ? true: false;} // Context management, Only used to provide indentation suite_ptr suite_enter(suite_ptr self) { return self;} bool suite_exit(suite_ptr self,const bp::object& type,const bp::object& value,const bp::object& traceback){return false;} family_ptr family_enter(family_ptr self) { return self;} bool family_exit(family_ptr self,const bp::object& type,const bp::object& value,const bp::object& traceback){return false;} family_ptr family_init(const std::string& name, bp::list the_list, bp::dict kw) { //cout << "family_init : " << name << " the_list: " << len(the_list) << " dict: " << len(kw) << endl; family_ptr node = Family::create(name); (void)NodeUtil::add_variable_dict(node,kw); (void)NodeUtil::node_iadd(node,the_list); return node; } suite_ptr suite_init(const std::string& name, bp::list the_list, bp::dict kw) { //cout << "suite_init : " << name << " the_list: " << len(the_list) << " dict: " << len(kw) << endl; suite_ptr node = Suite::create(name); (void)NodeUtil::add_variable_dict(node,kw); (void)NodeUtil::node_iadd(node,the_list); return node; } void export_SuiteAndFamily() { // Turn off proxies by passing true as the NoProxy template parameter. // shared_ptrs don't need proxies because calls on one a copy of the // shared_ptr will affect all of them (duh!). class_<std::vector<family_ptr> >("FamilyVec","Hold a list of `family`_ nodes") .def(vector_indexing_suite<std::vector<family_ptr>, true >()) ; class_<std::vector<suite_ptr> >("SuiteVec","Hold a list of `suite`_ nodes's") .def(vector_indexing_suite<std::vector<suite_ptr>, true >()); // choose the correct overload class_<NodeContainer, bases<Node>, boost::noncopyable >("NodeContainer",DefsDoc::node_container_doc(), no_init) .def("__iter__",bp::range(&NodeContainer::node_begin,&NodeContainer::node_end)) .def("add_family",&NodeContainer::add_family ,DefsDoc::add_family_doc()) .def("add_family",add_family ) .def("add_task", &NodeContainer::add_task , DefsDoc::add_task_doc()) .def("add_task", add_task ) .def("find_node", &NodeContainer::find_by_name, "Find immediate child node given a name") .def("find_task", &NodeContainer::findTask , "Find a task given a name") .def("find_family", &NodeContainer::findFamily , "Find a family given a name") .add_property("nodes",bp::range( &NodeContainer::node_begin,&NodeContainer::node_end),"Returns a list of Node's") ; class_<Family, bases<NodeContainer>, family_ptr>("Family",DefsDoc::family_doc()) .def("__init__",raw_function(&NodeUtil::node_raw_constructor,1)) // will call -> family_init .def("__init__",make_constructor(&family_init), DefsDoc::family_doc()) .def("__init__",make_constructor(&Family::create_me), DefsDoc::family_doc()) .def(self == self ) // __eq__ .def("__str__", &Family::to_string) // __str__ .def("__copy__", copyObject<Family>) // __copy__ uses copy constructor .def("__enter__", &family_enter) // allow with statement, hence indentation support .def("__exit__", &family_exit) // allow with statement, hence indentation support .def("__len__", &family_len) // Implement sized protocol for immediate children .def("__contains__",&family_container) // Implement container protocol for immediate children ; #if ECF_ENABLE_PYTHON_PTR_REGISTER bp::register_ptr_to_python<family_ptr>(); // needed for mac and boost 1.6 #endif class_<Suite, bases<NodeContainer>, suite_ptr>("Suite",DefsDoc::suite_doc()) .def("__init__",raw_function(&NodeUtil::node_raw_constructor,1)) // will call -> suite_init .def("__init__",make_constructor(&suite_init), DefsDoc::suite_doc()) .def("__init__",make_constructor(&Suite::create_me), DefsDoc::suite_doc()) .def(self == self ) // __eq__ .def("__str__", &Suite::to_string) // __str__ .def("__copy__", copyObject<Suite>) // __copy__ uses copy constructor .def("__enter__", &suite_enter) // allow with statement, hence indentation support .def("__exit__", &suite_exit) // allow with statement, hence indentation support .def("__len__", &suite_len) // Implement sized protocol for immediate children .def("__contains__",&suite_container) // Implement container protocol for immediate children .def("add_clock", &add_clock) .def("get_clock", &Suite::clockAttr,"Returns the `suite`_ `clock`_") .def("add_end_clock", &add_end_clock,"End clock, used to mark end of simulation") .def("get_end_clock", &Suite::clock_end_attr,"Return the suite's end clock. Can be NULL") .def("begun", &Suite::begun, "Returns true if the `suite`_ has begun, false otherwise") ; #if ECF_ENABLE_PYTHON_PTR_REGISTER bp::register_ptr_to_python<suite_ptr>(); // needed for mac and boost 1.6 #endif }
6,961
2,305
/* * File: clrHost.cpp * Author: MarkAtk * Date: 09.10.2018 * * MIT License * * Copyright (c) 2018 Rage-MP-C-SDK * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "clrHost.h" #include <iostream> #ifdef _WIN32 #include <windows.h> #else #include <stdlib.h> #include <dlfcn.h> #include <dirent.h> #include <sys/stat.h> #endif #define RUNTIME_DIR_PATH "./dotnet/runtime/" #define PLUGIN_DIR_PATH "./dotnet/plugins/" #define PLUGIN_NAME "AlternateLife.RageMP.Net" #define PLUGIN_CLASS_NAME "AlternateLife.RageMP.Net.PluginWrapper" #ifdef _WIN32 #define LIST_SEPARATOR ";" #else #define LIST_SEPARATOR ":" #endif ClrHost::ClrHost() { _runtimeHost = nullptr; _domainId = 0; _mainCallback = nullptr; _coreClrLib = nullptr; _initializeCoreCLR = nullptr; _shutdownCoreCLR = nullptr; _createDelegate = nullptr; } ClrHost::~ClrHost() { unload(); } bool ClrHost::load() { if (_coreClrLib == nullptr && loadCoreClr() == false) { return false; } if ((_runtimeHost == 0 || _domainId == 0) && createAppDomain() == false) { return false; } if (_mainCallback == nullptr && getDelegate("Main", (void **)&_mainCallback) == false) { return false; } return true; } void ClrHost::unload() { #ifdef _WIN32 if (_runtimeHost == nullptr) { return; } _shutdownCoreCLR(_runtimeHost, _domainId, nullptr); _runtimeHost = nullptr; _domainId = 0; _mainCallback = nullptr; #else if (_coreClrLib != nullptr) { dlclose(_coreClrLib); _coreClrLib = nullptr; } #endif } MainMethod ClrHost::mainCallback() const { return _mainCallback; } bool ClrHost::loadCoreClr() { std::string coreClrDllPath = getAbsolutePath(RUNTIME_DIR_PATH); #ifdef _WIN32 coreClrDllPath += "/coreclr.dll"; _coreClrLib = LoadLibraryEx(coreClrDllPath.c_str(), NULL, 0); if (_coreClrLib == NULL) { std::cerr << "[.NET] Unable to find CoreCLR dll" << std::endl; return false; } _initializeCoreCLR = (coreclr_initialize_ptr)GetProcAddress(_coreClrLib, "coreclr_initialize"); _shutdownCoreCLR = (coreclr_shutdown_2_ptr)GetProcAddress(_coreClrLib, "coreclr_shutdown_2"); _createDelegate = (coreclr_create_delegate_ptr)GetProcAddress(_coreClrLib, "coreclr_create_delegate"); #else #ifdef __APPLE__ coreClrDllPath += "libcoreclr.dylib"; #else coreClrDllPath += "libcoreclr.so"; #endif _coreClrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL); if (_coreClrLib == nullptr) { std::cerr << "[.NET] Unable to find CoreCLR dll [" << coreClrDllPath << "]: " << dlerror() << std::endl; return false; } _initializeCoreCLR = (coreclr_initialize_ptr)dlsym(_coreClrLib, "coreclr_initialize"); _shutdownCoreCLR = (coreclr_shutdown_2_ptr)dlsym(_coreClrLib, "coreclr_shutdown_2"); _createDelegate = (coreclr_create_delegate_ptr)dlsym(_coreClrLib, "coreclr_create_delegate"); #endif if (_initializeCoreCLR == nullptr || _shutdownCoreCLR == nullptr || _createDelegate == nullptr) { std::cerr << "[.NET] Unable to find CoreCLR dll methods" << std::endl; return false; } return true; } bool ClrHost::createAppDomain() { std::string tpaList = ""; for (auto &tpa : getTrustedAssemblies()) { tpaList += tpa; tpaList += LIST_SEPARATOR; } auto appPath = getAbsolutePath(PLUGIN_DIR_PATH); auto nativeDllPaths = appPath; nativeDllPaths += LIST_SEPARATOR; nativeDllPaths += getAbsolutePath(RUNTIME_DIR_PATH); auto rootDirectory = getAbsolutePath("."); const char *propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "System.GC.Server", "System.Globalization.Invariant", }; const char *propertyValues[] = { tpaList.c_str(), appPath.c_str(), appPath.c_str(), nativeDllPaths.c_str(), "true", "true", }; int result = _initializeCoreCLR( rootDirectory.c_str(), "RageMP Host Domain", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, &_runtimeHost, &_domainId ); if (result < 0) { std::cerr << "[.NET] Unable to create app domain: 0x" << std::hex << result << std::endl; return false; } return true; } std::set<std::string> ClrHost::getTrustedAssemblies() { std::set<std::string> assemblies; const char * const tpaExtensions[] = { ".ni.dll", ".dll", ".ni.exe", ".exe", ".winmd" }; std::string runtimeDirectory = getAbsolutePath(RUNTIME_DIR_PATH); #ifndef _WIN32 auto directory = opendir(runtimeDirectory.c_str()); if (directory == nullptr) { std::cerr << "[.NET] Runtime directory not found" << std::endl; return assemblies; } struct dirent* entry; #endif for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; size_t extLength = strlen(ext); #ifdef _WIN32 std::string searchPath = runtimeDirectory; searchPath += "*"; searchPath += ext; WIN32_FIND_DATA findData; HANDLE fileHandle = FindFirstFile(searchPath.c_str(), &findData); if (fileHandle == INVALID_HANDLE_VALUE) { continue; } do { std::string filePath = runtimeDirectory; filePath += findData.cFileName; // Ensure assemblies are unique in the list if (assemblies.find(filePath) != assemblies.end()) { continue; } assemblies.insert(filePath); } while (FindNextFile(fileHandle, &findData)); FindClose(fileHandle); #else while ((entry = readdir(directory)) != nullptr) { switch (entry->d_type) { case DT_REG: break; // Handle symlinks and file systems that do not support d_type case DT_LNK: case DT_UNKNOWN: { std::string fullFilename; fullFilename.append(runtimeDirectory); fullFilename.append("/"); fullFilename.append(entry->d_name); struct stat sb; if (stat(fullFilename.c_str(), &sb) == -1) { continue; } if (!S_ISREG(sb.st_mode)) { continue; } } break; default: continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for int extPos = filename.length() - extLength; if (extPos <= 0 || filename.compare(extPos, extLength, ext) != 0) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Ensure assemblies are unique in the list if (assemblies.find(filenameWithoutExt) != assemblies.end()) { continue; } auto filePath = runtimeDirectory; filePath.append("/"); filePath.append(filename); assemblies.insert(filePath); } // rewind directory to search for next extension rewinddir(directory); #endif } #ifndef _WIN32 closedir(directory); #endif return assemblies; } bool ClrHost::getDelegate(std::string methodName, void **callback) { if (_runtimeHost == nullptr || _domainId == 0) { std::cerr << "[.NET] Core CLR host not loaded" << std::endl; return false; } int result = _createDelegate(_runtimeHost, _domainId, PLUGIN_NAME, PLUGIN_CLASS_NAME, methodName.c_str(), callback); if (result < 0) { std::cerr << "[.NET] Unable to get '" << methodName << "'" << std::endl; return false; } return true; } std::string ClrHost::getAbsolutePath(std::string relativePath) { #ifdef _WIN32 char absolutePath[MAX_PATH]; GetFullPathName(relativePath.c_str(), MAX_PATH, absolutePath, NULL); #else char absolutePath[PATH_MAX]; if (realpath(relativePath.c_str(), absolutePath) != nullptr) { strcat(absolutePath, "/"); } else { // no absolute path found absolutePath[0] = '\0'; } #endif return std::string(absolutePath); } std::string ClrHost::getFilenameWithoutExtension(std::string filename) { auto pos = filename.rfind("."); if (pos == std::string::npos) { return filename; } return filename.substr(0, pos); }
9,931
3,279
#include <rusql/rusql.hpp> #include "test.hpp" #include "database_test.hpp" #include <cstdlib> int main(int argc, char *argv[]) { auto db = get_database(argc, argv); test_init(4); test_start_try(4); try { db->execute("CREATE TABLE rusqltest (`id` INTEGER(10) PRIMARY KEY AUTO_INCREMENT, `value` INT(2) NOT NULL)"); auto statement = db->prepare("INSERT INTO rusqltest (`value`) VALUES (67)"); statement.execute(); uint64_t insert_id = statement.insert_id(); auto st2 = db->prepare("SELECT id FROM rusqltest WHERE value=67"); st2.execute(); uint64_t real_insert_id = 0xdeadbeef; st2.bind_results(real_insert_id); test(st2.fetch(), "one result"); test(real_insert_id != 0xdeadbeef, "real_insert_id was changed"); test(real_insert_id == insert_id, "last_insert_id() returned correctly"); test(!st2.fetch(), "one result only"); } catch(std::exception &e) { diag(e); } test_finish_try(); db->execute("DROP TABLE rusqltest"); return 0; }
969
387
#include "../Binding_pch.h" #include <glbinding/gl/functions.h> namespace gl { void glLabelObjectEXT(GLenum type, GLuint object, GLsizei length, const GLchar * label) { return glbinding::Binding::LabelObjectEXT(type, object, length, label); } void glLGPUCopyImageSubDataNVX(GLuint sourceGpu, GLbitfield destinationGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srxY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth) { return glbinding::Binding::LGPUCopyImageSubDataNVX(sourceGpu, destinationGpuMask, srcName, srcTarget, srcLevel, srcX, srxY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, width, height, depth); } void glLGPUInterlockNVX() { return glbinding::Binding::LGPUInterlockNVX(); } void glLGPUNamedBufferSubDataNVX(GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const void * data) { return glbinding::Binding::LGPUNamedBufferSubDataNVX(gpuMask, buffer, offset, size, data); } void glLightEnviSGIX(GLenum pname, GLint param) { return glbinding::Binding::LightEnviSGIX(pname, param); } void glLightf(GLenum light, GLenum pname, GLfloat param) { return glbinding::Binding::Lightf(light, pname, param); } void glLightfv(GLenum light, GLenum pname, const GLfloat * params) { return glbinding::Binding::Lightfv(light, pname, params); } void glLighti(GLenum light, GLenum pname, GLint param) { return glbinding::Binding::Lighti(light, pname, param); } void glLightiv(GLenum light, GLenum pname, const GLint * params) { return glbinding::Binding::Lightiv(light, pname, params); } void glLightModelf(GLenum pname, GLfloat param) { return glbinding::Binding::LightModelf(pname, param); } void glLightModelfv(GLenum pname, const GLfloat * params) { return glbinding::Binding::LightModelfv(pname, params); } void glLightModeli(GLenum pname, GLint param) { return glbinding::Binding::LightModeli(pname, param); } void glLightModeliv(GLenum pname, const GLint * params) { return glbinding::Binding::LightModeliv(pname, params); } void glLightModelxOES(GLenum pname, GLfixed param) { return glbinding::Binding::LightModelxOES(pname, param); } void glLightModelxvOES(GLenum pname, const GLfixed * param) { return glbinding::Binding::LightModelxvOES(pname, param); } void glLightxOES(GLenum light, GLenum pname, GLfixed param) { return glbinding::Binding::LightxOES(light, pname, param); } void glLightxvOES(GLenum light, GLenum pname, const GLfixed * params) { return glbinding::Binding::LightxvOES(light, pname, params); } void glLineStipple(GLint factor, GLushort pattern) { return glbinding::Binding::LineStipple(factor, pattern); } void glLineWidth(GLfloat width) { return glbinding::Binding::LineWidth(width); } void glLineWidthxOES(GLfixed width) { return glbinding::Binding::LineWidthxOES(width); } void glLinkProgram(GLuint program) { return glbinding::Binding::LinkProgram(program); } void glLinkProgramARB(GLhandleARB programObj) { return glbinding::Binding::LinkProgramARB(programObj); } void glListBase(GLuint base) { return glbinding::Binding::ListBase(base); } void glListDrawCommandsStatesClientNV(GLuint list, GLuint segment, const void ** indirects, const GLsizei * sizes, const GLuint * states, const GLuint * fbos, GLuint count) { return glbinding::Binding::ListDrawCommandsStatesClientNV(list, segment, indirects, sizes, states, fbos, count); } void glListParameterfSGIX(GLuint list, GLenum pname, GLfloat param) { return glbinding::Binding::ListParameterfSGIX(list, pname, param); } void glListParameterfvSGIX(GLuint list, GLenum pname, const GLfloat * params) { return glbinding::Binding::ListParameterfvSGIX(list, pname, params); } void glListParameteriSGIX(GLuint list, GLenum pname, GLint param) { return glbinding::Binding::ListParameteriSGIX(list, pname, param); } void glListParameterivSGIX(GLuint list, GLenum pname, const GLint * params) { return glbinding::Binding::ListParameterivSGIX(list, pname, params); } void glLoadIdentity() { return glbinding::Binding::LoadIdentity(); } void glLoadIdentityDeformationMapSGIX(FfdMaskSGIX mask) { return glbinding::Binding::LoadIdentityDeformationMapSGIX(mask); } void glLoadMatrixd(const GLdouble * m) { return glbinding::Binding::LoadMatrixd(m); } void glLoadMatrixf(const GLfloat * m) { return glbinding::Binding::LoadMatrixf(m); } void glLoadMatrixxOES(const GLfixed * m) { return glbinding::Binding::LoadMatrixxOES(m); } void glLoadName(GLuint name) { return glbinding::Binding::LoadName(name); } void glLoadProgramNV(GLenum target, GLuint id, GLsizei len, const GLubyte * program) { return glbinding::Binding::LoadProgramNV(target, id, len, program); } void glLoadTransposeMatrixd(const GLdouble * m) { return glbinding::Binding::LoadTransposeMatrixd(m); } void glLoadTransposeMatrixdARB(const GLdouble * m) { return glbinding::Binding::LoadTransposeMatrixdARB(m); } void glLoadTransposeMatrixf(const GLfloat * m) { return glbinding::Binding::LoadTransposeMatrixf(m); } void glLoadTransposeMatrixfARB(const GLfloat * m) { return glbinding::Binding::LoadTransposeMatrixfARB(m); } void glLoadTransposeMatrixxOES(const GLfixed * m) { return glbinding::Binding::LoadTransposeMatrixxOES(m); } void glLockArraysEXT(GLint first, GLsizei count) { return glbinding::Binding::LockArraysEXT(first, count); } void glLogicOp(GLenum opcode) { return glbinding::Binding::LogicOp(opcode); } } // namespace gl
5,633
1,932
// Copyright Carl Philipp Reh 2006 - 2019. // 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 <sge/opengl/call.hpp> #include <sge/opengl/check_state.hpp> #include <sge/opengl/common.hpp> #include <sge/opengl/clear/depth_buffer.hpp> #include <sge/renderer/exception.hpp> #include <sge/renderer/clear/depth_buffer_value.hpp> #include <fcppt/text.hpp> #include <fcppt/cast/size.hpp> void sge::opengl::clear::depth_buffer(sge::renderer::clear::depth_buffer_value const &_value) { sge::opengl::call(::glClearDepth, fcppt::cast::size<GLdouble>(_value)); SGE_OPENGL_CHECK_STATE(FCPPT_TEXT("glClearDepth failed"), sge::renderer::exception) }
776
307
#include "oscilloscope.h" #include <ImGui/implot.h> void OscilloscopeComponent::update(Synth const & synth) { memset(samples, 0, sizeof(samples)); for (auto const & [other, weight] : inputs[0].others) { for (int i = 0; i < BLOCK_SIZE; i++) { samples[i] += weight * other->get_sample(i).left; } } } void OscilloscopeComponent::render(Synth const & synth) { auto avail = ImGui::GetContentRegionAvail(); auto space = ImVec2(avail.x, std::max( ImGui::GetTextLineHeightWithSpacing(), avail.y - (inputs.size() + outputs.size()) * ImGui::GetTextLineHeightWithSpacing() )); ImPlot::SetNextPlotLimits(0.0, BLOCK_SIZE, -1.0, 1.0, ImGuiCond_Always); if (ImPlot::BeginPlot("Osciloscope", nullptr, nullptr, space, ImPlotFlags_CanvasOnly, ImPlotAxisFlags_NoDecorations)) { ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f); ImPlot::PlotShaded("", samples, BLOCK_SIZE); ImPlot::PlotLine ("", samples, BLOCK_SIZE); ImPlot::PopStyleVar(); ImPlot::EndPlot(); } }
989
400
/* -------------------------------------------------------------------------- * * OpenMMAmoeba * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2008-2018 Stanford University and the Authors. * * Authors: Peter Eastman, Mark Friedrichs * * Contributors: * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as published * * by the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * -------------------------------------------------------------------------- */ #ifdef WIN32 #define _USE_MATH_DEFINES // Needed to get M_PI #endif #include "AmoebaCudaKernels.h" #include "CudaAmoebaKernelSources.h" #include "openmm/internal/ContextImpl.h" #include "openmm/internal/AmoebaGeneralizedKirkwoodForceImpl.h" #include "openmm/internal/AmoebaMultipoleForceImpl.h" #include "openmm/internal/AmoebaWcaDispersionForceImpl.h" #include "openmm/internal/AmoebaTorsionTorsionForceImpl.h" #include "openmm/internal/AmoebaVdwForceImpl.h" #include "openmm/internal/NonbondedForceImpl.h" #include "CudaBondedUtilities.h" #include "CudaFFT3D.h" #include "CudaForceInfo.h" #include "CudaKernelSources.h" #include "jama_lu.h" #include <algorithm> #include <cmath> #ifdef _MSC_VER #include <windows.h> #endif using namespace OpenMM; using namespace std; #define CHECK_RESULT(result, prefix) \ if (result != CUDA_SUCCESS) { \ std::stringstream m; \ m<<prefix<<": "<<cu.getErrorString(result)<<" ("<<result<<")"<<" at "<<__FILE__<<":"<<__LINE__; \ throw OpenMMException(m.str());\ } /* -------------------------------------------------------------------------- * * AmoebaBondForce * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaBondForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaBondForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumBonds(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2; double length, k; force.getBondParameters(index, particle1, particle2, length, k); particles.resize(2); particles[0] = particle1; particles[1] = particle2; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2; double length1, length2, k1, k2; force.getBondParameters(group1, particle1, particle2, length1, k1); force.getBondParameters(group2, particle1, particle2, length2, k2); return (length1 == length2 && k1 == k2); } private: const AmoebaBondForce& force; }; CudaCalcAmoebaBondForceKernel::CudaCalcAmoebaBondForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaBondForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaBondForceKernel::initialize(const System& system, const AmoebaBondForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumBonds()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumBonds()/numContexts; numBonds = endIndex-startIndex; if (numBonds == 0) return; vector<vector<int> > atoms(numBonds, vector<int>(2)); params.initialize<float2>(cu, numBonds, "bondParams"); vector<float2> paramVector(numBonds); for (int i = 0; i < numBonds; i++) { double length, k; force.getBondParameters(startIndex+i, atoms[i][0], atoms[i][1], length, k); paramVector[i] = make_float2((float) length, (float) k); } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["COMPUTE_FORCE"] = CudaAmoebaKernelSources::amoebaBondForce; replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2"); replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalBondCubic()); replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalBondQuartic()); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaKernelSources::bondForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaBondForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaBondForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaBondForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumBonds()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumBonds()/numContexts; if (numBonds != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of bonds has changed"); if (numBonds == 0) return; // Record the per-bond parameters. vector<float2> paramVector(numBonds); for (int i = 0; i < numBonds; i++) { int atom1, atom2; double length, k; force.getBondParameters(startIndex+i, atom1, atom2, length, k); paramVector[i] = make_float2((float) length, (float) k); } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaAngleForce * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaAngleForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaAngleForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumAngles(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3; double angle, k; force.getAngleParameters(index, particle1, particle2, particle3, angle, k); particles.resize(3); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3; double angle1, angle2, k1, k2; force.getAngleParameters(group1, particle1, particle2, particle3, angle1, k1); force.getAngleParameters(group2, particle1, particle2, particle3, angle2, k2); return (angle1 == angle2 && k1 == k2); } private: const AmoebaAngleForce& force; }; CudaCalcAmoebaAngleForceKernel::CudaCalcAmoebaAngleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaAngleForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaAngleForceKernel::initialize(const System& system, const AmoebaAngleForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts; numAngles = endIndex-startIndex; if (numAngles == 0) return; vector<vector<int> > atoms(numAngles, vector<int>(3)); params.initialize<float2>(cu, numAngles, "angleParams"); vector<float2> paramVector(numAngles); for (int i = 0; i < numAngles; i++) { double angle, k; force.getAngleParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], angle, k); paramVector[i] = make_float2((float) angle, (float) k); } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["COMPUTE_FORCE"] = CudaAmoebaKernelSources::amoebaAngleForce; replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2"); replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleCubic()); replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleQuartic()); replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAnglePentic()); replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleSextic()); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaKernelSources::angleForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaAngleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaAngleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaAngleForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts; if (numAngles != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of angles has changed"); if (numAngles == 0) return; // Record the per-angle parameters. vector<float2> paramVector(numAngles); for (int i = 0; i < numAngles; i++) { int atom1, atom2, atom3; double angle, k; force.getAngleParameters(startIndex+i, atom1, atom2, atom3, angle, k); paramVector[i] = make_float2((float) angle, (float) k); } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaInPlaneAngleForce * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaInPlaneAngleForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaInPlaneAngleForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumAngles(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3, particle4; double angle, k; force.getAngleParameters(index, particle1, particle2, particle3, particle4, angle, k); particles.resize(4); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; particles[3] = particle4; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3, particle4; double angle1, angle2, k1, k2; force.getAngleParameters(group1, particle1, particle2, particle3, particle4, angle1, k1); force.getAngleParameters(group2, particle1, particle2, particle3, particle4, angle2, k2); return (angle1 == angle2 && k1 == k2); } private: const AmoebaInPlaneAngleForce& force; }; CudaCalcAmoebaInPlaneAngleForceKernel::CudaCalcAmoebaInPlaneAngleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaInPlaneAngleForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaInPlaneAngleForceKernel::initialize(const System& system, const AmoebaInPlaneAngleForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts; numAngles = endIndex-startIndex; if (numAngles == 0) return; vector<vector<int> > atoms(numAngles, vector<int>(4)); params.initialize<float2>(cu, numAngles, "angleParams"); vector<float2> paramVector(numAngles); for (int i = 0; i < numAngles; i++) { double angle, k; force.getAngleParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], angle, k); paramVector[i] = make_float2((float) angle, (float) k); } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2"); replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleCubic()); replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleQuartic()); replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAnglePentic()); replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleSextic()); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaInPlaneForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaInPlaneAngleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaInPlaneAngleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaInPlaneAngleForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts; if (numAngles != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of in-plane angles has changed"); if (numAngles == 0) return; // Record the per-angle parameters. vector<float2> paramVector(numAngles); for (int i = 0; i < numAngles; i++) { int atom1, atom2, atom3, atom4; double angle, k; force.getAngleParameters(startIndex+i, atom1, atom2, atom3, atom4, angle, k); paramVector[i] = make_float2((float) angle, (float) k); } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaPiTorsion * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaPiTorsionForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaPiTorsionForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumPiTorsions(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3, particle4, particle5, particle6; double k; force.getPiTorsionParameters(index, particle1, particle2, particle3, particle4, particle5, particle6, k); particles.resize(6); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; particles[3] = particle4; particles[4] = particle5; particles[5] = particle6; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3, particle4, particle5, particle6; double k1, k2; force.getPiTorsionParameters(group1, particle1, particle2, particle3, particle4, particle5, particle6, k1); force.getPiTorsionParameters(group2, particle1, particle2, particle3, particle4, particle5, particle6, k2); return (k1 == k2); } private: const AmoebaPiTorsionForce& force; }; CudaCalcAmoebaPiTorsionForceKernel::CudaCalcAmoebaPiTorsionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaPiTorsionForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaPiTorsionForceKernel::initialize(const System& system, const AmoebaPiTorsionForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumPiTorsions()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumPiTorsions()/numContexts; numPiTorsions = endIndex-startIndex; if (numPiTorsions == 0) return; vector<vector<int> > atoms(numPiTorsions, vector<int>(6)); params.initialize<float>(cu, numPiTorsions, "piTorsionParams"); vector<float> paramVector(numPiTorsions); for (int i = 0; i < numPiTorsions; i++) { double k; force.getPiTorsionParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], atoms[i][4], atoms[i][5], k); paramVector[i] = (float) k; } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float"); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaPiTorsionForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaPiTorsionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaPiTorsionForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaPiTorsionForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumPiTorsions()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumPiTorsions()/numContexts; if (numPiTorsions != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of torsions has changed"); if (numPiTorsions == 0) return; // Record the per-torsion parameters. vector<float> paramVector(numPiTorsions); for (int i = 0; i < numPiTorsions; i++) { int atom1, atom2, atom3, atom4, atom5, atom6; double k; force.getPiTorsionParameters(startIndex+i, atom1, atom2, atom3, atom4, atom5, atom6, k); paramVector[i] = (float) k; } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaStretchBend * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaStretchBendForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaStretchBendForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumStretchBends(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3; double lengthAB, lengthCB, angle, k1, k2; force.getStretchBendParameters(index, particle1, particle2, particle3, lengthAB, lengthCB, angle, k1, k2); particles.resize(3); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3; double lengthAB1, lengthAB2, lengthCB1, lengthCB2, angle1, angle2, k11, k12, k21, k22; force.getStretchBendParameters(group1, particle1, particle2, particle3, lengthAB1, lengthCB1, angle1, k11, k12); force.getStretchBendParameters(group2, particle1, particle2, particle3, lengthAB2, lengthCB2, angle2, k21, k22); return (lengthAB1 == lengthAB2 && lengthCB1 == lengthCB2 && angle1 == angle2 && k11 == k21 && k12 == k22); } private: const AmoebaStretchBendForce& force; }; CudaCalcAmoebaStretchBendForceKernel::CudaCalcAmoebaStretchBendForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaStretchBendForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaStretchBendForceKernel::initialize(const System& system, const AmoebaStretchBendForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumStretchBends()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumStretchBends()/numContexts; numStretchBends = endIndex-startIndex; if (numStretchBends == 0) return; vector<vector<int> > atoms(numStretchBends, vector<int>(3)); params1.initialize<float3>(cu, numStretchBends, "stretchBendParams"); params2.initialize<float2>(cu, numStretchBends, "stretchBendForceConstants"); vector<float3> paramVector(numStretchBends); vector<float2> paramVectorK(numStretchBends); for (int i = 0; i < numStretchBends; i++) { double lengthAB, lengthCB, angle, k1, k2; force.getStretchBendParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], lengthAB, lengthCB, angle, k1, k2); paramVector[i] = make_float3((float) lengthAB, (float) lengthCB, (float) angle); paramVectorK[i] = make_float2((float) k1, (float) k2); } params1.upload(paramVector); params2.upload(paramVectorK); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params1.getDevicePointer(), "float3"); replacements["FORCE_CONSTANTS"] = cu.getBondedUtilities().addArgument(params2.getDevicePointer(), "float2"); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaStretchBendForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaStretchBendForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaStretchBendForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaStretchBendForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumStretchBends()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumStretchBends()/numContexts; if (numStretchBends != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of bend-stretch terms has changed"); if (numStretchBends == 0) return; // Record the per-stretch-bend parameters. vector<float3> paramVector(numStretchBends); vector<float2> paramVector1(numStretchBends); for (int i = 0; i < numStretchBends; i++) { int atom1, atom2, atom3; double lengthAB, lengthCB, angle, k1, k2; force.getStretchBendParameters(startIndex+i, atom1, atom2, atom3, lengthAB, lengthCB, angle, k1, k2); paramVector[i] = make_float3((float) lengthAB, (float) lengthCB, (float) angle); paramVector1[i] = make_float2((float) k1, (float) k2); } params1.upload(paramVector); params2.upload(paramVector1); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaOutOfPlaneBend * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaOutOfPlaneBendForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaOutOfPlaneBendForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumOutOfPlaneBends(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3, particle4; double k; force.getOutOfPlaneBendParameters(index, particle1, particle2, particle3, particle4, k); particles.resize(4); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; particles[3] = particle4; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3, particle4; double k1, k2; force.getOutOfPlaneBendParameters(group1, particle1, particle2, particle3, particle4, k1); force.getOutOfPlaneBendParameters(group2, particle1, particle2, particle3, particle4, k2); return (k1 == k2); } private: const AmoebaOutOfPlaneBendForce& force; }; CudaCalcAmoebaOutOfPlaneBendForceKernel::CudaCalcAmoebaOutOfPlaneBendForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaOutOfPlaneBendForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaOutOfPlaneBendForceKernel::initialize(const System& system, const AmoebaOutOfPlaneBendForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumOutOfPlaneBends()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumOutOfPlaneBends()/numContexts; numOutOfPlaneBends = endIndex-startIndex; if (numOutOfPlaneBends == 0) return; vector<vector<int> > atoms(numOutOfPlaneBends, vector<int>(4)); params.initialize<float>(cu, numOutOfPlaneBends, "outOfPlaneParams"); vector<float> paramVector(numOutOfPlaneBends); for (int i = 0; i < numOutOfPlaneBends; i++) { double k; force.getOutOfPlaneBendParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], k); paramVector[i] = (float) k; } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float"); replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendCubic()); replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendQuartic()); replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendPentic()); replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendSextic()); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaOutOfPlaneBendForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaOutOfPlaneBendForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaOutOfPlaneBendForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaOutOfPlaneBendForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumOutOfPlaneBends()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumOutOfPlaneBends()/numContexts; if (numOutOfPlaneBends != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of out-of-plane bends has changed"); if (numOutOfPlaneBends == 0) return; // Record the per-bend parameters. vector<float> paramVector(numOutOfPlaneBends); for (int i = 0; i < numOutOfPlaneBends; i++) { int atom1, atom2, atom3, atom4; double k; force.getOutOfPlaneBendParameters(startIndex+i, atom1, atom2, atom3, atom4, k); paramVector[i] = (float) k; } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaTorsionTorsion * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaTorsionTorsionForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaTorsionTorsionForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumTorsionTorsions(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3, particle4, particle5, chiralCheckAtomIndex, gridIndex; force.getTorsionTorsionParameters(index, particle1, particle2, particle3, particle4, particle5, chiralCheckAtomIndex, gridIndex); particles.resize(5); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; particles[3] = particle4; particles[4] = particle5; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3, particle4, particle5; int chiral1, chiral2, grid1, grid2; force.getTorsionTorsionParameters(group1, particle1, particle2, particle3, particle4, particle5, chiral1, grid1); force.getTorsionTorsionParameters(group2, particle1, particle2, particle3, particle4, particle5, chiral2, grid2); return (grid1 == grid2); } private: const AmoebaTorsionTorsionForce& force; }; CudaCalcAmoebaTorsionTorsionForceKernel::CudaCalcAmoebaTorsionTorsionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaTorsionTorsionForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaTorsionTorsionForceKernel::initialize(const System& system, const AmoebaTorsionTorsionForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumTorsionTorsions()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumTorsionTorsions()/numContexts; numTorsionTorsions = endIndex-startIndex; if (numTorsionTorsions == 0) return; // Record torsion parameters. vector<vector<int> > atoms(numTorsionTorsions, vector<int>(5)); vector<int2> torsionParamsVec(numTorsionTorsions); torsionParams.initialize<int2>(cu, numTorsionTorsions, "torsionTorsionParams"); for (int i = 0; i < numTorsionTorsions; i++) force.getTorsionTorsionParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], atoms[i][4], torsionParamsVec[i].x, torsionParamsVec[i].y); torsionParams.upload(torsionParamsVec); // Record the grids. vector<float4> gridValuesVec; vector<float4> gridParamsVec; for (int i = 0; i < force.getNumTorsionTorsionGrids(); i++) { const TorsionTorsionGrid& initialGrid = force.getTorsionTorsionGrid(i); // check if grid needs to be reordered: x-angle should be 'slow' index bool reordered = false; TorsionTorsionGrid reorderedGrid; if (initialGrid[0][0][0] != initialGrid[0][1][0]) { AmoebaTorsionTorsionForceImpl::reorderGrid(initialGrid, reorderedGrid); reordered = true; } const TorsionTorsionGrid& grid = (reordered ? reorderedGrid : initialGrid); float range = grid[0][grid[0].size()-1][1] - grid[0][0][1]; gridParamsVec.push_back(make_float4(gridValuesVec.size(), grid[0][0][0], range/(grid.size()-1), grid.size())); for (int j = 0; j < grid.size(); j++) for (int k = 0; k < grid[j].size(); k++) gridValuesVec.push_back(make_float4((float) grid[j][k][2], (float) grid[j][k][3], (float) grid[j][k][4], (float) grid[j][k][5])); } gridValues.initialize<float4>(cu, gridValuesVec.size(), "torsionTorsionGridValues"); gridParams.initialize<float4>(cu, gridParamsVec.size(), "torsionTorsionGridParams"); gridValues.upload(gridValuesVec); gridParams.upload(gridParamsVec); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["GRID_VALUES"] = cu.getBondedUtilities().addArgument(gridValues.getDevicePointer(), "float4"); replacements["GRID_PARAMS"] = cu.getBondedUtilities().addArgument(gridParams.getDevicePointer(), "float4"); replacements["TORSION_PARAMS"] = cu.getBondedUtilities().addArgument(torsionParams.getDevicePointer(), "int2"); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaTorsionTorsionForce, replacements), force.getForceGroup()); cu.getBondedUtilities().addPrefixCode(CudaAmoebaKernelSources::bicubic); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaTorsionTorsionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } /* -------------------------------------------------------------------------- * * AmoebaMultipole * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaMultipoleForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaMultipoleForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double charge1, charge2, thole1, thole2, damping1, damping2, polarity1, polarity2; int axis1, axis2, multipole11, multipole12, multipole21, multipole22, multipole31, multipole32; vector<double> dipole1, dipole2, quadrupole1, quadrupole2; force.getMultipoleParameters(particle1, charge1, dipole1, quadrupole1, axis1, multipole11, multipole21, multipole31, thole1, damping1, polarity1); force.getMultipoleParameters(particle2, charge2, dipole2, quadrupole2, axis2, multipole12, multipole22, multipole32, thole2, damping2, polarity2); if (charge1 != charge2 || thole1 != thole2 || damping1 != damping2 || polarity1 != polarity2 || axis1 != axis2) { return false; } for (int i = 0; i < (int) dipole1.size(); ++i) { if (dipole1[i] != dipole2[i]) { return false; } } for (int i = 0; i < (int) quadrupole1.size(); ++i) { if (quadrupole1[i] != quadrupole2[i]) { return false; } } return true; } int getNumParticleGroups() { return 7*force.getNumMultipoles(); } void getParticlesInGroup(int index, vector<int>& particles) { int particle = index/7; int type = index-7*particle; force.getCovalentMap(particle, AmoebaMultipoleForce::CovalentType(type), particles); } bool areGroupsIdentical(int group1, int group2) { return ((group1%7) == (group2%7)); } private: const AmoebaMultipoleForce& force; }; CudaCalcAmoebaMultipoleForceKernel::CudaCalcAmoebaMultipoleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaMultipoleForceKernel(name, platform), cu(cu), system(system), hasInitializedScaleFactors(false), hasInitializedFFT(false), multipolesAreValid(false), hasCreatedEvent(false), gkKernel(NULL) { } CudaCalcAmoebaMultipoleForceKernel::~CudaCalcAmoebaMultipoleForceKernel() { cu.setAsCurrent(); if (hasInitializedFFT) cufftDestroy(fft); if (hasCreatedEvent) cuEventDestroy(syncEvent); } void CudaCalcAmoebaMultipoleForceKernel::initialize(const System& system, const AmoebaMultipoleForce& force) { cu.setAsCurrent(); // Initialize multipole parameters. numMultipoles = force.getNumMultipoles(); CudaArray& posq = cu.getPosq(); vector<double4> temp(posq.getSize()); float4* posqf = (float4*) &temp[0]; double4* posqd = (double4*) &temp[0]; vector<float2> dampingAndTholeVec; vector<float> polarizabilityVec; vector<float> molecularDipolesVec; vector<float> molecularQuadrupolesVec; vector<int4> multipoleParticlesVec; for (int i = 0; i < numMultipoles; i++) { double charge, thole, damping, polarity; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; force.getMultipoleParameters(i, charge, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity); if (cu.getUseDoublePrecision()) posqd[i] = make_double4(0, 0, 0, charge); else posqf[i] = make_float4(0, 0, 0, (float) charge); dampingAndTholeVec.push_back(make_float2((float) damping, (float) thole)); polarizabilityVec.push_back((float) polarity); multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType)); for (int j = 0; j < 3; j++) molecularDipolesVec.push_back((float) dipole[j]); molecularQuadrupolesVec.push_back((float) quadrupole[0]); molecularQuadrupolesVec.push_back((float) quadrupole[1]); molecularQuadrupolesVec.push_back((float) quadrupole[2]); molecularQuadrupolesVec.push_back((float) quadrupole[4]); molecularQuadrupolesVec.push_back((float) quadrupole[5]); } hasQuadrupoles = false; for (auto q : molecularQuadrupolesVec) if (q != 0.0) hasQuadrupoles = true; int paddedNumAtoms = cu.getPaddedNumAtoms(); for (int i = numMultipoles; i < paddedNumAtoms; i++) { dampingAndTholeVec.push_back(make_float2(0, 0)); polarizabilityVec.push_back(0); multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0)); for (int j = 0; j < 3; j++) molecularDipolesVec.push_back(0); for (int j = 0; j < 5; j++) molecularQuadrupolesVec.push_back(0); } dampingAndThole.initialize<float2>(cu, paddedNumAtoms, "dampingAndThole"); polarizability.initialize<float>(cu, paddedNumAtoms, "polarizability"); multipoleParticles.initialize<int4>(cu, paddedNumAtoms, "multipoleParticles"); molecularDipoles.initialize<float>(cu, 3*paddedNumAtoms, "molecularDipoles"); molecularQuadrupoles.initialize<float>(cu, 5*paddedNumAtoms, "molecularQuadrupoles"); lastPositions.initialize(cu, cu.getPosq().getSize(), cu.getPosq().getElementSize(), "lastPositions"); dampingAndThole.upload(dampingAndTholeVec); polarizability.upload(polarizabilityVec); multipoleParticles.upload(multipoleParticlesVec); molecularDipoles.upload(molecularDipolesVec); molecularQuadrupoles.upload(molecularQuadrupolesVec); posq.upload(&temp[0]); // Create workspace arrays. polarizationType = force.getPolarizationType(); int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); labFrameDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "labFrameDipoles"); labFrameQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "labFrameQuadrupoles"); sphericalDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "sphericalDipoles"); sphericalQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "sphericalQuadrupoles"); fracDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "fracDipoles"); fracQuadrupoles.initialize(cu, 6*paddedNumAtoms, elementSize, "fracQuadrupoles"); field.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "field"); fieldPolar.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "fieldPolar"); torque.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "torque"); inducedDipole.initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipole"); inducedDipolePolar.initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipolePolar"); if (polarizationType == AmoebaMultipoleForce::Mutual) { inducedDipoleErrors.initialize(cu, cu.getNumThreadBlocks(), sizeof(float2), "inducedDipoleErrors"); prevDipoles.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipoles"); prevDipolesPolar.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesPolar"); prevErrors.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevErrors"); diisMatrix.initialize(cu, MaxPrevDIISDipoles*MaxPrevDIISDipoles, elementSize, "diisMatrix"); diisCoefficients.initialize(cu, MaxPrevDIISDipoles+1, sizeof(float), "diisMatrix"); CHECK_RESULT(cuEventCreate(&syncEvent, CU_EVENT_DISABLE_TIMING), "Error creating event for AmoebaMultipoleForce"); hasCreatedEvent = true; } else if (polarizationType == AmoebaMultipoleForce::Extrapolated) { int numOrders = force.getExtrapolationCoefficients().size(); extrapolatedDipole.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipole"); extrapolatedDipolePolar.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipolePolar"); inducedDipoleFieldGradient.initialize(cu, 6*paddedNumAtoms, sizeof(long long), "inducedDipoleFieldGradient"); inducedDipoleFieldGradientPolar.initialize(cu, 6*paddedNumAtoms, sizeof(long long), "inducedDipoleFieldGradientPolar"); extrapolatedDipoleFieldGradient.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradient"); extrapolatedDipoleFieldGradientPolar.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientPolar"); } cu.addAutoclearBuffer(field); cu.addAutoclearBuffer(fieldPolar); cu.addAutoclearBuffer(torque); // Record which atoms should be flagged as exclusions based on covalent groups, and determine // the values for the covalent group flags. vector<vector<int> > exclusions(numMultipoles); for (int i = 0; i < numMultipoles; i++) { vector<int> atoms; set<int> allAtoms; allAtoms.insert(i); force.getCovalentMap(i, AmoebaMultipoleForce::Covalent12, atoms); allAtoms.insert(atoms.begin(), atoms.end()); force.getCovalentMap(i, AmoebaMultipoleForce::Covalent13, atoms); allAtoms.insert(atoms.begin(), atoms.end()); for (int atom : allAtoms) covalentFlagValues.push_back(make_int3(i, atom, 0)); force.getCovalentMap(i, AmoebaMultipoleForce::Covalent14, atoms); allAtoms.insert(atoms.begin(), atoms.end()); for (int atom : atoms) covalentFlagValues.push_back(make_int3(i, atom, 1)); force.getCovalentMap(i, AmoebaMultipoleForce::Covalent15, atoms); for (int atom : atoms) covalentFlagValues.push_back(make_int3(i, atom, 2)); allAtoms.insert(atoms.begin(), atoms.end()); force.getCovalentMap(i, AmoebaMultipoleForce::PolarizationCovalent11, atoms); allAtoms.insert(atoms.begin(), atoms.end()); exclusions[i].insert(exclusions[i].end(), allAtoms.begin(), allAtoms.end()); // Workaround for bug in TINKER: if an atom is listed in both the PolarizationCovalent11 // and PolarizationCovalent12 maps, the latter takes precedence. vector<int> atoms12; force.getCovalentMap(i, AmoebaMultipoleForce::PolarizationCovalent12, atoms12); for (int atom : atoms) if (find(atoms12.begin(), atoms12.end(), atom) == atoms12.end()) polarizationFlagValues.push_back(make_int2(i, atom)); } set<pair<int, int> > tilesWithExclusions; for (int atom1 = 0; atom1 < (int) exclusions.size(); ++atom1) { int x = atom1/CudaContext::TileSize; for (int atom2 : exclusions[atom1]) { int y = atom2/CudaContext::TileSize; tilesWithExclusions.insert(make_pair(max(x, y), min(x, y))); } } // Record other options. if (polarizationType == AmoebaMultipoleForce::Mutual) { maxInducedIterations = force.getMutualInducedMaxIterations(); inducedEpsilon = force.getMutualInducedTargetEpsilon(); } else maxInducedIterations = 0; if (polarizationType != AmoebaMultipoleForce::Direct) { inducedField.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedField"); inducedFieldPolar.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedFieldPolar"); } usePME = (force.getNonbondedMethod() == AmoebaMultipoleForce::PME); // See whether there's an AmoebaGeneralizedKirkwoodForce in the System. const AmoebaGeneralizedKirkwoodForce* gk = NULL; for (int i = 0; i < system.getNumForces() && gk == NULL; i++) gk = dynamic_cast<const AmoebaGeneralizedKirkwoodForce*>(&system.getForce(i)); double innerDielectric = (gk == NULL ? 1.0 : gk->getSoluteDielectric()); // Create the kernels. bool useShuffle = (cu.getComputeCapability() >= 3.0 && !cu.getUseDoublePrecision()); double fixedThreadMemory = 19*elementSize+2*sizeof(float)+3*sizeof(int)/(double) cu.TileSize; double inducedThreadMemory = 15*elementSize+2*sizeof(float); if (polarizationType == AmoebaMultipoleForce::Extrapolated) inducedThreadMemory += 12*elementSize; double electrostaticsThreadMemory = 0; if (!useShuffle) fixedThreadMemory += 3*elementSize; map<string, string> defines; defines["NUM_ATOMS"] = cu.intToString(numMultipoles); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456/innerDielectric); if (polarizationType == AmoebaMultipoleForce::Direct) defines["DIRECT_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Mutual) defines["MUTUAL_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Extrapolated) defines["EXTRAPOLATED_POLARIZATION"] = ""; if (useShuffle) defines["USE_SHUFFLE"] = ""; if (hasQuadrupoles) defines["INCLUDE_QUADRUPOLES"] = ""; defines["TILE_SIZE"] = cu.intToString(CudaContext::TileSize); int numExclusionTiles = tilesWithExclusions.size(); defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(numExclusionTiles); int numContexts = cu.getPlatformData().contexts.size(); int startExclusionIndex = cu.getContextIndex()*numExclusionTiles/numContexts; int endExclusionIndex = (cu.getContextIndex()+1)*numExclusionTiles/numContexts; defines["FIRST_EXCLUSION_TILE"] = cu.intToString(startExclusionIndex); defines["LAST_EXCLUSION_TILE"] = cu.intToString(endExclusionIndex); maxExtrapolationOrder = force.getExtrapolationCoefficients().size(); defines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder); stringstream coefficients; for (int i = 0; i < maxExtrapolationOrder; i++) { if (i > 0) coefficients << ","; double sum = 0; for (int j = i; j < maxExtrapolationOrder; j++) sum += force.getExtrapolationCoefficients()[j]; coefficients << cu.doubleToString(sum); } defines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str(); if (usePME) { int nx, ny, nz; force.getPMEParameters(alpha, nx, ny, nz); if (nx == 0 || alpha == 0.0) { NonbondedForce nb; nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance()); nb.setCutoffDistance(force.getCutoffDistance()); NonbondedForceImpl::calcPMEParameters(system, nb, alpha, gridSizeX, gridSizeY, gridSizeZ, false); gridSizeX = CudaFFT3D::findLegalDimension(gridSizeX); gridSizeY = CudaFFT3D::findLegalDimension(gridSizeY); gridSizeZ = CudaFFT3D::findLegalDimension(gridSizeZ); } else { gridSizeX = CudaFFT3D::findLegalDimension(nx); gridSizeY = CudaFFT3D::findLegalDimension(ny); gridSizeZ = CudaFFT3D::findLegalDimension(nz); } defines["EWALD_ALPHA"] = cu.doubleToString(alpha); defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); defines["USE_EWALD"] = ""; defines["USE_CUTOFF"] = ""; defines["USE_PERIODIC"] = ""; defines["CUTOFF_SQUARED"] = cu.doubleToString(force.getCutoffDistance()*force.getCutoffDistance()); } if (gk != NULL) { defines["USE_GK"] = ""; defines["GK_C"] = cu.doubleToString(2.455); double solventDielectric = gk->getSolventDielectric(); defines["GK_FC"] = cu.doubleToString(1*(1-solventDielectric)/(0+1*solventDielectric)); defines["GK_FD"] = cu.doubleToString(2*(1-solventDielectric)/(1+2*solventDielectric)); defines["GK_FQ"] = cu.doubleToString(3*(1-solventDielectric)/(2+3*solventDielectric)); fixedThreadMemory += 4*elementSize; inducedThreadMemory += 13*elementSize; if (polarizationType == AmoebaMultipoleForce::Mutual) { prevDipolesGk.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesGk"); prevDipolesGkPolar.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesGkPolar"); } else if (polarizationType == AmoebaMultipoleForce::Extrapolated) { inducedThreadMemory += 12*elementSize; int numOrders = force.getExtrapolationCoefficients().size(); extrapolatedDipoleGk.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipoleGk"); extrapolatedDipoleGkPolar.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipoleGkPolar"); inducedDipoleFieldGradientGk.initialize(cu, 6*numMultipoles, elementSize, "inducedDipoleFieldGradientGk"); inducedDipoleFieldGradientGkPolar.initialize(cu, 6*numMultipoles, elementSize, "inducedDipoleFieldGradientGkPolar"); extrapolatedDipoleFieldGradientGk.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientGk"); extrapolatedDipoleFieldGradientGkPolar.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientGkPolar"); } } int maxThreads = cu.getNonbondedUtilities().getForceThreadBlockSize(); fixedFieldThreads = min(maxThreads, cu.computeThreadBlockSize(fixedThreadMemory)); inducedFieldThreads = min(maxThreads, cu.computeThreadBlockSize(inducedThreadMemory)); CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoles, defines); computeMomentsKernel = cu.getKernel(module, "computeLabFrameMoments"); recordInducedDipolesKernel = cu.getKernel(module, "recordInducedDipoles"); mapTorqueKernel = cu.getKernel(module, "mapTorqueToForce"); computePotentialKernel = cu.getKernel(module, "computePotentialAtPoints"); defines["THREAD_BLOCK_SIZE"] = cu.intToString(fixedFieldThreads); module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleFixedField, defines); computeFixedFieldKernel = cu.getKernel(module, "computeFixedField"); if (polarizationType != AmoebaMultipoleForce::Direct) { defines["THREAD_BLOCK_SIZE"] = cu.intToString(inducedFieldThreads); defines["MAX_PREV_DIIS_DIPOLES"] = cu.intToString(MaxPrevDIISDipoles); module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleInducedField, defines); computeInducedFieldKernel = cu.getKernel(module, "computeInducedField"); updateInducedFieldKernel = cu.getKernel(module, "updateInducedFieldByDIIS"); recordDIISDipolesKernel = cu.getKernel(module, "recordInducedDipolesForDIIS"); buildMatrixKernel = cu.getKernel(module, "computeDIISMatrix"); solveMatrixKernel = cu.getKernel(module, "solveDIISMatrix"); initExtrapolatedKernel = cu.getKernel(module, "initExtrapolatedDipoles"); iterateExtrapolatedKernel = cu.getKernel(module, "iterateExtrapolatedDipoles"); computeExtrapolatedKernel = cu.getKernel(module, "computeExtrapolatedDipoles"); addExtrapolatedGradientKernel = cu.getKernel(module, "addExtrapolatedFieldGradientToForce"); } stringstream electrostaticsSource; electrostaticsSource << CudaKernelSources::vectorOps; electrostaticsSource << CudaAmoebaKernelSources::sphericalMultipoles; if (usePME) electrostaticsSource << CudaAmoebaKernelSources::pmeMultipoleElectrostatics; else electrostaticsSource << CudaAmoebaKernelSources::multipoleElectrostatics; electrostaticsThreadMemory = 24*elementSize+3*sizeof(float)+3*sizeof(int)/(double) cu.TileSize; electrostaticsThreads = min(maxThreads, cu.computeThreadBlockSize(electrostaticsThreadMemory)); defines["THREAD_BLOCK_SIZE"] = cu.intToString(electrostaticsThreads); module = cu.createModule(electrostaticsSource.str(), defines); electrostaticsKernel = cu.getKernel(module, "computeElectrostatics"); // Set up PME. if (usePME) { // Create the PME kernels. map<string, string> pmeDefines; pmeDefines["EWALD_ALPHA"] = cu.doubleToString(alpha); pmeDefines["PME_ORDER"] = cu.intToString(PmeOrder); pmeDefines["NUM_ATOMS"] = cu.intToString(numMultipoles); pmeDefines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); pmeDefines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456); pmeDefines["GRID_SIZE_X"] = cu.intToString(gridSizeX); pmeDefines["GRID_SIZE_Y"] = cu.intToString(gridSizeY); pmeDefines["GRID_SIZE_Z"] = cu.intToString(gridSizeZ); pmeDefines["M_PI"] = cu.doubleToString(M_PI); pmeDefines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); if (polarizationType == AmoebaMultipoleForce::Direct) pmeDefines["DIRECT_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Mutual) pmeDefines["MUTUAL_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Extrapolated) pmeDefines["EXTRAPOLATED_POLARIZATION"] = ""; CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipolePme, pmeDefines); pmeTransformMultipolesKernel = cu.getKernel(module, "transformMultipolesToFractionalCoordinates"); pmeTransformPotentialKernel = cu.getKernel(module, "transformPotentialToCartesianCoordinates"); pmeSpreadFixedMultipolesKernel = cu.getKernel(module, "gridSpreadFixedMultipoles"); pmeSpreadInducedDipolesKernel = cu.getKernel(module, "gridSpreadInducedDipoles"); pmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge"); pmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution"); pmeFixedPotentialKernel = cu.getKernel(module, "computeFixedPotentialFromGrid"); pmeInducedPotentialKernel = cu.getKernel(module, "computeInducedPotentialFromGrid"); pmeFixedForceKernel = cu.getKernel(module, "computeFixedMultipoleForceAndEnergy"); pmeInducedForceKernel = cu.getKernel(module, "computeInducedDipoleForceAndEnergy"); pmeRecordInducedFieldDipolesKernel = cu.getKernel(module, "recordInducedFieldDipoles"); cuFuncSetCacheConfig(pmeSpreadFixedMultipolesKernel, CU_FUNC_CACHE_PREFER_L1); cuFuncSetCacheConfig(pmeSpreadInducedDipolesKernel, CU_FUNC_CACHE_PREFER_L1); cuFuncSetCacheConfig(pmeFixedPotentialKernel, CU_FUNC_CACHE_PREFER_L1); cuFuncSetCacheConfig(pmeInducedPotentialKernel, CU_FUNC_CACHE_PREFER_L1); // Create required data structures. int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); pmeGrid.initialize(cu, gridSizeX*gridSizeY*gridSizeZ, 2*elementSize, "pmeGrid"); cu.addAutoclearBuffer(pmeGrid); pmeBsplineModuliX.initialize(cu, gridSizeX, elementSize, "pmeBsplineModuliX"); pmeBsplineModuliY.initialize(cu, gridSizeY, elementSize, "pmeBsplineModuliY"); pmeBsplineModuliZ.initialize(cu, gridSizeZ, elementSize, "pmeBsplineModuliZ"); pmePhi.initialize(cu, 20*numMultipoles, elementSize, "pmePhi"); pmePhid.initialize(cu, 10*numMultipoles, elementSize, "pmePhid"); pmePhip.initialize(cu, 10*numMultipoles, elementSize, "pmePhip"); pmePhidp.initialize(cu, 20*numMultipoles, elementSize, "pmePhidp"); pmeCphi.initialize(cu, 10*numMultipoles, elementSize, "pmeCphi"); cufftResult result = cufftPlan3d(&fft, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2Z : CUFFT_C2C); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); hasInitializedFFT = true; // Initialize the b-spline moduli. double data[PmeOrder]; double x = 0.0; data[0] = 1.0 - x; data[1] = x; for (int i = 2; i < PmeOrder; i++) { double denom = 1.0/i; data[i] = x*data[i-1]*denom; for (int j = 1; j < i; j++) data[i-j] = ((x+j)*data[i-j-1] + ((i-j+1)-x)*data[i-j])*denom; data[0] = (1.0-x)*data[0]*denom; } int maxSize = max(max(gridSizeX, gridSizeY), gridSizeZ); vector<double> bsplines_data(maxSize+1, 0.0); for (int i = 2; i <= PmeOrder+1; i++) bsplines_data[i] = data[i-2]; for (int dim = 0; dim < 3; dim++) { int ndata = (dim == 0 ? gridSizeX : dim == 1 ? gridSizeY : gridSizeZ); vector<double> moduli(ndata); // get the modulus of the discrete Fourier transform double factor = 2.0*M_PI/ndata; for (int i = 0; i < ndata; i++) { double sc = 0.0; double ss = 0.0; for (int j = 1; j <= ndata; j++) { double arg = factor*i*(j-1); sc += bsplines_data[j]*cos(arg); ss += bsplines_data[j]*sin(arg); } moduli[i] = sc*sc+ss*ss; } // Fix for exponential Euler spline interpolation failure. double eps = 1.0e-7; if (moduli[0] < eps) moduli[0] = 0.9*moduli[1]; for (int i = 1; i < ndata-1; i++) if (moduli[i] < eps) moduli[i] = 0.9*(moduli[i-1]+moduli[i+1]); if (moduli[ndata-1] < eps) moduli[ndata-1] = 0.9*moduli[ndata-2]; // Compute and apply the optimal zeta coefficient. int jcut = 50; for (int i = 1; i <= ndata; i++) { int k = i - 1; if (i > ndata/2) k = k - ndata; double zeta; if (k == 0) zeta = 1.0; else { double sum1 = 1.0; double sum2 = 1.0; factor = M_PI*k/ndata; for (int j = 1; j <= jcut; j++) { double arg = factor/(factor+M_PI*j); sum1 += pow(arg, PmeOrder); sum2 += pow(arg, 2*PmeOrder); } for (int j = 1; j <= jcut; j++) { double arg = factor/(factor-M_PI*j); sum1 += pow(arg, PmeOrder); sum2 += pow(arg, 2*PmeOrder); } zeta = sum2/sum1; } moduli[i-1] = moduli[i-1]*zeta*zeta; } if (cu.getUseDoublePrecision()) { if (dim == 0) pmeBsplineModuliX.upload(moduli); else if (dim == 1) pmeBsplineModuliY.upload(moduli); else pmeBsplineModuliZ.upload(moduli); } else { vector<float> modulif(ndata); for (int i = 0; i < ndata; i++) modulif[i] = (float) moduli[i]; if (dim == 0) pmeBsplineModuliX.upload(modulif); else if (dim == 1) pmeBsplineModuliY.upload(modulif); else pmeBsplineModuliZ.upload(modulif); } } } // Add an interaction to the default nonbonded kernel. This doesn't actually do any calculations. It's // just so that CudaNonbondedUtilities will build the exclusion flags and maintain the neighbor list. cu.getNonbondedUtilities().addInteraction(usePME, usePME, true, force.getCutoffDistance(), exclusions, "", force.getForceGroup()); cu.getNonbondedUtilities().setUsePadding(false); cu.addForce(new ForceInfo(force)); } void CudaCalcAmoebaMultipoleForceKernel::initializeScaleFactors() { hasInitializedScaleFactors = true; CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); // Figure out the covalent flag values to use for each atom pair. vector<ushort2> exclusionTiles; nb.getExclusionTiles().download(exclusionTiles); map<pair<int, int>, int> exclusionTileMap; for (int i = 0; i < (int) exclusionTiles.size(); i++) { ushort2 tile = exclusionTiles[i]; exclusionTileMap[make_pair(tile.x, tile.y)] = i; } covalentFlags.initialize<uint2>(cu, nb.getExclusions().getSize(), "covalentFlags"); vector<uint2> covalentFlagsVec(nb.getExclusions().getSize(), make_uint2(0, 0)); for (int3 values : covalentFlagValues) { int atom1 = values.x; int atom2 = values.y; int value = values.z; int x = atom1/CudaContext::TileSize; int offset1 = atom1-x*CudaContext::TileSize; int y = atom2/CudaContext::TileSize; int offset2 = atom2-y*CudaContext::TileSize; int f1 = (value == 0 || value == 1 ? 1 : 0); int f2 = (value == 0 || value == 2 ? 1 : 0); if (x == y) { int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize; covalentFlagsVec[index+offset1].x |= f1<<offset2; covalentFlagsVec[index+offset1].y |= f2<<offset2; covalentFlagsVec[index+offset2].x |= f1<<offset1; covalentFlagsVec[index+offset2].y |= f2<<offset1; } else if (x > y) { int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize; covalentFlagsVec[index+offset1].x |= f1<<offset2; covalentFlagsVec[index+offset1].y |= f2<<offset2; } else { int index = exclusionTileMap[make_pair(y, x)]*CudaContext::TileSize; covalentFlagsVec[index+offset2].x |= f1<<offset1; covalentFlagsVec[index+offset2].y |= f2<<offset1; } } covalentFlags.upload(covalentFlagsVec); // Do the same for the polarization flags. polarizationGroupFlags.initialize<unsigned int>(cu, nb.getExclusions().getSize(), "polarizationGroupFlags"); vector<unsigned int> polarizationGroupFlagsVec(nb.getExclusions().getSize(), 0); for (int2 values : polarizationFlagValues) { int atom1 = values.x; int atom2 = values.y; int x = atom1/CudaContext::TileSize; int offset1 = atom1-x*CudaContext::TileSize; int y = atom2/CudaContext::TileSize; int offset2 = atom2-y*CudaContext::TileSize; if (x == y) { int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize; polarizationGroupFlagsVec[index+offset1] |= 1<<offset2; polarizationGroupFlagsVec[index+offset2] |= 1<<offset1; } else if (x > y) { int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize; polarizationGroupFlagsVec[index+offset1] |= 1<<offset2; } else { int index = exclusionTileMap[make_pair(y, x)]*CudaContext::TileSize; polarizationGroupFlagsVec[index+offset2] |= 1<<offset1; } } polarizationGroupFlags.upload(polarizationGroupFlagsVec); } double CudaCalcAmoebaMultipoleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { if (!hasInitializedScaleFactors) { initializeScaleFactors(); for (auto impl : context.getForceImpls()) { AmoebaGeneralizedKirkwoodForceImpl* gkImpl = dynamic_cast<AmoebaGeneralizedKirkwoodForceImpl*>(impl); if (gkImpl != NULL) { gkKernel = dynamic_cast<CudaCalcAmoebaGeneralizedKirkwoodForceKernel*>(&gkImpl->getKernel().getImpl()); break; } } } CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); // Compute the lab frame moments. void* computeMomentsArgs[] = {&cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer(), &molecularDipoles.getDevicePointer(), &molecularQuadrupoles.getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer()}; cu.executeKernel(computeMomentsKernel, computeMomentsArgs, cu.getNumAtoms()); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); if (!pmeGrid.isInitialized()) { // Compute induced dipoles. if (gkKernel == NULL) { void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads); void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms()); } else { gkKernel->computeBornRadii(); void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &gkKernel->getBornRadii().getDevicePointer(), &gkKernel->getField().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads); void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &gkKernel->getField().getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms()); } // Iterate until the dipoles converge. if (polarizationType == AmoebaMultipoleForce::Extrapolated) computeExtrapolatedDipoles(NULL); for (int i = 0; i < maxInducedIterations; i++) { computeInducedField(NULL); bool converged = iterateDipolesByDIIS(i); if (converged) break; } // Compute electrostatic force. void* electrostaticsArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(electrostaticsKernel, electrostaticsArgs, numForceThreadBlocks*electrostaticsThreads, electrostaticsThreads); if (gkKernel != NULL) gkKernel->finishComputation(torque, labFrameDipoles, labFrameQuadrupoles, inducedDipole, inducedDipolePolar, dampingAndThole, covalentFlags, polarizationGroupFlags); } else { // Compute reciprocal box vectors. Vec3 boxVectors[3]; cu.getPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]); double determinant = boxVectors[0][0]*boxVectors[1][1]*boxVectors[2][2]; double scale = 1.0/determinant; double3 recipBoxVectors[3]; recipBoxVectors[0] = make_double3(boxVectors[1][1]*boxVectors[2][2]*scale, 0, 0); recipBoxVectors[1] = make_double3(-boxVectors[1][0]*boxVectors[2][2]*scale, boxVectors[0][0]*boxVectors[2][2]*scale, 0); recipBoxVectors[2] = make_double3((boxVectors[1][0]*boxVectors[2][1]-boxVectors[1][1]*boxVectors[2][0])*scale, -boxVectors[0][0]*boxVectors[2][1]*scale, boxVectors[0][0]*boxVectors[1][1]*scale); float3 recipBoxVectorsFloat[3]; void* recipBoxVectorPointer[3]; if (cu.getUseDoublePrecision()) { recipBoxVectorPointer[0] = &recipBoxVectors[0]; recipBoxVectorPointer[1] = &recipBoxVectors[1]; recipBoxVectorPointer[2] = &recipBoxVectors[2]; } else { recipBoxVectorsFloat[0] = make_float3((float) recipBoxVectors[0].x, 0, 0); recipBoxVectorsFloat[1] = make_float3((float) recipBoxVectors[1].x, (float) recipBoxVectors[1].y, 0); recipBoxVectorsFloat[2] = make_float3((float) recipBoxVectors[2].x, (float) recipBoxVectors[2].y, (float) recipBoxVectors[2].z); recipBoxVectorPointer[0] = &recipBoxVectorsFloat[0]; recipBoxVectorPointer[1] = &recipBoxVectorsFloat[1]; recipBoxVectorPointer[2] = &recipBoxVectorsFloat[2]; } // Reciprocal space calculation. unsigned int maxTiles = nb.getInteractingTiles().getSize(); void* pmeTransformMultipolesArgs[] = {&labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformMultipolesKernel, pmeTransformMultipolesArgs, cu.getNumAtoms()); void* pmeSpreadFixedMultipolesArgs[] = {&cu.getPosq().getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadFixedMultipolesKernel, pmeSpreadFixedMultipolesArgs, cu.getNumAtoms()); void* finishSpreadArgs[] = {&pmeGrid.getDevicePointer()}; if (cu.getUseDoublePrecision()) { cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize()); cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); } else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); void* pmeConvolutionArgs[] = {&pmeGrid.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(), &pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); void* pmeFixedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhi.getDevicePointer(), &field.getDevicePointer(), &fieldPolar .getDevicePointer(), &cu.getPosq().getDevicePointer(), &labFrameDipoles.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeFixedPotentialKernel, pmeFixedPotentialArgs, cu.getNumAtoms()); void* pmeTransformFixedPotentialArgs[] = {&pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformPotentialKernel, pmeTransformFixedPotentialArgs, cu.getNumAtoms()); void* pmeFixedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeFixedForceKernel, pmeFixedForceArgs, cu.getNumAtoms()); // Direct space calculation. void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &nb.getInteractingTiles().getDevicePointer(), &nb.getInteractionCount().getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), &maxTiles, &nb.getBlockCenters().getDevicePointer(), &nb.getInteractingAtoms().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads); void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms()); // Reciprocal space calculation for the induced dipoles. cu.clearBuffer(pmeGrid); void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms()); if (cu.getUseDoublePrecision()) { cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize()); cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); } else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); void* pmeInducedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms()); // Iterate until the dipoles converge. if (polarizationType == AmoebaMultipoleForce::Extrapolated) computeExtrapolatedDipoles(recipBoxVectorPointer); for (int i = 0; i < maxInducedIterations; i++) { computeInducedField(recipBoxVectorPointer); bool converged = iterateDipolesByDIIS(i); if (converged) break; } // Compute electrostatic force. void* electrostaticsArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &nb.getInteractingTiles().getDevicePointer(), &nb.getInteractionCount().getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), &maxTiles, &nb.getBlockCenters().getDevicePointer(), &nb.getInteractingAtoms().getDevicePointer(), &sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(electrostaticsKernel, electrostaticsArgs, numForceThreadBlocks*electrostaticsThreads, electrostaticsThreads); void* pmeTransformInducedPotentialArgs[] = {&pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformPotentialKernel, pmeTransformInducedPotentialArgs, cu.getNumAtoms()); void* pmeInducedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &pmePhi.getDevicePointer(), &pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedForceKernel, pmeInducedForceArgs, cu.getNumAtoms()); } // If using extrapolated polarization, add in force contributions from µ(m) T µ(n). if (polarizationType == AmoebaMultipoleForce::Extrapolated) { if (gkKernel == NULL) { void* extrapolatedArgs[] = {&cu.getForce().getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer()}; cu.executeKernel(addExtrapolatedGradientKernel, extrapolatedArgs, numMultipoles); } else { void* extrapolatedArgs[] = {&cu.getForce().getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer(), &extrapolatedDipoleFieldGradientGk.getDevicePointer(), &extrapolatedDipoleFieldGradientGkPolar.getDevicePointer()}; cu.executeKernel(addExtrapolatedGradientKernel, extrapolatedArgs, numMultipoles); } } // Map torques to force. void* mapTorqueArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer()}; cu.executeKernel(mapTorqueKernel, mapTorqueArgs, cu.getNumAtoms()); // Record the current atom positions so we can tell later if they have changed. cu.getPosq().copyTo(lastPositions); multipolesAreValid = true; return 0.0; } void CudaCalcAmoebaMultipoleForceKernel::computeInducedField(void** recipBoxVectorPointer) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); unsigned int maxTiles = 0; vector<void*> computeInducedFieldArgs; computeInducedFieldArgs.push_back(&inducedField.getDevicePointer()); computeInducedFieldArgs.push_back(&inducedFieldPolar.getDevicePointer()); computeInducedFieldArgs.push_back(&cu.getPosq().getDevicePointer()); computeInducedFieldArgs.push_back(&nb.getExclusionTiles().getDevicePointer()); computeInducedFieldArgs.push_back(&inducedDipole.getDevicePointer()); computeInducedFieldArgs.push_back(&inducedDipolePolar.getDevicePointer()); computeInducedFieldArgs.push_back(&startTileIndex); computeInducedFieldArgs.push_back(&numTileIndices); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { computeInducedFieldArgs.push_back(&inducedDipoleFieldGradient.getDevicePointer()); computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientPolar.getDevicePointer()); } if (pmeGrid.isInitialized()) { computeInducedFieldArgs.push_back(&nb.getInteractingTiles().getDevicePointer()); computeInducedFieldArgs.push_back(&nb.getInteractionCount().getDevicePointer()); computeInducedFieldArgs.push_back(cu.getPeriodicBoxSizePointer()); computeInducedFieldArgs.push_back(cu.getInvPeriodicBoxSizePointer()); computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecXPointer()); computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecYPointer()); computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecZPointer()); computeInducedFieldArgs.push_back(&maxTiles); computeInducedFieldArgs.push_back(&nb.getBlockCenters().getDevicePointer()); computeInducedFieldArgs.push_back(&nb.getInteractingAtoms().getDevicePointer()); } if (gkKernel != NULL) { computeInducedFieldArgs.push_back(&gkKernel->getInducedField().getDevicePointer()); computeInducedFieldArgs.push_back(&gkKernel->getInducedFieldPolar().getDevicePointer()); computeInducedFieldArgs.push_back(&gkKernel->getInducedDipoles().getDevicePointer()); computeInducedFieldArgs.push_back(&gkKernel->getInducedDipolesPolar().getDevicePointer()); computeInducedFieldArgs.push_back(&gkKernel->getBornRadii().getDevicePointer()); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientGk.getDevicePointer()); computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientGkPolar.getDevicePointer()); } } computeInducedFieldArgs.push_back(&dampingAndThole.getDevicePointer()); cu.clearBuffer(inducedField); cu.clearBuffer(inducedFieldPolar); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { cu.clearBuffer(inducedDipoleFieldGradient); cu.clearBuffer(inducedDipoleFieldGradientPolar); } if (gkKernel != NULL) { cu.clearBuffer(gkKernel->getInducedField()); cu.clearBuffer(gkKernel->getInducedFieldPolar()); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { cu.clearBuffer(inducedDipoleFieldGradientGk); cu.clearBuffer(inducedDipoleFieldGradientGkPolar); } } if (!pmeGrid.isInitialized()) cu.executeKernel(computeInducedFieldKernel, &computeInducedFieldArgs[0], numForceThreadBlocks*inducedFieldThreads, inducedFieldThreads); else { maxTiles = nb.getInteractingTiles().getSize(); cu.executeKernel(computeInducedFieldKernel, &computeInducedFieldArgs[0], numForceThreadBlocks*inducedFieldThreads, inducedFieldThreads); cu.clearBuffer(pmeGrid); void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms()); if (cu.getUseDoublePrecision()) { void* finishSpreadArgs[] = {&pmeGrid.getDevicePointer()}; cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize()); cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); } else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); void* pmeConvolutionArgs[] = {&pmeGrid.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(), &pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); void* pmeInducedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms()); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &inducedField.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms()); } else { void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &inducedField.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms()); } } } bool CudaCalcAmoebaMultipoleForceKernel::iterateDipolesByDIIS(int iteration) { void* npt = NULL; bool trueValue = true, falseValue = false; int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); // Record the dipoles and errors into the lists of previous dipoles. if (gkKernel != NULL) { void* recordDIISDipolesGkArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &gkKernel->getField().getDevicePointer(), &gkKernel->getInducedField().getDevicePointer(), &gkKernel->getInducedFieldPolar().getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &polarizability.getDevicePointer(), &inducedDipoleErrors.getDevicePointer(), &prevDipolesGk.getDevicePointer(), &prevDipolesGkPolar.getDevicePointer(), &prevErrors.getDevicePointer(), &iteration, &falseValue, &diisMatrix.getDevicePointer()}; cu.executeKernel(recordDIISDipolesKernel, recordDIISDipolesGkArgs, cu.getNumThreadBlocks()*cu.ThreadBlockSize, cu.ThreadBlockSize, cu.ThreadBlockSize*elementSize*2); } void* recordDIISDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &npt, &inducedField.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer(), &inducedDipoleErrors.getDevicePointer(), &prevDipoles.getDevicePointer(), &prevDipolesPolar.getDevicePointer(), &prevErrors.getDevicePointer(), &iteration, &trueValue, &diisMatrix.getDevicePointer()}; cu.executeKernel(recordDIISDipolesKernel, recordDIISDipolesArgs, cu.getNumThreadBlocks()*cu.ThreadBlockSize, cu.ThreadBlockSize, cu.ThreadBlockSize*elementSize*2); float2* errors = (float2*) cu.getPinnedBuffer(); inducedDipoleErrors.download(errors, false); cuEventRecord(syncEvent, cu.getCurrentStream()); // Build the DIIS matrix. int numPrev = (iteration+1 < MaxPrevDIISDipoles ? iteration+1 : MaxPrevDIISDipoles); void* buildMatrixArgs[] = {&prevErrors.getDevicePointer(), &iteration, &diisMatrix.getDevicePointer()}; int threadBlocks = min(numPrev, cu.getNumThreadBlocks()); int blockSize = 512; cu.executeKernel(buildMatrixKernel, buildMatrixArgs, threadBlocks*blockSize, blockSize, blockSize*elementSize); // Solve the matrix. void* solveMatrixArgs[] = {&iteration, &diisMatrix.getDevicePointer(), &diisCoefficients.getDevicePointer()}; cu.executeKernel(solveMatrixKernel, solveMatrixArgs, 32, 32); // Determine whether the iteration has converged. cuEventSynchronize(syncEvent); double total1 = 0.0, total2 = 0.0; for (int j = 0; j < inducedDipoleErrors.getSize(); j++) { total1 += errors[j].x; total2 += errors[j].y; } if (48.033324*sqrt(max(total1, total2)/cu.getNumAtoms()) < inducedEpsilon) return true; // Compute the dipoles. void* updateInducedFieldArgs[] = {&inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &prevDipoles.getDevicePointer(), &prevDipolesPolar.getDevicePointer(), &diisCoefficients.getDevicePointer(), &numPrev}; cu.executeKernel(updateInducedFieldKernel, updateInducedFieldArgs, 3*cu.getNumAtoms(), 256); if (gkKernel != NULL) { void* updateInducedFieldGkArgs[] = {&gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &prevDipolesGk.getDevicePointer(), &prevDipolesGkPolar.getDevicePointer(), &diisCoefficients.getDevicePointer(), &numPrev}; cu.executeKernel(updateInducedFieldKernel, updateInducedFieldGkArgs, 3*cu.getNumAtoms(), 256); } return false; } void CudaCalcAmoebaMultipoleForceKernel::computeExtrapolatedDipoles(void** recipBoxVectorPointer) { // Start by storing the direct dipoles as PT0 if (gkKernel == NULL) { void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer()}; cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize()); } else { void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer(), &inducedDipoleFieldGradientGk.getDevicePointer(), &inducedDipoleFieldGradientGkPolar.getDevicePointer()}; cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize()); } // Recursively apply alpha.Tau to the µ_(n) components to generate µ_(n+1), and store the result for (int order = 1; order < maxExtrapolationOrder; ++order) { computeInducedField(recipBoxVectorPointer); if (gkKernel == NULL) { void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize()); } else { void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer(), &inducedDipoleFieldGradientGk.getDevicePointer(), &inducedDipoleFieldGradientGkPolar.getDevicePointer(), &gkKernel->getInducedField().getDevicePointer(), &gkKernel->getInducedFieldPolar().getDevicePointer(), &extrapolatedDipoleFieldGradientGk.getDevicePointer(), &extrapolatedDipoleFieldGradientGkPolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize()); } } // Take a linear combination of the µ_(n) components to form the total dipole if (gkKernel == NULL) { void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer()}; cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize()); } else { void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer()}; cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize()); } computeInducedField(recipBoxVectorPointer); } void CudaCalcAmoebaMultipoleForceKernel::ensureMultipolesValid(ContextImpl& context) { if (multipolesAreValid) { int numParticles = cu.getNumAtoms(); if (cu.getUseDoublePrecision()) { vector<double4> pos1, pos2; cu.getPosq().download(pos1); lastPositions.download(pos2); for (int i = 0; i < numParticles; i++) if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) { multipolesAreValid = false; break; } } else { vector<float4> pos1, pos2; cu.getPosq().download(pos1); lastPositions.download(pos2); for (int i = 0; i < numParticles; i++) if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) { multipolesAreValid = false; break; } } } if (!multipolesAreValid) context.calcForcesAndEnergy(false, false, -1); } void CudaCalcAmoebaMultipoleForceKernel::getLabFramePermanentDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double> labDipoleVec; labFrameDipoles.download(labDipoleVec); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(labDipoleVec[3*i], labDipoleVec[3*i+1], labDipoleVec[3*i+2]); } else { vector<float> labDipoleVec; labFrameDipoles.download(labDipoleVec); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(labDipoleVec[3*i], labDipoleVec[3*i+1], labDipoleVec[3*i+2]); } } void CudaCalcAmoebaMultipoleForceKernel::getInducedDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double> d; inducedDipole.download(d); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(d[3*i], d[3*i+1], d[3*i+2]); } else { vector<float> d; inducedDipole.download(d); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(d[3*i], d[3*i+1], d[3*i+2]); } } void CudaCalcAmoebaMultipoleForceKernel::getTotalDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double4> posqVec; vector<double> labDipoleVec; vector<double> inducedDipoleVec; double totalDipoleVecX; double totalDipoleVecY; double totalDipoleVecZ; inducedDipole.download(inducedDipoleVec); labFrameDipoles.download(labDipoleVec); cu.getPosq().download(posqVec); for (int i = 0; i < numParticles; i++) { totalDipoleVecX = labDipoleVec[3*i] + inducedDipoleVec[3*i]; totalDipoleVecY = labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1]; totalDipoleVecZ = labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2]; dipoles[order[i]] = Vec3(totalDipoleVecX, totalDipoleVecY, totalDipoleVecZ); } } else { vector<float4> posqVec; vector<float> labDipoleVec; vector<float> inducedDipoleVec; float totalDipoleVecX; float totalDipoleVecY; float totalDipoleVecZ; inducedDipole.download(inducedDipoleVec); labFrameDipoles.download(labDipoleVec); cu.getPosq().download(posqVec); for (int i = 0; i < numParticles; i++) { totalDipoleVecX = labDipoleVec[3*i] + inducedDipoleVec[3*i]; totalDipoleVecY = labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1]; totalDipoleVecZ = labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2]; dipoles[order[i]] = Vec3(totalDipoleVecX, totalDipoleVecY, totalDipoleVecZ); } } } void CudaCalcAmoebaMultipoleForceKernel::getElectrostaticPotential(ContextImpl& context, const vector<Vec3>& inputGrid, vector<double>& outputElectrostaticPotential) { ensureMultipolesValid(context); int numPoints = inputGrid.size(); int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); CudaArray points(cu, numPoints, 4*elementSize, "points"); CudaArray potential(cu, numPoints, elementSize, "potential"); // Copy the grid points to the GPU. if (cu.getUseDoublePrecision()) { vector<double4> p(numPoints); for (int i = 0; i < numPoints; i++) p[i] = make_double4(inputGrid[i][0], inputGrid[i][1], inputGrid[i][2], 0); points.upload(p); } else { vector<float4> p(numPoints); for (int i = 0; i < numPoints; i++) p[i] = make_float4((float) inputGrid[i][0], (float) inputGrid[i][1], (float) inputGrid[i][2], 0); points.upload(p); } // Compute the potential. void* computePotentialArgs[] = {&cu.getPosq().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &points.getDevicePointer(), &potential.getDevicePointer(), &numPoints, cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer()}; int blockSize = 128; cu.executeKernel(computePotentialKernel, computePotentialArgs, numPoints, blockSize, blockSize*15*elementSize); outputElectrostaticPotential.resize(numPoints); if (cu.getUseDoublePrecision()) potential.download(outputElectrostaticPotential); else { vector<float> p(numPoints); potential.download(p); for (int i = 0; i < numPoints; i++) outputElectrostaticPotential[i] = p[i]; } } template <class T, class T4, class M4> void CudaCalcAmoebaMultipoleForceKernel::computeSystemMultipoleMoments(ContextImpl& context, vector<double>& outputMultipoleMoments) { // Compute the local coordinates relative to the center of mass. int numAtoms = cu.getNumAtoms(); vector<T4> posq; vector<M4> velm; cu.getPosq().download(posq); cu.getVelm().download(velm); double totalMass = 0.0; Vec3 centerOfMass(0, 0, 0); for (int i = 0; i < numAtoms; i++) { double mass = (velm[i].w > 0 ? 1.0/velm[i].w : 0.0); totalMass += mass; centerOfMass[0] += mass*posq[i].x; centerOfMass[1] += mass*posq[i].y; centerOfMass[2] += mass*posq[i].z; } if (totalMass > 0.0) { centerOfMass[0] /= totalMass; centerOfMass[1] /= totalMass; centerOfMass[2] /= totalMass; } vector<double4> posqLocal(numAtoms); for (int i = 0; i < numAtoms; i++) { posqLocal[i].x = posq[i].x - centerOfMass[0]; posqLocal[i].y = posq[i].y - centerOfMass[1]; posqLocal[i].z = posq[i].z - centerOfMass[2]; posqLocal[i].w = posq[i].w; } // Compute the multipole moments. double totalCharge = 0.0; double xdpl = 0.0; double ydpl = 0.0; double zdpl = 0.0; double xxqdp = 0.0; double xyqdp = 0.0; double xzqdp = 0.0; double yxqdp = 0.0; double yyqdp = 0.0; double yzqdp = 0.0; double zxqdp = 0.0; double zyqdp = 0.0; double zzqdp = 0.0; vector<T> labDipoleVec, inducedDipoleVec, quadrupoleVec; labFrameDipoles.download(labDipoleVec); inducedDipole.download(inducedDipoleVec); labFrameQuadrupoles.download(quadrupoleVec); for (int i = 0; i < numAtoms; i++) { totalCharge += posqLocal[i].w; double netDipoleX = (labDipoleVec[3*i] + inducedDipoleVec[3*i]); double netDipoleY = (labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1]); double netDipoleZ = (labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2]); xdpl += posqLocal[i].x*posqLocal[i].w + netDipoleX; ydpl += posqLocal[i].y*posqLocal[i].w + netDipoleY; zdpl += posqLocal[i].z*posqLocal[i].w + netDipoleZ; xxqdp += posqLocal[i].x*posqLocal[i].x*posqLocal[i].w + 2*posqLocal[i].x*netDipoleX; xyqdp += posqLocal[i].x*posqLocal[i].y*posqLocal[i].w + posqLocal[i].x*netDipoleY + posqLocal[i].y*netDipoleX; xzqdp += posqLocal[i].x*posqLocal[i].z*posqLocal[i].w + posqLocal[i].x*netDipoleZ + posqLocal[i].z*netDipoleX; yxqdp += posqLocal[i].y*posqLocal[i].x*posqLocal[i].w + posqLocal[i].y*netDipoleX + posqLocal[i].x*netDipoleY; yyqdp += posqLocal[i].y*posqLocal[i].y*posqLocal[i].w + 2*posqLocal[i].y*netDipoleY; yzqdp += posqLocal[i].y*posqLocal[i].z*posqLocal[i].w + posqLocal[i].y*netDipoleZ + posqLocal[i].z*netDipoleY; zxqdp += posqLocal[i].z*posqLocal[i].x*posqLocal[i].w + posqLocal[i].z*netDipoleX + posqLocal[i].x*netDipoleZ; zyqdp += posqLocal[i].z*posqLocal[i].y*posqLocal[i].w + posqLocal[i].z*netDipoleY + posqLocal[i].y*netDipoleZ; zzqdp += posqLocal[i].z*posqLocal[i].z*posqLocal[i].w + 2*posqLocal[i].z*netDipoleZ; } // Convert the quadrupole from traced to traceless form. double qave = (xxqdp + yyqdp + zzqdp)/3; xxqdp = 1.5*(xxqdp-qave); xyqdp = 1.5*xyqdp; xzqdp = 1.5*xzqdp; yxqdp = 1.5*yxqdp; yyqdp = 1.5*(yyqdp-qave); yzqdp = 1.5*yzqdp; zxqdp = 1.5*zxqdp; zyqdp = 1.5*zyqdp; zzqdp = 1.5*(zzqdp-qave); // Add the traceless atomic quadrupoles to the total quadrupole moment. for (int i = 0; i < numAtoms; i++) { xxqdp = xxqdp + 3*quadrupoleVec[5*i]; xyqdp = xyqdp + 3*quadrupoleVec[5*i+1]; xzqdp = xzqdp + 3*quadrupoleVec[5*i+2]; yxqdp = yxqdp + 3*quadrupoleVec[5*i+1]; yyqdp = yyqdp + 3*quadrupoleVec[5*i+3]; yzqdp = yzqdp + 3*quadrupoleVec[5*i+4]; zxqdp = zxqdp + 3*quadrupoleVec[5*i+2]; zyqdp = zyqdp + 3*quadrupoleVec[5*i+4]; zzqdp = zzqdp + -3*(quadrupoleVec[5*i]+quadrupoleVec[5*i+3]); } double debye = 4.80321; outputMultipoleMoments.resize(13); outputMultipoleMoments[0] = totalCharge; outputMultipoleMoments[1] = 10.0*xdpl*debye; outputMultipoleMoments[2] = 10.0*ydpl*debye; outputMultipoleMoments[3] = 10.0*zdpl*debye; outputMultipoleMoments[4] = 100.0*xxqdp*debye; outputMultipoleMoments[5] = 100.0*xyqdp*debye; outputMultipoleMoments[6] = 100.0*xzqdp*debye; outputMultipoleMoments[7] = 100.0*yxqdp*debye; outputMultipoleMoments[8] = 100.0*yyqdp*debye; outputMultipoleMoments[9] = 100.0*yzqdp*debye; outputMultipoleMoments[10] = 100.0*zxqdp*debye; outputMultipoleMoments[11] = 100.0*zyqdp*debye; outputMultipoleMoments[12] = 100.0*zzqdp*debye; } void CudaCalcAmoebaMultipoleForceKernel::getSystemMultipoleMoments(ContextImpl& context, vector<double>& outputMultipoleMoments) { ensureMultipolesValid(context); if (cu.getUseDoublePrecision()) computeSystemMultipoleMoments<double, double4, double4>(context, outputMultipoleMoments); else if (cu.getUseMixedPrecision()) computeSystemMultipoleMoments<float, float4, double4>(context, outputMultipoleMoments); else computeSystemMultipoleMoments<float, float4, float4>(context, outputMultipoleMoments); } void CudaCalcAmoebaMultipoleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaMultipoleForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumMultipoles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of multipoles has changed"); // Record the per-multipole parameters. cu.getPosq().download(cu.getPinnedBuffer()); float4* posqf = (float4*) cu.getPinnedBuffer(); double4* posqd = (double4*) cu.getPinnedBuffer(); vector<float2> dampingAndTholeVec; vector<float> polarizabilityVec; vector<float> molecularDipolesVec; vector<float> molecularQuadrupolesVec; vector<int4> multipoleParticlesVec; for (int i = 0; i < force.getNumMultipoles(); i++) { double charge, thole, damping, polarity; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; force.getMultipoleParameters(i, charge, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity); if (cu.getUseDoublePrecision()) posqd[i].w = charge; else posqf[i].w = (float) charge; dampingAndTholeVec.push_back(make_float2((float) damping, (float) thole)); polarizabilityVec.push_back((float) polarity); multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType)); for (int j = 0; j < 3; j++) molecularDipolesVec.push_back((float) dipole[j]); molecularQuadrupolesVec.push_back((float) quadrupole[0]); molecularQuadrupolesVec.push_back((float) quadrupole[1]); molecularQuadrupolesVec.push_back((float) quadrupole[2]); molecularQuadrupolesVec.push_back((float) quadrupole[4]); molecularQuadrupolesVec.push_back((float) quadrupole[5]); } if (!hasQuadrupoles) { for (auto q : molecularQuadrupolesVec) if (q != 0.0) throw OpenMMException("updateParametersInContext: Cannot set a non-zero quadrupole moment, because quadrupoles were excluded from the kernel"); } for (int i = force.getNumMultipoles(); i < cu.getPaddedNumAtoms(); i++) { dampingAndTholeVec.push_back(make_float2(0, 0)); polarizabilityVec.push_back(0); multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0)); for (int j = 0; j < 3; j++) molecularDipolesVec.push_back(0); for (int j = 0; j < 5; j++) molecularQuadrupolesVec.push_back(0); } dampingAndThole.upload(dampingAndTholeVec); polarizability.upload(polarizabilityVec); multipoleParticles.upload(multipoleParticlesVec); molecularDipoles.upload(molecularDipolesVec); molecularQuadrupoles.upload(molecularQuadrupolesVec); cu.getPosq().upload(cu.getPinnedBuffer()); cu.invalidateMolecules(); multipolesAreValid = false; } void CudaCalcAmoebaMultipoleForceKernel::getPMEParameters(double& alpha, int& nx, int& ny, int& nz) const { if (!usePME) throw OpenMMException("getPMEParametersInContext: This Context is not using PME"); alpha = this->alpha; nx = gridSizeX; ny = gridSizeY; nz = gridSizeZ; } /* -------------------------------------------------------------------------- * * AmoebaGeneralizedKirkwood * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaGeneralizedKirkwoodForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaGeneralizedKirkwoodForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double charge1, charge2, radius1, radius2, scale1, scale2; force.getParticleParameters(particle1, charge1, radius1, scale1); force.getParticleParameters(particle2, charge2, radius2, scale2); return (charge1 == charge2 && radius1 == radius2 && scale1 == scale2); } private: const AmoebaGeneralizedKirkwoodForce& force; }; CudaCalcAmoebaGeneralizedKirkwoodForceKernel::CudaCalcAmoebaGeneralizedKirkwoodForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaGeneralizedKirkwoodForceKernel(name, platform), cu(cu), system(system), hasInitializedKernels(false) { } void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::initialize(const System& system, const AmoebaGeneralizedKirkwoodForce& force) { cu.setAsCurrent(); if (cu.getPlatformData().contexts.size() > 1) throw OpenMMException("AmoebaGeneralizedKirkwoodForce does not support using multiple CUDA devices"); const AmoebaMultipoleForce* multipoles = NULL; for (int i = 0; i < system.getNumForces() && multipoles == NULL; i++) multipoles = dynamic_cast<const AmoebaMultipoleForce*>(&system.getForce(i)); if (multipoles == NULL) throw OpenMMException("AmoebaGeneralizedKirkwoodForce requires the System to also contain an AmoebaMultipoleForce"); CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int paddedNumAtoms = cu.getPaddedNumAtoms(); int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); params.initialize<float2>(cu, paddedNumAtoms, "amoebaGkParams"); bornRadii .initialize(cu, paddedNumAtoms, elementSize, "bornRadii"); field .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkField"); bornSum.initialize<long long>(cu, paddedNumAtoms, "bornSum"); bornForce.initialize<long long>(cu, paddedNumAtoms, "bornForce"); inducedDipoleS .initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipoleS"); inducedDipolePolarS .initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipolePolarS"); polarizationType = multipoles->getPolarizationType(); if (polarizationType != AmoebaMultipoleForce::Direct) { inducedField .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkInducedField"); inducedFieldPolar .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkInducedFieldPolar"); } cu.addAutoclearBuffer(field); cu.addAutoclearBuffer(bornSum); cu.addAutoclearBuffer(bornForce); vector<float2> paramsVector(paddedNumAtoms); for (int i = 0; i < force.getNumParticles(); i++) { double charge, radius, scalingFactor; force.getParticleParameters(i, charge, radius, scalingFactor); paramsVector[i] = make_float2((float) radius, (float) (scalingFactor*radius)); // Make sure the charge matches the one specified by the AmoebaMultipoleForce. double charge2, thole, damping, polarity; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; multipoles->getMultipoleParameters(i, charge2, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity); if (charge != charge2) throw OpenMMException("AmoebaGeneralizedKirkwoodForce and AmoebaMultipoleForce must specify the same charge for every atom"); } params.upload(paramsVector); // Select the number of threads for each kernel. double computeBornSumThreadMemory = 4*elementSize+3*sizeof(float); double gkForceThreadMemory = 24*elementSize; double chainRuleThreadMemory = 10*elementSize; double ediffThreadMemory = 28*elementSize+2*sizeof(float)+3*sizeof(int)/(double) cu.TileSize; int maxThreads = cu.getNonbondedUtilities().getForceThreadBlockSize(); computeBornSumThreads = min(maxThreads, cu.computeThreadBlockSize(computeBornSumThreadMemory)); gkForceThreads = min(maxThreads, cu.computeThreadBlockSize(gkForceThreadMemory)); chainRuleThreads = min(maxThreads, cu.computeThreadBlockSize(chainRuleThreadMemory)); ediffThreads = min(maxThreads, cu.computeThreadBlockSize(ediffThreadMemory)); // Set preprocessor macros we will use when we create the kernels. defines["NUM_ATOMS"] = cu.intToString(cu.getNumAtoms()); defines["PADDED_NUM_ATOMS"] = cu.intToString(paddedNumAtoms); defines["BORN_SUM_THREAD_BLOCK_SIZE"] = cu.intToString(computeBornSumThreads); defines["GK_FORCE_THREAD_BLOCK_SIZE"] = cu.intToString(gkForceThreads); defines["CHAIN_RULE_THREAD_BLOCK_SIZE"] = cu.intToString(chainRuleThreads); defines["EDIFF_THREAD_BLOCK_SIZE"] = cu.intToString(ediffThreads); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["GK_C"] = cu.doubleToString(2.455); double solventDielectric = force.getSolventDielectric(); defines["GK_FC"] = cu.doubleToString(1*(1-solventDielectric)/(0+1*solventDielectric)); defines["GK_FD"] = cu.doubleToString(2*(1-solventDielectric)/(1+2*solventDielectric)); defines["GK_FQ"] = cu.doubleToString(3*(1-solventDielectric)/(2+3*solventDielectric)); defines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456); defines["M_PI"] = cu.doubleToString(M_PI); defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456/force.getSoluteDielectric()); if (polarizationType == AmoebaMultipoleForce::Direct) defines["DIRECT_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Mutual) defines["MUTUAL_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Extrapolated) defines["EXTRAPOLATED_POLARIZATION"] = ""; includeSurfaceArea = force.getIncludeCavityTerm(); if (includeSurfaceArea) { defines["SURFACE_AREA_FACTOR"] = cu.doubleToString(force.getSurfaceAreaFactor()); defines["PROBE_RADIUS"] = cu.doubleToString(force.getProbeRadius()); defines["DIELECTRIC_OFFSET"] = cu.doubleToString(0.009); } cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaGeneralizedKirkwoodForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { // Since GK is so tightly entwined with the electrostatics, this method does nothing, and the force calculation // is driven by AmoebaMultipoleForce. return 0.0; } void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::computeBornRadii() { if (!hasInitializedKernels) { hasInitializedKernels = true; // Create the kernels. int numExclusionTiles = cu.getNonbondedUtilities().getExclusionTiles().getSize(); defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(numExclusionTiles); int numContexts = cu.getPlatformData().contexts.size(); int startExclusionIndex = cu.getContextIndex()*numExclusionTiles/numContexts; int endExclusionIndex = (cu.getContextIndex()+1)*numExclusionTiles/numContexts; defines["FIRST_EXCLUSION_TILE"] = cu.intToString(startExclusionIndex); defines["LAST_EXCLUSION_TILE"] = cu.intToString(endExclusionIndex); stringstream forceSource; forceSource << CudaKernelSources::vectorOps; forceSource << CudaAmoebaKernelSources::amoebaGk; forceSource << "#define F1\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; forceSource << CudaAmoebaKernelSources::gkEDiffPairForce; forceSource << "#undef F1\n"; forceSource << "#define F2\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; forceSource << "#undef F2\n"; forceSource << "#define T1\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; forceSource << CudaAmoebaKernelSources::gkEDiffPairForce; forceSource << "#undef T1\n"; forceSource << "#define T2\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; forceSource << "#undef T2\n"; forceSource << "#define T3\n"; forceSource << CudaAmoebaKernelSources::gkEDiffPairForce; forceSource << "#undef T3\n"; forceSource << "#define B1\n"; forceSource << "#define B2\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; CUmodule module = cu.createModule(forceSource.str(), defines); computeBornSumKernel = cu.getKernel(module, "computeBornSum"); reduceBornSumKernel = cu.getKernel(module, "reduceBornSum"); gkForceKernel = cu.getKernel(module, "computeGKForces"); chainRuleKernel = cu.getKernel(module, "computeChainRuleForce"); ediffKernel = cu.getKernel(module, "computeEDiffForce"); if (includeSurfaceArea) surfaceAreaKernel = cu.getKernel(module, "computeSurfaceAreaForce"); } CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int numTiles = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); void* computeBornSumArgs[] = {&bornSum.getDevicePointer(), &cu.getPosq().getDevicePointer(), &params.getDevicePointer(), &numTiles}; cu.executeKernel(computeBornSumKernel, computeBornSumArgs, numForceThreadBlocks*computeBornSumThreads, computeBornSumThreads); void* reduceBornSumArgs[] = {&bornSum.getDevicePointer(), &params.getDevicePointer(), &bornRadii.getDevicePointer()}; cu.executeKernel(reduceBornSumKernel, reduceBornSumArgs, cu.getNumAtoms()); } void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::finishComputation(CudaArray& torque, CudaArray& labFrameDipoles, CudaArray& labFrameQuadrupoles, CudaArray& inducedDipole, CudaArray& inducedDipolePolar, CudaArray& dampingAndThole, CudaArray& covalentFlags, CudaArray& polarizationGroupFlags) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); // Compute the GK force. void* gkForceArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices, &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &inducedDipoleS.getDevicePointer(), &inducedDipolePolarS.getDevicePointer(), &bornRadii.getDevicePointer(), &bornForce.getDevicePointer()}; cu.executeKernel(gkForceKernel, gkForceArgs, numForceThreadBlocks*gkForceThreads, gkForceThreads); // Compute the surface area force. if (includeSurfaceArea) { void* surfaceAreaArgs[] = {&bornForce.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &params.getDevicePointer(), &bornRadii.getDevicePointer()}; cu.executeKernel(surfaceAreaKernel, surfaceAreaArgs, cu.getNumAtoms()); } // Apply the remaining terms. void* chainRuleArgs[] = {&cu.getForce().getDevicePointer(), &cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices, &params.getDevicePointer(), &bornRadii.getDevicePointer(), &bornForce.getDevicePointer()}; cu.executeKernel(chainRuleKernel, chainRuleArgs, numForceThreadBlocks*chainRuleThreads, chainRuleThreads); void* ediffArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &inducedDipoleS.getDevicePointer(), &inducedDipolePolarS.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(ediffKernel, ediffArgs, numForceThreadBlocks*ediffThreads, ediffThreads); } void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaGeneralizedKirkwoodForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumParticles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of particles has changed"); // Record the per-particle parameters. vector<float2> paramsVector(cu.getPaddedNumAtoms()); for (int i = 0; i < force.getNumParticles(); i++) { double charge, radius, scalingFactor; force.getParticleParameters(i, charge, radius, scalingFactor); paramsVector[i] = make_float2((float) radius, (float) (scalingFactor*radius)); } params.upload(paramsVector); cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaVdw * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaVdwForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaVdwForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { int iv1, iv2; double sigma1, sigma2, epsilon1, epsilon2, reduction1, reduction2; bool isAlchemical1, isAlchemical2; force.getParticleParameters(particle1, iv1, sigma1, epsilon1, reduction1, isAlchemical1); force.getParticleParameters(particle2, iv2, sigma2, epsilon2, reduction2, isAlchemical2); return (sigma1 == sigma2 && epsilon1 == epsilon2 && reduction1 == reduction2 && isAlchemical1 == isAlchemical2); } private: const AmoebaVdwForce& force; }; CudaCalcAmoebaVdwForceKernel::CudaCalcAmoebaVdwForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaVdwForceKernel(name, platform), cu(cu), system(system), hasInitializedNonbonded(false), nonbonded(NULL), vdwLambdaPinnedBuffer(NULL) { } CudaCalcAmoebaVdwForceKernel::~CudaCalcAmoebaVdwForceKernel() { cu.setAsCurrent(); if (nonbonded != NULL) delete nonbonded; if (vdwLambdaPinnedBuffer != NULL) cuMemFreeHost(vdwLambdaPinnedBuffer); } void CudaCalcAmoebaVdwForceKernel::initialize(const System& system, const AmoebaVdwForce& force) { cu.setAsCurrent(); sigmaEpsilon.initialize<float2>(cu, cu.getPaddedNumAtoms(), "sigmaEpsilon"); bondReductionAtoms.initialize<int>(cu, cu.getPaddedNumAtoms(), "bondReductionAtoms"); bondReductionFactors.initialize<float>(cu, cu.getPaddedNumAtoms(), "bondReductionFactors"); tempPosq.initialize(cu, cu.getPaddedNumAtoms(), cu.getUseDoublePrecision() ? sizeof(double4) : sizeof(float4), "tempPosq"); tempForces.initialize<long long>(cu, 3*cu.getPaddedNumAtoms(), "tempForces"); // Record atom parameters. vector<float2> sigmaEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 1)); vector<float> isAlchemicalVec(cu.getPaddedNumAtoms(), 0); vector<int> bondReductionAtomsVec(cu.getPaddedNumAtoms(), 0); vector<float> bondReductionFactorsVec(cu.getPaddedNumAtoms(), 0); vector<vector<int> > exclusions(cu.getNumAtoms()); // Handle Alchemical parameters. hasAlchemical = force.getAlchemicalMethod() != AmoebaVdwForce::None; if (hasAlchemical) { isAlchemical.initialize<float>(cu, cu.getPaddedNumAtoms(), "isAlchemical"); vdwLambda.initialize<float>(cu, 1, "vdwLambda"); CHECK_RESULT(cuMemHostAlloc(&vdwLambdaPinnedBuffer, sizeof(float), 0), "Error allocating vdwLambda pinned buffer"); } for (int i = 0; i < force.getNumParticles(); i++) { int ivIndex; double sigma, epsilon, reductionFactor; bool alchemical; force.getParticleParameters(i, ivIndex, sigma, epsilon, reductionFactor, alchemical); sigmaEpsilonVec[i] = make_float2((float) sigma, (float) epsilon); isAlchemicalVec[i] = (alchemical) ? 1.0f : 0.0f; bondReductionAtomsVec[i] = ivIndex; bondReductionFactorsVec[i] = (float) reductionFactor; force.getParticleExclusions(i, exclusions[i]); exclusions[i].push_back(i); } sigmaEpsilon.upload(sigmaEpsilonVec); bondReductionAtoms.upload(bondReductionAtomsVec); bondReductionFactors.upload(bondReductionFactorsVec); if (force.getUseDispersionCorrection()) dispersionCoefficient = AmoebaVdwForceImpl::calcDispersionCorrection(system, force); else dispersionCoefficient = 0.0; // This force is applied based on modified atom positions, where hydrogens have been moved slightly // closer to their parent atoms. We therefore create a separate CudaNonbondedUtilities just for // this force, so it will have its own neighbor list and interaction kernel. nonbonded = new CudaNonbondedUtilities(cu); nonbonded->addParameter(CudaNonbondedUtilities::ParameterInfo("sigmaEpsilon", "float", 2, sizeof(float2), sigmaEpsilon.getDevicePointer())); if (hasAlchemical) { isAlchemical.upload(isAlchemicalVec); ((float*) vdwLambdaPinnedBuffer)[0] = 1.0f; currentVdwLambda = 1.0f; vdwLambda.upload(vdwLambdaPinnedBuffer, false); nonbonded->addParameter(CudaNonbondedUtilities::ParameterInfo("isAlchemical", "float", 1, sizeof(float), isAlchemical.getDevicePointer())); nonbonded->addArgument(CudaNonbondedUtilities::ParameterInfo("vdwLambda", "float", 1, sizeof(float), vdwLambda.getDevicePointer())); } // Create the interaction kernel. map<string, string> replacements; string sigmaCombiningRule = force.getSigmaCombiningRule(); if (sigmaCombiningRule == "ARITHMETIC") replacements["SIGMA_COMBINING_RULE"] = "1"; else if (sigmaCombiningRule == "GEOMETRIC") replacements["SIGMA_COMBINING_RULE"] = "2"; else if (sigmaCombiningRule == "CUBIC-MEAN") replacements["SIGMA_COMBINING_RULE"] = "3"; else throw OpenMMException("Illegal combining rule for sigma: "+sigmaCombiningRule); string epsilonCombiningRule = force.getEpsilonCombiningRule(); if (epsilonCombiningRule == "ARITHMETIC") replacements["EPSILON_COMBINING_RULE"] = "1"; else if (epsilonCombiningRule == "GEOMETRIC") replacements["EPSILON_COMBINING_RULE"] = "2"; else if (epsilonCombiningRule =="HARMONIC") replacements["EPSILON_COMBINING_RULE"] = "3"; else if (epsilonCombiningRule == "W-H") replacements["EPSILON_COMBINING_RULE"] = "4"; else if (epsilonCombiningRule == "HHG") replacements["EPSILON_COMBINING_RULE"] = "5"; else throw OpenMMException("Illegal combining rule for sigma: "+sigmaCombiningRule); replacements["VDW_ALCHEMICAL_METHOD"] = cu.intToString(force.getAlchemicalMethod()); replacements["VDW_SOFTCORE_POWER"] = cu.intToString(force.getSoftcorePower()); replacements["VDW_SOFTCORE_ALPHA"] = cu.doubleToString(force.getSoftcoreAlpha()); double cutoff = force.getCutoffDistance(); double taperCutoff = cutoff*0.9; replacements["CUTOFF_DISTANCE"] = cu.doubleToString(force.getCutoffDistance()); replacements["TAPER_CUTOFF"] = cu.doubleToString(taperCutoff); replacements["TAPER_C3"] = cu.doubleToString(10/pow(taperCutoff-cutoff, 3.0)); replacements["TAPER_C4"] = cu.doubleToString(15/pow(taperCutoff-cutoff, 4.0)); replacements["TAPER_C5"] = cu.doubleToString(6/pow(taperCutoff-cutoff, 5.0)); bool useCutoff = (force.getNonbondedMethod() != AmoebaVdwForce::NoCutoff); nonbonded->addInteraction(useCutoff, useCutoff, true, force.getCutoffDistance(), exclusions, cu.replaceStrings(CudaAmoebaKernelSources::amoebaVdwForce2, replacements), 0); // Create the other kernels. map<string, string> defines; defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); CUmodule module = cu.createModule(CudaAmoebaKernelSources::amoebaVdwForce1, defines); prepareKernel = cu.getKernel(module, "prepareToComputeForce"); spreadKernel = cu.getKernel(module, "spreadForces"); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaVdwForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { if (!hasInitializedNonbonded) { hasInitializedNonbonded = true; nonbonded->initialize(system); } if (hasAlchemical) { float contextLambda = context.getParameter(AmoebaVdwForce::Lambda()); if (contextLambda != currentVdwLambda) { // Non-blocking copy of vdwLambda to device memory ((float*) vdwLambdaPinnedBuffer)[0] = contextLambda; vdwLambda.upload(vdwLambdaPinnedBuffer, false); currentVdwLambda = contextLambda; } } cu.getPosq().copyTo(tempPosq); cu.getForce().copyTo(tempForces); void* prepareArgs[] = {&cu.getForce().getDevicePointer(), &cu.getPosq().getDevicePointer(), &tempPosq.getDevicePointer(), &bondReductionAtoms.getDevicePointer(), &bondReductionFactors.getDevicePointer()}; cu.executeKernel(prepareKernel, prepareArgs, cu.getPaddedNumAtoms()); nonbonded->prepareInteractions(1); nonbonded->computeInteractions(1, includeForces, includeEnergy); void* spreadArgs[] = {&cu.getForce().getDevicePointer(), &tempForces.getDevicePointer(), &bondReductionAtoms.getDevicePointer(), &bondReductionFactors.getDevicePointer()}; cu.executeKernel(spreadKernel, spreadArgs, cu.getPaddedNumAtoms()); tempPosq.copyTo(cu.getPosq()); tempForces.copyTo(cu.getForce()); double4 box = cu.getPeriodicBoxSize(); return dispersionCoefficient/(box.x*box.y*box.z); } void CudaCalcAmoebaVdwForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaVdwForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumParticles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of particles has changed"); // Record the per-particle parameters. vector<float2> sigmaEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 1)); vector<float> isAlchemicalVec(cu.getPaddedNumAtoms(), 0); vector<int> bondReductionAtomsVec(cu.getPaddedNumAtoms(), 0); vector<float> bondReductionFactorsVec(cu.getPaddedNumAtoms(), 0); for (int i = 0; i < force.getNumParticles(); i++) { int ivIndex; double sigma, epsilon, reductionFactor; bool alchemical; force.getParticleParameters(i, ivIndex, sigma, epsilon, reductionFactor, alchemical); sigmaEpsilonVec[i] = make_float2((float) sigma, (float) epsilon); isAlchemicalVec[i] = (alchemical) ? 1.0f : 0.0f; bondReductionAtomsVec[i] = ivIndex; bondReductionFactorsVec[i] = (float) reductionFactor; } sigmaEpsilon.upload(sigmaEpsilonVec); if (hasAlchemical) isAlchemical.upload(isAlchemicalVec); bondReductionAtoms.upload(bondReductionAtomsVec); bondReductionFactors.upload(bondReductionFactorsVec); if (force.getUseDispersionCorrection()) dispersionCoefficient = AmoebaVdwForceImpl::calcDispersionCorrection(system, force); else dispersionCoefficient = 0.0; cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaWcaDispersion * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaWcaDispersionForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaWcaDispersionForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double radius1, radius2, epsilon1, epsilon2; force.getParticleParameters(particle1, radius1, epsilon1); force.getParticleParameters(particle2, radius2, epsilon2); return (radius1 == radius2 && epsilon1 == epsilon2); } private: const AmoebaWcaDispersionForce& force; }; CudaCalcAmoebaWcaDispersionForceKernel::CudaCalcAmoebaWcaDispersionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaWcaDispersionForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaWcaDispersionForceKernel::initialize(const System& system, const AmoebaWcaDispersionForce& force) { int numParticles = system.getNumParticles(); int paddedNumAtoms = cu.getPaddedNumAtoms(); // Record parameters. vector<float2> radiusEpsilonVec(paddedNumAtoms, make_float2(0, 0)); for (int i = 0; i < numParticles; i++) { double radius, epsilon; force.getParticleParameters(i, radius, epsilon); radiusEpsilonVec[i] = make_float2((float) radius, (float) epsilon); } radiusEpsilon.initialize<float2>(cu, paddedNumAtoms, "radiusEpsilon"); radiusEpsilon.upload(radiusEpsilonVec); // Create the kernel. map<string, string> defines; defines["NUM_ATOMS"] = cu.intToString(numParticles); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["THREAD_BLOCK_SIZE"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize()); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["EPSO"] = cu.doubleToString(force.getEpso()); defines["EPSH"] = cu.doubleToString(force.getEpsh()); defines["RMINO"] = cu.doubleToString(force.getRmino()); defines["RMINH"] = cu.doubleToString(force.getRminh()); defines["AWATER"] = cu.doubleToString(force.getAwater()); defines["SHCTD"] = cu.doubleToString(force.getShctd()); defines["M_PI"] = cu.doubleToString(M_PI); CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::amoebaWcaForce, defines); forceKernel = cu.getKernel(module, "computeWCAForce"); totalMaximumDispersionEnergy = AmoebaWcaDispersionForceImpl::getTotalMaximumDispersionEnergy(force); // Add an interaction to the default nonbonded kernel. This doesn't actually do any calculations. It's // just so that CudaNonbondedUtilities will keep track of the tiles. vector<vector<int> > exclusions; cu.getNonbondedUtilities().addInteraction(false, false, false, 1.0, exclusions, "", force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaWcaDispersionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); int forceThreadBlockSize = nb.getForceThreadBlockSize(); void* forceArgs[] = {&cu.getForce().getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices, &radiusEpsilon.getDevicePointer()}; cu.executeKernel(forceKernel, forceArgs, numForceThreadBlocks*forceThreadBlockSize, forceThreadBlockSize); return totalMaximumDispersionEnergy; } void CudaCalcAmoebaWcaDispersionForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaWcaDispersionForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumParticles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of particles has changed"); // Record the per-particle parameters. vector<float2> radiusEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 0)); for (int i = 0; i < cu.getNumAtoms(); i++) { double radius, epsilon; force.getParticleParameters(i, radius, epsilon); radiusEpsilonVec[i] = make_float2((float) radius, (float) epsilon); } radiusEpsilon.upload(radiusEpsilonVec); totalMaximumDispersionEnergy = AmoebaWcaDispersionForceImpl::getTotalMaximumDispersionEnergy(force); cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * HippoNonbondedForce * * -------------------------------------------------------------------------- */ class CudaCalcHippoNonbondedForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const HippoNonbondedForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double charge1, coreCharge1, alpha1, epsilon1, damping1, c61, pauliK1, pauliQ1, pauliAlpha1, polarizability1; double charge2, coreCharge2, alpha2, epsilon2, damping2, c62, pauliK2, pauliQ2, pauliAlpha2, polarizability2; int axisType1, multipoleZ1, multipoleX1, multipoleY1; int axisType2, multipoleZ2, multipoleX2, multipoleY2; vector<double> dipole1, dipole2, quadrupole1, quadrupole2; force.getParticleParameters(particle1, charge1, dipole1, quadrupole1, coreCharge1, alpha1, epsilon1, damping1, c61, pauliK1, pauliQ1, pauliAlpha1, polarizability1, axisType1, multipoleZ1, multipoleX1, multipoleY1); force.getParticleParameters(particle2, charge2, dipole2, quadrupole2, coreCharge2, alpha2, epsilon2, damping2, c62, pauliK2, pauliQ2, pauliAlpha2, polarizability2, axisType2, multipoleZ2, multipoleX2, multipoleY2); if (charge1 != charge2 || coreCharge1 != coreCharge2 || alpha1 != alpha2 || epsilon1 != epsilon1 || damping1 != damping2 || c61 != c62 || pauliK1 != pauliK2 || pauliQ1 != pauliQ2 || pauliAlpha1 != pauliAlpha2 || polarizability1 != polarizability2 || axisType1 != axisType2) { return false; } for (int i = 0; i < dipole1.size(); ++i) if (dipole1[i] != dipole2[i]) return false; for (int i = 0; i < quadrupole1.size(); ++i) if (quadrupole1[i] != quadrupole2[i]) return false; return true; } int getNumParticleGroups() { return force.getNumExceptions(); } void getParticlesInGroup(int index, vector<int>& particles) { int particle1, particle2; double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale; force.getExceptionParameters(index, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale); particles.resize(2); particles[0] = particle1; particles[1] = particle2; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2; double multipoleMultipoleScale1, dipoleMultipoleScale1, dipoleDipoleScale1, dispersionScale1, repulsionScale1, chargeTransferScale1; double multipoleMultipoleScale2, dipoleMultipoleScale2, dipoleDipoleScale2, dispersionScale2, repulsionScale2, chargeTransferScale2; force.getExceptionParameters(group1, particle1, particle2, multipoleMultipoleScale1, dipoleMultipoleScale1, dipoleDipoleScale1, dispersionScale1, repulsionScale1, chargeTransferScale1); force.getExceptionParameters(group2, particle1, particle2, multipoleMultipoleScale2, dipoleMultipoleScale2, dipoleDipoleScale2, dispersionScale2, repulsionScale2, chargeTransferScale2); return (multipoleMultipoleScale1 == multipoleMultipoleScale2 && dipoleMultipoleScale1 == dipoleMultipoleScale2 && dipoleDipoleScale1 == dipoleDipoleScale2 && dispersionScale1 == dispersionScale2 && repulsionScale1 == repulsionScale2 && chargeTransferScale1 == chargeTransferScale2); } private: const HippoNonbondedForce& force; }; class CudaCalcHippoNonbondedForceKernel::TorquePostComputation : public CudaContext::ForcePostComputation { public: TorquePostComputation(CudaCalcHippoNonbondedForceKernel& owner) : owner(owner) { } double computeForceAndEnergy(bool includeForces, bool includeEnergy, int groups) { owner.addTorquesToForces(); return 0.0; } private: CudaCalcHippoNonbondedForceKernel& owner; }; CudaCalcHippoNonbondedForceKernel::CudaCalcHippoNonbondedForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcHippoNonbondedForceKernel(name, platform), cu(cu), system(system), sort(NULL), hasInitializedKernels(false), hasInitializedFFT(false), multipolesAreValid(false) { } CudaCalcHippoNonbondedForceKernel::~CudaCalcHippoNonbondedForceKernel() { cu.setAsCurrent(); if (sort != NULL) delete sort; if (hasInitializedFFT) { cufftDestroy(fftForward); cufftDestroy(fftBackward); cufftDestroy(dfftForward); cufftDestroy(dfftBackward); } } void CudaCalcHippoNonbondedForceKernel::initialize(const System& system, const HippoNonbondedForce& force) { cu.setAsCurrent(); extrapolationCoefficients = force.getExtrapolationCoefficients(); usePME = (force.getNonbondedMethod() == HippoNonbondedForce::PME); // Initialize particle parameters. numParticles = force.getNumParticles(); vector<double> coreChargeVec, valenceChargeVec, alphaVec, epsilonVec, dampingVec, c6Vec, pauliKVec, pauliQVec, pauliAlphaVec, polarizabilityVec; vector<double> localDipolesVec, localQuadrupolesVec; vector<int4> multipoleParticlesVec; vector<vector<int> > exclusions(numParticles); for (int i = 0; i < numParticles; i++) { double charge, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; force.getParticleParameters(i, charge, dipole, quadrupole, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability, axisType, atomZ, atomX, atomY); coreChargeVec.push_back(coreCharge); valenceChargeVec.push_back(charge-coreCharge); alphaVec.push_back(alpha); epsilonVec.push_back(epsilon); dampingVec.push_back(damping); c6Vec.push_back(c6); pauliKVec.push_back(pauliK); pauliQVec.push_back(pauliQ); pauliAlphaVec.push_back(pauliAlpha); polarizabilityVec.push_back(polarizability); multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType)); for (int j = 0; j < 3; j++) localDipolesVec.push_back(dipole[j]); localQuadrupolesVec.push_back(quadrupole[0]); localQuadrupolesVec.push_back(quadrupole[1]); localQuadrupolesVec.push_back(quadrupole[2]); localQuadrupolesVec.push_back(quadrupole[4]); localQuadrupolesVec.push_back(quadrupole[5]); exclusions[i].push_back(i); } int paddedNumAtoms = cu.getPaddedNumAtoms(); for (int i = numParticles; i < paddedNumAtoms; i++) { coreChargeVec.push_back(0); valenceChargeVec.push_back(0); alphaVec.push_back(0); epsilonVec.push_back(0); dampingVec.push_back(0); c6Vec.push_back(0); pauliKVec.push_back(0); pauliQVec.push_back(0); pauliAlphaVec.push_back(0); polarizabilityVec.push_back(0); multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0)); for (int j = 0; j < 3; j++) localDipolesVec.push_back(0); for (int j = 0; j < 5; j++) localQuadrupolesVec.push_back(0); } int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); coreCharge.initialize(cu, paddedNumAtoms, elementSize, "coreCharge"); valenceCharge.initialize(cu, paddedNumAtoms, elementSize, "valenceCharge"); alpha.initialize(cu, paddedNumAtoms, elementSize, "alpha"); epsilon.initialize(cu, paddedNumAtoms, elementSize, "epsilon"); damping.initialize(cu, paddedNumAtoms, elementSize, "damping"); c6.initialize(cu, paddedNumAtoms, elementSize, "c6"); pauliK.initialize(cu, paddedNumAtoms, elementSize, "pauliK"); pauliQ.initialize(cu, paddedNumAtoms, elementSize, "pauliQ"); pauliAlpha.initialize(cu, paddedNumAtoms, elementSize, "pauliAlpha"); polarizability.initialize(cu, paddedNumAtoms, elementSize, "polarizability"); multipoleParticles.initialize<int4>(cu, paddedNumAtoms, "multipoleParticles"); localDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "localDipoles"); localQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "localQuadrupoles"); lastPositions.initialize(cu, cu.getPosq().getSize(), cu.getPosq().getElementSize(), "lastPositions"); coreCharge.upload(coreChargeVec, true); valenceCharge.upload(valenceChargeVec, true); alpha.upload(alphaVec, true); epsilon.upload(epsilonVec, true); damping.upload(dampingVec, true); c6.upload(c6Vec, true); pauliK.upload(pauliKVec, true); pauliQ.upload(pauliQVec, true); pauliAlpha.upload(pauliAlphaVec, true); polarizability.upload(polarizabilityVec, true); multipoleParticles.upload(multipoleParticlesVec); localDipoles.upload(localDipolesVec, true); localQuadrupoles.upload(localQuadrupolesVec, true); // Create workspace arrays. labDipoles.initialize(cu, paddedNumAtoms, 3*elementSize, "dipole"); labQuadrupoles[0].initialize(cu, paddedNumAtoms, elementSize, "qXX"); labQuadrupoles[1].initialize(cu, paddedNumAtoms, elementSize, "qXY"); labQuadrupoles[2].initialize(cu, paddedNumAtoms, elementSize, "qXZ"); labQuadrupoles[3].initialize(cu, paddedNumAtoms, elementSize, "qYY"); labQuadrupoles[4].initialize(cu, paddedNumAtoms, elementSize, "qYZ"); fracDipoles.initialize(cu, paddedNumAtoms, 3*elementSize, "fracDipoles"); fracQuadrupoles.initialize(cu, 6*paddedNumAtoms, elementSize, "fracQuadrupoles"); field.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "field"); inducedField.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedField"); torque.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "torque"); inducedDipole.initialize(cu, paddedNumAtoms, 3*elementSize, "inducedDipole"); int numOrders = extrapolationCoefficients.size(); extrapolatedDipole.initialize(cu, 3*numParticles*numOrders, elementSize, "extrapolatedDipole"); extrapolatedPhi.initialize(cu, 10*numParticles*numOrders, elementSize, "extrapolatedPhi"); cu.addAutoclearBuffer(field); cu.addAutoclearBuffer(torque); // Record exceptions and exclusions. vector<double> exceptionScaleVec[6]; vector<int2> exceptionAtomsVec; for (int i = 0; i < force.getNumExceptions(); i++) { int particle1, particle2; double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale; force.getExceptionParameters(i, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale); exclusions[particle1].push_back(particle2); exclusions[particle2].push_back(particle1); if (usePME || multipoleMultipoleScale != 0 || dipoleMultipoleScale != 0 || dipoleDipoleScale != 0 || dispersionScale != 0 || repulsionScale != 0 || chargeTransferScale != 0) { exceptionAtomsVec.push_back(make_int2(particle1, particle2)); exceptionScaleVec[0].push_back(multipoleMultipoleScale); exceptionScaleVec[1].push_back(dipoleMultipoleScale); exceptionScaleVec[2].push_back(dipoleDipoleScale); exceptionScaleVec[3].push_back(dispersionScale); exceptionScaleVec[4].push_back(repulsionScale); exceptionScaleVec[5].push_back(chargeTransferScale); } } if (exceptionAtomsVec.size() > 0) { exceptionAtoms.initialize<int2>(cu, exceptionAtomsVec.size(), "exceptionAtoms"); exceptionAtoms.upload(exceptionAtomsVec); for (int i = 0; i < 6; i++) { exceptionScales[i].initialize(cu, exceptionAtomsVec.size(), elementSize, "exceptionScales"); exceptionScales[i].upload(exceptionScaleVec[i], true); } } // Create the kernels. bool useShuffle = (cu.getComputeCapability() >= 3.0 && !cu.getUseDoublePrecision()); map<string, string> defines; defines["HIPPO"] = "1"; defines["NUM_ATOMS"] = cu.intToString(numParticles); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456); if (useShuffle) defines["USE_SHUFFLE"] = ""; maxExtrapolationOrder = extrapolationCoefficients.size(); defines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder); stringstream coefficients; for (int i = 0; i < maxExtrapolationOrder; i++) { if (i > 0) coefficients << ","; double sum = 0; for (int j = i; j < maxExtrapolationOrder; j++) sum += extrapolationCoefficients[j]; coefficients << cu.doubleToString(sum); } defines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str(); cutoff = force.getCutoffDistance(); if (usePME) { int nx, ny, nz; force.getPMEParameters(pmeAlpha, nx, ny, nz); if (nx == 0 || pmeAlpha == 0) { NonbondedForce nb; nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance()); nb.setCutoffDistance(force.getCutoffDistance()); NonbondedForceImpl::calcPMEParameters(system, nb, pmeAlpha, gridSizeX, gridSizeY, gridSizeZ, false); gridSizeX = CudaFFT3D::findLegalDimension(gridSizeX); gridSizeY = CudaFFT3D::findLegalDimension(gridSizeY); gridSizeZ = CudaFFT3D::findLegalDimension(gridSizeZ); } else { gridSizeX = CudaFFT3D::findLegalDimension(nx); gridSizeY = CudaFFT3D::findLegalDimension(ny); gridSizeZ = CudaFFT3D::findLegalDimension(nz); } force.getDPMEParameters(dpmeAlpha, nx, ny, nz); if (nx == 0 || dpmeAlpha == 0) { NonbondedForce nb; nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance()); nb.setCutoffDistance(force.getCutoffDistance()); NonbondedForceImpl::calcPMEParameters(system, nb, dpmeAlpha, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, true); dispersionGridSizeX = CudaFFT3D::findLegalDimension(dispersionGridSizeX); dispersionGridSizeY = CudaFFT3D::findLegalDimension(dispersionGridSizeY); dispersionGridSizeZ = CudaFFT3D::findLegalDimension(dispersionGridSizeZ); } else { dispersionGridSizeX = CudaFFT3D::findLegalDimension(nx); dispersionGridSizeY = CudaFFT3D::findLegalDimension(ny); dispersionGridSizeZ = CudaFFT3D::findLegalDimension(nz); } defines["EWALD_ALPHA"] = cu.doubleToString(pmeAlpha); defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); defines["USE_EWALD"] = ""; defines["USE_CUTOFF"] = ""; defines["USE_PERIODIC"] = ""; defines["CUTOFF_SQUARED"] = cu.doubleToString(force.getCutoffDistance()*force.getCutoffDistance()); } CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::hippoMultipoles, defines); computeMomentsKernel = cu.getKernel(module, "computeLabFrameMoments"); recordInducedDipolesKernel = cu.getKernel(module, "recordInducedDipoles"); mapTorqueKernel = cu.getKernel(module, "mapTorqueToForce"); module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleInducedField, defines); initExtrapolatedKernel = cu.getKernel(module, "initExtrapolatedDipoles"); iterateExtrapolatedKernel = cu.getKernel(module, "iterateExtrapolatedDipoles"); computeExtrapolatedKernel = cu.getKernel(module, "computeExtrapolatedDipoles"); polarizationEnergyKernel = cu.getKernel(module, "computePolarizationEnergy"); // Set up PME. if (usePME) { // Create the PME kernels. map<string, string> pmeDefines; pmeDefines["HIPPO"] = "1"; pmeDefines["EWALD_ALPHA"] = cu.doubleToString(pmeAlpha); pmeDefines["DISPERSION_EWALD_ALPHA"] = cu.doubleToString(dpmeAlpha); pmeDefines["PME_ORDER"] = cu.intToString(PmeOrder); pmeDefines["NUM_ATOMS"] = cu.intToString(numParticles); pmeDefines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); pmeDefines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456); pmeDefines["GRID_SIZE_X"] = cu.intToString(gridSizeX); pmeDefines["GRID_SIZE_Y"] = cu.intToString(gridSizeY); pmeDefines["GRID_SIZE_Z"] = cu.intToString(gridSizeZ); pmeDefines["M_PI"] = cu.doubleToString(M_PI); pmeDefines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); pmeDefines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str(); pmeDefines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder); CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipolePme, pmeDefines); pmeTransformMultipolesKernel = cu.getKernel(module, "transformMultipolesToFractionalCoordinates"); pmeTransformPotentialKernel = cu.getKernel(module, "transformPotentialToCartesianCoordinates"); pmeSpreadFixedMultipolesKernel = cu.getKernel(module, "gridSpreadFixedMultipoles"); pmeSpreadInducedDipolesKernel = cu.getKernel(module, "gridSpreadInducedDipoles"); pmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge"); pmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution"); pmeFixedPotentialKernel = cu.getKernel(module, "computeFixedPotentialFromGrid"); pmeInducedPotentialKernel = cu.getKernel(module, "computeInducedPotentialFromGrid"); pmeFixedForceKernel = cu.getKernel(module, "computeFixedMultipoleForceAndEnergy"); pmeInducedForceKernel = cu.getKernel(module, "computeInducedDipoleForceAndEnergy"); pmeRecordInducedFieldDipolesKernel = cu.getKernel(module, "recordInducedFieldDipoles"); pmeSelfEnergyKernel = cu.getKernel(module, "calculateSelfEnergyAndTorque"); // Create the dispersion PME kernels. pmeDefines["EWALD_ALPHA"] = cu.doubleToString(dpmeAlpha); pmeDefines["EPSILON_FACTOR"] = "1"; pmeDefines["GRID_SIZE_X"] = cu.intToString(dispersionGridSizeX); pmeDefines["GRID_SIZE_Y"] = cu.intToString(dispersionGridSizeY); pmeDefines["GRID_SIZE_Z"] = cu.intToString(dispersionGridSizeZ); pmeDefines["RECIP_EXP_FACTOR"] = cu.doubleToString(M_PI*M_PI/(dpmeAlpha*dpmeAlpha)); pmeDefines["CHARGE"] = "charges[atom]"; pmeDefines["USE_LJPME"] = "1"; module = cu.createModule(CudaKernelSources::vectorOps+CudaKernelSources::pme, pmeDefines); dpmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge"); dpmeGridIndexKernel = cu.getKernel(module, "findAtomGridIndex"); dpmeSpreadChargeKernel = cu.getKernel(module, "gridSpreadCharge"); dpmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution"); dpmeEvalEnergyKernel = cu.getKernel(module, "gridEvaluateEnergy"); dpmeInterpolateForceKernel = cu.getKernel(module, "gridInterpolateForce"); // Create required data structures. int roundedZSize = PmeOrder*(int) ceil(gridSizeZ/(double) PmeOrder); int gridElements = gridSizeX*gridSizeY*roundedZSize; roundedZSize = PmeOrder*(int) ceil(dispersionGridSizeZ/(double) PmeOrder); gridElements = max(gridElements, dispersionGridSizeX*dispersionGridSizeY*roundedZSize); pmeGrid1.initialize(cu, gridElements, elementSize, "pmeGrid1"); pmeGrid2.initialize(cu, gridElements, 2*elementSize, "pmeGrid2"); cu.addAutoclearBuffer(pmeGrid1); pmeBsplineModuliX.initialize(cu, gridSizeX, elementSize, "pmeBsplineModuliX"); pmeBsplineModuliY.initialize(cu, gridSizeY, elementSize, "pmeBsplineModuliY"); pmeBsplineModuliZ.initialize(cu, gridSizeZ, elementSize, "pmeBsplineModuliZ"); dpmeBsplineModuliX.initialize(cu, dispersionGridSizeX, elementSize, "dpmeBsplineModuliX"); dpmeBsplineModuliY.initialize(cu, dispersionGridSizeY, elementSize, "dpmeBsplineModuliY"); dpmeBsplineModuliZ.initialize(cu, dispersionGridSizeZ, elementSize, "dpmeBsplineModuliZ"); pmePhi.initialize(cu, 20*numParticles, elementSize, "pmePhi"); pmePhidp.initialize(cu, 20*numParticles, elementSize, "pmePhidp"); pmeCphi.initialize(cu, 10*numParticles, elementSize, "pmeCphi"); pmeAtomGridIndex.initialize<int2>(cu, numParticles, "pmeAtomGridIndex"); sort = new CudaSort(cu, new SortTrait(), cu.getNumAtoms()); cufftResult result = cufftPlan3d(&fftForward, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_D2Z : CUFFT_R2C); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); result = cufftPlan3d(&fftBackward, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2D : CUFFT_C2R); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); result = cufftPlan3d(&dfftForward, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, cu.getUseDoublePrecision() ? CUFFT_D2Z : CUFFT_R2C); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); result = cufftPlan3d(&dfftBackward, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2D : CUFFT_C2R); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); hasInitializedFFT = true; // Initialize the B-spline moduli. double data[PmeOrder]; double x = 0.0; data[0] = 1.0 - x; data[1] = x; for (int i = 2; i < PmeOrder; i++) { double denom = 1.0/i; data[i] = x*data[i-1]*denom; for (int j = 1; j < i; j++) data[i-j] = ((x+j)*data[i-j-1] + ((i-j+1)-x)*data[i-j])*denom; data[0] = (1.0-x)*data[0]*denom; } int maxSize = max(max(gridSizeX, gridSizeY), gridSizeZ); vector<double> bsplines_data(maxSize+1, 0.0); for (int i = 2; i <= PmeOrder+1; i++) bsplines_data[i] = data[i-2]; for (int dim = 0; dim < 3; dim++) { int ndata = (dim == 0 ? gridSizeX : dim == 1 ? gridSizeY : gridSizeZ); vector<double> moduli(ndata); // get the modulus of the discrete Fourier transform double factor = 2.0*M_PI/ndata; for (int i = 0; i < ndata; i++) { double sc = 0.0; double ss = 0.0; for (int j = 1; j <= ndata; j++) { double arg = factor*i*(j-1); sc += bsplines_data[j]*cos(arg); ss += bsplines_data[j]*sin(arg); } moduli[i] = sc*sc+ss*ss; } // Fix for exponential Euler spline interpolation failure. double eps = 1.0e-7; if (moduli[0] < eps) moduli[0] = 0.9*moduli[1]; for (int i = 1; i < ndata-1; i++) if (moduli[i] < eps) moduli[i] = 0.9*(moduli[i-1]+moduli[i+1]); if (moduli[ndata-1] < eps) moduli[ndata-1] = 0.9*moduli[ndata-2]; // Compute and apply the optimal zeta coefficient. int jcut = 50; for (int i = 1; i <= ndata; i++) { int k = i - 1; if (i > ndata/2) k = k - ndata; double zeta; if (k == 0) zeta = 1.0; else { double sum1 = 1.0; double sum2 = 1.0; factor = M_PI*k/ndata; for (int j = 1; j <= jcut; j++) { double arg = factor/(factor+M_PI*j); sum1 += pow(arg, PmeOrder); sum2 += pow(arg, 2*PmeOrder); } for (int j = 1; j <= jcut; j++) { double arg = factor/(factor-M_PI*j); sum1 += pow(arg, PmeOrder); sum2 += pow(arg, 2*PmeOrder); } zeta = sum2/sum1; } moduli[i-1] = moduli[i-1]*zeta*zeta; } if (cu.getUseDoublePrecision()) { if (dim == 0) pmeBsplineModuliX.upload(moduli); else if (dim == 1) pmeBsplineModuliY.upload(moduli); else pmeBsplineModuliZ.upload(moduli); } else { vector<float> modulif(ndata); for (int i = 0; i < ndata; i++) modulif[i] = (float) moduli[i]; if (dim == 0) pmeBsplineModuliX.upload(modulif); else if (dim == 1) pmeBsplineModuliY.upload(modulif); else pmeBsplineModuliZ.upload(modulif); } } // Initialize the b-spline moduli for dispersion PME. maxSize = max(max(dispersionGridSizeX, dispersionGridSizeY), dispersionGridSizeZ); vector<double> ddata(PmeOrder); bsplines_data.resize(maxSize); data[PmeOrder-1] = 0.0; data[1] = 0.0; data[0] = 1.0; for (int i = 3; i < PmeOrder; i++) { double div = 1.0/(i-1.0); data[i-1] = 0.0; for (int j = 1; j < (i-1); j++) data[i-j-1] = div*(j*data[i-j-2]+(i-j)*data[i-j-1]); data[0] = div*data[0]; } // Differentiate. ddata[0] = -data[0]; for (int i = 1; i < PmeOrder; i++) ddata[i] = data[i-1]-data[i]; double div = 1.0/(PmeOrder-1); data[PmeOrder-1] = 0.0; for (int i = 1; i < (PmeOrder-1); i++) data[PmeOrder-i-1] = div*(i*data[PmeOrder-i-2]+(PmeOrder-i)*data[PmeOrder-i-1]); data[0] = div*data[0]; for (int i = 0; i < maxSize; i++) bsplines_data[i] = 0.0; for (int i = 1; i <= PmeOrder; i++) bsplines_data[i] = data[i-1]; // Evaluate the actual bspline moduli for X/Y/Z. for(int dim = 0; dim < 3; dim++) { int ndata = (dim == 0 ? dispersionGridSizeX : dim == 1 ? dispersionGridSizeY : dispersionGridSizeZ); vector<double> moduli(ndata); for (int i = 0; i < ndata; i++) { double sc = 0.0; double ss = 0.0; for (int j = 0; j < ndata; j++) { double arg = (2.0*M_PI*i*j)/ndata; sc += bsplines_data[j]*cos(arg); ss += bsplines_data[j]*sin(arg); } moduli[i] = sc*sc+ss*ss; } for (int i = 0; i < ndata; i++) if (moduli[i] < 1.0e-7) moduli[i] = (moduli[i-1]+moduli[i+1])*0.5; if (dim == 0) dpmeBsplineModuliX.upload(moduli, true); else if (dim == 1) dpmeBsplineModuliY.upload(moduli, true); else dpmeBsplineModuliZ.upload(moduli, true); } } // Add the interaction to the default nonbonded kernel. CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); nb.setKernelSource(CudaAmoebaKernelSources::hippoInteractionHeader+CudaAmoebaKernelSources::hippoNonbonded); nb.addArgument(CudaNonbondedUtilities::ParameterInfo("torqueBuffers", "unsigned long long", 1, torque.getElementSize(), torque.getDevicePointer(), false)); nb.addArgument(CudaNonbondedUtilities::ParameterInfo("extrapolatedDipole", "real3", 1, extrapolatedDipole.getElementSize(), extrapolatedDipole.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("coreCharge", "real", 1, coreCharge.getElementSize(), coreCharge.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("valenceCharge", "real", 1, valenceCharge.getElementSize(), valenceCharge.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("alpha", "real", 1, alpha.getElementSize(), alpha.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("epsilon", "real", 1, epsilon.getElementSize(), epsilon.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("damping", "real", 1, damping.getElementSize(), damping.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("c6", "real", 1, c6.getElementSize(), c6.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliK", "real", 1, pauliK.getElementSize(), pauliK.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliQ", "real", 1, pauliQ.getElementSize(), pauliQ.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliAlpha", "real", 1, pauliAlpha.getElementSize(), pauliAlpha.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("dipole", "real", 3, labDipoles.getElementSize(), labDipoles.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("inducedDipole", "real", 3, inducedDipole.getElementSize(), inducedDipole.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXX", "real", 1, labQuadrupoles[0].getElementSize(), labQuadrupoles[0].getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXY", "real", 1, labQuadrupoles[1].getElementSize(), labQuadrupoles[1].getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXZ", "real", 1, labQuadrupoles[2].getElementSize(), labQuadrupoles[2].getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qYY", "real", 1, labQuadrupoles[3].getElementSize(), labQuadrupoles[3].getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qYZ", "real", 1, labQuadrupoles[4].getElementSize(), labQuadrupoles[4].getDevicePointer())); map<string, string> replacements; replacements["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456); replacements["SWITCH_CUTOFF"] = cu.doubleToString(force.getSwitchingDistance()); replacements["SWITCH_C3"] = cu.doubleToString(10/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 3.0)); replacements["SWITCH_C4"] = cu.doubleToString(15/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 4.0)); replacements["SWITCH_C5"] = cu.doubleToString(6/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 5.0)); replacements["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder); replacements["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str(); replacements["USE_EWALD"] = (usePME ? "1" : "0"); replacements["PME_ALPHA"] = (usePME ? cu.doubleToString(pmeAlpha) : "0"); replacements["DPME_ALPHA"] = (usePME ? cu.doubleToString(dpmeAlpha) : "0"); replacements["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); string interactionSource = cu.replaceStrings(CudaAmoebaKernelSources::hippoInteraction, replacements); nb.addInteraction(usePME, usePME, true, force.getCutoffDistance(), exclusions, interactionSource, force.getForceGroup()); nb.setUsePadding(false); // Create the kernel for computing exceptions. if (exceptionAtoms.isInitialized()) { replacements["COMPUTE_INTERACTION"] = interactionSource; string exceptionsSrc = CudaKernelSources::vectorOps+CudaAmoebaKernelSources::hippoInteractionHeader+CudaAmoebaKernelSources::hippoNonbondedExceptions; exceptionsSrc = cu.replaceStrings(exceptionsSrc, replacements); defines["NUM_EXCEPTIONS"] = cu.intToString(exceptionAtoms.getSize()); module = cu.createModule(exceptionsSrc, defines); computeExceptionsKernel = cu.getKernel(module, "computeNonbondedExceptions"); } cu.addForce(new ForceInfo(force)); cu.addPostComputation(new TorquePostComputation(*this)); } void CudaCalcHippoNonbondedForceKernel::createFieldKernel(const string& interactionSrc, vector<CudaArray*> params, CudaArray& fieldBuffer, CUfunction& kernel, vector<void*>& args, CUfunction& exceptionKernel, vector<void*>& exceptionArgs, CudaArray& exceptionScale) { // Create the kernel source. map<string, string> replacements; replacements["COMPUTE_FIELD"] = interactionSrc; stringstream extraArgs, atomParams, loadLocal1, loadLocal2, load1, load2, load3; for (auto param : params) { string name = param->getName(); string type = (param->getElementSize() == 4 || param->getElementSize() == 8 ? "real" : "real3"); extraArgs << ", const " << type << "* __restrict__ " << name; atomParams << type << " " << name << ";\n"; loadLocal1 << "localData[localAtomIndex]." << name << " = " << name << "1;\n"; loadLocal2 << "localData[localAtomIndex]." << name << " = " << name << "[j];\n"; load1 << type << " " << name << "1 = " << name << "[atom1];\n"; load2 << type << " " << name << "2 = localData[atom2]." << name << ";\n"; load3 << type << " " << name << "2 = " << name << "[atom2];\n"; } replacements["PARAMETER_ARGUMENTS"] = extraArgs.str(); replacements["ATOM_PARAMETER_DATA"] = atomParams.str(); replacements["LOAD_LOCAL_PARAMETERS_FROM_1"] = loadLocal1.str(); replacements["LOAD_LOCAL_PARAMETERS_FROM_GLOBAL"] = loadLocal2.str(); replacements["LOAD_ATOM1_PARAMETERS"] = load1.str(); replacements["LOAD_ATOM2_PARAMETERS"] = load2.str(); replacements["LOAD_ATOM2_PARAMETERS_FROM_GLOBAL"] = load3.str(); string src = cu.replaceStrings(CudaAmoebaKernelSources::hippoComputeField, replacements); // Set defines and create the kernel. map<string, string> defines; if (usePME) { defines["USE_CUTOFF"] = "1"; defines["USE_PERIODIC"] = "1"; defines["USE_EWALD"] = "1"; defines["PME_ALPHA"] = cu.doubleToString(pmeAlpha); defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); } defines["WARPS_PER_GROUP"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize()/CudaContext::TileSize); defines["THREAD_BLOCK_SIZE"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize()); defines["CUTOFF"] = cu.doubleToString(cutoff); defines["CUTOFF_SQUARED"] = cu.doubleToString(cutoff*cutoff); defines["NUM_ATOMS"] = cu.intToString(cu.getNumAtoms()); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["TILE_SIZE"] = cu.intToString(CudaContext::TileSize); defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(cu.getNonbondedUtilities().getExclusionTiles().getSize()); defines["NUM_EXCEPTIONS"] = cu.intToString(exceptionAtoms.isInitialized() ? exceptionAtoms.getSize() : 0); CUmodule module = cu.createModule(CudaKernelSources::vectorOps+src, defines); kernel = cu.getKernel(module, "computeField"); // Build the list of arguments. CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); args.push_back(&cu.getPosq().getDevicePointer()); args.push_back(&cu.getNonbondedUtilities().getExclusions().getDevicePointer()); args.push_back(&cu.getNonbondedUtilities().getExclusionTiles().getDevicePointer()); args.push_back(&fieldBuffer.getDevicePointer()); if (nb.getUseCutoff()) { args.push_back(&nb.getInteractingTiles().getDevicePointer()); args.push_back(&nb.getInteractionCount().getDevicePointer()); args.push_back(cu.getPeriodicBoxSizePointer()); args.push_back(cu.getInvPeriodicBoxSizePointer()); args.push_back(cu.getPeriodicBoxVecXPointer()); args.push_back(cu.getPeriodicBoxVecYPointer()); args.push_back(cu.getPeriodicBoxVecZPointer()); args.push_back(&maxTiles); args.push_back(&nb.getBlockCenters().getDevicePointer()); args.push_back(&nb.getBlockBoundingBoxes().getDevicePointer()); args.push_back(&nb.getInteractingAtoms().getDevicePointer()); } else args.push_back(&maxTiles); for (auto param : params) args.push_back(&param->getDevicePointer()); // If there are any exceptions, build the kernel and arguments to compute them. if (exceptionAtoms.isInitialized()) { exceptionKernel = cu.getKernel(module, "computeFieldExceptions"); exceptionArgs.push_back(&cu.getPosq().getDevicePointer()); exceptionArgs.push_back(&fieldBuffer.getDevicePointer()); exceptionArgs.push_back(&exceptionAtoms.getDevicePointer()); exceptionArgs.push_back(&exceptionScale.getDevicePointer()); if (nb.getUseCutoff()) { exceptionArgs.push_back(cu.getPeriodicBoxSizePointer()); exceptionArgs.push_back(cu.getInvPeriodicBoxSizePointer()); exceptionArgs.push_back(cu.getPeriodicBoxVecXPointer()); exceptionArgs.push_back(cu.getPeriodicBoxVecYPointer()); exceptionArgs.push_back(cu.getPeriodicBoxVecZPointer()); } for (auto param : params) exceptionArgs.push_back(&param->getDevicePointer()); } } double CudaCalcHippoNonbondedForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); if (!hasInitializedKernels) { hasInitializedKernels = true; // These kernels can't be compiled in initialize(), because the nonbonded utilities object // has not yet been initialized then. maxTiles = (nb.getUseCutoff() ? nb.getInteractingTiles().getSize() : cu.getNumAtomBlocks()*(cu.getNumAtomBlocks()+1)/2); createFieldKernel(CudaAmoebaKernelSources::hippoFixedField, {&coreCharge, &valenceCharge, &alpha, &labDipoles, &labQuadrupoles[0], &labQuadrupoles[1], &labQuadrupoles[2], &labQuadrupoles[3], &labQuadrupoles[4]}, field, fixedFieldKernel, fixedFieldArgs, fixedFieldExceptionKernel, fixedFieldExceptionArgs, exceptionScales[1]); createFieldKernel(CudaAmoebaKernelSources::hippoMutualField, {&alpha, &inducedDipole}, inducedField, mutualFieldKernel, mutualFieldArgs, mutualFieldExceptionKernel, mutualFieldExceptionArgs, exceptionScales[2]); if (exceptionAtoms.isInitialized()) { computeExceptionsArgs.push_back(&cu.getForce().getDevicePointer()); computeExceptionsArgs.push_back(&cu.getEnergyBuffer().getDevicePointer()); computeExceptionsArgs.push_back(&torque.getDevicePointer()); computeExceptionsArgs.push_back(&cu.getPosq().getDevicePointer()); computeExceptionsArgs.push_back(&extrapolatedDipole.getDevicePointer()); computeExceptionsArgs.push_back(&exceptionAtoms.getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[0].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[1].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[2].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[3].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[4].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[5].getDevicePointer()); computeExceptionsArgs.push_back(&coreCharge.getDevicePointer()); computeExceptionsArgs.push_back(&valenceCharge.getDevicePointer()); computeExceptionsArgs.push_back(&alpha.getDevicePointer()); computeExceptionsArgs.push_back(&epsilon.getDevicePointer()); computeExceptionsArgs.push_back(&damping.getDevicePointer()); computeExceptionsArgs.push_back(&c6.getDevicePointer()); computeExceptionsArgs.push_back(&pauliK.getDevicePointer()); computeExceptionsArgs.push_back(&pauliQ.getDevicePointer()); computeExceptionsArgs.push_back(&pauliAlpha.getDevicePointer()); computeExceptionsArgs.push_back(&labDipoles.getDevicePointer()); computeExceptionsArgs.push_back(&inducedDipole.getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[0].getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[1].getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[2].getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[3].getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[4].getDevicePointer()); computeExceptionsArgs.push_back(&extrapolatedDipole.getDevicePointer()); if (nb.getUseCutoff()) { computeExceptionsArgs.push_back(cu.getPeriodicBoxSizePointer()); computeExceptionsArgs.push_back(cu.getInvPeriodicBoxSizePointer()); computeExceptionsArgs.push_back(cu.getPeriodicBoxVecXPointer()); computeExceptionsArgs.push_back(cu.getPeriodicBoxVecYPointer()); computeExceptionsArgs.push_back(cu.getPeriodicBoxVecZPointer()); } } } // Make sure the arrays for the neighbor list haven't been recreated. if (nb.getUseCutoff()) { if (maxTiles < nb.getInteractingTiles().getSize()) { maxTiles = nb.getInteractingTiles().getSize(); fixedFieldArgs[4] = &nb.getInteractingTiles().getDevicePointer(); fixedFieldArgs[14] = &nb.getInteractingAtoms().getDevicePointer(); mutualFieldArgs[4] = &nb.getInteractingTiles().getDevicePointer(); mutualFieldArgs[14] = &nb.getInteractingAtoms().getDevicePointer(); } } // Compute the lab frame moments. void* computeMomentsArgs[] = {&cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer(), &localDipoles.getDevicePointer(), &localQuadrupoles.getDevicePointer(), &labDipoles.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer()}; cu.executeKernel(computeMomentsKernel, computeMomentsArgs, cu.getNumAtoms()); void* recipBoxVectorPointer[3]; if (usePME) { // Compute reciprocal box vectors. Vec3 boxVectors[3]; cu.getPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]); double determinant = boxVectors[0][0]*boxVectors[1][1]*boxVectors[2][2]; double scale = 1.0/determinant; double3 recipBoxVectors[3]; recipBoxVectors[0] = make_double3(boxVectors[1][1]*boxVectors[2][2]*scale, 0, 0); recipBoxVectors[1] = make_double3(-boxVectors[1][0]*boxVectors[2][2]*scale, boxVectors[0][0]*boxVectors[2][2]*scale, 0); recipBoxVectors[2] = make_double3((boxVectors[1][0]*boxVectors[2][1]-boxVectors[1][1]*boxVectors[2][0])*scale, -boxVectors[0][0]*boxVectors[2][1]*scale, boxVectors[0][0]*boxVectors[1][1]*scale); float3 recipBoxVectorsFloat[3]; if (cu.getUseDoublePrecision()) { recipBoxVectorPointer[0] = &recipBoxVectors[0]; recipBoxVectorPointer[1] = &recipBoxVectors[1]; recipBoxVectorPointer[2] = &recipBoxVectors[2]; } else { recipBoxVectorsFloat[0] = make_float3((float) recipBoxVectors[0].x, 0, 0); recipBoxVectorsFloat[1] = make_float3((float) recipBoxVectors[1].x, (float) recipBoxVectors[1].y, 0); recipBoxVectorsFloat[2] = make_float3((float) recipBoxVectors[2].x, (float) recipBoxVectors[2].y, (float) recipBoxVectors[2].z); recipBoxVectorPointer[0] = &recipBoxVectorsFloat[0]; recipBoxVectorPointer[1] = &recipBoxVectorsFloat[1]; recipBoxVectorPointer[2] = &recipBoxVectorsFloat[2]; } // Reciprocal space calculation for electrostatics. void* pmeTransformMultipolesArgs[] = {&labDipoles.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformMultipolesKernel, pmeTransformMultipolesArgs, cu.getNumAtoms()); void* pmeSpreadFixedMultipolesArgs[] = {&cu.getPosq().getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmeGrid1.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadFixedMultipolesKernel, pmeSpreadFixedMultipolesArgs, cu.getNumAtoms()); if (cu.getUseDoublePrecision()) { void* finishSpreadArgs[] = {&pmeGrid1.getDevicePointer()}; cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid1.getSize()); cufftExecD2Z(fftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer()); } else cufftExecR2C(fftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer()); void* pmeConvolutionArgs[] = {&pmeGrid2.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(), &pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2D(fftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer()); else cufftExecC2R(fftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer()); void* pmeFixedPotentialArgs[] = {&pmeGrid1.getDevicePointer(), &pmePhi.getDevicePointer(), &field.getDevicePointer(), &cu.getPosq().getDevicePointer(), &labDipoles.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeFixedPotentialKernel, pmeFixedPotentialArgs, cu.getNumAtoms()); void* pmeTransformFixedPotentialArgs[] = {&pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformPotentialKernel, pmeTransformFixedPotentialArgs, cu.getNumAtoms()); void* pmeFixedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeFixedForceKernel, pmeFixedForceArgs, cu.getNumAtoms()); // Reciprocal space calculation for dispersion. void* gridIndexArgs[] = {&cu.getPosq().getDevicePointer(), &pmeAtomGridIndex.getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(dpmeGridIndexKernel, gridIndexArgs, cu.getNumAtoms()); sort->sort(pmeAtomGridIndex); cu.clearBuffer(pmeGrid2); void* spreadArgs[] = {&cu.getPosq().getDevicePointer(), &pmeGrid2.getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2], &pmeAtomGridIndex.getDevicePointer(), &c6.getDevicePointer()}; cu.executeKernel(dpmeSpreadChargeKernel, spreadArgs, cu.getNumAtoms(), 128); void* finishSpreadArgs[] = {&pmeGrid2.getDevicePointer(), &pmeGrid1.getDevicePointer()}; cu.executeKernel(dpmeFinishSpreadChargeKernel, finishSpreadArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecD2Z(dfftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer()); else cufftExecR2C(dfftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer()); if (includeEnergy) { void* computeEnergyArgs[] = {&pmeGrid2.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &dpmeBsplineModuliX.getDevicePointer(), &dpmeBsplineModuliY.getDevicePointer(), &dpmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(dpmeEvalEnergyKernel, computeEnergyArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ); } void* convolutionArgs[] = {&pmeGrid2.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &dpmeBsplineModuliX.getDevicePointer(), &dpmeBsplineModuliY.getDevicePointer(), &dpmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(dpmeConvolutionKernel, convolutionArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2D(dfftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer()); else cufftExecC2R(dfftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer()); void* interpolateArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &pmeGrid1.getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2], &pmeAtomGridIndex.getDevicePointer(), &c6.getDevicePointer()}; cu.executeKernel(dpmeInterpolateForceKernel, interpolateArgs, cu.getNumAtoms(), 128); } // Compute the field from fixed multipoles. cu.executeKernel(fixedFieldKernel, &fixedFieldArgs[0], nb.getNumForceThreadBlocks()*nb.getForceThreadBlockSize(), nb.getForceThreadBlockSize()); if (fixedFieldExceptionArgs.size() > 0) cu.executeKernel(fixedFieldExceptionKernel, &fixedFieldExceptionArgs[0], exceptionAtoms.getSize()); // Iterate the induced dipoles. computeExtrapolatedDipoles(recipBoxVectorPointer); // Add the polarization energy. if (includeEnergy) { void* polarizationEnergyArgs[] = {&cu.getEnergyBuffer().getDevicePointer(), &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(polarizationEnergyKernel, polarizationEnergyArgs, cu.getNumAtoms()); } // Compute the forces due to the reciprocal space PME calculation for induced dipoles. if (usePME) { void* pmeTransformInducedPotentialArgs[] = {&pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformPotentialKernel, pmeTransformInducedPotentialArgs, cu.getNumAtoms()); void* pmeInducedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &extrapolatedPhi.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &pmePhi.getDevicePointer(), &pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedForceKernel, pmeInducedForceArgs, cu.getNumAtoms()); void* pmeSelfEnergyArgs[] = {&torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), &c6.getDevicePointer(), &inducedDipole.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer()}; cu.executeKernel(pmeSelfEnergyKernel, pmeSelfEnergyArgs, cu.getNumAtoms()); } // Compute nonbonded exceptions. if (exceptionAtoms.isInitialized()) cu.executeKernel(computeExceptionsKernel, &computeExceptionsArgs[0], exceptionAtoms.getSize()); // Record the current atom positions so we can tell later if they have changed. cu.getPosq().copyTo(lastPositions); multipolesAreValid = true; return 0.0; } void CudaCalcHippoNonbondedForceKernel::computeInducedField(void** recipBoxVectorPointer, int optOrder) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); cu.clearBuffer(inducedField); cu.executeKernel(mutualFieldKernel, &mutualFieldArgs[0], nb.getNumForceThreadBlocks()*nb.getForceThreadBlockSize(), nb.getForceThreadBlockSize()); if (mutualFieldExceptionArgs.size() > 0) cu.executeKernel(mutualFieldExceptionKernel, &mutualFieldExceptionArgs[0], exceptionAtoms.getSize()); if (usePME) { cu.clearBuffer(pmeGrid1); void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(), &pmeGrid1.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms()); if (cu.getUseDoublePrecision()) { void* finishSpreadArgs[] = {&pmeGrid1.getDevicePointer()}; cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid1.getSize()); cufftExecD2Z(fftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer()); } else cufftExecR2C(fftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer()); void* pmeConvolutionArgs[] = {&pmeGrid2.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(), &pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2D(fftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer()); else cufftExecC2R(fftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer()); void* pmeInducedPotentialArgs[] = {&pmeGrid1.getDevicePointer(), &extrapolatedPhi.getDevicePointer(), &optOrder, &pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms()); void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhidp.getDevicePointer(), &inducedField.getDevicePointer(), &inducedDipole.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms()); } } void CudaCalcHippoNonbondedForceKernel::computeExtrapolatedDipoles(void** recipBoxVectorPointer) { // Start by storing the direct dipoles as PT0 void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &inducedDipole.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms()); void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer()}; cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize()); // Recursively apply alpha.Tau to the µ_(n) components to generate µ_(n+1), and store the result for (int order = 1; order < maxExtrapolationOrder; ++order) { computeInducedField(recipBoxVectorPointer, order-1); void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize()); } // Take a linear combination of the µ_(n) components to form the total dipole void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer()}; cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize()); computeInducedField(recipBoxVectorPointer, maxExtrapolationOrder-1); } void CudaCalcHippoNonbondedForceKernel::addTorquesToForces() { void* mapTorqueArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer()}; cu.executeKernel(mapTorqueKernel, mapTorqueArgs, cu.getNumAtoms()); } void CudaCalcHippoNonbondedForceKernel::getInducedDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double3> d; inducedDipole.download(d); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(d[i].x, d[i].y, d[i].z); } else { vector<float3> d; inducedDipole.download(d); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(d[i].x, d[i].y, d[i].z); } } void CudaCalcHippoNonbondedForceKernel::ensureMultipolesValid(ContextImpl& context) { if (multipolesAreValid) { int numParticles = cu.getNumAtoms(); if (cu.getUseDoublePrecision()) { vector<double4> pos1, pos2; cu.getPosq().download(pos1); lastPositions.download(pos2); for (int i = 0; i < numParticles; i++) if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) { multipolesAreValid = false; break; } } else { vector<float4> pos1, pos2; cu.getPosq().download(pos1); lastPositions.download(pos2); for (int i = 0; i < numParticles; i++) if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) { multipolesAreValid = false; break; } } } if (!multipolesAreValid) context.calcForcesAndEnergy(false, false, -1); } void CudaCalcHippoNonbondedForceKernel::getLabFramePermanentDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double3> labDipoleVec; labDipoles.download(labDipoleVec); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(labDipoleVec[i].x, labDipoleVec[i].y, labDipoleVec[i].z); } else { vector<float3> labDipoleVec; labDipoles.download(labDipoleVec); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(labDipoleVec[i].x, labDipoleVec[i].y, labDipoleVec[i].z); } } void CudaCalcHippoNonbondedForceKernel::copyParametersToContext(ContextImpl& context, const HippoNonbondedForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumParticles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of particles has changed"); // Record the per-particle parameters. vector<double> coreChargeVec, valenceChargeVec, alphaVec, epsilonVec, dampingVec, c6Vec, pauliKVec, pauliQVec, pauliAlphaVec, polarizabilityVec; vector<double> localDipolesVec, localQuadrupolesVec; vector<int4> multipoleParticlesVec; for (int i = 0; i < numParticles; i++) { double charge, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; force.getParticleParameters(i, charge, dipole, quadrupole, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability, axisType, atomZ, atomX, atomY); coreChargeVec.push_back(coreCharge); valenceChargeVec.push_back(charge-coreCharge); alphaVec.push_back(alpha); epsilonVec.push_back(epsilon); dampingVec.push_back(damping); c6Vec.push_back(c6); pauliKVec.push_back(pauliK); pauliQVec.push_back(pauliQ); pauliAlphaVec.push_back(pauliAlpha); polarizabilityVec.push_back(polarizability); multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType)); for (int j = 0; j < 3; j++) localDipolesVec.push_back(dipole[j]); localQuadrupolesVec.push_back(quadrupole[0]); localQuadrupolesVec.push_back(quadrupole[1]); localQuadrupolesVec.push_back(quadrupole[2]); localQuadrupolesVec.push_back(quadrupole[4]); localQuadrupolesVec.push_back(quadrupole[5]); } int paddedNumAtoms = cu.getPaddedNumAtoms(); for (int i = numParticles; i < paddedNumAtoms; i++) { coreChargeVec.push_back(0); valenceChargeVec.push_back(0); alphaVec.push_back(0); epsilonVec.push_back(0); dampingVec.push_back(0); c6Vec.push_back(0); pauliKVec.push_back(0); pauliQVec.push_back(0); pauliAlphaVec.push_back(0); polarizabilityVec.push_back(0); multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0)); for (int j = 0; j < 3; j++) localDipolesVec.push_back(0); for (int j = 0; j < 5; j++) localQuadrupolesVec.push_back(0); } coreCharge.upload(coreChargeVec, true); valenceCharge.upload(valenceChargeVec, true); alpha.upload(alphaVec, true); epsilon.upload(epsilonVec, true); damping.upload(dampingVec, true); c6.upload(c6Vec, true); pauliK.upload(pauliKVec, true); pauliQ.upload(pauliQVec, true); pauliAlpha.upload(pauliAlphaVec, true); polarizability.upload(polarizabilityVec, true); multipoleParticles.upload(multipoleParticlesVec); localDipoles.upload(localDipolesVec, true); localQuadrupoles.upload(localQuadrupolesVec, true); // Record the per-exception parameters. vector<double> exceptionScaleVec[6]; vector<int2> exceptionAtomsVec; for (int i = 0; i < force.getNumExceptions(); i++) { int particle1, particle2; double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale; force.getExceptionParameters(i, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale); if (usePME || multipoleMultipoleScale != 0 || dipoleMultipoleScale != 0 || dipoleDipoleScale != 0 || dispersionScale != 0 || repulsionScale != 0 || chargeTransferScale != 0) { exceptionAtomsVec.push_back(make_int2(particle1, particle2)); exceptionScaleVec[0].push_back(multipoleMultipoleScale); exceptionScaleVec[1].push_back(dipoleMultipoleScale); exceptionScaleVec[2].push_back(dipoleDipoleScale); exceptionScaleVec[3].push_back(dispersionScale); exceptionScaleVec[4].push_back(repulsionScale); exceptionScaleVec[5].push_back(chargeTransferScale); } } if (exceptionAtomsVec.size() > 0) { if (!exceptionAtoms.isInitialized() || exceptionAtoms.getSize() != exceptionAtomsVec.size()) throw OpenMMException("updateParametersInContext: The number of exceptions has changed"); exceptionAtoms.upload(exceptionAtomsVec); for (int i = 0; i < 6; i++) exceptionScales[i].upload(exceptionScaleVec[i], true); } else if (exceptionAtoms.isInitialized()) throw OpenMMException("updateParametersInContext: The number of exceptions has changed"); cu.invalidateMolecules(); multipolesAreValid = false; } void CudaCalcHippoNonbondedForceKernel::getPMEParameters(double& alpha, int& nx, int& ny, int& nz) const { alpha = pmeAlpha; nx = gridSizeX; ny = gridSizeY; nz = gridSizeZ; } void CudaCalcHippoNonbondedForceKernel::getDPMEParameters(double& alpha, int& nx, int& ny, int& nz) const { alpha = dpmeAlpha; nx = dispersionGridSizeX; ny = dispersionGridSizeY; nz = dispersionGridSizeZ; }
211,173
70,996
#include <inc/v3.h> using namespace std; int main() { v3 a = v3(1,2,3); // Test Accessers cout << "Testing Accessors" << endl; cout << a[0] << a[1] << a[2]; cout << " -- Should be 123" << endl; a[0] = 5, a[1] = 5, a[2] = 5; cout << a[0] << a[1] << a[2]; cout << " -- Should be 555" << endl << endl; a[0] = 1, a[1] = 2, a[2] = 3; // Test ostream cout << "Testing ostream" << endl; cout << a; cout << " -- Should be {1,2,3}" << endl << endl; // Test unary operators cout << "Testing Unary Operators" << endl; cout << +a; cout << " -- Should be {1,2,3}" << endl; cout << -a; cout << " -- Should be {-1,-2,-3}" << endl << endl; // Test assignments cout << "Testing Assignments" << endl; a += v3(1,1,1); cout << a; cout << " -- Should be {2,3,4}" << endl; a -= v3(1,2,1); cout << a; cout << " -- Should be {1,1,3}" << endl; a *= v3(1,2,4); cout << a; cout << " -- Should be {1,2,12}" << endl; a /= v3(1,1,4); cout << a; cout << " -- Should be {1,2,3}" << endl; a *= 5; cout << a; cout << " -- Should be {5,10,15}" << endl; a /= 5; cout << a; cout << " -- Should be {1,2,3}" << endl << endl; // Operations cout << "Testing Operations" << endl; cout << a + v3(1,1,1); cout << " -- Should be {2,3,4}" << endl; cout << a - v3(1,2,1); cout << " -- Should be {0,0,2}" << endl; cout << a * v3(1,2,4); cout << " -- Should be {1,4,12}" << endl; cout << a / v3(1,1,4); cout << " -- Should be {1,2,0.75}" << endl; cout << a * 5; cout << " -- Should be {5,10,15}" << endl; cout << a / 5; cout << " -- Should be {0.2,0.4,0.6}" << endl << endl; // Vector Operations cout << "Testing Vector Operations" << endl; v3 b = v3(7,8,9); cout << a.crossProduct(b); cout << " -- Should be {-6,12,-6}" << endl; cout << a.dotProduct(b); cout << " -- Should be 50" << endl; cout << a.magnitude(); cout << " -- Should be 3.7417" << endl; cout << a.magnitudeSquared(); cout << " -- Should be 14" << endl; cout << a.unitVector(); cout << " -- Should be {0.27,0.53,0.80}" << endl << endl; }
2,344
1,003
//////////////////////////////////////////////////////////////////////////////// /// Copyright 2018-present Xinyan DAI<xinyan.dai@outlook.com> /// /// permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to /// deal in the Software without restriction, including without limitation the /// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or /// sell copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions ofthe Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS /// IN THE SOFTWARE. /// @version 0.1 /// @author Xinyan DAI /// @contact xinyan.dai@outlook.com ////////////////////////////////////////////////////////////////////////////// #pragma once #include <utility> #include <vector> #include <random> #include <unordered_map> #include <boost/progress.hpp> #include "../index.hpp" namespace ss { using std::vector; template<class DataType> class KMeansIndex : public Index<DataType> { protected: /// _center[i] means the i'th center's coordinate vector<vector<DataType > > _centers; /// _points[i] means all points' indexes belong to i'th center /// _points[i][j] means the j'th point's index belongs to i'th center vector<vector<int > > _points; public: explicit KMeansIndex(const parameter& para) : Index<DataType >(para), _centers(para.kmeans_centers), _points(para.kmeans_centers) {} const vector<vector<DataType > > & get_centers() const { return _centers; } const vector<vector<int > > & get_points() const { return _points; } void reset(int num_centers) { this->_centers = vector<vector<DataType > >(num_centers); this->_points = vector<vector<int > >(num_centers); } void set_centers(const vector<vector<DataType > >& centers) { _centers = centers; } void Train(const Matrix<DataType > & data) override { Iterate(Visitor<DataType >(data, 0, data.getDim())); } void Add(const Matrix<DataType > & data) override { Assign(Visitor<DataType >(data, 0, data.getDim())); } void Search(const DataType *query, const std::function<void (int)>& prober) override { const vector<int>& idx = _points[NearestCenter(query, _centers[0].size())]; for (int id : idx) { prober(id); } } const vector<int>& Search(const DataType *query) { return _points[NearestCenter(query, _centers[0].size())]; } /*** * iteratively update centers and re-assign points * @param data */ void Iterate(const Visitor<DataType> & data) { /// initialize centers /// TODO(Xinyan): should initialized randomly for(int i=0; i<_centers.size(); i++) { _centers[i] = vector<DataType >(data[i], data[i]+data.getDim()); } boost::progress_display progress(this->_para.iteration); for (int iter = 0; iter < this->_para.iteration; ++iter, ++progress) { /// Assignment Assign(data); /// UpdateCenter Update(data); /// clear points in each centers for (int c = 0; c<_points.size(); c++) { _points[c].clear(); } } } /** * re-calculate center by averaging points' coordinate */ void Update(const Visitor<DataType> & data) { for (int c = 0; c < _centers.size(); ++c) { vector<DataType > sum(data.getDim(), 0.0f); for (int p = 0; p < _points[c].size(); ++p) { for (int d = 0; d < data.getDim(); ++d) { sum[d] += data[_points[c][p]][d]; /// add up } } for (int d = 0; d < data.getDim(); ++d) { _centers[c][d] = sum[d] / _points[c].size(); /// average } } } /** * assign each point in {@link data} to nearest center */ void Assign(const Visitor<DataType> & data) { vector<int > codes(data.getSize()); #pragma omp parallel for for (int i = 0; i < data.getSize(); ++i) { codes[i] = NearestCenter(data[i], data.getDim()); } for (int i=0; i<data.getSize(); ++i) { _points[codes[i]].push_back(i); } } int NearestCenter(const DataType * vector, int dimension) { DataType min_distance = ss::EuclidDistance(vector, _centers[0].data(), dimension); int nearest_center = 0; for (int c = 1; c < _centers.size(); c++) { DataType distance = Distance(vector, dimension, c); if (distance < min_distance) { min_distance = distance; nearest_center = c; } } return nearest_center; } /** * calculate distances from {@link vector} to each center * @return distances within a vector of pair<distance, center> */ std::vector<std::pair<float, int > > ClusterDistance(const DataType *vector, int dimension) { std::vector<std::pair<float, int>> dist_centers(this->_centers.size()); for (int center = 0; center < (this->_centers.size()); ++center) { DataType distance = Distance(vector, dimension, center); dist_centers[center] = std::make_pair(distance, center); } return dist_centers; } inline DataType Distance(const DataType * vector, int dimension, int center) { return ss::EuclidDistance(vector, _centers[center].data(), dimension); } }; } // namespace ss
6,726
1,960
#include "n2k.h" #include "n2ksocket.h" #include "generated/windData.cc" #include "generated/waterDepth.cc" #include "generated/vesselHeading.cc" #include "pipe.h" #include <stdio.h> #include <signal.h> #include <bits/stdc++.h> void handleWind(const n2k::Message & m); void handleDepth(const n2k::Message & m); void handleHeading(const n2k::Message & m); std::ostream* out = &std::cout; int main(int argc, char *argv[]) { // if you pass any argument, you skip writing to rrdtool if (argc <= 1) { out = new opipestream("rrdtool - >/dev/null"); } signal(SIGINT, exit); n2k::SocketCanReceiver r("can0"); int callbackCount = 0; if (access("wind.rrd", W_OK) || argc > 1) { n2k::Callback cb( n2k::WindData::PGN, n2k::WindData::Type, handleWind); r.addCallback(cb); callbackCount++; } if (access("depth.rrd", W_OK) || argc > 1) { n2k::Callback cb2( n2k::WaterDepth::PGN, n2k::WaterDepth::Type, handleDepth); r.addCallback(cb2); callbackCount++; } if (access("heading.rrd", W_OK) || argc > 1) { n2k::Callback cb3( n2k::VesselHeading::PGN, n2k::VesselHeading::Type, handleHeading); r.addCallback(cb3); callbackCount++; } if (callbackCount == 0) { std::cerr << "No writeable rrd files!\n"; exit(1); } r.applyKernelFilter(); r.run(); } void handleWind(const n2k::Message & m) { static n2k::WindData last; static int repeatCount; const int kRepeatLimit = 10; const n2k::WindData &w = static_cast<const n2k::WindData&>(m); if ((repeatCount++ < kRepeatLimit) && (w.getWindSpeedKnots() == last.getWindSpeedKnots()) && (w.getWindAngleDegrees() == last.getWindAngleDegrees())) { return; } last = w; repeatCount = 0; *out << "update wind.rrd N:" << std::setprecision(2) << w.getWindSpeedKnots() << ":" << w.getWindAngleDegrees() << "\n"; } void handleDepth(const n2k::Message & m) { const n2k::WaterDepth &d = static_cast<const n2k::WindData&>(m); *out << "update depth.rrd N:" << std::setprecision(2) << d.getDepthFeet() << "\n"; } void handleHeading(const n2k::Message & m) { static double last; static int repeatCount; const int kRepeatLimit = 10; const n2k::VesselHeading &h = static_cast<const n2k::WindData&>(m); auto diff = last - h.getHeadingDegrees(); if ((repeatCount++ < kRepeatLimit) && (diff < .1 && diff > -.1)) { return; } last = h.getHeadingDegrees(); repeatCount = 0; *out << "update heading.rrd N:" << std::setprecision(2) << h.getHeadingDegrees() << "\n"; }
2,675
1,056
//Code written by Christian Neij #include "NonMoveableSprite.h" namespace minMotor { NonMoveableSprite::NonMoveableSprite(int x, int y, int w, int h) :Sprite(x, y, w, h) { } }
184
77
/* * 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 <COPYRIGHT HOLDER> ``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 * <COPYRIGHT HOLDER> 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 "session.h" #include "lua/utils.h" #include "lua/trigger.h" #include "box/user.h" #include "scoped_guard.h" extern "C" { #include <lua.h> #include <lauxlib.h> #include <lualib.h> } #include <fiber.h> #include <sio.h> #include "box/session.h" static const char *sessionlib_name = "box.session"; /** * Return a unique monotonic session * identifier. The identifier can be used * to check whether or not a session is alive. * 0 means there is no session (e.g. * a procedure is running in a detached * fiber). */ static int lbox_session_id(struct lua_State *L) { lua_pushnumber(L, current_session()->id); return 1; } /** * Return the id of currently executed request. * Many requests share the same session so this is only * valid at session start. 0 for non-iproto sessions. */ static int lbox_session_sync(struct lua_State *L) { lua_pushnumber(L, current_session()->sync); return 1; } /** * Session user id. * Note: effective user id (current_user()->uid) * may be different in a setuid function. */ static int lbox_session_uid(struct lua_State *L) { /* * Sic: push session user, not the current user, * which may differ inside a setuid function. */ lua_pushnumber(L, current_session()->credentials.uid); return 1; } /** * Session user name. * Note: effective user name may be different in * a setuid function. */ static int lbox_session_user(struct lua_State *L) { struct user *user = user_by_id(current_session()->credentials.uid); if (user) lua_pushstring(L, user->name); else lua_pushnil(L); return 1; } /** Session user id. */ static int lbox_session_su(struct lua_State *L) { int top = lua_gettop(L); if (top < 1) luaL_error(L, "session.su(): bad arguments"); struct session *session = current_session(); if (session == NULL) luaL_error(L, "session.su(): session does not exit"); struct user *user; if (lua_type(L, 1) == LUA_TSTRING) { size_t len; const char *name = lua_tolstring(L, 1, &len); user = user_cache_find_by_name(name, len); } else { user = user_cache_find(lua_tointeger(L, 1)); } struct credentials orig_cr; credentials_copy(&orig_cr, &session->credentials); credentials_init(&session->credentials, user); if (top == 1) return 0; /* su */ /* sudo */ auto scoped_guard = make_scoped_guard([&] { credentials_copy(&session->credentials, &orig_cr); }); lua_call(L, top - 2, LUA_MULTRET); return lua_gettop(L) - 1; } /** * Check whether or not a session exists. */ static int lbox_session_exists(struct lua_State *L) { if (lua_gettop(L) != 1) luaL_error(L, "session.exists(sid): bad arguments"); uint32_t sid = luaL_checkint(L, -1); lua_pushboolean(L, session_find(sid) != NULL); return 1; } /** * Check whether or not a session exists. */ static int lbox_session_fd(struct lua_State *L) { if (lua_gettop(L) != 1) luaL_error(L, "session.fd(sid): bad arguments"); uint32_t sid = luaL_checkint(L, -1); struct session *session = session_find(sid); if (session == NULL) luaL_error(L, "session.fd(): session does not exit"); lua_pushinteger(L, session->fd); return 1; } /** * Pretty print peer name. */ static int lbox_session_peer(struct lua_State *L) { if (lua_gettop(L) > 1) luaL_error(L, "session.peer(sid): bad arguments"); int fd; struct session *session; if (lua_gettop(L) == 1) session = session_find(luaL_checkint(L, 1)); else session = current_session(); if (session == NULL) luaL_error(L, "session.peer(): session does not exit"); fd = session->fd; if (fd < 0) { lua_pushnil(L); /* no associated peer */ return 1; } struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); sio_getpeername(fd, (struct sockaddr *)&addr, &addrlen); lua_pushstring(L, sio_strfaddr((struct sockaddr *)&addr, addrlen)); return 1; } /** * run on_connect|on_disconnect trigger */ static void lbox_session_run_trigger(struct trigger *trigger, void * /* event */) { lua_State *L = lua_newthread(tarantool_L); LuarefGuard coro_guard(tarantool_L); lua_rawgeti(L, LUA_REGISTRYINDEX, (intptr_t) trigger->data); lbox_call(L, 0, 0); } static int lbox_session_on_connect(struct lua_State *L) { return lbox_trigger_reset(L, 2, &session_on_connect, lbox_session_run_trigger); } static int lbox_session_on_disconnect(struct lua_State *L) { return lbox_trigger_reset(L, 2, &session_on_disconnect, lbox_session_run_trigger); } void session_storage_cleanup(int sid) { static int ref = LUA_REFNIL; struct lua_State *L = tarantool_L; int top = lua_gettop(L); if (ref == LUA_REFNIL) { lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); if (!lua_istable(L, -1)) goto exit; lua_getfield(L, -1, "session"); if (!lua_istable(L, -1)) goto exit; lua_getmetatable(L, -1); if (!lua_istable(L, -1)) goto exit; lua_getfield(L, -1, "aggregate_storage"); if (!lua_istable(L, -1)) goto exit; ref = luaL_ref(L, LUA_REGISTRYINDEX); } lua_rawgeti(L, LUA_REGISTRYINDEX, ref); lua_pushnil(L); lua_rawseti(L, -2, sid); exit: lua_settop(L, top); } void box_lua_session_init(struct lua_State *L) { static const struct luaL_reg sessionlib[] = { {"id", lbox_session_id}, {"sync", lbox_session_sync}, {"uid", lbox_session_uid}, {"user", lbox_session_user}, {"su", lbox_session_su}, {"fd", lbox_session_fd}, {"exists", lbox_session_exists}, {"peer", lbox_session_peer}, {"on_connect", lbox_session_on_connect}, {"on_disconnect", lbox_session_on_disconnect}, {NULL, NULL} }; luaL_register_module(L, sessionlib_name, sessionlib); lua_pop(L, 1); }
6,854
2,758
#include "CodegenManager.h" #include "TempDirectory.h" #include "Utility.h" #include <boost/process.hpp> namespace process = boost::process; CodegenManager::CodegenManager(const string& templateDir) { this->redirectHeader = Utility::readFile(templateDir + "/redirect.h"); this->redirectCode = Utility::readFile(templateDir + "/redirect.cpp"); this->templateCode = Utility::readFile(templateDir + "/template.cpp"); this->cmakeLists = Utility::readFile(templateDir + "/CMakeLists.txt"); } string CodegenManager::performCodegen(const string& prefixCode, const string& mainCode) { //Create an auto-deleting temporary directory to hold our codegen build TempDirectory tempDir; //Populate the template source code string codegenSource = this->templateCode; codegenSource = Utility::strReplace("//$$__PREFIX_CODE__$$", prefixCode, codegenSource); codegenSource = Utility::strReplace("//$$__MAIN_CODE__$$", mainCode, codegenSource); //Write our template files to the temp directory Utility::writeFile(tempDir.getPath() + "/redirect.h", this->redirectHeader); Utility::writeFile(tempDir.getPath() + "/redirect.cpp", this->redirectCode); Utility::writeFile(tempDir.getPath() + "/template.cpp", codegenSource); Utility::writeFile(tempDir.getPath() + "/CMakeLists.txt", this->cmakeLists); //Attempt to perform codegen auto cmake = process::search_path("cmake"); Utility::execute(tempDir.getPath(), cmake, "."); ProcessOutput output = Utility::execute(tempDir.getPath(), cmake, "--build", ".", "--target", "install"); if (output.code != 0) { throw std::runtime_error("codegen failed with exit code " + std::to_string(output.code) + " and stdout: \"" + output.stdout + "\" and stderr: \"" + output.stderr + "\""); } //Retrieve the generated executable data return Utility::readFile(tempDir.getPath() + "/bin/out"); }
1,839
588
#include "RSA.h" #include "prime.h" const bigint RSA::DEFAULT_E(65537); /** * RSA密钥生成 * * @param bits 密钥长度 * @return 密钥对 */ RSA::KeyPair RSA::generate(size_t bits) { size_t len = (bits + 1) / 2; bigint N; bigint p; bigint q; while (true) { p = prime::generate(len); q = prime::generate(len); N = p * q; if (N.bitLength() == bits) { break; } } auto pSubtractOne = p - bigint::ONE; auto qSubtractOne = q - bigint::ONE; bigint d = DEFAULT_E.modInverse(pSubtractOne * qSubtractOne); PublicKey publicKey(N, DEFAULT_E); // e·dP = 1 (mod (p–1)) // e·dQ = 1 (mod (q–1)) // q·qInv = 1 (mod p) PrivateKey privateKey(N, p, q, d, DEFAULT_E.modInverse(pSubtractOne), DEFAULT_E.modInverse(qSubtractOne), q.modInverse(p)); return KeyPair(privateKey, publicKey); } bigint RSA::encrypt(const bigint &m, const RSA::PublicKey &publicKey) { return m.modPow(publicKey.e, publicKey.n); } bigint RSA::decrypt(const bigint &c, const RSA::PrivateKey &privateKey) { return c.modPow(privateKey.d, privateKey.n); }
1,142
468
#include "gardp.hpp" #include "test_common.hpp" // Execute the dynamic programming algorithm presented at p. 221, Integer // Programming, Robert S. Garfinkel, over a hardcoded set of instances. Used to // check if it is still working after a change. All the instances have only // integers, but we execute the gardp version where the profit values are // stored as doubles to test it. int main(int argc, char** argv) { int exit_code; std::cout << "hbm::benchmark_pyasukp<size_t, size_t, size_t>(&hbm::gardp, argc, argv)" << std::endl; exit_code = hbm::benchmark_pyasukp<size_t, size_t, size_t>(&hbm::gardp, argc, argv); if (exit_code != EXIT_SUCCESS) return exit_code; std::cout << "hbm::benchmark_pyasukp<size_t, double, size_t>(&hbm::gardp)" << std::endl; return hbm::benchmark_pyasukp<size_t, double, size_t>(&hbm::gardp, argc, argv); }
856
321
#include <vector> #include <string> #include <cctype> class Solution { public: std::string reformat(std::string s) { if (!s.size()) return ""; int count[2]{}; // digit, alpha for (const auto c : s) count[std::isalpha(c) ? 1 : 0]++; std::string res; if (std::abs(count[0] - count[1]) <= 1) { res.resize(s.size()); int alpha{}, digit{}; if (count[0] < count[1]) { for (int i = 0; i < s.size(); i++) { if (std::isalpha(s[i])) { res[2 * alpha++] = s[i]; } else { res[2 * (digit++) + 1] = s[i]; } } } else { for (int i = 0; i < s.size(); i++) { if (std::isalpha(s[i])) { res[2 * (alpha++) + 1] = s[i]; } else { res[2 * digit++] = s[i]; } } } } return res; } };
1,288
375
#include "Resource.h" #include "ModuleFileSystem.h" #include "JSONFile.h" #include <stdio.h> const uint Resource::type = std::hash<std::string>()(TO_STRING(Resource)); UID Resource::GetUID() const { return uid; } void Resource::SaveVariable(void * info, char ** data_cursor, size_t bytes) { memcpy(*data_cursor, info, bytes); *data_cursor += bytes; } void Resource::LoadVariable(void* info, char ** data_cursor, size_t bytes) { memcpy(info, *data_cursor, bytes); *data_cursor += bytes; } //INFO: Keeps the resource but deletes all its data bool Resource::ReleaseData() { bool ret = false; return ret; } Resource::Resource() { } //INFO: Called each time a GameObject needs to use this resource //INFO: Only load resource once bool Resource::StartUsingResource() { if (reference_count > 0u) { ++reference_count; } else { if (LoadFileData()) { ++reference_count; } } return reference_count > 0u; } uint Resource::GetReferenceCount() const { return reference_count; } //INFO: Called each time a GameObject stops using this resource //INFO: Unload resource when no GameObject references it bool Resource::StopUsingResource() { bool ret = true; --reference_count; if (reference_count == 0u) { ret = ReleaseData(); } return ret; } void Resource::SaveModifiedDate(JSONFile * meta_file, const char * asset_path) { struct stat file_stat; if (stat(asset_path, &file_stat) == 0) { meta_file->SaveNumber("dateModified", file_stat.st_atime); } }
1,482
526
#ifdef ICD2_CPP //convert linear pixel data { 0x00, 0x55, 0xaa, 0xff } to 2bpp planar tiledata void ICD2::render(const uint16 *source) { memset(lcd.output, 0x00, 320 * sizeof(uint16)); for(unsigned y = 0; y < 8; y++) { for(unsigned x = 0; x < 160; x++) { unsigned pixel = *source++; unsigned addr = y * 2 + (x / 8 * 16); lcd.output[addr + 0] |= ((pixel & 1) >> 0) << (7 - (x & 7)); lcd.output[addr + 1] |= ((pixel & 2) >> 1) << (7 - (x & 7)); } } } uint8 ICD2::read(unsigned addr) { addr &= 0xffff; //LY counter if(addr == 0x6000) { r6000_ly = GameBoy::lcd.status.ly; r6000_row = lcd.row; return r6000_ly; } //command ready port if(addr == 0x6002) { bool data = packetsize > 0; if(data) { for(unsigned i = 0; i < 16; i++) r7000[i] = packet[0][i]; packetsize--; for(unsigned i = 0; i < packetsize; i++) packet[i] = packet[i + 1]; } return data; } //ICD2 revision if(addr == 0x600f) { return 0x21; } //command port if((addr & 0xfff0) == 0x7000) { return r7000[addr & 15]; } //VRAM port if(addr == 0x7800) { uint8 data = lcd.output[r7800]; r7800 = (r7800 + 1) % 320; return data; } return 0x00; } void ICD2::write(unsigned addr, uint8 data) { addr &= 0xffff; //VRAM port if(addr == 0x6001) { r6001 = data; r7800 = 0; unsigned offset = (r6000_row - (4 - (r6001 - (r6000_ly & 3)))) & 3; render(lcd.buffer + offset * 160 * 8); return; } //control port //d7: 0 = halt, 1 = reset //d5,d4: 0 = 1-player, 1 = 2-player, 2 = 4-player, 3 = ??? //d1,d0: 0 = frequency divider (clock rate adjust) if(addr == 0x6003) { if((r6003 & 0x80) == 0x00 && (data & 0x80) == 0x80) { reset(); } switch(data & 3) { case 0: frequency = cpu.frequency / 4; break; //fast (glitchy, even on real hardware) case 1: frequency = cpu.frequency / 5; break; //normal case 2: frequency = cpu.frequency / 7; break; //slow case 3: frequency = cpu.frequency / 9; break; //very slow } r6003 = data; return; } if(addr == 0x6004) { r6004 = data; return; } //joypad 1 if(addr == 0x6005) { r6005 = data; return; } //joypad 2 if(addr == 0x6006) { r6006 = data; return; } //joypad 3 if(addr == 0x6007) { r6007 = data; return; } //joypad 4 } #endif
2,362
1,157
// DynaMix // Copyright (c) 2013-2016 Borislav Stanimirov, Zahary Karadjov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #include "basic.hpp" #include "d3d_renderer.hpp" #include "rendering_messages.hpp" #include "transform_messages.hpp" #include "system_messages.hpp" using namespace std; void d3d_renderer::render() const { render(0); } void d3d_renderer::render(int render_target) const { int transform = get_combined_transform(dm_this); // main_devince->SetTransform(D3DTS_WORLD, transform); cout << "D3D rendering object " << get_id(dm_this) << endl << "\ton target " << render_target << endl << "\twith transformation: " << transform << endl << "\t" << (_casts_shadows ? "" : "not ") << "casting shadows" << endl; } void d3d_renderer::trace(std::ostream& o) const { o << "\twith a d3d renderer" << endl; } DYNAMIX_DEFINE_MIXIN(d3d_renderer, all_rendering_messages & trace_msg);
1,031
373
#include "guiCamera.h" void GuiCamera::setup(){ cameraParameters.add(gCtoggleOnOff.set("Camera On/Off",false)); //cameraParameters.add(gCtoggleShowImage.set("Camera show image",false)); //cameraParameters.add(gCtoggleGrayscale.set("Camera grayscale",false)); //cameraParameters.add(gCtoggleMask.set("Camera mask",false)); //cameraParameters.add(gCtoggleDetect.set("Camera detect",false)); cameraParameters.add(gC2SliderScale.set("Scale Camera ",ofVec2f(1,1), ofVec2f(0.1, 0.1), ofVec2f(10,10))); cameraParameters.add(gCtoggFit.set("Fit Camera to quad",false)); cameraParameters.add(gCtoggKeepAspect.set("Keep Camera aspect ratio",false)); cameraParameters.add(gCtoggHflip.set("Camera horizontal flip",false)); cameraParameters.add(gCtoggVflip.set("Camera vertical flip",false)); cameraParameters.add(gCcolor.set("Camera color",ofFloatColor(1,1,1), ofFloatColor(0, 0), ofFloatColor(1,1))); cameraParameters.add(gCtoggGreenscreen.set("Camera Greenscreen",false)); cameraParameters.add(gCfsliderVolume.set("Camera Volume",0.0, 0.0, 1.0)); cameraParametersSecond.add(gCtoggleSampler.set("Camera sampler playback",false)); } void GuiCamera::draw(){ //ofSetColor(red, green, blue); //ofCircle(posX, posY, radius); }
1,281
452
#define RUN_ME_WITH_SH /* g++ -Wall -std=c++14 -g -DDEBUG -DIL_STD -DVERBOSE -o ${0%.*} ${0} \ -I/opt/ibm/ILOG/CPLEX_Studio1261/cplex/include \ -I/opt/ibm/ILOG/CPLEX_Studio1261/concert/include \ -L/opt/ibm/ILOG/CPLEX_Studio1261/cplex/lib/x86-64_linux/static_pic \ -L/opt/ibm/ILOG/CPLEX_Studio1261/concert/lib/x86-64_linux/static_pic \ -lilocplex \ -lcplex \ -lcplexdistmip \ -lconcert \ -lpthread \ -lm exit */ #include <ilcplex/ilocplex.h> #include <cstdlib> #include <vector> #include <sstream> #include <fstream> #include <string> #include <queue> using namespace std; // For now suppose those two are constants once the input file is loaded int minNumCross = 3, maxRectSize = 12; struct Block { public: enum Type { RegularType = 0 , HamType , SelectedRegularType , SelectedHamType , DoNotExistsType }; static Block const Regular; static Block const SelectedRegular; static Block const Ham; static Block const SelectedHam; static Block const DoNotExists; Type const type; Block( Type t ): type{ t } { } char const * GetString() { return blockStrings[type]; } private: static char const * const blockStrings[]; }; char const * const Block::blockStrings[] = { "-", "+", "x", "o", "#" }; Block const Block::Regular = Block{ Block::RegularType }; Block const Block::SelectedRegular = Block{ Block::SelectedRegularType }; Block const Block::Ham = Block{ Block::HamType }; Block const Block::SelectedHam = Block{ Block::SelectedHamType }; Block const Block::DoNotExists = Block{ Block::DoNotExistsType }; struct Base { Base() { } Base( vector< Block > && b, int w, int h ) : blocks{ move( b ) }, width{ w }, height{ h } { } Base( vector< Base > const & bases, int w, int h ) : width{ w }, height{ h } { int numBaseInWidth = 0, accWidth = 0; for ( int i = 0; i < width; ++i ) { if ( i >= accWidth + bases[numBaseInWidth].width ) { accWidth += bases[numBaseInWidth].width; ++numBaseInWidth; } } ++numBaseInWidth; // Count last one int accHeight = 0; int startingBase = 0; for ( int j = 0; j < height; ++j ) { if ( j >= accHeight + bases[startingBase].height ) { accHeight += bases[startingBase].height; startingBase += numBaseInWidth; } int y = j - accHeight; int accWidth = 0; int baseOffset = 0; for ( int i = 0; i < width; ++i ) { if ( i >= accWidth + bases[startingBase + baseOffset].width ) { accWidth += bases[startingBase + baseOffset].width; ++baseOffset; } int x = i - accWidth; AddBlock( bases[startingBase + baseOffset].access( x, y ) ); } } } void AddBlock( Block block ) { switch ( block.type ) { case Block::DoNotExistsType: { ++numDoNotExists; break; } case Block::SelectedRegularType: { ++numRegular; break; } case Block::RegularType: { ++numRegular; break; } case Block::SelectedHamType: { ++numHam; break; } case Block::HamType: { ++numHam; break; } } blocks.push_back( block ); } int size() const { return (int)blocks.size(); } int index( int i, int j ) const { return i + width*j; } Block access( int i, int j ) const { return blocks[index( i, j )]; } friend ostream & operator<<( ostream & o, Base const & b ) { o << '+'; for ( int i = 0; i < b.width; ++i ) { o << '='; } o << "+\n"; for ( int j = 0; j < b.height; ++j ) { o << '|'; for ( int i = 0; i < b.width; ++i ) { o << b.access( i, j ).GetString(); } o << "|\n"; } o << '+'; for ( int i = 0; i < b.width; ++i ) { o << '='; } o << "+\n"; return o; } vector< Block > blocks; int width, height; int numRegular = 0; int numHam = 0; int numDoNotExists = 0; }; Base LoadBaseFromFile( char const * fileName ) { FILE * fin = fopen( fileName, "rb" ); Base base; if ( fscanf( fin, "%d %d %d %d\n", &base.height, &base.width, &minNumCross, &maxRectSize ) != 4 ) { cerr << "Invalid first line in input file" << endl; exit( 1 ); } for ( int i = 0; i < (base.width+1)*base.height; ++i ) { char rc; if ( fscanf( fin, "%c", &rc ) != 1 ) { cerr << "Missing characters in input file" << endl; exit( 1 ); } switch ( rc ) { case '\n': { continue; } case '-': // fall through case 'T': { base.AddBlock( Block::Regular ); break; } case '+': // fall through case 'H': { base.AddBlock( Block::Ham ); break; } case 'x': { base.AddBlock( Block::SelectedRegular ); break; } case 'o': { base.AddBlock( Block::SelectedHam ); break; } case '#': { base.AddBlock( Block::DoNotExists ); break; } default: { cerr << "Unknown character: '" << rc << "' in input file" << endl; exit( 1 ); } } } fclose( fin ); return base; } // Maximum Independent Set of Rectangles class MISRSolver { public: MISRSolver( Base const & b ) : env{} , model{ env } , cplex{ model } , base{ b } { InitBaseVariables(); InitRectVariables(); InitMIPStart(); InitOverlapConstraints(); InitObjectiveFunction(); SetCplexParameters( cplex ); } bool Solve() { if ( !cplex.solve() ) { if ( cplex.getStatus() != IloAlgorithm::Infeasible ) { clog << "Optimization error, CPLEX status code: " << cplex.getStatus() << endl; } else { clog << "Infeasible, CPLEX status code: " << cplex.getStatus() << endl; } return false; } FillSolvedBase(); return true; } double GetBestScore() const { return cplex.getBestObjValue(); } void PrintConstraints( ostream & o = cout ) { IloModel::Iterator it{ model }; while ( it.ok() ) { if ( (*it).asConstraint().getImpl() ) { o << (*it).asConstraint() << endl; } ++it; } } void PrintSolution( ostream & o ) const { o << "Input: \n" << base << "\nSolution: \n" << solvedBase << "Score: " << GetBestScore() << endl; } Base const & GetBase() const { return base; } Base const & GetSolvedBase() const { return solvedBase; } private: struct RectVarsType { RectVarsType( IloBoolVarArray const & vars, int w, int h ) : rectVars{ vars }, rectWidth{ w }, rectHeight{ h } { } IloBoolVarArray rectVars; int rectWidth, rectHeight; }; private: IloEnv env; IloModel model; IloCplex cplex; Base const & base; Base solvedBase; IloBoolVarArray blocksVars; vector< RectVarsType > rectsVarsArray; private: void InitBaseVariables() { blocksVars = IloBoolVarArray{ env, base.size() }; for ( int i = 0; i < base.size(); ++i ) { char buf[1024]; snprintf( buf, 1024, "x_{%d,%d}", i%(base.width), i/base.width ); blocksVars[i].setName( buf ); if ( base.blocks[i].type == Block::DoNotExistsType ) { model.add( blocksVars[i] == 0 ); } } } void InitRectVariables() { for ( int i = 1; i <= maxRectSize; ++i ) { for ( int j = 1; j <= maxRectSize; ++j ) { if ( i*j <= maxRectSize ) { rectsVarsArray.emplace_back( AddRectangle( env, model, blocksVars, i, j ), i, j ); } } } } void InitMIPStart() { } void InitOverlapConstraints() { for ( int i = 0; i < base.width; ++i ) { for ( int j = 0; j < base.height; ++j ) { IloExpr overlapExpr{ env }; for ( int k = 0; k < (int)rectsVarsArray.size(); ++k ) { IloBoolVarArray const & rectVars = rectsVarsArray[k].rectVars; int w = rectsVarsArray[k].rectWidth; int h = rectsVarsArray[k].rectHeight; overlapExpr += ConstructInclusionConstraintsAndOverlapExpr( env, model, i, j , rectVars, w, h ); } model.add( overlapExpr <= 1 ); model.add( blocksVars[base.index( i, j )] <= overlapExpr ); } } } void InitObjectiveFunction() { IloExpr objExpr{ env }; for ( int i = 0; i < base.size(); ++i ) { objExpr += blocksVars[i]; } model.add( IloObjective( env, objExpr, IloObjective::Maximize ) ); } void SetCplexParameters( IloCplex & cplex ) { cplex.setParam( IloCplex::Param::Parallel, IloCplex::Opportunistic ); cplex.setParam( IloCplex::Param::Threads, cplex.getNumCores() ); cplex.setParam( IloCplex::Param::Emphasis::MIP, IloCplex::MIPEmphasisBestBound ); } void FillSolvedBase() { solvedBase.width = base.width; solvedBase.height = base.height; for ( int i = 0; i < base.size(); ++i ) { switch ( base.blocks[i].type ) { case Block::DoNotExistsType: { solvedBase.AddBlock( Block::DoNotExists ); } break; case Block::SelectedRegularType: // fall through case Block::RegularType: { if ( cplex.getValue( blocksVars[i] ) == 0 ) { solvedBase.AddBlock( Block::Regular ); } else { solvedBase.AddBlock( Block::SelectedRegular ); } } break; case Block::SelectedHamType: // fall through case Block::HamType: { if ( cplex.getValue( blocksVars[i] ) == 0 ) { solvedBase.AddBlock( Block::Ham ); } else { solvedBase.AddBlock( Block::SelectedHam ); } } break; } } } IloBoolVar AddMultConstraints( IloEnv & env, IloModel & model, IloBoolVar const & v0, IloBoolVar const & v1 ) { IloBoolVar res{ env }; model.add( res <= v0 ); model.add( res <= v1 ); model.add( res >= v0 + v1 - 1 ); return res; } IloBoolVar AddProductConstraints( IloEnv & env, IloModel & model , IloBoolVarArray const & baseVars, int x, int y , int w, int h ) { queue< IloBoolVar > mulQueue; for ( int i = 0; i < w; ++i ) { for ( int j = 0; j < h; ++j ) { mulQueue.push( baseVars[x+i + base.width*(y+j)] ); } } while ( mulQueue.size() > 1 ) { IloBoolVar v0 = mulQueue.front(); mulQueue.pop(); IloBoolVar v1 = mulQueue.front(); mulQueue.pop(); IloBoolVar mult = AddMultConstraints( env, model, v0, v1 ); mulQueue.push( mult ); } IloBoolVar last = mulQueue.front(); mulQueue.pop(); return last; } bool IsValidRect( int x, int y, int w, int h ) const { int sum = 0; for ( int i = 0; i < w; ++i ) { for ( int j = 0; j < h; ++j ) { Block::Type blockType = base.access( x+i, y+j ).type; if ( blockType == Block::DoNotExistsType ) { return false; } else if ( blockType == Block::HamType || blockType == Block::SelectedHamType ) { ++sum; } } } return sum >= minNumCross; } IloBoolVarArray AddRectangle( IloEnv & env, IloModel & model, IloBoolVarArray const & baseVars, int w, int h ) { int matrixW = base.width-w+1; int matrixH = base.height-h+1; int matrixSize = matrixW*matrixH; IloBoolVarArray rect{ env, matrixSize }; for ( int i = 0; i < matrixSize; ++i ) { char buf[1024]; snprintf( buf, 1024, "%dx%d_{%d,%d}", w, h, i % matrixW, i / matrixW ); rect[i].setName( buf ); } for ( int i = 0; i < matrixW; ++i ) { for ( int j = 0; j < matrixH; ++j ) { if ( !IsValidRect( i, j, w, h ) ) { model.add( rect[i + matrixW*j] == 0 ); } else { IloBoolVar product = AddProductConstraints( env, model, baseVars, i, j, w, h ); model.add( rect[i + matrixW*j] <= product ); } } } return rect; } IloExpr ConstructInclusionConstraintsAndOverlapExpr( IloEnv & env, IloModel & model, int x, int y , IloBoolVarArray const & rects, int w, int h ) { IloExpr expr{ env }; for ( int i = 0; i < w; ++i ) { for ( int j = 0; j < h; ++j ) { if ( x-i >= 0 && x-i < base.width-w+1 && y-j >= 0 && y-j < base.height-h+1 ) { model.add( blocksVars[base.index( x, y )] >= rects[x-i + (base.width-w+1)*(y-j)] ); expr += rects[x-i + (base.width-w+1)*(y-j)]; } } } return expr; } }; vector< Block > CopySubMatrix( Base const & base, int x, int y, int w, int h ) { vector< Block > res; for ( int j = y; j < y+h; ++j ) { for ( int i = x; i < x+w; ++i ) { res.push_back( base.access( i, j ) ); } } return res; } vector< Base > DivideBase( Base const & base, int numX, int numY ) { int w = base.width; int h = base.height; int wD = w / numX; int hD = h / numY; vector< Base > bases; for ( int j = 0; j < numY; ++j ) { for ( int i = 0; i < numX; ++i ) { int curX = i*wD, curY = j*hD; int curW, curH; if ( i == numX-1 ) { if ( j == numY-1 ) { curW = w-(i*wD); curH = h-(j*hD); } else { curW = w-(i*wD); curH = hD; } } else if ( j == numY-1 ) { curW = wD; curH = h-(j*hD); } else { curW = wD; curH = hD; } bases.emplace_back( CopySubMatrix( base, curX, curY, curW, curH ), curW, curH ); } } return bases; } int main( int argc, char * argv[] ) { if ( argc != 5 ) { cerr << "Usage: " << argv[0] << " <file> <outfile> [<num subdivide x> <num subdivide y>]" << endl; exit( 0 ); } Base initialBase = LoadBaseFromFile( argv[1] ); int numSubdivideX = (argc > 3 ? atoi( argv[3] ) : 1); int numSubdivideY = (argc > 4 ? atoi( argv[4] ) : 1); auto bases = DivideBase( initialBase, numSubdivideX, numSubdivideY ); vector< MISRSolver > solvers; int numIter = 0, sumScores = 0; for ( auto const & base: bases ) { solvers.emplace_back( base ); cout << "===== Iteration number: " << ++numIter << " / " << bases.size() << " ======" << endl; solvers.back().Solve(); solvers.back().PrintSolution( cout ); sumScores += solvers.back().GetBestScore(); cout << "===== Cumulative score: " << sumScores << " ======" << endl; cout << "===== Potential score: " << bases.size()/(double)numIter*sumScores << " ======\n" << endl; } cout << "Total score w/ Do Not Exists: " << sumScores + initialBase.numDoNotExists << endl; vector< Base > solvedBases; for ( auto const & solver: solvers ) { solvedBases.push_back( solver.GetSolvedBase() ); } Base endBase{ solvedBases, initialBase.width, initialBase.height }; cout << "Initial base: \n" << initialBase << "Solved base: \n" << endBase << "Score: " << sumScores << endl; return 0; }
14,507
6,186
#include "./Allocation.hpp" #include "./Element.hpp" #include "./RenderScript.hpp" #include "./Type.hpp" #include "./Script_FieldBase.hpp" namespace android::renderscript { // Fields // QJniObject forward Script_FieldBase::Script_FieldBase(QJniObject obj) : JObject(obj) {} // Constructors // Methods android::renderscript::Allocation Script_FieldBase::getAllocation() const { return callObjectMethod( "getAllocation", "()Landroid/renderscript/Allocation;" ); } android::renderscript::Element Script_FieldBase::getElement() const { return callObjectMethod( "getElement", "()Landroid/renderscript/Element;" ); } android::renderscript::Type Script_FieldBase::getType() const { return callObjectMethod( "getType", "()Landroid/renderscript/Type;" ); } void Script_FieldBase::updateAllocation() const { callMethod<void>( "updateAllocation", "()V" ); } } // namespace android::renderscript
949
353
// Andrew Naplavkov #ifndef BRIG_DETAIL_DYNAMIC_LOADING_HPP #define BRIG_DETAIL_DYNAMIC_LOADING_HPP #include <brig/detail/stringify.hpp> #ifdef _WIN32 #include <windows.h> #define BRIG_DL_LIBRARY(win, lin) LoadLibraryA(win) #define BRIG_DL_FUNCTION(lib, fun) (decltype(fun)*)GetProcAddress(lib, BRIG_STRINGIFY(fun)) #elif defined __linux__ #include <dlfcn.h> #define BRIG_DL_LIBRARY(win, lin) dlopen(lin, RTLD_LAZY) #define BRIG_DL_FUNCTION(lib, fun) (decltype(fun)*)dlsym(lib, BRIG_STRINGIFY(fun)) #endif #endif // BRIG_DETAIL_DYNAMIC_LOADING_HPP
586
275
// Qt #include <QPainter> #include <QAction> #include <QGraphicsItem> #include <QGraphicsPixmapItem> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsSceneMouseEvent> #include <QWheelEvent> #include <QPoint> #include <qmath.h> // Opencv #include <opencv2/imgproc/imgproc.hpp> // Project #include "FilterTool.h" #include "Core/LayerUtils.h" namespace Tools { //****************************************************************************** /*! \class FilterTool \brief Abstract class inherits from ImageCreationTool class and represent a base structure to filter image part under the mouse in real-time mode. Abstract method processData() should be subclassed to process input data under the mouse. Virtual method onFinalize() should be subclassed to finish the processing and send the result. The result of the filtering can be a QGraphicsItem or Core::DrawingsItem which is not owned by the class. */ //****************************************************************************** FilterTool::FilterTool(QGraphicsScene *scene, QGraphicsView *view, QObject *parent): ImageCreationTool(parent), _scene(scene), _view(view), _dataProvider(0), _cursorShape(0), _cursorShapeScale(-1), _cursorShapeZValue(1000), _size(100), _isValid(false), _opacity(0.5), _color(Qt::green) { _toolType = Type; _finalize = new QAction(tr("Finalize"), this); _finalize->setEnabled(false); connect(_finalize, SIGNAL(triggered()), this, SLOT(onFinalize())); _actions.append(_finalize); _hideShowResult = new QAction(tr("Hide result"), this); _hideShowResult->setEnabled(false); connect(_hideShowResult, SIGNAL(triggered()), this, SLOT(onHideShowResult())); _actions.append(_hideShowResult); QAction * separator = new QAction(this); separator->setSeparator(true); _actions.append(separator); _clear = new QAction(tr("Clear"), this); _clear->setEnabled(false); connect(_clear, SIGNAL(triggered()), this, SLOT(clear())); _actions.append(_clear); _isValid = _scene && _view; } //****************************************************************************** bool FilterTool::dispatch(QEvent *e, QGraphicsScene *scene) { if (!_isValid) return false; if (e->type() == QEvent::GraphicsSceneMousePress) { QGraphicsSceneMouseEvent * event = static_cast<QGraphicsSceneMouseEvent*>(e); if (event->button() == Qt::LeftButton && !_pressed && !(event->modifiers() & Qt::ControlModifier)) { // check if _drawingsItem exists if (!_drawingsItem) { // create drawings item for the current visible extent QRect wr = _view->viewport()->rect(); QRectF r = _view->mapToScene(wr).boundingRect(); if (r.width() < 2000 && r.height() < 2000) { _drawingsItem = new Core::DrawingsItem(r.width(), r.height(), QColor(Qt::transparent)); _drawingsItem->setPos(r.x(), r.y()); _drawingsItem->setZValue(_cursorShapeZValue-10); _drawingsItem->setOpacity(_opacity); // visible canvas QGraphicsRectItem * canvas = new QGraphicsRectItem(QRectF(0.0,0.0,r.width(), r.height()), _drawingsItem); canvas->setPen(QPen(Qt::white, 0)); canvas->setBrush(QBrush(QColor(127,127,127,50))); canvas->setFlag(QGraphicsItem::ItemStacksBehindParent); scene->addItem(_drawingsItem); _finalize->setEnabled(true); _clear->setEnabled(true); _hideShowResult->setEnabled(true); } else { SD_WARN("Visible zone is too large. Zoom to define smaller zone"); } } if (_drawingsItem && _cursorShape) { _pressed = true; _anchor = event->scenePos(); drawAtPoint(event->scenePos()); return true; } } } else if (e->type() == QEvent::GraphicsSceneMouseMove) { QGraphicsSceneMouseEvent * event = static_cast<QGraphicsSceneMouseEvent*>(e); if (_cursorShape) { double size = _size / qMin(_view->matrix().m11(), _view->matrix().m22()); QPointF pos = event->scenePos(); _cursorShape->setPos(pos - QPointF(0.5*size, 0.5*size)); if (_dataProvider && !_erase) { size *= _cursorShape->scale(); pos -= QPointF(0.5*size, 0.5*size); // SD_TRACE(QString("rect : %1, %2, %3, %4") // .arg(pos.x()) // .arg(pos.y()) // .arg(size) // .arg(size)); QRect r(pos.x(), pos.y(), size, size); cv::Mat data = _dataProvider->getImageData(r); if (!data.empty()) { cv::Mat out = processData(data); // SD_TRACE(QString("out : %1, %2, %3, %4") // .arg(out.rows) // .arg(out.cols) // .arg(out.channels()) // .arg(out.elemSize1())); QPixmap p = QPixmap::fromImage(QImage(out.data, out.cols, out.rows, QImage::Format_ARGB32).copy()); p = p.scaled(QSize(_size,_size)); _cursorShape->setPixmap(p); } } } if (_pressed && (event->buttons() & Qt::LeftButton) && _drawingsItem && _cursorShape) { drawAtPoint(event->scenePos()); } // Allow to process other options on mouse move. Otherwise should return true return false; } else if (e->type() == QEvent::GraphicsSceneMouseRelease) { QGraphicsSceneMouseEvent * event = static_cast<QGraphicsSceneMouseEvent*>(e); if (event->button() == Qt::LeftButton && _pressed) { _pressed=false; _anchor = QPointF(); return true; } return false; } return false; } //****************************************************************************** bool FilterTool::dispatch(QEvent *e, QWidget *viewport) { if (!_isValid) return false; if (e->type() == QEvent::Enter) { // This handle the situation when GraphicsScene was cleared between Enter and Leave events if (!_cursorShape) { createCursor(); viewport->setCursor(_cursor); } return true; } else if (e->type() == QEvent::Leave) { // This handle the situation when GraphicsScene was cleared between Enter and Leave events if (_cursorShape) { destroyCursor(); viewport->setCursor(QCursor()); } return true; } else if (e->type() == QEvent::Wheel) { QWheelEvent * event = static_cast<QWheelEvent*>(e); if (event->modifiers() & Qt::ControlModifier ) { if (_cursorShape) { // mouse has X units that covers 360 degrees. Zoom when 15 degrees is provided #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QPoint numDegrees = event->angleDelta() / 8; #else QPoint numDegrees(0,event->delta() / 8); #endif double scale = _cursorShape->scale(); if (!numDegrees.isNull()) { if (numDegrees.y() >= 15) { // make smaller scale *= 0.6667; scale = scale < 0.2 ? 0.2 : scale; } else if (numDegrees.y() <= -15) { // make larger scale *= 1.5; scale = scale > 5.0 ? 5.0 : scale; } // emit sizeChanged(_size); _cursorShape->setScale(scale); event->accept(); return true; } } } } return false; } //****************************************************************************** void FilterTool::createCursor() { // if (!_cursorShape) // { QPixmap p = QPixmap(_size,_size); p.fill(_drawingsItem ? _drawingsItem->getBackground() : Qt::transparent); QGraphicsPixmapItem * item = new QGraphicsPixmapItem(p); item->setTransformOriginPoint(0.5*_size,0.5*_size); item->setZValue(_cursorShapeZValue); item->setFlag(QGraphicsItem::ItemIgnoresTransformations); item->setOpacity(_opacity); QGraphicsRectItem * br = new QGraphicsRectItem(item->boundingRect(), item); br->setZValue(+1); br->setPen(QPen(Qt::green, 0)); br->setBrush(Qt::transparent); br->setFlag(QGraphicsItem::ItemIgnoresParentOpacity); _cursorShape = item; if (_cursorShapeScale>0) _cursorShape->setScale(_cursorShapeScale); _scene->addItem(_cursorShape); // } } //****************************************************************************** void FilterTool::destroyCursor() { _cursorShapeScale = _cursorShape->scale(); QGraphicsScene * scene = _cursorShape->scene(); if (scene) { scene->removeItem(_cursorShape); delete _cursorShape; _cursorShape = 0; } } //****************************************************************************** void FilterTool::onHideShowResult() { if (_drawingsItem->isVisible()) { _drawingsItem->setVisible(false); _hideShowResult->setText(tr("Show result")); } else { _drawingsItem->setVisible(true); _hideShowResult->setText(tr("Hide result")); } } //****************************************************************************** void FilterTool::onFinalize() { _drawingsItem = 0; _finalize->setEnabled(false); _clear->setEnabled(false); _hideShowResult->setEnabled(false); } //****************************************************************************** void FilterTool::clear() { if (_cursorShape) { destroyCursor(); _cursorShapeScale = -1.0; } if (_drawingsItem) { _scene->removeItem(_drawingsItem); delete _drawingsItem; } FilterTool::onFinalize(); } //****************************************************************************** void FilterTool::setErase(bool erase) { ImageCreationTool::setErase(erase); } //****************************************************************************** void FilterTool::drawAtPoint(const QPointF &pos) { // check if the rectangle to paint is in the drawingItem zone: QRectF r = _drawingsItem->boundingRect(); r.moveTo(_drawingsItem->pos()); double size = _size * _cursorShape->scale() / qMin(_view->matrix().m11(), _view->matrix().m22()); QRectF r2 = QRectF(pos.x()-size*0.5, pos.y()-size*0.5, size, size); if (r.intersects(QRectF(pos.x()-_size*0.5, pos.y()-_size*0.5, _size, _size))) { r2.translate(-_drawingsItem->scenePos()); QPainter p(&_drawingsItem->getImage()); p.setCompositionMode((QPainter::CompositionMode)_mode); QPixmap px = _cursorShape->pixmap(); p.drawPixmap(r2, px, QRectF(0.0,0.0,px.width(),px.height())); r2=r2.adjusted(-size*0.25, -size*0.25, size*0.25, size*0.25); _drawingsItem->update(r2); } } //****************************************************************************** }
12,579
3,640
#include "Player.hpp" #include <Plinth/Sfml/Generic.hpp> namespace { const pl::Vector2d playerSize{ 64.0, 32.0 }; constexpr double initialSpeed{ 300.0 }; const double minimumPosition{ 0.0 + playerSize.x / 2.0 }; } Player::Player(const sf::RenderWindow& window, const double dt, const Graphics& graphics) : m_dt(dt) , m_speed(initialSpeed) , m_size(playerSize) , m_positionLimits({ minimumPosition, window.getSize().x - playerSize.x / 2.0 }) , m_position(m_positionLimits.min) { } void Player::move(const Direction direction) { double movement; switch (direction) { case Direction::Left: movement = -1.0; break; case Direction::Right: movement = 1.0; break; default: movement = 0.0; } m_position += movement * m_speed * m_dt; m_position = m_positionLimits.clamp(m_position); } void Player::reset() { m_position = minimumPosition; m_speed = initialSpeed; } double Player::getPosition() const { return m_position; } pl::Vector2d Player::getSize() const { return m_size; }
1,005
398
/* * Copyright (C) 2012 Google 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sky/engine/config.h" #include "sky/engine/core/inspector/InjectedScriptManager.h" #include "bindings/core/v8/V8InjectedScriptHost.h" #include "bindings/core/v8/V8Window.h" #include "sky/engine/bindings/core/v8/BindingSecurity.h" #include "sky/engine/bindings/core/v8/ScopedPersistent.h" #include "sky/engine/bindings/core/v8/ScriptDebugServer.h" #include "sky/engine/bindings/core/v8/ScriptValue.h" #include "sky/engine/bindings/core/v8/V8Binding.h" #include "sky/engine/bindings/core/v8/V8ObjectConstructor.h" #include "sky/engine/bindings/core/v8/V8ScriptRunner.h" #include "sky/engine/core/frame/LocalDOMWindow.h" #include "sky/engine/core/inspector/InjectedScriptHost.h" #include "sky/engine/wtf/RefPtr.h" namespace blink { InjectedScriptManager::CallbackData* InjectedScriptManager::createCallbackData(InjectedScriptManager* injectedScriptManager) { OwnPtr<InjectedScriptManager::CallbackData> callbackData = adoptPtr(new InjectedScriptManager::CallbackData()); InjectedScriptManager::CallbackData* callbackDataPtr = callbackData.get(); callbackData->injectedScriptManager = injectedScriptManager; m_callbackDataSet.add(callbackData.release()); return callbackDataPtr; } void InjectedScriptManager::removeCallbackData(InjectedScriptManager::CallbackData* callbackData) { ASSERT(m_callbackDataSet.contains(callbackData)); m_callbackDataSet.remove(callbackData); } static v8::Local<v8::Object> createInjectedScriptHostV8Wrapper(PassRefPtr<InjectedScriptHost> host, InjectedScriptManager* injectedScriptManager, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(host); v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toScriptWrappableBase(host.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; // Create a weak reference to the v8 wrapper of InspectorBackend to deref // InspectorBackend when the wrapper is garbage collected. InjectedScriptManager::CallbackData* callbackData = injectedScriptManager->createCallbackData(injectedScriptManager); callbackData->host = host.get(); callbackData->handle.set(isolate, wrapper); callbackData->handle.setWeak(callbackData, &InjectedScriptManager::setWeakCallback); V8DOMWrapper::setNativeInfo(wrapper, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toScriptWrappableBase(host.get())); ASSERT(V8DOMWrapper::isDOMWrapper(wrapper)); return wrapper; } ScriptValue InjectedScriptManager::createInjectedScript(const String& scriptSource, ScriptState* inspectedScriptState, int id) { v8::Isolate* isolate = inspectedScriptState->isolate(); ScriptState::Scope scope(inspectedScriptState); // Call custom code to create InjectedScripHost wrapper specific for the context // instead of calling toV8() that would create the // wrapper in the current context. // FIXME: make it possible to use generic bindings factory for InjectedScriptHost. v8::Local<v8::Object> scriptHostWrapper = createInjectedScriptHostV8Wrapper(m_injectedScriptHost, this, inspectedScriptState->context()->Global(), inspectedScriptState->isolate()); if (scriptHostWrapper.IsEmpty()) return ScriptValue(); // Inject javascript into the context. The compiled script is supposed to evaluate into // a single anonymous function(it's anonymous to avoid cluttering the global object with // inspector's stuff) the function is called a few lines below with InjectedScriptHost wrapper, // injected script id and explicit reference to the inspected global object. The function is expected // to create and configure InjectedScript instance that is going to be used by the inspector. v8::Local<v8::Value> value = V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, scriptSource), isolate); ASSERT(!value.IsEmpty()); ASSERT(value->IsFunction()); v8::Local<v8::Object> windowGlobal = inspectedScriptState->context()->Global(); v8::Handle<v8::Value> info[] = { scriptHostWrapper, windowGlobal, v8::Number::New(inspectedScriptState->isolate(), id) }; v8::Local<v8::Value> injectedScriptValue = V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(value), windowGlobal, WTF_ARRAY_LENGTH(info), info, inspectedScriptState->isolate()); return ScriptValue(inspectedScriptState, injectedScriptValue); } void InjectedScriptManager::setWeakCallback(const v8::WeakCallbackData<v8::Object, InjectedScriptManager::CallbackData>& data) { InjectedScriptManager::CallbackData* callbackData = data.GetParameter(); callbackData->injectedScriptManager->removeCallbackData(callbackData); } } // namespace blink
6,323
1,940
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "diffpatch.h" #include <cstdlib> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <vector> #include "openssl/sha.h" namespace updatepatch { int32_t WriteDataToFile(const std::string &fileName, const std::vector<uint8_t> &data, size_t dataSize) { std::ofstream patchFile(fileName, std::ios::out | std::ios::binary); PATCH_CHECK(patchFile, return -1, "Failed to open %s", fileName.c_str()); patchFile.write(reinterpret_cast<const char*>(data.data()), dataSize); patchFile.close(); return PATCH_SUCCESS; } int32_t PatchMapFile(const std::string &fileName, MemMapInfo &info) { int32_t file = open(fileName.c_str(), O_RDONLY); PATCH_CHECK(file >= 0, return -1, "Failed to open file %s", fileName.c_str()); struct stat st {}; int32_t ret = fstat(file, &st); PATCH_CHECK(ret >= 0, close(file); return ret, "Failed to fstat"); info.memory = static_cast<uint8_t*>(mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, file, 0)); PATCH_CHECK(info.memory != nullptr, close(file); return -1, "Failed to memory map"); info.length = st.st_size; close(file); return PATCH_SUCCESS; } std::string GeneraterBufferHash(const BlockBuffer &buffer) { SHA256_CTX sha256Ctx; SHA256_Init(&sha256Ctx); SHA256_Update(&sha256Ctx, buffer.buffer, buffer.length); std::vector<uint8_t> digest(SHA256_DIGEST_LENGTH); SHA256_Final(digest.data(), &sha256Ctx); return ConvertSha256Hex({ digest.data(), SHA256_DIGEST_LENGTH }); } std::string ConvertSha256Hex(const BlockBuffer &buffer) { const std::string hexChars = "0123456789abcdef"; std::string haxSha256 = ""; unsigned int c; for (size_t i = 0; i < buffer.length; ++i) { auto d = buffer.buffer[i]; c = (d >> SHIFT_RIGHT_FOUR_BITS) & 0xf; // last 4 bits haxSha256.push_back(hexChars[c]); haxSha256.push_back(hexChars[d & 0xf]); } return haxSha256; } } // namespace updatepatch
2,693
1,007
#include <opencv2/highgui/highgui.hpp> #include <algorithm> #include <ros/ros.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/transforms.h> #include <pcl/io/pcd_io.h> #include <opencv2/opencv.hpp> #include <cv_bridge/cv_bridge.h> #include <image_geometry/pinhole_camera_model.h> #include <sensor_msgs/image_encodings.h> #include <geometry_msgs/TransformStamped.h> #include <tf2/convert.h> #include <tf2/transform_datatypes.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2_eigen/tf2_eigen.h> #include <std_msgs/String.h> #include <anchor_msgs/ObjectArray.h> #include <anchor_msgs/ClusterArray.h> #include <anchor_msgs/MovementArray.h> #include <hand_tracking/TrackingService.h> #include <object_segmentation/object_segmentation.hpp> #include <pcl_ros/point_cloud.h> // ------------------------ // Public functions // ------------------------- ObjectSegmentation::ObjectSegmentation(ros::NodeHandle nh, bool useApprox) : nh_(nh) , it_(nh) , priv_nh_("~") , tf2_listener_(buffer_) , useApprox_(useApprox) , queueSize_(5) , display_image_(false) { // Subscribers / publishers //image_transport::TransportHints hints(useCompressed ? "compressed" : "raw"); //image_sub_ = new image_transport::SubscriberFilter( it_, topicColor, "image", hints); image_sub_ = new image_transport::SubscriberFilter( it_, "image", queueSize_); camera_info_sub_ = new message_filters::Subscriber<sensor_msgs::CameraInfo>( nh_, "camera_info", queueSize_); cloud_sub_ = new message_filters::Subscriber<sensor_msgs::PointCloud2>( nh_, "cloud", queueSize_); obj_pub_ = nh_.advertise<anchor_msgs::ObjectArray>("/objects/raw", queueSize_); cluster_pub_ = nh_.advertise<anchor_msgs::ClusterArray>("/objects/clusters", queueSize_); move_pub_ = nh_.advertise<anchor_msgs::MovementArray>("/movements", queueSize_); // Hand tracking _tracking_client = nh_.serviceClient<hand_tracking::TrackingService>("/hand_tracking"); // Used for the web interface display_trigger_sub_ = nh_.subscribe("/display/trigger", 1, &ObjectSegmentation::triggerCb, this); display_image_pub_ = it_.advertise("/display/image", 1); // Set up sync policies if(useApprox) { syncApproximate_ = new message_filters::Synchronizer<ApproximateSyncPolicy>(ApproximateSyncPolicy(queueSize_), *image_sub_, *camera_info_sub_, *cloud_sub_); syncApproximate_->registerCallback( boost::bind( &ObjectSegmentation::segmentationCb, this, _1, _2, _3)); } else { syncExact_ = new message_filters::Synchronizer<ExactSyncPolicy>(ExactSyncPolicy(queueSize_), *image_sub_, *camera_info_sub_, *cloud_sub_); syncExact_->registerCallback( boost::bind( &ObjectSegmentation::segmentationCb, this, _1, _2, _3)); } // Read the base frame priv_nh_.param( "base_frame", base_frame_, std::string("base_link")); // Read segmentation parameters int type, size; double th, factor; if( priv_nh_.getParam("compare_type", type) ) { if( type >= 0 && type <= 3 ) { this->seg_.setComparatorType(type); } else { ROS_WARN("[ObjectSegmentation::ObjectSegmentation] Not a valid comparator type, using default instead."); } } if( priv_nh_.getParam("plane_min_size", size) ) { this->seg_.setPlaneMinSize (size); } if( priv_nh_.getParam("cluster_min_size", size) ) { this->seg_.setClusterMinSize (size); } if( priv_nh_.getParam("cluster_min_size", size) ) { this->seg_.setClusterMinSize (size); } if( priv_nh_.getParam("angular_th", th) ) { this->seg_.setAngularTh (th); } if( priv_nh_.getParam("distance_th", th) ) { this->seg_.setDistanceTh (th); } if( priv_nh_.getParam("refine_factor", factor) ) { this->seg_.setRefineFactor (factor); } // Read spatial thresholds (default values = no filtering) this->priv_nh_.param<double>( "min_x", this->min_x_, 0.0); this->priv_nh_.param<double>( "max_x", this->max_x_, -1.0); this->priv_nh_.param<double>( "min_y", this->min_y_, 0.0); this->priv_nh_.param<double>( "max_y", this->max_y_, -1.0); this->priv_nh_.param<double>( "min_z", this->min_z_, 0.0); this->priv_nh_.param<double>( "max_z", this->max_z_, -1.0); // Read toggle paramter for displayig the result (OpenCV window view) this->priv_nh_.param<bool>( "display_window", display_window_, false); } ObjectSegmentation::~ObjectSegmentation() { if(useApprox_) { delete syncApproximate_; } else { delete syncExact_; } delete image_sub_; delete camera_info_sub_; delete cloud_sub_; //delete tf_listener_; } void ObjectSegmentation::spin() { ros::Rate rate(100); while(ros::ok()) { // OpenCV window for display if( this->display_window_ ) { if( !this->result_img_.empty() ) { cv::imshow( "Segmented clusters...", this->result_img_ ); } // Wait for a keystroke in the window char key = cv::waitKey(1); if( key == 27 || key == 'Q' || key == 'q' ) { break; } } ros::spinOnce(); rate.sleep(); } } void ObjectSegmentation::triggerCb( const std_msgs::String::ConstPtr &msg) { this->display_image_ = (msg->data == "segmentation") ? true : false; ROS_WARN("Got trigger: %s", msg->data.c_str()); } // -------------------------- // Callback function (ROS) // -------------------------- void ObjectSegmentation::segmentationCb( const sensor_msgs::Image::ConstPtr image_msg, const sensor_msgs::CameraInfo::ConstPtr camera_info_msg, const sensor_msgs::PointCloud2::ConstPtr cloud_msg) { // Get the transformation (as geoemtry message) geometry_msgs::TransformStamped tf_forward, tf_inverse; try{ tf_forward = this->buffer_.lookupTransform( base_frame_, cloud_msg->header.frame_id, cloud_msg->header.stamp); tf_inverse = this->buffer_.lookupTransform( cloud_msg->header.frame_id, base_frame_, cloud_msg->header.stamp); } catch (tf2::TransformException &ex) { ROS_WARN("[ObjectSegmentation::callback] %s" , ex.what()); return; } // Get the transformation (as tf/tf2) //tf2::Stamped<tf2::Transform> transform2; //tf2::fromMsg(tf_forward, transform2); //tf::Vector3d tf::Transform transform = tf::Transform(transform2.getOrigin(), transform2.getRotation()); //tf::Transform transfrom = tf::Transform(tf_forward.transfrom); // Read the cloud pcl::PointCloud<segmentation::Point>::Ptr raw_cloud_ptr (new pcl::PointCloud<segmentation::Point>); pcl::fromROSMsg (*cloud_msg, *raw_cloud_ptr); // Transform the cloud to the world frame pcl::PointCloud<segmentation::Point>::Ptr transformed_cloud_ptr (new pcl::PointCloud<segmentation::Point>); //pcl_ros::transformPointCloud( *raw_cloud_ptr, *transformed_cloud_ptr, transform); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_forward.transform).matrix(), *raw_cloud_ptr, *transformed_cloud_ptr); // Filter the transformed point cloud this->filter (transformed_cloud_ptr); // ---------------------- pcl::PointCloud<segmentation::Point>::Ptr original_cloud_ptr (new pcl::PointCloud<segmentation::Point>); //pcl_ros::transformPointCloud( *transformed_cloud_ptr, *original_cloud_ptr, transform.inverse()); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_inverse.transform).matrix(), *raw_cloud_ptr, *transformed_cloud_ptr); // Read the RGB image cv::Mat img; cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy( image_msg, image_msg->encoding); cv_ptr->image.copyTo(img); } catch (cv_bridge::Exception& ex){ ROS_ERROR("[ObjectSegmentation::callback]: Failed to convert image."); return; } // Saftey check if( img.empty() ) { return; } // TEST // -------------------------------------- // Downsample the orignal point cloud int scale = 2; pcl::PointCloud<segmentation::Point>::Ptr downsampled_cloud_ptr( new pcl::PointCloud<segmentation::Point> ); downsampled_cloud_ptr->width = original_cloud_ptr->width / scale; downsampled_cloud_ptr->height = original_cloud_ptr->height / scale; downsampled_cloud_ptr->resize( downsampled_cloud_ptr->width * downsampled_cloud_ptr->height ); for( uint i = 0, k = 0; i < original_cloud_ptr->width; i += scale, k++ ) { for( uint j = 0, l = 0; j < original_cloud_ptr->height; j += scale, l++ ) { downsampled_cloud_ptr->at(k,l) = original_cloud_ptr->at(i,j); } } // ----------- // Convert to grayscale and back (for display purposes) if( display_image_ || display_window_) { cv::cvtColor( img, this->result_img_, CV_BGR2GRAY); cv::cvtColor( this->result_img_, this->result_img_, CV_GRAY2BGR); this->result_img_.convertTo( this->result_img_, -1, 1.0, 50); } // Camera information image_geometry::PinholeCameraModel cam_model; cam_model.fromCameraInfo(camera_info_msg); // Make a remote call to get the 'hand' (or glove) //double t = this->timerStart(); std::map< int, pcl::PointIndices > hand_indices; std::vector< std::vector<cv::Point> > hand_contours; hand_tracking::TrackingService srv; srv.request.image = *image_msg; if( this->_tracking_client.call(srv)) { // Get the hand mask contour for( int i = 0; i < srv.response.contours.size(); i++) { std::vector<cv::Point> contour; for( uint j = 0; j < srv.response.contours[i].contour.size(); j++) { cv::Point p( srv.response.contours[i].contour[j].x, srv.response.contours[i].contour[j].y ); contour.push_back(p); } hand_contours.push_back(contour); } // Filter the indices of all 3D points within the hand contour int key = 0; for ( int i = 0; i < hand_contours.size(); i++) { cv::Mat mask( img.size(), CV_8U, cv::Scalar(0)); cv::drawContours( mask, hand_contours, i, cv::Scalar(255), -1); uint idx = 0; pcl::PointIndices point_idx; BOOST_FOREACH ( const segmentation::Point pt, downsampled_cloud_ptr->points ) { tf2::Vector3 trans_pt( pt.x, pt.y, pt.z); //tf2::doTransform( trans_pt, trans_pt, tf_forward); trans_pt = transform * trans_pt; if( ( trans_pt.x() > this->min_x_ && trans_pt.x() < this->max_x_ ) && ( trans_pt.y() > this->min_y_ && trans_pt.y() < this->max_y_ ) && ( trans_pt.z() > this->min_z_ && trans_pt.z() < this->max_z_ ) ) { cv::Point3d pt_3d( pt.x, pt.y, pt.z); cv::Point pt_2d = cam_model.project3dToPixel(pt_3d); if ( pt_2d.y >= 0 && pt_2d.y < mask.rows && pt_2d.x >= 0 && pt_2d.x < mask.cols ) { if( mask.at<uchar>( pt_2d.y, pt_2d.x) != 0 ) { point_idx.indices.push_back(idx); } } } idx++; } //ROS_WARN("[TEST] Points: %d", (int)point_idx.indices.size()); if( point_idx.indices.size() >= this->seg_.getClusterMinSize() ) hand_indices.insert( std::pair< int, pcl::PointIndices>( key, point_idx) ); key++; } } //this->timerEnd( t, "Hand detection"); // Cluster cloud into objects // ---------------------------------------- std::vector<pcl::PointIndices> cluster_indices; //this->seg_.clusterOrganized(transformed_cloud_ptr, cluster_indices); //this->seg_.clusterOrganized(raw_cloud_ptr, cluster_indices); // TEST - Use downsampled cloud instead // ----------------------------------------- //t = this->timerStart(); this->seg_.clusterOrganized( downsampled_cloud_ptr, cluster_indices); //this->timerEnd( t, "Clustering"); // Post-process the segmented clusters (filter out the 'hand' points) //t = this->timerStart(); if( !hand_indices.empty() ) { for( uint i = 0; i < hand_indices.size(); i++ ) { for ( uint j = 0; j < cluster_indices.size (); j++) { for( auto &idx : hand_indices[i].indices) { auto ite = std::find (cluster_indices[j].indices.begin(), cluster_indices[j].indices.end(), idx); if( ite != cluster_indices[j].indices.end() ) { cluster_indices[j].indices.erase(ite); } } if( cluster_indices[j].indices.size() < this->seg_.getClusterMinSize() ) cluster_indices.erase( cluster_indices.begin() + j ); } } // Add the 'hand' indecies to the reaming cluster indices for( auto &ite : hand_indices ) { cluster_indices.insert( cluster_indices.begin() + ite.first, ite.second ); } //ROS_INFO("Clusters: %d (include a 'hand' cluster)", (int)cluster_indices.size()); } else { //ROS_INFO("Clusters: %d", (int)cluster_indices.size()); } //this->timerEnd( t, "Post-processing"); /* ROS_INFO("Clusters: \n"); for (size_t i = 0; i < cluster_indices.size (); i++) { if( hand_indices.find(i) != hand_indices.end() ) ROS_INFO("Hand size: %d", (int)cluster_indices[i].indices.size()); else ROS_INFO("Object size: %d", (int)cluster_indices[i].indices.size()); } ROS_INFO("-----------"); */ // Process all segmented clusters (including the 'hand' cluster) if( !cluster_indices.empty() ) { // Image & Cloud output anchor_msgs::ClusterArray clusters; anchor_msgs::ObjectArray objects; anchor_msgs::MovementArray movements; objects.header = cloud_msg->header; objects.image = *image_msg; objects.info = *camera_info_msg; objects.transform = tf_forward; /* // Store the inverse transformation tf::Quaternion tf_quat = transform.inverse().getRotation(); objects.transform.rotation.x = tf_quat.x(); objects.transform.rotation.y = tf_quat.y(); objects.transform.rotation.z = tf_quat.z(); objects.transform.rotation.w = tf_quat.w(); tf::Vector3 tf_vec = transform.inverse().getOrigin(); objects.transform.translation.x = tf_vec.getX(); objects.transform.translation.y = tf_vec.getY(); objects.transform.translation.z = tf_vec.getZ(); */ // Process the segmented clusters int sz = 5; cv::Mat kernel = cv::getStructuringElement( cv::BORDER_CONSTANT, cv::Size( sz, sz), cv::Point(-1,-1) ); for (size_t i = 0; i < cluster_indices.size (); i++) { // Get the cluster pcl::PointCloud<segmentation::Point>::Ptr cluster_ptr (new pcl::PointCloud<segmentation::Point>); //pcl::copyPointCloud( *original_cloud_ptr, cluster_indices[i], *cluster_ptr); // TEST - Use downsampled cloud instead // ----------------------------------------- pcl::copyPointCloud( *downsampled_cloud_ptr, cluster_indices[i], *cluster_ptr); //std::cout << cluster_ptr->points.size() << std::endl; if( cluster_ptr->points.empty() ) continue; // Post-process the cluster try { // Create the cluster image cv::Mat cluster_img( img.size(), CV_8U, cv::Scalar(0)); BOOST_FOREACH ( const segmentation::Point pt, cluster_ptr->points ) { cv::Point3d pt_cv( pt.x, pt.y, pt.z); cv::Point2f p = cam_model.project3dToPixel(pt_cv); circle( cluster_img, p, 2, cv::Scalar(255), -1, 8, 0 ); } // Apply morphological operations the cluster image cv::dilate( cluster_img, cluster_img, kernel); cv::erode( cluster_img, cluster_img, kernel); // Find the contours of the cluster std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours( cluster_img, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // Get the contour of the convex hull std::vector<cv::Point> contour = getLargetsContour( contours ); // Create and add the object output message if( contour.size() > 0 ) { anchor_msgs::Object obj; for( size_t j = 0; j < contour.size(); j++) { anchor_msgs::Point2d p; p.x = contour[j].x; p.y = contour[j].y; obj.visual.border.contour.push_back(p); } // Add segmented object to display image img.copyTo( this->result_img_, cluster_img); // Draw the contour (for display) cv::Scalar color = cv::Scalar( 32, 84, 233); // Orange //cv::Scalar color = cv::Scalar( 0, 0, 233); // Red //cv::Scalar color = cv::Scalar::all(64); // Dark gray // Check if we have a hand countour if( hand_indices.find(i) != hand_indices.end() ) { color = cv::Scalar( 0, 233, 0); // Green } cv::drawContours( this->result_img_, contours, -1, color, 1); // Transfrom the the cloud once again //tf2::doTransform( *cluster_ptr, *cluster_ptr, tf_forward); //pcl_ros::transformPointCloud( *cluster_ptr, *cluster_ptr, transform); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_forward.transform).matrix(), *cluster_ptr, *cluster_ptr); // 1. Extract the position geometry_msgs::PoseStamped pose; pose.header.stamp = cloud_msg->header.stamp; segmentation::getOrientedPosition( cluster_ptr, pose.pose); obj.position.data = pose; // Add the position to the movement array movements.movements.push_back(pose); //std::cout << "Position: [" << obj.position.data.pose.position.x << ", " << obj.position.data.pose.position.y << ", " << obj.position.data.pose.position.z << "]" << std::endl; // 2. Extract the shape segmentation::getSize( cluster_ptr, obj.size.data ); // Ground size symbols std::vector<double> data = { obj.size.data.x, obj.size.data.y, obj.size.data.z}; std::sort( data.begin(), data.end(), std::greater<double>()); if( data.front() <= 0.1 ) { // 0 - 15 [cm] = small obj.size.symbols.push_back("small"); } else if( data.front() <= 0.20 ) { // 16 - 30 [cm] = medium obj.size.symbols.push_back("medium"); } else { // > 30 [cm] = large obj.size.symbols.push_back("large"); } if( data[0] < data[1] * 1.1 ) { obj.size.symbols.push_back("square"); } else { obj.size.symbols.push_back("rectangle"); if( data[0] > data[1] * 1.5 ) { obj.size.symbols.push_back("long"); } else { obj.size.symbols.push_back("short"); } } // TEST // --------------------------------------- // Attempt to filter out glitchs if ( obj.size.data.z < 0.02 ) continue; // Add the object to the object array message objects.objects.push_back(obj); /* Eigen::Vector4f centroid; pcl::compute3DCentroid ( transformed_cloud, centroid); if( centroid[0] > 0.0 && centroid[1] < 0.5 && centroid[1] > -0.5 ) std::cout << "Position [" << centroid[0] << ", " << centroid[1] << ", " << centroid[2] << "]" << std::endl; */ // Add the (un-transformed) cluster to the array message geometry_msgs::Pose center; segmentation::getPosition( cluster_ptr, center ); clusters.centers.push_back(center); sensor_msgs::PointCloud2 cluster; pcl::toROSMsg( *cluster_ptr, cluster ); clusters.clusters.push_back(cluster); } } catch( cv::Exception &exc ) { ROS_ERROR("[object_recognition] CV processing error: %s", exc.what() ); } } //std::cout << "---" << std::endl; // Publish the "segmented" image if( display_image_ ) { cv_ptr->image = this->result_img_; cv_ptr->encoding = "bgr8"; display_image_pub_.publish(cv_ptr->toImageMsg()); } // Publish the object array if( !objects.objects.empty() || !clusters.clusters.empty() ) { // ROS_INFO("Publishing: %d objects.", (int)objects.objects.size()); obj_pub_.publish(objects); cluster_pub_.publish(clusters); move_pub_.publish(movements); } } } void ObjectSegmentation::filter( pcl::PointCloud<segmentation::Point>::Ptr &cloud_ptr ) { // Filter the transformed point cloud if( cloud_ptr->isOrganized ()) { segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "x", this->min_x_, this->max_x_); segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "y", this->min_y_, this->max_y_); segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "z", this->min_z_, this->max_z_); /* for( auto &p: cloud_ptr->points) { if( !( p.x > this->min_x_ && p.x < this->max_x_ ) || !( p.y > this->min_y_ && p.y < this->max_y_ ) || !( p.z > this->min_z_ && p.z < this->max_z_ ) ) { p.x = std::numeric_limits<double>::quiet_NaN(); //infinity(); p.y = std::numeric_limits<double>::quiet_NaN(); p.z = std::numeric_limits<double>::quiet_NaN(); p.b = p.g = p.r = 0; } } */ } else { pcl::PointCloud<segmentation::Point>::Ptr result_ptr (new pcl::PointCloud<segmentation::Point>); for( auto &p: cloud_ptr->points) { if( ( p.x > this->min_x_ && p.x < this->max_x_ ) && ( p.y > this->min_y_ && p.y < this->max_y_ ) && ( p.z > this->min_z_ && p.z < this->max_z_ ) ) { result_ptr->points.push_back (p); } } cloud_ptr.swap (result_ptr); } } std::vector<cv::Point> ObjectSegmentation::getLargetsContour( std::vector<std::vector<cv::Point> > contours ) { std::vector<cv::Point> result = contours.front(); for ( size_t i = 1; i< contours.size(); i++) if( contours[i].size() > result.size() ) result = contours[i]; return result; } std::vector<cv::Point> ObjectSegmentation::contoursConvexHull( std::vector<std::vector<cv::Point> > contours ) { std::vector<cv::Point> result; std::vector<cv::Point> pts; for ( size_t i = 0; i< contours.size(); i++) for ( size_t j = 0; j< contours[i].size(); j++) pts.push_back(contours[i][j]); cv::convexHull( pts, result ); return result; } // Detect a 'hand'/'glove' object based on color segmentation std::vector<cv::Point> ObjectSegmentation::handDetection( cv::Mat &img ) { cv::Mat hsv_img; int sz = 5; // Convert to HSV color space cv::cvtColor( img, hsv_img, cv::COLOR_BGR2HSV); // Pre-process the image by blur cv::blur( hsv_img, hsv_img, cv::Size( sz, sz)); // Extrace binary mask cv::Mat mask; cv::inRange( hsv_img, cv::Scalar( 31, 68, 141), cv::Scalar( 47, 255, 255), mask); // Post-process the threshold image cv::Mat kernel = cv::getStructuringElement( cv::BORDER_CONSTANT, cv::Size( sz, sz), cv::Point(-1,-1) ); cv::dilate( mask, mask, kernel); cv::erode( mask, mask, kernel); // Find the contours std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours( mask, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // Filter the contoruse based on size std::vector<std::vector<cv::Point> > result; for ( int i = 0; i < contours.size(); i++) { if ( cv::contourArea(contours[i]) > 500 ) { result.push_back(contours[i]); } } return result[0]; } // Timer functions double ObjectSegmentation::timerStart() { return (double)cv::getTickCount(); } void ObjectSegmentation::timerEnd( double t, std::string msg) { t = ((double)cv::getTickCount() - t) / (double)cv::getTickFrequency(); ROS_INFO("[Timer] %s: %.4f (s)", msg.c_str(), t); } // ---------------------- // Main function // ------------------ int main(int argc, char **argv) { ros::init(argc, argv, "object_segmentation_node"); ros::NodeHandle nh; // Saftey check if(!ros::ok()) { return 0; } ObjectSegmentation node(nh); node.spin(); ros::shutdown(); return 0; }
22,899
8,586
// ------------------------------------ // #include "SuperContainer.h" #include "Common.h" #include "DualView.h" using namespace DV; // ------------------------------------ // //#define SUPERCONTAINER_RESIZE_REFLOW_CHECK_ONLY_FIRST_ROW SuperContainer::SuperContainer() : Gtk::ScrolledWindow(), View(get_hadjustment(), get_vadjustment()) { _CommonCtor(); } SuperContainer::SuperContainer( _GtkScrolledWindow* widget, Glib::RefPtr<Gtk::Builder> builder) : Gtk::ScrolledWindow(widget), View(get_hadjustment(), get_vadjustment()) { _CommonCtor(); } void SuperContainer::_CommonCtor() { add(View); View.add(Container); View.show(); Container.show(); PositionIndicator.property_width_request() = 2; PositionIndicator.set_orientation(Gtk::ORIENTATION_VERTICAL); PositionIndicator.get_style_context()->add_class("PositionIndicator"); signal_size_allocate().connect(sigc::mem_fun(*this, &SuperContainer::_OnResize)); signal_button_press_event().connect( sigc::mem_fun(*this, &SuperContainer::_OnMouseButtonPressed)); // Both scrollbars need to be able to appear, otherwise the width cannot be reduced // so that wrapping occurs set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); } SuperContainer::~SuperContainer() { Clear(); } // ------------------------------------ // void SuperContainer::Clear(bool deselect /*= false*/) { DualView::IsOnMainThreadAssert(); // This could be made more efficient if(deselect) DeselectAllItems(); // This will delete all the widgets // Positions.clear(); _PositionIndicator(); LayoutDirty = false; } // ------------------------------------ // void SuperContainer::UpdatePositioning() { if(!LayoutDirty) return; LayoutDirty = false; WidestRow = Margin; if(Positions.empty()) { _PositionIndicator(); return; } int32_t CurrentRow = Margin; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(WidestRow < CurrentRow) WidestRow = CurrentRow; CurrentRow = position.X; CurrentY = position.Y; } CurrentRow += position.Width + Padding; _ApplyWidgetPosition(position); } // Last row needs to be included, too // if(WidestRow < CurrentRow) WidestRow = CurrentRow; // Add margin WidestRow += Margin; _PositionIndicator(); } void SuperContainer::UpdateRowWidths() { WidestRow = Margin; int32_t CurrentRow = Margin; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(WidestRow < CurrentRow) WidestRow = CurrentRow; CurrentRow = position.X; CurrentY = position.Y; } CurrentRow += position.Width + Padding; } // Last row needs to be included, too // if(WidestRow < CurrentRow) WidestRow = CurrentRow; // Add margin WidestRow += Margin; } // ------------------------------------ // size_t SuperContainer::CountRows() const { size_t count = 0; int32_t CurrentY = -1; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.Y != CurrentY) { ++count; CurrentY = position.Y; } } return count; } size_t SuperContainer::CountItems() const { size_t count = 0; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; ++count; } return count; } // ------------------------------------ // size_t SuperContainer::CountSelectedItems() const { size_t count = 0; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget->IsSelected()) ++count; } return count; } void SuperContainer::DeselectAllItems() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Deselect(); } } void SuperContainer::SelectAllItems() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Select(); } } void SuperContainer::DeselectAllExcept(const ListItem* item) { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget.get() == item) continue; position.WidgetToPosition->Widget->Deselect(); } } void SuperContainer::DeselectFirstItem() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget->IsSelected()) { position.WidgetToPosition->Widget->Deselect(); return; } } } void SuperContainer::SelectFirstItems(int count) { int selected = 0; for(auto& position : Positions) { // If enough are selected stop if(selected >= count) break; // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Select(); ++selected; } } void SuperContainer::SelectNextItem() { bool select = false; for(auto iter = Positions.begin(); iter != Positions.end(); ++iter) { auto& position = *iter; // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(select == true) { position.WidgetToPosition->Widget->Select(); DeselectAllExcept(position.WidgetToPosition->Widget.get()); break; } if(position.WidgetToPosition->Widget->IsSelected()) { select = true; } } if(!select) { // None selected // SelectFirstItem(); } } void SuperContainer::SelectPreviousItem() { bool select = false; for(auto iter = Positions.rbegin(); iter != Positions.rend(); ++iter) { auto& position = *iter; // When reversing we can't stop when the tailing empty slots are reached if(!position.WidgetToPosition) continue; if(select == true) { position.WidgetToPosition->Widget->Select(); DeselectAllExcept(position.WidgetToPosition->Widget.get()); break; } if(position.WidgetToPosition->Widget->IsSelected()) { select = true; } } if(!select) { // None selected // SelectFirstItem(); } } void SuperContainer::ShiftSelectTo(const ListItem* item) { // Find first non-matching item to start from size_t selectStart = 0; // And also where item is size_t itemsPosition = 0; for(size_t i = 0; i < Positions.size(); ++i) { auto& position = Positions[i]; if(!position.WidgetToPosition) continue; if(position.WidgetToPosition->Widget.get() == item) { itemsPosition = i; } else if(selectStart == 0 && position.WidgetToPosition->Widget->IsSelected()) { selectStart = i; } } // Swap so that the order is always the lower to higher if(selectStart > itemsPosition) std::swap(selectStart, itemsPosition); // TODO: pre-select callback // Perform actual selections for(size_t i = selectStart; i <= itemsPosition; ++i) { auto& position = Positions[i]; if(!position.WidgetToPosition) continue; position.WidgetToPosition->Widget->Select(); } // TODO: post-select callback } // ------------------------------------ // bool SuperContainer::IsEmpty() const { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; // Found non-empty return false; } return true; } // ------------------------------------ // std::shared_ptr<ResourceWithPreview> SuperContainer::GetFirstVisibleResource( double scrollOffset) const { for(const auto& position : Positions) { if(((position.Y + 5) > scrollOffset) && position.WidgetToPosition) { return position.WidgetToPosition->CreatedFrom; } } return nullptr; } std::vector<std::shared_ptr<ResourceWithPreview>> SuperContainer::GetResourcesVisibleAfter( double scrollOffset) const { std::vector<std::shared_ptr<ResourceWithPreview>> result; result.reserve(Positions.size() / 3); for(const auto& position : Positions) { if(((position.Y + 5) > scrollOffset) && position.WidgetToPosition) { result.push_back(position.WidgetToPosition->CreatedFrom); } } return result; } double SuperContainer::GetResourceOffset(std::shared_ptr<ResourceWithPreview> resource) const { for(const auto& position : Positions) { if(position.WidgetToPosition && position.WidgetToPosition->CreatedFrom == resource) { return position.Y; } } return -1; } // ------------------------------------ // void SuperContainer::UpdateMarginAndPadding(int newmargin, int newpadding) { Margin = newmargin; Padding = newpadding; LayoutDirty = true; Reflow(0); UpdatePositioning(); } // ------------------------------------ // void SuperContainer::Reflow(size_t index) { if(Positions.empty() || index >= Positions.size()) return; LayoutDirty = true; // The first one doesn't have a previous position // if(index == 0) { LastWidthReflow = get_width(); _PositionGridPosition(Positions.front(), nullptr, Positions.size()); ++index; } // This is a check for debugging //_CheckPositions(); for(size_t i = index; i < Positions.size(); ++i) { _PositionGridPosition(Positions[i], &Positions[i - 1], i - 1); } } void SuperContainer::_PositionGridPosition( GridPosition& current, const GridPosition* const previous, size_t previousindex) const { // First is at fixed position // if(previous == nullptr) { current.X = Margin; current.Y = Margin; return; } LEVIATHAN_ASSERT(previousindex < Positions.size(), "previousindex is out of range"); // Check does it fit on the line // if(previous->X + previous->Width + Padding + current.Width <= get_width()) { // It fits on the line // current.Y = previous->Y; current.X = previous->X + previous->Width + Padding; return; } // A new line is needed // // Find the tallest element in the last row int32_t lastRowMaxHeight = previous->Height; // Start from the one before previous, doesn't matter if the index wraps around as // the loop won't be entered in that case size_t scanIndex = previousindex - 1; const auto rowY = previous->Y; while(scanIndex < Positions.size()) { if(Positions[scanIndex].Y != rowY) { // Full row scanned // break; } // Check current height // const auto currentHeight = Positions[scanIndex].Height; if(currentHeight > lastRowMaxHeight) lastRowMaxHeight = currentHeight; // Move to previous // --scanIndex; if(scanIndex == 0) break; } // Position according to the maximum height of the last row current.X = Margin; current.Y = previous->Y + lastRowMaxHeight + Padding; } SuperContainer::GridPosition& SuperContainer::_AddNewGridPosition( int32_t width, int32_t height) { GridPosition pos; pos.Width = width; pos.Height = height; if(Positions.empty()) { _PositionGridPosition(pos, nullptr, 0); } else { _PositionGridPosition(pos, &Positions.back(), Positions.size() - 1); } Positions.push_back(pos); return Positions.back(); } // ------------------------------------ // void SuperContainer::_SetWidgetSize(Element& widget) { int width_min, width_natural; int height_min, height_natural; widget.Widget->SetItemSize(SelectedItemSize); Container.add(*widget.Widget); widget.Widget->show(); widget.Widget->get_preferred_width(width_min, width_natural); widget.Widget->get_preferred_height_for_width(width_natural, height_min, height_natural); widget.Width = width_natural; widget.Height = height_natural; widget.Widget->set_size_request(widget.Width, widget.Height); } void SuperContainer::SetItemSize(LIST_ITEM_SIZE newsize) { if(SelectedItemSize == newsize) return; SelectedItemSize = newsize; if(Positions.empty()) return; // Resize all elements // for(const auto& position : Positions) { if(position.WidgetToPosition) { _SetWidgetSize(*position.WidgetToPosition); } } LayoutDirty = true; UpdatePositioning(); } // ------------------------------------ // void SuperContainer::_SetKeepFalse() { for(auto& position : Positions) { if(position.WidgetToPosition) position.WidgetToPosition->Keep = false; } } void SuperContainer::_RemoveElementsNotMarkedKeep() { size_t reflowStart = Positions.size(); for(size_t i = 0; i < Positions.size();) { auto& current = Positions[i]; // If the current position has no widget try to get the next widget, or end // if(!current.WidgetToPosition) { if(i + 1 < Positions.size()) { // Swap with the next one // if(Positions[i].SwapWidgets(Positions[i + 1])) { if(reflowStart > i) reflowStart = i; } } // If still empty there are no more widgets to process // It doesn't seem to be right for some reason to break here if(!current.WidgetToPosition) { ++i; continue; } } if(!Positions[i].WidgetToPosition->Keep) { LayoutDirty = true; // Remove this widget // Container.remove(*current.WidgetToPosition->Widget); current.WidgetToPosition.reset(); // On the next iteration the next widget will be moved to this position } else { ++i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } // ------------------------------------ // void SuperContainer::_RemoveWidget(size_t index) { if(index >= Positions.size()) throw Leviathan::InvalidArgument("index out of range"); LayoutDirty = true; size_t reflowStart = Positions.size(); Container.remove(*Positions[index].WidgetToPosition->Widget); Positions[index].WidgetToPosition.reset(); // Move forward all the widgets // for(size_t i = index; i + 1 < Positions.size(); ++i) { if(Positions[i].SwapWidgets(Positions[i + 1])) { if(reflowStart > i) reflowStart = i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } void SuperContainer::_SetWidget( size_t index, std::shared_ptr<Element> widget, bool selectable, bool autoreplace) { if(index >= Positions.size()) throw Leviathan::InvalidArgument("index out of range"); if(Positions[index].WidgetToPosition) { if(!autoreplace) { throw Leviathan::InvalidState("index is not empty and no autoreplace specified"); } else { // Remove the current one Container.remove(*Positions[index].WidgetToPosition->Widget); } } // Initialize a size for the widget _SetWidgetSize(*widget); _SetWidgetAdvancedSelection(*widget->Widget, selectable); // Set it // if(Positions[index].SetNewWidget(widget)) { // Do a reflow // Reflow(index); } else { // Apply positioning now // if(!LayoutDirty) { _ApplyWidgetPosition(Positions[index]); UpdateRowWidths(); _PositionIndicator(); } } } // ------------------------------------ // void SuperContainer::_PushBackWidgets(size_t index) { if(Positions.empty()) return; LayoutDirty = true; size_t reflowStart = Positions.size(); // Create a new position and then pull back widgets until index is reached and then // stop // We can skip adding if the last is empty // if(Positions.back().WidgetToPosition) _AddNewGridPosition(Positions.back().Width, Positions.back().Height); for(size_t i = Positions.size() - 1; i > index; --i) { // Swap pointers around, the current index is always empty so the empty // spot will propagate to index // Also i - 1 cannot be out of range as the smallest index 0 wouldn't enter // this loop if(Positions[i].SwapWidgets(Positions[i - 1])) { if(reflowStart > i) reflowStart = i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } void SuperContainer::_AddWidgetToEnd(std::shared_ptr<ResourceWithPreview> item, const std::shared_ptr<ItemSelectable>& selectable) { // Create the widget // auto element = std::make_shared<Element>(item, selectable); // Initialize a size for the widget _SetWidgetSize(*element); _SetWidgetAdvancedSelection(*element->Widget, selectable.operator bool()); // Find the first empty spot // for(size_t i = 0; i < Positions.size(); ++i) { if(!Positions[i].WidgetToPosition) { if(Positions[i].SetNewWidget(element)) { // Do a reflow // Reflow(i); } return; } } // No empty spots, create a new one // GridPosition& pos = _AddNewGridPosition(element->Width, element->Height); pos.WidgetToPosition = element; if(!LayoutDirty) { _ApplyWidgetPosition(pos); UpdateRowWidths(); _PositionIndicator(); } } // ------------------------------------ // void SuperContainer::_SetWidgetAdvancedSelection(ListItem& widget, bool selectable) { if(widget.HasAdvancedSelection() == selectable) return; if(selectable) { widget.SetAdvancedSelection([=](ListItem& item) { ShiftSelectTo(&item); }); } else { widget.SetAdvancedSelection(nullptr); } } // ------------------------------------ // void SuperContainer::_CheckPositions() const { // Find duplicate stuff // for(size_t i = 0; i < Positions.size(); ++i) { for(size_t a = 0; a < Positions.size(); ++a) { if(a == i) continue; if(Positions[i].WidgetToPosition.get() == Positions[a].WidgetToPosition.get()) { LEVIATHAN_ASSERT( false, "SuperContainer::_CheckPositions: duplicate Element ptr"); } if(Positions[i].X == Positions[a].X && Positions[i].Y == Positions[a].Y) { LEVIATHAN_ASSERT(false, "SuperContainer::_CheckPositions: duplicate position"); } if(Positions[i].WidgetToPosition->Widget.get() == Positions[a].WidgetToPosition->Widget.get()) { LEVIATHAN_ASSERT( false, "SuperContainer::_CheckPositions: duplicate ListItem ptr"); } } } } // ------------------------------------ // // Position indicator void SuperContainer::EnablePositionIndicator() { if(PositionIndicatorEnabled) return; PositionIndicatorEnabled = true; Container.add(PositionIndicator); // Enable the click to change indicator position add_events(Gdk::BUTTON_PRESS_MASK); _PositionIndicator(); } size_t SuperContainer::GetIndicatorPosition() const { return IndicatorPosition; } void SuperContainer::SetIndicatorPosition(size_t position) { if(IndicatorPosition == position) return; IndicatorPosition = position; _PositionIndicator(); } void SuperContainer::SuperContainer::_PositionIndicator() { if(!PositionIndicatorEnabled) { return; } constexpr auto indicatorHeightSmallerBy = 6; // Detect emptyness, but also the widget size bool found = false; for(const auto& position : Positions) { if(position.WidgetToPosition) { found = true; PositionIndicator.property_height_request() = position.WidgetToPosition->Height - indicatorHeightSmallerBy; break; } } if(!found) { // Empty PositionIndicator.property_visible() = false; return; } PositionIndicator.property_visible() = true; // Optimization for last if(IndicatorPosition >= Positions.size()) { for(size_t i = Positions.size() - 1;; --i) { const auto& position = Positions[i]; if(position.WidgetToPosition) { // Found the end Container.move(PositionIndicator, position.X + position.Width + Padding / 2, position.Y + indicatorHeightSmallerBy / 2); return; } if(i == 0) { break; } } } else { if(IndicatorPosition == 0) { // Optimization for first Container.move( PositionIndicator, Margin / 2, Margin + indicatorHeightSmallerBy / 2); return; } else { // Find a suitable position (or leave hidden) bool after = false; for(size_t i = IndicatorPosition;; --i) { const auto& position = Positions[i]; if(position.WidgetToPosition) { Container.move(PositionIndicator, after ? position.X + Positions[i].Width + Padding / 2 : position.X - Padding / 2, position.Y + indicatorHeightSmallerBy / 2); return; } else { after = true; } if(i == 0) { break; } } } } LOG_ERROR("SuperContainer: failed to find position for indicator"); PositionIndicator.property_visible() = false; } size_t SuperContainer::CalculateIndicatorPositionFromCursor(int cursorx, int cursory) { size_t newPosition = -1; // The cursor position needs to be adjusted by the scroll offset const auto x = get_hadjustment()->get_value() + cursorx; const auto y = get_vadjustment()->get_value() + cursory; for(size_t i = 0; i < Positions.size(); ++i) { const auto& position = Positions[i]; if(!position.WidgetToPosition) break; // If click is not on this row, ignore if(y < position.Y || y > position.Y + position.Height + Padding) continue; // If click is to the left of position this is the target if(position.X + position.Width / 2 > x) { newPosition = i; break; } // If click is to the right of this the next position (if it exists) might be the // target if(x > position.X + position.Width) { newPosition = i + 1; } } return newPosition; } // ------------------------------------ // // Callbacks void SuperContainer::_OnResize(Gtk::Allocation& allocation) { if(Positions.empty()) return; // Skip if width didn't change // if(allocation.get_width() == LastWidthReflow) return; // Even if we don't reflow we don't want to be called again with the same width LastWidthReflow = allocation.get_width(); bool reflow = false; // If doesn't fit dual margins if(allocation.get_width() < WidestRow + Margin) { // Rows don't fit anymore // reflow = true; } else { // Check would wider rows fit // int32_t CurrentRow = 0; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(Margin + CurrentRow + Padding + position.Width < allocation.get_width()) { // The previous row (this is the first position of the first row) could // now fit this widget reflow = true; break; } CurrentRow = 0; CurrentY = position.Y; // Break if only checking first row #ifdef SUPERCONTAINER_RESIZE_REFLOW_CHECK_ONLY_FIRST_ROW break; #endif } CurrentRow += position.Width; } } if(reflow) { Reflow(0); UpdatePositioning(); // Forces update of positions Container.check_resize(); } } bool SuperContainer::_OnMouseButtonPressed(GdkEventButton* event) { if(event->type == GDK_BUTTON_PRESS) { SetIndicatorPosition(CalculateIndicatorPositionFromCursor(event->x, event->y)); return true; } return false; } // ------------------------------------ // // GridPosition bool SuperContainer::GridPosition::SetNewWidget(std::shared_ptr<Element> widget) { const auto newWidth = widget->Width; const auto newHeight = widget->Height; WidgetToPosition = widget; if(newWidth != Width && newHeight != Height) { Width = newWidth; Height = newHeight; return true; } return false; } bool SuperContainer::GridPosition::SwapWidgets(GridPosition& other) { WidgetToPosition.swap(other.WidgetToPosition); if(Width != other.Width || Height != other.Height) { Width = other.Width; Height = other.Height; return true; } return false; } std::string SuperContainer::GridPosition::ToString() const { return "[" + std::to_string(X) + ", " + std::to_string(Y) + " dim: " + std::to_string(Width) + ", " + std::to_string(Height) + " " + (WidgetToPosition ? "(filled)" : "(empty)"); }
26,872
7,785
#include "stdafx.h" #include "WeaponKnife.h" #include "WeaponHUD.h" #include "Entity.h" #include "Actor.h" #include "level.h" #include "xr_level_controller.h" #include "game_cl_base.h" #include "../skeletonanimated.h" #include "gamemtllib.h" #include "level_bullet_manager.h" #include "ai_sounds.h" #define KNIFE_MATERIAL_NAME "objects\\knife" CWeaponKnife::CWeaponKnife() : CWeapon("KNIFE") { m_attackStart = false; m_bShotLight = false; SetState ( eHidden ); SetNextState ( eHidden ); knife_material_idx = (u16)-1; } CWeaponKnife::~CWeaponKnife() { HUD_SOUND::DestroySound(m_sndShot); } void CWeaponKnife::Load (LPCSTR section) { // verify class inherited::Load (section); fWallmarkSize = pSettings->r_float(section,"wm_size"); // HUD :: Anims R_ASSERT (m_pHUD); animGet (mhud_idle, pSettings->r_string(*hud_sect,"anim_idle")); animGet (mhud_hide, pSettings->r_string(*hud_sect,"anim_hide")); animGet (mhud_show, pSettings->r_string(*hud_sect,"anim_draw")); animGet (mhud_attack, pSettings->r_string(*hud_sect,"anim_shoot1_start")); animGet (mhud_attack2, pSettings->r_string(*hud_sect,"anim_shoot2_start")); animGet (mhud_attack_e, pSettings->r_string(*hud_sect,"anim_shoot1_end")); animGet (mhud_attack2_e,pSettings->r_string(*hud_sect,"anim_shoot2_end")); HUD_SOUND::LoadSound(section,"snd_shoot" , m_sndShot , ESoundTypes(SOUND_TYPE_WEAPON_SHOOTING) ); knife_material_idx = GMLib.GetMaterialIdx(KNIFE_MATERIAL_NAME); } void CWeaponKnife::OnStateSwitch (u32 S) { inherited::OnStateSwitch(S); switch (S) { case eIdle: switch2_Idle (); break; case eShowing: switch2_Showing (); break; case eHiding: switch2_Hiding (); break; case eHidden: switch2_Hidden (); break; case eFire: { //------------------------------------------- m_eHitType = m_eHitType_1; fHitPower = fHitPower_1; fHitImpulse = fHitImpulse_1; //------------------------------------------- switch2_Attacking (S); }break; case eFire2: { //------------------------------------------- m_eHitType = m_eHitType_2; fHitPower = fHitPower_2; fHitImpulse = fHitImpulse_2; //------------------------------------------- switch2_Attacking (S); }break; } } void CWeaponKnife::KnifeStrike(const Fvector& pos, const Fvector& dir) { CCartridge cartridge; cartridge.m_buckShot = 1; cartridge.m_impair = 1; cartridge.m_kDisp = 1; cartridge.m_kHit = 1; cartridge.m_kImpulse = 1; cartridge.m_kPierce = 1; cartridge.m_flags.set (CCartridge::cfTracer, FALSE); cartridge.m_flags.set (CCartridge::cfRicochet, FALSE); cartridge.fWallmarkSize = fWallmarkSize; cartridge.bullet_material_idx = knife_material_idx; while(m_magazine.size() < 2) m_magazine.push_back(cartridge); iAmmoElapsed = m_magazine.size(); bool SendHit = SendHitAllowed(H_Parent()); PlaySound (m_sndShot,pos); Level().BulletManager().AddBullet( pos, dir, m_fStartBulletSpeed, fHitPower, fHitImpulse, H_Parent()->ID(), ID(), m_eHitType, fireDistance, cartridge, SendHit); } void CWeaponKnife::OnAnimationEnd(u32 state) { switch (state) { case eHiding: SwitchState(eHidden); break; case eFire: case eFire2: { if(m_attackStart) { m_attackStart = false; if(GetState()==eFire) m_pHUD->animPlay(random_anim(mhud_attack_e), TRUE, this, GetState()); else m_pHUD->animPlay(random_anim(mhud_attack2_e), TRUE, this, GetState()); Fvector p1, d; p1.set(get_LastFP()); d.set(get_LastFD()); if(H_Parent()) smart_cast<CEntity*>(H_Parent())->g_fireParams(this, p1,d); else break; KnifeStrike(p1,d); } else SwitchState(eIdle); }break; case eShowing: case eIdle: SwitchState(eIdle); break; } } void CWeaponKnife::state_Attacking (float) { } void CWeaponKnife::switch2_Attacking (u32 state) { if(m_bPending) return; if(state==eFire) m_pHUD->animPlay(random_anim(mhud_attack), FALSE, this, state); else //eFire2 m_pHUD->animPlay(random_anim(mhud_attack2), FALSE, this, state); m_attackStart = true; m_bPending = true; } void CWeaponKnife::switch2_Idle () { VERIFY(GetState()==eIdle); m_pHUD->animPlay(random_anim(mhud_idle), TRUE, this, GetState()); m_bPending = false; } void CWeaponKnife::switch2_Hiding () { FireEnd (); VERIFY(GetState()==eHiding); m_pHUD->animPlay (random_anim(mhud_hide), TRUE, this, GetState()); // m_bPending = true; } void CWeaponKnife::switch2_Hidden() { signal_HideComplete (); } void CWeaponKnife::switch2_Showing () { VERIFY(GetState()==eShowing); m_pHUD->animPlay (random_anim(mhud_show), FALSE, this, GetState()); // m_bPending = true; } void CWeaponKnife::FireStart() { inherited::FireStart(); SwitchState (eFire); } void CWeaponKnife::Fire2Start () { inherited::Fire2Start(); SwitchState(eFire2); } bool CWeaponKnife::Action(s32 cmd, u32 flags) { if(inherited::Action(cmd, flags)) return true; switch(cmd) { case kWPN_ZOOM : if(flags&CMD_START) Fire2Start(); else Fire2End(); return true; } return false; } void CWeaponKnife::LoadFireParams(LPCSTR section, LPCSTR prefix) { inherited::LoadFireParams(section, prefix); string256 full_name; fHitPower_1 = fHitPower; fHitImpulse_1 = fHitImpulse; m_eHitType_1 = ALife::g_tfString2HitType(pSettings->r_string(section, "hit_type")); fHitPower_2 = pSettings->r_float (section,strconcat(full_name, prefix, "hit_power_2")); fHitImpulse_2 = pSettings->r_float (section,strconcat(full_name, prefix, "hit_impulse_2")); m_eHitType_2 = ALife::g_tfString2HitType(pSettings->r_string(section, "hit_type_2")); } void CWeaponKnife::StartIdleAnim() { m_pHUD->animDisplay(mhud_idle[Random.randI(mhud_idle.size())], TRUE); } void CWeaponKnife::GetBriefInfo(xr_string& str_name, xr_string& icon_sect_name, xr_string& str_count) { str_name = NameShort(); str_count = ""; icon_sect_name = *cNameSect(); } #include "script_space.h" using namespace luabind; #pragma optimize("s",on) void CWeaponKnife::script_register (lua_State *L) { module(L) [ class_<CWeaponKnife,CGameObject>("CWeaponKnife") .def(constructor<>()) ]; }
6,585
3,193
// basic STL streams #include <iostream> #include <sstream> // GLEW lib // http://glew.sourceforge.net/basic.html #include <GL/glew.h> // Update 05/08/16 #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <ImGUI/imgui.h> #include <ImGUI/imgui_impl_sdl.h> #include <ImGUI/imgui_impl_opengl3.h> // Here we decide which of the two versions we want to use // If your systems supports both, choose to uncomment USE_OPENGL32 // otherwise choose to uncomment USE_OPENGL21 // GLView cna also help you decide before running this program: // // FOR MACOSX only, please use OPENGL32 for AntTweakBar to work properly // #define USE_OPENGL32 #include <glGA/glGARigMesh.h> // GLM lib // http://glm.g-truc.net/api/modules.html #define GLM_SWIZZLE #define GLM_FORCE_INLINE #include <glm/glm.hpp> #include <glm/gtx/string_cast.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/random.hpp> #include <fstream> //local #include "glGA/glGAHelper.h" #include "glGA/glGAMesh.h" // number of Squares for Plane #define NumOfSQ 20 // update globals SDL_Window *gWindow = NULL; SDL_GLContext gContext; float bgColor[] = { 0.0f, 0.0f, 0.0f, 0.1f }; double FPS; // global variables int windowWidth=1024, windowHeight=768; GLuint programPlane, programPS; GLuint vao, vaoPlane, vaoPS; GLuint bufferPlane, bufferPS; GLuint MV_uniformPlane , MVP_uniformPlane , Normal_uniformPlane; GLuint MV_uniform3D , MVP_uniformPS , Normal_uniform3D; GLuint TextureMatrix_Uniform; int timesc = 0; GLuint gSampler1,gSampler; Texture *pTexture = NULL; Mesh *m = NULL; const int NumVerticesSQ = ( (NumOfSQ) * (NumOfSQ)) * (2) * (3) + (1); const int NumVerticesCube = 36; //(6 faces)(2 triangles/face)(3 vertices/triangle) bool wireFrame = false; bool camera = false; bool SYNC = true; typedef glm::vec4 color4; typedef glm::vec4 point4; int IndexSQ = 0,IndexSQ1 = 0,IndexCube = 0; //Modelling arrays point4 pointsq[NumVerticesSQ]; color4 colorsq[NumVerticesSQ]; glm::vec3 normalsq[NumVerticesSQ]; glm::vec4 tex_coords[NumVerticesSQ]; glm::vec3 pos = glm::vec3( 0.0f, 0.0f , 30.0f ); float horizAngle = 3.14f; float verticAngle = 0.0f; float speedo = 3.0f; float mouseSpeedo = 0.005f; int xpos = 0,ypos = 0; float zNear; float zFar; float FOV; float initialFoV = 45.0f; int divideFactor = 2; float m10 = -15.0f,m101 = -15.0f; int go2 = 0; // Scene orientation (stored as a quaternion) float Rotation[] = { 0.0f, 0.0f, 0.0f, 1.0f }; //Plane point4 planeVertices[NumVerticesSQ]; color4 planeColor[NumVerticesSQ]; // Update function prototypes bool initSDL(); bool event_handler(SDL_Event* event); void close(); void resize_window(int width, int height); bool initImGui(); void displayGui(); // Update functions bool initSDL() { //Init flag bool success = true; //Basic Setup if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) { std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { std::cout << std::endl << "Yay! Initialized SDL succesfully!" << std::endl; //Use OpenGL Core 3.2 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); //SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16); #ifdef __APPLE__ SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1"); #endif //Create Window SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, &current); #ifdef __APPLE__ gWindow = SDL_CreateWindow("Chapter16", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI ); divideFactor = 4; #else gWindow = SDL_CreateWindow("Chapter16", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); #endif if (gWindow == NULL) { std::cout << "Window could not be created! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { std::cout << std::endl << "Yay! Created window sucessfully!" << std::endl << std::endl; //Create context gContext = SDL_GL_CreateContext(gWindow); if (gContext == NULL) { std::cout << "OpenGL context could not be created! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { //Initialize GLEW glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { std::cout << "Error initializing GLEW! " << glewGetErrorString(glewError) << std::endl; } //Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { std::cout << "Warning: Unable to set Vsync! SDL Error: " << SDL_GetError() << std::endl; } //Initializes ImGui if (!initImGui()) { std::cout << "Error initializing ImGui! " << std::endl; success = false; } //Init glViewport first time; resize_window(windowWidth, windowHeight); } } } return success; } bool event_handler(SDL_Event* event) { switch (event->type) { case SDL_WINDOWEVENT: { if (event->window.event == SDL_WINDOWEVENT_RESIZED) { resize_window(event->window.data1, event->window.data2); } } case SDL_MOUSEWHEEL: { return true; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) if (event->button.button == SDL_BUTTON_RIGHT) if (event->button.button == SDL_BUTTON_MIDDLE) return true; } case SDL_TEXTINPUT: { return true; } case SDL_KEYDOWN: { if (event->key.keysym.sym == SDLK_w) { if (wireFrame) { wireFrame = false; } else { wireFrame = true; } return true; } if (event->key.keysym.sym == SDLK_SPACE) { if (camera == false) { camera = true; SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); SDL_ShowCursor(0); } else { camera = false; SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); SDL_ShowCursor(1); } return true; } return true; } case SDL_KEYUP: { return true; } case SDL_MOUSEMOTION: { return true; } } return false; } void close() { //Cleanup ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(gContext); SDL_DestroyWindow(gWindow); SDL_Quit(); } void resize_window(int width, int height) { // Set OpenGL viewport and default camera glViewport(0, 0, width, height); float aspect = (GLfloat)width / (GLfloat)height; windowWidth = width; windowHeight = height; } bool initImGui() { // Setup ImGui binding IMGUI_CHECKVERSION(); ImGui::SetCurrentContext(ImGui::CreateContext()); // Setup ImGui binding if (!ImGui_ImplOpenGL3_Init("#version 150")) { return false; } if (!ImGui_ImplSDL2_InitForOpenGL(gWindow, gContext)) { return false; } // Load Fonts // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details) // Marios -> in order to use custom Fonts, //there is a file named extra_fonts inside /_thirdPartyLibs/include/ImGUI/extra_fonts //Uncomment the next line -> ImGui::GetIO() and one of the others -> io.Fonts->AddFontFromFileTTF("", 15.0f). //Important : Make sure to check the first parameter is the correct file path of the .ttf or you get an assertion. //ImGuiIO& io = ImGui::GetIO(); //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../_thirdPartyLibs/include/ImGUI/extra_fonts/Karla-Regular.ttf", 14.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); return true; } void displayGui(){ ImGui::Begin("Main Editor"); ImGui::SetWindowSize(ImVec2(200, 200), ImGuiSetCond_Once); ImGui::SetWindowPos(ImVec2(10, 10), ImGuiSetCond_Once); static bool checkbox = false; if (ImGui::Checkbox("Wireframe", &checkbox)) { if (checkbox) wireFrame = true; else wireFrame = false; } ImGui::Separator(); ImGui::ColorEdit3("bgColor", bgColor); ImGui::Separator(); if (ImGui::TreeNode("Scene Rotation")) { ImGui::InputFloat4("SceneRotation", (float*)&Rotation, 2); ImGui::Separator(); ImGui::SliderFloat("X", (float*)&Rotation[0], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("Y", (float*)&Rotation[1], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("Z", (float*)&Rotation[2], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("W", (float*)&Rotation[3], -1.0f, 1.0f, "%.2f"); ImGui::TreePop(); } ImGui::Separator(); if (ImGui::Button("Reset View", ImVec2(100, 20))) { Rotation[0] = 0.0f; Rotation[1] = 0.0f; Rotation[2] = 0.0f; Rotation[3] = 1.0f; pos = glm::vec3(5.0f, 3.0f, 18.0f); zNear = 0.1f; zFar = 100.0f; FOV = 45.0f; horizAngle = 3.14f; verticAngle = 0.0f; } ImGui::Separator(); if (ImGui::TreeNode("Projection Properties")) { ImGui::SliderFloat("Near Clip Plane", &zNear, 0.5, 100.0, "%.2f"); ImGui::Separator(); ImGui::SliderFloat("Far Clip Plane", &zFar, 0.5, 1000.0, "%.2f"); ImGui::Separator(); ImGui::SliderFloat("Field of View", &FOV, 0.0f, 100.0f, "%.2f"); ImGui::TreePop(); } ImGui::Separator(); if (ImGui::TreeNode("Frame Rate")) { ImGui::BulletText("MS per 1 Frame %.2f", FPS); ImGui::NewLine(); ImGui::BulletText("Frames Per Second %.2f", ImGui::GetIO().Framerate); ImGui::NewLine(); ImGui::BulletText("vSYNC %d", SYNC); ImGui::TreePop(); } ImGui::End(); } #if !defined(__APPLE__) /*void setVSync(bool sync) { // Function pointer for the wgl extention function we need to enable/disable // vsync typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALPROC)( int ); PFNWGLSWAPINTERVALPROC wglSwapIntervalEXT = 0; //const char *extensions = (char*)glGetString( GL_EXTENSIONS ); //if( strstr( extensions, "WGL_EXT_swap_control" ) == 0 ) //if(glewIsSupported("WGL_EXT_swap_control")) //{ // std::cout<<"\nWGL_EXT_swap_control Extension is not supported.\n"; // return; //} //else //{ wglSwapIntervalEXT = (PFNWGLSWAPINTERVALPROC)wglGetProcAddress( "wglSwapIntervalEXT" ); if( wglSwapIntervalEXT ) wglSwapIntervalEXT(sync); std::cout<<"\nDONE :: "<<sync<<"\n"; //} }*/ #endif static GLint arrayWidth, arrayHeight; static GLfloat *verts = NULL; static GLfloat *colors = NULL; static GLfloat *velocities = NULL; static GLfloat *startTimes = NULL; GLfloat Time = 0.0f,Time1 = 0.0f; glm::vec4 Background = glm::vec4(0.0,0.0,0.0,1.0); // Routine to convert a quaternion to a 4x4 matrix glm::mat4 ConvertQuaternionToMatrix(float *quat,glm::mat4 &mat) { float yy2 = 2.0f * quat[1] * quat[1]; float xy2 = 2.0f * quat[0] * quat[1]; float xz2 = 2.0f * quat[0] * quat[2]; float yz2 = 2.0f * quat[1] * quat[2]; float zz2 = 2.0f * quat[2] * quat[2]; float wz2 = 2.0f * quat[3] * quat[2]; float wy2 = 2.0f * quat[3] * quat[1]; float wx2 = 2.0f * quat[3] * quat[0]; float xx2 = 2.0f * quat[0] * quat[0]; mat[0][0] = - yy2 - zz2 + 1.0f; mat[0][1] = xy2 + wz2; mat[0][2] = xz2 - wy2; mat[0][3] = 0; mat[1][0] = xy2 - wz2; mat[1][1] = - xx2 - zz2 + 1.0f; mat[1][2] = yz2 + wx2; mat[1][3] = 0; mat[2][0] = xz2 + wy2; mat[2][1] = yz2 - wx2; mat[2][2] = - xx2 - yy2 + 1.0f; mat[2][3] = 0; mat[3][0] = mat[3][1] = mat[3][2] = 0; mat[3][3] = 1; return mat; } float ax = (0.0f/NumOfSQ),ay = (0.0f/NumOfSQ); // { 0.0 , 0.0 } float bx = (0.0f/NumOfSQ),by = (1.0f/NumOfSQ); // { 0.0 , 1.0 } float cx = (1.0f/NumOfSQ),cy = (1.0f/NumOfSQ); // { 1.0 , 1.0 } float dx = (1.0f/NumOfSQ),dy = (0.0f/NumOfSQ); // { 1.0 , 0.0 } int counter2 = 0,counter3 = 1; void quadSQ( int a, int b, int c, int d ) { // 0, 3, 2, 1 //specify temporary vectors along each quad's edge in order to compute the face // normal using the cross product rule glm::vec3 u = (planeVertices[b]-planeVertices[a]).xyz(); glm::vec3 v = (planeVertices[c]-planeVertices[b]).xyz(); glm::vec3 norm = glm::cross(u, v); glm::vec3 normal= glm::normalize(norm); normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[a]; pointsq[IndexSQ] = planeVertices[a];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[b]; pointsq[IndexSQ] = planeVertices[b];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[c]; pointsq[IndexSQ] = planeVertices[c];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[a]; pointsq[IndexSQ] = planeVertices[a];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[c]; pointsq[IndexSQ] = planeVertices[c];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[d]; pointsq[IndexSQ] = planeVertices[d];IndexSQ++; // Texture Coordinate Generation for the Plane if(counter2 != NumOfSQ) { tex_coords[IndexSQ1] = glm::vec4((bx) + (counter2 * (1.0/NumOfSQ)),(by),0.0,0.0);IndexSQ1++; // { 0.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((cx) + (counter2 * (1.0/NumOfSQ)),(cy),0.0,0.0);IndexSQ1++; // { 1.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((dx) + (counter2 * (1.0/NumOfSQ)),(dy),0.0,0.0);IndexSQ1++; // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4((bx) + (counter2 * (1.0/NumOfSQ)),(by),0.0,0.0);IndexSQ1++; // { 0.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((dx) + (counter2 * (1.0/NumOfSQ)),(dy),0.0,0.0);IndexSQ1++; // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4((ax) + (counter2 * (1.0/NumOfSQ)),(ay),0.0,0.0);IndexSQ1++; // { 0.0 , 0.0 } counter2++; } else { ax = (ax);ay = (ay) + (counter3 * (1.0/NumOfSQ)); // { 0.0 , 0.0 } bx = (bx);by = (by) + (counter3 * (1.0/NumOfSQ)); // { 0.0 , 1.0 } cx = (cx);cy = (cy) + (counter3 * (1.0/NumOfSQ)); // { 1.0 , 1.0 } dx = (dx);dy = (dy) + (counter3 * (1.0/NumOfSQ)); // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4(bx,by,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(cx,cy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(dx,dy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(bx,by,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(dx,dy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(ax,ay,0.0,0.0);IndexSQ1++; counter2 = 1; } } void initPlane() { float numX = 0.0f,numX1 = 0.5f; float numZ = 0.0f,numZ1 = 0.5f; planeVertices[0] = point4 ( numX, 0.0, numZ1, 1.0); planeColor[0] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 0 a planeVertices[1] = point4 ( numX, 0.0, numZ, 1.0); planeColor[1] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 1 d planeVertices[2] = point4 ( numX1, 0.0, numZ, 1.0); planeColor[2] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 2 c planeVertices[3] = point4 ( numX1, 0.0, numZ1, 1.0); planeColor[3] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 3 b int k = 4; int counter = 0; for(k=4;k<NumVerticesSQ;k=k+4) { numX+=0.5f; numX1+=0.5f; counter++; planeVertices[k] = point4 (numX, 0.0, numZ1, 1.0); planeColor[k] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+1] = point4 (numX, 0.0, numZ, 1.0); planeColor[k+1] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+2] = point4 (numX1, 0.0, numZ, 1.0); planeColor[k+2] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+3] = point4 (numX1, 0.0, numZ1, 1.0); planeColor[k+3] = color4 (0.603922, 0.803922, 0.196078, 1.0); if( counter == (NumOfSQ - 1) ) { numX = 0.0f;numX1 = 0.5f;k+=4; counter = 0; numZ+=0.5f;numZ1+=0.5f; planeVertices[k] = point4 (numX, 0.0, numZ1, 1.0); planeColor[k] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+1] = point4 (numX, 0.0, numZ, 1.0); planeColor[k+1] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+2] = point4 (numX1, 0.0, numZ, 1.0); planeColor[k+2] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+3] = point4 (numX1, 0.0, numZ1, 1.0); planeColor[k+3] = color4 (0.603922, 0.803922, 0.196078, 1.0); } } //generate and bind a VAO for the 3D axes glGenVertexArrays(1, &vaoPlane); glBindVertexArray(vaoPlane); pTexture = new Texture(GL_TEXTURE_2D,"./Textures/nvidia_logo.jpg"); //pTexture = new Texture(GL_TEXTURE_2D,"./Textures/NVIDIA.jpg"); if (!pTexture->loadTexture()) { exit(EXIT_FAILURE); } int lp = 0,a,b,c,d; a=0,b=3,c=2,d=1; for(lp = 0;lp < (NumOfSQ * NumOfSQ);lp++) { quadSQ(a,b,c,d); a+=4;b+=4;c+=4;d+=4; } // Load shaders and use the resulting shader program programPlane = LoadShaders( "./Shaders/vPlaneShader.vert", "./Shaders/fPlaneShader.frag" ); glUseProgram( programPlane ); // Create and initialize a buffer object on the server side (GPU) //GLuint buffer; glGenBuffers( 1, &bufferPlane ); glBindBuffer( GL_ARRAY_BUFFER, bufferPlane ); glBufferData( GL_ARRAY_BUFFER, sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq) + sizeof(tex_coords),NULL, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(pointsq), pointsq ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointsq), sizeof(colorsq), colorsq ); glBufferSubData( GL_ARRAY_BUFFER,sizeof(pointsq) + sizeof(colorsq),sizeof(normalsq),normalsq ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq) ,sizeof(tex_coords) , tex_coords ); // set up vertex arrays GLuint vPosition = glGetAttribLocation( programPlane, "MCvertex" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) ); GLuint vColor = glGetAttribLocation( programPlane, "vColor" ); glEnableVertexAttribArray( vColor ); glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq)) ); GLuint vNormal = glGetAttribLocation( programPlane, "vNormal" ); glEnableVertexAttribArray( vNormal ); glVertexAttribPointer( vNormal, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq) + sizeof(colorsq)) ); GLuint vText = glGetAttribLocation( programPlane, "MultiTexCoord0" ); glEnableVertexAttribArray( vText ); glVertexAttribPointer( vText, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq)) ); glEnable( GL_DEPTH_TEST ); glClearColor( 0.0, 0.0, 0.0, 1.0 ); // only one VAO can be bound at a time, so disable it to avoid altering it accidentally //glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void initParticleSystem() { m = new Mesh(); m->loadMesh("./Models/sphere.dae"); float *speed = NULL; float *lifetime = NULL; speed = (float *)malloc(m->numIndices * sizeof(float)); lifetime = (float *)malloc(m->numIndices * sizeof(float)); for(int i = 0; i < m->numIndices ; i++) { speed[i] = ((float)rand() / RAND_MAX ) / 10; lifetime[i] = 75.0 + (float)rand()/((float)RAND_MAX/(120.0-75.0)); } //generate and bind a VAO for the 3D axes glGenVertexArrays(1, &vaoPS); glBindVertexArray(vaoPS); // Load shaders and use the resulting shader program programPS = LoadShaders( "./Shaders/vParticleShader.vert", "./Shaders/fParticleShader.frag" ); glUseProgram( programPS ); // Create and initialize a buffer object on the server side (GPU) //GLuint buffer; glGenBuffers( 1, &bufferPS ); glBindBuffer( GL_ARRAY_BUFFER, bufferPS ); glBufferData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + 2*(m->numIndices * sizeof(float)),NULL, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, (sizeof(m->Positions[0]) * m->Positions.size()), &m->Positions[0] ); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()),(sizeof(m->Normals[0]) * m->Normals.size()),&m->Normals[0] ); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()),(m->numIndices * sizeof(float)),speed); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + (m->numIndices * sizeof(float)),(m->numIndices * sizeof(float)),lifetime); // set up vertex arrays GLuint vPosition = glGetAttribLocation( programPS, "MCVertex" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) ); GLuint vVelocity = glGetAttribLocation( programPS, "Velocity" ); glEnableVertexAttribArray( vVelocity ); glVertexAttribPointer( vVelocity, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size())) ); GLuint vSpeed = glGetAttribLocation( programPS, "Speed" ); glEnableVertexAttribArray( vSpeed ); glVertexAttribPointer( vSpeed, 1, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size())) ); GLuint vLifeTime = glGetAttribLocation( programPS, "LifeTime" ); glEnableVertexAttribArray( vLifeTime ); glVertexAttribPointer( vLifeTime, 1, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + (m->numIndices * sizeof(float))) ); glEnable( GL_DEPTH_TEST ); glClearColor( 0.0, 0.0, 0.0, 1.0 ); // only one VAO can be bound at a time, so disable it to avoid altering it accidentally //glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void checkActiveUniforms() { GLint nUniforms, maxLen; glGetProgramiv( programPS, GL_ACTIVE_UNIFORM_MAX_LENGTH,&maxLen); glGetProgramiv( programPS, GL_ACTIVE_UNIFORMS,&nUniforms); GLchar * name = (GLchar *) malloc( maxLen ); GLint size, location; GLsizei written; GLenum type; printf(" Location | Name\n"); printf("------------------------------------------------\n"); for( int i = 0; i < nUniforms; ++i ) { glGetActiveUniform( programPS, i, maxLen, &written,&size, &type, name ); location = glGetUniformLocation(programPS, name); printf(" %-8d | %s\n", location, name); } free(name); } void displayPlane(glm::mat4 &md,glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv) { glUseProgram(programPlane); glBindVertexArray(vaoPlane); glDisable(GL_CULL_FACE); glPushAttrib(GL_ALL_ATTRIB_BITS); if (wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); MV_uniformPlane = glGetUniformLocation(programPlane, "MV_mat"); MVP_uniformPlane = glGetUniformLocation(programPlane, "MVP_mat"); Normal_uniformPlane = glGetUniformLocation(programPlane, "Normal_mat"); TextureMatrix_Uniform = glGetUniformLocation(programPlane, "TextureMatrix"); glm::mat4 TexMat = glm::mat4(); glUniformMatrix4fv(TextureMatrix_Uniform,1,GL_FALSE,glm::value_ptr(TexMat)); // Calculation of ModelView Matrix glm::mat4 model_mat_plane = md; glm::mat4 view_mat_plane = glm::lookAt(positionv,positionv + directionv,upv); glm::mat4 MV_mat_plane = view_mat_plane * model_mat_plane; glUniformMatrix4fv(MV_uniformPlane,1, GL_FALSE, glm::value_ptr(MV_mat_plane)); // Calculation of Normal Matrix glm::mat3 Normal_mat_plane = glm::transpose(glm::inverse(glm::mat3(MV_mat_plane))); glUniformMatrix3fv(Normal_uniformPlane,1, GL_FALSE, glm::value_ptr(Normal_mat_plane)); // Calculation of ModelViewProjection Matrix float aspect_plane = (GLfloat)windowWidth / (GLfloat)windowHeight; glm::mat4 projection_mat_plane = glm::perspective(FOV, aspect_plane,zNear,zFar); glm::mat4 MVP_mat_plane = projection_mat_plane * MV_mat_plane; glUniformMatrix4fv(MVP_uniformPlane, 1, GL_FALSE, glm::value_ptr(MVP_mat_plane)); gSampler = glGetUniformLocationARB(programPlane, "gSampler"); glUniform1iARB(gSampler, 0); pTexture->bindTexture(GL_TEXTURE0); glDrawArrays( GL_TRIANGLES, 0, NumVerticesSQ ); glPopAttrib(); glBindVertexArray(0); //glUseProgram(0); } int flagP = 0,flagP1 = 0; void displayParticleSystem(glm::mat4 &md,glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv,int firew) { glUseProgram(programPS); glBindVertexArray(vaoPS); glDisable(GL_CULL_FACE); glPushAttrib(GL_ALL_ATTRIB_BITS); glPointSize(1.5); if (wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); MVP_uniformPS = glGetUniformLocation(programPS, "MVPMatrix"); // Calculation of ModelView Matrix glm::mat4 model_matx; if(firew == 1) { model_matx = glm::translate(md,glm::vec3(0.0,m10,0.0)); glUniform1i(glGetUniformLocation(programPS,"firew"),firew); } else { model_matx = glm::translate(md,glm::vec3(-5.0,m101,4.0)); glUniform1i(glGetUniformLocation(programPS,"firew"),firew); } glm::mat4 view_matx = glm::lookAt(positionv,positionv + directionv,upv); glm::mat4 MV_matx = view_matx * model_matx; // Calculation of ModelViewProjection Matrix float aspectx = (GLfloat)windowWidth / (GLfloat)windowHeight; glm::mat4 projection_matx = glm::perspective(45.0f, aspectx,0.1f,100.0f); glm::mat4 MVP_matx = projection_matx * MV_matx; glUniformMatrix4fv(MVP_uniformPS, 1, GL_FALSE, glm::value_ptr(MVP_matx)); glUniform4fv(glGetUniformLocation(programPS,"Background"),1,glm::value_ptr(Background)); if(Time <= 30.009 && Time >= 0) { m10 += 0.1; Time += 0.15f; } else if(Time >= 30.009) { flagP = 1; } if(flagP == 1) { Time += 0.2f; if(Time >= 0.009 && Time <= 4.00) { Time += 0.29f; } else if(Time >= 4.00 && Time <= 9.00) { Time += 0.4f; } } std::cout<<"CurrentTIME: "<<Time<<"\n"; glUniform1f(glGetUniformLocation(programPS,"Time"),Time); if(go2 == 1 && firew == 2) { if(Time1 <= 30.009 && Time1 >= 0) { m101 += 0.1; Time1 += 0.15f; } else if(Time1 >= 30.009) { flagP1 = 1; } if(flagP1 == 1) { Time1 += 0.2f; if(Time1 >= 0.009 && Time1 <= 4.00) { Time1 += 0.29f; } else if(Time1 >= 4.00 && Time1 <= 9.00) { Time1 += 0.4f; } } glUniform1f(glGetUniformLocation(programPS,"Time"),Time1); } glDrawArrays( GL_POINTS, 0, m->numVertices ); glPopAttrib(); glBindVertexArray(0); //glUseProgram(0); } int main (int argc, char * argv[]) { glm::mat4 mat; float axis[] = { 0.7f, 0.7f, 0.7f }; // initial model rotation float angle = 0.8f; double FT = 0; double starting = 0.0; double ending = 0.0; int rate = 0; int fr = 0; zNear = 0.1f; zFar = 100.0f; FOV = 45.0f; // Current time double time = 0; // initialise GLFW int running = GL_TRUE; if (!initSDL()) { exit(EXIT_FAILURE); } std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; std::ostringstream stream1,stream2; stream1 << glGetString(GL_VENDOR); stream2 << glGetString(GL_RENDERER); std::string vendor ="Title : Chapter-16 Vendor : " + stream1.str() + " Renderer : " +stream2.str(); const char *tit = vendor.c_str(); SDL_SetWindowTitle(gWindow, tit); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); initPlane(); //initialize Plane initParticleSystem(); GLfloat rat = 0.001f; if(SYNC == false) { rat = 0.001f; } else { rat = 0.01f; } // Initialize time time = SDL_GetTicks() / 1000.0f; uint32 currentTime; uint32 lastTime = 0U; int Frames = 0; double LT = SDL_GetTicks() / 1000.0f; starting = SDL_GetTicks() / 1000.0f; int play = 0; #if !defined (__APPLE__) if(SDL_GL_SetSwapInterval(1) == 0) SYNC = true; //setVSync(SYNC); #endif FOV = initialFoV; #ifdef __APPLE__ int *w = (int*)malloc(sizeof(int)); int *h = (int*)malloc(sizeof(int)); #endif while (running) { glm::vec3 direction(cos(verticAngle) * sin(horizAngle), sin(verticAngle), cos(verticAngle) * cos(horizAngle)); glm::vec3 right = glm::vec3(sin(horizAngle - 3.14f / 2.0f), 0, cos(horizAngle - 3.14f / 2.0f)); glm::vec3 up = glm::cross(right, direction); currentTime = SDL_GetTicks(); float dTime = float(currentTime - lastTime) / 1000.0f; lastTime = currentTime; SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSDL2_ProcessEvent(&event); event_handler(&event); if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_UP) pos += direction * dTime * speedo; if (event.key.keysym.sym == SDLK_DOWN) pos -= direction * dTime * speedo; if (event.key.keysym.sym == SDLK_RIGHT) pos += right * dTime * speedo; if (event.key.keysym.sym == SDLK_LEFT) pos -= right * dTime * speedo; if (event.key.keysym.sym == SDLK_RETURN) { if (play == 0) play = 1; else play = 0; } } if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) { running = GL_FALSE; } if (event.type == SDL_QUIT) running = GL_FALSE; } ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(gWindow); ImGui::NewFrame(); glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3]); //black color if(camera == true) { SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); horizAngle += mouseSpeedo * float(windowWidth/divideFactor - xpos ); verticAngle += mouseSpeedo * float( windowHeight/divideFactor - ypos ); } mat = ConvertQuaternionToMatrix(Rotation, mat); if(play == 1) { displayParticleSystem(mat,pos,direction,up,1); if(Time >= 40) { go2 = 1; } if(go2 == 1) { displayParticleSystem(mat,pos,direction,up,2); } if(Time >= 350) { mat = glm::mat4(); flagP = 0; flagP1 = 0; Time=0; Time1=0; go2=0; m10 = -15.0f; m101 = -15.0f; } } fr++; ending = SDL_GetTicks() / 1000.0f; if(ending - starting >= 1) { rate = fr; fr = 0; starting = SDL_GetTicks() / 1000.0f; } double CT = SDL_GetTicks() / 1000.0f; Frames++; if(CT -LT >= 1.0) { FPS = 1000.0 / (double)Frames; Frames = 0; LT += 1.0f; } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); displayGui(); ImGui::Render(); SDL_GL_MakeCurrent(gWindow, gContext); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(gWindow); #ifdef __APPLE__ if(w!=NULL && h!=NULL){ SDL_GL_GetDrawableSize(gWindow, w, h); resize_window(*w, *h); } #endif } //close OpenGL window and terminate ImGui and SDL2 close(); exit(EXIT_SUCCESS); }
31,539
14,627
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * Copyright (c) 2016-2019 Intel Corporation * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #include "../../common/utils/utils.h" #include <bpl/bpl_cfg.h> #include "bpl_cfg_helper.h" #include "bpl_cfg_uci.h" #include "mapf/common/logger.h" namespace beerocks { namespace bpl { int cfg_set_onboarding(int enable) { return 0; } } // namespace bpl } // namespace beerocks
488
195
// Use default !!!
18
6
/* * Copyright (c) 2013, Mathias Hällman. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "sound/SoundLoader.h" #include "sound/SoundResource.h" std::shared_ptr<Resource> SoundLoader::Load( const ResourceKey& key, const FileManager& fileManager) const { File file; fileManager.Open(key.GetFilePath(), file); SoundFileFormat format = SoundFileFormatUnknown; if (ExtractFileEnding(key.GetFilePath()).compare(".ogg") == 0) { format = SoundFileFormatOGG; } return std::make_shared<SoundResource>(file.ReadAll(), format); }
1,827
648
/* A DP solution for solving LCS problem */ #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; void printArray(vector<vector<int>> arr) { for (int i = 0; i < arr.size(); i++) { for (int j = 0; j < arr[i].size(); j++) { cout << arr[i][j] << " "; } cout << endl; } } int findLCS(string s1, string s2) { int m = s1.size(); int n = s2.size(); vector<vector<int>> L(m, vector<int>(n)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { L[i][j] = (s1[i] == s2[j]) ? 1 : 0; } else if (s1[i] == s2[j]) { L[i][j] = 1 + L[i - 1][j - 1]; } else { L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } //cout << "L" << endl; //printArray(L); } // return last element in L return L[m - 1][n - 1]; } int main() { string s1("AGGTAB"); string s2("GXTXAYB"); int ans = findLCS(s1, s2); cout << ans << endl; std::cin.ignore(); return 0; }
1,166
468
#pragma once #include "flexlib/reflect/ReflTypes.hpp" /// \todo improve based on p1240r1 /// http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2019/p1240r1.pdf namespace reflection { using namespace clang; class AstReflector { public: explicit AstReflector(const clang::ASTContext* context) : m_astContext(context) { } EnumInfoPtr ReflectEnum(const clang::EnumDecl* decl, NamespacesTree* nsTree); TypedefInfoPtr ReflectTypedef(const clang::TypedefNameDecl* decl, NamespacesTree* nsTree); ClassInfoPtr ReflectClass(const clang::CXXRecordDecl* decl, NamespacesTree* nsTree, bool recursive = true); MethodInfoPtr ReflectMethod(const clang::FunctionDecl* decl, NamespacesTree* nsTree); static void SetupNamedDeclInfo(const clang::NamedDecl* decl, NamedDeclInfo* info, const clang::ASTContext* astContext); private: const clang::NamedDecl* FindEnclosingOpaqueDecl(const clang::DeclContext* decl); void ReflectImplicitSpecialMembers(const clang::CXXRecordDecl* decl, ClassInfo* classInfo, NamespacesTree* nsTree); private: const clang::ASTContext* m_astContext; }; } // namespace reflection
1,149
397
// // Tizen C++ SDK // Copyright (c) 2012 Samsung Electronics Co., Ltd. // // Licensed under the Flora License, Version 1.1 (the License); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://floralicense.org/license // // 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 "AppResourceId.h" const wchar_t* IDF_FORM = L"IDF_FORM"; const wchar_t* IDC_INFO_LABEL = L"IDC_INFO_LABEL"; const wchar_t* ID_POPUP = L"ID_POPUP"; const wchar_t* IDC_BUTTON_YES = L"IDC_BUTTON_YES"; const wchar_t* IDC_BUTTON_NO = L"IDC_BUTTON_NO"; const wchar_t* IDC_TEXTBOX = L"IDC_TEXTBOX";
921
334
/* * Copyright © 2010,2011,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Google Author(s): Behdad Esfahbod */ #pragma once #include "hb.hh" #include "hb-ot-layout.hh" #include "hb-ot-shape-normalize.hh" #include "hb-ot-shape.hh" /* buffer var allocations, used by complex shapers */ #define complex_var_u8_0() var2.u8[2] #define complex_var_u8_1() var2.u8[3] #define HB_OT_SHAPE_COMPLEX_MAX_COMBINING_MARKS 32 extern "C" { void rb_preprocess_text_vowel_constraints(rb_buffer_t *buffer); } enum hb_ot_shape_zero_width_marks_type_t { HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE, HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_EARLY, HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_LATE }; typedef struct hb_ot_complex_shaper_t hb_ot_complex_shaper_t; extern "C" { void hb_ot_complex_shaper_collect_features(const hb_ot_complex_shaper_t *shaper, hb_ot_shape_planner_t *planner); void hb_ot_complex_shaper_override_features(const hb_ot_complex_shaper_t *shaper, hb_ot_shape_planner_t *planner); void *hb_ot_complex_shaper_data_create(const hb_ot_complex_shaper_t *shaper, hb_shape_plan_t *plan); void hb_ot_complex_shaper_data_destroy(const hb_ot_complex_shaper_t *shaper, void *data); void hb_ot_complex_shaper_preprocess_text(const hb_ot_complex_shaper_t *shaper, const hb_shape_plan_t *plan, rb_buffer_t *buffer, hb_font_t *font); void hb_ot_complex_shaper_postprocess_glyphs(const hb_ot_complex_shaper_t *shaper, const hb_shape_plan_t *plan, rb_buffer_t *buffer, hb_font_t *font); hb_ot_shape_normalization_mode_t hb_ot_complex_shaper_normalization_preference(const hb_ot_complex_shaper_t *shaper); bool hb_ot_complex_shaper_decompose(const hb_ot_complex_shaper_t *shaper, const hb_ot_shape_normalize_context_t *c, hb_codepoint_t ab, hb_codepoint_t *a, hb_codepoint_t *b); bool hb_ot_complex_shaper_compose(const hb_ot_complex_shaper_t *shaper, const hb_ot_shape_normalize_context_t *c, hb_codepoint_t a, hb_codepoint_t b, hb_codepoint_t *ab); void hb_ot_complex_shaper_setup_masks(const hb_ot_complex_shaper_t *shaper, const hb_shape_plan_t *plan, rb_buffer_t *buffer, hb_font_t *font); hb_tag_t hb_ot_complex_shaper_gpos_tag(const hb_ot_complex_shaper_t *shaper); void hb_ot_complex_shaper_reorder_marks(const hb_ot_complex_shaper_t *shaper, const hb_shape_plan_t *plan, rb_buffer_t *buffer, unsigned int start, unsigned int end); hb_ot_shape_zero_width_marks_type_t hb_ot_complex_shaper_zero_width_marks(const hb_ot_complex_shaper_t *shaper); bool hb_ot_complex_shaper_fallback_position(const hb_ot_complex_shaper_t *shaper); } extern "C" { hb_ot_complex_shaper_t *rb_create_default_shaper(); hb_ot_complex_shaper_t *rb_create_arabic_shaper(); hb_ot_complex_shaper_t *rb_create_hangul_shaper(); hb_ot_complex_shaper_t *rb_create_hebrew_shaper(); hb_ot_complex_shaper_t *rb_create_indic_shaper(); hb_ot_complex_shaper_t *rb_create_khmer_shaper(); hb_ot_complex_shaper_t *rb_create_myanmar_shaper(); hb_ot_complex_shaper_t *rb_create_myanmar_zawgyi_shaper(); hb_ot_complex_shaper_t *rb_create_thai_shaper(); hb_ot_complex_shaper_t *rb_create_use_shaper(); } inline const hb_ot_complex_shaper_t *hb_ot_shape_complex_categorize(const hb_ot_shape_planner_t *planner) { switch ((hb_tag_t)planner->props.script) { default: return rb_create_default_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_ARABIC: /* Unicode-3.0 additions */ case HB_SCRIPT_MONGOLIAN: case HB_SCRIPT_SYRIAC: /* Unicode-5.0 additions */ case HB_SCRIPT_NKO: case HB_SCRIPT_PHAGS_PA: /* Unicode-6.0 additions */ case HB_SCRIPT_MANDAIC: /* Unicode-7.0 additions */ case HB_SCRIPT_MANICHAEAN: case HB_SCRIPT_PSALTER_PAHLAVI: /* Unicode-9.0 additions */ case HB_SCRIPT_ADLAM: /* Unicode-11.0 additions */ case HB_SCRIPT_HANIFI_ROHINGYA: case HB_SCRIPT_SOGDIAN: /* For Arabic script, use the Arabic shaper even if no OT script tag was found. * This is because we do fallback shaping for Arabic script (and not others). * But note that Arabic shaping is applicable only to horizontal layout; for * vertical text, just use the generic shaper instead. */ if ((rb_ot_map_builder_chosen_script(planner->map, 0) != HB_OT_TAG_DEFAULT_SCRIPT || planner->props.script == HB_SCRIPT_ARABIC) && HB_DIRECTION_IS_HORIZONTAL(planner->props.direction)) return rb_create_arabic_shaper(); else return rb_create_default_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_THAI: case HB_SCRIPT_LAO: return rb_create_thai_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_HANGUL: return rb_create_hangul_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_HEBREW: return rb_create_hebrew_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_BENGALI: case HB_SCRIPT_DEVANAGARI: case HB_SCRIPT_GUJARATI: case HB_SCRIPT_GURMUKHI: case HB_SCRIPT_KANNADA: case HB_SCRIPT_MALAYALAM: case HB_SCRIPT_ORIYA: case HB_SCRIPT_TAMIL: case HB_SCRIPT_TELUGU: /* Unicode-3.0 additions */ case HB_SCRIPT_SINHALA: /* If the designer designed the font for the 'DFLT' script, * (or we ended up arbitrarily pick 'latn'), use the default shaper. * Otherwise, use the specific shaper. * * If it's indy3 tag, send to USE. */ if (rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('D', 'F', 'L', 'T') || rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('l', 'a', 't', 'n')) return rb_create_default_shaper(); else if ((rb_ot_map_builder_chosen_script(planner->map, 0) & 0x000000FF) == '3') return rb_create_use_shaper(); else return rb_create_indic_shaper(); case HB_SCRIPT_KHMER: return rb_create_khmer_shaper(); case HB_SCRIPT_MYANMAR: /* If the designer designed the font for the 'DFLT' script, * (or we ended up arbitrarily pick 'latn'), use the default shaper. * Otherwise, use the specific shaper. * * If designer designed for 'mymr' tag, also send to default * shaper. That's tag used from before Myanmar shaping spec * was developed. The shaping spec uses 'mym2' tag. */ if (rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('D', 'F', 'L', 'T') || rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('l', 'a', 't', 'n') || rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('m', 'y', 'm', 'r')) return rb_create_default_shaper(); else return rb_create_myanmar_shaper(); /* https://github.com/harfbuzz/harfbuzz/issues/1162 */ case HB_SCRIPT_MYANMAR_ZAWGYI: return rb_create_myanmar_zawgyi_shaper(); /* Unicode-2.0 additions */ case HB_SCRIPT_TIBETAN: /* Unicode-3.0 additions */ // case HB_SCRIPT_MONGOLIAN: // case HB_SCRIPT_SINHALA: /* Unicode-3.2 additions */ case HB_SCRIPT_BUHID: case HB_SCRIPT_HANUNOO: case HB_SCRIPT_TAGALOG: case HB_SCRIPT_TAGBANWA: /* Unicode-4.0 additions */ case HB_SCRIPT_LIMBU: case HB_SCRIPT_TAI_LE: /* Unicode-4.1 additions */ case HB_SCRIPT_BUGINESE: case HB_SCRIPT_KHAROSHTHI: case HB_SCRIPT_SYLOTI_NAGRI: case HB_SCRIPT_TIFINAGH: /* Unicode-5.0 additions */ case HB_SCRIPT_BALINESE: // case HB_SCRIPT_NKO: // case HB_SCRIPT_PHAGS_PA: /* Unicode-5.1 additions */ case HB_SCRIPT_CHAM: case HB_SCRIPT_KAYAH_LI: case HB_SCRIPT_LEPCHA: case HB_SCRIPT_REJANG: case HB_SCRIPT_SAURASHTRA: case HB_SCRIPT_SUNDANESE: /* Unicode-5.2 additions */ case HB_SCRIPT_EGYPTIAN_HIEROGLYPHS: case HB_SCRIPT_JAVANESE: case HB_SCRIPT_KAITHI: case HB_SCRIPT_MEETEI_MAYEK: case HB_SCRIPT_TAI_THAM: case HB_SCRIPT_TAI_VIET: /* Unicode-6.0 additions */ case HB_SCRIPT_BATAK: case HB_SCRIPT_BRAHMI: // case HB_SCRIPT_MANDAIC: /* Unicode-6.1 additions */ case HB_SCRIPT_CHAKMA: case HB_SCRIPT_SHARADA: case HB_SCRIPT_TAKRI: /* Unicode-7.0 additions */ case HB_SCRIPT_DUPLOYAN: case HB_SCRIPT_GRANTHA: case HB_SCRIPT_KHOJKI: case HB_SCRIPT_KHUDAWADI: case HB_SCRIPT_MAHAJANI: // case HB_SCRIPT_MANICHAEAN: case HB_SCRIPT_MODI: case HB_SCRIPT_PAHAWH_HMONG: // case HB_SCRIPT_PSALTER_PAHLAVI: case HB_SCRIPT_SIDDHAM: case HB_SCRIPT_TIRHUTA: /* Unicode-8.0 additions */ case HB_SCRIPT_AHOM: /* Unicode-9.0 additions */ // case HB_SCRIPT_ADLAM: case HB_SCRIPT_BHAIKSUKI: case HB_SCRIPT_MARCHEN: case HB_SCRIPT_NEWA: /* Unicode-10.0 additions */ case HB_SCRIPT_MASARAM_GONDI: case HB_SCRIPT_SOYOMBO: case HB_SCRIPT_ZANABAZAR_SQUARE: /* Unicode-11.0 additions */ case HB_SCRIPT_DOGRA: case HB_SCRIPT_GUNJALA_GONDI: // case HB_SCRIPT_HANIFI_ROHINGYA: case HB_SCRIPT_MAKASAR: // case HB_SCRIPT_SOGDIAN: /* Unicode-12.0 additions */ case HB_SCRIPT_NANDINAGARI: /* If the designer designed the font for the 'DFLT' script, * (or we ended up arbitrarily pick 'latn'), use the default shaper. * Otherwise, use the specific shaper. * Note that for some simple scripts, there may not be *any* * GSUB/GPOS needed, so there may be no scripts found! */ if (rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('D', 'F', 'L', 'T') || rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('l', 'a', 't', 'n')) return rb_create_default_shaper(); else return rb_create_use_shaper(); } }
11,573
4,552
#pragma once struct FloatBinomial { vector<long double> f; static constexpr long double LOGZERO = -1e10; FloatBinomial(int MAX) { f.resize(MAX + 1, 0.0); f[0] = 0.0; for (int i = 1; i <= MAX; i++) { f[i] = f[i - 1] + logl(i); } } long double logfac(int n) const { return f[n]; } long double logfinv(int n) const { return -f[n]; } long double logC(int n, int k) const { if (n < k || k < 0 || n < 0) return LOGZERO; return f[n] - f[n - k] - f[k]; } long double logP(int n, int k) const { if (n < k || k < 0 || n < 0) return LOGZERO; return f[n] - f[n - k]; } };
625
285
#pragma once #include <ymmsl/ymmsl.hpp> #include <libmuscle/data.hpp> #include <libmuscle/mcp/message.hpp> #include <libmuscle/outbox.hpp> namespace libmuscle { namespace impl { class MockPostOffice { public: MockPostOffice() = default; bool has_message(ymmsl::Reference const & receiver); std::unique_ptr<DataConstRef> get_message( ymmsl::Reference const & receiver); void deposit( ymmsl::Reference const & receiver, std::unique_ptr<DataConstRef> message); void wait_for_receivers() const; // Mock control variables static void reset(); static ymmsl::Reference last_receiver; static std::unique_ptr<mcp::Message> last_message; }; using PostOffice = MockPostOffice; } }
809
248
/* * The MIT License * * Copyright (c) 1997-2019 The University of Utah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <cstdlib> #include <cstdio> #include <iostream> #include <fstream> #include <cmath> #include <string> #include <vector> // Find the current location of a set of points whose initial // position is known (from puda) (for the Taylor impact test) using namespace std; bool inbox(double px, double py, double pz, double xmin, double xmax, double ymin, double ymax, double zmin, double zmax) { if (px > xmin && py > ymin && pz > zmin && px < xmax && py < ymax && pz < zmax) return true; return false; } int main(int argc, char** argv) { // Check if the number of arguments is correct if (argc != 3) { cerr << "Usage: extractTaylor <int_pos_file> <final_pos_file>" << endl; exit(0); } // Parse arguments string posFileName = argv[1]; string finposFileName = argv[2]; // Open the files ifstream posFile(posFileName.c_str()); if(!posFile) { cerr << "File " << posFileName << " can't be opened." << endl; exit(0); } string pidFileName = posFileName+".pid"; ofstream pidFile(pidFileName.c_str()); // Read in the initial particle location double rad, height; cout << "\n Enter radius and height "; cin >> rad >> height; cout << rad << " " << height << endl; double dx; cout << "\n Enter width of search box "; cin >> dx; cout << dx << endl; // Create an array for storing the PIDs vector<int64_t> pidVec; // Read the header posFile.ignore(1000,'\n'); int64_t pID; int patch, mat; double time, x, y, z; double xmin, ymin, xmax, ymax, zmin, zmax; while (posFile >> time >> patch >> mat >> pID >> x >> y >> z){ // Create the width box (top) xmin = -dx; ymin = height - dx; zmin = -dx; xmax = rad + dx; ymax = height + dx; zmax = dx; if (inbox(x, y, z, xmin, xmax, ymin, ymax, zmin, zmax)){ //cout << " pID = " << pID << " [" << x <<","<<y<<","<<z<<"]\n"; pidFile << pID << " " << x << " " << y << " " << z << endl; pidVec.push_back(pID); } // Create the height box xmin = rad - dx; ymin = -dx; zmin = -dx; xmax = rad + dx; ymax = height + dx; zmax = dx; if (inbox(x, y, z, xmin, xmax, ymin, ymax, zmin, zmax)){ //cout << " pID = " << pID << " [" << x <<","<<y<<","<<z<<"]\n"; pidFile << pID << " " << x << " " << y << " " << z << endl; pidVec.push_back(pID); } // Create the width box (bottom) xmin = -dx; ymin = - dx; zmin = -dx; xmax = rad + dx; ymax = dx; zmax = dx; if (inbox(x, y, z, xmin, xmax, ymin, ymax, zmin, zmax)){ //cout << " pID = " << pID << " [" << x <<","<<y<<","<<z<<"]\n"; pidFile << pID << " " << x << " " << y << " " << z << endl; pidVec.push_back(pID); } } posFile.close(); // Open the files ifstream finposFile(finposFileName.c_str()); if(!finposFile) { cerr << "File " << finposFileName << " can't be opened." << endl; exit(0); } string finpidFileName = finposFileName+".pid"; ofstream finpidFile(finpidFileName.c_str()); // Read the header finposFile.ignore(1000,'\n'); int numPID = pidVec.size(); while (finposFile >> time >> patch >> mat >> pID >> x >> y >> z){ for (int ii = 0; ii < numPID; ++ii) { if (pID == pidVec[ii]) //cout << " pID = " << pID << " [" << x <<","<<y<<","<<z<<"]\n"; finpidFile << pID << " " << x << " " << y << " " << z << endl; } } finposFile.close(); }
4,640
1,680
#include <iostream> #include <vector> #include <map> using namespace std; class VectorTools{ public: void sorted(vector<int>::iterator first, vector<int>::iterator last) { if (first == last || first + 1 == last) return; vector<int>::iterator pivot = first; int temp; for (vector<int>::iterator it = first+1; it != last; it ++) { if (*it<*pivot) { temp = *it; *it = *(pivot+1); *(pivot+1) = *pivot; *pivot = temp; pivot ++; } } sorted(first, pivot); sorted(pivot+1, last); } int binary_search(vector<int>::iterator first, int size, bool have_sorted, int tar) { int l = 0; int r = size - 1; int mid = (l+r)/2; if (size==0) return -1; else if (size==1) return 0; if (!have_sorted) sorted(first, first+size); if (*(first+l)>=tar) return l; if (*(first+r)<=tar) return r; while (l < r - 1) { mid = (l+r)/2; if (*(first+mid) < tar) l = mid; else if (*(first+mid) == tar) { int i = 0; while((mid - i)>=0 && *(first+mid-i) == tar) i ++; return *(first+mid-i)==tar?(mid-i):(mid-i+1); } else r = mid; } return (tar-*(first+l) >= *(first+r) - tar)?r:l; } void vector_display(vector<int>& v) { for (vector<int>:: iterator it = v.begin(); it != v.end(); it ++) { printf("%d ",*it); }printf("\n"); } }; class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int result,temp_result, distance; distance = INT_MAX; if (nums.size()<3) return result; VectorTools V; V.sorted(nums.begin(), nums.end()); for (int i = 0; i < nums.size()-2; i ++) { if(i>0 && nums[i]==nums[i-1]) continue; for (int j = i+1; j < nums.size()-1; j ++) { if(j>i+1 && nums[j] == nums[j-1]) continue; int l,r; l = nums[i]; r = nums[j]; int tar = target - (l + r); temp_result = nums[j+1+V.binary_search(nums.begin()+j+1,nums.size()-j-1,true,tar)]; //printf("%d: %d %d %d\n",tar,l,r,temp_result); temp_result += (l+r); if(abs(temp_result-target)<distance){ result = temp_result; distance = abs(temp_result-target); } } } return result; } }; int main () { int intList[] = {-1, 0, 1, 1, 55}; vector<int> v(intList, intList + sizeof(intList)/sizeof(int)); Solution s; VectorTools V; int result = s.threeSumClosest(v,3); printf("%d\n",result); }
2,865
983
/* * * Copyright (C) 2015 Open Source Robotics Foundation * * 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. * */ /// \file TerrainTestPlugin.hh /// \brief A plugin that outputs an elevation.csv and a terrain.csv file. /// The elevation.csv file contains elevation information within the search /// area. The terrain.csv files contains terrain type informaiton within the /// search area. These csv files can be used in conjunction with terrain.py /// to produce png file respresentations of the raw data. #ifndef __SWARM_TERRAIN_DEBUG_PLUGIN_HH__ #define __SWARM_TERRAIN_DEBUG_PLUGIN_HH__ #include "swarm/RobotPlugin.hh" namespace swarm { /// \brief A plugin useful for testing terrain elevation and terrain type. /// Refere to the following tutorial for more information: class TerrainTestPlugin : public swarm::RobotPlugin { /// \brief constructor public: TerrainTestPlugin(); /// \brief destructor public: virtual ~TerrainTestPlugin() = default; /// \brief Produces the elevation.csv and terrain.csv files. /// \param[in] _sdf Pointer the sdf information. public: virtual void Load(sdf::ElementPtr _sdf); }; } #endif
1,675
495
#include <QString> #include "cwheelitemmodel.h" /** * @brief CWheelItemModel::VelocityValueConverter::Value2String Convert velocity value * in uint32_t data type into QString. * The format is xxxx.yyy, the decade part * has 3 number. * @param value Value to convert. * @return Convert value in QString data type. */ QString CWheelItemModel::VelocityValueConverter::Value2String(uint32_t value) { uint32_t integerPart = value / 1000; uint32_t decadePart = value % 1000; QString valueString = QString::number(integerPart) + QString(".") + QString::number(decadePart).rightJustified(3, '0') + this->getUnit(); return valueString; } /** * @brief CWheelItemModel::VelocityValueConverter::getUnit Returns the unit of velocity. * @return Unit of velocity. */ QString CWheelItemModel::VelocityValueConverter::getUnit() { return QString("[km/h]"); } /** * @brief CWheelItemModel::RotateValueConverter::Value2String Convert the number of rotation value * in uint32_t data type into QString. * @param value Rotation value to be converted. * @return Converted value in QStirng data type. */ QString CWheelItemModel::RotateValueConverter::Value2String(uint32_t value) { QString valueString = QString::number(value) + this->getUnit(); return valueString; } /** * @brief CWheelItemModel::RotateValueConverter::getUnit Returns teh unit of rotation. * @return Unit of rotation. */ QString CWheelItemModel::RotateValueConverter::getUnit() { return QString("[RPM]"); } /** * @brief CWheelItemModel::CWheelItemModel Constructs a CWheelItemModel object * with given parent. * @param parent Pointer to parent. */ CWheelItemModel::CWheelItemModel(QObject* parent) : CBicycleItemModel (parent) {} /** * @brief CWheelItemModel::setPinData Set data of wheel, velocity and rotate into model. * @param pin GPIO pin number. * @param velocity Velocity of wheel to set * @param rotate */ void CWheelItemModel::setData(const int pin, const uint32_t rotate, const uint32_t velocity) { int rowIndex = this->Pin2RowIndex(pin); RotateValueConverter rotateConverter; VelocityValueConverter velocityConverter; this->setData(rowIndex, MODEL_COLUMN_INDEX_ROTATE, rotate, rotateConverter); this->setData(rowIndex, MODEL_COLUMN_INDEX_VELOCITY, velocity, velocityConverter); } /** * @brief CWheelItemModel::setData Set data into model specified by index of row, rowIndex, and column, columnIndex. * The value is set both in raw number and string with format. * @param rowIndex Index of row of model the value to be set. * @param columnIndex Index of column of model the value to be set. * @param value The value to be set to model. * @param converter Instance of IValueConverter's subclass to be used convert value into string. */ void CWheelItemModel::setData( const int rowIndex, const int columnIndex, const uint32_t value, IValueConverter &converter) { QModelIndex modelIndex = this->index(rowIndex, columnIndex); CBicycleItemModel::setData(modelIndex, QVariant(value), false); this->setData(columnIndex, converter); } #define AVERAGE(value1, value2) (((value1) >> 1) + (value2 >> 1)) /** * @brief CWheelItemModel::updateData * @param columnIndex * @param converter */ void CWheelItemModel::setData(const int columnIndex, IValueConverter &converter) { QModelIndex frontModelIndex = this->index(MODEL_ROW_INDEX_FRONT_WHEEL_MODEL, columnIndex); QVariant frontVariant = this->data(frontModelIndex); uint32_t frontValue = frontVariant.toUInt(); QModelIndex rearModelIndex = this->index(MODEL_ROW_INDEX_REAR_WHEEL_MODEL, columnIndex); QVariant rearVariant = this->data(rearModelIndex); uint32_t rearValue = rearVariant.toUInt(); uint32_t average = AVERAGE(frontValue, rearValue); QModelIndex averageModelIndex = this->index(MODEL_ROW_INDEX_INTEGRATED_WHEEL_MODEL, columnIndex); CBicycleItemModel::setData(averageModelIndex, QVariant(average), false); averageModelIndex = this->index(MODEL_ROW_INDEX_INTEGRATED_WHEEL_MODEL, columnIndex + 2); QString stringAverage = converter.Value2String(average); CBicycleItemModel::setData(averageModelIndex, QVariant(stringAverage)); }
4,635
1,409
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/async/cpp/executor.h> #include <lib/async/cpp/task.h> #include <gtest/gtest.h> #include "src/media/vnext/lib/stream_sink/stream_queue.h" namespace fmlib::test { // Tests the |pull| method. TEST(StreamQueueTest, Pull) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } loop.RunUntilIdle(); // Expect the tasks actually ran. EXPECT_EQ(kElements, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); executor.schedule_task( under_test.pull().and_then([&exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(kElements, element.packet()); ++exec_count; })); // Expect the task hasn't run yet. EXPECT_EQ(kElements, exec_count); // Push one more element. under_test.push(kElements); loop.RunUntilIdle(); // Expect the task ran once more. EXPECT_EQ(kElements + 1, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); } // Tests the |pull| method when the stream is ended. TEST(StreamQueueTest, PullEnded) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // End the stream. under_test.end(); // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } // Attempt to pull one more...expect |kEnded|. executor.schedule_task( under_test.pull().and_then([&exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_ended()); ++exec_count; })); loop.RunUntilIdle(); // Expect the tasks actually ran. EXPECT_EQ(kElements + 1, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); } // Tests the |pull| method when the stream is ended asynchronously. TEST(StreamQueueTest, PullEndedAsync) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } // Attempt to pull one more...expect |kEnded|. executor.schedule_task( under_test.pull().and_then([&exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_ended()); ++exec_count; })); loop.RunUntilIdle(); // Expect the initial tasks actually ran. EXPECT_EQ(kElements, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // End the stream. under_test.end(); loop.RunUntilIdle(); // Expect the final task actually ran. EXPECT_EQ(kElements + 1, exec_count); } // Tests the |pull| method when the stream is drained. TEST(StreamQueueTest, PullDrained) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // Drain the stream. under_test.drain(); // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } // Attempt to pull one more...expect drained. executor.schedule_task( under_test.pull().then([&exec_count](StreamQueue<size_t, float>::PullResult& result) { EXPECT_TRUE(result.is_error()); EXPECT_EQ(StreamQueueError::kDrained, result.error()); ++exec_count; })); loop.RunUntilIdle(); // Expect the tasks actually ran. EXPECT_EQ(kElements + 1, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); } // Tests the |pull| method when the stream is drained asynchronously. TEST(StreamQueueTest, PullDrainedAsync) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } // Attempt to pull one more...expect drained. executor.schedule_task( under_test.pull().then([&exec_count](StreamQueue<size_t, float>::PullResult& result) { EXPECT_TRUE(result.is_error()); EXPECT_EQ(StreamQueueError::kDrained, result.error()); ++exec_count; })); loop.RunUntilIdle(); // Expect the initial tasks actually ran. EXPECT_EQ(kElements, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Drain the stream. under_test.drain(); loop.RunUntilIdle(); // Expect the final task actually ran. EXPECT_EQ(kElements + 1, exec_count); } // Tests the |pull| method when the queue is cleared. TEST(StreamQueueTest, PullClear) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; // Try to pull an element. size_t exec_count = 0; executor.schedule_task( under_test.pull().and_then([&exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_clear_request()); EXPECT_EQ(0.0f, element.clear_request()); ++exec_count; })); loop.RunUntilIdle(); // Expect the task hasn't run yet. EXPECT_EQ(0u, exec_count); // Clear the queue. under_test.clear(0.0f); loop.RunUntilIdle(); // Expect the task ran once. EXPECT_EQ(1u, exec_count); } // Tests the |cancel_pull| method. TEST(StreamQueueTest, CancelPull) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; // Expect |cancel_pull| to return false, because there's no |pull| pending. EXPECT_FALSE(under_test.cancel_pull()); // Attempt to pull. bool task_ran = false; executor.schedule_task( under_test.pull().then([&task_ran](StreamQueue<size_t, float>::PullResult& result) { EXPECT_TRUE(result.is_error()); EXPECT_EQ(StreamQueueError::kCanceled, result.error()); task_ran = true; })); loop.RunUntilIdle(); // Expect that the task didn't run. EXPECT_FALSE(task_ran); // Abandon the pull. Expect |cancel_pull| to return true, because there's a |pull| pending. EXPECT_TRUE(under_test.cancel_pull()); loop.RunUntilIdle(); // Expect that the task ran (returning StreamQueueError::kCanceled). EXPECT_TRUE(task_ran); } } // namespace fmlib::test
9,866
3,631
/******************************************************************** created: 2010/04/10 filename: RenderTarget.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <graphics/RenderTarget.h> #include <interface/public/graphics/IRenderDevice.h> #include <graphics/Texture.h> namespace Blade { ////////////////////////////////////////////////////////////////////////// RenderTarget::RenderTarget(const TString& name,IRenderDevice* device, size_t viewWidth, size_t viewHeight) :mName(name) ,mDevice(device) ,mListener(NULL) ,mViewWidth(viewWidth) ,mViewHeight(viewHeight) { } ////////////////////////////////////////////////////////////////////////// RenderTarget::~RenderTarget() { } /************************************************************************/ /* IRenderTarget interface */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// const TString& RenderTarget::getName() const { return mName; } ////////////////////////////////////////////////////////////////////////// const HTEXTURE& RenderTarget::getDepthBuffer() const { return mDepthBuffer; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setDepthBuffer(const HTEXTURE& hDethBuffer) { if( hDethBuffer != NULL && !hDethBuffer->getPixelFormat().isDepth() && !hDethBuffer->getPixelFormat().isDepthStencil() ) { assert(false); return false; } mDepthBuffer = hDethBuffer; return true; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setColorBuffer(index_t index, const HTEXTURE& buffer) { if( index >= mDevice->getDeviceCaps().mMaxMRT ) { assert(false); return false; } assert( index == 0 || buffer == NULL || buffer->getWidth() == this->getWidth() ); assert( index == 0 || buffer == NULL || buffer->getHeight() == this->getHeight() ); if( index < mOutputBuffers.size() ) mOutputBuffers[index] = buffer; else if( index == mOutputBuffers.size() ) mOutputBuffers.push_back(buffer); else { assert(false); return false; } return true; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setColorBufferCount(index_t count) { if( count <= mDevice->getDeviceCaps().mMaxMRT ) { mOutputBuffers.resize(count); return true; } assert(false); return false; } ////////////////////////////////////////////////////////////////////////// const HTEXTURE& RenderTarget::getColorBuffer(index_t index) const { if( index < mOutputBuffers.size() ) return mOutputBuffers[index]; else return HTEXTURE::EMPTY; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setViewRect(int32 left, int32 top, int32 width, int32 height) { bool ret = false; for (size_t i = 0; i < mOutputBuffers.size(); ++i) { Texture* tex = static_cast<Texture*>(mOutputBuffers[i]); if (tex != NULL) { scalar fwidth = (scalar)tex->getWidth(); scalar fheight = (scalar)tex->getHeight(); ret |= tex->setViewRect((scalar)left/fwidth, (scalar)top/fheight, std::min<scalar>(1.0f, width / fwidth), std::min<scalar>(1.0f, (scalar)height / fheight)); } } if (mDepthBuffer != NULL) { Texture* tex = static_cast<Texture*>(mDepthBuffer); if (tex != NULL) { scalar fwidth = (scalar)tex->getWidth(); scalar fheight = (scalar)tex->getHeight(); ret |= tex->setViewRect((scalar)left / fwidth, (scalar)top / fheight, std::min<scalar>(1.0f, width / fwidth), std::min<scalar>(1.0f, (scalar)height / fheight)); } } return ret; } ////////////////////////////////////////////////////////////////////////// size_t RenderTarget::getColorBufferCount() const { return mOutputBuffers.size(); } ////////////////////////////////////////////////////////////////////////// RenderTarget::IListener*RenderTarget::setListener(IListener* listener) { IListener* old = mListener; mListener = listener; return old; } RenderTarget::IListener*RenderTarget::getListener() const { return mListener; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::isReady() const { return this->getColorBuffer(0) != NULL; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::swapBuffers() { return true; } /************************************************************************/ /* custom methods */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void RenderTarget::notifySizeChange(IRenderTarget* target) { if( mListener != NULL ) mListener->onTargetSizeChange(target); } }//namespace Blade
5,141
1,621
/* I/O of pointclouds to/from different formats This file is part of the source code used for the calculation of the moment invariants as described in the dissertation of Max Langbein https://nbn-resolving.org/urn:nbn:de:hbz:386-kluedo-38558 Copyright (C) 2020 TU Kaiserslautern, Prof.Dr. Hans Hagen (AG Computergraphik und HCI) (hagen@cs.uni-kl.de) Author: Max Langbein (m_langbe@cs.uni-kl.de) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include<iostream> #include<fstream> #include<cassert> #include<stdlib.h> #include<sys/stat.h> #include<sys/types.h> #include<fcntl.h> #ifndef GNUCC #include<io.h> #else #include<errno.h> #include<unistd.h> #endif #include "PointCloudIO.h" #include "equaldist.h" #include "osgio.h" #ifndef OLD_VC #include<string.h> #include<stdexcept> #define _EXCEPTION_ std::runtime_error #else #define _EXCEPTION_ exception #endif using namespace std; PointCloudIO::PointCloudIO(void) { } PointCloudIO::~PointCloudIO(void) { } bool PointCloudIO::accept(const char *name, const char *format) { if(format) return strcmp(format,this->format())==0; const char*s=strstr(name,ext()); if(!s)return false; if(strlen(s)!=strlen(ext())) return false; return true; } PointCloudIO::Factory* PointCloudIO::instance=0; PointCloudIO* PointCloudIO::Factory::getIO(const char *name, const char *format) { for(int i=0;i<instances.size();++i) if(instances[i]->accept(name,format)) return instances[i]; cerr<<"no appropriate reader or writer for "<<name<<" found"; throw; } //-------------------------------------------------------------------------- //now instances of reader/writers: struct pcio_raw : public PointCloudIO { void read_(vector<mynum> & points ,const char*fname) { struct stat s; if(stat(fname,&s)<0) {throw _EXCEPTION_("couldn't read");} points.resize(s.st_size/sizeof(mynum)); FILE*f=fopen(fname,"rb"); fread(&points[0],sizeof(points[0]),points.size(),f); fclose(f); } void write_(const vector<mynum> & points ,const char*fname) { /* struct stat s; errno=0; int fd=open(fname,O_CREAT|O_RDWR,S_IWRITE|S_IREAD); if(fd<0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw exception("couldn't write");} else { ::write(fd,&points[0],sizeof(points[0])*points.size()); close(fd); } */ FILE *f=fopen(fname,"wb"); if(f==0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw _EXCEPTION_("couldn't write");} else { //Achtung: Dateigroesse bei 64-bit-Version ist groesser als die geschriebenen Daten size_t num=fwrite(&points[0],sizeof(points[0]),points.size(),f); fclose(f); } } const char *ext(){return ".raw";} pcio_raw() { reg(); } } pcio_1; struct pcio_rw2 : public PointCloudIO { //typedef unsigned __int64 tlen; typedef u_int64_t tlen; void read_(vector<mynum> & points ,const char*fname) { FILE*f=fopen(fname,"rb"); if(f==0) { cerr<<"could not open "<<fname<<endl; throw _EXCEPTION_("could not read"); } tlen len; tlen x; fread(&x,sizeof(x),1,f); fread(&len,sizeof(len),1,f); if(x!=sizeof(mynum)){ printf("\n%s: number size=%d bytes != read size=%d bytes\n",fname,(int)x,(int)sizeof(mynum)); throw _EXCEPTION_("number format does not match"); } points.resize(len); size_t nread=fread(&points[0],x,len,f); if(nread!=len){ printf("\n%s: length=%d != read=%d \n",fname,(int)len,(int)nread); throw _EXCEPTION_("could not read full length"); } fclose(f); } void write_(const vector<mynum> & points ,const char*fname) { FILE *f=fopen(fname,"wb"); if(f==0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw _EXCEPTION_("couldn't write");} tlen x=sizeof(mynum); fwrite(&x,sizeof(x),1,f); tlen len=points.size(); fwrite(&len,sizeof(len),1,f); //Achtung: Dateigroesse bei 64-bit-Version ist groesser als die geschriebenen Daten size_t num=fwrite(&points[0],sizeof(points[0]),len,f); fclose(f); } const char *ext(){return ".rw2";} pcio_rw2() { reg(); } } pcio_1_1; struct pcio_asc:public PointCloudIO { void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname); vector<mynum>::const_iterator i; for(i=points.begin();i<points.end();) out <<*(i++)<<' ' <<*(i++)<<' ' <<*(i++)<<endl; } const char*ext(){ return ".asc"; } pcio_asc(){reg();} } pcio_2; struct pcio_gavabvrml:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { char buf[80]; ifstream in(fname); for(;;){ in.getline(buf,79); if(strstr(buf,"point [")!=0) break; if(in.eof())return; } mynum x,y,z; char cc; in.clear(); points.clear(); for(;;){ in>>x>>y>>z; if(in.fail())break; in>>cc; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } const char*ext(){ return ".wrl"; } pcio_gavabvrml(){reg();} } pcio_3; //create the points eually distributed over the surface. struct pcio_gavabvrml_equaldist:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { equaldist eq; char buf[80]; ifstream in(fname); for(;;){ in.getline(buf,79); if(strstr(buf,"point [")!=0) break; if(in.eof())return; } mynum x,y,z; char cc; in.clear(); eq.points.clear(); for(;;){ in>>x>>y>>z; if(in.fail())break; in>>cc; eq.points.push_back(x); eq.points.push_back(y); eq.points.push_back(z); } vector<int> bufidx; in.clear(); for(;;){ in.getline(buf,79); if(strstr(buf,"coordIndex [")!=0) break; if(in.eof())return; } int vidx; for(;;){ in>>vidx; if(in.fail())break; if(vidx>=0) bufidx.push_back(vidx); else { if(bufidx.size()==3) { eq.tris.resize(eq.tris.size()+3); copy(bufidx.begin(),bufidx.end(),eq.tris.end()-3); bufidx.clear(); } else if(bufidx.size()==4) { eq.quads.resize(eq.quads.size()+4); copy(bufidx.begin(),bufidx.end(),eq.quads.end()-4); bufidx.clear(); } else { eq.polygons.push_back(bufidx); bufidx.clear(); } } in>>cc; } in.close(); eq.createEqualDist(points,eq.points.size()/3); } const char*ext(){ return ".wrl"; } const char*format(){ return "equaldist"; } pcio_gavabvrml_equaldist(){reg();} } pcio_3_1; struct pcio_3drma:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname,ios::binary); points.clear(); short int n; assert(sizeof(short int)==2); assert(strstr(fname,".xyz")!=0); assert(sizeof(mynum)>=2); while(!in.eof()) { n=0; in.read((char*)&n,2); if(n==0)continue; int onpt=points.size(); points.resize(points.size()+n*3); //use output vector as read buffer short int*buf=(short int*)&points[onpt]; in.read((char*)buf,n*3*sizeof(short int)); //assign backwards, so you don't overwrite values that are still to be converted for(int i=n*3-1;i>=0;--i) { points[onpt+i]=buf[i]; } } } void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname,ios::binary); short int n; assert(sizeof(short int)==2); static const int nmax=((1<<15)-1); short int buf[1+3*nmax]; buf[0]=(short int)nmax; vector<mynum>::const_iterator it; for(it=points.begin(); points.end()-it >=nmax*3; ) { short int*pts=buf+1, *ptsend=pts+nmax*3; for(;pts!=ptsend;++pts,++it) *pts=(short int)*it; out.write((const char*)buf,sizeof(buf)); } buf[0] = (short int) ((points.end()-it)/3); for(short int*pts=buf+1;it!=points.end();++pts,++it) *pts=(short int)*it; out.write((const char*)&n,sizeof(n)); out.write((const char*)buf,(int(buf[0])*3+1)*sizeof(buf[0])); } const char*ext(){ return ".xyz"; } pcio_3drma(){reg();} } pcio_4; struct pcio_scandump_denker:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); while(!in.eof()) { buf[0]=0; in.getline(buf,80,'\n'); if('A'<=buf[0] && buf[0] <='Z' || buf[0]==0) continue; size_t ps=points.size(); points.resize(points.size()+3); #ifdef GNUCC const char*formatstr="%Lf,%Lf,%Lf"; #else const char*formatstr="%lf,%lf,%lf"; #endif if( sscanf(buf,formatstr, &points[ps],&points[ps+1],&points[ps+2])!=3 ) {cout<<"sth wrong at pos:"<<ps<<":"<<buf<<endl;} } in.close(); } const char*ext(){return ".dump";} pcio_scandump_denker() {reg();} } pcio_5; /* point cloud from zaman with 4 values per row: x,y,z,intensity */ struct pcio_zaman:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x,y,z,v; while(!in.eof()) { in>>x>>y>>z>>v; if(in.fail()) break; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } const char*ext(){ return ".txt"; } const char*format() {return "xyzi";} pcio_zaman(){reg();} } pcio_6; /* point cloud from zaman with 3 values per row: x,y,z */ struct pcio_csv:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x,y,z; while(!in.eof()) { in>>x; in.ignore(1,','); in>>y; in.ignore(1,','); in>>z; if(in.fail()) break; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname); vector<mynum>::const_iterator it; for(it=points.begin(); it!=points.end(); it+=3 ) { out<<it[0]<<','<<it[1]<<','<<it[2]<<'\n'; } } const char*ext(){ return ".csv"; } pcio_csv(){reg();} } pcio_7; /* point cloud from zaman with 4 values per row: x,y,z,intensity */ struct pcio_csv28:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x; while(!in.eof()) { in>>x; if(in.fail()) break; in.ignore(1,','); points.push_back(x); } in.close(); } void write_(const vector<mynum> & points , const char*fname,int n) { ofstream out(fname); assert(points.size()%n==0); out.precision(sizeof(mynum)*2); vector<mynum>::const_iterator it; for(it=points.begin(); it!=points.end(); it+=n ) { out<<it[0]; for(int i=1;i<n;++i) out<<','<<it[i]; out<<"\r\n"; } } void write_(const vector<mynum> & points , const char*fname) { write_(points,fname,28); } const char*ext(){ return ".csv"; } const char*format(){ return "csv28"; } pcio_csv28(){reg();} }pcio_8; //create the points eually distributed over the surface. struct pcio_off_equaldist:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { equaldist eq; char buf[80]; ifstream in(fname); in>>buf; int nverts,nfaces,nedges; in>>nverts>>nfaces>>nedges; mynum x,y,z; char cc; in.clear(); eq.points.clear(); for(int i=0;i<nverts;++i){ in>>x>>y>>z; if(in.fail())break; eq.points.push_back(x); eq.points.push_back(y); eq.points.push_back(z); } in.clear(); int vertsperface; for(int i=0;i<nfaces;++i){ in>>vertsperface; if(vertsperface==3) { int a,b,c; in>>a>>b>>c; eq.tris.push_back(a); eq.tris.push_back(b); eq.tris.push_back(c); } else if(vertsperface==4) { int a,b,c,d; in>>a>>b>>c>>d; eq.tris.push_back(a); eq.tris.push_back(b); eq.tris.push_back(c); eq.tris.push_back(d); } else { eq.polygons.resize(eq.polygons.size()+1); vector<int> &last=eq.polygons.back(); last.resize(vertsperface); for(int i=0;i<vertsperface;++i) { in>>last[i]; } } } in.close(); int npoints=(eq.points.size()/3) *10; if(npoints <1000)npoints= 1000; if(npoints>50000)npoints=50000; eq.createEqualDist(points,npoints); } const char*ext(){ return ".off"; } const char*format(){ return "offequaldist"; } pcio_off_equaldist(){reg();} } pcio_9_1; struct pcio_osg:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { std::ifstream in(fname); osgreadpoints(points,in); in.close(); } void write_(const vector<mynum> & points , const char*fname) { std::ofstream of(fname); osgpointcloud(of ,points); of.close(); } const char*ext(){ return ".osg"; } pcio_osg(){reg();} } pcio_10; #undef _EXCEPTION_
14,101
6,644
#include "symbols.hpp" #define FDP_MODULE "map" #include "indexer.hpp" #include "interfaces/if_symbols.hpp" #include "log.hpp" #include <fstream> #include <sstream> namespace { bool setup(symbols::Indexer& indexer, const fs::path& filename) { auto filestream = std::ifstream(filename); if(!filestream) return FAIL(false, "unable to open %s", filename.generic_string().data()); auto row = std::string{}; auto offset = uint64_t{}; auto type = char{}; auto symbol = std::string{}; while(std::getline(filestream, row)) { const auto ok = !!(std::istringstream{row} >> std::hex >> offset >> std::dec >> type >> symbol); if(!ok) return FAIL(false, "unable to parse row '%s' in file %s", row.data(), filename.generic_string().data()); indexer.add_symbol(symbol, offset); } return true; } } std::shared_ptr<symbols::Module> symbols::make_map(const std::string& module, const std::string& guid) { const auto* path = getenv("_LINUX_SYMBOL_PATH"); if(!path) return nullptr; const auto indexer = symbols::make_indexer(guid); if(!indexer) return nullptr; const auto ok = setup(*indexer, fs::path(path) / module / guid / "System.map"); if(!ok) return nullptr; indexer->finalize(); return indexer; }
1,410
459
#include "physx_character_handler.h" #include "actor.h" #include "camera.h" #include "character.h" #include "entity_manager.h" #include "gui_text.h" #include "transform.h" namespace lib_physics { PhysxCharacterHandler::PhysxCharacterHandler(physx::PxPhysics* phys, physx::PxScene* scene) : physics_(phys) { controller_manager_ = PxCreateControllerManager(*scene); report_callback = std::make_unique<PhysxReportCallback>(); add_callback_ = g_ent_mgr.RegisterAddComponentCallback<Character>( [&](lib_core::Entity ent) { add_character_.push_back(ent); }); remove_callback_ = g_ent_mgr.RegisterRemoveComponentCallback<Character>( [&](lib_core::Entity ent) { remove_character_.push_back(ent); }); } PhysxCharacterHandler::~PhysxCharacterHandler() { controller_manager_->release(); g_ent_mgr.UnregisterAddComponentCallback<Character>(add_callback_); g_ent_mgr.UnregisterRemoveComponentCallback<Character>(remove_callback_); } void PhysxCharacterHandler::UpdateCharacters(float dt) { for (auto& e : add_character_) CreateCharacterController(e); add_character_.clear(); for (auto& e : remove_character_) RemoveCharacterController(e); remove_character_.clear(); auto characters = g_ent_mgr.GetNewCbt<Character>(); if (characters) { float gravity_acc = -9.82f * dt; auto old_characters = g_ent_mgr.GetOldCbt<Character>(); auto char_ents = g_ent_mgr.GetEbt<Character>(); auto char_update = g_ent_mgr.GetNewUbt<Character>(); for (int i = 0; i < char_update->size(); ++i) { if (!(*char_update)[i]) continue; g_ent_mgr.MarkForUpdate<lib_graphics::Camera>(char_ents->at(i)); g_ent_mgr.MarkForUpdate<lib_graphics::Transform>(char_ents->at(i)); auto& c = characters->at(i); auto& old_c = old_characters->at(i); auto character = controllers_[char_ents->at(i)]; if (c.teleport) { character->setPosition( physx::PxExtendedVec3(c.port_loc[0], c.port_loc[1], c.port_loc[2])); c.teleport = false; g_ent_mgr.MarkForUpdate<lib_physics::Character>(char_ents->at(i)); } if (c.resize) { character->resize(c.height); old_c.height = c.height; c.resize = false; } c.vert_velocity = old_c.vert_velocity; c.vert_velocity += gravity_acc * 3.f; if (c.vert_velocity < 0.2f) c.vert_velocity += gravity_acc * 2.5f; c.vert_velocity += c.disp[1]; auto add_position = dt * c.vert_velocity; auto filter = physx::PxControllerFilters(); auto flags = character->move(physx::PxVec3(c.disp[0], add_position, c.disp[2]), 0.001f, dt, filter); c.disp.ZeroMem(); if (flags & physx::PxControllerCollisionFlag::eCOLLISION_UP && c.vert_velocity > 0.f) c.vert_velocity = 0.f; if (flags & physx::PxControllerCollisionFlag::eCOLLISION_DOWN) { c.vert_velocity = 0.f; c.grounded = true; } else { c.grounded = false; } auto pos = character->getPosition(); pos += (character->getPosition() - character->getFootPosition()) * 0.9f; lib_core::Vector3 pos_vec = {float(pos.x), float(pos.y), float(pos.z)}; c.pos = pos_vec; if (c.pos[0] == old_c.pos[0] && c.pos[1] == old_c.pos[1] && c.pos[2] == old_c.pos[2] && c.vert_velocity == old_c.vert_velocity && c.vert_velocity == 0.f) (*char_update)[i] = false; } } } void PhysxCharacterHandler::CreateCharacterController(lib_core::Entity ent) { RemoveCharacterController(ent); auto ent_ptr = g_ent_mgr.GetNewCbeR<Character>(ent); physx::PxCapsuleControllerDesc desc; desc.contactOffset = 0.2f; desc.density = ent_ptr->density; desc.position.x = ent_ptr->pos[0]; desc.position.y = ent_ptr->pos[1]; desc.position.z = ent_ptr->pos[2]; desc.height = ent_ptr->height; desc.radius = ent_ptr->radius; physx::PxMaterial* material = physics_->createMaterial(1.5, 1.5, 1.5); desc.material = material; desc.reportCallback = report_callback.get(); auto controller = controller_manager_->createController(desc); controllers_[ent] = controller; material->release(); } void PhysxCharacterHandler::RemoveCharacterController(lib_core::Entity ent) { if (controllers_.find(ent) != controllers_.end()) { controllers_[ent]->release(); controllers_.erase(ent); } } void PhysxCharacterHandler::PhysxReportCallback::onShapeHit( const physx::PxControllerShapeHit& hit) { auto type = hit.actor->getType(); if (type == physx::PxActorType::eRIGID_DYNAMIC) { auto rigid_dynamic = static_cast<physx::PxRigidDynamic*>(hit.actor); if (rigid_dynamic->getRigidBodyFlags() & physx::PxRigidBodyFlag::eKINEMATIC) return; if (hit.dir.y > -0.5) rigid_dynamic->addForce(hit.dir * hit.length * 10, physx::PxForceMode::eIMPULSE); } } void PhysxCharacterHandler::PhysxReportCallback::onControllerHit( const physx::PxControllersHit& hit) {} void PhysxCharacterHandler::PhysxReportCallback::onObstacleHit( const physx::PxControllerObstacleHit& hit) {} } // namespace lib_physics
5,195
1,832
#include <TMB.hpp> #include <string> const int DEBUG = 0; #include "../include/tmbTCSAM.hpp" template<class Type> Type objective_function<Type>::operator() () { //get data objects DATA_INTEGER(debug); //flag to print debugging info wtsPRINTSTR_DEBUG("Printing debugging information") DATA_STRUCT(stMC,structModelConfig); if (debug>2) wtsPRINTSTR_DEBUG("structModelConfig:") if (debug>2) wtsPRINTSTRUCT_DEBUG("mc = ",stMC) ModelConfig<Type>* pMC = ModelConfig<Type>::getInstance(stMC); if (debug>3) wtsPRINTSTR_DEBUG("class ModelConfig (testing local pointer):") if (debug>3) std::cout<<(*pMC)<<std::endl; if (debug>4) wtsPRINTSTR_DEBUG("class ModelConfig (testing static instance):") if (debug>4) std::cout<<(*(ModelConfig<Type>::getInstance()))<<std::endl; //for testing if (debug>2) wtsPRINTSTR_DEBUG("Printing testArray_zsmxray information") DATA_ARRAY(testArray_zsmxray); if (debug>2) wtsPRINTVAR_DEBUG("array dim = ",testArray_zsmxray.dim); if (debug>2) wtsPRINTVAR_DEBUG("array mlt = ",testArray_zsmxray.mult); if (debug>2) wtsPRINTVAR_DEBUG("ncols = ",testArray_zsmxray.cols()); if (debug>2) wtsPRINTVAR_DEBUG("nrows = ",testArray_zsmxray.rows()); //for testing vector<int> idx(7);//zsmxray { idx << 0,0,0,0,0,0,0; std::string str = "idx("; str += "0,0,0,0,0,0,0"; str +=")"; int res = calcIndex(idx,ModelConfig<Type>::getInstance()->dims); wtsPRINTVAR_DEBUG(str+" = ",res); Type t = testArray_zsmxray(res); wtsPRINTVAR_DEBUG("t = ",t); } { idx << 0,1,0,0,0,0,0; std::string str = "idx("; str +="0,1,0,0,0,0,0"; str +=")"; int res = calcIndex(idx,ModelConfig<Type>::getInstance()->dims); wtsPRINTVAR_DEBUG(str+" = ",res); Type t = testArray_zsmxray(res); wtsPRINTVAR_DEBUG("t = ",t); } { int idy = pMC->dims[con::iY]-1; idx << 0,0,0,0,0,0,idy; std::string str = "idx(";str+=+"0,0,0,0,0,0,"; str+=std::to_string(idy); str+=")"; int res = calcIndex(idx,ModelConfig<Type>::getInstance()->dims); wtsPRINTVAR_DEBUG(str+" = ",res); Type t = testArray_zsmxray(res); wtsPRINTVAR_DEBUG("t = ",t); } if (debug>20) { wtsPRINTSTR_DEBUG("Printing testArray_zsmxra information"); array<Type> testArray_zsmxra = testArray_zsmxray.col(0); wtsPRINTVAR_DEBUG("array dim = ",testArray_zsmxra.dim); wtsPRINTVAR_DEBUG("array mlt = ",testArray_zsmxra.mult); wtsPRINTVAR_DEBUG("ncols = ",testArray_zsmxra.cols()); wtsPRINTVAR_DEBUG("nrows = ",testArray_zsmxra.rows()); } //get parameter objects PARAMETER(pZ50); //selectivity parameter vector if (debug>1) wtsPRINTVAR_DEBUG("pZ50 = ",pZ50) PARAMETER(pSlp); //selectivity parameter vector if (debug>1) wtsPRINTVAR_DEBUG("pSlp = ",pSlp) //define objective function Type f = 0; //calculate selectivity curve double fZ = 100.0; vector<Type> p(2); p(0) = pZ50; p(1) = pSlp; vector<Type> s = asclogistic(stMC.zBs_z,p,fZ); //report s REPORT(s); //return objective function return f; }
3,217
1,268
#include <bits/stdc++.h> using namespace std; typedef intmax_t I; typedef pair<I, I> II; int main() { cout.sync_with_stdio(false); cin.tie(0); I n, k; cin >> n >> k; vector<I> t(n); for(I i = 0; i < n; ++i) { t[i] = i * 2; //cin >> t[i]; } sort(t.begin(), t.end()); vector<map<I, I>> u(3); for(I i = 0; i < n; ++i) { ++u[0][t[i]]; } for(I j = 1; j < 3; ++j) { for(auto it = u[j - 1].rbegin(); it != u[j - 1].rend(); ++it) { //cout << "'" << it->first << " " << it->second << '\n'; for(I i = 0; i < n; ++i) { u[j][it->first + t[i]] += it->second; } } } /*for(I i = 0; i < 3; ++i) { cout << i << ": "; for(II j : u[i]) { for(I l = 0; l < j.second; ++l) { cout << j.first << ' '; } } cout << '\n'; }*/ I c = 0; for(II p : u[2]) { c += p.second; if(c >= k) { cout << p.first << '\n'; break; } } return 0; }
1,095
474
/*!********************************************************************** \name EntryPoint \author Pedro Barreiro \date 19/03/2020 \version 1.0 *********************************************************************/ #include "EntryPoint.h" #include "MainWindow.h" #include <iostream> /*!********************************************************************** \name main \author Pedro Barreiro \date 19/03/2020 \version 1.0 \param[in] int argc \param[in] char* argv[] *********************************************************************/ int main(int argc, char* argv[]) { std::cout << "Sophie" << std::endl; sophie::MainWindow* mainWindow = new sophie::MainWindow; mainWindow->show(); std::cin.get(); }
751
257
// Copyright 2017 Google Inc. All Rights Reserved. // Author: ericv@google.com (Eric Veach) // // This example shows how to build and query an in-memory index of points // using S2PointIndex. #include <cinttypes> #include <cstdint> #include <cstdio> #include "s2/base/commandlineflags.h" #include "s2/s2earth.h" #include "absl/flags/flag.h" #include "s2/s1chord_angle.h" #include "s2/s2closest_point_query.h" #include "s2/s2point_index.h" #include "s2/s2testing.h" S2_DEFINE_int32(num_index_points, 10000, "Number of points to index"); S2_DEFINE_int32(num_queries, 10000, "Number of queries"); S2_DEFINE_double(query_radius_km, 100, "Query radius in kilometers"); int main(int argc, char **argv) { // Build an index containing random points anywhere on the Earth. S2PointIndex<int> index; for (int i = 0; i < absl::GetFlag(FLAGS_num_index_points); ++i) { index.Add(S2Testing::RandomPoint(), i); } // Create a query to search within the given radius of a target point. S2ClosestPointQuery<int> query(&index); query.mutable_options()->set_max_distance(S1Angle::Radians( S2Earth::KmToRadians(absl::GetFlag(FLAGS_query_radius_km)))); // Repeatedly choose a random target point, and count how many index points // are within the given radius of that point. int64_t num_found = 0; for (int i = 0; i < absl::GetFlag(FLAGS_num_queries); ++i) { S2ClosestPointQuery<int>::PointTarget target(S2Testing::RandomPoint()); num_found += query.FindClosestPoints(&target).size(); } std::printf("Found %" PRId64 " points in %d queries\n", num_found, absl::GetFlag(FLAGS_num_queries)); return 0; }
1,646
623
#include "npp/cdb/payload_adapter_db.h" #include <mutex> #include "npp/util/base64.h" #include "npp/util/json_schema.h" #include "npp/util/log.h" #include "npp/util/rng.h" #include "npp/util/util.h" #include "npp/util/uuid.h" #include "npp/cdb/http_client.h" namespace NPP { namespace CDB { using namespace soci; using namespace NPP::Util; std::mutex cdbnpp_db_access_mutex; // protects db calls, as SOCI is not thread-safe PayloadAdapterDb::PayloadAdapterDb() : IPayloadAdapter("db") {} PayloadResults_t PayloadAdapterDb::getPayloads( const std::set<std::string>& paths, const std::vector<std::string>& flavors, const PathToTimeMap_t& maxEntryTimeOverrides, int64_t maxEntryTime, int64_t eventTime, int64_t run, int64_t seq ) { PayloadResults_t res; if ( !ensureMetadata() ) { return res; } std::set<std::string> unfolded_paths{}; for ( const auto& path : paths ) { std::vector<std::string> parts = explode( path, ":" ); std::string flavor = parts.size() == 2 ? parts[0] : ""; std::string unflavored_path = parts.size() == 2 ? parts[1] : parts[0]; if ( mPaths.count(unflavored_path) == 0 ) { for ( const auto& [ key, value ] : mPaths ) { if ( string_starts_with( key, unflavored_path ) && value->mode() > 0 ) { unfolded_paths.insert( ( flavor.size() ? ( flavor + ":" ) : "" ) + key ); } } } else { unfolded_paths.insert( path ); } } for ( const auto& path : unfolded_paths ) { Result<SPayloadPtr_t> rc = getPayload( path, flavors, maxEntryTimeOverrides, maxEntryTime, eventTime, run, seq ); if ( rc.valid() ) { SPayloadPtr_t p = rc.get(); res.insert({ p->directory() + "/" + p->structName(), p }); } } return res; } Result<SPayloadPtr_t> PayloadAdapterDb::getPayload( const std::string& path, const std::vector<std::string>& service_flavors, const PathToTimeMap_t& maxEntryTimeOverrides, int64_t maxEntryTime, int64_t eventTime, int64_t eventRun, int64_t eventSeq ) { Result<SPayloadPtr_t> res; if ( !ensureMetadata() ) { res.setMsg("cannot get metadata"); return res; } if ( !setAccessMode("get") ) { res.setMsg( "cannot switch to GET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure database connection"); return res; } auto [ flavors, directory, structName, is_path_valid ] = Payload::decodePath( path ); if ( !is_path_valid ) { res.setMsg( "request path has not been decoded, path: " + path ); return res; } if ( !service_flavors.size() && !flavors.size() ) { res.setMsg( "no flavor specified, path: " + path ); return res; } if ( !directory.size() ) { res.setMsg( "request does not specify directory, path: " + path ); return res; } if ( !structName.size() ) { res.setMsg( "request does not specify structName, path: " + path ); return res; } std::string dirpath = directory + "/" + structName; // check for path-specific maxEntryTime overrides if ( maxEntryTimeOverrides.size() ) { for ( const auto& [ opath, otime ] : maxEntryTimeOverrides ) { if ( string_starts_with( dirpath, opath ) ) { maxEntryTime = otime; break; } } } // get tag auto tagit = mPaths.find( dirpath ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag for the " + dirpath ); return res; } // get tbname from tag std::string tbname = tagit->second->tbname(), pid = tagit->second->id(); if ( !tbname.size() ) { res.setMsg( "requested path points to the directory, need struct: " + dirpath ); return res; } for ( const auto& flavor : ( flavors.size() ? flavors : service_flavors ) ) { std::string id{""}, uri{""}, fmt{""}; uint64_t bt = 0, et = 0, ct = 0, dt = 0, run = 0, seq = 0, mode = tagit->second->mode(); if ( mode == 2 ) { // fetch id, run, seq { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT id, uri, bt, et, ct, dt, run, seq, fmt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND run = :run " + "AND seq = :seq " + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY ct DESC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventRun, "run" ), use( eventSeq, "seq" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventRun, "run" ), use( eventSeq, "seq" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !id.size() ) { continue; } // nothing found } else if ( mode == 1 ) { // fetch id, bt, et { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT id, uri, bt, et, ct, dt, run, seq, fmt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND bt <= :et AND ( et = 0 OR et > :et ) " + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY bt DESC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventTime, "et" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventTime, "et" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !id.size() ) { continue; } // nothing found if ( et == 0 ) { // if no endTime, do another query to establish endTime { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT bt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND bt >= :et " + "AND ( et = 0 OR et < :et )" + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY bt ASC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(et), use( flavor, "flavor"), use( eventTime, "et" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(et), use( flavor, "flavor"), use( eventTime, "et" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !et ) { et = std::numeric_limits<uint64_t>::max(); } } } // create payload ptr, populate with data auto p = std::make_shared<Payload>( id, pid, flavor, structName, directory, ct, bt, et, dt, run, seq ); p->setURI( uri ); res = p; return res; } return res; } Result<std::string> PayloadAdapterDb::setPayload( const SPayloadPtr_t& payload ) { Result<std::string> res; if ( !payload->ready() ) { res.setMsg( "payload is not ready to be stored" ); return res; } if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata"); return res; } if ( payload->dataSize() && payload->format() != "dat" ) { // validate json against schema if exists Result<std::string> schema = getTagSchema( payload->directory() + "/" + payload->structName() ); if ( schema.valid() ) { Result<bool> rc = validate_json_using_schema( payload->dataAsJson(), schema.get() ); if ( rc.invalid() ) { res.setMsg( "schema validation failed" ); return res; } } } // get tag, fetch tbname auto tagit = mPaths.find( payload->directory() + "/" + payload->structName() ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find payload tag in the database: " + payload->directory() + "/" + payload->structName() ); return res; } std::string tbname = tagit->second->tbname(); sanitize_alnumuscore(tbname); // unpack values for SOCI std::string id = payload->id(), pid = payload->pid(), flavor = payload->flavor(), fmt = payload->format(); int64_t ct = std::time(nullptr), bt = payload->beginTime(), et = payload->endTime(), run = payload->run(), seq = payload->seq(); if ( !setAccessMode("set") ) { res.setMsg( "cannot switch to SET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("db adapter cannot connect to the database"); return res; } // insert iov into cdb_iov_<table-name>, data into cdb_data_<table-name> { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { int64_t dt = 0; transaction tr( *mSession.get() ); if ( !payload->URI().size() && payload->dataSize() ) { // if uri is empty and data is not empty, store data locally to the database size_t data_size = payload->dataSize(); std::string data = base64::encode( payload->data() ); mSession->once << ( "INSERT INTO cdb_data_" + tbname + " ( id, pid, ct, dt, data, size ) VALUES ( :id, :pid, :ct, :dt, :data, :size )" ) ,use(id), use(pid), use(ct), use(dt), use(data), use(data_size); payload->setURI( "db://" + tbname + "/" + id ); } std::string uri = payload->URI(); mSession->once << ( "INSERT INTO cdb_iov_" + tbname + " ( id, pid, flavor, ct, bt, et, dt, run, seq, uri, fmt ) VALUES ( :id, :pid, :flavor, :ct, :bt, :et, :dt, :run, :seq, :uri, :bin )" ) ,use(id), use(pid), use(flavor), use(ct), use(bt), use(et), use(dt), use(run), use(seq), use(uri), use(fmt); tr.commit(); res = id; } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex return res; } Result<std::string> PayloadAdapterDb::deactivatePayload( const SPayloadPtr_t& payload, int64_t deactiveTime ) { Result<std::string> res; if ( !payload->ready() ) { res.setMsg( "payload is not ready to be used for deactivation" ); return res; } if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("db adapter cannot connect to the database"); return res; } // get tag, fetch tbname auto tagit = mPaths.find( payload->directory() + "/" + payload->structName() ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find payload tag in the database: " + payload->directory() + "/" + payload->structName() ); return res; } std::string tbname = tagit->second->tbname(); sanitize_alnumuscore(tbname); std::string id = payload->id(); sanitize_alnumdash(id); { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "UPDATE cdb_iov_" + tbname + " SET dt = :dt WHERE id = :id", use(deactiveTime), use( id ); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } res = id; return res; } Result<SPayloadPtr_t> PayloadAdapterDb::prepareUpload( const std::string& path ) { Result<SPayloadPtr_t> res; // check if Db Adapter is configured for writes if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } auto [ flavors, directory, structName, is_path_valid ] = Payload::decodePath( path ); if ( !flavors.size() ) { res.setMsg( "no flavor provided: " + path ); return res; } if ( !is_path_valid ) { res.setMsg( "bad path provided: " + path ); return res; } // see if path exists in the known tags map auto tagit = mPaths.find( directory + "/" + structName ); if ( tagit == mPaths.end() ) { res.setMsg( "path does not exist in the db. path: " + path ); return res; } // check if path is really a struct if ( !tagit->second->tbname().size() ) { res.setMsg( "cannot upload to the folder, need struct. path: " + path ); return res; } SPayloadPtr_t p = std::make_shared<Payload>(); p->setId( generate_uuid() ); p->setPid( tagit->second->id() ); p->setFlavor( flavors[0] ); p->setDirectory( directory ); p->setStructName( structName ); p->setMode( tagit->second->mode() ); res = p; return res; } Result<bool> PayloadAdapterDb::dropTagSchema( const std::string& tag_path ) { Result<bool> res; if ( !ensureMetadata() ) { res.setMsg("cannot ensure metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg("cannot set ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } // make sure tag_path exists and is a struct std::string sanitized_path = tag_path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != tag_path ) { res.setMsg( "sanitized tag path != input tag path... path: " + sanitized_path ); return res; } std::string tag_pid = ""; auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag path in the database... path: " + sanitized_path ); return res; } tag_pid = (tagit->second)->id(); // find tbname and id for the tag std::string tbname = (tagit->second)->tbname(); if ( !tbname.size() ) { res.setMsg( "tag is not a struct... path: " + sanitized_path ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "DELETE FROM cdb_schemas WHERE pid = :pid", use(tag_pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } res = true; return res; } Result<bool> PayloadAdapterDb::createDatabaseTables() { Result<bool> res; if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "cannot connect to the database" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { transaction tr( *mSession.get() ); // cdb_tags { soci::ddl_type ddl = mSession->create_table("cdb_tags"); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("name", soci::dt_string, 128 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("mode", soci::dt_unsigned_long_long )("not null default 0"); // 0 = tag, 1 = struct bt,et; 2 = struct run,seq ddl.column("tbname", soci::dt_string, 512 )("not null"); ddl.primary_key("cdb_tags_pk", "pid,name,dt"); ddl.unique("cdb_tags_id", "id"); } // cdb_schemas { soci::ddl_type ddl = mSession->create_table("cdb_schemas"); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("null default 0"); ddl.column("data", soci::dt_string )("not null"); ddl.primary_key("cdb_schemas_pk", "pid,dt"); ddl.unique("cdb_schemas_id", "id"); } tr.commit(); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } Result<bool> PayloadAdapterDb::createIOVDataTables( const std::string& tablename, bool create_storage ) { Result<bool> res; if ( !setAccessMode("admin") ) { res.setMsg("cannot get ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } { //RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { transaction tr( *mSession.get() ); // cdb_iov_<tablename> { soci::ddl_type ddl = mSession->create_table("cdb_iov_"+tablename); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("flavor", soci::dt_string, 128 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("bt", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 0 ddl.column("et", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 0 ddl.column("run", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 1 ddl.column("seq", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 1 ddl.column("fmt", soci::dt_string, 36 )("not null"); // see Service::formats() ddl.column("uri", soci::dt_string, 2048 )("not null"); ddl.primary_key("cdb_iov_"+tablename+"_pk", "pid,bt,run,seq,dt,flavor"); ddl.unique("cdb_iov_"+tablename+"_id", "id"); } mSession->once << "CREATE INDEX cdb_iov_" + tablename + "_ct ON cdb_iov_" + tablename + " (ct)"; if ( create_storage ) { // cdb_data_<tablename> { soci::ddl_type ddl = mSession->create_table("cdb_data_"+tablename); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("data", soci::dt_string )("not null"); ddl.column("size", soci::dt_unsigned_long_long )("not null default 0"); ddl.primary_key("cdb_data_"+tablename+"_pk", "id,pid,dt"); ddl.unique("cdb_data_"+tablename+"_id", "id"); } mSession->once << "CREATE INDEX cdb_data_" + tablename + "_pid ON cdb_data_" + tablename + " (pid)"; mSession->once << "CREATE INDEX cdb_data_" + tablename + "_ct ON cdb_data_" + tablename + " (ct)"; } tr.commit(); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } std::vector<std::string> PayloadAdapterDb::listDatabaseTables() { std::vector<std::string> tables; if ( !setAccessMode("admin") ) { return tables; } if ( !ensureConnection() ) { return tables; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string name; soci::statement st = (mSession->prepare_table_names(), into(name)); st.execute(); while (st.fetch()) { tables.push_back( name ); } } catch( std::exception const & e ) { // database exception: " << e.what() tables.clear(); } } // RAII scope block for the db access mutex return tables; } Result<bool> PayloadAdapterDb::dropDatabaseTables() { Result<bool> res; std::vector<std::string> tables = listDatabaseTables(); if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "cannot connect to the database" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { for ( const auto& tbname : tables ) { mSession->drop_table( tbname ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } res = true; } // RAII scope block for the db access mutex return res; } bool PayloadAdapterDb::setAccessMode( const std::string& mode ) { if ( !hasAccess(mode) ) { // cannot set access mode return false; } if ( mAccessMode == mode ) { return true; } mAccessMode = mode; if ( isConnected() ) { return reconnect(); } return true; } void PayloadAdapterDb::disconnect() { if ( !isConnected() ) { return; } { // RAII block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->close(); mIsConnected = false; mDbType = ""; } catch ( std::exception const & e ) { // database exception, e.what() } } // RAII block for the db access mutex } bool PayloadAdapterDb::connect( const std::string& dbtype, const std::string& host, int port, const std::string& user, const std::string& pass, const std::string& dbname, const std::string& options ) { if ( isConnected() ) { disconnect(); } { // RAII block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); if ( mSession == nullptr ) { mSession = std::make_shared<soci::session>(); } std::string connect_string{ dbtype + "://" + ( host.size() ? "host=" + host : "") + ( port > 0 ? " port=" + std::to_string(port) : "" ) + ( user.size() ? " user=" + user : "" ) + ( pass.size() ? " password=" + pass : "" ) + ( dbname.size() ? " dbname=" + dbname : "" ) + ( options.size() ? " " + options : "" ) }; try { mSession->open( connect_string ); } catch ( std::exception const & e ) { // database exception: " << e.what() return false; } mIsConnected = true; mDbType = dbtype; } // RAII scope block for the db access mutex return true; } bool PayloadAdapterDb::reconnect() { if ( !hasAccess( mAccessMode ) ) { return false; } if ( isConnected() ) { disconnect(); } int port{0}; std::string dbtype{}, host{}, user{}, pass{}, dbname{}, options{}; nlohmann::json node; size_t idx = RngS::Instance().random_inclusive<size_t>( 0, mConfig["adapters"]["db"][ mAccessMode ].size() - 1 ); node = mConfig["adapters"]["db"][ mAccessMode ][ idx ]; if ( node.contains("dbtype") ) { dbtype = node["dbtype"]; } if ( node.contains("host") ) { host = node["host"]; } if ( node.contains("port") ) { port = node["port"]; } if ( node.contains("user") ) { user = node["user"]; } if ( node.contains("pass") ) { pass = node["pass"]; } if ( node.contains("dbname") ) { dbname = node["dbname"]; } if ( node.contains("options") ) { options = node["options"]; } return connect( dbtype, host, port, user, pass, dbname, options ); } bool PayloadAdapterDb::ensureMetadata() { return mMetadataAvailable ? true : downloadMetadata(); } bool PayloadAdapterDb::downloadMetadata() { if ( !ensureConnection() ) { return false; } const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); if ( mMetadataAvailable ) { return true; } mTags.clear(); mPaths.clear(); // download tags and populate lookup map: tag ID => Tag obj try { std::string id, name, pid, tbname, schema_id; int64_t ct, dt, mode; soci::indicator ind; statement st = ( mSession->prepare << "SELECT t.id, t.name, t.pid, t.tbname, t.ct, t.dt, t.mode, COALESCE(s.id,'') as schema_id FROM cdb_tags t LEFT JOIN cdb_schemas s ON t.id = s.pid", into(id), into(name), into(pid), into(tbname), into(ct), into(dt), into(mode), into(schema_id, ind) ); st.execute(); while (st.fetch()) { mTags.insert({ id, std::make_shared<Tag>( id, name, pid, tbname, ct, dt, mode, ind == i_ok ? schema_id : "" ) }); } } catch ( std::exception const & e ) { // database exception: " << e.what() return false; } if ( mTags.size() ) { // erase tags that have parent id but no parent exists => side-effect of tag deactivation and/or maxEntryTime // unfortunately, std::erase_if is C++20 container_erase_if( mTags, [this]( const auto item ) { return ( item.second->pid().size() && mTags.find( item.second->pid() ) == mTags.end() ); }); } // parent-child: assign children and parents if ( mTags.size() ) { for ( auto& tag : mTags ) { if ( !(tag.second)->pid().size() ) { continue; } auto rc = mTags.find( ( tag.second )->pid() ); if ( rc == mTags.end() ) { continue; } ( tag.second )->setParent( rc->second ); ( rc->second )->addChild( tag.second ); } // populate lookup map: path => Tag obj for ( const auto& tag : mTags ) { mPaths.insert({ ( tag.second )->path(), tag.second }); } } // TODO: filter mTags and mPaths based on maxEntryTime return true; } Result<std::string> PayloadAdapterDb::createTag( const STagPtr_t& tag ) { return createTag( tag->id(), tag->name(), tag->pid(), tag->tbname(), tag->ct(), tag->dt(), tag->mode() ); } Result<std::string> PayloadAdapterDb::createTag( const std::string& path, int64_t tag_mode ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to database"); return res; } std::string sanitized_path = path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != path ) { res.setMsg( "path contains unwanted characters, path: " + path ); return res; } // check for existing tag if ( mPaths.find( sanitized_path ) != mPaths.end() ) { res.setMsg( "attempt to create an existing tag " + sanitized_path ); return res; } std::string tag_id = uuid_from_str( sanitized_path ), tag_name = "", tag_tbname = "", tag_pid = ""; if ( !tag_id.size() ) { res.setMsg( "new tag uuid generation failed" ); return res; } long long tag_ct = time(0), tag_dt = 0; Tag* parent_tag = nullptr; std::vector<std::string> parts = explode( sanitized_path, '/' ); tag_name = parts.back(); parts.pop_back(); sanitized_path = parts.size() ? implode( parts, "/" ) : ""; if ( sanitized_path.size() ) { auto ptagit = mPaths.find( sanitized_path ); if ( ptagit != mPaths.end() ) { parent_tag = (ptagit->second).get(); tag_pid = parent_tag->id(); } else { res.setMsg( "parent tag does not exist: " + sanitized_path ); return res; } } if ( tag_mode > 0 ) { tag_tbname = ( parent_tag ? parent_tag->path() + "/" + tag_name : tag_name ); std::replace( tag_tbname.begin(), tag_tbname.end(), '/', '_'); string_to_lower_case( tag_tbname ); } return createTag( tag_id, tag_name, tag_pid, tag_tbname, tag_ct, tag_dt, tag_mode ); } Result<std::string> PayloadAdapterDb::deactivateTag( const std::string& path, int64_t deactiveTime ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "db adapter is not configured for writes" ); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to database"); return res; } std::string sanitized_path = path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != path ) { res.setMsg( "path contains unwanted characters, path: " + path ); return res; } // check for existing tag auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find path in the database, path: " + path ); return res; } std::string tag_id = tagit->second->id(); if ( !tag_id.size() ) { res.setMsg( "empty tag id found" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "UPDATE cdb_tags SET dt = :dt WHERE id = :id", use(deactiveTime), use(tag_id); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } res = tag_id; } // RAII scope block for the db access mutex return res; } Result<std::string> PayloadAdapterDb::createTag( const std::string& tag_id, const std::string& tag_name, const std::string& tag_pid, const std::string& tag_tbname, int64_t tag_ct, int64_t tag_dt, int64_t tag_mode ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !tag_id.size() ) { res.setMsg( "cannot create new tag: empty tag id provided" ); return res; } if ( !tag_name.size() ) { res.setMsg( "cannot create new tag: empty tag name provided" ); return res; } if ( tag_pid.size() && mTags.find( tag_pid ) == mTags.end() ) { res.setMsg( "parent tag provided but not found in the map" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "db adapter cannot ensure connection" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); // insert new tag into the database try { mSession->once << "INSERT INTO cdb_tags ( id, name, pid, tbname, ct, dt, mode ) VALUES ( :id, :name, :pid, :tbname, :ct, :dt, :mode ) ", use(tag_id), use(tag_name), use(tag_pid), use(tag_tbname), use(tag_ct), use(tag_dt), use(tag_mode); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex // if it is a struct, create IOV + Data tables if ( tag_tbname.size() ) { Result<bool> rc = createIOVDataTables( tag_tbname ); if ( rc.invalid() ) { res.setMsg( "failed to create IOV Data Tables for tag: " + tag_name + ", tbname: " + tag_tbname ); return res; } } // create new tag object and set parent-child relationship STagPtr_t new_tag = std::make_shared<Tag>( tag_id, tag_name, tag_pid, tag_tbname, tag_ct, tag_dt ); if ( tag_pid.size() ) { STagPtr_t parent_tag = ( mTags.find( tag_pid ) )->second; new_tag->setParent( parent_tag ); parent_tag->addChild( new_tag ); } // add new tag to maps mTags.insert({ tag_id, new_tag }); mPaths.insert({ new_tag->path(), new_tag }); res = tag_id; return res; } std::vector<std::string> PayloadAdapterDb::getTags( bool skipStructs ) { std::vector<std::string> tags; if ( !ensureMetadata() ) { return tags; } if ( !setAccessMode("get") ) { return tags; } if ( !ensureConnection() ) { return tags; } tags.reserve( mPaths.size() ); for ( const auto& [key, value] : mPaths ) { if ( value->mode() == 0 ) { const auto& children = value->children(); if ( children.size() == 0 ) { tags.push_back( "[-] " + key ); } else { bool has_folders = std::find_if( children.begin(), children.end(), []( auto& child ) { return child.second->tbname().size() == 0; } ) != children.end(); if ( has_folders ) { tags.push_back( "[+] " + key ); } else { tags.push_back( "[-] " + key ); } } } else if ( !skipStructs ) { std::string schema = "-"; if ( value->schema().size() ) { schema = "s"; } tags.push_back( "[s/" + schema + "/" + std::to_string( value->mode() ) + "] " + key ); } } return tags; } Result<std::string> PayloadAdapterDb::downloadData( const std::string& uri ) { Result<std::string> res; if ( !uri.size() ) { res.setMsg("empty uri"); return res; } // uri = db://<tablename>/<item-uuid> auto parts = explode( uri, "://" ); if ( parts.size() != 2 || parts[0] != "db" ) { res.setMsg("bad uri"); return res; } if ( !setAccessMode("get") ) { res.setMsg( "db adapter is not configured" ); } if ( !ensureConnection() ) { res.setMsg("cannot ensure database connection"); return res; } auto tbparts = explode( parts[1], "/" ); if ( tbparts.size() != 2 ) { res.setMsg("bad uri tbname"); return res; } std::string storage_name = tbparts[0], id = tbparts[1], data; { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << ("SELECT data FROM cdb_data_" + storage_name + " WHERE id = :id"), into(data), use( id ); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope lock for the db access mutex if ( !data.size() ) { res.setMsg("no data"); return res; } res = base64::decode(data); return res; } Result<std::string> PayloadAdapterDb::getTagSchema( const std::string& tag_path ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg("cannot download metadata"); return res; } if ( !setAccessMode("get") ) { res.setMsg("cannot switch to GET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to the database"); return res; } auto tagit = mPaths.find( tag_path ); if ( tagit == mPaths.end() ) { res.setMsg("cannot find path"); return res; } std::string pid = tagit->second->id(); std::string schema{""}; { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "SELECT data FROM cdb_schemas WHERE pid = :pid ", into(schema), use(pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( schema.size() ) { res = schema; } else { res.setMsg("no schema"); } return res; } Result<std::string> PayloadAdapterDb::exportTagsSchemas( bool tags, bool schemas ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg("cannot download metadata"); return res; } if ( !mTags.size() || !mPaths.size() ) { res.setMsg("no tags, cannot export"); return res; } if ( !tags && !schemas ) { res.setMsg( "neither tags nor schemas were requested for export"); return res; } nlohmann::json output; output["export_type"] = "cdbnpp_tags_schemas"; output["export_timestamp"] = std::time(nullptr); if ( tags ) { output["tags"] = nlohmann::json::array(); } if ( schemas ) { output["schemas"] = nlohmann::json::array(); } for ( const auto& [ key, value ] : mPaths ) { if ( tags ) { output["tags"].push_back( value->toJson() ); } if ( schemas && value->schema().size() ) { Result<std::string> schema_str = getTagSchema( key ); if ( schema_str.valid() ) { output["schemas"].push_back({ { "id", value->schema() }, { "pid", value->id() }, { "path", value->path() }, {"data", schema_str.get() } }); } // cannot get schema for a tag, contact db admin :( } } res = output.dump(2); return res; } Result<bool> PayloadAdapterDb::importTagsSchemas(const std::string& stringified_json ) { Result<bool> res; if ( !stringified_json.size() ) { res.setMsg("empty tag/schema data provided"); return res; } nlohmann::json data = nlohmann::json::parse( stringified_json.begin(), stringified_json.end(), nullptr, false, true ); if ( data.empty() || data.is_discarded() || data.is_null() ) { res.setMsg( "bad input data" ); return res; } bool tag_import_errors = false, schema_import_errors = false; if ( data.contains("tags") ) { for ( const auto& [ key, tag ] : data["tags"].items() ) { Result<std::string> rc = createTag( tag["id"].get<std::string>(), tag["name"].get<std::string>(), tag["pid"].get<std::string>(), tag["tbname"].get<std::string>(), tag["ct"].get<uint64_t>(), tag["dt"].get<uint64_t>(), tag["mode"].get<uint64_t>() ); if ( rc.invalid() ) { tag_import_errors = true; } } } if ( data.contains("schemas") ) { for ( const auto& [ key, schema ] : data["schemas"].items() ) { Result<bool> rc = setTagSchema( schema["path"].get<std::string>(), schema["data"].get<std::string>() ); if ( rc.invalid() ) { schema_import_errors = true; } } } res = !tag_import_errors && !schema_import_errors; return res; } Result<bool> PayloadAdapterDb::setTagSchema( const std::string& tag_path, const std::string& schema_json ) { Result<bool> res; if ( !schema_json.size() ) { res.setMsg( "empty tag schema provided" ); return res; } if ( !ensureMetadata() ) { res.setMsg("cannot ensure metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg("cannot set ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } // make sure tag_path exists and is a struct std::string sanitized_path = tag_path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != tag_path ) { res.setMsg("sanitized tag path != input tag path... path: " + sanitized_path ); return res; } std::string tag_pid = ""; auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag path in the database... path: " + sanitized_path ); return res; } tag_pid = (tagit->second)->id(); // find tbname and id for the tag std::string tbname = (tagit->second)->tbname(); if ( !tbname.size() ) { res.setMsg( "tag is not a struct... path: " + sanitized_path ); return res; } std::string existing_id = ""; { // RAII scope block for the db access schema const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "SELECT id FROM cdb_schemas WHERE pid = :pid ", into(existing_id), use(tag_pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access schema if ( existing_id.size() ) { res.setMsg( "cannot set schema as it already exists for " + sanitized_path ); return res; } // validate schema against schema std::string schema = R"({ "$id": "file://.cdbnpp_config.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "CDBNPP Config File", "type": "object", "required": [ "$id", "$schema", "properties", "required" ], "properties": { "$id": { "type": "string" }, "$schema": { "type": "string" }, "properties": { "type": "object" }, "required": { "type": "array", "items": { "type": "string" } } } })"; Result<bool> rc = validate_json_using_schema( schema_json, schema ); if ( rc.invalid() ) { res.setMsg( "proposed schema is invalid" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); // insert schema into cdb_schemas table try { std::string schema_id = generate_uuid(), data = schema_json; long long ct = 0, dt = 0; mSession->once << "INSERT INTO cdb_schemas ( id, pid, data, ct, dt ) VALUES( :schema_id, :pid, :data, :ct, :dt )", use(schema_id), use(tag_pid), use(data), use(ct), use(dt); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } } // namespace CDB } // namespace NPP
40,347
16,963
/* Copyright (C) 2010-2013 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to 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) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ /* These need to be before any possible inclusions of stdint.h or inttypes.h. * */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include "../generator/make_graph.h" #include "../generator/utils.h" // #include "/home/jewillco/mpe-install/include/mpe.h" #include "common.hpp" #include "bitmap.hpp" #include "onesided.hpp" #include <math.h> #include <mpi.h> #include <assert.h> #include <string.h> #include <stdlib.h> #include <stddef.h> #include <stdio.h> #include <stdarg.h> #include <limits.h> #include <stdint.h> #include <inttypes.h> #include <algorithm> #include <execinfo.h> #include <unistd.h> #include <iostream> #include <iomanip> #if defined(CRAYPAT) && 0 #include <pat_api.h> #warning "CrayPAT on" #endif static int compare_doubles(const void* a, const void* b) { double aa = *(const double*)a; double bb = *(const double*)b; return (aa < bb) ? -1 : (aa == bb) ? 0 : 1; } enum {s_minimum, s_firstquartile, s_median, s_thirdquartile, s_maximum, s_mean, s_std, s_LAST}; static void get_statistics(const double x[], int n, double r[s_LAST]) { double temp; /* Compute mean. */ temp = 0.; for (int i = 0; i < n; ++i) temp += x[i]; temp /= n; r[s_mean] = temp; /* Compute std. dev. */ temp = 0.; for (int i = 0; i < n; ++i) temp += (x[i] - r[s_mean]) * (x[i] - r[s_mean]); temp /= double(n - 1); r[s_std] = sqrt(temp); /* Sort x. */ double* xx = (double*)xmalloc(n * sizeof(double)); memcpy(xx, x, n * sizeof(double)); qsort(xx, n, sizeof(double), compare_doubles); /* Get order statistics. */ r[s_minimum] = xx[0]; r[s_firstquartile] = (xx[(n - 1) / 4] + xx[n / 4]) * .5; r[s_median] = (xx[(n - 1) / 2] + xx[n / 2]) * .5; r[s_thirdquartile] = (xx[n - 1 - (n - 1) / 4] + xx[n - 1 - n / 4]) * .5; r[s_maximum] = xx[n - 1]; /* Clean up. */ xfree(xx); } void do_trace(const char* fmt, ...) __attribute__((format(printf, 1, 2))); void do_trace(const char* fmt, ...) { (void)fmt; #if 0 if (rank != 0) return; va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fflush(stderr); void* trace[20]; int len = backtrace(trace, 20), i; fprintf(stderr, "Trace length %d\n", len); for (i = 0; i < len; ++i) fprintf(stderr, "%d: %p\n", i, trace[i]); backtrace_symbols_fd(trace, len, 2); fsync(2); #endif } std::ostream& operator<<(std::ostream& os, const bfs_settings& s) { os << "compression=" << s.compression_level << " nbfs=" << s.nbfs << " keep_queue_stats=" << std::boolalpha << s.keep_queue_stats << " keep_average_level_times=" << s.keep_average_level_times << " official_results=" << s.official_results << " bcast_step_size=" << s.bcast_step_size; return os; } uint_fast32_t seed[5]; // These two are used in common.hpp for graph regen int SCALE; int main(int argc, char** argv) { #ifdef _OPENMP int thr_wanted; #if 0 MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &thr_wanted); if (!(thr_wanted >= MPI_THREAD_SERIALIZED)) { if (rank == 0) { fprintf(stderr, "When compiled with OpenMP, this code requires MPI_THREAD_SERIALIZED\n"); } MPI_Abort(MPI_COMM_WORLD, 50); } #endif MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &thr_wanted); if (!(thr_wanted >= MPI_THREAD_MULTIPLE)) { if (rank == 0) { fprintf(stderr, "When compiled with OpenMP, this code requires MPI_THREAD_MULTIPLE\n"); } MPI_Abort(MPI_COMM_WORLD, 50); } #else MPI_Init(&argc, &argv); #endif #ifdef _OPENMP #pragma omp parallel fprintf(stderr, "%s", ""); // Make sure threads run #endif // MPE_Stop_log(); #if defined(CRAYPAT) && 0 PAT_record(PAT_STATE_OFF); #endif setup_globals(); /* Parse arguments. */ SCALE = 26; int edgefactor = 16; /* nedges / nvertices, i.e., 2*avg. degree */ if (argc >= 2) SCALE = atoi(argv[1]); if (argc >= 3) edgefactor = atoi(argv[2]); if (argc <= 1 || argc >= 4 || SCALE == 0 || edgefactor == 0) { if (rank == 0) { fprintf(stderr, "Usage: %s SCALE edgefactor\n SCALE = log_2(# vertices) [integer, required]\n edgefactor = (# edges) / (# vertices) = .5 * (average vertex degree) [integer, defaults to 16]\n(Random number seed and Kronecker initiator are in main.c)\n", argv[0]); } MPI_Abort(MPI_COMM_WORLD, 1); } uint64_t seed1 = 2, seed2 = 3; tuple_graph tg; tg.nglobaledges = (uint64_t)(edgefactor) << SCALE; uint64_t nglobalverts = (uint64_t)(1) << SCALE; /* Make the raw graph edges. */ /* Get roots for BFS runs, plus maximum vertex with non-zero degree (used by * validator). */ // unsigned int num_bfs_roots = 64; unsigned int num_bfs_roots = 3; do_trace("Before graph_generation\n"); double make_graph_start = MPI_Wtime(); scoped_array<uint64_t> bfs_roots; uint64_t max_used_vertex = 0; { /* Spread the two 64-bit numbers into five nonzero values in the correct * range. */ make_mrg_seed(seed1, seed2, seed); /* Generate the graph. */ size_t block_limit = size_t(DIV_SIZE((tg.nglobaledges + size * FILE_CHUNKSIZE - 1) / FILE_CHUNKSIZE)); tg.edgememory.reset_to_new(block_limit); for (size_t block_idx = 0; block_idx < block_limit; ++block_idx) { if (rank == 0) fprintf(stderr, "%d: Generating block %d of %d\n", rank, (int)block_idx, (int)block_limit); uint64_t start_edge_index = (std::min)(uint64_t(FILE_CHUNKSIZE) * (MUL_SIZE(block_idx) + rank), tg.nglobaledges); size_t edge_count = size_t((std::min)(tg.nglobaledges - start_edge_index, uint64_t(FILE_CHUNKSIZE))); assert (start_edge_index <= tg.nglobaledges); assert (edge_count <= size_t(FILE_CHUNKSIZE)); scoped_array<packed_edge>& buf = tg.edgememory[block_idx]; buf.reset_to_new(edge_count); generate_kronecker_range(seed, SCALE, start_edge_index, start_edge_index + edge_count, buf.get(0, edge_count)); } /* Find root vertices and the largest vertex number with incident edges. * We first generate a larger number of candidate roots, then scan the * edges to find which of them have incident edges. Hopefully enough do; * otherwise, we need to iterate until we find them. */ do_trace("Before finding roots\n"); { const unsigned int candidates_to_scan_per_iter = 4 * num_bfs_roots; bfs_roots.reset_to_new(num_bfs_roots); unsigned int bfs_root_idx = 0; scoped_array<uint64_t> candidate_roots; candidate_roots.reset_to_new(candidates_to_scan_per_iter); scoped_array<int> candidate_root_marks; candidate_root_marks.reset_to_new(candidates_to_scan_per_iter); unsigned int pass_num = 0; while (bfs_root_idx < (unsigned int)(num_bfs_roots)) { ++pass_num; if (rank == 0) fprintf(stderr, "Finding roots, pass %u\n", pass_num); for (unsigned int i = 0; i < candidates_to_scan_per_iter; ++i) { double d[2]; make_random_numbers(2, seed1, seed2, 2 * (pass_num * candidates_to_scan_per_iter + i), d); uint64_t root = uint64_t((d[0] + d[1]) * double(nglobalverts)) % nglobalverts; assert (root < nglobalverts); candidate_roots[i] = root; candidate_root_marks[i] = 0; } ITERATE_TUPLE_GRAPH_BEGIN(&tg, edgebuf, edgebuf_size) { if (rank == 0) fprintf(stderr, "Block %zu of %zu\n", size_t(ITERATE_TUPLE_GRAPH_BLOCK_NUMBER), size_t(ITERATE_TUPLE_GRAPH_BLOCK_COUNT(&tg))); // Global max code from http://www.openmp.org/pipermail/omp/2005/000257.html #pragma omp parallel { uint64_t my_max_used_vertex = max_used_vertex; #pragma omp for for (ptrdiff_t i = 0; i < edgebuf_size; ++i) { uint64_t src = uint64_t(get_v0_from_edge(&edgebuf[i])); uint64_t tgt = uint64_t(get_v1_from_edge(&edgebuf[i])); if (src == tgt) continue; for (unsigned int j = 0; j < candidates_to_scan_per_iter; ++j) { if (candidate_roots[j] == src || candidate_roots[j] == tgt) { #pragma omp atomic candidate_root_marks[j] |= true; } if (src > my_max_used_vertex) { my_max_used_vertex = src; } if (tgt > my_max_used_vertex) { my_max_used_vertex = tgt; } } } #pragma omp critical { if (my_max_used_vertex > max_used_vertex) max_used_vertex = my_max_used_vertex; } } } ITERATE_TUPLE_GRAPH_END; MPI_Allreduce(MPI_IN_PLACE, candidate_root_marks.get(0, candidates_to_scan_per_iter), candidates_to_scan_per_iter, MPI_INT, MPI_LOR, MPI_COMM_WORLD); MPI_Allreduce(MPI_IN_PLACE, &max_used_vertex, 1, MPI_UINT64_T, MPI_MAX, MPI_COMM_WORLD); /* This control flow is common to all nodes. */ for (unsigned int i = 0; i < candidates_to_scan_per_iter; ++i) { if (candidate_root_marks[i] == 1) { bool is_duplicate = false; for (unsigned int j = 0; j < bfs_root_idx; ++j) { if (candidate_roots[i] == bfs_roots[j]) { is_duplicate = true; break; } } if (!is_duplicate) { bfs_roots[bfs_root_idx++] = candidate_roots[i]; if (bfs_root_idx >= (unsigned int)(num_bfs_roots)) break; } } } } } } double make_graph_stop = MPI_Wtime(); double make_graph_time = make_graph_stop - make_graph_start; if (rank == 0) { /* Not an official part of the results */ fprintf(stderr, "graph_generation: %f s\n", make_graph_time); } do_trace("After graph_generation\n"); // int begin_bfs_event = MPE_Log_get_event_number(); // int end_bfs_event = MPE_Log_get_event_number(); // if (rank == 0) MPE_Describe_state(begin_bfs_event, end_bfs_event, "BFS", "red"); /* Make user's graph data structure. */ double data_struct_start = MPI_Wtime(); make_graph_data_structure(&tg); double data_struct_stop = MPI_Wtime(); double data_struct_time = data_struct_stop - data_struct_start; if (rank == 0) { /* Not an official part of the results */ fprintf(stderr, "construction_time: %f s\n", data_struct_time); } do_trace("After user graph data structure construction\n"); tg.edgememory.reset(); do_trace("After cleanup\n"); /* Number of edges visited in each BFS; a double so get_statistics can be * used directly. */ double* edge_counts = (double*)xmalloc(num_bfs_roots * sizeof(double)); /* Run BFS. */ int validation_passed = 1; double* bfs_times = (double*)xmalloc(num_bfs_roots * sizeof(double)); double* validate_times = (double*)xmalloc(num_bfs_roots * sizeof(double)); uint64_t nlocalverts = get_nlocalverts_for_pred(); assert (nlocalverts * sizeof(int64_t) <= SIZE_MAX); memalloc("pred", size_t(nlocalverts) * sizeof(int64_t)); int64_t* pred = (int64_t*)xMPI_Alloc_mem(size_t(nlocalverts) * sizeof(int64_t)); // const int default_bcast_step_size = 8; const bfs_settings settings[] = { // {2, num_bfs_roots, false, false, true, default_bcast_step_size}, {3, num_bfs_roots, false, true, false, 4} /* , {3, 1, false, true, false, 6}, {3, 1, false, true, false, 8}, {3, 1, false, true, false, 12}, {3, 1, false, true, false, 16}, {3, 1, false, true, false, 24}, {3, 1, false, true, false, 32}, {3, 1, false, true, false, 48}, {3, 1, false, true, false, 64}, {3, 1, false, true, false, 96}, {3, 1, false, true, false, 128}, {3, 1, false, true, false, 192}, {3, 1, false, true, false, 256}, {3, num_bfs_roots, false, false, true, -1}, {3, 1, true, true, false, -1}, */ // {2, 1, false, false, false, -1}, // {1, 1, false, true, false, -1}, // {0, 1, false, true, false, -1}, }; bfs_settings best_settings = settings[0]; double best_teps = 0.; for (size_t i = 0; i < sizeof(settings) / sizeof(*settings); ++i) { bfs_settings s = settings[i]; if (s.nbfs > (size_t)num_bfs_roots) { if (rank == 0) fprintf(stderr, "Root count %zu in settings too large for %u generated roots\n", s.nbfs, num_bfs_roots); MPI_Abort(MPI_COMM_WORLD, 1); } if (s.bcast_step_size == -1) s.bcast_step_size = best_settings.bcast_step_size; for (int bfs_root_idx = 0; bfs_root_idx < (int)s.nbfs; ++bfs_root_idx) { int64_t root = bfs_roots[bfs_root_idx]; if (rank == 0) fprintf(stderr, "Running settings %d BFS %d\n", (int)i, bfs_root_idx); /* Clear the pred array. */ memset(pred, 0, size_t(nlocalverts) * sizeof(int64_t)); do_trace("Before BFS %d\n", bfs_root_idx); /* Do the actual BFS. */ // MPE_Start_log(); // MPE_Log_event(begin_bfs_event, 0, "Start of BFS"); MPI_Barrier(MPI_COMM_WORLD); #if defined(CRAYPAT) && 0 if (s.official_results) PAT_record(PAT_STATE_ON); #endif double bfs_start = MPI_Wtime(); run_bfs(root, &pred[0], s); MPI_Barrier(MPI_COMM_WORLD); // MPE_Stop_log(); // MPE_Log_event(end_bfs_event, 0, "End of BFS"); double bfs_stop = MPI_Wtime(); #if defined(CRAYPAT) && 0 if (s.official_results) PAT_record(PAT_STATE_OFF); #endif bfs_times[bfs_root_idx] = bfs_stop - bfs_start; if (rank == 0) fprintf(stderr, "Time for BFS %d is %f\n", bfs_root_idx, bfs_times[bfs_root_idx]); do_trace("After BFS %d\n", bfs_root_idx); #if 1 /* Validate result. */ if (rank == 0) fprintf(stderr, "Validating BFS %d\n", bfs_root_idx); double validate_start = MPI_Wtime(); int64_t edge_visit_count; // fprintf(stderr, "%d: validate_bfs_result(nglobalverts = %" PRId64 ", nlocalverts = %" PRIu64 ", root = %" PRId64 ")\n", rank, max_used_vertex + 1, nlocalverts, root); int validation_passed_one = validate_bfs_result(&tg, max_used_vertex + 1, size_t(nlocalverts), root, pred, &edge_visit_count); double validate_stop = MPI_Wtime(); do_trace("After validating BFS %d\n", bfs_root_idx); validate_times[bfs_root_idx] = validate_stop - validate_start; if (rank == 0) fprintf(stderr, "Validate time for BFS %d is %f\n", bfs_root_idx, validate_times[bfs_root_idx]); edge_counts[bfs_root_idx] = (double)edge_visit_count; if (rank == 0) { std::cerr << "Settings: " << s << std::endl; fprintf(stderr, "TEPS for BFS %d is %g\n", bfs_root_idx, double(edge_visit_count) / bfs_times[bfs_root_idx]); } if (!validation_passed_one) { validation_passed = 0; if (rank == 0) fprintf(stderr, "Validation failed for this BFS root; aborting.\n"); abort(); } #endif if (double(edge_visit_count) / bfs_times[bfs_root_idx] > best_teps) { best_settings = s; best_teps = double(edge_visit_count) / bfs_times[bfs_root_idx]; } } /* Print results. */ if (rank == 0 && s.official_results) { if (!validation_passed) { fprintf(stdout, "No results printed for invalid run.\n"); } else { fprintf(stdout, "compression_level: %d\n", (int)s.compression_level); fprintf(stdout, "SCALE: %d\n", SCALE); fprintf(stdout, "edgefactor: %d\n", edgefactor); fprintf(stdout, "NBFS: %zu\n", s.nbfs); fprintf(stdout, "graph_generation: %g\n", make_graph_time); fprintf(stdout, "num_mpi_processes: %d\n", size); fprintf(stdout, "construction_time: %g\n", data_struct_time); double stats[s_LAST]; get_statistics(bfs_times, s.nbfs, stats); fprintf(stdout, "min_time: %g\n", stats[s_minimum]); fprintf(stdout, "firstquartile_time: %g\n", stats[s_firstquartile]); fprintf(stdout, "median_time: %g\n", stats[s_median]); fprintf(stdout, "thirdquartile_time: %g\n", stats[s_thirdquartile]); fprintf(stdout, "max_time: %g\n", stats[s_maximum]); fprintf(stdout, "mean_time: %g\n", stats[s_mean]); fprintf(stdout, "stddev_time: %g\n", stats[s_std]); get_statistics(edge_counts, s.nbfs, stats); fprintf(stdout, "min_nedge: %.11g\n", stats[s_minimum]); fprintf(stdout, "firstquartile_nedge: %.11g\n", stats[s_firstquartile]); fprintf(stdout, "median_nedge: %.11g\n", stats[s_median]); fprintf(stdout, "thirdquartile_nedge: %.11g\n", stats[s_thirdquartile]); fprintf(stdout, "max_nedge: %.11g\n", stats[s_maximum]); fprintf(stdout, "mean_nedge: %.11g\n", stats[s_mean]); fprintf(stdout, "stddev_nedge: %.11g\n", stats[s_std]); double* secs_per_edge = (double*)xmalloc(s.nbfs * sizeof(double)); for (size_t i = 0; i < s.nbfs; ++i) secs_per_edge[i] = bfs_times[i] / edge_counts[i]; get_statistics(secs_per_edge, s.nbfs, stats); fprintf(stdout, "min_TEPS: %g\n", 1. / stats[s_maximum]); fprintf(stdout, "firstquartile_TEPS: %g\n", 1. / stats[s_thirdquartile]); fprintf(stdout, "median_TEPS: %g\n", 1. / stats[s_median]); fprintf(stdout, "thirdquartile_TEPS: %g\n", 1. / stats[s_firstquartile]); fprintf(stdout, "max_TEPS: %g\n", 1. / stats[s_minimum]); fprintf(stdout, "harmonic_mean_TEPS: %g\n", 1. / stats[s_mean]); /* Formula from: * Title: The Standard Errors of the Geometric and Harmonic Means and * Their Application to Index Numbers * Author(s): Nilan Norris * Source: The Annals of Mathematical Statistics, Vol. 11, No. 4 (Dec., 1940), pp. 445-448 * Publisher(s): Institute of Mathematical Statistics * Stable URL: http://www.jstor.org/stable/2235723 * (same source as in specification). */ fprintf(stdout, "harmonic_stddev_TEPS: %g\n", stats[s_std] / (stats[s_mean] * stats[s_mean] * sqrt(s.nbfs - 1))); xfree(secs_per_edge); secs_per_edge = NULL; get_statistics(validate_times, s.nbfs, stats); fprintf(stdout, "min_validate: %g\n", stats[s_minimum]); fprintf(stdout, "firstquartile_validate: %g\n", stats[s_firstquartile]); fprintf(stdout, "median_validate: %g\n", stats[s_median]); fprintf(stdout, "thirdquartile_validate: %g\n", stats[s_thirdquartile]); fprintf(stdout, "max_validate: %g\n", stats[s_maximum]); fprintf(stdout, "mean_validate: %g\n", stats[s_mean]); fprintf(stdout, "stddev_validate: %g\n", stats[s_std]); #if 0 for (int i = 0; i < s.nbfs; ++i) { fprintf(stdout, "Run %3d: %g s, validation %g s\n", i + 1, bfs_times[i], validate_times[i]); } #endif fprintf(stdout, "\n"); } } } memfree("pred", size_t(nlocalverts) * sizeof(int64_t)); xfree(edge_counts); edge_counts = NULL; xMPI_Free_mem(pred); bfs_roots.reset(); free_graph_data_structure(); xfree(bfs_times); xfree(validate_times); cleanup_globals(); MPI_Finalize(); return 0; }
20,216
7,814
#include "CalibTracker/SiStripCommon/interface/ShallowSimhitClustersProducer.h" #include "CalibTracker/SiStripCommon/interface/ShallowTools.h" #include "DataFormats/SiStripCluster/interface/SiStripCluster.h" #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "CondFormats/SiStripObjects/interface/SiStripLorentzAngle.h" #include "CondFormats/DataRecord/interface/SiStripLorentzAngleRcd.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h" #include "Geometry/CommonTopologies/interface/StripTopology.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" ShallowSimhitClustersProducer::ShallowSimhitClustersProducer(const edm::ParameterSet& iConfig) : clusters_token_(consumes<edmNew::DetSetVector<SiStripCluster>>(iConfig.getParameter<edm::InputTag>("Clusters"))), Prefix(iConfig.getParameter<std::string>("Prefix")), runningmode_(iConfig.getParameter<std::string>("runningMode")) { std::vector<edm::InputTag> simhits_tags = iConfig.getParameter<std::vector<edm::InputTag>>("InputTags"); for (auto itag : simhits_tags) { simhits_tokens_.push_back(consumes<std::vector<PSimHit>>(itag)); } produces<std::vector<unsigned>>(Prefix + "hits"); produces<std::vector<float>>(Prefix + "strip"); produces<std::vector<float>>(Prefix + "localtheta"); produces<std::vector<float>>(Prefix + "localphi"); produces<std::vector<float>>(Prefix + "localx"); produces<std::vector<float>>(Prefix + "localy"); produces<std::vector<float>>(Prefix + "localz"); produces<std::vector<float>>(Prefix + "momentum"); produces<std::vector<float>>(Prefix + "energyloss"); produces<std::vector<float>>(Prefix + "time"); produces<std::vector<int>>(Prefix + "particle"); produces<std::vector<unsigned short>>(Prefix + "process"); } void ShallowSimhitClustersProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { shallow::CLUSTERMAP clustermap = shallow::make_cluster_map(iEvent, clusters_token_); int size = clustermap.size(); auto hits = std::make_unique<std::vector<unsigned>>(size, 0); auto strip = std::make_unique<std::vector<float>>(size, -100); auto localtheta = std::make_unique<std::vector<float>>(size, -100); auto localphi = std::make_unique<std::vector<float>>(size, -100); auto localx = std::make_unique<std::vector<float>>(size, -100); auto localy = std::make_unique<std::vector<float>>(size, -100); auto localz = std::make_unique<std::vector<float>>(size, -100); auto momentum = std::make_unique<std::vector<float>>(size, 0); auto energyloss = std::make_unique<std::vector<float>>(size, -1); auto time = std::make_unique<std::vector<float>>(size, -1); auto particle = std::make_unique<std::vector<int>>(size, -500); auto process = std::make_unique<std::vector<unsigned short>>(size, 0); edm::ESHandle<TrackerGeometry> theTrackerGeometry; iSetup.get<TrackerDigiGeometryRecord>().get(theTrackerGeometry); edm::ESHandle<MagneticField> magfield; iSetup.get<IdealMagneticFieldRecord>().get(magfield); edm::ESHandle<SiStripLorentzAngle> SiStripLorentzAngle; iSetup.get<SiStripLorentzAngleRcd>().get(runningmode_, SiStripLorentzAngle); edm::Handle<edmNew::DetSetVector<SiStripCluster>> clusters; iEvent.getByLabel("siStripClusters", "", clusters); for (auto& simhit_token : simhits_tokens_) { edm::Handle<std::vector<PSimHit>> simhits; iEvent.getByToken(simhit_token, simhits); for (auto const& hit : *simhits) { const uint32_t id = hit.detUnitId(); const StripGeomDetUnit* theStripDet = dynamic_cast<const StripGeomDetUnit*>(theTrackerGeometry->idToDet(id)); const LocalVector drift = shallow::drift(theStripDet, *magfield, *SiStripLorentzAngle); const float driftedstrip_ = theStripDet->specificTopology().strip(hit.localPosition() + 0.5 * drift); const float hitstrip_ = theStripDet->specificTopology().strip(hit.localPosition()); shallow::CLUSTERMAP::const_iterator cluster = match_cluster(id, driftedstrip_, clustermap, *clusters); if (cluster != clustermap.end()) { unsigned i = cluster->second; hits->at(i) += 1; if (hits->at(i) == 1) { strip->at(i) = hitstrip_; localtheta->at(i) = hit.thetaAtEntry(); localphi->at(i) = hit.phiAtEntry(); localx->at(i) = hit.localPosition().x(); localy->at(i) = hit.localPosition().y(); localz->at(i) = hit.localPosition().z(); momentum->at(i) = hit.pabs(); energyloss->at(i) = hit.energyLoss(); time->at(i) = hit.timeOfFlight(); particle->at(i) = hit.particleType(); process->at(i) = hit.processType(); } } } } iEvent.put(std::move(hits), Prefix + "hits"); iEvent.put(std::move(strip), Prefix + "strip"); iEvent.put(std::move(localtheta), Prefix + "localtheta"); iEvent.put(std::move(localphi), Prefix + "localphi"); iEvent.put(std::move(localx), Prefix + "localx"); iEvent.put(std::move(localy), Prefix + "localy"); iEvent.put(std::move(localz), Prefix + "localz"); iEvent.put(std::move(momentum), Prefix + "momentum"); iEvent.put(std::move(energyloss), Prefix + "energyloss"); iEvent.put(std::move(time), Prefix + "time"); iEvent.put(std::move(particle), Prefix + "particle"); iEvent.put(std::move(process), Prefix + "process"); } shallow::CLUSTERMAP::const_iterator ShallowSimhitClustersProducer::match_cluster( const unsigned& id, const float& strip_, const shallow::CLUSTERMAP& clustermap, const edmNew::DetSetVector<SiStripCluster>& clusters) const { shallow::CLUSTERMAP::const_iterator cluster = clustermap.end(); edmNew::DetSetVector<SiStripCluster>::const_iterator clustersDetSet = clusters.find(id); if (clustersDetSet != clusters.end()) { edmNew::DetSet<SiStripCluster>::const_iterator left, right = clustersDetSet->begin(); while (right != clustersDetSet->end() && strip_ > right->barycenter()) right++; left = right - 1; if (right != clustersDetSet->end() && right != clustersDetSet->begin()) { unsigned firstStrip = (right->barycenter() - strip_) < (strip_ - left->barycenter()) ? right->firstStrip() : left->firstStrip(); cluster = clustermap.find(std::make_pair(id, firstStrip)); } else if (right != clustersDetSet->begin()) cluster = clustermap.find(std::make_pair(id, left->firstStrip())); else cluster = clustermap.find(std::make_pair(id, right->firstStrip())); } return cluster; }
6,808
2,384
#include <fstream> #include <cmath> int main() { double PI = std::acos(-1); std::ofstream file("sine_table.bin"); for (int i = 0; i < 256; ++i) { char f = std::sin(i / 64.0 * PI) * 32.0 + 48.0; file.put(f); } }
222
122