hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
a9a48281c3eb8e78cda7687f4c1b0c13f8d25d3c
7,077
cpp
C++
src/replay_system.cpp
Bigbird37/walsureta
79e90edf5ca747898894ce16fb1c36e53396ec82
[ "MIT" ]
34
2021-01-16T18:08:43.000Z
2022-03-31T12:16:11.000Z
src/replay_system.cpp
Bigbird37/walsureta
79e90edf5ca747898894ce16fb1c36e53396ec82
[ "MIT" ]
22
2021-04-18T05:12:58.000Z
2022-03-23T02:30:46.000Z
src/replay_system.cpp
Bigbird37/walsureta
79e90edf5ca747898894ce16fb1c36e53396ec82
[ "MIT" ]
16
2021-01-16T02:13:18.000Z
2022-03-21T14:03:20.000Z
#include "replay_system.hpp" #include "hooks.hpp" void ReplaySystem::record_action(bool hold, bool player1, bool flip) { if (is_recording()) { auto gm = gd::GameManager::sharedState(); auto play_layer = gm->getPlayLayer(); auto is_two_player = play_layer->m_levelSettings->m_twoPlayerMode; player1 ^= flip && gm->getGameVariable("0010"); Action action; action.hold = hold; action.player2 = is_two_player && !player1; if (replay.get_type() == ReplayType::XPOS) action.x = play_layer->m_player1->m_position.x; else if (replay.get_type() == ReplayType::FRAME) action.frame = get_frame(); replay.add_action(action); } } void ReplaySystem::play_action(const Action& action) { auto gm = gd::GameManager::sharedState(); auto flip = gm->getGameVariable("0010"); if (action.hold) orig<&Hooks::PlayLayer_pushButton>(gm->getPlayLayer(), 0, !action.player2 ^ flip); else orig<&Hooks::PlayLayer_releaseButton>(gm->getPlayLayer(), 0, !action.player2 ^ flip); } unsigned ReplaySystem::get_frame() { auto play_layer = gd::GameManager::sharedState()->getPlayLayer(); if (play_layer != nullptr) { return static_cast<unsigned>(play_layer->m_time * replay.get_fps()) + frame_offset; } return 0; } void ReplaySystem::update_frame_offset() { // if there is no last checkpoint then it should default to 0 frame_offset = practice_fixes.get_last_checkpoint().frame; } void ReplaySystem::toggle_playing() { state = is_playing() ? NOTHING : PLAYING; auto pl = gd::GameManager::sharedState()->getPlayLayer(); if (is_playing()) { if (pl && get_frame() > 0) should_restart_next_time = true; action_index = 0; } else should_restart_next_time = false; update_frame_offset(); _update_status_label(); } void ReplaySystem::toggle_recording() { state = is_recording() ? NOTHING : RECORDING; if (!is_recording()) { frame_advance = false; should_restart_next_time = false; } else { replay = Replay(default_fps, default_type); if (gd::GameManager::sharedState()->getPlayLayer() && get_frame() > 0) should_restart_next_time = true; } update_frame_offset(); _update_status_label(); } void ReplaySystem::on_reset() { auto play_layer = gd::GameManager::sharedState()->getPlayLayer(); if (is_playing()) { update_frame_offset(); orig<&Hooks::PlayLayer_releaseButton>(play_layer, 0, false); orig<&Hooks::PlayLayer_releaseButton>(play_layer, 0, true); action_index = 0; practice_fixes.activated_objects.clear(); practice_fixes.activated_objects_p2.clear(); } else { bool has_checkpoints = play_layer->m_checkpoints->count(); const auto checkpoint = practice_fixes.get_last_checkpoint(); if (!has_checkpoints) { practice_fixes.activated_objects.clear(); practice_fixes.activated_objects_p2.clear(); frame_offset = 0; } else { frame_offset = checkpoint.frame; constexpr auto delete_from = [&](auto& vec, size_t index) { vec.erase(vec.begin() + index, vec.end()); }; delete_from(practice_fixes.activated_objects, checkpoint.activated_objects_size); delete_from(practice_fixes.activated_objects_p2, checkpoint.activated_objects_p2_size); if (is_recording()) { for (const auto& object : practice_fixes.activated_objects) { object->m_hasBeenActivated = true; } for (const auto& object : practice_fixes.activated_objects_p2) { object->m_hasBeenActivatedP2 = true; } } } if (is_recording()) { if (replay.get_type() == ReplayType::XPOS) replay.remove_actions_after(play_layer->m_player1->m_position.x); else replay.remove_actions_after(get_frame()); const auto& actions = replay.get_actions(); bool holding = play_layer->m_player1->m_isHolding; if ((holding && actions.empty()) || (!actions.empty() && actions.back().hold != holding)) { record_action(holding, true, false); if (holding) { orig<&Hooks::PlayLayer_releaseButton>(play_layer, 0, true); orig<&Hooks::PlayLayer_pushButton>(play_layer, 0, true); play_layer->m_player1->m_hasJustHeld = true; } } else if (!actions.empty() && actions.back().hold && holding && has_checkpoints && checkpoint.player1.buffer_orb) { orig<&Hooks::PlayLayer_releaseButton>(play_layer, 0, true); orig<&Hooks::PlayLayer_pushButton>(play_layer, 0, true); } if (play_layer->m_levelSettings->m_twoPlayerMode) record_action(false, false, false); practice_fixes.apply_checkpoint(); } } } void ReplaySystem::handle_playing() { if (is_playing()) { auto x = gd::GameManager::sharedState()->getPlayLayer()->m_player1->m_position.x; auto& actions = replay.get_actions(); Action action; if (replay.get_type() == ReplayType::XPOS) { while (action_index < actions.size() && x >= (action = actions[action_index]).x) { play_action(action); ++action_index; } } else { while (action_index < actions.size() && get_frame() >= (action = actions[action_index]).frame) { play_action(action); ++action_index; } } if (action_index >= actions.size()) toggle_playing(); } } // why here out of all places? idk constexpr int STATUS_LABEL_TAG = 10032; auto _create_status_label(CCLayer* layer) { auto label = CCLabelBMFont::create("", "chatFont.fnt"); label->setTag(STATUS_LABEL_TAG); label->setAnchorPoint({0, 0}); label->setPosition({5, 5}); label->setZOrder(999); layer->addChild(label); return label; } void ReplaySystem::_update_status_label() { auto play_layer = gd::GameManager::sharedState()->getPlayLayer(); if (play_layer) { auto label = cast<CCLabelBMFont*>(play_layer->getChildByTag(STATUS_LABEL_TAG)); if (!label) label = _create_status_label(play_layer); switch (state) { case NOTHING: label->setString(""); if (recorder.m_recording && (!recorder.m_until_end || from_offset<bool>(play_layer, 0x4BD))) recorder.stop(); break; case RECORDING: label->setString("Recording"); break; case PLAYING: label->setString(showcase_mode ? "" : "Playing"); break; } } else if (recorder.m_recording) { recorder.stop(); } }
38.884615
128
0.600537
[ "object" ]
a9aafb4a7f479815ed714730805ecdfe0f7730dd
8,833
hpp
C++
src/core/shape_inference/include/lstm_cell_shape_inference.hpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
null
null
null
src/core/shape_inference/include/lstm_cell_shape_inference.hpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
18
2022-01-21T08:42:58.000Z
2022-03-28T13:21:31.000Z
src/core/shape_inference/include/lstm_cell_shape_inference.hpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <openvino/op/lstm_cell.hpp> #include "utils.hpp" namespace ov { namespace op { namespace ShapeInferLSTM { template <class OpsType, class ShapeType> void lstm_shape_infer(const OpsType* op, const std::vector<ShapeType>& input_shapes, std::vector<ShapeType>& output_shapes, std::size_t gates_count) { using DimType = typename std::iterator_traits<typename ShapeType::iterator>::value_type; enum { X, initial_hidden_state, initial_cell_state, W, R, B }; std::vector<bool> input_rank_static(6, false); bool all_rank_dynamic = true; bool all_rank_static = true; // Prepare OutShape auto& hidden_shape = output_shapes[0]; auto& cell_shape = output_shapes[1]; hidden_shape.resize(2); cell_shape.resize(2); // If rank is dynamic, then output_shape is undefined for (size_t i = 0; i < input_shapes.size() && i < 6; i++) { input_rank_static[i] = input_shapes[i].rank().is_static(); all_rank_dynamic &= !input_rank_static[i]; all_rank_static &= input_rank_static[i]; } if (all_rank_dynamic) { return; } const auto& x_pshape = input_shapes[0]; const auto& w_pshape = input_shapes[3]; DimType output_batch_size; DimType output_hidden_size; bool is_batch_init = false; bool is_hidden_init = false; // deduce batch/hidden_size for (size_t i = 0; i < input_shapes.size() && i < 6; i++) { const auto& input = input_shapes[i]; if (input_rank_static[i]) { // batch could be deduced from x, cell_state or hidden_state if (i == X || i == initial_cell_state || i == initial_hidden_state) { NODE_VALIDATION_CHECK(op, (input.size() == 2), "LSTMCell input rank is not correct for ", i, " input parameter. Current rank: ", input.size(), ", expected: 2."); if (!is_batch_init) { output_batch_size = input[0]; is_batch_init = true; } else { NODE_VALIDATION_CHECK( op, DimType::merge(output_batch_size, output_batch_size, input[0]), "Parameter batch_size not matched for X, initial_hidden_state or initial_cell_state " "inputs."); } if (i == initial_cell_state || i == initial_hidden_state) { if (!is_hidden_init) { output_hidden_size = input[1]; is_hidden_init = true; } else { NODE_VALIDATION_CHECK(op, DimType::merge(output_hidden_size, output_hidden_size, input[1]), "Parameter hidden_size not matched for W, R, B, initial_hidden_state and " "initial_cell_state " "inputs."); } } } else if (i == W || i == R || i == B) { // check input dimension if (i == B) { NODE_VALIDATION_CHECK(op, (input.size() == 1), "LSTMCell input tensor dimension is not correct for ", i, " input parameter. Current input length: ", input.size(), ", expected: 1."); if (input[0].is_static()) { if (!is_hidden_init) { output_hidden_size = input[0].get_length() / gates_count; is_hidden_init = true; } else { NODE_VALIDATION_CHECK( op, DimType::merge(output_hidden_size, output_hidden_size, input[0].get_length() / gates_count), "Parameter hidden_size not matched for W, R, B, initial_hidden_state and " "initial_cell_state " "inputs."); } } } else { NODE_VALIDATION_CHECK(op, (input.size() == 2), "LSTMCell input rank is not correct for ", i, " input parameter. Current rank: ", input.size(), ", expected: 2."); if (input[0].is_static()) { if (!is_hidden_init) { output_hidden_size = input[0].get_length() / gates_count; is_hidden_init = true; } else { NODE_VALIDATION_CHECK( op, DimType::merge(output_hidden_size, output_hidden_size, input[0].get_length() / gates_count), "Parameter hidden_size not matched for W, R, B, initial_hidden_state and " "initial_cell_state " "inputs."); } } if (i == R) { if (!is_hidden_init) { output_hidden_size = input[1]; is_hidden_init = true; } else { NODE_VALIDATION_CHECK(op, DimType::merge(output_hidden_size, output_hidden_size, input[1]), "Parameter hidden_size not matched for W, R, B, initial_hidden_state " "and initial_cell_state " "inputs."); } } } } } } // Check peepholes if (input_shapes.size() == 7) { const auto& p_pshape = input_shapes[6]; NODE_VALIDATION_CHECK(op, (p_pshape.rank().compatible(1)), "LSTMCell input tensor P shall have dimension 1D."); } // check input size if (input_rank_static[X] && input_rank_static[W]) { NODE_VALIDATION_CHECK(op, (x_pshape[1].compatible(w_pshape[1])), "LSTMCell mismatched input_size dimension."); } hidden_shape[0] = output_batch_size; hidden_shape[1] = output_hidden_size; cell_shape[0] = output_batch_size; cell_shape[1] = output_hidden_size; } } // namespace ShapeInferLSTM namespace v0 { using ShapeInferLSTM::lstm_shape_infer; template <class T> void shape_infer(const LSTMCell* op, const std::vector<T>& input_shapes, std::vector<T>& output_shapes) { NODE_VALIDATION_CHECK(op, input_shapes.size() == 7 && output_shapes.size() == 2); const auto& p_pshape = input_shapes[6]; lstm_shape_infer(op, input_shapes, output_shapes, op->s_gates_count); const auto& hidden_size = output_shapes[0][1]; if (p_pshape[0].is_static() && hidden_size.is_static()) { NODE_VALIDATION_CHECK(op, p_pshape[0].compatible(hidden_size * op->s_peepholes_count), "Parameter hidden_size mistmatched in P input. Current value is: ", p_pshape[0].get_length(), ", expected: ", hidden_size.get_length() * op->s_peepholes_count, "."); } } } // namespace v0 namespace v4 { using ShapeInferLSTM::lstm_shape_infer; template <class T> void shape_infer(const LSTMCell* op, const std::vector<T>& input_shapes, std::vector<T>& output_shapes) { NODE_VALIDATION_CHECK(op, input_shapes.size() == 6 && output_shapes.size() == 2); lstm_shape_infer(op, input_shapes, output_shapes, op->s_gates_count); } } // namespace v4 } // namespace op } // namespace ov
45.297436
120
0.46564
[ "vector" ]
a9ac99ded95cad9d8ffa428436cac34aeb4efc07
9,321
cpp
C++
wallet/qt/coldstakingpage.cpp
abdullahnazar/neblio
d47fa3d3645dfc0bfb5da54b1688fd423bcedda9
[ "MIT" ]
1
2021-02-23T22:38:06.000Z
2021-02-23T22:38:06.000Z
wallet/qt/coldstakingpage.cpp
abdullahnazar/neblio
d47fa3d3645dfc0bfb5da54b1688fd423bcedda9
[ "MIT" ]
null
null
null
wallet/qt/coldstakingpage.cpp
abdullahnazar/neblio
d47fa3d3645dfc0bfb5da54b1688fd423bcedda9
[ "MIT" ]
null
null
null
#include "coldstakingpage.h" #include "bitcoinunits.h" #include "checkpoints.h" #include "coldstakinglistfilterproxy.h" #include "coldstakinglistitemdelegate.h" #include "coldstakingmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "main.h" #include "newstakedelegationdialog.h" #include "optionsmodel.h" #include "qt/coldstakingmodel.h" #include "transactiontablemodel.h" #include "wallet.h" #include "walletmodel.h" #include <QAction> #include <QClipboard> #include <QDesktopServices> #include <QKeyEvent> #include <QMenu> #include <QUrl> #include "txdb.h" #define LOAD_MIN_TIME_INTERVAL 15 const QString ColdStakingPage::copyOwnerAddressText = "Copy owner address"; const QString ColdStakingPage::copyStakerAddressText = "Copy staker address"; const QString ColdStakingPage::copyAmountText = "Copy amount"; const QString ColdStakingPage::enableStakingText = "Enable staking for this address"; const QString ColdStakingPage::disableStakingText = "Disable staking for this address"; const QString ColdStakingPage::cantStakeText = "Cannot stake an address you delegated"; ColdStakingPage::ColdStakingPage(QWidget* parent) : QWidget(parent), ui(new Ui_ColdStaking), model(new ColdStakingModel), itemDelegate(new ColdStakingListItemDelegate) { ui->setupUi(this); ui->listColdStakingView->setItemDelegate(itemDelegate); ui->listColdStakingView->setIconSize(QSize(ColdStakingListItemDelegate::DECORATION_SIZE, ColdStakingListItemDelegate::DECORATION_SIZE)); ui->listColdStakingView->setMinimumHeight(ColdStakingListItemDelegate::NUM_ITEMS * (ColdStakingListItemDelegate::DECORATION_SIZE + 2)); ui->listColdStakingView->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listColdStakingView, &ColdStakingListView::clicked, this, &ColdStakingPage::handleElementClicked); setupContextMenu(); filter = new ColdStakingListFilterProxy(ui->filter_lineEdit, this); filter->setDynamicSortFilter(true); setModel(model); refreshData(); newStakeDelegationDialog = new NewStakeDelegationDialog(this); connect(ui->delegateStakeButton, &QPushButton::clicked, this, &ColdStakingPage::slot_openNewColdStakeDialog); connect(ui->filter_lineEdit, &QLineEdit::textChanged, filter, &ColdStakingListFilterProxy::setFilterWildcard); } void ColdStakingPage::handleElementClicked(const QModelIndex& index) { if (filter) emit tokenClicked(filter->mapToSource(index)); } void ColdStakingPage::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_F && (event->modifiers() & Qt::ControlModifier)) { ui->filter_lineEdit->setFocus(); } } void ColdStakingPage::setupContextMenu() { ui->listColdStakingView->setContextMenuPolicy(Qt::CustomContextMenu); contextMenu = new QMenu(this); copyOwnerAddrAction = new QAction(copyOwnerAddressText, this); copyStakerAddrAction = new QAction(copyStakerAddressText, this); copyAmountAction = new QAction(copyAmountText, this); toggleStakingAction = new QAction(enableStakingText, this); contextMenu->addAction(copyOwnerAddrAction); contextMenu->addAction(copyStakerAddrAction); contextMenu->addAction(copyAmountAction); contextMenu->addSeparator(); contextMenu->addAction(toggleStakingAction); connect(ui->listColdStakingView, &ColdStakingListView::customContextMenuRequested, this, &ColdStakingPage::slot_contextMenuRequested); connect(copyOwnerAddrAction, &QAction::triggered, this, &ColdStakingPage::slot_copyOwnerAddr); connect(copyStakerAddrAction, &QAction::triggered, this, &ColdStakingPage::slot_copyStakerAddr); connect(copyAmountAction, &QAction::triggered, this, &ColdStakingPage::slot_copyAmount); } void ColdStakingPage::slot_copyOwnerAddr() { copyField(ColdStakingModel::ColumnIndex::OWNER_ADDRESS, "owner address"); } void ColdStakingPage::slot_copyStakerAddr() { copyField(ColdStakingModel::ColumnIndex::STAKING_ADDRESS, "staker address"); } void ColdStakingPage::slot_copyAmount() { copyField(ColdStakingModel::ColumnIndex::TOTAL_STACKEABLE_AMOUNT_STR, "amount"); } void ColdStakingPage::slot_enableStaking(const QModelIndex& idx) { model->whitelist(idx); } void ColdStakingPage::slot_disableStaking(const QModelIndex& idx) { model->blacklist(idx); } void ColdStakingPage::slot_openNewColdStakeDialog() { const int currentHeight = std::max({cPeerBlockCounts.median(), CTxDB().GetBestChainHeight().value_or(0), Checkpoints::GetTotalBlocksEstimate()}); const int activationHeight = Params().GetNetForks().getFirstBlockOfFork(NetworkFork::NETFORK__5_COLD_STAKING); if (currentHeight >= activationHeight) { newStakeDelegationDialog->open(); } else { QMessageBox::information(this, "Cold Staking is Testnet-Only", "Neblio Cold Staking is not yet enabled on Mainnet." "It will be activated at height " + QVariant(activationHeight).toString() + ". \n\n" + QVariant(activationHeight - currentHeight).toString() + " blocks remain for the activation"); } } ColdStakingPage::~ColdStakingPage() { notifyWalletConnection.disconnect(); delete ui; } ColdStakingModel* ColdStakingPage::getTokenListModel() const { return model; } void ColdStakingPage::setModel(ColdStakingModel* model) { if (model) { filter->setSourceModel(model); ui->listColdStakingView->setModel(filter); } } void ColdStakingPage::setWalletModel(WalletModel* wModel) { model->setWalletModel(wModel); connect(model->getTransactionTableModel(), &TransactionTableModel::txArrived, this, &ColdStakingPage::onTxArrived); newStakeDelegationDialog->setWalletModel(model->getWalletModel()); notifyWalletConnection = model->getWalletModel()->getWallet()->NotifyAddressBookChanged.connect( [this](CWallet* /*wallet*/, const CTxDestination& /*address*/, const std::string& /*label*/, bool /*isMine*/, const std::string& /*purpose*/, ChangeType /*status*/) { refreshData(); }); } void ColdStakingPage::slot_contextMenuRequested(QPoint pos) { QModelIndexList selected = ui->listColdStakingView->selectedIndexesP(); if (selected.size() == 1) { contextMenu->popup(ui->listColdStakingView->viewport()->mapToGlobal(pos)); configureToggleStakingAction(selected.front()); } } void ColdStakingPage::onTxArrived(const QString /*hash*/) { tryRefreshData(); } void ColdStakingPage::tryRefreshData() { // Check for min update time to not reload the UI so often if the node is syncing. int64_t now = GetTime(); if (lastRefreshTime + LOAD_MIN_TIME_INTERVAL < now) { lastRefreshTime = now; refreshData(); } } void ColdStakingPage::refreshData() { model->updateCSList(); } void ColdStakingPage::copyField(ColdStakingModel::ColumnIndex column, const QString& columnName) { const QModelIndexList selected = ui->listColdStakingView->selectedIndexesP(); std::set<int> rows; for (long i = 0; i < selected.size(); i++) { QModelIndex index = selected.at(i); int row = index.row(); rows.insert(row); } if (rows.size() != 1) { QMessageBox::warning(this, "Failed to copy", "Failed to copy " + columnName + "; selected items size is not equal to one"); return; } const QModelIndex idx = ui->listColdStakingView->model()->index(*rows.begin(), 0); QString resultStr = ui->listColdStakingView->model()->data(idx, column).toString(); if (!resultStr.isEmpty()) { QClipboard* clipboard = QGuiApplication::clipboard(); clipboard->setText(resultStr); } else { QMessageBox::warning(this, "Failed to copy", "No information to include in the clipboard"); } } void ColdStakingPage::configureToggleStakingAction(const QModelIndex& idx) { bool isWhitelisted = ui->listColdStakingView->model() ->data(idx, ColdStakingModel::ColumnIndex::IS_WHITELISTED) .toBool(); bool isStaker = ui->listColdStakingView->model() ->data(idx, ColdStakingModel::ColumnIndex::IS_RECEIVED_DELEGATION) .toBool(); // disconnect everything and reconnect it below toggleStakingAction->disconnect(); if (!isStaker) { if (isWhitelisted) { toggleStakingAction->setText(disableStakingText); connect(toggleStakingAction, &QAction::triggered, this, [=]() { slot_disableStaking(idx); }); } else { toggleStakingAction->setText(enableStakingText); connect(toggleStakingAction, &QAction::triggered, this, [=]() { slot_enableStaking(idx); }); } toggleStakingAction->setEnabled(true); } else { toggleStakingAction->setText(cantStakeText); toggleStakingAction->setEnabled(false); } }
37.584677
105
0.687158
[ "model" ]
a9aed8b7653fec5b16858262f3ecd5cbc2758b02
94,901
cpp
C++
Mysql/storage/ndb/test/ndbapi/testMgm.cpp
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
1
2015-12-24T16:44:50.000Z
2015-12-24T16:44:50.000Z
Mysql/storage/ndb/test/ndbapi/testMgm.cpp
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
1
2015-12-24T18:23:56.000Z
2015-12-24T18:24:26.000Z
Mysql/storage/ndb/test/ndbapi/testMgm.cpp
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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 <NDBT.hpp> #include <NDBT_Test.hpp> #include "NdbMgmd.hpp" #include <mgmapi.h> #include <mgmapi_debug.h> #include "../../src/mgmapi/mgmapi_internal.h" #include <InputStream.hpp> #include <signaldata/EventReport.hpp> #include <NdbRestarter.hpp> #include <random.h> /* Tests that only need the mgmd(s) started Start ndb_mgmd and set NDB_CONNECTSTRING pointing to that/those ndb_mgmd(s), then run testMgm */ int runTestApiSession(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; Uint64 session_id= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgmd.getConnectString()); ndb_mgm_connect(h,0,0,0); #ifdef NDB_WIN SOCKET s = ndb_mgm_get_fd(h); #else int s= ndb_mgm_get_fd(h); #endif session_id= ndb_mgm_get_session_id(h); ndbout << "MGM Session id: " << session_id << endl; send(s,"get",3,0); ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); struct NdbMgmSession sess; int slen= sizeof(struct NdbMgmSession); h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgmd.getConnectString()); ndb_mgm_connect(h,0,0,0); NdbSleep_SecSleep(1); if(ndb_mgm_get_session(h,session_id,&sess,&slen)) { ndbout << "Failed, session still exists" << endl; ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return NDBT_FAILED; } else { ndbout << "SUCCESS: session is gone" << endl; ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return NDBT_OK; } } int runTestApiConnectTimeout(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; g_info << "Check connect works with timeout 3000" << endl; if (!mgmd.set_timeout(3000)) return NDBT_FAILED; if (!mgmd.connect(0, 0, 0)) { g_err << "Connect failed with timeout 3000" << endl; return NDBT_FAILED; } if (!mgmd.disconnect()) return NDBT_FAILED; g_info << "Check connect to illegal host will timeout after 3000" << endl; if (!mgmd.set_timeout(3000)) return NDBT_FAILED; mgmd.setConnectString("1.1.1.1"); const Uint64 tstart= NdbTick_CurrentMillisecond(); if (mgmd.connect(0, 0, 0)) { g_err << "Connect to illegal host suceeded" << endl; return NDBT_FAILED; } const Uint64 msecs= NdbTick_CurrentMillisecond() - tstart; ndbout << "Took about " << msecs <<" milliseconds"<<endl; if(msecs > 6000) { g_err << "The connect to illegal host timedout after much longer " << "time than was expected, expected <= 6000, got " << msecs << endl; return NDBT_FAILED; } return NDBT_OK; } int runTestApiTimeoutBasic(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; int result= NDBT_FAILED; int cc= 0; int mgmd_nodeid= 0; ndb_mgm_reply reply; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgmd.getConnectString()); ndbout << "TEST timout check_connection" << endl; int errs[] = { 1, 2, 3, -1}; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndbout << "trying error " << error_ins << endl; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << endl; result= NDBT_FAILED; goto done; } ndb_mgm_set_timeout(h,2500); cc= ndb_mgm_check_connection(h); if(cc < 0) result= NDBT_OK; else result= NDBT_FAILED; if(ndb_mgm_is_connected(h)) { ndbout << "FAILED: still connected" << endl; result= NDBT_FAILED; } } ndbout << "TEST get_mgmd_nodeid" << endl; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_insert_error(h, mgmd_nodeid, 0, &reply)< 0) { ndbout << "failed to remove inserted error " << endl; result= NDBT_FAILED; goto done; } cc= ndb_mgm_get_mgmd_nodeid(h); ndbout << "got node id: " << cc << endl; if(cc==0) { ndbout << "FAILED: didn't get node id" << endl; result= NDBT_FAILED; } else result= NDBT_OK; ndbout << "TEST end_session" << endl; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_insert_error(h, mgmd_nodeid, 4, &reply)< 0) { ndbout << "FAILED: insert error 1" << endl; result= NDBT_FAILED; goto done; } cc= ndb_mgm_end_session(h); if(cc==0) { ndbout << "FAILED: success in calling end_session" << endl; result= NDBT_FAILED; } else if(ndb_mgm_get_latest_error(h)!=ETIMEDOUT) { ndbout << "FAILED: Incorrect error code (" << ndb_mgm_get_latest_error(h) << " != expected " << ETIMEDOUT << ") desc: " << ndb_mgm_get_latest_error_desc(h) << " line: " << ndb_mgm_get_latest_error_line(h) << " msg: " << ndb_mgm_get_latest_error_msg(h) << endl; result= NDBT_FAILED; } else result= NDBT_OK; if(ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestApiGetStatusTimeout(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; int result= NDBT_OK; int mgmd_nodeid= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgmd.getConnectString()); int errs[] = { 0, 5, 6, 7, 8, 9, -1 }; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } ndb_mgm_reply reply; reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << error_ins << endl; result= NDBT_FAILED; } ndbout << "trying error: " << error_ins << endl; ndb_mgm_set_timeout(h,2500); struct ndb_mgm_cluster_state *cl= ndb_mgm_get_status(h); if(cl!=NULL) free(cl); /* * For whatever strange reason, * get_status is okay with not having the last enter there. * instead of "fixing" the api, let's have a special case * so we don't break any behaviour */ if(error_ins!=0 && error_ins!=9 && cl!=NULL) { ndbout << "FAILED: got a ndb_mgm_cluster_state back" << endl; result= NDBT_FAILED; } if(error_ins!=0 && error_ins!=9 && ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } if(error_ins!=0 && error_ins!=9 && ndb_mgm_get_latest_error(h)!=ETIMEDOUT) { ndbout << "FAILED: Incorrect error code (" << ndb_mgm_get_latest_error(h) << " != expected " << ETIMEDOUT << ") desc: " << ndb_mgm_get_latest_error_desc(h) << " line: " << ndb_mgm_get_latest_error_line(h) << " msg: " << ndb_mgm_get_latest_error_msg(h) << endl; result= NDBT_FAILED; } } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestMgmApiGetConfigTimeout(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; int result= NDBT_OK; int mgmd_nodeid= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgmd.getConnectString()); int errs[] = { 0, 1, 2, 3, -1 }; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } ndb_mgm_reply reply; reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << error_ins << endl; result= NDBT_FAILED; } ndbout << "trying error: " << error_ins << endl; ndb_mgm_set_timeout(h,2500); struct ndb_mgm_configuration *c= ndb_mgm_get_configuration(h,0); if(c!=NULL) free(c); if(error_ins!=0 && c!=NULL) { ndbout << "FAILED: got a ndb_mgm_configuration back" << endl; result= NDBT_FAILED; } if(error_ins!=0 && ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } if(error_ins!=0 && ndb_mgm_get_latest_error(h)!=ETIMEDOUT) { ndbout << "FAILED: Incorrect error code (" << ndb_mgm_get_latest_error(h) << " != expected " << ETIMEDOUT << ") desc: " << ndb_mgm_get_latest_error_desc(h) << " line: " << ndb_mgm_get_latest_error_line(h) << " msg: " << ndb_mgm_get_latest_error_msg(h) << endl; result= NDBT_FAILED; } } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestMgmApiEventTimeout(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; int result= NDBT_OK; int mgmd_nodeid= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgmd.getConnectString()); int errs[] = { 10000, 0, -1 }; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } ndb_mgm_reply reply; reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << error_ins << endl; result= NDBT_FAILED; } ndbout << "trying error: " << error_ins << endl; ndb_mgm_set_timeout(h,2500); int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 1, NDB_MGM_EVENT_CATEGORY_STARTUP, 0 }; NDB_SOCKET_TYPE my_fd; #ifdef NDB_WIN SOCKET fd= ndb_mgm_listen_event(h, filter); my_fd.s= fd; #else int fd= ndb_mgm_listen_event(h, filter); my_fd.fd= fd; #endif if(!my_socket_valid(my_fd)) { ndbout << "FAILED: could not listen to event" << endl; result= NDBT_FAILED; } union { Uint32 theData[25]; EventReport repData; }; EventReport *fake_event = &repData; fake_event->setEventType(NDB_LE_NDBStopForced); fake_event->setNodeId(42); theData[2]= 0; theData[3]= 0; theData[4]= 0; theData[5]= 0; ndb_mgm_report_event(h, theData, 6); char *tmp= 0; char buf[512]; SocketInputStream in(my_fd,2000); for(int i=0; i<20; i++) { if((tmp = in.gets(buf, sizeof(buf)))) { // const char ping_token[]="<PING>"; // if(memcmp(ping_token,tmp,sizeof(ping_token)-1)) if(tmp && strlen(tmp)) ndbout << tmp; } else { if(in.timedout()) { ndbout << "TIMED OUT READING EVENT at iteration " << i << endl; break; } } } /* * events go through a *DIFFERENT* socket than the NdbMgmHandle * so we should still be connected (and be able to check_connection) * */ if(ndb_mgm_check_connection(h) && !ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } ndb_mgm_disconnect(h); } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestMgmApiStructEventTimeout(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; int result= NDBT_OK; int mgmd_nodeid= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgmd.getConnectString()); int errs[] = { 10000, 0, -1 }; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } ndb_mgm_reply reply; reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << error_ins << endl; result= NDBT_FAILED; } ndbout << "trying error: " << error_ins << endl; ndb_mgm_set_timeout(h,2500); int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 1, NDB_MGM_EVENT_CATEGORY_STARTUP, 0 }; NdbLogEventHandle le_handle= ndb_mgm_create_logevent_handle(h, filter); struct ndb_logevent le; for(int i=0; i<20; i++) { if(error_ins==0 || (error_ins!=0 && i<5)) { union { Uint32 theData[25]; EventReport repData; }; EventReport *fake_event = &repData; fake_event->setEventType(NDB_LE_NDBStopForced); fake_event->setNodeId(42); theData[2]= 0; theData[3]= 0; theData[4]= 0; theData[5]= 0; ndb_mgm_report_event(h, theData, 6); } int r= ndb_logevent_get_next(le_handle, &le, 2500); if(r>0) { ndbout << "Receieved event" << endl; } else if(r<0) { ndbout << "ERROR" << endl; } else // no event { ndbout << "TIMED OUT READING EVENT at iteration " << i << endl; if(error_ins==0) result= NDBT_FAILED; else result= NDBT_OK; break; } } /* * events go through a *DIFFERENT* socket than the NdbMgmHandle * so we should still be connected (and be able to check_connection) * */ if(ndb_mgm_check_connection(h) && !ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } ndb_mgm_disconnect(h); } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runSetConfig(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int loops= ctx->getNumLoops(); for (int l= 0; l < loops; l++){ g_info << l << ": "; struct ndb_mgm_configuration* conf= ndb_mgm_get_configuration(mgmd.handle(), 0); if (!conf) { g_err << "ndb_mgm_get_configuration failed, error: " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << endl; return NDBT_FAILED; } int r= ndb_mgm_set_configuration(mgmd.handle(), conf); free(conf); if (r != 0) { g_err << "ndb_mgm_set_configuration failed, error: " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << endl; return NDBT_FAILED; } } return NDBT_OK; } int runSetConfigUntilStopped(NDBT_Context* ctx, NDBT_Step* step) { int result= NDBT_OK; while(!ctx->isTestStopped() && (result= runSetConfig(ctx, step)) == NDBT_OK) ; return result; } int runGetConfig(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int loops= ctx->getNumLoops(); for (int l= 0; l < loops; l++){ g_info << l << ": "; struct ndb_mgm_configuration* conf= ndb_mgm_get_configuration(mgmd.handle(), 0); if (!conf) return NDBT_FAILED; free(conf); } return NDBT_OK; } int runGetConfigUntilStopped(NDBT_Context* ctx, NDBT_Step* step) { int result= NDBT_OK; while(!ctx->isTestStopped() && (result= runGetConfig(ctx, step)) == NDBT_OK) ; return result; } // Find a random node of a given type. static bool get_nodeid_of_type(NdbMgmd& mgmd, ndb_mgm_node_type type, int *nodeId) { ndb_mgm_node_type node_types[2] = { type, NDB_MGM_NODE_TYPE_UNKNOWN }; ndb_mgm_cluster_state *cs = ndb_mgm_get_status2(mgmd.handle(), node_types); if (cs == NULL) { g_err << "ndb_mgm_get_status2 failed, error: " << ndb_mgm_get_latest_error(mgmd.handle()) << " " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << endl; return false; } int noOfNodes = cs->no_of_nodes; int randomnode = myRandom48(noOfNodes); ndb_mgm_node_state *ns = cs->node_states + randomnode; require((Uint32)ns->node_type == (Uint32)type); require(ns->node_id != 0); *nodeId = ns->node_id; g_info << "Got node id " << *nodeId << " of type " << type << endl; free(cs); return true; } // Ensure getting config from an illegal node fails. // Return true in that case. static bool get_config_from_illegal_node(NdbMgmd& mgmd, int nodeId) { struct ndb_mgm_configuration* conf= ndb_mgm_get_configuration_from_node(mgmd.handle(), nodeId); // Get conf from an illegal node should fail. if (ndb_mgm_get_latest_error(mgmd.handle()) != NDB_MGM_GET_CONFIG_FAILED) { g_err << "ndb_mgm_get_configuration from illegal node " << nodeId << " not failed, error: " << ndb_mgm_get_latest_error(mgmd.handle()) << " " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << endl; return false; } if (conf) { // Should not get a conf from an illegal node. g_err << "ndb_mgm_get_configuration from illegal node: " << nodeId << ", error: " << ndb_mgm_get_latest_error(mgmd.handle()) << " " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << endl; free(conf); return false; } return true; } // Check get_config from a non-existing node fails. static bool check_get_config_illegal_node(NdbMgmd& mgmd) { // Find a node that does not exist Config conf; if (!mgmd.get_config(conf)) return false; int nodeId = 0; for(Uint32 i= 1; i < MAX_NODES; i++){ ConfigIter iter(&conf, CFG_SECTION_NODE); if (iter.find(CFG_NODE_ID, i) != 0){ nodeId = i; break; } } if (nodeId == 0) return true; // All nodes probably defined return get_config_from_illegal_node(mgmd, nodeId); } // Check get_config from a non-NDB/MGM node type fails static bool check_get_config_wrong_type(NdbMgmd& mgmd) { int myChoice = myRandom48(2); ndb_mgm_node_type randomAllowedType = (myChoice) ? NDB_MGM_NODE_TYPE_API : NDB_MGM_NODE_TYPE_MGM; int nodeId = 0; if (get_nodeid_of_type(mgmd, randomAllowedType, &nodeId)) { return get_config_from_illegal_node(mgmd, nodeId); } // No API/MGM nodes found. return true; } /* Find management node or a random data node, and get config from it. * Also ensure failure when getting config from * an illegal node (a non-NDB/MGM type, nodeid not defined, * or nodeid > MAX_NODES). */ int runGetConfigFromNode(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; if (!check_get_config_wrong_type(mgmd) || !check_get_config_illegal_node(mgmd) || !get_config_from_illegal_node(mgmd, MAX_NODES + 2)) { return NDBT_FAILED; } int loops= ctx->getNumLoops(); for (int l= 0; l < loops; l++) { /* Get config from a node of type: * NDB_MGM_NODE_TYPE_NDB */ int nodeId = 0; if (get_nodeid_of_type(mgmd, NDB_MGM_NODE_TYPE_NDB, &nodeId)) { struct ndb_mgm_configuration* conf = ndb_mgm_get_configuration_from_node(mgmd.handle(), nodeId); if (!conf) { g_err << "ndb_mgm_get_configuration_from_node " << nodeId << " failed, error: " << ndb_mgm_get_latest_error(mgmd.handle()) << " " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << endl; return NDBT_FAILED; } free(conf); } else { // ignore } } return NDBT_OK; } int runGetConfigFromNodeUntilStopped(NDBT_Context* ctx, NDBT_Step* step) { int result= NDBT_OK; while(!ctx->isTestStopped() && (result= runGetConfigFromNode(ctx, step)) == NDBT_OK) ; return result; } int runTestStatus(NDBT_Context* ctx, NDBT_Step* step) { ndb_mgm_node_type types[2] = { NDB_MGM_NODE_TYPE_NDB, NDB_MGM_NODE_TYPE_UNKNOWN }; NdbMgmd mgmd; struct ndb_mgm_cluster_state *state; int iterations = ctx->getNumLoops(); if (!mgmd.connect()) return NDBT_FAILED; int result= NDBT_OK; while (iterations-- != 0 && result == NDBT_OK) { state = ndb_mgm_get_status(mgmd.handle()); if(state == NULL) { ndbout_c("Could not get status!"); result= NDBT_FAILED; continue; } free(state); state = ndb_mgm_get_status2(mgmd.handle(), types); if(state == NULL){ ndbout_c("Could not get status2!"); result= NDBT_FAILED; continue; } free(state); state = ndb_mgm_get_status2(mgmd.handle(), 0); if(state == NULL){ ndbout_c("Could not get status2 second time!"); result= NDBT_FAILED; continue; } free(state); } return result; } int runTestStatusUntilStopped(NDBT_Context* ctx, NDBT_Step* step) { int result= NDBT_OK; while(!ctx->isTestStopped() && (result= runTestStatus(ctx, step)) == NDBT_OK) ; return result; } static bool get_nodeid(NdbMgmd& mgmd, const Properties& args, Properties& reply) { // Fill in default values of other args Properties call_args(args); if (!call_args.contains("version")) call_args.put("version", 1); if (!call_args.contains("nodetype")) call_args.put("nodetype", 1); if (!call_args.contains("nodeid")) call_args.put("nodeid", 1); if (!call_args.contains("user")) call_args.put("user", "mysqld"); if (!call_args.contains("password")) call_args.put("password", "mysqld"); if (!call_args.contains("public key")) call_args.put("public key", "a public key"); if (!call_args.contains("name")) call_args.put("name", "testMgm"); if (!call_args.contains("log_event")) call_args.put("log_event", 1); if (!call_args.contains("timeout")) call_args.put("timeout", 100); if (!call_args.contains("endian")) { union { long l; char c[sizeof(long)]; } endian_check; endian_check.l = 1; call_args.put("endian", (endian_check.c[sizeof(long)-1])?"big":"little"); } if (!mgmd.call("get nodeid", call_args, "get nodeid reply", reply)) { g_err << "get_nodeid: mgmd.call failed" << endl; return false; } // reply.print(); return true; } static const char* get_result(const Properties& reply) { const char* result; if (!reply.get("result", &result)){ ndbout_c("result: no 'result' found in reply"); return NULL; } return result; } static bool result_contains(const Properties& reply, const char* expected_result) { BaseString result(get_result(reply)); if (strstr(result.c_str(), expected_result) == NULL){ ndbout_c("result_contains: result string '%s' " "didn't contain expected result '%s'", result.c_str(), expected_result); return false; } g_info << " result: " << result << endl; return true; } static bool ok(const Properties& reply) { BaseString result(get_result(reply)); if (result == "Ok") return true; return false; } static bool failed(const Properties& reply) { BaseString result(get_result(reply)); if (result == "Failed") return true; return false; } static const char* get_message(const Properties& reply) { const char* message; if (!reply.get("message", &message)){ ndbout_c("message: no 'message' found in reply"); return NULL; } return message; } static bool message_contains(const Properties& reply, const char* expected_message) { BaseString message(get_message(reply)); if (strstr(message.c_str(), expected_message) == NULL){ ndbout_c("message_contains: message string '%s' " "didn't contain expected message '%s'", message.c_str(), expected_message); return false; } g_info << " message: " << message << endl; return true; } static bool get_nodeid_result_contains(NdbMgmd& mgmd, const Properties& args, const char* expected_result) { Properties reply; if (!get_nodeid(mgmd, args, reply)) return false; return result_contains(reply, expected_result); } static bool check_get_nodeid_invalid_endian1(NdbMgmd& mgmd) { union { long l; char c[sizeof(long)]; } endian_check; endian_check.l = 1; Properties args; /* Set endian to opposite value */ args.put("endian", (endian_check.c[sizeof(long)-1])?"little":"big"); return get_nodeid_result_contains(mgmd, args, "Node does not have the same endian"); } static bool check_get_nodeid_invalid_endian2(NdbMgmd& mgmd) { Properties args; /* Set endian to weird value */ args.put("endian", "hepp"); return get_nodeid_result_contains(mgmd, args, "Node does not have the same endian"); } static bool check_get_nodeid_invalid_nodetype1(NdbMgmd& mgmd) { Properties args; args.put("nodetype", 37); return get_nodeid_result_contains(mgmd, args, "unknown nodetype 37"); } static bool check_get_nodeid_invalid_nodeid(NdbMgmd& mgmd) { for (int nodeId = MAX_NODES; nodeId < MAX_NODES+2; nodeId++){ g_info << "Testing invalid node " << nodeId << endl;; Properties args; args.put("nodeid", nodeId); BaseString expected; expected.assfmt("illegal nodeid %d", nodeId); if (!get_nodeid_result_contains(mgmd, args, expected.c_str())) return false; } return true; } static bool check_get_nodeid_dynamic_nodeid(NdbMgmd& mgmd) { bool result = true; Uint32 nodeId= 0; // Get dynamic node id for (int nodeType = NDB_MGM_NODE_TYPE_MIN; nodeType < NDB_MGM_NODE_TYPE_MAX; nodeType++){ while(true) { g_info << "Testing dynamic nodeid " << nodeId << ", nodeType: " << nodeType << endl; Properties args; args.put("nodeid", nodeId); args.put("nodetype", nodeType); Properties reply; if (!get_nodeid(mgmd, args, reply)) return false; /* Continue to get dynamic id's until an error "there is no more nodeid" occur */ if (!ok(reply)){ BaseString expected1; expected1.assfmt("No free node id found for %s", NdbMgmd::NodeType(nodeType).c_str()); BaseString expected2; expected2.assfmt("Connection done from wrong host"); if (!(result_contains(reply, expected1.c_str()) || result_contains(reply, expected2.c_str()))) result= false; // Got wrong error message break; } } } return result; } static bool check_get_nodeid_nonode(NdbMgmd& mgmd) { // Find a node that does not exist Config conf; if (!mgmd.get_config(conf)) return false; Uint32 nodeId = 0; for(Uint32 i= 1; i < MAX_NODES; i++){ ConfigIter iter(&conf, CFG_SECTION_NODE); if (iter.find(CFG_NODE_ID, i) != 0){ nodeId = i; break; } } if (nodeId == 0) return true; // All nodes probably defined g_info << "Testing nonexisting node " << nodeId << endl;; Properties args; args.put("nodeid", nodeId); BaseString expected; expected.assfmt("No node defined with id=%d", nodeId); return get_nodeid_result_contains(mgmd, args, expected.c_str()); } #if 0 static bool check_get_nodeid_nodeid1(NdbMgmd& mgmd) { // Find a node that does exist Config conf; if (!mgmd.get_config(conf)) return false; Uint32 nodeId = 0; Uint32 nodeType = NDB_MGM_NODE_TYPE_UNKNOWN; for(Uint32 i= 1; i < MAX_NODES; i++){ ConfigIter iter(&conf, CFG_SECTION_NODE); if (iter.find(CFG_NODE_ID, i) == 0){ nodeId = i; iter.get(CFG_TYPE_OF_SECTION, &nodeType); break; } } require(nodeId); require(nodeType != (Uint32)NDB_MGM_NODE_TYPE_UNKNOWN); Properties args, reply; args.put("nodeid",nodeId); args.put("nodetype",nodeType); if (!get_nodeid(mgmd, args, reply)) { g_err << "check_get_nodeid_nodeid1: failed for " << "nodeid: " << nodeId << ", nodetype: " << nodeType << endl; return false; } reply.print(); return ok(reply); } #endif static bool check_get_nodeid_wrong_nodetype(NdbMgmd& mgmd) { // Find a node that does exist Config conf; if (!mgmd.get_config(conf)) return false; Uint32 nodeId = 0; Uint32 nodeType = NDB_MGM_NODE_TYPE_UNKNOWN; for(Uint32 i= 1; i < MAX_NODES; i++){ ConfigIter iter(&conf, CFG_SECTION_NODE); if (iter.find(CFG_NODE_ID, i) == 0){ nodeId = i; iter.get(CFG_TYPE_OF_SECTION, &nodeType); break; } } require(nodeId); require(nodeType != (Uint32)NDB_MGM_NODE_TYPE_UNKNOWN); nodeType = (nodeType + 1) / NDB_MGM_NODE_TYPE_MAX; require((int)nodeType >= (int)NDB_MGM_NODE_TYPE_MIN && (int)nodeType <= (int)NDB_MGM_NODE_TYPE_MAX); Properties args, reply; args.put("nodeid",nodeId); args.put("nodeid",nodeType); if (!get_nodeid(mgmd, args, reply)) { g_err << "check_get_nodeid_nodeid1: failed for " << "nodeid: " << nodeId << ", nodetype: " << nodeType << endl; return false; } BaseString expected; expected.assfmt("Id %d configured as", nodeId); return result_contains(reply, expected.c_str()); } int runTestGetNodeId(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int result= NDBT_FAILED; if ( check_get_nodeid_invalid_endian1(mgmd) && check_get_nodeid_invalid_endian2(mgmd) && check_get_nodeid_invalid_nodetype1(mgmd) && check_get_nodeid_invalid_nodeid(mgmd) && check_get_nodeid_dynamic_nodeid(mgmd) && check_get_nodeid_nonode(mgmd) && // check_get_nodeid_nodeid1(mgmd) && check_get_nodeid_wrong_nodetype(mgmd) && true) result= NDBT_OK; if (!mgmd.end_session()) result= NDBT_FAILED; return result; } int runTestGetNodeIdUntilStopped(NDBT_Context* ctx, NDBT_Step* step) { int result= NDBT_OK; while(!ctx->isTestStopped() && (result= runTestGetNodeId(ctx, step)) == NDBT_OK) ; return result; } int runSleepAndStop(NDBT_Context* ctx, NDBT_Step* step) { int counter= 3*ctx->getNumLoops(); while(!ctx->isTestStopped() && counter--) NdbSleep_SecSleep(1);; ctx->stopTest(); return NDBT_OK; } static bool check_connection(NdbMgmd& mgmd) { Properties args, reply; mgmd.verbose(false); // Verbose off bool result= mgmd.call("check connection", args, "check connection reply", reply); mgmd.verbose(); // Verbose on return result; } static bool check_transporter_connect(NdbMgmd& mgmd, const char * hello) { SocketOutputStream out(mgmd.socket()); // Call 'transporter connect' if (out.println("transporter connect\n")) { g_err << "Send failed" << endl; return false; } // Send the 'hello' g_info << "Client hello: '" << hello << "'" << endl; if (out.println("%s", hello)) { g_err << "Send hello '" << hello << "' failed" << endl; return false; } // Should not be possible to read a reply now, socket // should have been closed if (check_connection(mgmd)){ g_err << "not disconnected" << endl; return false; } // disconnect and connect again if (!mgmd.disconnect()) return false; if (!mgmd.connect()) return false; return true; } int runTestTransporterConnect(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int result = NDBT_FAILED; if ( // Junk hello strings check_transporter_connect(mgmd, "hello") && check_transporter_connect(mgmd, "hello again") && // "Blow" the buffer check_transporter_connect(mgmd, "string_longer_than_buf_1234567890") && // Out of range nodeid check_transporter_connect(mgmd, "-1") && check_transporter_connect(mgmd, "-2 2") && check_transporter_connect(mgmd, "10000") && check_transporter_connect(mgmd, "99999 8") && // Valid nodeid, invalid transporter type // Valid nodeid and transporter type, state != CONNECTING // ^These are only possible to test by finding an existing // NDB node that are not started and use its setting(s) true) result = NDBT_OK; return result; } static bool show_config(NdbMgmd& mgmd, const Properties& args, Properties& reply) { if (!mgmd.call("show config", args, "show config reply", reply, NULL, false)) { g_err << "show_config: mgmd.call failed" << endl; return false; } // reply.print(); return true; } int runCheckConfig(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; // Connect to any mgmd and get the config if (!mgmd.connect()) return NDBT_FAILED; Properties args1; Properties config1; if (!show_config(mgmd, args1, config1)) return NDBT_FAILED; // Get the binary config Config conf; if (!mgmd.get_config(conf)) return NDBT_FAILED; // Extract list of connectstrings to each mgmd BaseString connectstring; conf.getConnectString(connectstring, ";"); Vector<BaseString> mgmds; connectstring.split(mgmds, ";"); // Connect to each mgmd and check // they all have the same config for (unsigned i = 0; i < mgmds.size(); i++) { NdbMgmd mgmd2; g_info << "Connecting to " << mgmds[i].c_str() << endl; if (!mgmd2.connect(mgmds[i].c_str())) return NDBT_FAILED; Properties args2; Properties config2; if (!show_config(mgmd, args2, config2)) return NDBT_FAILED; // Compare config1 and config2 line by line Uint32 line = 1; const char* value1; const char* value2; while (true) { if (config1.get("line", line, &value1)) { // config1 had line, so should config2 if (config2.get("line", line, &value2)) { // both configs had line, check they are equal if (strcmp(value1, value2) != 0) { g_err << "the value on line " << line << "didn't match!" << endl; g_err << "config1, value: " << value1 << endl; g_err << "config2, value: " << value2 << endl; return NDBT_FAILED; } // g_info << line << ": " << value1 << " = " << value2 << endl; } else { g_err << "config2 didn't have line " << line << "!" << endl; return NDBT_FAILED; } } else { // Make sure config2 does not have this line either and end loop if (config2.get("line", line, &value2)) { g_err << "config2 had line " << line << " not in config1!" << endl; return NDBT_FAILED; } // End of loop g_info << "There was " << line << " lines in config" << endl; break; } line++; } if (line == 0) { g_err << "FAIL: config should have lines!" << endl; return NDBT_FAILED; } // Compare the binary config Config conf2; if (!mgmd.get_config(conf2)) return NDBT_FAILED; if (!conf.equal(&conf2)) { g_err << "The binary config was different! host: " << mgmds[i] << endl; return NDBT_FAILED; } } return NDBT_OK; } static bool reload_config(NdbMgmd& mgmd, const Properties& args, Properties& reply) { if (!mgmd.call("reload config", args, "reload config reply", reply)) { g_err << "reload config: mgmd.call failed" << endl; return false; } //reply.print(); return true; } static bool reload_config_result_contains(NdbMgmd& mgmd, const Properties& args, const char* expected_result) { Properties reply; if (!reload_config(mgmd, args, reply)) return false; return result_contains(reply, expected_result); } static bool check_reload_config_both_config_and_mycnf(NdbMgmd& mgmd) { Properties args; // Send reload command with both config_filename and mycnf set args.put("config_filename", "some filename"); args.put("mycnf", 1); return reload_config_result_contains(mgmd, args, "ERROR: Both mycnf and config_filename"); } static bool show_variables(NdbMgmd& mgmd, Properties& reply) { if (!mgmd.call("show variables", "", "show variables reply", reply)) { g_err << "show_variables: mgmd.call failed" << endl; return false; } return true; } static bool check_reload_config_invalid_config_filename(NdbMgmd& mgmd, bool mycnf) { BaseString expected("Could not load configuration from 'nonexisting_file"); if (mycnf) { // Differing error message if started from my.cnf expected.assign("Can't switch to use config.ini 'nonexisting_file' " "when node was started from my.cnf"); } Properties args; // Send reload command with an invalid config_filename args.put("config_filename", "nonexisting_file"); return reload_config_result_contains(mgmd, args, expected.c_str()); } int runTestReloadConfig(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; Properties variables; if (!show_variables(mgmd, variables)) return NDBT_FAILED; variables.print(); const char* mycnf_str; if (!variables.get("mycnf", &mycnf_str)) abort(); bool uses_mycnf = (strcmp(mycnf_str, "yes") == 0); int result= NDBT_FAILED; if ( check_reload_config_both_config_and_mycnf(mgmd) && check_reload_config_invalid_config_filename(mgmd, uses_mycnf) && true) result= NDBT_OK; if (!mgmd.end_session()) result= NDBT_FAILED; return result; } static bool set_config(NdbMgmd& mgmd, const Properties& args, BaseString encoded_config, Properties& reply) { // Fill in default values of other args Properties call_args(args); if (!call_args.contains("Content-Type")) call_args.put("Content-Type", "ndbconfig/octet-stream"); if (!call_args.contains("Content-Transfer-Encoding")) call_args.put("Content-Transfer-Encoding", "base64"); if (!call_args.contains("Content-Length")) call_args.put("Content-Length", encoded_config.length() ? encoded_config.length() - 1 : 1); if (!mgmd.call("set config", call_args, "set config reply", reply, encoded_config.c_str())) { g_err << "set config: mgmd.call failed" << endl; return false; } //reply.print(); return true; } static bool set_config_result_contains(NdbMgmd& mgmd, const Properties& args, const BaseString& encoded_config, const char* expected_result) { Properties reply; if (!set_config(mgmd, args, encoded_config, reply)) return false; return result_contains(reply, expected_result); } static bool set_config_result_contains(NdbMgmd& mgmd, const Config& conf, const char* expected_result) { Properties reply; Properties args; BaseString encoded_config; if (!conf.pack64(encoded_config)) return false; if (!set_config(mgmd, args, encoded_config, reply)) return false; return result_contains(reply, expected_result); } static bool check_set_config_invalid_content_type(NdbMgmd& mgmd) { Properties args; args.put("Content-Type", "illegal type"); return set_config_result_contains(mgmd, args, BaseString(""), "Unhandled content type 'illegal type'"); } static bool check_set_config_invalid_content_encoding(NdbMgmd& mgmd) { Properties args; args.put("Content-Transfer-Encoding", "illegal encoding"); return set_config_result_contains(mgmd, args, BaseString(""), "Unhandled content encoding " "'illegal encoding'"); } static bool check_set_config_too_large_content_length(NdbMgmd& mgmd) { Properties args; args.put("Content-Length", 1024*1024 + 1); return set_config_result_contains(mgmd, args, BaseString(""), "Illegal config length size 1048577"); } static bool check_set_config_too_small_content_length(NdbMgmd& mgmd) { Properties args; args.put("Content-Length", (Uint32)0); return set_config_result_contains(mgmd, args, BaseString(""), "Illegal config length size 0"); } static bool check_set_config_wrong_config_length(NdbMgmd& mgmd) { // Get the binary config Config conf; if (!mgmd.get_config(conf)) return false; BaseString encoded_config; if (!conf.pack64(encoded_config)) return false; Properties args; args.put("Content-Length", encoded_config.length() - 20); bool res = set_config_result_contains(mgmd, args, encoded_config, "Failed to unpack config"); if (res){ /* There are now additional 20 bytes of junk that has been sent to mgmd, reconnect to get rid of it */ if (!mgmd.disconnect()) return false; if (!mgmd.connect()) return false; } return res; } static bool check_set_config_any_node(NDBT_Context* ctx, NDBT_Step* step, NdbMgmd& mgmd) { // Get the binary config Config conf; if (!mgmd.get_config(conf)) return false; // Extract list of connectstrings to each mgmd BaseString connectstring; conf.getConnectString(connectstring, ";"); Vector<BaseString> mgmds; connectstring.split(mgmds, ";"); // Connect to each mgmd and check // they all have the same config for (unsigned i = 0; i < mgmds.size(); i++) { NdbMgmd mgmd2; g_info << "Connecting to " << mgmds[i].c_str() << endl; if (!mgmd2.connect(mgmds[i].c_str())) return false; // Get the binary config Config conf2; if (!mgmd2.get_config(conf2)) return false; // Set the modified config if (!mgmd2.set_config(conf2)) return false; // Check that all mgmds now have the new config if (runCheckConfig(ctx, step) != NDBT_OK) return false; } return true; } static bool check_set_config_fail_wrong_generation(NdbMgmd& mgmd) { // Get the binary config Config conf; if (!mgmd.get_config(conf)) return false; // Change generation if (!conf.setGeneration(conf.getGeneration() + 10)) return false; // Set the modified config return set_config_result_contains(mgmd, conf, "Invalid generation in"); } static bool check_set_config_fail_wrong_name(NdbMgmd& mgmd) { // Get the binary config Config conf; if (!mgmd.get_config(conf)) return false; // Change name if (!conf.setName("NEWNAME")) return false; // Set the modified config return set_config_result_contains(mgmd, conf, "Invalid configuration name"); } static bool check_set_config_fail_wrong_primary(NdbMgmd& mgmd) { // Get the binary config Config conf; if (!mgmd.get_config(conf)) return false; // Change primary and thus make this configuration invalid if (!conf.setPrimaryMgmNode(conf.getPrimaryMgmNode()+10)) return false; // Set the modified config return set_config_result_contains(mgmd, conf, "Not primary mgm node"); } int runTestSetConfig(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int result= NDBT_FAILED; if ( check_set_config_invalid_content_type(mgmd) && check_set_config_invalid_content_encoding(mgmd) && check_set_config_too_large_content_length(mgmd) && check_set_config_too_small_content_length(mgmd) && check_set_config_wrong_config_length(mgmd) && check_set_config_any_node(ctx, step, mgmd) && check_set_config_fail_wrong_generation(mgmd) && check_set_config_fail_wrong_name(mgmd) && check_set_config_fail_wrong_primary(mgmd) && true) result= NDBT_OK; if (!mgmd.end_session()) result= NDBT_FAILED; return result; } int runTestSetConfigParallel(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int result = NDBT_OK; int loops = ctx->getNumLoops(); int sucessful = 0; int invalid_generation = 0, config_change_ongoing = 0; /* continue looping until "loops" number of successful changes have been made from this thread */ while (sucessful < loops && !ctx->isTestStopped() && result == NDBT_OK) { // Get the binary config Config conf; if (!mgmd.get_config(conf)) return NDBT_FAILED; /* Set the config and check for valid errors */ mgmd.verbose(false); if (mgmd.set_config(conf)) { /* Config change suceeded */ sucessful++; } else { /* Config change failed */ if (mgmd.last_error() != NDB_MGM_CONFIG_CHANGE_FAILED) { g_err << "Config change failed with unexpected error: " << mgmd.last_error() << endl; result = NDBT_FAILED; continue; } BaseString error(mgmd.last_error_message()); if (error == "Invalid generation in configuration") invalid_generation++; else if (error == "Config change ongoing") config_change_ongoing++; else { g_err << "Config change failed with unexpected error: '" << error << "'" << endl; result = NDBT_FAILED; } } } ndbout << "Thread " << step->getStepNo() << ", sucess: " << sucessful << ", ongoing: " << config_change_ongoing << ", invalid_generation: " << invalid_generation << endl; return result; } int runTestSetConfigParallelUntilStopped(NDBT_Context* ctx, NDBT_Step* step) { int result= NDBT_OK; while(!ctx->isTestStopped() && (result= runTestSetConfigParallel(ctx, step)) == NDBT_OK) ; return result; } static bool get_connection_parameter(NdbMgmd& mgmd, const Properties& args, Properties& reply) { // Fill in default values of other args Properties call_args(args); if (!call_args.contains("node1")) call_args.put("node1", 1); if (!call_args.contains("node2")) call_args.put("node2", 1); if (!call_args.contains("param")) call_args.put("param", CFG_CONNECTION_SERVER_PORT); if (!mgmd.call("get connection parameter", call_args, "get connection parameter reply", reply)) { g_err << "get_connection_parameter: mgmd.call failed" << endl; return false; } return true; } static bool set_connection_parameter(NdbMgmd& mgmd, const Properties& args, Properties& reply) { // Fill in default values of other args Properties call_args(args); if (!call_args.contains("node1")) call_args.put("node1", 1); if (!call_args.contains("node2")) call_args.put("node2", 1); if (!call_args.contains("param")) call_args.put("param", CFG_CONNECTION_SERVER_PORT); if (!call_args.contains("value")) call_args.put("value", 37); if (!mgmd.call("set connection parameter", call_args, "set connection parameter reply", reply)) { g_err << "set_connection_parameter: mgmd.call failed" << endl; return false; } return true; } static bool check_connection_parameter_invalid_nodeid(NdbMgmd& mgmd) { for (int nodeId = MAX_NODES; nodeId < MAX_NODES+2; nodeId++){ g_info << "Testing invalid node " << nodeId << endl;; Properties args; args.put("node1", nodeId); args.put("node2", nodeId); Properties get_result; if (!get_connection_parameter(mgmd, args, get_result)) return false; if (!result_contains(get_result, "Unable to find connection between nodes")) return false; Properties set_result; if (!set_connection_parameter(mgmd, args, set_result)) return false; if (!failed(set_result)) return false; if (!message_contains(set_result, "Unable to find connection between nodes")) return false; } return true; } static bool check_connection_parameter(NdbMgmd& mgmd) { // Find a NDB node with dynamic port Config conf; if (!mgmd.get_config(conf)) return false; Uint32 nodeId1 = 0; for(Uint32 i= 1; i < MAX_NODES; i++){ Uint32 nodeType; ConfigIter iter(&conf, CFG_SECTION_NODE); if (iter.find(CFG_NODE_ID, i) == 0 && iter.get(CFG_TYPE_OF_SECTION, &nodeType) == 0 && nodeType == NDB_MGM_NODE_TYPE_NDB){ nodeId1 = i; break; } } NodeId otherNodeId = 0; BaseString original_value; // Get current value of first connection between mgmd and other node for (int nodeId = 1; nodeId < MAX_NODES; nodeId++){ g_info << "Checking if connection between " << nodeId1 << " and " << nodeId << " exists" << endl; Properties args; args.put("node1", nodeId1); args.put("node2", nodeId); Properties result; if (!get_connection_parameter(mgmd, args, result)) return false; if (!ok(result)) continue; result.print(); // Get the nodeid otherNodeId = nodeId; // Get original value if (!result.get("value", original_value)) { g_err << "Failed to get original value" << endl; return false; } break; // Done with the loop } if (otherNodeId == 0) { g_err << "Could not find a suitable connection for test" << endl; return false; } Properties get_args; get_args.put("node1", nodeId1); get_args.put("node2", otherNodeId); { g_info << "Set new value(37 by default)" << endl; Properties set_args(get_args); Properties set_result; if (!set_connection_parameter(mgmd, set_args, set_result)) return false; if (!ok(set_result)) return false; } { g_info << "Check new value" << endl; Properties get_result; if (!get_connection_parameter(mgmd, get_args, get_result)) return false; if (!ok(get_result)) return false; BaseString new_value; if (!get_result.get("value", new_value)) { g_err << "Failed to get new value" << endl; return false; } g_info << "new_value: " << new_value << endl; if (new_value != "37") { g_err << "New value was not correct, expected 37, got " << new_value << endl; return false; } } { g_info << "Restore old value" << endl; Properties set_args(get_args); if (!set_args.put("value", original_value.c_str())) { g_err << "Failed to put original_value" << endl; return false; } Properties set_result; if (!set_connection_parameter(mgmd, set_args, set_result)) return false; if (!ok(set_result)) return false; } { g_info << "Check restored value" << endl; Properties get_result; if (!get_connection_parameter(mgmd, get_args, get_result)) return false; if (!ok(get_result)) return false; BaseString restored_value; if (!get_result.get("value", restored_value)) { g_err << "Failed to get restored value" << endl; return false; } if (restored_value != original_value) { g_err << "Restored value was not correct, expected " << original_value << ", got " << restored_value << endl; return false; } g_info << "restored_value: " << restored_value << endl; } return true; } int runTestConnectionParameter(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int result= NDBT_FAILED; if ( check_connection_parameter(mgmd) && check_connection_parameter_invalid_nodeid(mgmd) && true) result= NDBT_OK; if (!mgmd.end_session()) result= NDBT_FAILED; return result; } int runTestConnectionParameterUntilStopped(NDBT_Context* ctx, NDBT_Step* step) { int result= NDBT_OK; while(!ctx->isTestStopped() && (result= runTestConnectionParameter(ctx, step)) == NDBT_OK) ; return result; } static bool set_ports(NdbMgmd& mgmd, const Properties& args, const char* bulk_arg, Properties& reply) { if (!mgmd.call("set ports", args, "set ports reply", reply, bulk_arg)) { g_err << "set_ports: mgmd.call failed" << endl; return false; } return true; } static bool check_set_ports_invalid_nodeid(NdbMgmd& mgmd) { for (int nodeId = MAX_NODES; nodeId < MAX_NODES+2; nodeId++) { g_err << "Testing invalid node " << nodeId << endl; Properties args; args.put("node", nodeId); args.put("num_ports", 2); Properties set_result; if (!set_ports(mgmd, args, "", set_result)) return false; if (ok(set_result)) return false; if (!result_contains(set_result, "Illegal value for argument node")) return false; } return true; } static bool check_set_ports_invalid_num_ports(NdbMgmd& mgmd) { g_err << "Testing invalid number of ports "<< endl; Properties args; args.put("node", 1); args.put("num_ports", MAX_NODES + 37); Properties set_result; if (!set_ports(mgmd, args, "", set_result)) return false; if (ok(set_result)) return false; if (!result_contains(set_result, "Illegal value for argument num_ports")) return false; return true; } static bool check_set_ports_invalid_mismatch_num_port_1(NdbMgmd& mgmd) { g_err << "Testing invalid num port 1"<< endl; Properties args; args.put("node", 1); args.put("num_ports", 1); // Intend to send 1 ^ but passes two below Properties set_result; if (!set_ports(mgmd, args, "1=-37\n2=-38\n", set_result)) return false; if (ok(set_result)) return false; set_result.print(); if (!result_contains(set_result, "expected empty line")) return false; return true; } static bool check_set_ports_invalid_mismatch_num_port_2(NdbMgmd& mgmd) { g_err << "Testing invalid num port 2"<< endl; Properties args; args.put("node", 1); args.put("num_ports", 2); // Intend to send 2 ^ but pass only one line below Properties set_result; if (!set_ports(mgmd, args, "1=-37\n", set_result)) return false; if (ok(set_result)) return false; set_result.print(); if (!result_contains(set_result, "expected name=value pair")) return false; return true; } static bool check_set_ports_invalid_port_list(NdbMgmd& mgmd) { g_err << "Testing invalid port list"<< endl; Properties args; args.put("node", 1); // No connection from 1 -> 1 exist args.put("num_ports", 1); Properties set_result; if (!set_ports(mgmd, args, "1=-37\n", set_result)) return false; set_result.print(); if (ok(set_result)) return false; if (!result_contains(set_result, "Unable to find connection between nodes 1 -> 1")) return false; return true; } static bool check_mgmapi_err(NdbMgmd& mgmd, int return_code, int expected_error, const char* expected_message) { if (return_code != -1) { ndbout_c("check_mgmapi_error: unexpected return code: %d", return_code); return false; } if (mgmd.last_error() != expected_error) { ndbout_c("check_mgmapi_error: unexpected error code: %d " "expected %d", mgmd.last_error(), expected_error); return false; } if (strstr(mgmd.last_error_message(), expected_message) == NULL) { ndbout_c("check_mgmapi_error: last_error_message '%s' " "didn't contain expected message '%s'", mgmd.last_error_message(), expected_message); return false; } return true; } static bool check_set_ports_mgmapi(NdbMgmd& mgmd) { g_err << "Testing mgmapi"<< endl; int ret; int nodeid = 1; unsigned num_ports = 1; ndb_mgm_dynamic_port ports[MAX_NODES * 10]; compile_time_assert(MAX_NODES < NDB_ARRAY_SIZE(ports)); ports[0].nodeid = 1; ports[0].port = -1; { ndbout_c("No handle"); NdbMgmd no_handle; ret = ndb_mgm_set_dynamic_ports(no_handle.handle(), nodeid, ports, num_ports); if (ret != -1) return false; } { ndbout_c("Not connected"); NdbMgmd no_con; no_con.verbose(false); if (no_con.connect("no_such_host:12345", 0, 1)) { // Connect should not suceed! return false; } ret = ndb_mgm_set_dynamic_ports(no_con.handle(), nodeid, ports, num_ports); if (!check_mgmapi_err(no_con, ret, NDB_MGM_SERVER_NOT_CONNECTED, "")) return false; } ndbout_c("Invalid number of ports"); num_ports = 0; // << ret = ndb_mgm_set_dynamic_ports(mgmd.handle(), nodeid, ports, num_ports); if (!check_mgmapi_err(mgmd, ret, NDB_MGM_USAGE_ERROR, "Illegal number of dynamic ports")) return false; ndbout_c("Invalid nodeid"); nodeid = 0; // << num_ports = 1; ret = ndb_mgm_set_dynamic_ports(mgmd.handle(), nodeid, ports, num_ports); if (!check_mgmapi_err(mgmd, ret, NDB_MGM_USAGE_ERROR, "Illegal value for argument node: 0")) return false; ndbout_c("Invalid port in list"); nodeid = 1; ports[0].nodeid = 1; ports[0].port = 1; // << ret = ndb_mgm_set_dynamic_ports(mgmd.handle(), nodeid, ports, num_ports); if (!check_mgmapi_err(mgmd, ret, NDB_MGM_USAGE_ERROR, "Illegal port specfied in ports array")) return false; ndbout_c("Invalid nodeid in list"); nodeid = 1; ports[0].nodeid = 0; // << ports[0].port = -11; ret = ndb_mgm_set_dynamic_ports(mgmd.handle(), nodeid, ports, num_ports); if (!check_mgmapi_err(mgmd, ret, NDB_MGM_USAGE_ERROR, "Illegal nodeid specfied in ports array")) return false; ndbout_c("Max number of ports exceeded"); nodeid = 1; num_ports = MAX_NODES; // << for (unsigned i = 0; i < num_ports; i++) { ports[i].nodeid = i+1; ports[i].port = -37; } ret = ndb_mgm_set_dynamic_ports(mgmd.handle(), nodeid, ports, num_ports); if (!check_mgmapi_err(mgmd, ret, NDB_MGM_USAGE_ERROR, "Illegal value for argument num_ports")) return false; ndbout_c("Many many ports"); nodeid = 1; num_ports = NDB_ARRAY_SIZE(ports); // << for (unsigned i = 0; i < num_ports; i++) { ports[i].nodeid = i+1; ports[i].port = -37; } ret = ndb_mgm_set_dynamic_ports(mgmd.handle(), nodeid, ports, num_ports); if (!check_mgmapi_err(mgmd, ret, NDB_MGM_USAGE_ERROR, "Illegal value for argument num_ports")) return false; return true; } // Return name value pair of nodeid/ports which can be sent // verbatim back to ndb_mgmd static bool get_all_ports(NdbMgmd& mgmd, Uint32 nodeId1, BaseString& values) { for (int nodeId = 1; nodeId < MAX_NODES; nodeId++) { Properties args; args.put("node1", nodeId1); args.put("node2", nodeId); Properties result; if (!get_connection_parameter(mgmd, args, result)) return false; if (!ok(result)) continue; // Get value BaseString value; if (!result.get("value", value)) { g_err << "Failed to get value" << endl; return false; } values.appfmt("%d=%s\n", nodeId, value.c_str()); } return true; } static bool check_set_ports(NdbMgmd& mgmd) { // Find a NDB node with dynamic port Config conf; if (!mgmd.get_config(conf)) return false; Uint32 nodeId1 = 0; for(Uint32 i= 1; i < MAX_NODES; i++){ Uint32 nodeType; ConfigIter iter(&conf, CFG_SECTION_NODE); if (iter.find(CFG_NODE_ID, i) == 0 && iter.get(CFG_TYPE_OF_SECTION, &nodeType) == 0 && nodeType == NDB_MGM_NODE_TYPE_NDB){ nodeId1 = i; break; } } g_err << "Using NDB node with id: " << nodeId1 << endl; g_err << "Get original values of dynamic ports" << endl; BaseString original_values; if (!get_all_ports(mgmd, nodeId1, original_values)) { g_err << "Failed to get all original values" << endl; return false; } ndbout_c("original values: %s", original_values.c_str()); g_err << "Set new values for all dynamic ports" << endl; BaseString new_values; { Vector<BaseString> port_pairs; original_values.split(port_pairs, "\n"); // Remove last empty line require(port_pairs[port_pairs.size()-1] == ""); port_pairs.erase(port_pairs.size()-1); // Generate new portnumbers for (unsigned i = 0; i < port_pairs.size(); i++) { int nodeid, port; if (sscanf(port_pairs[i].c_str(), "%d=%d", &nodeid, &port) != 2) { g_err << "Failed to parse port_pairs[" << i << "]: '" << port_pairs[i] << "'" << endl; return false; } const int new_port = -(int)(i + 37); new_values.appfmt("%d=%d\n", nodeid, new_port); } Properties args; args.put("node", nodeId1); args.put("num_ports", port_pairs.size()); Properties set_result; if (!set_ports(mgmd, args, new_values.c_str(), set_result)) return false; if (!ok(set_result)) { g_err << "Unexpected result received from set_ports" << endl; set_result.print(); return false; } } g_err << "Compare new values of dynamic ports" << endl; { BaseString current_values; if (!get_all_ports(mgmd, nodeId1, current_values)) { g_err << "Failed to get all current values" << endl; return false; } ndbout_c("current values: %s", current_values.c_str()); if (current_values != new_values) { g_err << "Set values was not correct, expected " << new_values << ", got " << current_values << endl; return false; } } g_err << "Restore old values" << endl; { Vector<BaseString> port_pairs; original_values.split(port_pairs, "\n"); // Remove last empty line require(port_pairs[port_pairs.size()-1] == ""); port_pairs.erase(port_pairs.size()-1); Properties args; args.put("node", nodeId1); args.put("num_ports", port_pairs.size()); Properties set_result; if (!set_ports(mgmd, args, original_values.c_str(), set_result)) return false; if (!ok(set_result)) { g_err << "Unexpected result received from set_ports" << endl; set_result.print(); return false; } } g_err << "Check restored values" << endl; { BaseString current_values; if (!get_all_ports(mgmd, nodeId1, current_values)) { g_err << "Failed to get all current values" << endl; return false; } ndbout_c("current values: %s", current_values.c_str()); if (current_values != original_values) { g_err << "Restored values was not correct, expected " << original_values << ", got " << current_values << endl; return false; } } return true; } int runTestSetPorts(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int result= NDBT_FAILED; if ( check_set_ports(mgmd) && check_set_ports_invalid_nodeid(mgmd) && check_set_ports_invalid_num_ports(mgmd) && check_set_ports_invalid_mismatch_num_port_1(mgmd) && check_set_ports_invalid_mismatch_num_port_2(mgmd) && check_set_ports_invalid_port_list(mgmd) && check_set_ports_mgmapi(mgmd) && true) result= NDBT_OK; if (!mgmd.end_session()) result= NDBT_FAILED; return result; } #ifdef NOT_YET static bool check_restart_connected(NdbMgmd& mgmd) { if (!mgmd.restart()) return false; return true; } int runTestRestartMgmd(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int result= NDBT_FAILED; if ( check_restart_connected(mgmd) && true) result= NDBT_OK; if (!mgmd.end_session()) result= NDBT_FAILED; return result; } #endif static bool set_logfilter(NdbMgmd& mgmd, enum ndb_mgm_event_severity severity, int enable) { struct ndb_mgm_reply reply; if (ndb_mgm_set_clusterlog_severity_filter(mgmd.handle(), severity, enable, &reply ) == -1) { g_err << "set_logfilter: ndb_mgm_set_clusterlog_severity_filter failed" << endl; return false; } return true; } static bool get_logfilter(NdbMgmd& mgmd, enum ndb_mgm_event_severity severity, unsigned int* value) { struct ndb_mgm_severity severity_struct; severity_struct.category = severity; if (ndb_mgm_get_clusterlog_severity_filter(mgmd.handle(), &severity_struct, 1) != 1) { g_err << "get_logfilter: ndb_mgm_get_clusterlog_severity_filter failed" << endl; return false; } require(value); *value = severity_struct.value; return true; } int runTestSetLogFilter(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; for (int i = 0; i < (int)NDB_MGM_EVENT_SEVERITY_ALL; i++) { g_info << "severity: " << i << endl; ndb_mgm_event_severity severity = (ndb_mgm_event_severity)i; // Get initial value of level unsigned int initial_value; if (!get_logfilter(mgmd, severity, &initial_value)) return NDBT_FAILED; // Turn level off if (!set_logfilter(mgmd, severity, 0)) return NDBT_FAILED; // Check it's off unsigned int curr_value; if (!get_logfilter(mgmd, severity, &curr_value)) return NDBT_FAILED; if (curr_value != 0) { g_err << "Failed to turn off severity: " << severity << endl; return NDBT_FAILED; } // Turn level on if (!set_logfilter(mgmd, severity, 1)) return NDBT_FAILED; // Check it's on if (!get_logfilter(mgmd, severity, &curr_value)) return NDBT_FAILED; if (curr_value == 0) { g_err << "Filed to turn on severity: " << severity << endl; return NDBT_FAILED; } // Toggle, ie. turn off if (!set_logfilter(mgmd, severity, -1)) return NDBT_FAILED; // Check it's off if (!get_logfilter(mgmd, severity, &curr_value)) return NDBT_FAILED; if (curr_value != 0) { g_err << "Failed to toggle severity : " << severity << endl; return NDBT_FAILED; } // Set back initial value if (!set_logfilter(mgmd, severity, initial_value)) return NDBT_FAILED; } return NDBT_OK; } int runTestBug40922(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 1, NDB_MGM_EVENT_CATEGORY_STARTUP, 0 }; NdbLogEventHandle le_handle = ndb_mgm_create_logevent_handle(mgmd.handle(), filter); if (!le_handle) return NDBT_FAILED; g_info << "Calling ndb_log_event_get_next" << endl; struct ndb_logevent le_event; int r = ndb_logevent_get_next(le_handle, &le_event, 2000); g_info << "ndb_log_event_get_next returned " << r << endl; int result = NDBT_FAILED; if (r == 0) { // Got timeout g_info << "ndb_logevent_get_next returned timeout" << endl; result = NDBT_OK; } else { if(r>0) g_err << "ERROR: Receieved unexpected event: " << le_event.type << endl; if(r<0) g_err << "ERROR: ndb_logevent_get_next returned error: " << r << endl; } ndb_mgm_destroy_logevent_handle(&le_handle); return result; } int runTestBug45497(NDBT_Context* ctx, NDBT_Step* step) { int result = NDBT_OK; int loops = ctx->getNumLoops(); Vector<NdbMgmd*> mgmds; while(true) { NdbMgmd* mgmd = new NdbMgmd(); // Set quite short timeout if (!mgmd->set_timeout(1000)) { result = NDBT_FAILED; break; } if (mgmd->connect()) { mgmds.push_back(mgmd); g_info << "connections: " << mgmds.size() << endl; continue; } g_err << "Failed to make another connection, connections: " << mgmds.size() << endl; // Disconnect some connections int to_disconnect = 10; while(mgmds.size() && to_disconnect--) { g_info << "disconnnect, connections: " << mgmds.size() << endl; NdbMgmd* mgmd = mgmds[0]; mgmds.erase(0); delete mgmd; } if (loops-- == 0) break; } while(mgmds.size()) { NdbMgmd* mgmd = mgmds[0]; mgmds.erase(0); delete mgmd; } return result; } bool isCategoryValid(struct ndb_logevent* le) { switch (le->category) { case NDB_MGM_EVENT_CATEGORY_BACKUP: case NDB_MGM_EVENT_CATEGORY_STARTUP: case NDB_MGM_EVENT_CATEGORY_NODE_RESTART: case NDB_MGM_EVENT_CATEGORY_CONNECTION: case NDB_MGM_EVENT_CATEGORY_STATISTIC: case NDB_MGM_EVENT_CATEGORY_CHECKPOINT: return true; default: return false; } } int runTestBug16723708(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; int loops = ctx->getNumLoops(); int result = NDBT_FAILED; if (!mgmd.connect()) return NDBT_FAILED; int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 15, NDB_MGM_EVENT_CATEGORY_STARTUP, 15, NDB_MGM_EVENT_CATEGORY_NODE_RESTART, 15, NDB_MGM_EVENT_CATEGORY_CONNECTION, 15, NDB_MGM_EVENT_CATEGORY_STATISTIC, 15, NDB_MGM_EVENT_CATEGORY_CHECKPOINT, 0 }; NdbLogEventHandle le_handle = ndb_mgm_create_logevent_handle(mgmd.handle(), filter); if (!le_handle) return NDBT_FAILED; NdbLogEventHandle le_handle2 = ndb_mgm_create_logevent_handle(mgmd.handle(), filter); if (!le_handle2) return NDBT_FAILED; for(int l=0; l<loops; l++) { g_info << "Calling ndb_log_event_get_next" << endl; struct ndb_logevent le_event; int r = ndb_logevent_get_next(le_handle, &le_event, 2000); g_info << "ndb_log_event_get_next returned " << r << endl; struct ndb_logevent le_event2; int r2 = ndb_logevent_get_next2(le_handle2, &le_event2, 2000); g_info << "ndb_log_event_get_next2 returned " << r2 << endl; result = NDBT_OK; if ((r == 0) || (r2 == 0)) { // Got timeout g_info << "ndb_logevent_get_next[2] returned timeout" << endl; } else { if(r>0) { g_info << "next() ndb_logevent type : " << le_event.type << " category : " << le_event.category << " " << ndb_mgm_get_event_category_string(le_event.category) << endl; if (isCategoryValid(&le_event)) { g_err << "ERROR: ndb_logevent_get_next() returned valid category! " << le_event.category << endl; result = NDBT_FAILED; } } else { g_err << "ERROR: ndb_logevent_get_next returned error: " << r << endl; } if(r2>0) { g_info << "next2() ndb_logevent type : " << le_event2.type << " category : " << le_event2.category << " " << ndb_mgm_get_event_category_string(le_event2.category) << endl; if (!isCategoryValid(&le_event2)) { g_err << "ERROR: ndb_logevent_get_next2() returned invalid category! " << le_event2.category << endl; result = NDBT_FAILED; } } else { g_err << "ERROR: ndb_logevent_get_next2 returned error: " << r << endl; result = NDBT_FAILED; } } if(result == NDBT_FAILED) break; } ndb_mgm_destroy_logevent_handle(&le_handle2); ndb_mgm_destroy_logevent_handle(&le_handle); return result; } static int runTestGetVersion(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; char verStr[64]; int major, minor, build; if (ndb_mgm_get_version(mgmd.handle(), &major, &minor, &build, sizeof(verStr), verStr) != 1) { g_err << "ndb_mgm_get_version failed," << "error: " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << "desc: " << ndb_mgm_get_latest_error_desc(mgmd.handle()) << endl; return NDBT_FAILED; } g_info << "Using major: " << major << " minor: " << minor << " build: " << build << " string: " << verStr << endl; int l = 0; int loops = ctx->getNumLoops(); while(l < loops) { char verStr2[64]; int major2, minor2, build2; if (ndb_mgm_get_version(mgmd.handle(), &major2, &minor2, &build2, sizeof(verStr2), verStr2) != 1) { g_err << "ndb_mgm_get_version failed," << "error: " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << "desc: " << ndb_mgm_get_latest_error_desc(mgmd.handle()) << endl; return NDBT_FAILED; } if (major != major2) { g_err << "Got different major: " << major2 << " excpected: " << major << endl; return NDBT_FAILED; } if (minor != minor2) { g_err << "Got different minor: " << minor2 << " excpected: " << minor << endl; return NDBT_FAILED; } if (build != build2) { g_err << "Got different build: " << build2 << " excpected: " << build << endl; return NDBT_FAILED; } if (strcmp(verStr, verStr2) != 0) { g_err << "Got different verStr: " << verStr2 << " excpected: " << verStr << endl; return NDBT_FAILED; } l++; } return NDBT_OK; } static int runTestGetVersionUntilStopped(NDBT_Context* ctx, NDBT_Step* step) { int result= NDBT_OK; while(!ctx->isTestStopped() && (result= runTestGetVersion(ctx, step)) == NDBT_OK) ; return result; } int runTestDumpEvents(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; // Test with unsupported logevent_type { const Ndb_logevent_type unsupported = NDB_LE_NDBStopForced; g_info << "ndb_mgm_dump_events(" << unsupported << ")" << endl; const struct ndb_mgm_events* events = ndb_mgm_dump_events(mgmd.handle(), unsupported, 0, 0); if (events != NULL) { g_err << "ndb_mgm_dump_events returned events " << "for unsupported Ndb_logevent_type" << endl; return NDBT_FAILED; } if (ndb_mgm_get_latest_error(mgmd.handle()) != NDB_MGM_USAGE_ERROR || strcmp("ndb_logevent_type 59 not supported", ndb_mgm_get_latest_error_desc(mgmd.handle()))) { g_err << "Unexpected error for unsupported logevent type, " << ndb_mgm_get_latest_error(mgmd.handle()) << ", desc: " << ndb_mgm_get_latest_error_desc(mgmd.handle()) << endl; return NDBT_FAILED; } } // Test with nodes >= MAX_NDB_NODES for (int i = MAX_NDB_NODES; i < MAX_NDB_NODES + 3; i++) { g_info << "ndb_mgm_dump_events(NDB_LE_MemoryUsage, 1, " << i << ")" << endl; const struct ndb_mgm_events* events = ndb_mgm_dump_events(mgmd.handle(), NDB_LE_MemoryUsage, 1, &i); if (events != NULL) { g_err << "ndb_mgm_dump_events returned events " << "for too large nodeid" << endl; return NDBT_FAILED; } int invalid_nodeid; if (ndb_mgm_get_latest_error(mgmd.handle()) != NDB_MGM_USAGE_ERROR || sscanf(ndb_mgm_get_latest_error_desc(mgmd.handle()), "invalid nodes: '%d'", &invalid_nodeid) != 1 || invalid_nodeid != i) { g_err << "Unexpected error for too large nodeid, " << ndb_mgm_get_latest_error(mgmd.handle()) << ", desc: " << ndb_mgm_get_latest_error_desc(mgmd.handle()) << endl; return NDBT_FAILED; } } int l = 0; int loops = ctx->getNumLoops(); while (l<loops) { const Ndb_logevent_type supported[] = { NDB_LE_MemoryUsage, NDB_LE_BackupStatus, (Ndb_logevent_type)0 }; // Test with supported logevent_type for (int i = 0; supported[i]; i++) { g_info << "ndb_mgm_dump_events(" << supported[i] << ")" << endl; struct ndb_mgm_events* events = ndb_mgm_dump_events(mgmd.handle(), supported[i], 0, 0); if (events == NULL) { g_err << "ndb_mgm_dump_events failed, type: " << supported[i] << ", error: " << ndb_mgm_get_latest_error(mgmd.handle()) << ", msg: " << ndb_mgm_get_latest_error_msg(mgmd.handle()) << endl; return NDBT_FAILED; } if (events->no_of_events < 0) { g_err << "ndb_mgm_dump_events returned a negative number of events: " << events->no_of_events << endl; free(events); return NDBT_FAILED; } g_info << "Got " << events->no_of_events << " events" << endl; free(events); } l++; } return NDBT_OK; } int runTestStatusAfterStop(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; ndb_mgm_node_type node_types[2] = { NDB_MGM_NODE_TYPE_NDB, NDB_MGM_NODE_TYPE_UNKNOWN }; // Test: get status, stop node, get status again printf("Getting status\n"); ndb_mgm_cluster_state *cs = ndb_mgm_get_status2(mgmd.handle(), node_types); if (cs == NULL) { printf("%s (%d)\n", ndb_mgm_get_latest_error_msg(mgmd.handle()), ndb_mgm_get_latest_error(mgmd.handle())); return NDBT_FAILED; } int nodeId = 0; for(int i=0; i < cs->no_of_nodes; i++ ) { ndb_mgm_node_state *ns = cs->node_states + i; printf("Node ID: %d status:%d\n", ns->node_id, ns->node_status); if (nodeId == 0 && ns->node_type == NDB_MGM_NODE_TYPE_NDB) nodeId = ns->node_id; } free(cs); cs = NULL; printf("Stopping data node\n"); // We only stop 1 data node, in this case NodeId=2 int nodes[1] = { nodeId }; int stopped = ndb_mgm_restart2(mgmd.handle(), NDB_ARRAY_SIZE(nodes), nodes, 0, 0, 1); if (stopped < 0) { printf("ndb_mgm_stop failed, '%s' (%d)\n", ndb_mgm_get_latest_error_msg(mgmd.handle()), ndb_mgm_get_latest_error(mgmd.handle())); return NDBT_FAILED; } printf("Stopped %d data node(s)\n", stopped); printf("Getting status\n"); cs = ndb_mgm_get_status2(mgmd.handle(), node_types); if (cs == NULL) { printf("%s (%d)\n", ndb_mgm_get_latest_error_msg(mgmd.handle()), ndb_mgm_get_latest_error(mgmd.handle())); return NDBT_FAILED; } for(int i=0; i < cs->no_of_nodes; i++ ) { ndb_mgm_node_state *ns = cs->node_states + i; printf("Node ID: %d status:%d\n", ns->node_id, ns->node_status); } free(cs); NdbRestarter res; res.startAll(); res.waitClusterStarted(); return NDBT_OK; } int sort_ng(const void * _e0, const void * _e1) { const struct ndb_mgm_node_state * e0 = (const struct ndb_mgm_node_state*)_e0; const struct ndb_mgm_node_state * e1 = (const struct ndb_mgm_node_state*)_e1; if (e0->node_group != e1->node_group) return e0->node_group - e1->node_group; return e0->node_id - e1->node_id; } int runBug12928429(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) { return NDBT_FAILED; } ndb_mgm_node_type node_types[2] = { NDB_MGM_NODE_TYPE_NDB, NDB_MGM_NODE_TYPE_UNKNOWN }; ndb_mgm_cluster_state * cs = ndb_mgm_get_status2(mgmd.handle(), node_types); if (cs == NULL) { printf("%s (%d)\n", ndb_mgm_get_latest_error_msg(mgmd.handle()), ndb_mgm_get_latest_error(mgmd.handle())); return NDBT_FAILED; } /** * sort according to node-group */ qsort(cs->node_states, cs->no_of_nodes, sizeof(cs->node_states[0]), sort_ng); int ng = cs->node_states[0].node_group; int replicas = 1; for (int i = 1; i < cs->no_of_nodes; i++) { if (cs->node_states[i].node_status != NDB_MGM_NODE_STATUS_STARTED) { ndbout_c("node %u is not started!!!", cs->node_states[i].node_id); free(cs); return NDBT_OK; } if (cs->node_states[i].node_group == ng) { replicas++; } else { break; } } if (replicas == 1) { free(cs); return NDBT_OK; } int nodes[MAX_NODES]; int cnt = 0; for (int i = 0; i < cs->no_of_nodes; i += replicas) { printf("%u ", cs->node_states[i].node_id); nodes[cnt++] = cs->node_states[i].node_id; } printf("\n"); int initial = 0; int nostart = 1; int abort = 0; int force = 1; int disconnnect = 0; /** * restart half of the node...should be only restart half of the nodes */ int res = ndb_mgm_restart4(mgmd.handle(), cnt, nodes, initial, nostart, abort, force, &disconnnect); if (res == -1) { ndbout_c("%u res: %u ndb_mgm_get_latest_error: %u line: %u msg: %s", __LINE__, res, ndb_mgm_get_latest_error(mgmd.handle()), ndb_mgm_get_latest_error_line(mgmd.handle()), ndb_mgm_get_latest_error_msg(mgmd.handle())); return NDBT_FAILED; } { ndb_mgm_cluster_state * cs2 = ndb_mgm_get_status2(mgmd.handle(),node_types); if (cs2 == NULL) { printf("%s (%d)\n", ndb_mgm_get_latest_error_msg(mgmd.handle()), ndb_mgm_get_latest_error(mgmd.handle())); return NDBT_FAILED; } for (int i = 0; i < cs2->no_of_nodes; i++) { int node_id = cs2->node_states[i].node_id; int expect = NDB_MGM_NODE_STATUS_STARTED; for (int c = 0; c < cnt; c++) { if (node_id == nodes[c]) { expect = NDB_MGM_NODE_STATUS_NOT_STARTED; break; } } if (cs2->node_states[i].node_status != expect) { ndbout_c("%u node %u expect: %u found: %u", __LINE__, cs2->node_states[i].node_id, expect, cs2->node_states[i].node_status); return NDBT_FAILED; } } free(cs2); } NdbRestarter restarter; restarter.startAll(); restarter.waitClusterStarted(); /** * restart half of the node...and all nodes in one node group * should restart cluster */ cnt = 0; for (int i = 0; i < replicas; i++) { printf("%u ", cs->node_states[i].node_id); nodes[cnt++] = cs->node_states[i].node_id; } for (int i = replicas; i < cs->no_of_nodes; i += replicas) { printf("%u ", cs->node_states[i].node_id); nodes[cnt++] = cs->node_states[i].node_id; } printf("\n"); res = ndb_mgm_restart4(mgmd.handle(), cnt, nodes, initial, nostart, abort, force, &disconnnect); if (res == -1) { ndbout_c("%u res: %u ndb_mgm_get_latest_error: %u line: %u msg: %s", __LINE__, res, ndb_mgm_get_latest_error(mgmd.handle()), ndb_mgm_get_latest_error_line(mgmd.handle()), ndb_mgm_get_latest_error_msg(mgmd.handle())); return NDBT_FAILED; } { ndb_mgm_cluster_state * cs2 = ndb_mgm_get_status2(mgmd.handle(),node_types); if (cs2 == NULL) { printf("%s (%d)\n", ndb_mgm_get_latest_error_msg(mgmd.handle()), ndb_mgm_get_latest_error(mgmd.handle())); return NDBT_FAILED; } for (int i = 0; i < cs2->no_of_nodes; i++) { int expect = NDB_MGM_NODE_STATUS_NOT_STARTED; if (cs2->node_states[i].node_status != expect) { ndbout_c("%u node %u expect: %u found: %u", __LINE__, cs2->node_states[i].node_id, expect, cs2->node_states[i].node_status); return NDBT_FAILED; } } free(cs2); } restarter.startAll(); restarter.waitClusterStarted(); free(cs); return NDBT_OK; } int runTestNdbApiConfig(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; if (!mgmd.connect()) return NDBT_FAILED; struct test_parameter { Uint32 key; Uint32 NdbApiConfig::*ptr; Uint32 values[2]; } parameters[] = { { CFG_MAX_SCAN_BATCH_SIZE, &NdbApiConfig::m_scan_batch_size, { 10, 1000 } }, { CFG_BATCH_BYTE_SIZE, &NdbApiConfig::m_batch_byte_size, { 10, 1000 } }, { CFG_BATCH_SIZE, &NdbApiConfig::m_batch_size, { 10, 1000 } }, // Skip test of m_waitfor_timeout since it is not configurable in API-section { CFG_DEFAULT_OPERATION_REDO_PROBLEM_ACTION, &NdbApiConfig::m_default_queue_option, { OPERATION_REDO_PROBLEM_ACTION_ABORT, OPERATION_REDO_PROBLEM_ACTION_QUEUE } }, { CFG_DEFAULT_HASHMAP_SIZE, &NdbApiConfig::m_default_hashmap_size, { 240, 3840 } }, }; // Catch if new members are added to NdbApiConfig, // if so add tests and adjust expected size NDB_STATIC_ASSERT(sizeof(NdbApiConfig) == 6 * sizeof(Uint32)); Config savedconf; if (!mgmd.get_config(savedconf)) return NDBT_FAILED; for (size_t i = 0; i < NDB_ARRAY_SIZE(parameters[0].values) ; i ++) { /** * Setup configuration */ // Get the binary config Config conf; if (!mgmd.get_config(conf)) return NDBT_FAILED; ConfigValues::Iterator iter(conf.m_configValues->m_config); for (Uint32 nodeid = 1; nodeid < MAX_NODES; nodeid ++) { Uint32 type; if (!iter.openSection(CFG_SECTION_NODE, nodeid)) continue; if (iter.get(CFG_TYPE_OF_SECTION, &type) && type == NDB_MGM_NODE_TYPE_API) { for (size_t param = 0; param < NDB_ARRAY_SIZE(parameters) ; param ++) { iter.set(parameters[param].key, parameters[param].values[i]); } } iter.closeSection(); } // Set the modified config if (!mgmd.set_config(conf)) return NDBT_FAILED; /** * Connect api */ Ndb_cluster_connection con(mgmd.getConnectString()); const int retries = 12; const int retry_delay = 5; const int verbose = 1; if (con.connect(retries, retry_delay, verbose) != 0) { g_err << "Ndb_cluster_connection.connect failed" << endl; return NDBT_FAILED; } /** * Check api configuration */ NDBT_Context conctx(con); int failures = 0; for (size_t param = 0; param < NDB_ARRAY_SIZE(parameters) ; param ++) { Uint32 expected = parameters[param].values[i]; Uint32 got = conctx.getConfig().*parameters[param].ptr; if (got != expected) { int j; for(j = 0; j < ConfigInfo::m_NoOfParams ; j ++) { if (ConfigInfo::m_ParamInfo[j]._paramId == parameters[param].key) break; } g_err << "Parameter "; if (j < ConfigInfo::m_NoOfParams) g_err << ConfigInfo::m_ParamInfo[j]._fname << " (" << parameters[param].key << ")"; else g_err << "Unknown (" << parameters[param].key << ")"; g_err << ": Expected " << expected << " got " << got << endl; failures++; } if (failures > 0) return NDBT_FAILED; } } // Restore conf after upgrading config generation Config conf; if (!mgmd.get_config(conf)) return NDBT_FAILED; savedconf.setGeneration(conf.getGeneration()); if (!mgmd.set_config(savedconf)) { g_err << "Failed to restore config." << endl; return NDBT_FAILED; } return NDBT_OK; } static int runTestCreateLogEvent(NDBT_Context* ctx, NDBT_Step* step) { NdbMgmd mgmd; int loops = ctx->getNumLoops(); if (!mgmd.connect()) return NDBT_FAILED; int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 0 }; for(int l=0; l<loops; l++) { g_info << "Creating log event handle " << l << endl; NdbLogEventHandle le_handle = ndb_mgm_create_logevent_handle(mgmd.handle(), filter); if (!le_handle) return NDBT_FAILED; ndb_mgm_destroy_logevent_handle(&le_handle); } return NDBT_OK; } NDBT_TESTSUITE(testMgm); DRIVER(DummyDriver); /* turn off use of NdbApi */ TESTCASE("ApiSessionFailure", "Test failures in MGMAPI session"){ INITIALIZER(runTestApiSession); } TESTCASE("ApiConnectTimeout", "Connect timeout tests for MGMAPI"){ INITIALIZER(runTestApiConnectTimeout); } TESTCASE("ApiTimeoutBasic", "Basic timeout tests for MGMAPI"){ INITIALIZER(runTestApiTimeoutBasic); } TESTCASE("ApiGetStatusTimeout", "Test timeout for MGMAPI getStatus"){ INITIALIZER(runTestApiGetStatusTimeout); } TESTCASE("ApiGetConfigTimeout", "Test timeouts for mgmapi get_configuration"){ INITIALIZER(runTestMgmApiGetConfigTimeout); } TESTCASE("ApiMgmEventTimeout", "Test timeouts for mgmapi get_configuration"){ INITIALIZER(runTestMgmApiEventTimeout); } TESTCASE("ApiMgmStructEventTimeout", "Test timeouts for mgmapi get_configuration"){ INITIALIZER(runTestMgmApiStructEventTimeout); } TESTCASE("SetConfig", "Tests the ndb_mgm_set_configuration function"){ INITIALIZER(runSetConfig); } TESTCASE("CheckConfig", "Connect to each ndb_mgmd and check they have the same configuration"){ INITIALIZER(runCheckConfig); } TESTCASE("TestReloadConfig", "Test of 'reload config'"){ INITIALIZER(runTestReloadConfig); } TESTCASE("TestSetConfig", "Test of 'set config'"){ INITIALIZER(runTestSetConfig); } TESTCASE("TestSetConfigParallel", "Test of 'set config' from 5 threads"){ STEPS(runTestSetConfigParallel, 5); } TESTCASE("GetConfig", "Run ndb_mgm_get_configuration in parallel"){ STEPS(runGetConfig, 64); } TESTCASE("TestStatus", "Test status and status2"){ INITIALIZER(runTestStatus); } TESTCASE("TestStatusMultiple", "Test status and status2 with 64 threads"){ /** * For this and other tests we are limited in how much TCP backlog * the MGM server socket has. It is currently set to a maximum of * 64, so if we need to test more than 64 threads in parallel we * need to introduce some sort of wait state to ensure that we * don't get all threads sending TCP connect at the same time. */ STEPS(runTestStatus, 64); } TESTCASE("TestGetNodeId", "Test 'get nodeid'"){ INITIALIZER(runTestGetNodeId); } TESTCASE("TestGetVersion", "Test 'get version' and 'ndb_mgm_get_version'"){ STEPS(runTestGetVersion, 20); } TESTCASE("TestTransporterConnect", "Test 'transporter connect'"){ INITIALIZER(runTestTransporterConnect); } TESTCASE("TestConnectionParameter", "Test 'get/set connection parameter'"){ INITIALIZER(runTestConnectionParameter); } TESTCASE("TestSetLogFilter", "Test 'set logfilter' and 'get info clusterlog'"){ INITIALIZER(runTestSetLogFilter); } #ifdef NOT_YET TESTCASE("TestRestartMgmd", "Test restart of ndb_mgmd(s)"){ INITIALIZER(runTestRestartMgmd); } #endif TESTCASE("Bug40922", "Make sure that ndb_logevent_get_next returns when " "called with a timeout"){ INITIALIZER(runTestBug40922); } TESTCASE("Bug16723708", "Check that ndb_logevent_get_next returns events " "which have valid category values"){ INITIALIZER(runTestBug16723708); } TESTCASE("Stress", "Run everything while changing config"){ STEP(runTestGetNodeIdUntilStopped); STEP(runSetConfigUntilStopped); STEPS(runGetConfigUntilStopped, 10); STEPS(runGetConfigFromNodeUntilStopped, 10); STEPS(runTestStatusUntilStopped, 10); STEPS(runTestGetVersionUntilStopped, 5); STEP(runSleepAndStop); } TESTCASE("Stress2", "Run everything while changing config in parallel"){ STEP(runTestGetNodeIdUntilStopped); STEPS(runTestSetConfigParallelUntilStopped, 5); STEPS(runGetConfigUntilStopped, 10); STEPS(runGetConfigFromNodeUntilStopped, 10); STEPS(runTestStatusUntilStopped, 10); STEPS(runTestGetVersionUntilStopped, 5); STEP(runSleepAndStop); } X_TESTCASE("Bug45497", "Connect to ndb_mgmd until it can't handle more connections"){ STEP(runTestBug45497); } TESTCASE("TestGetVersion", "Test 'get version' and 'ndb_mgm_get_version'"){ STEPS(runTestGetVersion, 20); } TESTCASE("TestDumpEvents", "Test 'dump events'"){ STEPS(runTestDumpEvents, 1); } TESTCASE("TestStatusAfterStop", "Test get status after stop "){ STEPS(runTestStatusAfterStop, 1); } TESTCASE("Bug12928429", "") { STEP(runBug12928429); } TESTCASE("TestNdbApiConfig", "") { STEP(runTestNdbApiConfig); } TESTCASE("TestSetPorts", "Test 'set ports'"){ INITIALIZER(runTestSetPorts); } TESTCASE("TestCreateLogEvent", "Test ndb_mgm_create_log_event_handle"){ STEPS(runTestCreateLogEvent, 5); } NDBT_TESTSUITE_END(testMgm); int main(int argc, const char** argv){ ndb_init(); NDBT_TESTSUITE_INSTANCE(testMgm); testMgm.setCreateTable(false); testMgm.setRunAllTables(true); return testMgm.execute(argc, argv); } template class Vector<NdbMgmd*>;
24.817207
104
0.625094
[ "vector" ]
a9b108bb9116aca7f49b44e28b2b08c8ee5412b0
7,388
cpp
C++
build/moc_coincontroldialog.cpp
zebbra2014/superpay
eb77638bacd8d64a593e0715a15d98b612c6caff
[ "MIT" ]
null
null
null
build/moc_coincontroldialog.cpp
zebbra2014/superpay
eb77638bacd8d64a593e0715a15d98b612c6caff
[ "MIT" ]
null
null
null
build/moc_coincontroldialog.cpp
zebbra2014/superpay
eb77638bacd8d64a593e0715a15d98b612c6caff
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'coincontroldialog.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.2.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../src/qt/coincontroldialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'coincontroldialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.2.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_CoinControlDialog_t { QByteArrayData data[23]; char stringdata[354]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ offsetof(qt_meta_stringdata_CoinControlDialog_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData) \ ) static const qt_meta_stringdata_CoinControlDialog_t qt_meta_stringdata_CoinControlDialog = { { QT_MOC_LITERAL(0, 0, 17), QT_MOC_LITERAL(1, 18, 11), QT_MOC_LITERAL(2, 30, 0), QT_MOC_LITERAL(3, 31, 8), QT_MOC_LITERAL(4, 40, 10), QT_MOC_LITERAL(5, 51, 9), QT_MOC_LITERAL(6, 61, 11), QT_MOC_LITERAL(7, 73, 19), QT_MOC_LITERAL(8, 93, 17), QT_MOC_LITERAL(9, 111, 15), QT_MOC_LITERAL(10, 127, 12), QT_MOC_LITERAL(11, 140, 17), QT_MOC_LITERAL(12, 158, 14), QT_MOC_LITERAL(13, 173, 17), QT_MOC_LITERAL(14, 191, 18), QT_MOC_LITERAL(15, 210, 15), QT_MOC_LITERAL(16, 226, 13), QT_MOC_LITERAL(17, 240, 13), QT_MOC_LITERAL(18, 254, 15), QT_MOC_LITERAL(19, 270, 16), QT_MOC_LITERAL(20, 287, 20), QT_MOC_LITERAL(21, 308, 21), QT_MOC_LITERAL(22, 330, 22) }, "CoinControlDialog\0beforeClose\0\0showMenu\0" "copyAmount\0copyLabel\0copyAddress\0" "copyTransactionHash\0clipboardQuantity\0" "clipboardAmount\0clipboardFee\0" "clipboardAfterFee\0clipboardBytes\0" "clipboardPriority\0clipboardLowOutput\0" "clipboardChange\0radioTreeMode\0" "radioListMode\0viewItemChanged\0" "QTreeWidgetItem*\0headerSectionClicked\0" "on_buttonBox_accepted\0buttonSelectAllClicked\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_CoinControlDialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 20, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 114, 2, 0x06, // slots: name, argc, parameters, tag, flags 3, 1, 115, 2, 0x08, 4, 0, 118, 2, 0x08, 5, 0, 119, 2, 0x08, 6, 0, 120, 2, 0x08, 7, 0, 121, 2, 0x08, 8, 0, 122, 2, 0x08, 9, 0, 123, 2, 0x08, 10, 0, 124, 2, 0x08, 11, 0, 125, 2, 0x08, 12, 0, 126, 2, 0x08, 13, 0, 127, 2, 0x08, 14, 0, 128, 2, 0x08, 15, 0, 129, 2, 0x08, 16, 1, 130, 2, 0x08, 17, 1, 133, 2, 0x08, 18, 2, 136, 2, 0x08, 20, 1, 141, 2, 0x08, 21, 0, 144, 2, 0x08, 22, 0, 145, 2, 0x08, // signals: parameters QMetaType::Void, // slots: parameters QMetaType::Void, QMetaType::QPoint, 2, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 2, QMetaType::Void, QMetaType::Bool, 2, QMetaType::Void, 0x80000000 | 19, QMetaType::Int, 2, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Void, 0 // eod }; void CoinControlDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { CoinControlDialog *_t = static_cast<CoinControlDialog *>(_o); switch (_id) { case 0: _t->beforeClose(); break; case 1: _t->showMenu((*reinterpret_cast< const QPoint(*)>(_a[1]))); break; case 2: _t->copyAmount(); break; case 3: _t->copyLabel(); break; case 4: _t->copyAddress(); break; case 5: _t->copyTransactionHash(); break; case 6: _t->clipboardQuantity(); break; case 7: _t->clipboardAmount(); break; case 8: _t->clipboardFee(); break; case 9: _t->clipboardAfterFee(); break; case 10: _t->clipboardBytes(); break; case 11: _t->clipboardPriority(); break; case 12: _t->clipboardLowOutput(); break; case 13: _t->clipboardChange(); break; case 14: _t->radioTreeMode((*reinterpret_cast< bool(*)>(_a[1]))); break; case 15: _t->radioListMode((*reinterpret_cast< bool(*)>(_a[1]))); break; case 16: _t->viewItemChanged((*reinterpret_cast< QTreeWidgetItem*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 17: _t->headerSectionClicked((*reinterpret_cast< int(*)>(_a[1]))); break; case 18: _t->on_buttonBox_accepted(); break; case 19: _t->buttonSelectAllClicked(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (CoinControlDialog::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CoinControlDialog::beforeClose)) { *result = 0; } } } } const QMetaObject CoinControlDialog::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_CoinControlDialog.data, qt_meta_data_CoinControlDialog, qt_static_metacall, 0, 0} }; const QMetaObject *CoinControlDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *CoinControlDialog::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CoinControlDialog.stringdata)) return static_cast<void*>(const_cast< CoinControlDialog*>(this)); return QWidget::qt_metacast(_clname); } int CoinControlDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 20) qt_static_metacall(this, _c, _id, _a); _id -= 20; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 20) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 20; } return _id; } // SIGNAL 0 void CoinControlDialog::beforeClose() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } QT_END_MOC_NAMESPACE
34.523364
131
0.592583
[ "object" ]
a9b2a1e0cadb8aa2832ef595f56e29d6e462e775
35,961
cc
C++
core/src/Utilities.cc
matthieuvigne/jiminy
f893b2254a9e695a4154b941b599536756ea3d8b
[ "MIT" ]
null
null
null
core/src/Utilities.cc
matthieuvigne/jiminy
f893b2254a9e695a4154b941b599536756ea3d8b
[ "MIT" ]
null
null
null
core/src/Utilities.cc
matthieuvigne/jiminy
f893b2254a9e695a4154b941b599536756ea3d8b
[ "MIT" ]
null
null
null
#include <math.h> #include <climits> #include <stdlib.h> /* srand, rand */ #ifndef _WIN32 #include <pwd.h> #include <unistd.h> #include <getopt.h> #else #include <stdlib.h> #include <stdio.h> #endif #include <Eigen/Dense> #include <Eigen/Geometry> #include "pinocchio/algorithm/joint-configuration.hpp" #include "jiminy/core/Utilities.h" #include "jiminy/core/Engine.h" // MIN_SIMULATION_TIMESTEP and MAX_SIMULATION_TIMESTEP namespace jiminy { extern float64_t const MIN_SIMULATION_TIMESTEP; extern float64_t const MAX_SIMULATION_TIMESTEP; // *************** Local Mutex/Lock mechanism ****************** MutexLocal::MutexLocal(void) : isLocked_(new bool_t{false}) { // Empty } MutexLocal::~MutexLocal(void) { *isLocked_ = false; } bool_t const & MutexLocal::isLocked(void) const { return *isLocked_; } MutexLocal::LockGuardLocal::LockGuardLocal(MutexLocal & mutexLocal) : mutexFlag_(mutexLocal.isLocked_) { *mutexFlag_ = true; } MutexLocal::LockGuardLocal::~LockGuardLocal(void) { *mutexFlag_ = false; } // ************************* Timer ************************** Timer::Timer(void) : t0(), tf(), dt(0) { tic(); } void Timer::tic(void) { t0 = Time::now(); } void Timer::toc(void) { tf = Time::now(); std::chrono::duration<float64_t> timeDiff = tf - t0; dt = timeDiff.count(); } // ************ IO file and Directory utilities ************** #ifndef _WIN32 std::string getUserDirectory(void) { struct passwd *pw = getpwuid(getuid()); return pw->pw_dir; } #else std::string getUserDirectory(void) { return {getenv("USERPROFILE")}; } #endif // ***************** Random number generator ***************** // Based on Ziggurat generator by Marsaglia and Tsang (JSS, 2000) std::mt19937 generator_; std::uniform_real_distribution<float32_t> distUniform_(0.0,1.0); uint32_t kn[128]; float32_t fn[128]; float32_t wn[128]; void r4_nor_setup(void) { float64_t const m1 = 2147483648.0; float64_t const vn = 9.91256303526217E-03; float64_t dn = 3.442619855899; float64_t tn = 3.442619855899; float64_t q = vn / exp (-0.5 * dn * dn); kn[0] = (uint32_t) ((dn / q) * m1); kn[1] = 0; wn[0] = static_cast<float32_t>(q / m1); wn[127] = static_cast<float32_t>(dn / m1); fn[0] = 1.0f; fn[127] = static_cast<float32_t>(exp(-0.5 * dn * dn)); for (uint8_t i=126; 1 <= i; i--) { dn = sqrt (-2.0 * log(vn / dn + exp(-0.5 * dn * dn))); kn[i+1] = static_cast<uint32_t>((dn / tn) * m1); tn = dn; fn[i] = static_cast<float32_t>(exp(-0.5 * dn * dn)); wn[i] = static_cast<float32_t>(dn / m1); } } float32_t r4_uni(void) { return distUniform_(generator_); } float32_t r4_nor(void) { float32_t const r = 3.442620f; int32_t hz; uint32_t iz; float32_t x; float32_t y; hz = static_cast<int32_t>(generator_()); iz = (hz & 127U); if (fabs(hz) < kn[iz]) { return static_cast<float32_t>(hz) * wn[iz]; } else { while(true) { if (iz == 0) { while(true) { x = - 0.2904764f * log(r4_uni()); y = - log(r4_uni()); if (x * x <= y + y) { break; } } if (hz <= 0) { return - r - x; } else { return + r + x; } } x = static_cast<float32_t>(hz) * wn[iz]; if (fn[iz] + r4_uni() * (fn[iz-1] - fn[iz]) < exp (-0.5f * x * x)) { return x; } hz = static_cast<int32_t>(generator_()); iz = (hz & 127); if (fabs(hz) < kn[iz]) { return static_cast<float32_t>(hz) * wn[iz]; } } } } // ************** Random number generator utilities **************** void resetRandGenerators(uint32_t seed) { srand(seed); // Eigen relies on srand for genering random matrix generator_.seed(seed); r4_nor_setup(); } float64_t randUniform(float64_t const & lo, float64_t const & hi) { return lo + r4_uni() * (hi - lo); } float64_t randNormal(float64_t const & mean, float64_t const & std) { return mean + r4_nor() * std; } vectorN_t randVectorNormal(uint32_t const & size, float64_t const & mean, float64_t const & std) { if (std > 0.0) { return vectorN_t::NullaryExpr(size, [&mean, &std] (vectorN_t::Index const &) -> float64_t { return randNormal(mean, std); }); } else { return vectorN_t::Constant(size, mean); } } vectorN_t randVectorNormal(uint32_t const & size, float64_t const & std) { return randVectorNormal(size, 0, std); } vectorN_t randVectorNormal(vectorN_t const & mean, vectorN_t const & std) { return vectorN_t::NullaryExpr(std.size(), [&mean, &std] (vectorN_t::Index const & i) -> float64_t { return randNormal(mean[i], std[i]); }); } vectorN_t randVectorNormal(vectorN_t const & std) { return vectorN_t::NullaryExpr(std.size(), [&std] (vectorN_t::Index const & i) -> float64_t { return randNormal(0, std[i]); }); } // ******************* Telemetry utilities ********************** std::vector<std::string> defaultVectorFieldnames(std::string const & baseName, uint32_t const & size) { std::vector<std::string> fieldnames; fieldnames.reserve(size); for (uint32_t i=0; i<size; i++) { fieldnames.emplace_back(baseName + std::to_string(i)); // TODO: MR going to support "." delimiter } return fieldnames; } std::string removeFieldnameSuffix(std::string fieldname, std::string const & suffix) { if (fieldname.size() > suffix.size()) { if (!fieldname.compare(fieldname.size() - suffix.size(), suffix.size(), suffix)) { fieldname.erase(fieldname.size() - suffix.size(), fieldname.size()); } } return fieldname; } std::vector<std::string> removeFieldnamesSuffix(std::vector<std::string> fieldnames, std::string const & suffix) { std::transform(fieldnames.begin(), fieldnames.end(), fieldnames.begin(), [&suffix](std::string const & name) -> std::string { return removeFieldnameSuffix(name, suffix); }); return fieldnames; } // ********************** Pinocchio utilities ********************** void computePositionDerivative(pinocchio::Model const & model, Eigen::Ref<vectorN_t const> q, Eigen::Ref<vectorN_t const> v, Eigen::Ref<vectorN_t> qDot, float64_t dt) { /* Hack to compute the configuration vector derivative, including the quaternions on SO3 automatically. Note that the time difference must not be too small to avoid failure. */ dt = std::max(MIN_SIMULATION_TIMESTEP, dt); vectorN_t qNext(q.size()); pinocchio::integrate(model, q, v*dt, qNext); qDot = (qNext - q) / dt; } result_t getJointNameFromPositionId(pinocchio::Model const & model, int32_t const & idIn, std::string & jointNameOut) { // Iterate over all joints. for (int32_t i = 0; i < model.njoints; i++) { // Get joint starting and ending index in position vector. int32_t startIndex = model.joints[i].idx_q(); int32_t endIndex = startIndex + model.joints[i].nq(); // If inIn is between start and end, we found the joint we were looking for. if(startIndex <= idIn && endIndex > idIn) { jointNameOut = model.names[i]; return result_t::SUCCESS; } } std::cout << "Error - Utilities::getJointNameFromVelocityId - Position index out of range." << std::endl; return result_t::ERROR_BAD_INPUT; } result_t getJointNameFromVelocityId(pinocchio::Model const & model, int32_t const & idIn, std::string & jointNameOut) { // Iterate over all joints. for(int32_t i = 0; i < model.njoints; i++) { // Get joint starting and ending index in velocity vector. int32_t startIndex = model.joints[i].idx_v(); int32_t endIndex = startIndex + model.joints[i].nv(); // If inIn is between start and end, we found the joint we were looking for. if(startIndex <= idIn && endIndex > idIn) { jointNameOut = model.names[i]; return result_t::SUCCESS; } } std::cout << "Error - Utilities::getJointNameFromVelocityId - Velocity index out of range." << std::endl; return result_t::ERROR_BAD_INPUT; } result_t getJointTypeFromId(pinocchio::Model const & model, int32_t const & idIn, joint_t & jointTypeOut) { if(model.njoints < idIn - 1) { std::cout << "Error - Utilities::getJointTypeFromId - Joint id out of range." << std::endl; return result_t::ERROR_GENERIC; } auto const & joint = model.joints[idIn]; if (joint.shortname() == "JointModelFreeFlyer") { jointTypeOut = joint_t::FREE; } else if (joint.shortname() == "JointModelSpherical") { jointTypeOut = joint_t::SPHERICAL; } else if (joint.shortname() == "JointModelPlanar") { jointTypeOut = joint_t::PLANAR; } else if (joint.shortname() == "JointModelPX" || joint.shortname() == "JointModelPY" || joint.shortname() == "JointModelPZ") { jointTypeOut = joint_t::LINEAR; } else if (joint.shortname() == "JointModelRX" || joint.shortname() == "JointModelRY" || joint.shortname() == "JointModelRZ") { jointTypeOut = joint_t::ROTARY; } else { // Unknown joint, throw an error to avoid any wrong manipulation. jointTypeOut = joint_t::NONE; std::cout << "Error - Utilities::getJointTypeFromId - Unknown joint type." << std::endl; return result_t::ERROR_GENERIC; } return result_t::SUCCESS; } result_t getJointTypePositionSuffixes(joint_t const & jointTypeIn, std::vector<std::string> & jointTypeSuffixesOut) { jointTypeSuffixesOut = std::vector<std::string>({std::string("")}); // If no extra discrimination is needed switch (jointTypeIn) { case joint_t::LINEAR: break; case joint_t::ROTARY: break; case joint_t::PLANAR: jointTypeSuffixesOut = std::vector<std::string>({std::string("TransX"), std::string("TransY"), std::string("TransZ")}); break; case joint_t::SPHERICAL: jointTypeSuffixesOut = std::vector<std::string>({std::string("QuatX"), std::string("QuatY"), std::string("QuatZ"), std::string("QuatW")}); break; case joint_t::FREE: jointTypeSuffixesOut = std::vector<std::string>({std::string("TransX"), std::string("TransY"), std::string("TransZ"), std::string("QuatX"), std::string("QuatY"), std::string("QuatZ"), std::string("QuatW")}); break; case joint_t::NONE: default: std::cout << "Error - Utilities::getJointFieldnamesFromType - Joints of type 'NONE' do not have fieldnames." << std::endl; return result_t::ERROR_GENERIC; } return result_t::SUCCESS; } result_t getJointTypeVelocitySuffixes(joint_t const & jointTypeIn, std::vector<std::string> & jointTypeSuffixesOut) { jointTypeSuffixesOut = std::vector<std::string>({std::string("")}); // If no extra discrimination is needed switch (jointTypeIn) { case joint_t::LINEAR: break; case joint_t::ROTARY: break; case joint_t::PLANAR: jointTypeSuffixesOut = std::vector<std::string>({std::string("LinX"), std::string("LinY"), std::string("LinZ")}); break; case joint_t::SPHERICAL: jointTypeSuffixesOut = std::vector<std::string>({std::string("AngX"), std::string("AngY"), std::string("AngZ")}); break; case joint_t::FREE: jointTypeSuffixesOut = std::vector<std::string>({std::string("LinX"), std::string("LinY"), std::string("LinZ"), std::string("AngX"), std::string("AngY"), std::string("AngZ")}); break; case joint_t::NONE: default: std::cout << "Error - Utilities::getJointFieldnamesFromType - Joints of type 'NONE' do not have fieldnames." << std::endl; return result_t::ERROR_GENERIC; } return result_t::SUCCESS; } result_t getFrameIdx(pinocchio::Model const & model, std::string const & frameName, int32_t & frameIdx) { if (!model.existFrame(frameName)) { std::cout << "Error - Utilities::getFrameIdx - Frame not found in urdf." << std::endl; return result_t::ERROR_BAD_INPUT; } frameIdx = model.getFrameId(frameName); return result_t::SUCCESS; } result_t getFramesIdx(pinocchio::Model const & model, std::vector<std::string> const & framesNames, std::vector<int32_t> & framesIdx) { result_t returnCode = result_t::SUCCESS; framesIdx.resize(0); for (std::string const & name : framesNames) { if (returnCode == result_t::SUCCESS) { int32_t idx; returnCode = getFrameIdx(model, name, idx); framesIdx.push_back(std::move(idx)); } } return returnCode; } result_t getJointPositionIdx(pinocchio::Model const & model, std::string const & jointName, std::vector<int32_t> & jointPositionIdx) { // It returns all the indices if the joint has multiple degrees of freedom if (!model.existJointName(jointName)) { std::cout << "Error - Utilities::getJointPositionIdx - Joint not found in urdf." << std::endl; return result_t::ERROR_BAD_INPUT; } int32_t const & jointModelIdx = model.getJointId(jointName); int32_t const & jointPositionFirstIdx = model.joints[jointModelIdx].idx_q(); int32_t const & jointNq = model.joints[jointModelIdx].nq(); jointPositionIdx.resize(jointNq); std::iota(jointPositionIdx.begin(), jointPositionIdx.end(), jointPositionFirstIdx); return result_t::SUCCESS; } result_t getJointPositionIdx(pinocchio::Model const & model, std::string const & jointName, int32_t & jointPositionFirstIdx) { // It returns the first index even if the joint has multiple degrees of freedom if (!model.existJointName(jointName)) { std::cout << "Error - Utilities::getJointPositionIdx - Joint not found in urdf." << std::endl; return result_t::ERROR_BAD_INPUT; } int32_t const & jointModelIdx = model.getJointId(jointName); jointPositionFirstIdx = model.joints[jointModelIdx].idx_q(); return result_t::SUCCESS; } result_t getJointsPositionIdx(pinocchio::Model const & model, std::vector<std::string> const & jointsNames, std::vector<int32_t> & jointsPositionIdx, bool_t const & firstJointIdxOnly) { result_t returnCode = result_t::SUCCESS; jointsPositionIdx.clear(); if (!firstJointIdxOnly) { std::vector<int32_t> jointPositionIdx; for (std::string const & jointName : jointsNames) { if (returnCode == result_t::SUCCESS) { returnCode = getJointPositionIdx(model, jointName, jointPositionIdx); } if (returnCode == result_t::SUCCESS) { jointsPositionIdx.insert(jointsPositionIdx.end(), jointPositionIdx.begin(), jointPositionIdx.end()); } } } else { int32_t jointPositionIdx; for (std::string const & jointName : jointsNames) { if (returnCode == result_t::SUCCESS) { returnCode = getJointPositionIdx(model, jointName, jointPositionIdx); } if (returnCode == result_t::SUCCESS) { jointsPositionIdx.push_back(jointPositionIdx); } } } return returnCode; } result_t getJointModelIdx(pinocchio::Model const & model, std::string const & jointName, int32_t & jointModelIdx) { // It returns the first index even if the joint has multiple degrees of freedom if (!model.existJointName(jointName)) { std::cout << "Error - Utilities::getJointPositionIdx - Joint not found in urdf." << std::endl; return result_t::ERROR_BAD_INPUT; } jointModelIdx = model.getJointId(jointName); return result_t::SUCCESS; } result_t getJointsModelIdx(pinocchio::Model const & model, std::vector<std::string> const & jointsNames, std::vector<int32_t> & jointsModelIdx) { result_t returnCode = result_t::SUCCESS; jointsModelIdx.clear(); int32_t jointModelIdx; for (std::string const & jointName : jointsNames) { if (returnCode == result_t::SUCCESS) { returnCode = getJointModelIdx(model, jointName, jointModelIdx); } if (returnCode == result_t::SUCCESS) { jointsModelIdx.push_back(jointModelIdx); } } return returnCode; } result_t getJointVelocityIdx(pinocchio::Model const & model, std::string const & jointName, std::vector<int32_t> & jointVelocityIdx) { // It returns all the indices if the joint has multiple degrees of freedom if (!model.existJointName(jointName)) { std::cout << "Error - getJointVelocityIdx - Frame not found in urdf." << std::endl; return result_t::ERROR_BAD_INPUT; } int32_t const & jointModelIdx = model.getJointId(jointName); int32_t const & jointVelocityFirstIdx = model.joints[jointModelIdx].idx_v(); int32_t const & jointNv = model.joints[jointModelIdx].nv(); jointVelocityIdx.resize(jointNv); std::iota(jointVelocityIdx.begin(), jointVelocityIdx.end(), jointVelocityFirstIdx); return result_t::SUCCESS; } result_t getJointVelocityIdx(pinocchio::Model const & model, std::string const & jointName, int32_t & jointVelocityFirstIdx) { // It returns the first index even if the joint has multiple degrees of freedom if (!model.existJointName(jointName)) { std::cout << "Error - getJointVelocityIdx - Frame not found in urdf." << std::endl; return result_t::ERROR_BAD_INPUT; } int32_t const & jointModelIdx = model.getJointId(jointName); jointVelocityFirstIdx = model.joints[jointModelIdx].idx_v(); return result_t::SUCCESS; } result_t getJointsVelocityIdx(pinocchio::Model const & model, std::vector<std::string> const & jointsNames, std::vector<int32_t> & jointsVelocityIdx, bool_t const & firstJointIdxOnly) { result_t returnCode = result_t::SUCCESS; jointsVelocityIdx.clear(); if (!firstJointIdxOnly) { std::vector<int32_t> jointVelocityIdx; for (std::string const & jointName : jointsNames) { if (returnCode == result_t::SUCCESS) { returnCode = getJointVelocityIdx(model, jointName, jointVelocityIdx); } if (returnCode == result_t::SUCCESS) { jointsVelocityIdx.insert(jointsVelocityIdx.end(), jointVelocityIdx.begin(), jointVelocityIdx.end()); } } } else { int32_t jointVelocityIdx; for (std::string const & jointName : jointsNames) { if (returnCode == result_t::SUCCESS) { returnCode = getJointVelocityIdx(model, jointName, jointVelocityIdx); } if (returnCode == result_t::SUCCESS) { jointsVelocityIdx.push_back(jointVelocityIdx); } } } return returnCode; } void switchJoints(pinocchio::Model & modelInOut, uint32_t const & firstJointId, uint32_t const & secondJointId) { // Only perform swap if firstJointId is less that secondJointId if (firstJointId < secondJointId) { // Update parents for other joints. for(uint32_t i = 0; i < modelInOut.parents.size(); i++) { if(firstJointId == modelInOut.parents[i]) { modelInOut.parents[i] = secondJointId; } else if(secondJointId == modelInOut.parents[i]) { modelInOut.parents[i] = firstJointId; } } // Update frame parents. for(uint32_t i = 0; i < modelInOut.frames.size(); i++) { if(firstJointId == modelInOut.frames[i].parent) { modelInOut.frames[i].parent = secondJointId; } else if(secondJointId == modelInOut.frames[i].parent) { modelInOut.frames[i].parent = firstJointId; } } // Update values in subtrees. for(uint32_t i = 0; i < modelInOut.subtrees.size(); i++) { for(uint32_t j = 0; j < modelInOut.subtrees[i].size(); j++) { if(firstJointId == modelInOut.subtrees[i][j]) { modelInOut.subtrees[i][j] = secondJointId; } else if(secondJointId == modelInOut.subtrees[i][j]) { modelInOut.subtrees[i][j] = firstJointId; } } } // Update vectors based on joint index: effortLimit, velocityLimit, // lowerPositionLimit and upperPositionLimit. swapVectorBlocks(modelInOut.effortLimit, modelInOut.joints[firstJointId].idx_v(), modelInOut.joints[firstJointId].nv(), modelInOut.joints[secondJointId].idx_v(), modelInOut.joints[secondJointId].nv()); swapVectorBlocks(modelInOut.velocityLimit, modelInOut.joints[firstJointId].idx_v(), modelInOut.joints[firstJointId].nv(), modelInOut.joints[secondJointId].idx_v(), modelInOut.joints[secondJointId].nv()); swapVectorBlocks(modelInOut.lowerPositionLimit, modelInOut.joints[firstJointId].idx_q(), modelInOut.joints[firstJointId].nq(), modelInOut.joints[secondJointId].idx_q(), modelInOut.joints[secondJointId].nq()); swapVectorBlocks(modelInOut.upperPositionLimit, modelInOut.joints[firstJointId].idx_q(), modelInOut.joints[firstJointId].nq(), modelInOut.joints[secondJointId].idx_q(), modelInOut.joints[secondJointId].nq()); // Switch elements in joint-indexed vectors: // parents, names, subtrees, joints, jointPlacements, inertias. uint32_t tempParent = modelInOut.parents[firstJointId]; modelInOut.parents[firstJointId] = modelInOut.parents[secondJointId]; modelInOut.parents[secondJointId] = tempParent; std::string tempName = modelInOut.names[firstJointId]; modelInOut.names[firstJointId] = modelInOut.names[secondJointId]; modelInOut.names[secondJointId] = tempName; std::vector<pinocchio::Index> tempSubtree = modelInOut.subtrees[firstJointId]; modelInOut.subtrees[firstJointId] = modelInOut.subtrees[secondJointId]; modelInOut.subtrees[secondJointId] = tempSubtree; pinocchio::JointModel jointTemp = modelInOut.joints[firstJointId]; modelInOut.joints[firstJointId] = modelInOut.joints[secondJointId]; modelInOut.joints[secondJointId] = jointTemp; pinocchio::SE3 tempPlacement = modelInOut.jointPlacements[firstJointId]; modelInOut.jointPlacements[firstJointId] = modelInOut.jointPlacements[secondJointId]; modelInOut.jointPlacements[secondJointId] = tempPlacement; pinocchio::Inertia tempInertia = modelInOut.inertias[firstJointId]; modelInOut.inertias[firstJointId] = modelInOut.inertias[secondJointId]; modelInOut.inertias[secondJointId] = tempInertia; /* Recompute all position and velocity indexes, as we may have switched joints that didn't have the same size. Skip 'universe' joint since it is not an actual joint. */ uint32_t incrementalNq = 0; uint32_t incrementalNv = 0; for(uint32_t i = 1; i < modelInOut.joints.size(); i++) { modelInOut.joints[i].setIndexes(i, incrementalNq, incrementalNv); incrementalNq += modelInOut.joints[i].nq(); incrementalNv += modelInOut.joints[i].nv(); } } } result_t insertFlexibilityInModel(pinocchio::Model & modelInOut, std::string const & childJointNameIn, std::string const & newJointNameIn) { if(!modelInOut.existJointName(childJointNameIn)) { std::cout << "Error - insertFlexibilityInModel - Child joint does not exist." << std::endl; return result_t::ERROR_GENERIC; } int32_t childId = modelInOut.getJointId(childJointNameIn); // Flexible joint is placed at the same position as the child joint, in its parent frame. pinocchio::SE3 jointPosition = modelInOut.jointPlacements[childId]; // Create joint. int32_t newId = modelInOut.addJoint(modelInOut.parents[childId], pinocchio::JointModelSpherical(), jointPosition, newJointNameIn); // Set child joint to be a child of the new joint, at the origin. modelInOut.parents[childId] = newId; modelInOut.jointPlacements[childId] = pinocchio::SE3::Identity(); // Add new joint to frame list. int32_t childFrameId = modelInOut.getFrameId(childJointNameIn); int32_t newFrameId = modelInOut.addJointFrame(newId, modelInOut.frames[childFrameId].previousFrame); // Update child joint previousFrame id. modelInOut.frames[childFrameId].previousFrame = newFrameId; // Update new joint subtree to include all the joints below it. for(uint32_t i = 0; i < modelInOut.subtrees[childId].size(); i++) { modelInOut.subtrees[newId].push_back(modelInOut.subtrees[childId][i]); } /* Add weightless body. In practice having a zero inertia makes some of pinocchio algorithm crash, so we set a very small value instead: 1g. */ std::string bodyName = newJointNameIn + "Body"; pinocchio::Inertia inertia = pinocchio::Inertia::Identity(); inertia.mass() *= 1.0e-3; inertia.FromEllipsoid(inertia.mass(), 1.0, 1.0, 1.0); modelInOut.appendBodyToJoint(newId, inertia, pinocchio::SE3::Identity()); /* Pinocchio requires that joints are in increasing order as we move to the leaves of the kinematic tree. Here this is no longer the case, as an intermediate joint was appended at the end. We put back this joint at the correct position, by doing successive permutations. */ for(int32_t i = childId; i < newId; i++) { switchJoints(modelInOut, i, newId); } return result_t::SUCCESS; } // ********************** Math utilities ************************* /////////////////////////////////////////////////////////////////////////////////////////////// /// /// \brief Continuously differentiable piecewise-defined saturation function. More /// precisely, it consists in adding fillets at the two discontinuous points: /// - It is perfectly linear for `uc` between `-bevelStart` and `bevelStart`. /// - It is perfectly constant equal to mi (resp. ma) for `uc` lower than /// `-bevelStop` (resp. higher than `-bevelStop`). /// - Then, two arcs of a circle connect those two modes continuously between /// `bevelStart` and `bevelStop` (resp. `-bevelStop` and `-bevelStart`). /// See the implementation for details about how `uc`, `bevelStart` and `bevelStop` /// are computed. /// /////////////////////////////////////////////////////////////////////////////////////////////// float64_t saturateSoft(float64_t const & in, float64_t const & mi, float64_t const & ma, float64_t const & r) { float64_t uc, range, middle, bevelL, bevelXc, bevelYc, bevelStart, bevelStop, out; float64_t const alpha = M_PI/8; float64_t const beta = M_PI/4; range = ma - mi; middle = (ma + mi)/2; uc = 2*(in - middle)/range; bevelL = r * tan(alpha); bevelStart = 1 - cos(beta)*bevelL; bevelStop = 1 + bevelL; bevelXc = bevelStop; bevelYc = 1 - r; if (uc >= bevelStop) { out = ma; } else if (uc <= -bevelStop) { out = mi; } else if (uc <= bevelStart && uc >= -bevelStart) { out = in; } else if (uc > bevelStart) { out = sqrt(r * r - (uc - bevelXc) * (uc - bevelXc)) + bevelYc; out = 0.5 * out * range + middle; } else if (uc < -bevelStart) { out = -sqrt(r * r - (uc + bevelXc) * (uc + bevelXc)) - bevelYc; out = 0.5 * out * range + middle; } else { out = in; } return out; } vectorN_t clamp(Eigen::Ref<vectorN_t const> data, float64_t const & minThr, float64_t const & maxThr) { return data.unaryExpr( [&minThr, &maxThr](float64_t const & x) -> float64_t { return clamp(x, minThr, maxThr); }); } float64_t clamp(float64_t const & data, float64_t const & minThr, float64_t const & maxThr) { if (!isnan(data)) { return std::min(std::max(data, minThr), maxThr); } else { return 0.0; } } }
36.694898
134
0.496594
[ "geometry", "vector", "model", "transform" ]
a9b530ce2ebdeb66d6b9214848a825221eff7f60
1,294
cxx
C++
json/Object.cxx
JeneLitsch/StreamJson
a2ae14302905c131569c10e9fa81f470304a23a9
[ "MIT" ]
null
null
null
json/Object.cxx
JeneLitsch/StreamJson
a2ae14302905c131569c10e9fa81f470304a23a9
[ "MIT" ]
null
null
null
json/Object.cxx
JeneLitsch/StreamJson
a2ae14302905c131569c10e9fa81f470304a23a9
[ "MIT" ]
null
null
null
#include "Object.hxx" #include "Value.hxx" #include "Array.hxx" void json::Object::readFromStream(std::istream & in) { this->dict.clear(); if(!match(in, '{')) { throw std::runtime_error("Object mmust begin with {"); } if(match(in, '}')) { return; } else while (true) { std::string key = readString(in); if(!match(in, ':')) { throw std::runtime_error("Expected : between and value"); } std::unique_ptr<Value> && value = std::make_unique<Value>(); in >> *value; this->dict.insert({key, std::move(value)}); if(in.eof()) { throw std::runtime_error("Unterminated Object"); } if(match(in, '}')) break; if(!match(in, ',')) { throw std::runtime_error("Expectd comma between elements in object"); } } } void json::Object::writeToStream(std::ostream & out) const { out << "{"; bool first = true; for(const auto & pair : this->dict) { if(first) { first = false; } else { out << ", "; } writeString(out, pair.first); out << " : " << *pair.second; } out << "}"; } const json::Node & json::Object::get(const std::string_view key) const { return *this->dict.at(std::string(key)); } void json::Object::insert( const std::string_view key, std::unique_ptr<Node> && value) { this->dict.insert({std::string(key), std::move(value)}); }
20.870968
72
0.608964
[ "object" ]
a9b64eb7a36e4ebdb1021ab3215654eab3dfc696
1,789
hpp
C++
test/uts/vranks_hybrid.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
null
null
null
test/uts/vranks_hybrid.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
null
null
null
test/uts/vranks_hybrid.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
1
2021-06-10T11:14:25.000Z
2021-06-10T11:14:25.000Z
#ifndef _f387e40c_d7ab_4dbf_a130_3bcd835cc3b9 #define _f387e40c_d7ab_4dbf_a130_3bcd835cc3b9 #include <upcxx/upcxx.hpp> #include <atomic> #include <thread> #include <vector> #include <sched.h> #if !UPCXX_THREADMODE #error This test may only be compiled in PAR threadmode #endif #define VRANKS_IMPL "ranks+threads" #define VRANK_LOCAL thread_local namespace vranks { std::vector<upcxx::persona*> thread_agents; int thread_per_rank; template<typename Fn> void send(int vrank, Fn msg) { int rank = vrank/thread_per_rank; int thd = vrank%thread_per_rank; upcxx::rpc_ff(rank, [=]() { thread_agents[thd]->lpc_ff(msg); } ); } inline void progress() { upcxx::progress(); } template<typename Fn> void spawn(Fn fn) { upcxx::init(); thread_per_rank = upcxx::os_env<int>("THREADS", 4); thread_agents.resize(thread_per_rank); std::vector<std::thread*> threads{(unsigned)thread_per_rank}; std::atomic<int> bar0{0}, bar1{0}; auto thread_main = [&](int thread_me) { thread_agents[thread_me] = &upcxx::default_persona(); bar0.fetch_add(1); while(bar0.load(std::memory_order_acquire) != thread_per_rank) sched_yield(); fn( /*agent_me*/thread_me + thread_per_rank*upcxx::rank_me(), /*agent_n*/thread_per_rank*upcxx::rank_n() ); bar1.fetch_add(1); while(bar1.load(std::memory_order_acquire) != thread_per_rank) upcxx::progress(); }; for(int t=1; t < thread_per_rank; t++) threads[t] = new std::thread{thread_main, t}; thread_main(0); for(int t=1; t < thread_per_rank; t++) { threads[t]->join(); delete threads[t]; } upcxx::finalize(); } } #endif
22.935897
68
0.634433
[ "vector" ]
a9b9752d526ea5dff04a30f21a14b5c6865619f0
5,321
cc
C++
src/connectivity/network/testing/netemul/runner/model/environment.cc
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
src/connectivity/network/testing/netemul/runner/model/environment.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
src/connectivity/network/testing/netemul/runner/model/environment.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 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 "environment.h" #include <src/lib/fxl/strings/string_printf.h> namespace netemul { namespace config { static const char* kDefaultName = ""; static const char* kName = "name"; static const char* kServices = "services"; static const char* kDevices = "devices"; static const char* kChildren = "children"; static const char* kTest = "test"; static const char* kInheritServices = "inherit_services"; static const char* kApps = "apps"; static const char* kSetup = "setup"; static const char* kLoggerOptions = "logger_options"; static const bool kDefaultInheritServices = true; bool Environment::ParseFromJSON(const rapidjson::Value& value, json::JSONParser* parser) { if (!value.IsObject()) { parser->ReportError("environment must be object type"); return false; } // load defaults: name_ = kDefaultName; inherit_services_ = kDefaultInheritServices; devices_.clear(); services_.clear(); test_.clear(); children_.clear(); apps_.clear(); setup_.clear(); logger_options_.SetDefaults(); // iterate over members: for (auto i = value.MemberBegin(); i != value.MemberEnd(); i++) { if (i->name == kName) { if (!i->value.IsString()) { parser->ReportError("environment name must be string value"); return false; } name_ = i->value.GetString(); } else if (i->name == kInheritServices) { if (!i->value.IsBool()) { parser->ReportError("inherit_services must be boolean value"); return false; } inherit_services_ = i->value.GetBool(); } else if (i->name == kDevices) { if (!i->value.IsArray()) { parser->ReportError("environment devices must be array of strings"); return false; } auto devs = i->value.GetArray(); for (auto d = devs.Begin(); d != devs.End(); d++) { if (!d->IsString()) { parser->ReportError("environment devices must be array of strings"); return false; } devices_.emplace_back(d->GetString()); } } else if (i->name == kServices) { if (!i->value.IsObject()) { parser->ReportError("environment services must be object"); return false; } for (auto s = i->value.MemberBegin(); s != i->value.MemberEnd(); s++) { auto& ns = services_.emplace_back(s->name.GetString()); if (!ns.ParseFromJSON(s->value, parser)) { return false; } } } else if (i->name == kTest) { if (!i->value.IsArray()) { parser->ReportError("environment tests must be array of objects"); return false; } auto test_arr = i->value.GetArray(); for (auto t = test_arr.Begin(); t != test_arr.End(); t++) { auto& nt = test_.emplace_back(); if (!nt.ParseFromJSON(*t, parser)) { return false; } } } else if (i->name == kChildren) { if (!i->value.IsArray()) { parser->ReportError("environment children must be array of objects"); return false; } auto ch_arr = i->value.GetArray(); for (auto c = ch_arr.Begin(); c != ch_arr.End(); c++) { auto& nc = children_.emplace_back(); if (!nc.ParseFromJSON(*c, parser)) { return false; } } } else if (i->name == kApps) { if (!i->value.IsArray()) { parser->ReportError("environment apps must be array"); return false; } auto app_arr = i->value.GetArray(); for (auto a = app_arr.Begin(); a != app_arr.End(); a++) { auto& na = apps_.emplace_back(); if (!na.ParseFromJSON(*a, parser)) { return false; } } } else if (i->name == kSetup) { if (!i->value.IsArray()) { parser->ReportError("environment setup must be array"); return false; } auto setup_arr = i->value.GetArray(); for (auto s = setup_arr.Begin(); s != setup_arr.End(); s++) { auto& ns = setup_.emplace_back(); if (!ns.ParseFromJSON(*s, parser)) { return false; } } } else if (i->name == kLoggerOptions) { if (!logger_options_.ParseFromJSON(i->value, parser)) { return false; } } else { parser->ReportError(fxl::StringPrintf( "Unrecognized environment member \"%s\"", i->name.GetString())); return false; } } return true; } const std::string& Environment::name() const { return name_; } const std::vector<Environment>& Environment::children() const { return children_; } const std::vector<std::string>& Environment::devices() const { return devices_; } const std::vector<LaunchService>& Environment::services() const { return services_; } const std::vector<LaunchApp>& Environment::test() const { return test_; } bool Environment::inherit_services() const { return inherit_services_; } const std::vector<LaunchApp>& Environment::apps() const { return apps_; } const std::vector<LaunchApp>& Environment::setup() const { return setup_; } const LoggerOptions& Environment::logger_options() const { return logger_options_; } } // namespace config } // namespace netemul
31.3
78
0.605149
[ "object", "vector" ]
a9bcc994631558d723e233dfed52bdb3becd3550
4,487
hpp
C++
openstudiocore/src/resultsviewer/TreeView.hpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
1
2015-06-28T09:06:24.000Z
2015-06-28T09:06:24.000Z
openstudiocore/src/resultsviewer/TreeView.hpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
11
2015-05-05T16:16:33.000Z
2017-08-10T08:15:50.000Z
openstudiocore/src/resultsviewer/TreeView.hpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
1
2017-09-23T12:51:13.000Z
2017-09-23T12:51:13.000Z
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef RESULTSVIEWER_TREEVIEW_HPP #define RESULTSVIEWER_TREEVIEW_HPP #include "LinePlot.hpp" #include "FloodPlot.hpp" #include "ResultsViewerData.hpp" #include "../utilities/sql/SqlFile.hpp" #include <QMainWindow> #include <QList> #include <QMenu> #include <QTreeWidget> #include <string> #include <QApplication> namespace resultsviewer{ /// node type identifying type in tree enum dataDictionaryType {ddtFile = 1001, ddtEnv = 1002, ddtReportingFrequency = 1003, ddtVariableName = 1004, ddtKeyValue = 1005}; /** TreeView is a ui widget to present EnergyPlus output in a tree format which can be sorted and filtered and expanded and collapsed. */ class TreeView : public QTreeWidget { Q_OBJECT public: /// display type for tree view of sql file enum treeViewDisplayType { tvdtVariableName, tvdtKeyValue }; TreeView( QWidget* parent=nullptr ); openstudio::OptionalTimeSeries timeseriesFromTreeItem(QTreeWidgetItem* treeItem); resultsviewer::ResultsViewerPlotData resultsViewerPlotDataFromTreeItem(QTreeWidgetItem* treeItem); void displayFile(const QString &alias, openstudio::SqlFile sqlFile, treeViewDisplayType treeViewDisplay); void displaySqlFileVariableName(const QString &alias, openstudio::SqlFile sqlFile); void updateFileAlias(const QString& alias, const QString& filename); void removeFile(const QString& filename); bool isEmpty(); // general plotting without caching - can be placed in Plot2DMimeData void applyFilter(QString& filterText); void clearFilter(); QString filenameFromTreeItem(QTreeWidgetItem *item); void goToFile(const QString& filename); public slots: void generateLinePlotData(); void generateFloodPlotData(); void generateIlluminancePlotData(); void generateLinePlotComparisonData(); void generateFloodPlotComparisonData(); void generateIlluminancePlotComparisonData(); void generateReverseLinePlotComparisonData(); void generateReverseFloodPlotComparisonData(); void generateReverseIlluminancePlotComparisonData(); protected: void mouseMoveEvent(QMouseEvent *e); void mousePressEvent(QMouseEvent *e); // internal plot2ddata creation without caching void performPlot2DDataDrag(); // external resultsviewerplotdata creation with caching of timeseries void performResultsViewerPlotDataDrag(); private: QPoint m_startPos; treeViewDisplayType m_defaultDisplayMode; QString filenameFromTopLevelItem(QTreeWidgetItem *topLevelItem); QString aliasFromTopLevelItem(QTreeWidgetItem *topLevelItem); void removeBranch(QTreeWidgetItem *item); std::vector<resultsviewer::ResultsViewerPlotData> generateResultsViewerPlotData(); signals: // plotting within resultsviewer with timeseries caching void signalAddLinePlot(const std::vector<resultsviewer::ResultsViewerPlotData> &plotDataVec); void signalAddFloodPlot(const std::vector<resultsviewer::ResultsViewerPlotData> &plotDataVec); void signalAddIlluminancePlot(const std::vector<resultsviewer::ResultsViewerPlotData> &plotDataVec); void signalAddLinePlotComparison(const std::vector<resultsviewer::ResultsViewerPlotData> &plotDataVec); void signalAddFloodPlotComparison(const std::vector<resultsviewer::ResultsViewerPlotData> &plotDataVec); void signalAddIlluminancePlotComparison(const std::vector<resultsviewer::ResultsViewerPlotData> &plotDataVec); void signalDragResultsViewerPlotData(const std::vector<resultsviewer::ResultsViewerPlotData> &plotDataVec); }; }; // resultsviewer namespace #endif // RESULTSVIEWER_TREEVIEW_HPP
40.790909
134
0.772677
[ "vector" ]
a9bdba3bb5ad8cc379b95929210301f7cce1cff4
20,472
cpp
C++
dlib-19.9/tools/python/src/object_detection.cpp
shumon84/FaceRotate
5d1c8434dc0aaeee2e116a66e4fa2108f759b9cd
[ "MIT" ]
null
null
null
dlib-19.9/tools/python/src/object_detection.cpp
shumon84/FaceRotate
5d1c8434dc0aaeee2e116a66e4fa2108f759b9cd
[ "MIT" ]
4
2018-02-27T15:44:25.000Z
2018-02-28T01:26:03.000Z
dlib-19.9/tools/python/src/object_detection.cpp
shumon84/FaceRotate
5d1c8434dc0aaeee2e116a66e4fa2108f759b9cd
[ "MIT" ]
null
null
null
// Copyright (C) 2015 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #include <dlib/python.h> #include <dlib/matrix.h> #include <dlib/geometry.h> #include <dlib/image_processing/frontal_face_detector.h> #include "simple_object_detector.h" #include "simple_object_detector_py.h" #include "conversion.h" using namespace dlib; using namespace std; namespace py = pybind11; // ---------------------------------------------------------------------------------------- string print_simple_test_results(const simple_test_results& r) { std::ostringstream sout; sout << "precision: "<<r.precision << ", recall: "<< r.recall << ", average precision: " << r.average_precision; return sout.str(); } // ---------------------------------------------------------------------------------------- inline simple_object_detector_py train_simple_object_detector_on_images_py ( const py::list& pyimages, const py::list& pyboxes, const simple_object_detector_training_options& options ) { const unsigned long num_images = py::len(pyimages); if (num_images != py::len(pyboxes)) throw dlib::error("The length of the boxes list must match the length of the images list."); // We never have any ignore boxes for this version of the API. std::vector<std::vector<rectangle> > ignore(num_images), boxes(num_images); dlib::array<array2d<rgb_pixel> > images(num_images); images_and_nested_params_to_dlib(pyimages, pyboxes, images, boxes); return train_simple_object_detector_on_images("", images, boxes, ignore, options); } inline simple_test_results test_simple_object_detector_with_images_py ( const py::list& pyimages, const py::list& pyboxes, simple_object_detector& detector, const unsigned int upsampling_amount ) { const unsigned long num_images = py::len(pyimages); if (num_images != py::len(pyboxes)) throw dlib::error("The length of the boxes list must match the length of the images list."); // We never have any ignore boxes for this version of the API. std::vector<std::vector<rectangle> > ignore(num_images), boxes(num_images); dlib::array<array2d<rgb_pixel> > images(num_images); images_and_nested_params_to_dlib(pyimages, pyboxes, images, boxes); return test_simple_object_detector_with_images(images, upsampling_amount, boxes, ignore, detector); } // ---------------------------------------------------------------------------------------- inline simple_test_results test_simple_object_detector_py_with_images_py ( const py::list& pyimages, const py::list& pyboxes, simple_object_detector_py& detector, const int upsampling_amount ) { // Allow users to pass an upsampling amount ELSE use the one cached on the object // Anything less than 0 is ignored and the cached value is used. unsigned int final_upsampling_amount = 0; if (upsampling_amount >= 0) final_upsampling_amount = upsampling_amount; else final_upsampling_amount = detector.upsampling_amount; return test_simple_object_detector_with_images_py(pyimages, pyboxes, detector.detector, final_upsampling_amount); } // ---------------------------------------------------------------------------------------- inline void find_candidate_object_locations_py ( py::object pyimage, py::list& pyboxes, py::tuple pykvals, unsigned long min_size, unsigned long max_merging_iterations ) { // Copy the data into dlib based objects array2d<rgb_pixel> image; if (is_gray_python_image(pyimage)) assign_image(image, numpy_gray_image(pyimage)); else if (is_rgb_python_image(pyimage)) assign_image(image, numpy_rgb_image(pyimage)); else throw dlib::error("Unsupported image type, must be 8bit gray or RGB image."); if (py::len(pykvals) != 3) throw dlib::error("kvals must be a tuple with three elements for start, end, num."); double start = pykvals[0].cast<double>(); double end = pykvals[1].cast<double>(); long num = pykvals[2].cast<long>(); matrix_range_exp<double> kvals = linspace(start, end, num); std::vector<rectangle> rects; const long count = py::len(pyboxes); // Copy any rectangles in the input pyboxes into rects so that any rectangles will be // properly deduped in the resulting output. for (long i = 0; i < count; ++i) rects.push_back(pyboxes[i].cast<rectangle>()); // Find candidate objects find_candidate_object_locations(image, rects, kvals, min_size, max_merging_iterations); // Collect boxes containing candidate objects std::vector<rectangle>::iterator iter; for (iter = rects.begin(); iter != rects.end(); ++iter) pyboxes.append(*iter); } // ---------------------------------------------------------------------------------------- void bind_object_detection(py::module& m) { { typedef simple_object_detector_training_options type; py::class_<type>(m, "simple_object_detector_training_options", "This object is a container for the options to the train_simple_object_detector() routine.") .def(py::init()) .def_readwrite("be_verbose", &type::be_verbose, "If true, train_simple_object_detector() will print out a lot of information to the screen while training.") .def_readwrite("add_left_right_image_flips", &type::add_left_right_image_flips, "if true, train_simple_object_detector() will assume the objects are \n\ left/right symmetric and add in left right flips of the training \n\ images. This doubles the size of the training dataset.") .def_readwrite("detection_window_size", &type::detection_window_size, "The sliding window used will have about this many pixels inside it.") .def_readwrite("C", &type::C, "C is the usual SVM C regularization parameter. So it is passed to \n\ structural_object_detection_trainer::set_c(). Larger values of C \n\ will encourage the trainer to fit the data better but might lead to \n\ overfitting. Therefore, you must determine the proper setting of \n\ this parameter experimentally.") .def_readwrite("epsilon", &type::epsilon, "epsilon is the stopping epsilon. Smaller values make the trainer's \n\ solver more accurate but might take longer to train.") .def_readwrite("num_threads", &type::num_threads, "train_simple_object_detector() will use this many threads of \n\ execution. Set this to the number of CPU cores on your machine to \n\ obtain the fastest training speed.") .def_readwrite("upsample_limit", &type::upsample_limit, "train_simple_object_detector() will upsample images if needed \n\ no more than upsample_limit times. Value 0 will forbid trainer to \n\ upsample any images. If trainer is unable to fit all boxes with \n\ required upsample_limit, exception will be thrown. Higher values \n\ of upsample_limit exponentially increases memory requiremens. \n\ Values higher than 2 (default) are not recommended."); } { typedef simple_test_results type; py::class_<type>(m, "simple_test_results") .def_readwrite("precision", &type::precision) .def_readwrite("recall", &type::recall) .def_readwrite("average_precision", &type::average_precision) .def("__str__", &::print_simple_test_results); } // Here, kvals is actually the result of linspace(start, end, num) and it is different from kvals used // in find_candidate_object_locations(). See dlib/image_transforms/segment_image_abstract.h for more details. m.def("find_candidate_object_locations", find_candidate_object_locations_py, py::arg("image"), py::arg("rects"), py::arg("kvals")=py::make_tuple(50, 200, 3), py::arg("min_size")=20, py::arg("max_merging_iterations")=50, "Returns found candidate objects\n\ requires\n\ - image == an image object which is a numpy ndarray\n\ - len(kvals) == 3\n\ - kvals should be a tuple that specifies the range of k values to use. In\n\ particular, it should take the form (start, end, num) where num > 0. \n\ ensures\n\ - This function takes an input image and generates a set of candidate\n\ rectangles which are expected to bound any objects in the image. It does\n\ this by running a version of the segment_image() routine on the image and\n\ then reports rectangles containing each of the segments as well as rectangles\n\ containing unions of adjacent segments. The basic idea is described in the\n\ paper: \n\ Segmentation as Selective Search for Object Recognition by Koen E. A. van de Sande, et al.\n\ Note that this function deviates from what is described in the paper slightly. \n\ See the code for details.\n\ - The basic segmentation is performed kvals[2] times, each time with the k parameter\n\ (see segment_image() and the Felzenszwalb paper for details on k) set to a different\n\ value from the range of numbers linearly spaced between kvals[0] to kvals[1].\n\ - When doing the basic segmentations prior to any box merging, we discard all\n\ rectangles that have an area < min_size. Therefore, all outputs and\n\ subsequent merged rectangles are built out of rectangles that contain at\n\ least min_size pixels. Note that setting min_size to a smaller value than\n\ you might otherwise be interested in using can be useful since it allows a\n\ larger number of possible merged boxes to be created.\n\ - There are max_merging_iterations rounds of neighboring blob merging.\n\ Therefore, this parameter has some effect on the number of output rectangles\n\ you get, with larger values of the parameter giving more output rectangles.\n\ - This function appends the output rectangles into #rects. This means that any\n\ rectangles in rects before this function was called will still be in there\n\ after it terminates. Note further that #rects will not contain any duplicate\n\ rectangles. That is, for all valid i and j where i != j it will be true\n\ that:\n\ - #rects[i] != rects[j]"); m.def("get_frontal_face_detector", get_frontal_face_detector, "Returns the default face detector"); m.def("train_simple_object_detector", train_simple_object_detector, py::arg("dataset_filename"), py::arg("detector_output_filename"), py::arg("options"), "requires \n\ - options.C > 0 \n\ ensures \n\ - Uses the structural_object_detection_trainer to train a \n\ simple_object_detector based on the labeled images in the XML file \n\ dataset_filename. This function assumes the file dataset_filename is in the \n\ XML format produced by dlib's save_image_dataset_metadata() routine. \n\ - This function will apply a reasonable set of default parameters and \n\ preprocessing techniques to the training procedure for simple_object_detector \n\ objects. So the point of this function is to provide you with a very easy \n\ way to train a basic object detector. \n\ - The trained object detector is serialized to the file detector_output_filename."); m.def("train_simple_object_detector", train_simple_object_detector_on_images_py, py::arg("images"), py::arg("boxes"), py::arg("options"), "requires \n\ - options.C > 0 \n\ - len(images) == len(boxes) \n\ - images should be a list of numpy matrices that represent images, either RGB or grayscale. \n\ - boxes should be a list of lists of dlib.rectangle object. \n\ ensures \n\ - Uses the structural_object_detection_trainer to train a \n\ simple_object_detector based on the labeled images and bounding boxes. \n\ - This function will apply a reasonable set of default parameters and \n\ preprocessing techniques to the training procedure for simple_object_detector \n\ objects. So the point of this function is to provide you with a very easy \n\ way to train a basic object detector. \n\ - The trained object detector is returned."); m.def("test_simple_object_detector", test_simple_object_detector, // Please see test_simple_object_detector for the reason upsampling_amount is -1 py::arg("dataset_filename"), py::arg("detector_filename"), py::arg("upsampling_amount")=-1, "requires \n\ - Optionally, take the number of times to upsample the testing images (upsampling_amount >= 0). \n\ ensures \n\ - Loads an image dataset from dataset_filename. We assume dataset_filename is \n\ a file using the XML format written by save_image_dataset_metadata(). \n\ - Loads a simple_object_detector from the file detector_filename. This means \n\ detector_filename should be a file produced by the train_simple_object_detector() \n\ routine. \n\ - This function tests the detector against the dataset and returns the \n\ precision, recall, and average precision of the detector. In fact, The \n\ return value of this function is identical to that of dlib's \n\ test_object_detection_function() routine. Therefore, see the documentation \n\ for test_object_detection_function() for a detailed definition of these \n\ metrics. " ); m.def("test_simple_object_detector", test_simple_object_detector_with_images_py, py::arg("images"), py::arg("boxes"), py::arg("detector"), py::arg("upsampling_amount")=0, "requires \n\ - len(images) == len(boxes) \n\ - images should be a list of numpy matrices that represent images, either RGB or grayscale. \n\ - boxes should be a list of lists of dlib.rectangle object. \n\ - Optionally, take the number of times to upsample the testing images (upsampling_amount >= 0). \n\ ensures \n\ - Loads a simple_object_detector from the file detector_filename. This means \n\ detector_filename should be a file produced by the train_simple_object_detector() \n\ routine. \n\ - This function tests the detector against the dataset and returns the \n\ precision, recall, and average precision of the detector. In fact, The \n\ return value of this function is identical to that of dlib's \n\ test_object_detection_function() routine. Therefore, see the documentation \n\ for test_object_detection_function() for a detailed definition of these \n\ metrics. " ); m.def("test_simple_object_detector", test_simple_object_detector_py_with_images_py, // Please see test_simple_object_detector_py_with_images_py for the reason upsampling_amount is -1 py::arg("images"), py::arg("boxes"), py::arg("detector"), py::arg("upsampling_amount")=-1, "requires \n\ - len(images) == len(boxes) \n\ - images should be a list of numpy matrices that represent images, either RGB or grayscale. \n\ - boxes should be a list of lists of dlib.rectangle object. \n\ ensures \n\ - Loads a simple_object_detector from the file detector_filename. This means \n\ detector_filename should be a file produced by the train_simple_object_detector() \n\ routine. \n\ - This function tests the detector against the dataset and returns the \n\ precision, recall, and average precision of the detector. In fact, The \n\ return value of this function is identical to that of dlib's \n\ test_object_detection_function() routine. Therefore, see the documentation \n\ for test_object_detection_function() for a detailed definition of these \n\ metrics. " ); { typedef simple_object_detector type; py::class_<type, std::shared_ptr<type>>(m, "fhog_object_detector", "This object represents a sliding window histogram-of-oriented-gradients based object detector.") .def(py::init(&load_object_from_file<type>), "Loads an object detector from a file that contains the output of the \n\ train_simple_object_detector() routine or a serialized C++ object of type\n\ object_detector<scan_fhog_pyramid<pyramid_down<6>>>.") .def("__call__", run_detector_with_upscale2, py::arg("image"), py::arg("upsample_num_times")=0, "requires \n\ - image is a numpy ndarray containing either an 8bit grayscale or RGB \n\ image. \n\ - upsample_num_times >= 0 \n\ ensures \n\ - This function runs the object detector on the input image and returns \n\ a list of detections. \n\ - Upsamples the image upsample_num_times before running the basic \n\ detector.") .def("run", run_rect_detector, py::arg("image"), py::arg("upsample_num_times")=0, py::arg("adjust_threshold")=0.0, "requires \n\ - image is a numpy ndarray containing either an 8bit grayscale or RGB \n\ image. \n\ - upsample_num_times >= 0 \n\ ensures \n\ - This function runs the object detector on the input image and returns \n\ a tuple of (list of detections, list of scores, list of weight_indices). \n\ - Upsamples the image upsample_num_times before running the basic \n\ detector.") .def_static("run_multiple", run_multiple_rect_detectors, py::arg("detectors"), py::arg("image"), py::arg("upsample_num_times")=0, py::arg("adjust_threshold")=0.0, "requires \n\ - detectors is a list of detectors. \n\ - image is a numpy ndarray containing either an 8bit grayscale or RGB \n\ image. \n\ - upsample_num_times >= 0 \n\ ensures \n\ - This function runs the list of object detectors at once on the input image and returns \n\ a tuple of (list of detections, list of scores, list of weight_indices). \n\ - Upsamples the image upsample_num_times before running the basic \n\ detector.") .def("save", save_simple_object_detector, py::arg("detector_output_filename"), "Save a simple_object_detector to the provided path.") .def(py::pickle(&getstate<type>, &setstate<type>)); } { typedef simple_object_detector_py type; py::class_<type, std::shared_ptr<type>>(m, "simple_object_detector", "This object represents a sliding window histogram-of-oriented-gradients based object detector.") .def(py::init(&load_object_from_file<type>), "Loads a simple_object_detector from a file that contains the output of the \n\ train_simple_object_detector() routine.") .def("__call__", &type::run_detector1, py::arg("image"), py::arg("upsample_num_times"), "requires \n\ - image is a numpy ndarray containing either an 8bit grayscale or RGB \n\ image. \n\ - upsample_num_times >= 0 \n\ ensures \n\ - This function runs the object detector on the input image and returns \n\ a list of detections. \n\ - Upsamples the image upsample_num_times before running the basic \n\ detector. If you don't know how many times you want to upsample then \n\ don't provide a value for upsample_num_times and an appropriate \n\ default will be used.") .def("__call__", &type::run_detector2, py::arg("image"), "requires \n\ - image is a numpy ndarray containing either an 8bit grayscale or RGB \n\ image. \n\ ensures \n\ - This function runs the object detector on the input image and returns \n\ a list of detections.") .def("save", save_simple_object_detector_py, py::arg("detector_output_filename"), "Save a simple_object_detector to the provided path.") .def(py::pickle(&getstate<type>, &setstate<type>)); } } // ----------------------------------------------------------------------------------------
54.446809
224
0.663443
[ "geometry", "object", "vector" ]
a9c0c2b155517d24339c7bff72266f72b7d416f9
70,322
cpp
C++
src/modules/osgDB/generated_code/ReaderWriter.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osgDB/generated_code/ReaderWriter.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osgDB/generated_code/ReaderWriter.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #include "boost/python.hpp" #include "__call_policies.pypp.hpp" #include "__convenience.pypp.hpp" #include "wrap_osgdb.h" #include "wrap_referenced.h" #include "readerwriter.pypp.hpp" namespace bp = boost::python; struct ReaderWriter_wrapper : osgDB::ReaderWriter, bp::wrapper< osgDB::ReaderWriter > { ReaderWriter_wrapper( ) : osgDB::ReaderWriter( ) , bp::wrapper< osgDB::ReaderWriter >(){ // null constructor } virtual bool acceptsExtension( ::std::string const & arg0 ) const { if( bp::override func_acceptsExtension = this->get_override( "acceptsExtension" ) ) return func_acceptsExtension( arg0 ); else{ return this->osgDB::ReaderWriter::acceptsExtension( arg0 ); } } bool default_acceptsExtension( ::std::string const & arg0 ) const { return osgDB::ReaderWriter::acceptsExtension( arg0 ); } virtual bool acceptsProtocol( ::std::string const & protocol ) const { if( bp::override func_acceptsProtocol = this->get_override( "acceptsProtocol" ) ) return func_acceptsProtocol( protocol ); else{ return this->osgDB::ReaderWriter::acceptsProtocol( protocol ); } } bool default_acceptsProtocol( ::std::string const & protocol ) const { return osgDB::ReaderWriter::acceptsProtocol( protocol ); } virtual char const * className( ) const { if( bp::override func_className = this->get_override( "className" ) ) return func_className( ); else{ return this->osgDB::ReaderWriter::className( ); } } char const * default_className( ) const { return osgDB::ReaderWriter::className( ); } virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const { if( bp::override func_clone = this->get_override( "clone" ) ) return func_clone( boost::ref(copyop) ); else{ return this->osgDB::ReaderWriter::clone( boost::ref(copyop) ); } } ::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const { return osgDB::ReaderWriter::clone( boost::ref(copyop) ); } virtual ::osg::Object * cloneType( ) const { if( bp::override func_cloneType = this->get_override( "cloneType" ) ) return func_cloneType( ); else{ return this->osgDB::ReaderWriter::cloneType( ); } } ::osg::Object * default_cloneType( ) const { return osgDB::ReaderWriter::cloneType( ); } virtual bool fileExists( ::std::string const & filename, ::osgDB::Options const * options ) const { if( bp::override func_fileExists = this->get_override( "fileExists" ) ) return func_fileExists( filename, boost::python::ptr(options) ); else{ return this->osgDB::ReaderWriter::fileExists( filename, boost::python::ptr(options) ); } } bool default_fileExists( ::std::string const & filename, ::osgDB::Options const * options ) const { return osgDB::ReaderWriter::fileExists( filename, boost::python::ptr(options) ); } virtual bool isSameKindAs( ::osg::Object const * obj ) const { if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) ) return func_isSameKindAs( boost::python::ptr(obj) ); else{ return this->osgDB::ReaderWriter::isSameKindAs( boost::python::ptr(obj) ); } } bool default_isSameKindAs( ::osg::Object const * obj ) const { return osgDB::ReaderWriter::isSameKindAs( boost::python::ptr(obj) ); } virtual char const * libraryName( ) const { if( bp::override func_libraryName = this->get_override( "libraryName" ) ) return func_libraryName( ); else{ return this->osgDB::ReaderWriter::libraryName( ); } } char const * default_libraryName( ) const { return osgDB::ReaderWriter::libraryName( ); } virtual ::osgDB::ReaderWriter::ReadResult openArchive( ::std::string const & arg0, ::osgDB::ReaderWriter::ArchiveStatus arg1, unsigned int arg2=4096, ::osgDB::Options const * arg3=0 ) const { if( bp::override func_openArchive = this->get_override( "openArchive" ) ) return func_openArchive( arg0, arg1, arg2, boost::python::ptr(arg3) ); else{ return this->osgDB::ReaderWriter::openArchive( arg0, arg1, arg2, boost::python::ptr(arg3) ); } } ::osgDB::ReaderWriter::ReadResult default_openArchive( ::std::string const & arg0, ::osgDB::ReaderWriter::ArchiveStatus arg1, unsigned int arg2=4096, ::osgDB::Options const * arg3=0 ) const { return osgDB::ReaderWriter::openArchive( arg0, arg1, arg2, boost::python::ptr(arg3) ); } virtual ::osgDB::ReaderWriter::ReadResult openArchive( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_openArchive = this->get_override( "openArchive" ) ) return func_openArchive( boost::ref(arg0), boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::openArchive( boost::ref(arg0), boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_openArchive( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::openArchive( boost::ref(arg0), boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readHeightField( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readHeightField = this->get_override( "readHeightField" ) ) return func_readHeightField( arg0, boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readHeightField( arg0, boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readHeightField( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readHeightField( arg0, boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readHeightField( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readHeightField = this->get_override( "readHeightField" ) ) return func_readHeightField( boost::ref(arg0), boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readHeightField( boost::ref(arg0), boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readHeightField( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readHeightField( boost::ref(arg0), boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readImage( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readImage = this->get_override( "readImage" ) ) return func_readImage( arg0, boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readImage( arg0, boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readImage( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readImage( arg0, boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readImage( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readImage = this->get_override( "readImage" ) ) return func_readImage( boost::ref(arg0), boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readImage( boost::ref(arg0), boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readImage( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readImage( boost::ref(arg0), boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readNode( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readNode = this->get_override( "readNode" ) ) return func_readNode( arg0, boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readNode( arg0, boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readNode( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readNode( arg0, boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readNode( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readNode = this->get_override( "readNode" ) ) return func_readNode( boost::ref(arg0), boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readNode( boost::ref(arg0), boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readNode( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readNode( boost::ref(arg0), boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readObject( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readObject = this->get_override( "readObject" ) ) return func_readObject( arg0, boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readObject( arg0, boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readObject( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readObject( arg0, boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readObject( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readObject = this->get_override( "readObject" ) ) return func_readObject( boost::ref(arg0), boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readObject( boost::ref(arg0), boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readObject( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readObject( boost::ref(arg0), boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readShader( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readShader = this->get_override( "readShader" ) ) return func_readShader( arg0, boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readShader( arg0, boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readShader( ::std::string const & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readShader( arg0, boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::ReadResult readShader( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { if( bp::override func_readShader = this->get_override( "readShader" ) ) return func_readShader( boost::ref(arg0), boost::python::ptr(arg1) ); else{ return this->osgDB::ReaderWriter::readShader( boost::ref(arg0), boost::python::ptr(arg1) ); } } ::osgDB::ReaderWriter::ReadResult default_readShader( ::std::istream & arg0, ::osgDB::Options const * arg1=0 ) const { return osgDB::ReaderWriter::readShader( boost::ref(arg0), boost::python::ptr(arg1) ); } virtual ::osgDB::ReaderWriter::Features supportedFeatures( ) const { if( bp::override func_supportedFeatures = this->get_override( "supportedFeatures" ) ) return func_supportedFeatures( ); else{ return this->osgDB::ReaderWriter::supportedFeatures( ); } } ::osgDB::ReaderWriter::Features default_supportedFeatures( ) const { return osgDB::ReaderWriter::supportedFeatures( ); } virtual ::osgDB::ReaderWriter::WriteResult writeHeightField( ::osg::HeightField const & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeHeightField = this->get_override( "writeHeightField" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeHeightField.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeHeightField( boost::ref(arg0), arg1, boost::python::ptr(arg2) ); } } static boost::python::object default_writeHeightField_492ba9227016a7cdc011f560ee63846b( ::osgDB::ReaderWriter const & inst, ::osg::HeightField & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeHeightField(arg0, arg1, arg2); } else{ result = inst.writeHeightField(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeHeightField( ::osg::HeightField const & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeHeightField = this->get_override( "writeHeightField" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeHeightField.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeHeightField( boost::ref(arg0), boost::ref(arg1), boost::python::ptr(arg2) ); } } static boost::python::object default_writeHeightField_9396c211b31e432102458b3f4acc5b01( ::osgDB::ReaderWriter const & inst, ::osg::HeightField & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeHeightField(arg0, arg1, arg2); } else{ result = inst.writeHeightField(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeImage( ::osg::Image const & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeImage = this->get_override( "writeImage" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeImage.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeImage( boost::ref(arg0), arg1, boost::python::ptr(arg2) ); } } static boost::python::object default_writeImage_48409f166d256ec2a1ce1aba7ba91b41( ::osgDB::ReaderWriter const & inst, ::osg::Image & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeImage(arg0, arg1, arg2); } else{ result = inst.writeImage(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeImage( ::osg::Image const & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeImage = this->get_override( "writeImage" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeImage.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeImage( boost::ref(arg0), boost::ref(arg1), boost::python::ptr(arg2) ); } } static boost::python::object default_writeImage_09e0c822c73aac048a8706dbb950438f( ::osgDB::ReaderWriter const & inst, ::osg::Image & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeImage(arg0, arg1, arg2); } else{ result = inst.writeImage(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeNode( ::osg::Node const & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeNode = this->get_override( "writeNode" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeNode.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeNode( boost::ref(arg0), arg1, boost::python::ptr(arg2) ); } } static boost::python::object default_writeNode_94ab5d58c5431145dd0b29259e29a1e0( ::osgDB::ReaderWriter const & inst, ::osg::Node & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeNode(arg0, arg1, arg2); } else{ result = inst.writeNode(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeNode( ::osg::Node const & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeNode = this->get_override( "writeNode" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeNode.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeNode( boost::ref(arg0), boost::ref(arg1), boost::python::ptr(arg2) ); } } static boost::python::object default_writeNode_85ada25f9394d5ca11dce46130e109e3( ::osgDB::ReaderWriter const & inst, ::osg::Node & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeNode(arg0, arg1, arg2); } else{ result = inst.writeNode(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeObject( ::osg::Object const & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeObject = this->get_override( "writeObject" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeObject.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeObject( boost::ref(arg0), arg1, boost::python::ptr(arg2) ); } } static boost::python::object default_writeObject_4b217c12bc66236059a76e176772f392( ::osgDB::ReaderWriter const & inst, ::osg::Object & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeObject(arg0, arg1, arg2); } else{ result = inst.writeObject(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeObject( ::osg::Object const & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeObject = this->get_override( "writeObject" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeObject.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeObject( boost::ref(arg0), boost::ref(arg1), boost::python::ptr(arg2) ); } } static boost::python::object default_writeObject_86a17357be0e1c05716ddbecef039a10( ::osgDB::ReaderWriter const & inst, ::osg::Object & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeObject(arg0, arg1, arg2); } else{ result = inst.writeObject(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeShader( ::osg::Shader const & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeShader = this->get_override( "writeShader" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeShader.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeShader( boost::ref(arg0), arg1, boost::python::ptr(arg2) ); } } static boost::python::object default_writeShader_be57249f6a6e741afc4665bd121f54f9( ::osgDB::ReaderWriter const & inst, ::osg::Shader & arg0, ::std::string const & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeShader(arg0, arg1, arg2); } else{ result = inst.writeShader(arg0, arg1, arg2); } return bp::object( result ); } virtual ::osgDB::ReaderWriter::WriteResult writeShader( ::osg::Shader const & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ) const { namespace bpl = boost::python; if( bpl::override func_writeShader = this->get_override( "writeShader" ) ){ bpl::object py_result = bpl::call<bpl::object>( func_writeShader.ptr(), arg0, arg1, arg2 ); return bpl::extract< ::osgDB::ReaderWriter::WriteResult >( pyplus_conv::get_out_argument( py_result, 0 ) ); } else{ return osgDB::ReaderWriter::writeShader( boost::ref(arg0), boost::ref(arg1), boost::python::ptr(arg2) ); } } static boost::python::object default_writeShader_88038c79c30b9deaaaed55931fcd9f34( ::osgDB::ReaderWriter const & inst, ::osg::Shader & arg0, ::std::ostream & arg1, ::osgDB::Options const * arg2=0 ){ osgDB::ReaderWriter::WriteResult result; if( dynamic_cast< ReaderWriter_wrapper const* >( boost::addressof( inst ) ) ){ result = inst.::osgDB::ReaderWriter::writeShader(arg0, arg1, arg2); } else{ result = inst.writeShader(arg0, arg1, arg2); } return bp::object( result ); } virtual void computeDataVariance( ) { if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) ) func_computeDataVariance( ); else{ this->osg::Object::computeDataVariance( ); } } void default_computeDataVariance( ) { osg::Object::computeDataVariance( ); } virtual ::osg::Referenced * getUserData( ) { if( bp::override func_getUserData = this->get_override( "getUserData" ) ) return func_getUserData( ); else{ return this->osg::Object::getUserData( ); } } ::osg::Referenced * default_getUserData( ) { return osg::Object::getUserData( ); } virtual ::osg::Referenced const * getUserData( ) const { if( bp::override func_getUserData = this->get_override( "getUserData" ) ) return func_getUserData( ); else{ return this->osg::Object::getUserData( ); } } ::osg::Referenced const * default_getUserData( ) const { return osg::Object::getUserData( ); } virtual void resizeGLObjectBuffers( unsigned int arg0 ) { if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) ) func_resizeGLObjectBuffers( arg0 ); else{ this->osg::Object::resizeGLObjectBuffers( arg0 ); } } void default_resizeGLObjectBuffers( unsigned int arg0 ) { osg::Object::resizeGLObjectBuffers( arg0 ); } virtual void setName( ::std::string const & name ) { if( bp::override func_setName = this->get_override( "setName" ) ) func_setName( name ); else{ this->osg::Object::setName( name ); } } void default_setName( ::std::string const & name ) { osg::Object::setName( name ); } virtual void setThreadSafeRefUnref( bool threadSafe ) { if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) ) func_setThreadSafeRefUnref( threadSafe ); else{ this->osg::Object::setThreadSafeRefUnref( threadSafe ); } } void default_setThreadSafeRefUnref( bool threadSafe ) { osg::Object::setThreadSafeRefUnref( threadSafe ); } virtual void setUserData( ::osg::Referenced * obj ) { if( bp::override func_setUserData = this->get_override( "setUserData" ) ) func_setUserData( boost::python::ptr(obj) ); else{ this->osg::Object::setUserData( boost::python::ptr(obj) ); } } void default_setUserData( ::osg::Referenced * obj ) { osg::Object::setUserData( boost::python::ptr(obj) ); } }; void register_ReaderWriter_class(){ { //::osgDB::ReaderWriter typedef bp::class_< ReaderWriter_wrapper, bp::bases< ::osg::Object >, osg::ref_ptr< ReaderWriter_wrapper >, boost::noncopyable > ReaderWriter_exposer_t; ReaderWriter_exposer_t ReaderWriter_exposer = ReaderWriter_exposer_t( "ReaderWriter", bp::init< >() ); bp::scope ReaderWriter_scope( ReaderWriter_exposer ); bp::enum_< osgDB::ReaderWriter::ArchiveStatus>("ArchiveStatus") .value("READ", osgDB::ReaderWriter::READ) .value("WRITE", osgDB::ReaderWriter::WRITE) .value("CREATE", osgDB::ReaderWriter::CREATE) .export_values() ; bp::enum_< osgDB::ReaderWriter::Features>("Features") .value("FEATURE_NONE", osgDB::ReaderWriter::FEATURE_NONE) .value("FEATURE_READ_OBJECT", osgDB::ReaderWriter::FEATURE_READ_OBJECT) .value("FEATURE_READ_IMAGE", osgDB::ReaderWriter::FEATURE_READ_IMAGE) .value("FEATURE_READ_HEIGHT_FIELD", osgDB::ReaderWriter::FEATURE_READ_HEIGHT_FIELD) .value("FEATURE_READ_NODE", osgDB::ReaderWriter::FEATURE_READ_NODE) .value("FEATURE_READ_SHADER", osgDB::ReaderWriter::FEATURE_READ_SHADER) .value("FEATURE_WRITE_OBJECT", osgDB::ReaderWriter::FEATURE_WRITE_OBJECT) .value("FEATURE_WRITE_IMAGE", osgDB::ReaderWriter::FEATURE_WRITE_IMAGE) .value("FEATURE_WRITE_HEIGHT_FIELD", osgDB::ReaderWriter::FEATURE_WRITE_HEIGHT_FIELD) .value("FEATURE_WRITE_NODE", osgDB::ReaderWriter::FEATURE_WRITE_NODE) .value("FEATURE_WRITE_SHADER", osgDB::ReaderWriter::FEATURE_WRITE_SHADER) .value("FEATURE_ALL", osgDB::ReaderWriter::FEATURE_ALL) .export_values() ; { //::osgDB::ReaderWriter::ReadResult typedef bp::class_< osgDB::ReaderWriter::ReadResult > ReadResult_exposer_t; ReadResult_exposer_t ReadResult_exposer = ReadResult_exposer_t( "ReadResult", bp::init< bp::optional< osgDB::ReaderWriter::ReadResult::ReadStatus > >(( bp::arg("status")=(long)(::osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED) )) ); bp::scope ReadResult_scope( ReadResult_exposer ); bp::enum_< osgDB::ReaderWriter::ReadResult::ReadStatus>("ReadStatus") .value("NOT_IMPLEMENTED", osgDB::ReaderWriter::ReadResult::NOT_IMPLEMENTED) .value("FILE_NOT_HANDLED", osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED) .value("FILE_NOT_FOUND", osgDB::ReaderWriter::ReadResult::FILE_NOT_FOUND) .value("ERROR_IN_READING_FILE", osgDB::ReaderWriter::ReadResult::ERROR_IN_READING_FILE) .value("FILE_LOADED", osgDB::ReaderWriter::ReadResult::FILE_LOADED) .value("FILE_LOADED_FROM_CACHE", osgDB::ReaderWriter::ReadResult::FILE_LOADED_FROM_CACHE) .value("FILE_REQUESTED", osgDB::ReaderWriter::ReadResult::FILE_REQUESTED) .value("INSUFFICIENT_MEMORY_TO_LOAD", osgDB::ReaderWriter::ReadResult::INSUFFICIENT_MEMORY_TO_LOAD) .export_values() ; bp::implicitly_convertible< osgDB::ReaderWriter::ReadResult::ReadStatus, osgDB::ReaderWriter::ReadResult >(); ReadResult_exposer.def( bp::init< std::string const & >(( bp::arg("m") )) ); bp::implicitly_convertible< std::string const &, osgDB::ReaderWriter::ReadResult >(); ReadResult_exposer.def( bp::init< osg::Object *, bp::optional< osgDB::ReaderWriter::ReadResult::ReadStatus > >(( bp::arg("obj"), bp::arg("status")=(long)(::osgDB::ReaderWriter::ReadResult::FILE_LOADED) )) ); bp::implicitly_convertible< osg::Object *, osgDB::ReaderWriter::ReadResult >(); ReadResult_exposer.def( bp::init< osgDB::ReaderWriter::ReadResult const & >(( bp::arg("rr") )) ); { //::osgDB::ReaderWriter::ReadResult::error typedef bool ( ::osgDB::ReaderWriter::ReadResult::*error_function_type)( ) const; ReadResult_exposer.def( "error" , error_function_type( &::osgDB::ReaderWriter::ReadResult::error ) ); } { //::osgDB::ReaderWriter::ReadResult::getArchive typedef ::osgDB::Archive * ( ::osgDB::ReaderWriter::ReadResult::*getArchive_function_type)( ) ; ReadResult_exposer.def( "getArchive" , getArchive_function_type( &::osgDB::ReaderWriter::ReadResult::getArchive ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::getHeightField typedef ::osg::HeightField * ( ::osgDB::ReaderWriter::ReadResult::*getHeightField_function_type)( ) ; ReadResult_exposer.def( "getHeightField" , getHeightField_function_type( &::osgDB::ReaderWriter::ReadResult::getHeightField ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::getImage typedef ::osg::Image * ( ::osgDB::ReaderWriter::ReadResult::*getImage_function_type)( ) ; ReadResult_exposer.def( "getImage" , getImage_function_type( &::osgDB::ReaderWriter::ReadResult::getImage ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::getNode typedef ::osg::Node * ( ::osgDB::ReaderWriter::ReadResult::*getNode_function_type)( ) ; ReadResult_exposer.def( "getNode" , getNode_function_type( &::osgDB::ReaderWriter::ReadResult::getNode ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::getObject typedef ::osg::Object * ( ::osgDB::ReaderWriter::ReadResult::*getObject_function_type)( ) ; ReadResult_exposer.def( "getObject" , getObject_function_type( &::osgDB::ReaderWriter::ReadResult::getObject ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::getShader typedef ::osg::Shader * ( ::osgDB::ReaderWriter::ReadResult::*getShader_function_type)( ) ; ReadResult_exposer.def( "getShader" , getShader_function_type( &::osgDB::ReaderWriter::ReadResult::getShader ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::loadedFromCache typedef bool ( ::osgDB::ReaderWriter::ReadResult::*loadedFromCache_function_type)( ) const; ReadResult_exposer.def( "loadedFromCache" , loadedFromCache_function_type( &::osgDB::ReaderWriter::ReadResult::loadedFromCache ) ); } { //::osgDB::ReaderWriter::ReadResult::message typedef ::std::string & ( ::osgDB::ReaderWriter::ReadResult::*message_function_type)( ) ; ReadResult_exposer.def( "message" , message_function_type( &::osgDB::ReaderWriter::ReadResult::message ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::message typedef ::std::string const & ( ::osgDB::ReaderWriter::ReadResult::*message_function_type)( ) const; ReadResult_exposer.def( "message" , message_function_type( &::osgDB::ReaderWriter::ReadResult::message ) , bp::return_value_policy< bp::copy_const_reference >() ); } { //::osgDB::ReaderWriter::ReadResult::notEnoughMemory typedef bool ( ::osgDB::ReaderWriter::ReadResult::*notEnoughMemory_function_type)( ) const; ReadResult_exposer.def( "notEnoughMemory" , notEnoughMemory_function_type( &::osgDB::ReaderWriter::ReadResult::notEnoughMemory ) ); } { //::osgDB::ReaderWriter::ReadResult::notFound typedef bool ( ::osgDB::ReaderWriter::ReadResult::*notFound_function_type)( ) const; ReadResult_exposer.def( "notFound" , notFound_function_type( &::osgDB::ReaderWriter::ReadResult::notFound ) ); } { //::osgDB::ReaderWriter::ReadResult::notHandled typedef bool ( ::osgDB::ReaderWriter::ReadResult::*notHandled_function_type)( ) const; ReadResult_exposer.def( "notHandled" , notHandled_function_type( &::osgDB::ReaderWriter::ReadResult::notHandled ) ); } ReadResult_exposer.def( bp::self < bp::self ); { //::osgDB::ReaderWriter::ReadResult::status typedef ::osgDB::ReaderWriter::ReadResult::ReadStatus ( ::osgDB::ReaderWriter::ReadResult::*status_function_type)( ) const; ReadResult_exposer.def( "status" , status_function_type( &::osgDB::ReaderWriter::ReadResult::status ) ); } { //::osgDB::ReaderWriter::ReadResult::success typedef bool ( ::osgDB::ReaderWriter::ReadResult::*success_function_type)( ) const; ReadResult_exposer.def( "success" , success_function_type( &::osgDB::ReaderWriter::ReadResult::success ) ); } { //::osgDB::ReaderWriter::ReadResult::takeArchive typedef ::osgDB::Archive * ( ::osgDB::ReaderWriter::ReadResult::*takeArchive_function_type)( ) ; ReadResult_exposer.def( "takeArchive" , takeArchive_function_type( &::osgDB::ReaderWriter::ReadResult::takeArchive ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::takeHeightField typedef ::osg::HeightField * ( ::osgDB::ReaderWriter::ReadResult::*takeHeightField_function_type)( ) ; ReadResult_exposer.def( "takeHeightField" , takeHeightField_function_type( &::osgDB::ReaderWriter::ReadResult::takeHeightField ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::takeImage typedef ::osg::Image * ( ::osgDB::ReaderWriter::ReadResult::*takeImage_function_type)( ) ; ReadResult_exposer.def( "takeImage" , takeImage_function_type( &::osgDB::ReaderWriter::ReadResult::takeImage ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::takeNode typedef ::osg::Node * ( ::osgDB::ReaderWriter::ReadResult::*takeNode_function_type)( ) ; ReadResult_exposer.def( "takeNode" , takeNode_function_type( &::osgDB::ReaderWriter::ReadResult::takeNode ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::takeObject typedef ::osg::Object * ( ::osgDB::ReaderWriter::ReadResult::*takeObject_function_type)( ) ; ReadResult_exposer.def( "takeObject" , takeObject_function_type( &::osgDB::ReaderWriter::ReadResult::takeObject ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::takeShader typedef ::osg::Shader * ( ::osgDB::ReaderWriter::ReadResult::*takeShader_function_type)( ) ; ReadResult_exposer.def( "takeShader" , takeShader_function_type( &::osgDB::ReaderWriter::ReadResult::takeShader ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::ReadResult::validArchive typedef bool ( ::osgDB::ReaderWriter::ReadResult::*validArchive_function_type)( ) ; ReadResult_exposer.def( "validArchive" , validArchive_function_type( &::osgDB::ReaderWriter::ReadResult::validArchive ) ); } { //::osgDB::ReaderWriter::ReadResult::validHeightField typedef bool ( ::osgDB::ReaderWriter::ReadResult::*validHeightField_function_type)( ) ; ReadResult_exposer.def( "validHeightField" , validHeightField_function_type( &::osgDB::ReaderWriter::ReadResult::validHeightField ) ); } { //::osgDB::ReaderWriter::ReadResult::validImage typedef bool ( ::osgDB::ReaderWriter::ReadResult::*validImage_function_type)( ) ; ReadResult_exposer.def( "validImage" , validImage_function_type( &::osgDB::ReaderWriter::ReadResult::validImage ) ); } { //::osgDB::ReaderWriter::ReadResult::validNode typedef bool ( ::osgDB::ReaderWriter::ReadResult::*validNode_function_type)( ) ; ReadResult_exposer.def( "validNode" , validNode_function_type( &::osgDB::ReaderWriter::ReadResult::validNode ) ); } { //::osgDB::ReaderWriter::ReadResult::validObject typedef bool ( ::osgDB::ReaderWriter::ReadResult::*validObject_function_type)( ) ; ReadResult_exposer.def( "validObject" , validObject_function_type( &::osgDB::ReaderWriter::ReadResult::validObject ) ); } { //::osgDB::ReaderWriter::ReadResult::validShader typedef bool ( ::osgDB::ReaderWriter::ReadResult::*validShader_function_type)( ) ; ReadResult_exposer.def( "validShader" , validShader_function_type( &::osgDB::ReaderWriter::ReadResult::validShader ) ); } } { //::osgDB::ReaderWriter::WriteResult typedef bp::class_< osgDB::ReaderWriter::WriteResult > WriteResult_exposer_t; WriteResult_exposer_t WriteResult_exposer = WriteResult_exposer_t( "WriteResult", bp::init< bp::optional< osgDB::ReaderWriter::WriteResult::WriteStatus > >(( bp::arg("status")=(long)(::osgDB::ReaderWriter::WriteResult::FILE_NOT_HANDLED) )) ); bp::scope WriteResult_scope( WriteResult_exposer ); bp::enum_< osgDB::ReaderWriter::WriteResult::WriteStatus>("WriteStatus") .value("NOT_IMPLEMENTED", osgDB::ReaderWriter::WriteResult::NOT_IMPLEMENTED) .value("FILE_NOT_HANDLED", osgDB::ReaderWriter::WriteResult::FILE_NOT_HANDLED) .value("ERROR_IN_WRITING_FILE", osgDB::ReaderWriter::WriteResult::ERROR_IN_WRITING_FILE) .value("FILE_SAVED", osgDB::ReaderWriter::WriteResult::FILE_SAVED) .export_values() ; bp::implicitly_convertible< osgDB::ReaderWriter::WriteResult::WriteStatus, osgDB::ReaderWriter::WriteResult >(); WriteResult_exposer.def( bp::init< std::string const & >(( bp::arg("m") )) ); bp::implicitly_convertible< std::string const &, osgDB::ReaderWriter::WriteResult >(); WriteResult_exposer.def( bp::init< osgDB::ReaderWriter::WriteResult const & >(( bp::arg("rr") )) ); { //::osgDB::ReaderWriter::WriteResult::error typedef bool ( ::osgDB::ReaderWriter::WriteResult::*error_function_type)( ) const; WriteResult_exposer.def( "error" , error_function_type( &::osgDB::ReaderWriter::WriteResult::error ) ); } { //::osgDB::ReaderWriter::WriteResult::message typedef ::std::string & ( ::osgDB::ReaderWriter::WriteResult::*message_function_type)( ) ; WriteResult_exposer.def( "message" , message_function_type( &::osgDB::ReaderWriter::WriteResult::message ) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::WriteResult::message typedef ::std::string const & ( ::osgDB::ReaderWriter::WriteResult::*message_function_type)( ) const; WriteResult_exposer.def( "message" , message_function_type( &::osgDB::ReaderWriter::WriteResult::message ) , bp::return_value_policy< bp::copy_const_reference >() ); } { //::osgDB::ReaderWriter::WriteResult::notHandled typedef bool ( ::osgDB::ReaderWriter::WriteResult::*notHandled_function_type)( ) const; WriteResult_exposer.def( "notHandled" , notHandled_function_type( &::osgDB::ReaderWriter::WriteResult::notHandled ) ); } WriteResult_exposer.def( bp::self < bp::self ); { //::osgDB::ReaderWriter::WriteResult::status typedef ::osgDB::ReaderWriter::WriteResult::WriteStatus ( ::osgDB::ReaderWriter::WriteResult::*status_function_type)( ) const; WriteResult_exposer.def( "status" , status_function_type( &::osgDB::ReaderWriter::WriteResult::status ) ); } { //::osgDB::ReaderWriter::WriteResult::success typedef bool ( ::osgDB::ReaderWriter::WriteResult::*success_function_type)( ) const; WriteResult_exposer.def( "success" , success_function_type( &::osgDB::ReaderWriter::WriteResult::success ) ); } } { //::osgDB::ReaderWriter::acceptsExtension typedef bool ( ::osgDB::ReaderWriter::*acceptsExtension_function_type)( ::std::string const & ) const; typedef bool ( ReaderWriter_wrapper::*default_acceptsExtension_function_type)( ::std::string const & ) const; ReaderWriter_exposer.def( "acceptsExtension" , acceptsExtension_function_type(&::osgDB::ReaderWriter::acceptsExtension) , default_acceptsExtension_function_type(&ReaderWriter_wrapper::default_acceptsExtension) , ( bp::arg("arg0") ) ); } { //::osgDB::ReaderWriter::acceptsProtocol typedef bool ( ::osgDB::ReaderWriter::*acceptsProtocol_function_type)( ::std::string const & ) const; typedef bool ( ReaderWriter_wrapper::*default_acceptsProtocol_function_type)( ::std::string const & ) const; ReaderWriter_exposer.def( "acceptsProtocol" , acceptsProtocol_function_type(&::osgDB::ReaderWriter::acceptsProtocol) , default_acceptsProtocol_function_type(&ReaderWriter_wrapper::default_acceptsProtocol) , ( bp::arg("protocol") ) ); } { //::osgDB::ReaderWriter::className typedef char const * ( ::osgDB::ReaderWriter::*className_function_type)( ) const; typedef char const * ( ReaderWriter_wrapper::*default_className_function_type)( ) const; ReaderWriter_exposer.def( "className" , className_function_type(&::osgDB::ReaderWriter::className) , default_className_function_type(&ReaderWriter_wrapper::default_className) ); } { //::osgDB::ReaderWriter::clone typedef ::osg::Object * ( ::osgDB::ReaderWriter::*clone_function_type)( ::osg::CopyOp const & ) const; typedef ::osg::Object * ( ReaderWriter_wrapper::*default_clone_function_type)( ::osg::CopyOp const & ) const; ReaderWriter_exposer.def( "clone" , clone_function_type(&::osgDB::ReaderWriter::clone) , default_clone_function_type(&ReaderWriter_wrapper::default_clone) , ( bp::arg("copyop") ) , bp::return_value_policy< bp::reference_existing_object >() ); } { //::osgDB::ReaderWriter::cloneType typedef ::osg::Object * ( ::osgDB::ReaderWriter::*cloneType_function_type)( ) const; typedef ::osg::Object * ( ReaderWriter_wrapper::*default_cloneType_function_type)( ) const; ReaderWriter_exposer.def( "cloneType" , cloneType_function_type(&::osgDB::ReaderWriter::cloneType) , default_cloneType_function_type(&ReaderWriter_wrapper::default_cloneType) , bp::return_value_policy< bp::reference_existing_object >() ); } { //::osgDB::ReaderWriter::featureAsString typedef ::std::list< std::string > ( *featureAsString_function_type )( ::osgDB::ReaderWriter::Features ); ReaderWriter_exposer.def( "featureAsString" , featureAsString_function_type( &::osgDB::ReaderWriter::featureAsString ) , ( bp::arg("feature") ) ); } { //::osgDB::ReaderWriter::fileExists typedef bool ( ::osgDB::ReaderWriter::*fileExists_function_type)( ::std::string const &,::osgDB::Options const * ) const; typedef bool ( ReaderWriter_wrapper::*default_fileExists_function_type)( ::std::string const &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "fileExists" , fileExists_function_type(&::osgDB::ReaderWriter::fileExists) , default_fileExists_function_type(&ReaderWriter_wrapper::default_fileExists) , ( bp::arg("filename"), bp::arg("options") ) ); } { //::osgDB::ReaderWriter::isSameKindAs typedef bool ( ::osgDB::ReaderWriter::*isSameKindAs_function_type)( ::osg::Object const * ) const; typedef bool ( ReaderWriter_wrapper::*default_isSameKindAs_function_type)( ::osg::Object const * ) const; ReaderWriter_exposer.def( "isSameKindAs" , isSameKindAs_function_type(&::osgDB::ReaderWriter::isSameKindAs) , default_isSameKindAs_function_type(&ReaderWriter_wrapper::default_isSameKindAs) , ( bp::arg("obj") ) ); } { //::osgDB::ReaderWriter::libraryName typedef char const * ( ::osgDB::ReaderWriter::*libraryName_function_type)( ) const; typedef char const * ( ReaderWriter_wrapper::*default_libraryName_function_type)( ) const; ReaderWriter_exposer.def( "libraryName" , libraryName_function_type(&::osgDB::ReaderWriter::libraryName) , default_libraryName_function_type(&ReaderWriter_wrapper::default_libraryName) ); } { //::osgDB::ReaderWriter::openArchive typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*openArchive_function_type)( ::std::string const &,::osgDB::ReaderWriter::ArchiveStatus,unsigned int,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_openArchive_function_type)( ::std::string const &,::osgDB::ReaderWriter::ArchiveStatus,unsigned int,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "openArchive" , openArchive_function_type(&::osgDB::ReaderWriter::openArchive) , default_openArchive_function_type(&ReaderWriter_wrapper::default_openArchive) , ( bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=(unsigned int)(4096), bp::arg("arg3")=bp::object() ) ); } { //::osgDB::ReaderWriter::openArchive typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*openArchive_function_type)( ::std::istream &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_openArchive_function_type)( ::std::istream &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "openArchive" , openArchive_function_type(&::osgDB::ReaderWriter::openArchive) , default_openArchive_function_type(&ReaderWriter_wrapper::default_openArchive) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readHeightField typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readHeightField_function_type)( ::std::string const &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readHeightField_function_type)( ::std::string const &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readHeightField" , readHeightField_function_type(&::osgDB::ReaderWriter::readHeightField) , default_readHeightField_function_type(&ReaderWriter_wrapper::default_readHeightField) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readHeightField typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readHeightField_function_type)( ::std::istream &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readHeightField_function_type)( ::std::istream &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readHeightField" , readHeightField_function_type(&::osgDB::ReaderWriter::readHeightField) , default_readHeightField_function_type(&ReaderWriter_wrapper::default_readHeightField) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readImage typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readImage_function_type)( ::std::string const &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readImage_function_type)( ::std::string const &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readImage" , readImage_function_type(&::osgDB::ReaderWriter::readImage) , default_readImage_function_type(&ReaderWriter_wrapper::default_readImage) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readImage typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readImage_function_type)( ::std::istream &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readImage_function_type)( ::std::istream &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readImage" , readImage_function_type(&::osgDB::ReaderWriter::readImage) , default_readImage_function_type(&ReaderWriter_wrapper::default_readImage) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readNode typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readNode_function_type)( ::std::string const &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readNode_function_type)( ::std::string const &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readNode" , readNode_function_type(&::osgDB::ReaderWriter::readNode) , default_readNode_function_type(&ReaderWriter_wrapper::default_readNode) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readNode typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readNode_function_type)( ::std::istream &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readNode_function_type)( ::std::istream &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readNode" , readNode_function_type(&::osgDB::ReaderWriter::readNode) , default_readNode_function_type(&ReaderWriter_wrapper::default_readNode) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readObject typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readObject_function_type)( ::std::string const &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readObject_function_type)( ::std::string const &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readObject" , readObject_function_type(&::osgDB::ReaderWriter::readObject) , default_readObject_function_type(&ReaderWriter_wrapper::default_readObject) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readObject typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readObject_function_type)( ::std::istream &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readObject_function_type)( ::std::istream &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readObject" , readObject_function_type(&::osgDB::ReaderWriter::readObject) , default_readObject_function_type(&ReaderWriter_wrapper::default_readObject) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readShader typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readShader_function_type)( ::std::string const &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readShader_function_type)( ::std::string const &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readShader" , readShader_function_type(&::osgDB::ReaderWriter::readShader) , default_readShader_function_type(&ReaderWriter_wrapper::default_readShader) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::readShader typedef ::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReaderWriter::*readShader_function_type)( ::std::istream &,::osgDB::Options const * ) const; typedef ::osgDB::ReaderWriter::ReadResult ( ReaderWriter_wrapper::*default_readShader_function_type)( ::std::istream &,::osgDB::Options const * ) const; ReaderWriter_exposer.def( "readShader" , readShader_function_type(&::osgDB::ReaderWriter::readShader) , default_readShader_function_type(&ReaderWriter_wrapper::default_readShader) , ( bp::arg("arg0"), bp::arg("arg1")=bp::object() ) ); } { //::osgDB::ReaderWriter::supportedExtensions typedef ::std::map< std::string, std::string > const & ( ::osgDB::ReaderWriter::*supportedExtensions_function_type)( ) const; ReaderWriter_exposer.def( "supportedExtensions" , supportedExtensions_function_type(&::osgDB::ReaderWriter::supportedExtensions) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::supportedFeatures typedef ::osgDB::ReaderWriter::Features ( ::osgDB::ReaderWriter::*supportedFeatures_function_type)( ) const; typedef ::osgDB::ReaderWriter::Features ( ReaderWriter_wrapper::*default_supportedFeatures_function_type)( ) const; ReaderWriter_exposer.def( "supportedFeatures" , supportedFeatures_function_type(&::osgDB::ReaderWriter::supportedFeatures) , default_supportedFeatures_function_type(&ReaderWriter_wrapper::default_supportedFeatures) ); } { //::osgDB::ReaderWriter::supportedOptions typedef ::std::map< std::string, std::string > const & ( ::osgDB::ReaderWriter::*supportedOptions_function_type)( ) const; ReaderWriter_exposer.def( "supportedOptions" , supportedOptions_function_type(&::osgDB::ReaderWriter::supportedOptions) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::supportedProtocols typedef ::std::map< std::string, std::string > const & ( ::osgDB::ReaderWriter::*supportedProtocols_function_type)( ) const; ReaderWriter_exposer.def( "supportedProtocols" , supportedProtocols_function_type(&::osgDB::ReaderWriter::supportedProtocols) , bp::return_internal_reference< >() ); } { //::osgDB::ReaderWriter::supportsExtension typedef void ( ::osgDB::ReaderWriter::*supportsExtension_function_type)( ::std::string const &,::std::string const & ) ; ReaderWriter_exposer.def( "supportsExtension" , supportsExtension_function_type( &::osgDB::ReaderWriter::supportsExtension ) , ( bp::arg("ext"), bp::arg("description") ) ); } { //::osgDB::ReaderWriter::supportsOption typedef void ( ::osgDB::ReaderWriter::*supportsOption_function_type)( ::std::string const &,::std::string const & ) ; ReaderWriter_exposer.def( "supportsOption" , supportsOption_function_type( &::osgDB::ReaderWriter::supportsOption ) , ( bp::arg("opt"), bp::arg("description") ) ); } { //::osgDB::ReaderWriter::supportsProtocol typedef void ( ::osgDB::ReaderWriter::*supportsProtocol_function_type)( ::std::string const &,::std::string const & ) ; ReaderWriter_exposer.def( "supportsProtocol" , supportsProtocol_function_type( &::osgDB::ReaderWriter::supportsProtocol ) , ( bp::arg("fmt"), bp::arg("description") ) ); } { //::osgDB::ReaderWriter::writeHeightField typedef boost::python::object ( *default_writeHeightField_function_type )( ::osgDB::ReaderWriter const &,::osg::HeightField &,::std::string const &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeHeightField" , default_writeHeightField_function_type( &ReaderWriter_wrapper::default_writeHeightField_492ba9227016a7cdc011f560ee63846b ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeHeightField typedef boost::python::object ( *default_writeHeightField_function_type )( ::osgDB::ReaderWriter const &,::osg::HeightField &,::std::ostream &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeHeightField" , default_writeHeightField_function_type( &ReaderWriter_wrapper::default_writeHeightField_9396c211b31e432102458b3f4acc5b01 ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeImage typedef boost::python::object ( *default_writeImage_function_type )( ::osgDB::ReaderWriter const &,::osg::Image &,::std::string const &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeImage" , default_writeImage_function_type( &ReaderWriter_wrapper::default_writeImage_48409f166d256ec2a1ce1aba7ba91b41 ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeImage typedef boost::python::object ( *default_writeImage_function_type )( ::osgDB::ReaderWriter const &,::osg::Image &,::std::ostream &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeImage" , default_writeImage_function_type( &ReaderWriter_wrapper::default_writeImage_09e0c822c73aac048a8706dbb950438f ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeNode typedef boost::python::object ( *default_writeNode_function_type )( ::osgDB::ReaderWriter const &,::osg::Node &,::std::string const &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeNode" , default_writeNode_function_type( &ReaderWriter_wrapper::default_writeNode_94ab5d58c5431145dd0b29259e29a1e0 ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeNode typedef boost::python::object ( *default_writeNode_function_type )( ::osgDB::ReaderWriter const &,::osg::Node &,::std::ostream &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeNode" , default_writeNode_function_type( &ReaderWriter_wrapper::default_writeNode_85ada25f9394d5ca11dce46130e109e3 ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeObject typedef boost::python::object ( *default_writeObject_function_type )( ::osgDB::ReaderWriter const &,::osg::Object &,::std::string const &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeObject" , default_writeObject_function_type( &ReaderWriter_wrapper::default_writeObject_4b217c12bc66236059a76e176772f392 ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeObject typedef boost::python::object ( *default_writeObject_function_type )( ::osgDB::ReaderWriter const &,::osg::Object &,::std::ostream &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeObject" , default_writeObject_function_type( &ReaderWriter_wrapper::default_writeObject_86a17357be0e1c05716ddbecef039a10 ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeShader typedef boost::python::object ( *default_writeShader_function_type )( ::osgDB::ReaderWriter const &,::osg::Shader &,::std::string const &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeShader" , default_writeShader_function_type( &ReaderWriter_wrapper::default_writeShader_be57249f6a6e741afc4665bd121f54f9 ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } { //::osgDB::ReaderWriter::writeShader typedef boost::python::object ( *default_writeShader_function_type )( ::osgDB::ReaderWriter const &,::osg::Shader &,::std::ostream &,::osgDB::Options const * ); ReaderWriter_exposer.def( "writeShader" , default_writeShader_function_type( &ReaderWriter_wrapper::default_writeShader_88038c79c30b9deaaaed55931fcd9f34 ) , ( bp::arg("inst"), bp::arg("arg0"), bp::arg("arg1"), bp::arg("arg2")=bp::object() ) ); } ReaderWriter_exposer.staticmethod( "featureAsString" ); } }
50.847433
254
0.587384
[ "object" ]
a9c1da563d4ebd6816640f2d3bfe6a2fd5b3b56b
6,902
cpp
C++
src/common/Misc/Camera.cpp
whatevermarch/Cauldron
b3a4f62bf79034240b979d575e67ee51790ab435
[ "MIT" ]
1
2021-10-13T06:15:46.000Z
2021-10-13T06:15:46.000Z
src/common/Misc/Camera.cpp
whatevermarch/Cauldron
b3a4f62bf79034240b979d575e67ee51790ab435
[ "MIT" ]
null
null
null
src/common/Misc/Camera.cpp
whatevermarch/Cauldron
b3a4f62bf79034240b979d575e67ee51790ab435
[ "MIT" ]
null
null
null
// AMD Cauldron code // // Copyright(c) 2020 Advanced Micro Devices, Inc.All rights reserved. // 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 "stdafx.h" #include "Camera.h" Camera::Camera() { m_View = XMMatrixIdentity(); m_eyePos = XMVectorSet(0, 0, 0, 0); m_distance = -1; } //-------------------------------------------------------------------------------------- // // OnCreate // //-------------------------------------------------------------------------------------- void Camera::SetFov(float fovV, uint32_t width, uint32_t height, float nearPlane, float farPlane) { m_aspectRatio = width * 1.f / height; m_near = nearPlane; m_far = farPlane; m_fovV = fovV; m_fovH = std::min<float>((m_fovV * width) / height, XM_PI / 2.0f); m_fovV = m_fovH * height / width; float halfWidth = (float)width / 2.0f; float halfHeight = (float)height / 2.0f; m_Viewport = XMMATRIX( halfWidth, 0.0f, 0.0f, 0.0f, 0.0f, -halfHeight, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, halfWidth, halfHeight, 0.0f, 1.0f); if (fovV==0) m_Proj = XMMatrixOrthographicRH(height/40.0f, height/40.0f, nearPlane, farPlane); else m_Proj = XMMatrixPerspectiveFovRH(fovV, m_aspectRatio, nearPlane, farPlane); } void Camera::SetMatrix(const XMMATRIX cameraMatrix) { m_eyePos = cameraMatrix.r[3]; m_View = XMMatrixInverse(nullptr, cameraMatrix); XMFLOAT3 zBasis; XMStoreFloat3(&zBasis, cameraMatrix.r[2]); m_yaw = atan2f(zBasis.x, zBasis.z); float fLen = sqrtf(zBasis.z * zBasis.z + zBasis.x * zBasis.x); m_pitch = atan2f(zBasis.y, fLen); } //-------------------------------------------------------------------------------------- // // LookAt, use this functions before calling update functions // //-------------------------------------------------------------------------------------- void Camera::LookAt(XMVECTOR eyePos, XMVECTOR lookAt) { m_eyePos = eyePos; m_View = LookAtRH(eyePos, lookAt); m_distance = XMVectorGetX(XMVector3Length(lookAt - eyePos)); XMMATRIX mInvView = XMMatrixInverse( nullptr, m_View ); XMFLOAT3 zBasis; XMStoreFloat3( &zBasis, mInvView.r[2] ); m_yaw = atan2f( zBasis.x, zBasis.z ); float fLen = sqrtf( zBasis.z * zBasis.z + zBasis.x * zBasis.x ); m_pitch = atan2f( zBasis.y, fLen ); } void Camera::LookAt(float yaw, float pitch, float distance, XMVECTOR at ) { LookAt(at + PolarToVector(yaw, pitch)*distance, at); } //-------------------------------------------------------------------------------------- // // UpdateCamera // //-------------------------------------------------------------------------------------- void Camera::UpdateCameraWASD(float yaw, float pitch, const bool keyDown[256], double deltaTime) { m_eyePos += XMVector4Transform(MoveWASD(keyDown) * m_speed * (float)deltaTime, XMMatrixTranspose(m_View)); XMVECTOR dir = PolarToVector(yaw, pitch) * m_distance; LookAt(GetPosition(), GetPosition() - dir); } void Camera::UpdateCameraPolar(float yaw, float pitch, float x, float y, float distance) { pitch = std::max(-XM_PIDIV2 + 1e-6f, std::min(pitch, XM_PIDIV2 - 1e-6f)); // Trucks camera, moves the camera parallel to the view plane. m_eyePos += GetSide() * x * distance / 10.0f; m_eyePos += GetUp() * y * distance / 10.0f; // Orbits camera, rotates a camera about the target XMVECTOR dir = GetDirection(); XMVECTOR pol = PolarToVector(yaw, pitch); XMVECTOR at = m_eyePos - dir * m_distance; LookAt(at + pol * distance, at); } //-------------------------------------------------------------------------------------- // // SetProjectionJitter // //-------------------------------------------------------------------------------------- void Camera::SetProjectionJitter(float jitterX, float jitterY) { XMFLOAT4X4 Proj; XMStoreFloat4x4(&Proj, m_Proj); Proj.m[2][0] = jitterX; Proj.m[2][1] = jitterY; m_Proj = XMLoadFloat4x4(&Proj); } void Camera::SetProjectionJitter(uint32_t width, uint32_t height, uint32_t &sampleIndex) { static const auto CalculateHaltonNumber = [](uint32_t index, uint32_t base) { float f = 1.0f, result = 0.0f; for (uint32_t i = index; i > 0;) { f /= static_cast<float>(base); result = result + f * static_cast<float>(i % base); i = static_cast<uint32_t>(floorf(static_cast<float>(i) / static_cast<float>(base))); } return result; }; sampleIndex = (sampleIndex + 1) % 16; // 16x TAA float jitterX = 2.0f * CalculateHaltonNumber(sampleIndex + 1, 2) - 1.0f; float jitterY = 2.0f * CalculateHaltonNumber(sampleIndex + 1, 3) - 1.0f; jitterX /= static_cast<float>(width); jitterY /= static_cast<float>(height); SetProjectionJitter(jitterX, jitterY); } //-------------------------------------------------------------------------------------- // // Get a vector pointing in the direction of yaw and pitch // //-------------------------------------------------------------------------------------- XMVECTOR PolarToVector(float yaw, float pitch) { return XMVectorSet(sinf(yaw) * cosf(pitch), sinf(pitch), cosf(yaw) * cosf(pitch), 0); } XMMATRIX LookAtRH(XMVECTOR eyePos, XMVECTOR lookAt) { return XMMatrixLookAtRH(eyePos, lookAt, XMVectorSet(0, 1, 0, 0)); } XMVECTOR MoveWASD(const bool keyDown[256]) { float scale = keyDown[VK_SHIFT] ? 5.0f : 1.0f; float x = 0, y = 0, z = 0; if (keyDown['W']) { z = -scale; } if (keyDown['S']) { z = scale; } if (keyDown['A']) { x = -scale; } if (keyDown['D']) { x = scale; } if (keyDown['E']) { y = scale; } if (keyDown['Q']) { y = -scale; } return XMVectorSet(x, y, z, 0.0f); }
31.953704
110
0.56998
[ "vector" ]
a9c1e7b251639a2907c75e72dd400c616a057c5a
1,912
hh
C++
cc/reference-panel-plot.hh
acorg/acmacs-draw
b570149453724929d3468d6814475014291d2c97
[ "MIT" ]
null
null
null
cc/reference-panel-plot.hh
acorg/acmacs-draw
b570149453724929d3468d6814475014291d2c97
[ "MIT" ]
null
null
null
cc/reference-panel-plot.hh
acorg/acmacs-draw
b570149453724929d3468d6814475014291d2c97
[ "MIT" ]
null
null
null
#include "acmacs-base/color.hh" #include "acmacs-base/size-scale.hh" #include "acmacs-chart-2/reference-panel-plot-data.hh" // ---------------------------------------------------------------------- namespace acmacs { class PointCoordinates; namespace surface { class Surface; } } // namespace acmacs namespace acmacs::draw { class ReferencePanelPlot { public: struct Parameters { std::string title{"*title*"}; mutable double hstep{1}; mutable double vstep{1}; double title_scale{0.1}; // relative to image width double cell_label_scale{2.0}; double cell_titer_scale{1.5}; double cell_padding_scale{2.0}; std::vector<std::string> titer_levels{"5", "10", "20", "40", "80", "160", "320", "640", "1280", "2560", "5120", "10240", "20480", "40960"}; Color color_median{0x00CD00}; Color color_next_to_median{0xCDCD00}; Color color_other{RED}; }; void plot(std::string_view output_filename, const chart::ReferencePanelPlotData::ASTable& as_table) const; Parameters& parameters() { return parameters_; } private: Parameters parameters_; void plot_cell(surface::Surface& cell_surface, const chart::ReferencePanelPlotData::AntigenSerumData& cell, std::string_view antigen_name, std::string_view serum_name) const; void text(surface::Surface& aSurface, const PointCoordinates& aOffset, std::string_view aText, Color aColor, Rotation aRotation, double aFontSize, double aMaxWidth) const; Color titer_color(double titer_logged, double median_titer_logged) const; }; } // namespace acmacs::draw // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
32.40678
182
0.596757
[ "vector" ]
a9c3141ba9911f12d53ba721ea9b0eacbf0274a0
16,279
cpp
C++
l2a/src/l2a_plugin.cpp
latex2ai/LaTeX2AI
b5c0db97017536b86b162bce2067a6fd8ba203df
[ "MIT" ]
13
2021-12-09T13:38:38.000Z
2022-03-23T14:57:10.000Z
l2a/src/l2a_plugin.cpp
latex2ai/LaTeX2AI
b5c0db97017536b86b162bce2067a6fd8ba203df
[ "MIT" ]
5
2021-11-11T10:11:42.000Z
2022-03-31T09:49:29.000Z
l2a/src/l2a_plugin.cpp
latex2ai/LaTeX2AI
b5c0db97017536b86b162bce2067a6fd8ba203df
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------- // MIT License // // Copyright (c) 2020 Ivo Steinbrecher // // 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. // ----------------------------------------------------------------------------- /** * \brief Define a class that represents this plugin. */ #include "IllustratorSDK.h" #include "SDKErrors.h" #include "AIMenuCommandNotifiers.h" #include "l2a_constants.h" #include "l2a_plugin.h" #include "l2a_error/l2a_error.h" #include "l2a_global/l2a_global.h" #include "l2a_item/l2a_item.h" #include "l2a_ai_functions/l2a_ai_functions.h" #include "l2a_annotator/l2a_annotator.h" #include "tests/testing.h" /** */ Plugin* AllocatePlugin(SPPluginRef pluginRef) { return new L2APlugin(pluginRef); } /** */ void FixupReload(Plugin* plugin) { L2APlugin::FixupVTable((L2APlugin*)plugin); } /* */ L2APlugin::L2APlugin(SPPluginRef pluginRef) : Plugin(pluginRef), fNotifySelectionChanged(nullptr), fNotifyDocumentSave(nullptr), fNotifyDocumentSaveAs(nullptr), fNotifyDocumentOpened(nullptr), fResourceManagerHandle(nullptr) { // Set the name that of this plugin in Illustrator. strncpy(fPluginName, L2A_PLUGIN_NAME, kMaxStringLength); } /* * */ ASErr L2APlugin::Notify(AINotifierMessage* message) { ASErr error = kNoErr; try { if (message->notifier == fNotifySelectionChanged) { // Selection of art items changed in the document. // Invalidate the entire document view bounds. annotator_->InvalAnnotation(); // If the annotator is active, update the item vector. annotator_->ArtSelectionChanged(); // Check if there is a single isolated l2a item. AIArtHandle placed_item; if (L2A::AI::GetSingleIsolationItem(placed_item)) { // Create Item and change it's contents. L2A::Item change_item(placed_item); change_item.Change(); } } else if (message->notifier == fNotifyDocumentOpened || message->notifier == fNotifyDocumentSave || message->notifier == fNotifyDocumentSaveAs) { L2A::AI::UndoActivate(); L2A::CheckItemDataStructure(); } } catch (L2A::ERR::Exception&) { sAIUser->MessageAlert(ai::UnicodeString("L2APlugin::Notify Error caught.")); } // Check which tool is selected. AIToolHandle selected_tool; sAITool->GetSelectedTool(&selected_tool); if (fToolHandle.size() > 0 && (selected_tool == fToolHandle[1] || selected_tool == fToolHandle[2] || selected_tool == fToolHandle[3])) { // The redo item is selected. Since this only acts as button we want to deselect the tool here. error = sAITool->SetSelectedToolByName(kSelectTool); l2a_check_ai_error(error); } return error; } /* */ ASErr L2APlugin::Message(char* caller, char* selector, void* message) { ASErr error = kNoErr; try { // Call the message method of the base class to access mouse events e.t.c. error = Plugin::Message(caller, selector, message); if (error == kUnhandledMsgErr) { if (strcmp(caller, kCallerAIAnnotation) == 0) { if (strcmp(selector, kSelectorAIDrawAnnotation) == 0) // Draw the l2a annotator. annotator_->Draw((AIAnnotatorMessage*)message); else if (strcmp(selector, kSelectorAIInvalAnnotation) == 0) // Invalidate the annotator. // TODO: maybe this function call can be removed. Check if it is called at all / what the given // invalidate box actually is. annotator_->InvalAnnotation((AIAnnotatorMessage*)message); } } else aisdk::check_ai_error(error); } catch (ai::Error& ex) { error = ex; } catch (...) { error = kCantHappenErr; } return error; } /* */ ASErr L2APlugin::StartupPlugin(SPInterfaceMessage* message) { ASErr error = kNoErr; try { ai::int32 pluginOptions = 0; // We need to call the base startup method to avoid memory leaks when closing the plugin. error = Plugin::StartupPlugin(message); aisdk::check_ai_error(error); error = sAIPlugin->GetPluginOptions(message->d.self, &pluginOptions); aisdk::check_ai_error(error); error = sAIPlugin->SetPluginOptions(message->d.self, pluginOptions | kPluginWantsResultsAutoSelectedOption); aisdk::check_ai_error(error); // Set the global l2a object. This object should only be used with the Get functions in L2A. L2A::GLOBAL::_l2a_global = new L2A::GLOBAL::Global(); L2A::GlobalMutable().SetUp(); if (L2A::Global().IsSetup()) { error = AddNotifier(message); aisdk::check_ai_error(error); error = AddTools(message); aisdk::check_ai_error(error); error = AddAnnotator(message); aisdk::check_ai_error(error); #ifdef _DEBUG // In the debug mode perform all unit tests at startup. static const bool print_status = false; L2A::TEST::TestingMain(print_status); #endif } } catch (ai::Error& ex) { error = ex; } catch (...) { error = kCantHappenErr; } return error; } /* */ ASErr L2APlugin::ShutdownPlugin(SPInterfaceMessage* message) { ASErr error = kNoErr; try { // If it was created, delete the global object. if (L2A::GLOBAL::_l2a_global != nullptr) delete L2A::GLOBAL::_l2a_global; // Dereference the annotator -> the object will be delete here, otherwise we would have a memory leak later. annotator_ = nullptr; // We need to call the base shutdown method to avoid memory leaks when closing the plugin. error = Plugin::ShutdownPlugin(message); aisdk::check_ai_error(error); } catch (ai::Error& ex) { error = ex; } catch (...) { error = kCantHappenErr; } return error; } /* */ ASErr L2APlugin::ToolMouseDown(AIToolMessage* message) { ASErr error = kNoErr; if (message->tool == this->fToolHandle[0]) { // Selected tool is item create. try { if (annotator_->IsArtHit()) { ai::UnicodeString undo_string("Undo Change LaTeX2AI item"); ai::UnicodeString redo_string("Redo Change LaTeX2AI item"); sAIUndo->SetUndoTextUS(undo_string, redo_string); // Get the existing item and change it. L2A::Item hit_item(annotator_->GetArtHit()); hit_item.Change(); } else { // Check if the current insertion point is locked. if (!L2A::AI::GetLockedInsertionPoint()) { ai::UnicodeString undo_string("Undo Create LaTeX2AI item"); ai::UnicodeString redo_string("Redo Create LaTeX2AI item"); sAIUndo->SetUndoTextUS(undo_string, redo_string); // Create am item at the clicked position. L2A::Item(message->cursor); } else sAIUser->MessageAlert( ai::UnicodeString("You tried to create a LaTeX2AI item inside a locked or hidden layer / " "group. This is not possible.")); } } catch (L2A::ERR::Exception&) { sAIUser->MessageAlert(ai::UnicodeString("L2APlugin::ToolMouseDown Error caught.")); } } return error; } /* */ ASErr L2APlugin::AddTools(SPInterfaceMessage* message) { AIErr error = kNoErr; // Set the number of tools. #ifdef _DEBUG static const unsigned int n_tools = 5; #else static const unsigned int n_tools = 4; #endif // Data used to add tool. AIAddToolData data; // General options for the tool. ai::int32 options = kToolWantsToTrackCursorOption; // Define the name and icon for the tools. char toolGroupName[256]; std::vector<char*> toolTitleStr = {"LaTeX2AI create edit mode", "LaTeX2AI redo items", "LaTeX2AI options", "LaTeX2AI save to PDF", "Perform LaTeX2AI Tests"}; std::vector<char*> toolTipStr = { "LaTeX2AI create edit mode: Create a new LaTeX2AI item, or edit and existing item by clicking on it.", // "LaTeX2AI redo items: Redo multiple items in this document.", // "LaTeX2AI options: Set local and global options for LaTeX2AI", // "LaTeX2AI save to PDF: Save a copy of the current Illustrator file to a pdf file with the same name.", // "Perform certain tests to ensure LaTeX2AI is working as expected."}; // Define icons. std::vector<ai::uint32> light_icon_id = {TOOL_ICON_CREATE_LIGHT_ID, TOOL_ICON_REDO_LIGHT_ID, TOOL_ICON_OPTIONS_LIGHT_ID, TOOL_ICON_SAVE_AS_PDF_LIGHT_ID, TOOL_ICON_TESTING_LIGHT_ID}; std::vector<ai::uint32> dark_icon_id = {TOOL_ICON_CREATE_DARK_ID, TOOL_ICON_REDO_DARK_ID, TOOL_ICON_OPTIONS_DARK_ID, TOOL_ICON_SAVE_AS_PDF_DARK_ID, TOOL_ICON_TESTING_DARK_ID}; // Create all tools. fToolHandle.resize(n_tools); for (short i = 0; i < n_tools; i++) { // Define the name and icon for the tool. #if kPluginInterfaceVersion >= 0x23000001 data.title = ai::UnicodeString(toolTitleStr[i]); data.tooltip = ai::UnicodeString(toolTipStr[i]); #else data.title = toolTitleStr[i]; data.tooltip = toolTipStr[i]; #endif data.normalIconResID = light_icon_id[i]; data.darkIconResID = dark_icon_id[i]; if (i == 0) { // The first tool creates a new tool palette. strcpy(toolGroupName, toolTitleStr[i]); // New group on tool palette. data.sameGroupAs = kNoTool; } else { error = sAITool->GetToolNumberFromName(toolGroupName, &data.sameGroupAs); l2a_check_ai_error(error); } // Each tool icon is on its own. data.sameToolsetAs = kNoTool; // Add the tool. #if kPluginInterfaceVersion >= 0x23000001 error = sAITool->AddTool(message->d.self, toolTitleStr[i], data, options, &fToolHandle[i]); #else error = sAITool->AddTool(message->d.self, toolTitleStr[i], &data, options, &fToolHandle[i]); #endif l2a_check_ai_error(error); } return error; } /** * */ ASErr L2APlugin::AddAnnotator(SPInterfaceMessage* message) { ASErr result = kNoErr; try { annotator_ = std::make_unique<L2A::Annotator>(message); } catch (ai::Error& ex) { result = ex; } catch (...) { result = kCantHappenErr; } return result; } /* * */ ASErr L2APlugin::AddNotifier(SPInterfaceMessage* /*message*/) { ASErr result = kNoErr; try { result = sAINotifier->AddNotifier( fPluginRef, L2A_PLUGIN_NAME, kAIArtSelectionChangedNotifier, &fNotifySelectionChanged); aisdk::check_ai_error(result); result = sAINotifier->AddNotifier(fPluginRef, L2A_PLUGIN_NAME, kAISaveCommandPreNotifierStr, &fNotifyDocumentSave); aisdk::check_ai_error(result); aisdk::check_ai_error(result); result = sAINotifier->AddNotifier( fPluginRef, L2A_PLUGIN_NAME, kAISaveAsCommandPostNotifierStr, &fNotifyDocumentSaveAs); aisdk::check_ai_error(result); result = sAINotifier->AddNotifier(fPluginRef, L2A_PLUGIN_NAME, kAIDocumentOpenedNotifier, &fNotifyDocumentOpened); aisdk::check_ai_error(result); } catch (ai::Error& ex) { result = ex; } catch (...) { result = kCantHappenErr; } return result; } /** * */ ASErr L2APlugin::SelectTool(AIToolMessage* message) { AIErr error = kNoErr; if (message->tool == this->fToolHandle[0]) { // Create / edit tool is selected. // Activate the annotator. annotator_->SetAnnotatorActive(); } else if (message->tool == this->fToolHandle[1] && L2A::AI::GetDocumentCount() > 0) { // Activate undo. ai::UnicodeString undo_string("Undo Update LaTeX2AI item"); ai::UnicodeString redo_string("Redo Update LaTeX2AI item"); sAIUndo->SetUndoTextUS(undo_string, redo_string); L2A::AI::UndoActivate(); // Redo tool is selected. L2A::RedoItems(); // Deselect all so a call to the plugin will be given, where the tools can be deselected. error = sAIMatchingArt->DeselectAll(); l2a_check_ai_error(error); } else if (message->tool == this->fToolHandle[2]) { // Open the global options dialog. L2A::GlobalMutable().SetFromUserForm(); // If a document is opend, deselect all artwork so a call to the plugin will be given, where the tools can be // deselected. And the selection tool will be activated. if (L2A::AI::GetDocumentCount() > 0) { error = sAIMatchingArt->DeselectAll(); l2a_check_ai_error(error); } } else if (message->tool == this->fToolHandle[3] && L2A::AI::GetDocumentCount() > 0) { L2A::AI::SaveToPDF(); // Deselect all so a call to the plugin will be given, where the tools can be deselected. error = sAIMatchingArt->DeselectAll(); l2a_check_ai_error(error); } #ifdef _DEBUG else if (message->tool == this->fToolHandle[4]) { // Test the LaTeX2AI framework. L2A::TEST::TestFramework(); } #endif return error; } /** * */ ASErr L2APlugin::DeselectTool(AIToolMessage*) { ASErr result = kNoErr; try { // Deactivate the annotator annotator_->SetAnnotatorInactive(); } catch (ai::Error& ex) { result = ex; } catch (...) { result = kCantHappenErr; } return result; } /** * */ ASErr L2APlugin::TrackToolCursor(AIToolMessage* message) { AIErr error = kNoErr; if (message->tool == this->fToolHandle[0]) { // Create edit mode is active. // Check if cursor is over an art item. ai::int32 cursor_id; if (annotator_->CheckForArtHit(message)) cursor_id = CURSOR_ICON_EDIT; else { if (L2A::AI::GetLockedInsertionPoint()) cursor_id = CURSOR_ICON_LOCKED; else cursor_id = CURSOR_ICON_CREATE; } error = sAIUser->SetCursor(cursor_id, fResourceManagerHandle); l2a_check_ai_error(error); } return error; } /** * */ ASErr L2APlugin::PostStartupPlugin() { AIErr result = kNoErr; result = sAIUser->CreateCursorResourceMgr(fPluginRef, &fResourceManagerHandle); return result; }
30.090573
120
0.608207
[ "object", "vector" ]
a9c3838bd9a68582da97612a41442be17a9356a0
4,498
cpp
C++
src/uscxml/plugins/datamodel/ecmascript/v8/dom/V8DOMImplementation.cpp
sradomski/uscxml
b8ba0e7c31f397a66f9d509ff20a85b33619475a
[ "W3C", "BSD-2-Clause" ]
null
null
null
src/uscxml/plugins/datamodel/ecmascript/v8/dom/V8DOMImplementation.cpp
sradomski/uscxml
b8ba0e7c31f397a66f9d509ff20a85b33619475a
[ "W3C", "BSD-2-Clause" ]
null
null
null
src/uscxml/plugins/datamodel/ecmascript/v8/dom/V8DOMImplementation.cpp
sradomski/uscxml
b8ba0e7c31f397a66f9d509ff20a85b33619475a
[ "W3C", "BSD-2-Clause" ]
null
null
null
/** * @file * @author This file has been generated by generate-bindings.pl. DO NOT MODIFY! * @copyright Simplified BSD * * @cond * This program is free software: you can redistribute it and/or modify * it under the terms of the FreeBSD license as published by the FreeBSD * project. * * 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. * * You should have received a copy of the FreeBSD license along with this * program. If not, see <http://www.opensource.org/licenses/bsd-license>. * @endcond */ #include "V8DOMImplementation.h" #include "V8Document.h" #include "V8DocumentType.h" namespace Arabica { namespace DOM { v8::Persistent<v8::FunctionTemplate> V8DOMImplementation::Tmpl; v8::Handle<v8::Value> V8DOMImplementation::hasFeatureCallback(const v8::Arguments& args) { v8::Local<v8::Object> self = args.Holder(); struct V8DOMImplementationPrivate* privData = V8DOM::toClassPtr<V8DOMImplementationPrivate >(self->GetInternalField(0)); if (false) { } else if (args.Length() == 2 && args[0]->IsString() && args[1]->IsString()) { v8::String::AsciiValue localFeature(args[0]); v8::String::AsciiValue localVersion(args[1]); bool retVal = privData->nativeObj->hasFeature(*localFeature, *localVersion); return v8::Boolean::New(retVal); } throw V8Exception("Parameter mismatch while calling hasFeature"); return v8::Undefined(); } v8::Handle<v8::Value> V8DOMImplementation::createDocumentTypeCallback(const v8::Arguments& args) { v8::Local<v8::Object> self = args.Holder(); struct V8DOMImplementationPrivate* privData = V8DOM::toClassPtr<V8DOMImplementationPrivate >(self->GetInternalField(0)); if (false) { } else if (args.Length() == 3 && args[0]->IsString() && args[1]->IsString() && args[2]->IsString()) { v8::String::AsciiValue localQualifiedName(args[0]); v8::String::AsciiValue localPublicId(args[1]); v8::String::AsciiValue localSystemId(args[2]); Arabica::DOM::DocumentType<std::string>* retVal = new Arabica::DOM::DocumentType<std::string>(privData->nativeObj->createDocumentType(*localQualifiedName, *localPublicId, *localSystemId)); v8::Handle<v8::Function> retCtor = V8DocumentType::getTmpl()->GetFunction(); v8::Persistent<v8::Object> retObj = v8::Persistent<v8::Object>::New(retCtor->NewInstance()); struct V8DocumentType::V8DocumentTypePrivate* retPrivData = new V8DocumentType::V8DocumentTypePrivate(); retPrivData->dom = privData->dom; retPrivData->nativeObj = retVal; retObj->SetInternalField(0, V8DOM::toExternal(retPrivData)); retObj.MakeWeak(0, V8DocumentType::jsDestructor); return retObj; } throw V8Exception("Parameter mismatch while calling createDocumentType"); return v8::Undefined(); } v8::Handle<v8::Value> V8DOMImplementation::createDocumentCallback(const v8::Arguments& args) { v8::Local<v8::Object> self = args.Holder(); struct V8DOMImplementationPrivate* privData = V8DOM::toClassPtr<V8DOMImplementationPrivate >(self->GetInternalField(0)); if (false) { } else if (args.Length() == 3 && args[0]->IsString() && args[1]->IsString() && args[2]->IsObject() && V8DocumentType::hasInstance(args[2])) { v8::String::AsciiValue localNamespaceURI(args[0]); v8::String::AsciiValue localQualifiedName(args[1]); Arabica::DOM::DocumentType<std::string>* localDoctype = V8DOM::toClassPtr<V8DocumentType::V8DocumentTypePrivate >(args[2]->ToObject()->GetInternalField(0))->nativeObj; Arabica::DOM::Document<std::string>* retVal = new Arabica::DOM::Document<std::string>(privData->nativeObj->createDocument(*localNamespaceURI, *localQualifiedName, *localDoctype)); v8::Handle<v8::Function> retCtor = V8Document::getTmpl()->GetFunction(); v8::Persistent<v8::Object> retObj = v8::Persistent<v8::Object>::New(retCtor->NewInstance()); struct V8Document::V8DocumentPrivate* retPrivData = new V8Document::V8DocumentPrivate(); retPrivData->dom = privData->dom; retPrivData->nativeObj = retVal; retObj->SetInternalField(0, V8DOM::toExternal(retPrivData)); retObj.MakeWeak(0, V8Document::jsDestructor); return retObj; } throw V8Exception("Parameter mismatch while calling createDocument"); return v8::Undefined(); } bool V8DOMImplementation::hasInstance(v8::Handle<v8::Value> value) { return getTmpl()->HasInstance(value); } } }
39.113043
190
0.721432
[ "object" ]
a9c5aecc62ac94dd3755af8b48ddc5b1a32580ea
1,979
cpp
C++
cpp-leetcode/leetcode103-zigzag-traverse_deque.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
45
2021-07-25T00:45:43.000Z
2022-03-24T05:10:43.000Z
cpp-leetcode/leetcode103-zigzag-traverse_deque.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
null
null
null
cpp-leetcode/leetcode103-zigzag-traverse_deque.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
15
2021-07-25T00:40:52.000Z
2021-12-27T06:25:31.000Z
#include <iostream> #include <vector> #include <deque> #include <algorithm> using namespace std; /** * Definition for a binary tree node. */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { if (!root) return {}; if (root->left == nullptr && root->right == nullptr) return {{root->val}}; vector<vector<int>> res; deque<TreeNode*> q {root}; while (!q.empty()) { vector<int> curLevel; for (int i = q.size() ; i > 0; --i) { TreeNode* p = q.front(); q.pop_front(); curLevel.push_back(p->val); if (p->left != nullptr) q.push_back(p->left); if (p->right != nullptr) q.push_back(p->right); } res.push_back(curLevel); } for (int i = 0; i < res.size(); i++) { vector<int> curLevel = res[i]; if (i % 2 == 1) { reverse(curLevel.begin(), curLevel.end()); res[i] = curLevel; } } return res; } }; // Test int main() { Solution sol; TreeNode* root = new TreeNode(3); root->left = new TreeNode(9); root->right = new TreeNode(20); root->right->left = new TreeNode(15); root->right->left->left = nullptr; root->right->left->right = nullptr; root->right->right = new TreeNode(7); root->right->right->left = nullptr; root->right->right->right = nullptr; vector<vector<int>> res = sol.zigzagLevelOrder(root); return 0; }
27.486111
90
0.498737
[ "vector" ]
a9cbc4c04bb07a6977df72c8b3fe751e021269b0
2,693
hpp
C++
src/ui/toast.hpp
mrichards42/remarkable_puzzles
5d2fe96e7f17229e3039cb5d72d1947af6cc7a34
[ "MIT" ]
8
2021-01-14T16:07:05.000Z
2021-12-07T11:35:31.000Z
src/ui/toast.hpp
mrichards42/remarkable_puzzles
5d2fe96e7f17229e3039cb5d72d1947af6cc7a34
[ "MIT" ]
15
2021-01-14T21:00:03.000Z
2022-01-04T04:09:12.000Z
src/ui/toast.hpp
mrichards42/remarkable_puzzles
5d2fe96e7f17229e3039cb5d72d1947af6cc7a34
[ "MIT" ]
2
2021-01-14T20:56:15.000Z
2021-03-04T19:59:13.000Z
#ifndef RMP_TOAST_HPP #define RMP_TOAST_HPP #include <string> #include <vector> #include <rmkit.h> #include "ui/util.hpp" class Toast : public ui::Widget { public: std::string text; remarkable_color color; ui::TimerPtr timer; int last_x = -1, last_y, last_w, last_h; Toast(int x, int y, int w, int h, remarkable_color color = color::GRAY_6) : ui::Widget(x, y, w, h), color(color) { set_style(ui::Stylesheet().justify_center()); hide(); } void show(const std::string & text, int timeout = 3000) { this->text = text; dirty = 1; if (timer) ui::cancel_timer(timer); timer = ui::set_timeout([=]() { if (visible && ui::MainLoop::is_visible(this)) { hide(); fb->draw_rect(last_x, last_y, last_w, last_h, WHITE); ui::MainLoop::refresh(); ui::MainLoop::redraw(); } }, timeout); // Clear the previous bounding box if we're still shown. if (last_x > -1) fb->draw_rect(last_x, last_y, last_w, last_h, WHITE); ui::Widget::show(); } void render() { auto old_dither = fb->dither; fb->dither = framebuffer::DITHER::BAYER_2; // Measure each line's width int font_size = style.font_size; int line_height = stbtext::get_line_height(font_size) * style.line_height; int max_width = 0; std::vector<std::string> lines = split_lines(text); std::vector<int> widths; for (auto line : lines) { image_data image = stbtext::get_text_size(line, font_size); widths.push_back(image.w); max_width = std::max(max_width, image.w); } // Draw background int x = this->x + (this->w - max_width) / 2; fb->draw_rect(x, y, max_width, lines.size() * line_height, WHITE); // Save the current bounding box for when we are hidden. last_x = x; last_y = y; last_w = max_width; last_h = this->h = line_height * lines.size(); // Draw text for (size_t i = 0; i < lines.size(); i++) { const std::string & line = lines[i]; int width = widths[i]; int dx = 0; if (style.justify == ui::Style::JUSTIFY::RIGHT) dx = max_width - width; else if (style.justify == ui::Style::JUSTIFY::CENTER) dx = (max_width - width) / 2; draw_colored_text(fb, x + dx, y + line_height * i, line.c_str(), font_size, color); } fb->dither = old_dither; } }; #endif // RMP_TOAST_HPP
29.271739
95
0.539918
[ "render", "vector" ]
a9cbc565aa454befbea5bea1e57640a82fa94cab
3,649
cc
C++
test/unit/core/algorithm_test.cc
BJackal/biodynamo_singularity
f2224b434b65e1d3f7e4cf154fbedad7e3cda40b
[ "Apache-2.0" ]
57
2016-02-12T13:30:13.000Z
2022-03-11T16:24:07.000Z
test/unit/core/algorithm_test.cc
BJackal/biodynamo_singularity
f2224b434b65e1d3f7e4cf154fbedad7e3cda40b
[ "Apache-2.0" ]
66
2016-06-23T08:47:52.000Z
2022-03-28T16:44:38.000Z
test/unit/core/algorithm_test.cc
BJackal/biodynamo_singularity
f2224b434b65e1d3f7e4cf154fbedad7e3cda40b
[ "Apache-2.0" ]
53
2016-06-06T13:11:26.000Z
2022-03-11T15:13:22.000Z
// ----------------------------------------------------------------------------- // // // Copyright (C) 2021 CERN & University of Surrey for the benefit of the // BioDynaMo collaboration. 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. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #include "core/algorithm.h" #include <gtest/gtest.h> #include <vector> namespace bdm { // ----------------------------------------------------------------------------- void CalcExpected(std::vector<uint64_t>* v) { for (uint64_t i = 1; i < v->size(); ++i) { (*v)[i] += (*v)[i - 1]; } } // ----------------------------------------------------------------------------- TEST(InPlaceParallelPrefixSum, Empty) { std::vector<uint64_t> v{}; decltype(v) expected = v; InPlaceParallelPrefixSum(v, v.size()); CalcExpected(&expected); EXPECT_EQ(expected, v); } // ----------------------------------------------------------------------------- TEST(InPlaceParallelPrefixSum, Size1) { std::vector<uint64_t> v{3}; decltype(v) expected = v; InPlaceParallelPrefixSum(v, v.size()); CalcExpected(&expected); EXPECT_EQ(expected, v); } // ----------------------------------------------------------------------------- TEST(InPlaceParallelPrefixSum, MultipleOf2) { std::vector<uint64_t> v{0, 1, 2, 3, 4, 5, 6, 7}; decltype(v) expected = v; InPlaceParallelPrefixSum(v, v.size()); CalcExpected(&expected); EXPECT_EQ(expected, v); } // ----------------------------------------------------------------------------- TEST(InPlaceParallelPrefixSum, Size9) { std::vector<uint64_t> v{0, 1, 2, 3, 4, 5, 6, 7, 8}; decltype(v) expected = v; InPlaceParallelPrefixSum(v, v.size()); CalcExpected(&expected); EXPECT_EQ(expected, v); } // ----------------------------------------------------------------------------- TEST(ExclusivePrefixSum, Size1) { std::vector<uint64_t> v{3}; decltype(v) expected{0}; ExclusivePrefixSum(&v, v.size() - 1); EXPECT_EQ(expected, v); } // ----------------------------------------------------------------------------- TEST(ExclusivePrefixSum, Size9) { std::vector<uint64_t> v{1, 2, 3, 4, 5, 6, 7, 0}; decltype(v) expected{0, 1, 3, 6, 10, 15, 21, 28}; ExclusivePrefixSum(&v, v.size() - 1); EXPECT_EQ(expected, v); } // ----------------------------------------------------------------------------- TEST(BinarySearch, Exact) { std::vector<uint64_t> v = {0, 1, 2, 3, 4, 5}; for (uint64_t i = 0; i < v.size(); ++i) { EXPECT_EQ(i, BinarySearch(i, v, 0, v.size() - 1)); } } // ----------------------------------------------------------------------------- TEST(BinarySearch, NoExactMatch) { std::vector<uint64_t> v = {2, 4, 6}; EXPECT_EQ(0u, BinarySearch(1u, v, 0, v.size() - 1)); EXPECT_EQ(0u, BinarySearch(3u, v, 0, v.size() - 1)); EXPECT_EQ(1u, BinarySearch(5u, v, 0, v.size() - 1)); } // ----------------------------------------------------------------------------- TEST(BinarySearch, Duplicates) { std::vector<uint64_t> v = {1, 1, 1, 1, 2, 2, 2, 3, 3, 4}; EXPECT_EQ(0u, BinarySearch(0u, v, 0, v.size() - 1)); EXPECT_EQ(3u, BinarySearch(1u, v, 0, v.size() - 1)); EXPECT_EQ(6u, BinarySearch(2u, v, 0, v.size() - 1)); EXPECT_EQ(8u, BinarySearch(3u, v, 0, v.size() - 1)); EXPECT_EQ(9u, BinarySearch(4u, v, 0, v.size() - 1)); } } // namespace bdm
32.873874
80
0.475473
[ "vector" ]
a9cc175d60bd38b3db482e25dbfe49855f75eff1
1,179
hpp
C++
libs/sprite/include/sge/sprite/compare/textures.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/sprite/include/sge/sprite/compare/textures.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/sprite/include/sge/sprite/compare/textures.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// 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) #ifndef SGE_SPRITE_COMPARE_TEXTURES_HPP_INCLUDED #define SGE_SPRITE_COMPARE_TEXTURES_HPP_INCLUDED #include <sge/sprite/object_fwd.hpp> #include <sge/sprite/compare/detail/textures.hpp> #include <sge/sprite/detail/config/has_texture.hpp> #include <sge/sprite/detail/config/texture_levels.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace sge::sprite::compare { struct textures { template <typename Choices> using is_trivial = std::false_type; using result_type = bool; template <typename Choices> inline std::enable_if_t<sge::sprite::detail::config::has_texture<Choices>::value, result_type> operator()( sge::sprite::object<Choices> const &_left, sge::sprite::object<Choices> const &_right) const { return sge::sprite::compare::detail::textures< sge::sprite::detail::config::texture_levels<Choices>::value>::execute(_left, _right); } }; } #endif
29.475
98
0.742154
[ "object" ]
a9cc48ddf6271facc1067e7b6250006d717826a6
541
hpp
C++
Board.hpp
ronsider/messageboard-b
352ad0b488b6f94fe5328ceb314ecb3fe5310ea4
[ "MIT" ]
null
null
null
Board.hpp
ronsider/messageboard-b
352ad0b488b6f94fe5328ceb314ecb3fe5310ea4
[ "MIT" ]
null
null
null
Board.hpp
ronsider/messageboard-b
352ad0b488b6f94fe5328ceb314ecb3fe5310ea4
[ "MIT" ]
null
null
null
#pragma once #include <string> #include<vector> #include "Direction.hpp" namespace ariel { class Board { private: std::vector<std::vector<char>> vec; public: Board() { std::vector<std::vector<char>>temp(9999,std::vector<char>(9999,'_'));//A 9999X9999 board vec=temp; } void post(unsigned int a,unsigned int b,Direction dir,const std::string &str);// std::string read(unsigned int a,unsigned int b,Direction dir,unsigned int c);// std::string show();// }; }
20.807692
96
0.604436
[ "vector" ]
a9cf0cb152551cf18ec979234c08b19613166d1d
1,704
cpp
C++
Day_01/01_Sort_Colors.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_01/01_Sort_Colors.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_01/01_Sort_Colors.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
// Problem Link: // https://leetcode.com/problems/sort-colors/ // Approach 1: (Count Sort) // TC: O(2*n) // SC: O(1) // Approach 2: (Dutch Flag Algorithm) // TC: O(n) // SC: O(1) #include <bits/stdc++.h> using namespace std; #define ll long long #define deb(x) cout << #x << ": " << x << "\n" void sortColors1(vector<int> &nums) { // Data structures vector<int> count(3, 0); // Traversing and finding count for (int i : nums) count[i]++; // Traversing and setting the value int itr{0}; while (count[0]) { nums[itr] = 0; count[0]--; itr++; } while (count[1]) { nums[itr] = 1; count[1]--; itr++; } while (count[2]) { nums[itr] = 2; count[2]--; itr++; } } void sortColors2(vector<int> &nums) { // Data Structures int low = 0, mid = 0, high = nums.size() - 1; // Looping until mid <= high while (mid <= high) { if (nums[mid] == 0) { swap(nums[low], nums[mid]); low++; mid++; } else if (nums[mid] == 1) mid++; else if (nums[mid] == 2) { swap(nums[mid], nums[high]); high--; } } } void solve() { vector<int> nums{2, 0, 2, 1, 1, 0}; sortColors1(nums); for (auto i : nums) cout << i << " "; cout << endl; nums = {2, 0, 2, 1, 1, 0}; sortColors2(nums); for (auto i : nums) cout << i << " "; cout << endl; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t{1}; // cin >> t; while (t--) solve(); return 0; }
17.04
58
0.450704
[ "vector" ]
a9d2a71039b16b4b0e4926ab4cf3810a93a4895b
10,098
cpp
C++
src/graphics/vulkan/swapchain_init.cpp
InspectorSolaris/nd-engine
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
[ "WTFPL" ]
null
null
null
src/graphics/vulkan/swapchain_init.cpp
InspectorSolaris/nd-engine
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
[ "WTFPL" ]
null
null
null
src/graphics/vulkan/swapchain_init.cpp
InspectorSolaris/nd-engine
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
[ "WTFPL" ]
null
null
null
#include "swapchain_init.hpp" #include "tools_runtime.hpp" namespace nd::src::graphics::vulkan { using namespace nd::src::tools; u32 getNextImageIndex(const VkDevice device, const VkSwapchainKHR swapchain, const VkSemaphore semaphore, const VkFence fence, const u64 timeout) noexcept(ND_VK_ASSERT_NOTHROW) { ND_SET_SCOPE(); u32 index; ND_VK_ASSERT(vkAcquireNextImageKHR(device, swapchain, timeout, semaphore, fence, &index)); return index; } vec<Image> getSwapchainImages(const VkDevice device, const VkSwapchainKHR swapchain) noexcept(ND_VK_ASSERT_NOTHROW) { ND_SET_SCOPE(); u32 count; ND_VK_ASSERT(vkGetSwapchainImagesKHR(device, swapchain, &count, nullptr)); auto images = vec<Image>(count); ND_VK_ASSERT(vkGetSwapchainImagesKHR(device, swapchain, &count, images.data())); return images; } vec<VkSurfaceFormatKHR> getSurfaceFormats(const VkPhysicalDevice physicalDevice, const VkSurfaceKHR surface) noexcept(ND_VK_ASSERT_NOTHROW) { ND_SET_SCOPE(); u32 count; ND_VK_ASSERT(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &count, nullptr)); auto formats = vec<VkSurfaceFormatKHR>(count); ND_VK_ASSERT(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &count, formats.data())); return formats; } vec<VkPresentModeKHR> getSurfacePresentModes(const VkPhysicalDevice physicalDevice, const VkSurfaceKHR surface) noexcept(ND_VK_ASSERT_NOTHROW) { ND_SET_SCOPE(); u32 count; ND_VK_ASSERT(vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &count, nullptr)); auto presentModes = vec<VkPresentModeKHR>(count); ND_VK_ASSERT(vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &count, presentModes.data())); return presentModes; } VkSurfaceCapabilitiesKHR getSurfaceCapabilities(const VkPhysicalDevice physicalDevice, const VkSurfaceKHR surface) noexcept(ND_VK_ASSERT_NOTHROW) { ND_SET_SCOPE(); VkSurfaceCapabilitiesKHR capabilities; ND_VK_ASSERT(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &capabilities)); return capabilities; } bool isSurfaceQueueFamilySupported(const VkPhysicalDevice physicalDevice, const VkSurfaceKHR surface, const QueueFamily& queueFamily) noexcept(ND_VK_ASSERT_NOTHROW) { ND_SET_SCOPE(); VkBool32 supported; ND_VK_ASSERT(vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamily.index, surface, &supported)); return supported; } bool isSwapchainImageFormatSupported(opt<const SwapchainCfg>::ref cfg, const vec<VkSurfaceFormatKHR>& formats) noexcept { ND_SET_SCOPE(); return std::any_of(formats.begin(), formats.end(), [&cfg](const auto format) { return format.format == cfg.imageFormat && format.colorSpace == cfg.imageColorSpace; }); } bool isSwapchainImageUsageSupported(opt<const SwapchainCfg>::ref cfg, const VkSurfaceCapabilitiesKHR& capabilities) noexcept { ND_SET_SCOPE(); return isContainsAll(capabilities.supportedUsageFlags, cfg.imageUsage); } bool isSwapchainTransformSupported(opt<const SwapchainCfg>::ref cfg, const VkSurfaceCapabilitiesKHR& capabilities) noexcept { ND_SET_SCOPE(); return isContainsAny(capabilities.supportedTransforms, cfg.transform); } bool isSwapchainCompositeAlphaSupported(opt<const SwapchainCfg>::ref cfg, const VkSurfaceCapabilitiesKHR& capabilities) noexcept { ND_SET_SCOPE(); return isContainsAny(capabilities.supportedCompositeAlpha, cfg.compositeAlpha); } bool isSwapchainPresentModeSupported(opt<const SwapchainCfg>::ref cfg, const vec<VkPresentModeKHR>& presentModes) noexcept { ND_SET_SCOPE(); return std::any_of(presentModes.begin(), presentModes.end(), [&cfg](const auto presentMode) { return presentMode == cfg.presentMode; }); } u32 getSwapchainImageCount(opt<const SwapchainCfg>::ref cfg, const VkSurfaceCapabilitiesKHR& capabilities) noexcept { ND_SET_SCOPE(); return capabilities.maxImageCount ? std::clamp(cfg.imageCount + 1, capabilities.minImageCount, capabilities.maxImageCount) : std::min(capabilities.minImageCount, cfg.imageCount + 1); } u32 getSwapchainImageArrayLayers(opt<const SwapchainCfg>::ref cfg, const VkSurfaceCapabilitiesKHR& capabilities) noexcept { ND_SET_SCOPE(); return std::min(cfg.imageArrayLayers, capabilities.maxImageArrayLayers); } VkExtent2D getSwapchainImageExtent(opt<const SwapchainCfg>::ref cfg, const VkSurfaceCapabilitiesKHR& capabilities) noexcept { ND_SET_SCOPE(); const auto anyExtent = capabilities.currentExtent.width == 0xFFFFFFFF && capabilities.currentExtent.height == 0xFFFFFFFF; return anyExtent ? VkExtent2D {std::clamp(cfg.imageExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width), std::clamp(cfg.imageExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height)} : capabilities.currentExtent; } Swapchain createSwapchain(opt<const SwapchainCfg>::ref cfg, const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW&& ND_ASSERT_NOTHROW) { ND_SET_SCOPE(); const auto formats = getSurfaceFormats(cfg.physicalDevice, cfg.surface); const auto presentModes = getSurfacePresentModes(cfg.physicalDevice, cfg.surface); const auto capabilities = getSurfaceCapabilities(cfg.physicalDevice, cfg.surface); ND_ASSERT(isSurfaceQueueFamilySupported(cfg.physicalDevice, cfg.surface, cfg.queueFamily.graphics)); ND_ASSERT(isSwapchainImageFormatSupported(cfg, formats)); ND_ASSERT(isSwapchainImageUsageSupported(cfg, capabilities)); ND_ASSERT(isSwapchainTransformSupported(cfg, capabilities)); ND_ASSERT(isSwapchainCompositeAlphaSupported(cfg, capabilities)); ND_ASSERT(isSwapchainPresentModeSupported(cfg, presentModes)); const auto imageCount = getSwapchainImageCount(cfg, capabilities); const auto imageArrayLayers = getSwapchainImageArrayLayers(cfg, capabilities); const auto imageExtent = getSwapchainImageExtent(cfg, capabilities); const auto queueFamilyIndices = array {static_cast<u32>(cfg.queueFamily.graphics.index)}; const auto createInfo = VkSwapchainCreateInfoKHR { .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .pNext = cfg.next, .flags = cfg.flags, .surface = cfg.surface, .minImageCount = imageCount, .imageFormat = cfg.imageFormat, .imageColorSpace = cfg.imageColorSpace, .imageExtent = imageExtent, .imageArrayLayers = imageArrayLayers, .imageUsage = cfg.imageUsage, .imageSharingMode = queueFamilyIndices.size() <= 1 ? VK_SHARING_MODE_EXCLUSIVE : VK_SHARING_MODE_CONCURRENT, .queueFamilyIndexCount = queueFamilyIndices.size(), .pQueueFamilyIndices = queueFamilyIndices.data(), .preTransform = cfg.transform, .compositeAlpha = cfg.compositeAlpha, .presentMode = cfg.presentMode, .clipped = cfg.clipped, .oldSwapchain = VK_NULL_HANDLE}; VkSwapchainKHR swapchain; ND_VK_ASSERT(vkCreateSwapchainKHR(device, &createInfo, ND_VK_ALLOCATION_CALLBACKS, &swapchain)); return {.queueFamily = cfg.queueFamily.graphics, .handle = swapchain, .width = static_cast<u16>(cfg.imageExtent.width), .height = static_cast<u16>(cfg.imageExtent.height)}; } vec<ImageView> createSwapchainImageViews(opt<const ImageViewCfg>::ref cfg, const VkDevice device, const vec<VkImage>& swapchainImages) noexcept(ND_VK_ASSERT_NOTHROW&& ND_ASSERT_NOTHROW) { ND_SET_SCOPE(); return getMapped<Image, ImageView>(swapchainImages, [&cfg, device](const auto swapchainImage, const auto index) { return createImageView(cfg, device, swapchainImage); }); } vec<Framebuffer> createSwapchainFramebuffers(opt<const FramebufferCfg>::ref cfg, const VkDevice device, const vec<VkImageView>& swapchainImageViews) noexcept(ND_VK_ASSERT_NOTHROW&& ND_ASSERT_NOTHROW) { ND_SET_SCOPE(); return getMapped<ImageView, Framebuffer>(swapchainImageViews, [&cfg, device](const auto swapchainImageView, const auto index) { return createFramebuffer(cfg, device, {swapchainImageView}); }); } } // namespace nd::src::graphics::vulkan
39.291829
146
0.623292
[ "transform" ]
a9d2e573f339d29f1a121d3a4508c4256805486e
7,078
cpp
C++
modules/gapi/test/gapi_desc_tests.cpp
ghennadii/opencv
c6a4bad3692e62ff6733fe98f51b557d75ce65a0
[ "BSD-3-Clause" ]
4
2019-03-04T05:47:18.000Z
2019-06-24T08:14:43.000Z
modules/gapi/test/gapi_desc_tests.cpp
ghennadii/opencv
c6a4bad3692e62ff6733fe98f51b557d75ce65a0
[ "BSD-3-Clause" ]
2
2019-03-23T03:53:50.000Z
2019-03-23T03:53:52.000Z
modules/gapi/test/gapi_desc_tests.cpp
ghennadii/opencv
c6a4bad3692e62ff6733fe98f51b557d75ce65a0
[ "BSD-3-Clause" ]
2
2019-07-21T08:20:06.000Z
2020-08-09T06:07:37.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #include "test_precomp.hpp" #include "opencv2/gapi/cpu/gcpukernel.hpp" namespace opencv_test { namespace { G_TYPED_KERNEL(KTest, <cv::GScalar(cv::GScalar)>, "org.opencv.test.scalar_kernel") { static cv::GScalarDesc outMeta(cv::GScalarDesc in) { return in; } }; GAPI_OCV_KERNEL(GOCVScalarTest, KTest) { static void run(const cv::Scalar &in, cv::Scalar &out) { out = in+cv::Scalar(1); } }; } TEST(GAPI_MetaDesc, MatDesc) { cv::Mat m1(240, 320, CV_8U); const auto desc1 = cv::descr_of(m1); EXPECT_EQ(CV_8U, desc1.depth); EXPECT_EQ(1, desc1.chan); EXPECT_EQ(320, desc1.size.width); EXPECT_EQ(240, desc1.size.height); cv::Mat m2(480, 640, CV_8UC3); const auto desc2 = cv::descr_of(m2); EXPECT_EQ(CV_8U, desc2.depth); EXPECT_EQ(3, desc2.chan); EXPECT_EQ(640, desc2.size.width); EXPECT_EQ(480, desc2.size.height); } TEST(GAPI_MetaDesc, VecMatDesc) { std::vector<cv::Mat> vec1 = { cv::Mat(240, 320, CV_8U)}; const auto desc1 = cv::descr_of(vec1); EXPECT_EQ((GMatDesc{CV_8U, 1, {320, 240}}), get<GMatDesc>(desc1[0])); std::vector<cv::UMat> vec2 = { cv::UMat(480, 640, CV_8UC3)}; const auto desc2 = cv::descr_of(vec2); EXPECT_EQ((GMatDesc{CV_8U, 3, {640, 480}}), get<GMatDesc>(desc2[0])); } TEST(GAPI_MetaDesc, VecOwnMatDesc) { std::vector<cv::gapi::own::Mat> vec = { cv::gapi::own::Mat(240, 320, CV_8U, nullptr), cv::gapi::own::Mat(480, 640, CV_8UC3, nullptr)}; const auto desc = cv::gapi::own::descr_of(vec); EXPECT_EQ((GMatDesc{CV_8U, 1, {320, 240}}), get<GMatDesc>(desc[0])); EXPECT_EQ((GMatDesc{CV_8U, 3, {640, 480}}), get<GMatDesc>(desc[1])); } TEST(GAPI_MetaDesc, AdlVecOwnMatDesc) { std::vector<cv::gapi::own::Mat> vec = { cv::gapi::own::Mat(240, 320, CV_8U, nullptr), cv::gapi::own::Mat(480, 640, CV_8UC3, nullptr)}; const auto desc = descr_of(vec); EXPECT_EQ((GMatDesc{CV_8U, 1, {320, 240}}), get<GMatDesc>(desc[0])); EXPECT_EQ((GMatDesc{CV_8U, 3, {640, 480}}), get<GMatDesc>(desc[1])); } TEST(GAPI_MetaDesc, Compare_Equal_MatDesc) { const auto desc1 = cv::GMatDesc{CV_8U, 1, {64, 64}}; const auto desc2 = cv::GMatDesc{CV_8U, 1, {64, 64}}; EXPECT_TRUE(desc1 == desc2); } TEST(GAPI_MetaDesc, Compare_Not_Equal_MatDesc) { const auto desc1 = cv::GMatDesc{CV_8U, 1, {64, 64}}; const auto desc2 = cv::GMatDesc{CV_32F, 1, {64, 64}}; EXPECT_TRUE(desc1 != desc2); } TEST(GAPI_MetaDesc, Compile_MatchMetaNumber_1) { cv::GMat in; cv::GComputation cc(in, in+in); const auto desc1 = cv::GMatDesc{CV_8U,1,{64,64}}; const auto desc2 = cv::GMatDesc{CV_32F,1,{128,128}}; EXPECT_NO_THROW(cc.compile(desc1)); EXPECT_NO_THROW(cc.compile(desc2)); // FIXME: custom exception type? // It is worth checking if compilation fails with different number // of meta parameters EXPECT_THROW(cc.compile(desc1, desc1), std::logic_error); EXPECT_THROW(cc.compile(desc1, desc2, desc2), std::logic_error); } TEST(GAPI_MetaDesc, Compile_MatchMetaNumber_2) { cv::GMat a, b; cv::GComputation cc(cv::GIn(a, b), cv::GOut(a+b)); const auto desc1 = cv::GMatDesc{CV_8U,1,{64,64}}; EXPECT_NO_THROW(cc.compile(desc1, desc1)); const auto desc2 = cv::GMatDesc{CV_32F,1,{128,128}}; EXPECT_NO_THROW(cc.compile(desc2, desc2)); // FIXME: custom exception type? EXPECT_THROW(cc.compile(desc1), std::logic_error); EXPECT_THROW(cc.compile(desc2), std::logic_error); EXPECT_THROW(cc.compile(desc2, desc2, desc2), std::logic_error); } TEST(GAPI_MetaDesc, Compile_MatchMetaType_Mat) { cv::GMat in; cv::GComputation cc(in, in+in); EXPECT_NO_THROW(cc.compile(cv::GMatDesc{CV_8U,1,{64,64}})); // FIXME: custom exception type? EXPECT_THROW(cc.compile(cv::empty_scalar_desc()), std::logic_error); } TEST(GAPI_MetaDesc, Compile_MatchMetaType_Scalar) { cv::GScalar in; cv::GComputation cc(cv::GIn(in), cv::GOut(KTest::on(in))); const auto desc1 = cv::descr_of(cv::Scalar(128)); const auto desc2 = cv::GMatDesc{CV_8U,1,{64,64}}; const auto pkg = cv::gapi::kernels<GOCVScalarTest>(); EXPECT_NO_THROW(cc.compile(desc1, cv::compile_args(pkg))); // FIXME: custom exception type? EXPECT_THROW(cc.compile(desc2, cv::compile_args(pkg)), std::logic_error); } TEST(GAPI_MetaDesc, Compile_MatchMetaType_Mixed) { cv::GMat a; cv::GScalar v; cv::GComputation cc(cv::GIn(a, v), cv::GOut(cv::gapi::addC(a, v))); const auto desc1 = cv::GMatDesc{CV_8U,1,{64,64}}; const auto desc2 = cv::descr_of(cv::Scalar(4)); EXPECT_NO_THROW(cc.compile(desc1, desc2)); // FIXME: custom exception type(s)? EXPECT_THROW(cc.compile(desc1), std::logic_error); EXPECT_THROW(cc.compile(desc2), std::logic_error); EXPECT_THROW(cc.compile(desc2, desc1), std::logic_error); EXPECT_THROW(cc.compile(desc1, desc1, desc1), std::logic_error); EXPECT_THROW(cc.compile(desc1, desc2, desc1), std::logic_error); } TEST(GAPI_MetaDesc, Typed_Compile_MatchMetaNumber_1) { cv::GComputationT<cv::GMat(cv::GMat)> cc([](cv::GMat in) { return in+in; }); const auto desc1 = cv::GMatDesc{CV_8U,1,{64,64}}; const auto desc2 = cv::GMatDesc{CV_32F,1,{128,128}}; EXPECT_NO_THROW(cc.compile(desc1)); EXPECT_NO_THROW(cc.compile(desc2)); } TEST(GAPI_MetaDesc, Typed_Compile_MatchMetaNumber_2) { cv::GComputationT<cv::GMat(cv::GMat,cv::GMat)> cc([](cv::GMat a, cv::GMat b) { return a + b; }); const auto desc1 = cv::GMatDesc{CV_8U,1,{64,64}}; EXPECT_NO_THROW(cc.compile(desc1, desc1)); const auto desc2 = cv::GMatDesc{CV_32F,1,{128,128}}; EXPECT_NO_THROW(cc.compile(desc2, desc2)); } TEST(GAPI_MetaDesc, Typed_Compile_MatchMetaType_Mat) { cv::GComputationT<cv::GMat(cv::GMat)> cc([](cv::GMat in) { return in+in; }); EXPECT_NO_THROW(cc.compile(cv::GMatDesc{CV_8U,1,{64,64}})); } TEST(GAPI_MetaDesc, Typed_Compile_MatchMetaType_Scalar) { cv::GComputationT<cv::GScalar(cv::GScalar)> cc([](cv::GScalar in) { return KTest::on(in); }); const auto desc1 = cv::descr_of(cv::Scalar(128)); const auto pkg = cv::gapi::kernels<GOCVScalarTest>(); // EXPECT_NO_THROW(cc.compile(desc1, cv::compile_args(pkg))); cc.compile(desc1, cv::compile_args(pkg)); } TEST(GAPI_MetaDesc, Typed_Compile_MatchMetaType_Mixed) { cv::GComputationT<cv::GMat(cv::GMat,cv::GScalar)> cc([](cv::GMat a, cv::GScalar v) { return cv::gapi::addC(a, v); }); const auto desc1 = cv::GMatDesc{CV_8U,1,{64,64}}; const auto desc2 = cv::descr_of(cv::Scalar(4)); EXPECT_NO_THROW(cc.compile(desc1, desc2)); } } // namespace opencv_test
29.491667
90
0.64976
[ "vector" ]
a9d2f74258aa452cc83250c4addb05a846cab3d5
9,488
cc
C++
test/server/admin/stats_handler_speed_test.cc
sergiitk/envoy
fa99ae02afda16ecdfe993d57d57e733e6d63d06
[ "Apache-2.0" ]
1
2022-03-02T14:23:12.000Z
2022-03-02T14:23:12.000Z
test/server/admin/stats_handler_speed_test.cc
sergiitk/envoy
fa99ae02afda16ecdfe993d57d57e733e6d63d06
[ "Apache-2.0" ]
153
2021-10-04T04:32:48.000Z
2022-03-31T04:22:40.000Z
test/server/admin/stats_handler_speed_test.cc
sergiitk/envoy
fa99ae02afda16ecdfe993d57d57e733e6d63d06
[ "Apache-2.0" ]
1
2021-12-14T02:39:44.000Z
2021-12-14T02:39:44.000Z
// Note: this should be run with --compilation_mode=opt, and would benefit from a // quiescent system with disabled cstate power management. #include "source/common/buffer/buffer_impl.h" #include "source/common/http/header_map_impl.h" #include "source/common/stats/custom_stat_namespaces_impl.h" #include "source/common/stats/thread_local_store.h" #include "source/server/admin/stats_handler.h" #include "test/test_common/test_runtime.h" #include "benchmark/benchmark.h" namespace Envoy { namespace Server { class StatsHandlerTest { public: StatsHandlerTest() : alloc_(symbol_table_), store_(alloc_) { // Benchmark will be 10k clusters each with 100 counters, with 100+ // character names. The first counter in each scope will be given a value so // it will be included in 'usedonly'. const std::string prefix(100, 'a'); for (uint32_t s = 0; s < 10000; ++s) { Stats::ScopeSharedPtr scope = store_.createScope(absl::StrCat("scope_", s)); scopes_.emplace_back(scope); for (uint32_t c = 0; c < 100; ++c) { Stats::Counter& counter = scope->counterFromString(absl::StrCat(prefix, "_", c)); if (c == 0) { counter.inc(); } } } } /** * Issues an admin request against the stats saved in store_. */ uint64_t handlerStats(const StatsParams& params) { Buffer::OwnedImpl data; if (params.format_ == Envoy::Server::StatsFormat::Prometheus) { Envoy::Server::StatsHandler::prometheusRender(store_, custom_namespaces_, params, data); return data.length(); } Admin::RequestPtr request = StatsHandler::makeRequest(store_, params); auto response_headers = Http::ResponseHeaderMapImpl::create(); request->start(*response_headers); uint64_t count = 0; bool more = true; do { more = request->nextChunk(data); count += data.length(); data.drain(data.length()); } while (more); return count; } Stats::SymbolTableImpl symbol_table_; Stats::AllocatorImpl alloc_; Stats::ThreadLocalStoreImpl store_; std::vector<Stats::ScopeSharedPtr> scopes_; Envoy::Stats::CustomStatNamespacesImpl custom_namespaces_; }; } // namespace Server } // namespace Envoy class UseRe2Filters { public: UseRe2Filters(bool use_re2) { scoped_runtime_.mergeValues( {{"envoy.reloadable_features.admin_stats_filter_use_re2", use_re2 ? "true" : "false"}}); } private: Envoy::TestScopedRuntime scoped_runtime_; }; Envoy::Server::StatsHandlerTest& testContext() { MUTABLE_CONSTRUCT_ON_FIRST_USE(Envoy::Server::StatsHandlerTest); } // NOLINTNEXTLINE(readability-identifier-naming) static void BM_AllCountersText(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); Envoy::Server::StatsParams params; for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count > 100 * 1000 * 1000, "expected count > 100M"); // actual = 117,789,000 } } BENCHMARK(BM_AllCountersText)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_UsedCountersText(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?usedonly", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count > 1000 * 1000, "expected count > 1M"); RELEASE_ASSERT(count < 2 * 1000 * 1000, "expected count < 2M"); // actual = 1,168,890 } } BENCHMARK(BM_UsedCountersText)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_FilteredCountersText(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); UseRe2Filters use_re2_filters(false); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?filter=no-match", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count == 0, "expected count == 0"); } } BENCHMARK(BM_FilteredCountersText)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_Re2FilteredCountersText(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); UseRe2Filters use_re2_filters(true); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?filter=no-match", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count == 0, "expected count == 0"); } } BENCHMARK(BM_Re2FilteredCountersText)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_AllCountersJson(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?format=json", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count > 130 * 1000 * 1000, "expected count > 130M"); // actual = 135,789,011 } } BENCHMARK(BM_AllCountersJson)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_UsedCountersJson(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?format=json&usedonly", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count > 1000 * 1000, "expected count > 1M"); RELEASE_ASSERT(count < 2 * 1000 * 1000, "expected count < 2M"); // actual = 1,348,901 } } BENCHMARK(BM_UsedCountersJson)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_FilteredCountersJson(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); UseRe2Filters use_re2_filters(false); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?format=json&filter=no-match", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count < 100, "expected count < 100"); // actual = 12 } } BENCHMARK(BM_FilteredCountersJson)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_Re2FilteredCountersJson(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); UseRe2Filters use_re2_filters(true); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?format=json&filter=no-match", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count < 100, "expected count < 100"); // actual = 12 } } BENCHMARK(BM_Re2FilteredCountersJson)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_AllCountersPrometheus(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?format=prometheus", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count > 250 * 1000 * 1000, "expected count > 250M"); // actual = 261,578,000 } } BENCHMARK(BM_AllCountersPrometheus)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_UsedCountersPrometheus(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?format=prometheus&usedonly", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count > 1000 * 1000, "expected count > 1M"); RELEASE_ASSERT(count < 3 * 1000 * 1000, "expected count < 3M"); // actual = 2,597,780 } } BENCHMARK(BM_UsedCountersPrometheus)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_FilteredCountersPrometheus(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); UseRe2Filters use_re2_filters(false); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?format=prometheus&filter=no-match", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count == 0, "expected count == 0"); } } BENCHMARK(BM_FilteredCountersPrometheus)->Unit(benchmark::kMillisecond); // NOLINTNEXTLINE(readability-identifier-naming) static void BM_Re2FilteredCountersPrometheus(benchmark::State& state) { Envoy::Server::StatsHandlerTest& test_context = testContext(); UseRe2Filters use_re2_filters(true); Envoy::Server::StatsParams params; Envoy::Buffer::OwnedImpl response; params.parse("?format=prometheus&filter=no-match", response); for (auto _ : state) { // NOLINT uint64_t count = test_context.handlerStats(params); RELEASE_ASSERT(count == 0, "expected count == 0"); } } BENCHMARK(BM_Re2FilteredCountersPrometheus)->Unit(benchmark::kMillisecond);
36.918288
96
0.729869
[ "vector" ]
a9d4c7e79e531fd1a519751cc98118fcd3cbcd99
7,745
cpp
C++
code/properties.cpp
Okityou/LessMore
cccebfe12e6f2d03e31dc536407da8a82de63f4b
[ "BSD-3-Clause" ]
232
2018-06-08T11:49:11.000Z
2022-02-02T16:17:35.000Z
code/properties.cpp
tomldh/LessMore
a9107b2765e367b6779a1edd82142651d16f3398
[ "BSD-3-Clause" ]
27
2018-06-22T04:48:44.000Z
2021-07-17T13:51:22.000Z
code/properties.cpp
tomldh/LessMore
a9107b2765e367b6779a1edd82142651d16f3398
[ "BSD-3-Clause" ]
43
2018-06-14T06:40:41.000Z
2021-12-08T08:02:27.000Z
/* Copyright (c) 2016, TU Dresden Copyright (c) 2017, Heidelberg University 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 the TU Dresden, Heidelberg 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 TU DRESDEN OR HEIDELBERG UNIVERSITY 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 "properties.h" #include "util.h" #include "thread_rand.h" #include <iostream> #include <fstream> #include <valarray> #include "generic_io.h" GlobalProperties* GlobalProperties::instance = NULL; GlobalProperties::GlobalProperties() { // testing parameters tP.sessionString = ""; tP.objScript = "train_obj.lua"; tP.scoreScript = "score_incount_ec6.lua"; tP.objModel = "obj_model_fcn_init.net"; tP.ransacIterations = 256; tP.ransacRefinementIterations = 100; tP.ransacInlierThreshold = 10; tP.randomDraw = true; //dataset parameters dP.config = "default"; dP.focalLength = 585.0f; dP.xShift = 0.f; dP.yShift = 0.f; dP.imgPadding = 4; dP.imageWidth = 640; dP.imageHeight = 480; dP.constD = 0; dP.imageSubSample = 1; dP.cnnSubSample = 8; } GlobalProperties* GlobalProperties::getInstance() { if(instance == NULL) instance = new GlobalProperties(); return instance; } bool GlobalProperties::readArguments(std::vector<std::string> argv) { int argc = argv.size(); for(int i = 0; i < argc; i++) { std::string s = argv[i]; if(s == "-iw") { i++; dP.imageWidth = std::atoi(argv[i].c_str()); std::cout << "image width: " << dP.imageWidth << "\n"; continue; } if(s == "-ih") { i++; dP.imageHeight = std::atoi(argv[i].c_str()); std::cout << "image height: " << dP.imageHeight << "\n"; continue; } if(s == "-fl") { i++; dP.focalLength = (float)std::atof(argv[i].c_str()); std::cout << "focal length: " << dP.focalLength << "\n"; continue; } if(s == "-xs") { i++; dP.xShift = (float)std::atof(argv[i].c_str()); std::cout << "x shift: " << dP.xShift << "\n"; continue; } if(s == "-ys") { i++; dP.yShift = (float)std::atof(argv[i].c_str()); std::cout << "y shift: " << dP.yShift << "\n"; continue; } if(s == "-cd") { i++; dP.constD = std::atof(argv[i].c_str()); std::cout << "const depth: " << dP.constD << "\n"; continue; } if(s == "-rdraw") { i++; tP.randomDraw = std::atoi(argv[i].c_str()); std::cout << "random draw: " << tP.randomDraw << "\n"; continue; } if(s == "-sid") { i++; tP.sessionString = argv[i]; std::cout << "session string: " << tP.sessionString << "\n"; dP.config = tP.sessionString; parseConfig(); continue; } if(s == "-oscript") { i++; tP.objScript = argv[i]; std::cout << "object script: " << tP.objScript << "\n"; continue; } if(s == "-sscript") { i++; tP.scoreScript = argv[i]; std::cout << "score script: " << tP.scoreScript << "\n"; continue; } if(s == "-omodel") { i++; tP.objModel = argv[i]; std::cout << "object model: " << tP.objModel << "\n"; continue; } if(s == "-rI") { i++; tP.ransacIterations = std::atoi(argv[i].c_str()); std::cout << "ransac iterations: " << tP.ransacIterations << "\n"; continue; } if(s == "-rT") { i++; tP.ransacInlierThreshold = (float)std::atof(argv[i].c_str()); std::cout << "ransac inlier threshold: " << tP.ransacInlierThreshold << "\n"; continue; } if(s == "-rRI") { i++; tP.ransacRefinementIterations = std::atoi(argv[i].c_str()); std::cout << "ransac iterations (refinement): " << tP.ransacRefinementIterations << "\n"; continue; } if(s == "-iSS") { i++; dP.imageSubSample = std::atoi(argv[i].c_str()); std::cout << "test image sub sampling: " << dP.imageSubSample << "\n"; continue; } if(s == "-cSS") { i++; dP.cnnSubSample = std::atoi(argv[i].c_str()); std::cout << "CNN sub sampling: " << dP.cnnSubSample << "\n"; continue; } //nothing found { std::cout << "unkown argument: " << argv[i] << "\n"; continue; } } } void GlobalProperties::parseCmdLine(int argc, const char* argv[]) { std::vector<std::string> argVec; for(int i = 1; i < argc; i++) argVec.push_back(argv[i]); readArguments(argVec); dP.imageWidth += 2 * dP.imgPadding; dP.imageHeight += 2 * dP.imgPadding; } void GlobalProperties::parseConfig() { std::string configFile = dP.config + ".config"; std::cout << BLUETEXT("Parsing config file: ") << configFile << std::endl; std::ifstream file(configFile); if(!file.is_open()) return; std::vector<std::string> argVec; std::string line; std::vector<std::string> tokens; while(true) { if(file.eof()) break; std::getline(file, line); if(line.length() == 0) continue; if(line.at(0) == '#') continue; tokens = split(line); if(tokens.empty()) continue; argVec.push_back("-" + tokens[0]); argVec.push_back(tokens[1]); } readArguments(argVec); } cv::Mat_<float> GlobalProperties::getCamMat() { float centerX = dP.imageWidth / 2 + dP.xShift; float centerY = dP.imageHeight / 2 + dP.yShift; float f = dP.focalLength; cv::Mat_<float> camMat = cv::Mat_<float>::zeros(3, 3); camMat(0, 0) = f; camMat(1, 1) = f; camMat(2, 2) = 1.f; camMat(0, 2) = centerX; camMat(1, 2) = centerY; return camMat; } static GlobalProperties* instance;
26.892361
101
0.540736
[ "object", "vector", "model" ]
a9d6240ea1c5ad250666d5d34eccec37f5bdb243
15,708
cc
C++
content/renderer/media/video_capture_impl.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
content/renderer/media/video_capture_impl.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/video_capture_impl.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:13.000Z
2020-11-04T07:24:13.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Notes about usage of this object by VideoCaptureImplManager. // // VideoCaptureImplManager access this object by using a Unretained() // binding and tasks on the IO thread. It is then important that // VideoCaptureImpl never post task to itself. All operations must be // synchronous. #include "content/renderer/media/video_capture_impl.h" #include "base/bind.h" #include "base/stl_util.h" #include "content/child/child_process.h" #include "content/common/media/video_capture_messages.h" #include "media/base/bind_to_current_loop.h" #include "media/base/limits.h" #include "media/base/video_frame.h" namespace content { class VideoCaptureImpl::ClientBuffer : public base::RefCountedThreadSafe<ClientBuffer> { public: ClientBuffer(scoped_ptr<base::SharedMemory> buffer, size_t buffer_size) : buffer(buffer.Pass()), buffer_size(buffer_size) {} const scoped_ptr<base::SharedMemory> buffer; const size_t buffer_size; private: friend class base::RefCountedThreadSafe<ClientBuffer>; virtual ~ClientBuffer() {} DISALLOW_COPY_AND_ASSIGN(ClientBuffer); }; VideoCaptureImpl::ClientInfo::ClientInfo() {} VideoCaptureImpl::ClientInfo::~ClientInfo() {} VideoCaptureImpl::VideoCaptureImpl( const media::VideoCaptureSessionId session_id, VideoCaptureMessageFilter* filter) : message_filter_(filter), device_id_(0), session_id_(session_id), suspended_(false), state_(VIDEO_CAPTURE_STATE_STOPPED), weak_factory_(this) { DCHECK(filter); thread_checker_.DetachFromThread(); } VideoCaptureImpl::~VideoCaptureImpl() { DCHECK(thread_checker_.CalledOnValidThread()); } void VideoCaptureImpl::Init() { DCHECK(thread_checker_.CalledOnValidThread()); message_filter_->AddDelegate(this); } void VideoCaptureImpl::DeInit() { DCHECK(thread_checker_.CalledOnValidThread()); if (state_ == VIDEO_CAPTURE_STATE_STARTED) Send(new VideoCaptureHostMsg_Stop(device_id_)); message_filter_->RemoveDelegate(this); } void VideoCaptureImpl::SuspendCapture(bool suspend) { DCHECK(thread_checker_.CalledOnValidThread()); suspended_ = suspend; } void VideoCaptureImpl::StartCapture( int client_id, const media::VideoCaptureParams& params, const VideoCaptureStateUpdateCB& state_update_cb, const VideoCaptureDeliverFrameCB& deliver_frame_cb) { DCHECK(thread_checker_.CalledOnValidThread()); ClientInfo client_info; client_info.params = params; client_info.state_update_cb = state_update_cb; client_info.deliver_frame_cb = deliver_frame_cb; if (state_ == VIDEO_CAPTURE_STATE_ERROR) { state_update_cb.Run(VIDEO_CAPTURE_STATE_ERROR); } else if (clients_pending_on_filter_.count(client_id) || clients_pending_on_restart_.count(client_id) || clients_.count(client_id)) { LOG(FATAL) << "This client has already started."; } else if (!device_id_) { clients_pending_on_filter_[client_id] = client_info; } else { // Note: |state_| might not be started at this point. But we tell // client that we have started. state_update_cb.Run(VIDEO_CAPTURE_STATE_STARTED); if (state_ == VIDEO_CAPTURE_STATE_STARTED) { clients_[client_id] = client_info; // TODO(sheu): Allowing resolution change will require that all // outstanding clients of a capture session support resolution change. DCHECK_EQ(params_.allow_resolution_change, params.allow_resolution_change); } else if (state_ == VIDEO_CAPTURE_STATE_STOPPING) { clients_pending_on_restart_[client_id] = client_info; DVLOG(1) << "StartCapture: Got new resolution " << params.requested_format.frame_size.ToString() << " during stopping."; } else { clients_[client_id] = client_info; if (state_ == VIDEO_CAPTURE_STATE_STARTED) return; params_ = params; if (params_.requested_format.frame_rate > media::limits::kMaxFramesPerSecond) { params_.requested_format.frame_rate = media::limits::kMaxFramesPerSecond; } DVLOG(1) << "StartCapture: starting with first resolution " << params_.requested_format.frame_size.ToString(); first_frame_timestamp_ = base::TimeTicks(); StartCaptureInternal(); } } } void VideoCaptureImpl::StopCapture(int client_id) { DCHECK(thread_checker_.CalledOnValidThread()); // A client ID can be in only one client list. // If this ID is in any client list, we can just remove it from // that client list and don't have to run the other following RemoveClient(). if (!RemoveClient(client_id, &clients_pending_on_filter_)) { if (!RemoveClient(client_id, &clients_pending_on_restart_)) { RemoveClient(client_id, &clients_); } } if (clients_.empty()) { DVLOG(1) << "StopCapture: No more client, stopping ..."; StopDevice(); client_buffers_.clear(); weak_factory_.InvalidateWeakPtrs(); } } void VideoCaptureImpl::GetDeviceSupportedFormats( const VideoCaptureDeviceFormatsCB& callback) { DCHECK(thread_checker_.CalledOnValidThread()); device_formats_cb_queue_.push_back(callback); if (device_formats_cb_queue_.size() == 1) Send(new VideoCaptureHostMsg_GetDeviceSupportedFormats(device_id_, session_id_)); } void VideoCaptureImpl::GetDeviceFormatsInUse( const VideoCaptureDeviceFormatsCB& callback) { DCHECK(thread_checker_.CalledOnValidThread()); device_formats_in_use_cb_queue_.push_back(callback); if (device_formats_in_use_cb_queue_.size() == 1) Send( new VideoCaptureHostMsg_GetDeviceFormatsInUse(device_id_, session_id_)); } void VideoCaptureImpl::OnBufferCreated( base::SharedMemoryHandle handle, int length, int buffer_id) { DCHECK(thread_checker_.CalledOnValidThread()); // In case client calls StopCapture before the arrival of created buffer, // just close this buffer and return. if (state_ != VIDEO_CAPTURE_STATE_STARTED) { base::SharedMemory::CloseHandle(handle); return; } scoped_ptr<base::SharedMemory> shm(new base::SharedMemory(handle, false)); if (!shm->Map(length)) { DLOG(ERROR) << "OnBufferCreated: Map failed."; return; } bool inserted = client_buffers_.insert(std::make_pair( buffer_id, new ClientBuffer(shm.Pass(), length))).second; DCHECK(inserted); } void VideoCaptureImpl::OnBufferDestroyed(int buffer_id) { DCHECK(thread_checker_.CalledOnValidThread()); ClientBufferMap::iterator iter = client_buffers_.find(buffer_id); if (iter == client_buffers_.end()) return; DCHECK(!iter->second || iter->second->HasOneRef()) << "Instructed to delete buffer we are still using."; client_buffers_.erase(iter); } void VideoCaptureImpl::OnBufferReceived(int buffer_id, const media::VideoCaptureFormat& format, base::TimeTicks timestamp) { DCHECK(thread_checker_.CalledOnValidThread()); // The capture pipeline supports only I420 for now. DCHECK_EQ(format.pixel_format, media::PIXEL_FORMAT_I420); if (state_ != VIDEO_CAPTURE_STATE_STARTED || suspended_) { Send(new VideoCaptureHostMsg_BufferReady( device_id_, buffer_id, std::vector<uint32>())); return; } last_frame_format_ = format; if (first_frame_timestamp_.is_null()) first_frame_timestamp_ = timestamp; // Used by chrome/browser/extension/api/cast_streaming/performance_test.cc TRACE_EVENT_INSTANT2( "cast_perf_test", "OnBufferReceived", TRACE_EVENT_SCOPE_THREAD, "timestamp", timestamp.ToInternalValue(), "time_delta", (timestamp - first_frame_timestamp_).ToInternalValue()); ClientBufferMap::iterator iter = client_buffers_.find(buffer_id); DCHECK(iter != client_buffers_.end()); scoped_refptr<ClientBuffer> buffer = iter->second; scoped_refptr<media::VideoFrame> frame = media::VideoFrame::WrapExternalPackedMemory( media::VideoFrame::I420, last_frame_format_.frame_size, gfx::Rect(last_frame_format_.frame_size), last_frame_format_.frame_size, reinterpret_cast<uint8*>(buffer->buffer->memory()), buffer->buffer_size, buffer->buffer->handle(), timestamp - first_frame_timestamp_, media::BindToCurrentLoop( base::Bind(&VideoCaptureImpl::OnClientBufferFinished, weak_factory_.GetWeakPtr(), buffer_id, buffer, std::vector<uint32>()))); for (ClientInfoMap::iterator it = clients_.begin(); it != clients_.end(); ++it) { it->second.deliver_frame_cb.Run(frame, format, timestamp); } } static void NullReadPixelsCB(const SkBitmap& bitmap) { NOTIMPLEMENTED(); } void VideoCaptureImpl::OnMailboxBufferReceived( int buffer_id, const gpu::MailboxHolder& mailbox_holder, const media::VideoCaptureFormat& format, base::TimeTicks timestamp) { DCHECK(thread_checker_.CalledOnValidThread()); if (state_ != VIDEO_CAPTURE_STATE_STARTED || suspended_) { Send(new VideoCaptureHostMsg_BufferReady( device_id_, buffer_id, std::vector<uint32>())); return; } last_frame_format_ = format; if (first_frame_timestamp_.is_null()) first_frame_timestamp_ = timestamp; scoped_refptr<media::VideoFrame> frame = media::VideoFrame::WrapNativeTexture( make_scoped_ptr(new gpu::MailboxHolder(mailbox_holder)), media::BindToCurrentLoop( base::Bind(&VideoCaptureImpl::OnClientBufferFinished, weak_factory_.GetWeakPtr(), buffer_id, scoped_refptr<ClientBuffer>())), last_frame_format_.frame_size, gfx::Rect(last_frame_format_.frame_size), last_frame_format_.frame_size, timestamp - first_frame_timestamp_, base::Bind(&NullReadPixelsCB)); for (ClientInfoMap::iterator it = clients_.begin(); it != clients_.end(); ++it) { it->second.deliver_frame_cb.Run(frame, format, timestamp); } } void VideoCaptureImpl::OnClientBufferFinished( int buffer_id, const scoped_refptr<ClientBuffer>& /* ignored_buffer */, const std::vector<uint32>& release_sync_points) { DCHECK(thread_checker_.CalledOnValidThread()); Send(new VideoCaptureHostMsg_BufferReady( device_id_, buffer_id, release_sync_points)); } void VideoCaptureImpl::OnStateChanged(VideoCaptureState state) { DCHECK(thread_checker_.CalledOnValidThread()); switch (state) { case VIDEO_CAPTURE_STATE_STARTED: // Camera has started in the browser process. Since we have already // told all clients that we have started there's nothing to do. break; case VIDEO_CAPTURE_STATE_STOPPED: state_ = VIDEO_CAPTURE_STATE_STOPPED; DVLOG(1) << "OnStateChanged: stopped!, device_id = " << device_id_; client_buffers_.clear(); weak_factory_.InvalidateWeakPtrs(); if (!clients_.empty() || !clients_pending_on_restart_.empty()) RestartCapture(); break; case VIDEO_CAPTURE_STATE_PAUSED: for (ClientInfoMap::iterator it = clients_.begin(); it != clients_.end(); ++it) { it->second.state_update_cb.Run(VIDEO_CAPTURE_STATE_PAUSED); } break; case VIDEO_CAPTURE_STATE_ERROR: DVLOG(1) << "OnStateChanged: error!, device_id = " << device_id_; for (ClientInfoMap::iterator it = clients_.begin(); it != clients_.end(); ++it) { it->second.state_update_cb.Run(VIDEO_CAPTURE_STATE_ERROR); } clients_.clear(); state_ = VIDEO_CAPTURE_STATE_ERROR; break; case VIDEO_CAPTURE_STATE_ENDED: DVLOG(1) << "OnStateChanged: ended!, device_id = " << device_id_; for (ClientInfoMap::iterator it = clients_.begin(); it != clients_.end(); ++it) { // We'll only notify the client that the stream has stopped. it->second.state_update_cb.Run(VIDEO_CAPTURE_STATE_STOPPED); } clients_.clear(); state_ = VIDEO_CAPTURE_STATE_ENDED; break; default: break; } } void VideoCaptureImpl::OnDeviceSupportedFormatsEnumerated( const media::VideoCaptureFormats& supported_formats) { DCHECK(thread_checker_.CalledOnValidThread()); for (size_t i = 0; i < device_formats_cb_queue_.size(); ++i) device_formats_cb_queue_[i].Run(supported_formats); device_formats_cb_queue_.clear(); } void VideoCaptureImpl::OnDeviceFormatsInUseReceived( const media::VideoCaptureFormats& formats_in_use) { DCHECK(thread_checker_.CalledOnValidThread()); for (size_t i = 0; i < device_formats_in_use_cb_queue_.size(); ++i) device_formats_in_use_cb_queue_[i].Run(formats_in_use); device_formats_in_use_cb_queue_.clear(); } void VideoCaptureImpl::OnDelegateAdded(int32 device_id) { DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "OnDelegateAdded: device_id " << device_id; device_id_ = device_id; for (ClientInfoMap::iterator it = clients_pending_on_filter_.begin(); it != clients_pending_on_filter_.end(); ) { int client_id = it->first; VideoCaptureStateUpdateCB state_update_cb = it->second.state_update_cb; VideoCaptureDeliverFrameCB deliver_frame_cb = it->second.deliver_frame_cb; const media::VideoCaptureParams params = it->second.params; clients_pending_on_filter_.erase(it++); StartCapture(client_id, params, state_update_cb, deliver_frame_cb); } } void VideoCaptureImpl::StopDevice() { DCHECK(thread_checker_.CalledOnValidThread()); if (state_ == VIDEO_CAPTURE_STATE_STARTED) { state_ = VIDEO_CAPTURE_STATE_STOPPING; Send(new VideoCaptureHostMsg_Stop(device_id_)); params_.requested_format.frame_size.SetSize(0, 0); } } void VideoCaptureImpl::RestartCapture() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(state_, VIDEO_CAPTURE_STATE_STOPPED); int width = 0; int height = 0; clients_.insert(clients_pending_on_restart_.begin(), clients_pending_on_restart_.end()); clients_pending_on_restart_.clear(); for (ClientInfoMap::iterator it = clients_.begin(); it != clients_.end(); ++it) { width = std::max(width, it->second.params.requested_format.frame_size.width()); height = std::max(height, it->second.params.requested_format.frame_size.height()); } params_.requested_format.frame_size.SetSize(width, height); DVLOG(1) << "RestartCapture, " << params_.requested_format.frame_size.ToString(); StartCaptureInternal(); } void VideoCaptureImpl::StartCaptureInternal() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(device_id_); Send(new VideoCaptureHostMsg_Start(device_id_, session_id_, params_)); state_ = VIDEO_CAPTURE_STATE_STARTED; } void VideoCaptureImpl::Send(IPC::Message* message) { DCHECK(thread_checker_.CalledOnValidThread()); message_filter_->Send(message); } bool VideoCaptureImpl::RemoveClient(int client_id, ClientInfoMap* clients) { DCHECK(thread_checker_.CalledOnValidThread()); bool found = false; ClientInfoMap::iterator it = clients->find(client_id); if (it != clients->end()) { it->second.state_update_cb.Run(VIDEO_CAPTURE_STATE_STOPPED); clients->erase(it); found = true; } return found; } } // namespace content
35.298876
80
0.703018
[ "object", "vector" ]
a9d689807e42769fdab6574646b40f55cc83ce7b
18,385
cpp
C++
lib/eval/dispatch_three_avx2.cpp
mastermind88/CandyPoker
37b502ce6ea8733ce0b70476fcf32930961923a8
[ "MIT" ]
null
null
null
lib/eval/dispatch_three_avx2.cpp
mastermind88/CandyPoker
37b502ce6ea8733ce0b70476fcf32930961923a8
[ "MIT" ]
null
null
null
lib/eval/dispatch_three_avx2.cpp
mastermind88/CandyPoker
37b502ce6ea8733ce0b70476fcf32930961923a8
[ "MIT" ]
null
null
null
#include "ps/eval/dispatch_table.h" #include "ps/eval/generic_shed.h" #include "ps/eval/generic_sub_eval.h" #include "ps/eval/optimized_transform.h" #include <boost/predef.h> #if BOOST_OS_LINUX #define PS_ALWAYS_INLINE __attribute__((__always_inline__)) #else #define PS_ALWAYS_INLINE #endif namespace ps{ // These are actually slower, hard to beat a good compiler struct sub_eval_three_intrinsic_avx2{ enum{ UpperMask = 0b111 + 1 }; using iter_t = instruction_list::iterator; sub_eval_three_intrinsic_avx2(iter_t iter, card_eval_instruction* instr) :iter_{iter}, instr_{instr} { hv = instr->get_vector(); hv_mask = hv.mask(); eval_.fill(0); } size_t hand_mask()const noexcept{ return hv_mask; } std::uint16_t make_mask(std::vector<ranking_t> const& R)const noexcept{ auto r0 = R[allocation_[0]]; auto r1 = R[allocation_[1]]; auto r2 = R[allocation_[2]]; auto r_min = std::min({r0,r1,r2}); std::uint16_t mask = 0; if( r_min == r0 ) mask |= 0b001; if( r_min == r1 ) mask |= 0b010; if( r_min == r2 ) mask |= 0b100; return mask; } void accept_weight(size_t weight, std::vector<ranking_t> const& R)noexcept { auto mask = make_mask(R); eval_[mask] += weight; } template<size_t Idx> PS_ALWAYS_INLINE void prepare_intrinsic_3( std::vector<ranking_t> const& R, __m256i& v0, __m256i& v1, __m256i& v2)noexcept { auto r0 = R[allocation_[0]]; auto r1 = R[allocation_[1]]; auto r2 = R[allocation_[2]]; v0 = _mm256_insert_epi16(v0, r0, Idx); v1 = _mm256_insert_epi16(v1, r1, Idx); v2 = _mm256_insert_epi16(v2, r2, Idx); } template<size_t Idx> PS_ALWAYS_INLINE void accept_intrinsic_3(size_t weight, std::vector<ranking_t> const& R, __m256i& masks)noexcept { int mask = _mm256_extract_epi16(masks, Idx); eval_[mask] += weight; } void finish(){ matrix_t mat; mat.resize(n, n); mat.fill(0); for(int mask = 1; mask != UpperMask; ++mask){ auto pcnt = detail::popcount(mask); if( mask & 0b001 ) mat(pcnt-1, 0) += eval_[mask]; if( mask & 0b010 ) mat(pcnt-1, 1) += eval_[mask]; if( mask & 0b100 ) mat(pcnt-1, 2) += eval_[mask]; } *iter_ = std::make_shared<matrix_instruction>(instr_->result_desc(), mat); } void declare(std::unordered_set<holdem_id>& S){ for(auto _ : hv){ S.insert(_); } } template<class Alloc> void allocate(Alloc const& alloc){ for(size_t idx=0;idx!=n;++idx){ allocation_[idx] = alloc(hv[idx]); } } private: iter_t iter_; card_eval_instruction* instr_; holdem_hand_vector hv; size_t hv_mask; size_t n{3}; std::array<size_t, 9> allocation_; std::array<size_t, UpperMask> eval_; }; struct scheduler_intrinsic_three_avx2{ enum{ CheckUnion = true }; enum{ CheckZeroWeight = false }; template<class SubPtrType> struct bind{ explicit bind(size_t batch_size, std::vector<SubPtrType>& subs) :subs_{subs} { evals_.resize(batch_size); } void put(size_t index, ranking_t rank)noexcept{ evals_[index] = rank; } void end_eval(mask_set const* ms, size_t single_mask)noexcept{ //#define DBG(REG, X) do{ std::cout << #REG "[" << (X) << "]=" << std::bitset<16>(_mm256_extract_epi16(REG,X)).to_string() << "\n"; }while(0) #define DBG(REG, X) do{}while(0) __m256i m0 = _mm256_set1_epi16(0b001); __m256i m1 = _mm256_set1_epi16(0b010); __m256i m2 = _mm256_set1_epi16(0b100); #define FOR_EACH(X) \ do {\ X(0);\ X(1);\ X(2);\ X(3);\ X(4);\ X(5);\ X(6);\ X(7);\ X(8);\ X(9);\ X(10);\ X(11);\ X(12);\ X(13);\ X(14);\ X(15);\ }while(0) size_t idx=0; for(;idx + 16 < subs_.size();idx+=16){ __m256i v0 = _mm256_setzero_si256(); __m256i v1 = _mm256_setzero_si256(); __m256i v2 = _mm256_setzero_si256(); #define PREPARE(N) \ do{ \ subs_[idx+N]->template prepare_intrinsic_3<N>(evals_, v0, v1, v2);\ }while(0) FOR_EACH(PREPARE); __m256i r_min = _mm256_min_epi16(v0, _mm256_min_epi16(v1, v2)); __m256i eq0 =_mm256_cmpeq_epi16(r_min, v0); __m256i eq1 =_mm256_cmpeq_epi16(r_min, v1); __m256i eq2 =_mm256_cmpeq_epi16(r_min, v2); __m256i a0 = _mm256_and_si256(eq0, m0); __m256i a1 = _mm256_and_si256(eq1, m1); __m256i a2 = _mm256_and_si256(eq2, m2); __m256i mask = _mm256_or_si256(a0, _mm256_or_si256(a1, a2)); #define FINALIZE(N) \ do{ \ size_t weight = generic_weight_policy{} \ .calculate( subs_[idx+ N]->hand_mask(), ms, single_mask); \ if( CheckZeroWeight ){\ if( weight == 0 ) break ; \ }\ subs_[idx+ N]->template accept_intrinsic_3< N>(weight, evals_, mask);\ }while(0) FOR_EACH(FINALIZE); } for(;idx!=subs_.size();++idx){ size_t weight = generic_weight_policy{} .calculate(subs_[idx]->hand_mask(), ms, single_mask); subs_[idx]->accept_weight(weight, evals_); } } void regroup()noexcept{ // nop } private: std::vector<ranking_t> evals_; std::vector<SubPtrType>& subs_; mask_set const* ms_; size_t out_{0}; }; }; struct dispatch_three_player_avx2 : dispatch_table{ using transform_type = optimized_transform< sub_eval_three_intrinsic_avx2, scheduler_intrinsic_three_avx2, basic_sub_eval_factory, rank_hash_eval>; virtual bool match(dispatch_context const& dispatch_ctx)const override{ return dispatch_ctx.homo_num_players && dispatch_ctx.homo_num_players.get() == 3; } virtual std::shared_ptr<optimized_transform_base> make()const override{ return std::make_shared<transform_type>(); } virtual std::string name()const override{ return "three-player-avx2"; } virtual size_t precedence()const override{ return 101; } }; static register_disptach_table<dispatch_three_player_avx2> reg_dispatch_three_player_avx2; struct scheduler_intrinsic_three_avx2_opt{ enum{ CheckUnion = true }; template<class SubPtrType> struct bind{ explicit bind(size_t batch_size, std::vector<SubPtrType>& subs) :subs_{subs} { evals_.resize(batch_size); } void put(size_t index, ranking_t rank)noexcept{ evals_[index] = rank; } void end_eval(mask_set const* ms, size_t single_mask)noexcept{ //#define DBG(REG, X) do{ std::cout << #REG "[" << (X) << "]=" << std::bitset<16>(_mm256_extract_epi16(REG,X)).to_string() << "\n"; }while(0) #define DBG(REG, X) do{}while(0) #define FOR_EACH(X) \ do {\ X(0);\ X(1);\ X(2);\ X(3);\ X(4);\ X(5);\ X(6);\ X(7);\ X(8);\ X(9);\ X(10);\ X(11);\ X(12);\ X(13);\ X(14);\ X(15);\ }while(0) size_t head=0; size_t tail=0; std::array<decltype(std::declval<SubPtrType>().get()), 16> batch; std::array<size_t, 16> batch_weight; __m256i m0 = _mm256_set1_epi16(0b001); __m256i m1 = _mm256_set1_epi16(0b010); __m256i m2 = _mm256_set1_epi16(0b100); for(; head != subs_.size();tail=head){ __m256i v0 = _mm256_setzero_si256(); __m256i v1 = _mm256_setzero_si256(); __m256i v2 = _mm256_setzero_si256(); #define SCATTER(N) \ do{ \ for(;head!=subs_.size() && count != 16;++head){\ size_t weight = generic_weight_policy{} \ .calculate( subs_[head]->hand_mask(), ms, single_mask); \ if( weight == 0 ) continue; \ batch_weight[N] = weight;\ batch[N] = subs_[head].get();\ batch[N]->template prepare_intrinsic_3<N>(evals_, v0, v1, v2);\ ++count;\ ++head;\ break;\ }\ }while(0) size_t count = 0; FOR_EACH(SCATTER); // no edge cases if( count != 16 ) break; __m256i r_min = _mm256_min_epi16(v0, _mm256_min_epi16(v1, v2)); __m256i eq0 =_mm256_cmpeq_epi16(r_min, v0); __m256i eq1 =_mm256_cmpeq_epi16(r_min, v1); __m256i eq2 =_mm256_cmpeq_epi16(r_min, v2); __m256i a0 = _mm256_and_si256(eq0, m0); __m256i a1 = _mm256_and_si256(eq1, m1); __m256i a2 = _mm256_and_si256(eq2, m2); __m256i mask = _mm256_or_si256(a0, _mm256_or_si256(a1, a2)); #define GATHER(N) \ do{ \ batch[N]->template accept_intrinsic_3< N>(batch_weight[N], evals_, mask);\ }while(0) FOR_EACH(GATHER); } for(;tail!=subs_.size();++tail){ size_t weight = generic_weight_policy{} .calculate(subs_[tail]->hand_mask(), ms, single_mask); subs_[tail]->accept_weight(weight, evals_); } } void regroup()noexcept{ // nop } private: std::vector<ranking_t> evals_; std::vector<SubPtrType>& subs_; mask_set const* ms_; size_t out_{0}; }; }; struct dispatch_three_player_avx2_opt : dispatch_table{ using transform_type = optimized_transform< sub_eval_three_intrinsic_avx2, scheduler_intrinsic_three_avx2_opt, basic_sub_eval_factory, rank_hash_eval>; virtual bool match(dispatch_context const& dispatch_ctx)const override{ return dispatch_ctx.homo_num_players && dispatch_ctx.homo_num_players.get() == 3; } virtual std::shared_ptr<optimized_transform_base> make()const override{ return std::make_shared<transform_type>(); } virtual std::string name()const override{ return "three-player-avx2-opt"; } virtual size_t precedence()const override{ return 102; } }; static register_disptach_table<dispatch_three_player_avx2_opt> reg_dispatch_three_player_avx2_opt; } // end namespace ps
48.254593
173
0.332282
[ "vector" ]
a9d8ede1750cd42c5581fde7a7c0588af87ef7ee
8,091
cc
C++
tensorflow/lite/delegates/gpu/gl/kernels/elementwise.cc
carchrae/tensorflow
6a69a6b2e286b14ac9ae813998bb0d78b6fee440
[ "Apache-2.0" ]
12
2020-12-28T18:42:10.000Z
2022-03-24T17:34:21.000Z
tensorflow/lite/delegates/gpu/gl/kernels/elementwise.cc
carchrae/tensorflow
6a69a6b2e286b14ac9ae813998bb0d78b6fee440
[ "Apache-2.0" ]
2
2021-08-25T15:58:27.000Z
2022-02-10T02:04:40.000Z
tensorflow/lite/delegates/gpu/gl/kernels/elementwise.cc
carchrae/tensorflow
6a69a6b2e286b14ac9ae813998bb0d78b6fee440
[ "Apache-2.0" ]
3
2020-03-09T19:17:02.000Z
2020-06-26T23:14:31.000Z
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/gl/kernels/elementwise.h" #include <string> #include "absl/memory/memory.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/common/types.h" namespace tflite { namespace gpu { namespace gl { namespace { class ElementwiseOneArgument : public NodeShader { public: explicit ElementwiseOneArgument(OperationType operation_type) : operation_type_(operation_type) {} Status GenerateCode(const GenerationContext& ctx, GeneratedCode* generated_code) const final { std::string source; switch (operation_type_) { case OperationType::ABS: source = "value_0 = abs(value_0);"; break; case OperationType::COS: source = "value_0 = cos(value_0);"; break; case OperationType::HARD_SWISH: source = "value_0 *= clamp(value_0 / 6.0 + vec4(0.5), vec4(0.0), " "vec4(1.0));"; break; case OperationType::LOG: source = R"( const float nan = normalize(vec4(0, 0, 0, 0)).x; value_0.x = value_0.x > 0.0 ? log(value_0.x) : nan; value_0.y = value_0.y > 0.0 ? log(value_0.y) : nan; value_0.z = value_0.z > 0.0 ? log(value_0.z) : nan; value_0.w = value_0.w > 0.0 ? log(value_0.w) : nan; )"; break; case OperationType::RSQRT: source = R"( const float nan = normalize(vec4(0, 0, 0, 0)).x; value_0.x = value_0.x >= 0.0 ? 1.0 / sqrt(value_0.x) : nan; value_0.y = value_0.y >= 0.0 ? 1.0 / sqrt(value_0.y) : nan; value_0.z = value_0.z >= 0.0 ? 1.0 / sqrt(value_0.z) : nan; value_0.w = value_0.w >= 0.0 ? 1.0 / sqrt(value_0.w) : nan; )"; break; case OperationType::SIGMOID: source = "value_0 = 1.0 / (1.0 + exp(-1.0 * value_0));"; break; case OperationType::SIN: source = "value_0 = sin(value_0);"; break; case OperationType::SQRT: source = R"( const float nan = normalize(vec4(0, 0, 0, 0)).x; value_0.x = value_0.x >= 0.0 ? sqrt(value_0.x) : nan; value_0.y = value_0.y >= 0.0 ? sqrt(value_0.y) : nan; value_0.z = value_0.z >= 0.0 ? sqrt(value_0.z) : nan; value_0.w = value_0.w >= 0.0 ? sqrt(value_0.w) : nan; )"; break; case OperationType::SQUARE: source = "value_0 = value_0 * value_0;"; break; case OperationType::TANH: source = "value_0 = tanh(value_0);"; break; default: return InvalidArgumentError("Incorrect elementwise operation type."); } *generated_code = { /*parameters=*/{}, /*objects=*/{}, /*shared_variables=*/{}, /*workload=*/uint3(), /*workgroup=*/uint3(), source, /*input=*/IOStructure::AUTO, /*output=*/IOStructure::AUTO, }; return OkStatus(); } private: OperationType operation_type_; }; class ElementwiseTwoArguments : public NodeShader { public: explicit ElementwiseTwoArguments(OperationType operation_type) : operation_type_(operation_type) {} bool IsSupportedElemwise(const GenerationContext& ctx) const { auto inputs = ctx.graph->FindInputs(ctx.node->id); // Implementation supports concatenation of 2 tensors only. if (inputs.size() != 2) { return false; } auto shape0 = inputs[0]->tensor.shape; auto shape1 = inputs[1]->tensor.shape; // Shapes must be the same if (shape0 != shape1) { return false; } return true; } Status ImplementElementwise(const GenerationContext& ctx, GeneratedCode* generated_code) const { std::string source; switch (operation_type_) { case OperationType::SUB: { source = "value_0 -= value_1;"; break; } case OperationType::DIV: { source = "value_0 /= value_1;"; break; } case OperationType::POW: { // From documentation : // The result is undefined if x<0 or if x=0 and y≤0. source = "value_0 = pow(value_0, value_1);"; break; } case OperationType::SQUARED_DIFF: { source = "value_0 = (value_0 - value_1) * (value_0 - value_1);"; break; } default: return InvalidArgumentError( "Incorrect elementwise with two arguments operation type."); } *generated_code = { /*parameters=*/{}, /*objects=*/{}, /*shared_variables=*/{}, /*workload=*/uint3(), /*workgroup=*/uint3(), /*source_code=*/source, /*input=*/IOStructure::AUTO, /*output=*/IOStructure::AUTO, }; return OkStatus(); } bool IsSupportedBroadcast(const GenerationContext& ctx) const { auto inputs = ctx.graph->FindInputs(ctx.node->id); auto outputs = ctx.graph->FindOutputs(ctx.node->id); if (inputs.size() != 2) { return false; } if (inputs[1]->tensor.shape.h != 1 || inputs[1]->tensor.shape.w != 1 || inputs[0]->tensor.shape.c != inputs[1]->tensor.shape.c) { return false; } return true; } Status ImplementElementwiseBroadcast(const GenerationContext& ctx, GeneratedCode* generated_code) const { std::string source; switch (operation_type_) { case OperationType::SQUARED_DIFF: { source = R"( vec4 diff = $input_data_0[gid.x, gid.y, gid.z]$ - $input_data_1[0, 0, gid.z]$; value_0 = diff * diff; )"; break; } default: return InvalidArgumentError( "Incorrect elementwise with two arguments operation type."); } *generated_code = { /*parameters=*/{}, /*objects=*/{}, /*shared_variables=*/{}, /*workload=*/uint3(), /*workgroup=*/uint3(), /*source_code=*/source, /*input=*/IOStructure::ONLY_DEFINITIONS, /*output=*/IOStructure::AUTO, }; return OkStatus(); } Status GenerateCode(const GenerationContext& ctx, GeneratedCode* generated_code) const final { if (IsSupportedElemwise(ctx)) { return ImplementElementwise(ctx, generated_code); } if (IsSupportedBroadcast(ctx)) { return ImplementElementwiseBroadcast(ctx, generated_code); } return InvalidArgumentError( "This case is not supported by subtract operation"); } private: OperationType operation_type_; }; } // namespace std::unique_ptr<NodeShader> NewElementwiseNodeShader( OperationType operation_type) { switch (operation_type) { case OperationType::ABS: case OperationType::COS: case OperationType::LOG: case OperationType::HARD_SWISH: case OperationType::RSQRT: case OperationType::SIGMOID: case OperationType::SIN: case OperationType::SQRT: case OperationType::SQUARE: case OperationType::TANH: return absl::make_unique<ElementwiseOneArgument>(operation_type); case OperationType::DIV: case OperationType::POW: case OperationType::SQUARED_DIFF: case OperationType::SUB: return absl::make_unique<ElementwiseTwoArguments>(operation_type); default: return nullptr; } } } // namespace gl } // namespace gpu } // namespace tflite
31.239382
80
0.596342
[ "shape" ]
a9e2a6b3ec792506ccd794186e047a3c630074f8
3,430
cpp
C++
SPOJ/POLYSUB.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
2
2018-12-11T14:37:24.000Z
2022-01-23T18:11:54.000Z
SPOJ/POLYSUB.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
null
null
null
SPOJ/POLYSUB.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define mt make_tuple #define mp make_pair #define pu push_back #define INF 1000000001 #define MOD 1000000007 #define EPS 1e-6 #define ll long long int #define ld long double #define fi first #define se second #define all(v) v.begin(),v.end() #define pr(v) { for(int i=0;i<v.size();i++) { v[i]==INF? cout<<"INF " : cout<<v[i]<<" "; } cout<<endl;} #define t1(x) cerr<<#x<<" : "<<x<<endl #define t2(x, y) cerr<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl #define t3(x, y, z) cerr<<#x<<" : " <<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl #define t4(a,b,c,d) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<endl #define t5(a,b,c,d,e) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<endl #define t6(a,b,c,d,e,f) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<" "<<#f<<" : "<<f<<endl #define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME #define t(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__) #define _ cerr<<"here"<<endl; #define __ {ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);} using namespace std; template<class A, class B> ostream& operator<<(ostream& out, const pair<A, B> &a){ return out<<"("<<a.first<<", "<<a.second<<")";} template <int> ostream& operator<<(ostream& os, const vector<int>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { if(v[i]!=INF) os << v[i]; else os << "INF";if (i != v.size() - 1) os << ", "; } os << "]\n"; return os; } template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { os << v[i]; ;if (i != v.size() - 1) os << ", "; } os << "]\n"; return os; } using cd = complex<double>; const double PI = acos(-1); void fft(vector<cd> & a, bool invert) { int n = a.size(); for (int i = 1, j = 0; i < n; i++) { int bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) swap(a[i], a[j]); } for (int len = 2; len <= n; len <<= 1) { double ang = 2 * PI / len * (invert ? -1 : 1); cd wlen(cos(ang), sin(ang)); for (int i = 0; i < n; i += len) { cd w(1); for (int j = 0; j < len / 2; j++) { cd u = a[i+j], v = a[i+j+len/2] * w; a[i+j] = u + v; a[i+j+len/2] = u - v; w *= wlen; } } } if (invert) { for (cd & x : a) x /= n; } } template<typename T> vector<T> multiply(vector<T> const& a, vector<T> const& b) { vector<cd> fa(a.begin(), a.end()), fb(b.begin(), b.end()); int n = 1; while (n < a.size() + b.size()) n <<= 1; fa.resize(n); fb.resize(n); fft(fa, false); fft(fb, false); for (int i = 0; i < n; i++) fa[i] *= fb[i]; fft(fa, true); vector<T> result(n); for (int i = 0; i < n; i++) result[i] = round(fa[i].real()); return result; } int main() { __; int t; cin >> t; while(t--) { int n; cin >> n; n++; vector<ll> v(n); vector<ll> w(n); for(ll i=0;i<n;i++) cin >> v[i]; for(ll i=0;i<n;i++) cin >> w[i]; vector<ll> ans = multiply(v,w); for(ll i=0;i<2*n-1;i++) cout << ans[i] << " "; cout << endl; } return 0; }
32.358491
226
0.439359
[ "vector" ]
a9e2e0a428fcd70d095d9ab3f7a0c8ee4942513f
29,797
cc
C++
media/mojo/services/watch_time_recorder_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
media/mojo/services/watch_time_recorder_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
media/mojo/services/watch_time_recorder_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium 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 "media/mojo/services/watch_time_recorder.h" #include <stddef.h> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/hash.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/histogram_tester.h" #include "base/test/test_message_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "components/ukm/test_ukm_recorder.h" #include "media/base/watch_time_keys.h" #include "media/mojo/services/media_metrics_provider.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" using UkmEntry = ukm::builders::Media_BasicPlayback; namespace media { constexpr char kTestOrigin[] = "https://test.google.com/"; class WatchTimeRecorderTest : public testing::Test { public: WatchTimeRecorderTest() : computation_keys_( {WatchTimeKey::kAudioSrc, WatchTimeKey::kAudioMse, WatchTimeKey::kAudioEme, WatchTimeKey::kAudioVideoSrc, WatchTimeKey::kAudioVideoMse, WatchTimeKey::kAudioVideoEme}), mtbr_keys_({kMeanTimeBetweenRebuffersAudioSrc, kMeanTimeBetweenRebuffersAudioMse, kMeanTimeBetweenRebuffersAudioEme, kMeanTimeBetweenRebuffersAudioVideoSrc, kMeanTimeBetweenRebuffersAudioVideoMse, kMeanTimeBetweenRebuffersAudioVideoEme}), smooth_keys_({kRebuffersCountAudioSrc, kRebuffersCountAudioMse, kRebuffersCountAudioEme, kRebuffersCountAudioVideoSrc, kRebuffersCountAudioVideoMse, kRebuffersCountAudioVideoEme}), discard_keys_({kDiscardedWatchTimeAudioSrc, kDiscardedWatchTimeAudioMse, kDiscardedWatchTimeAudioEme, kDiscardedWatchTimeAudioVideoSrc, kDiscardedWatchTimeAudioVideoMse, kDiscardedWatchTimeAudioVideoEme}) { ResetMetricRecorders(); MediaMetricsProvider::Create(nullptr, mojo::MakeRequest(&provider_)); } ~WatchTimeRecorderTest() override { base::RunLoop().RunUntilIdle(); } void Initialize(mojom::PlaybackPropertiesPtr properties) { provider_->Initialize(properties->is_mse, true /* is_top_frame */, url::Origin::Create(GURL(kTestOrigin))); provider_->AcquireWatchTimeRecorder(std::move(properties), mojo::MakeRequest(&wtr_)); } void Initialize(bool has_audio, bool has_video, bool is_mse, bool is_encrypted) { Initialize(mojom::PlaybackProperties::New( kUnknownAudioCodec, kUnknownVideoCodec, has_audio, has_video, false, false, is_mse, is_encrypted, false, gfx::Size(800, 600))); } void ExpectWatchTime(const std::vector<base::StringPiece>& keys, base::TimeDelta value) { for (int i = 0; i <= static_cast<int>(WatchTimeKey::kWatchTimeKeyMax); ++i) { const base::StringPiece test_key = ConvertWatchTimeKeyToStringForUma(static_cast<WatchTimeKey>(i)); if (test_key.empty()) continue; auto it = std::find(keys.begin(), keys.end(), test_key); if (it == keys.end()) { histogram_tester_->ExpectTotalCount(test_key.as_string(), 0); } else { histogram_tester_->ExpectUniqueSample(test_key.as_string(), value.InMilliseconds(), 1); } } } void ExpectHelper(const std::vector<base::StringPiece>& full_key_list, const std::vector<base::StringPiece>& keys, int64_t value) { for (auto key : full_key_list) { auto it = std::find(keys.begin(), keys.end(), key); if (it == keys.end()) histogram_tester_->ExpectTotalCount(key.as_string(), 0); else histogram_tester_->ExpectUniqueSample(key.as_string(), value, 1); } } void ExpectMtbrTime(const std::vector<base::StringPiece>& keys, base::TimeDelta value) { ExpectHelper(mtbr_keys_, keys, value.InMilliseconds()); } void ExpectZeroRebuffers(const std::vector<base::StringPiece>& keys) { ExpectHelper(smooth_keys_, keys, 0); } void ExpectRebuffers(const std::vector<base::StringPiece>& keys, int count) { ExpectHelper(smooth_keys_, keys, count); } void ExpectNoUkmWatchTime() { ASSERT_EQ(0u, test_recorder_->sources_count()); ASSERT_EQ(0u, test_recorder_->entries_count()); } void ExpectUkmWatchTime(const std::vector<base::StringPiece>& keys, base::TimeDelta value) { const auto& entries = test_recorder_->GetEntriesByName(UkmEntry::kEntryName); EXPECT_EQ(1u, entries.size()); for (const auto* entry : entries) { test_recorder_->ExpectEntrySourceHasUrl(entry, GURL(kTestOrigin)); for (auto key : keys) { test_recorder_->ExpectEntryMetric(entry, key.data(), value.InMilliseconds()); } } } void ResetMetricRecorders() { histogram_tester_.reset(new base::HistogramTester()); // Ensure cleared global before attempting to create a new TestUkmReporter. test_recorder_.reset(); test_recorder_.reset(new ukm::TestAutoSetUkmRecorder()); } MOCK_METHOD0(GetCurrentMediaTime, base::TimeDelta()); protected: base::MessageLoop message_loop_; mojom::MediaMetricsProviderPtr provider_; std::unique_ptr<base::HistogramTester> histogram_tester_; std::unique_ptr<ukm::TestAutoSetUkmRecorder> test_recorder_; mojom::WatchTimeRecorderPtr wtr_; const std::vector<WatchTimeKey> computation_keys_; const std::vector<base::StringPiece> mtbr_keys_; const std::vector<base::StringPiece> smooth_keys_; const std::vector<base::StringPiece> discard_keys_; DISALLOW_COPY_AND_ASSIGN(WatchTimeRecorderTest); }; TEST_F(WatchTimeRecorderTest, TestBasicReporting) { constexpr base::TimeDelta kWatchTime1 = base::TimeDelta::FromSeconds(25); constexpr base::TimeDelta kWatchTime2 = base::TimeDelta::FromSeconds(50); for (int i = 0; i <= static_cast<int>(WatchTimeKey::kWatchTimeKeyMax); ++i) { const WatchTimeKey key = static_cast<WatchTimeKey>(i); auto key_str = ConvertWatchTimeKeyToStringForUma(key); SCOPED_TRACE(key_str.empty() ? base::NumberToString(i) : key_str.as_string()); // Values for |is_background| and |is_muted| don't matter in this test since // they don't prevent the muted or background keys from being recorded. Initialize(true, false, true, true); wtr_->RecordWatchTime(WatchTimeKey::kWatchTimeKeyMax, kWatchTime1); wtr_->RecordWatchTime(key, kWatchTime1); wtr_->RecordWatchTime(key, kWatchTime2); base::RunLoop().RunUntilIdle(); // Nothing should be recorded yet since we haven't finalized. ExpectWatchTime({}, base::TimeDelta()); // Only the requested key should be finalized. wtr_->FinalizeWatchTime({key}); base::RunLoop().RunUntilIdle(); if (!key_str.empty()) ExpectWatchTime({key_str}, kWatchTime2); // These keys are only reported for a full finalize. ExpectMtbrTime({}, base::TimeDelta()); ExpectZeroRebuffers({}); ExpectNoUkmWatchTime(); // Verify nothing else is recorded except for what we finalized above. ResetMetricRecorders(); wtr_.reset(); base::RunLoop().RunUntilIdle(); ExpectWatchTime({}, base::TimeDelta()); ExpectMtbrTime({}, base::TimeDelta()); ExpectZeroRebuffers({}); switch (key) { case WatchTimeKey::kAudioAll: case WatchTimeKey::kAudioBackgroundAll: case WatchTimeKey::kAudioVideoAll: case WatchTimeKey::kAudioVideoBackgroundAll: case WatchTimeKey::kAudioVideoMutedAll: case WatchTimeKey::kVideoAll: case WatchTimeKey::kVideoBackgroundAll: ExpectUkmWatchTime({UkmEntry::kWatchTimeName}, kWatchTime2); break; // These keys are not reported, instead we boolean flags for each type. case WatchTimeKey::kAudioMse: case WatchTimeKey::kAudioEme: case WatchTimeKey::kAudioSrc: case WatchTimeKey::kAudioEmbeddedExperience: case WatchTimeKey::kAudioBackgroundMse: case WatchTimeKey::kAudioBackgroundEme: case WatchTimeKey::kAudioBackgroundSrc: case WatchTimeKey::kAudioBackgroundEmbeddedExperience: case WatchTimeKey::kAudioVideoMse: case WatchTimeKey::kAudioVideoEme: case WatchTimeKey::kAudioVideoSrc: case WatchTimeKey::kAudioVideoEmbeddedExperience: case WatchTimeKey::kAudioVideoMutedMse: case WatchTimeKey::kAudioVideoMutedEme: case WatchTimeKey::kAudioVideoMutedSrc: case WatchTimeKey::kAudioVideoMutedEmbeddedExperience: case WatchTimeKey::kAudioVideoBackgroundMse: case WatchTimeKey::kAudioVideoBackgroundEme: case WatchTimeKey::kAudioVideoBackgroundSrc: case WatchTimeKey::kAudioVideoBackgroundEmbeddedExperience: case WatchTimeKey::kVideoMse: case WatchTimeKey::kVideoEme: case WatchTimeKey::kVideoSrc: case WatchTimeKey::kVideoEmbeddedExperience: case WatchTimeKey::kVideoBackgroundMse: case WatchTimeKey::kVideoBackgroundEme: case WatchTimeKey::kVideoBackgroundSrc: case WatchTimeKey::kVideoBackgroundEmbeddedExperience: ExpectUkmWatchTime({}, base::TimeDelta()); break; // These keys roll up into the battery watch time field. case WatchTimeKey::kAudioBattery: case WatchTimeKey::kAudioBackgroundBattery: case WatchTimeKey::kAudioVideoBattery: case WatchTimeKey::kAudioVideoMutedBattery: case WatchTimeKey::kAudioVideoBackgroundBattery: case WatchTimeKey::kVideoBattery: case WatchTimeKey::kVideoBackgroundBattery: ExpectUkmWatchTime({UkmEntry::kWatchTime_BatteryName}, kWatchTime2); break; // These keys roll up into the AC watch time field. case WatchTimeKey::kAudioAc: case WatchTimeKey::kAudioBackgroundAc: case WatchTimeKey::kAudioVideoAc: case WatchTimeKey::kAudioVideoBackgroundAc: case WatchTimeKey::kAudioVideoMutedAc: case WatchTimeKey::kVideoAc: case WatchTimeKey::kVideoBackgroundAc: ExpectUkmWatchTime({UkmEntry::kWatchTime_ACName}, kWatchTime2); break; case WatchTimeKey::kAudioVideoDisplayFullscreen: case WatchTimeKey::kAudioVideoMutedDisplayFullscreen: case WatchTimeKey::kVideoDisplayFullscreen: ExpectUkmWatchTime({UkmEntry::kWatchTime_DisplayFullscreenName}, kWatchTime2); break; case WatchTimeKey::kAudioVideoDisplayInline: case WatchTimeKey::kAudioVideoMutedDisplayInline: case WatchTimeKey::kVideoDisplayInline: ExpectUkmWatchTime({UkmEntry::kWatchTime_DisplayInlineName}, kWatchTime2); break; case WatchTimeKey::kAudioVideoDisplayPictureInPicture: case WatchTimeKey::kAudioVideoMutedDisplayPictureInPicture: case WatchTimeKey::kVideoDisplayPictureInPicture: ExpectUkmWatchTime({UkmEntry::kWatchTime_DisplayPictureInPictureName}, kWatchTime2); break; case WatchTimeKey::kAudioNativeControlsOn: case WatchTimeKey::kAudioVideoNativeControlsOn: case WatchTimeKey::kAudioVideoMutedNativeControlsOn: case WatchTimeKey::kVideoNativeControlsOn: ExpectUkmWatchTime({UkmEntry::kWatchTime_NativeControlsOnName}, kWatchTime2); break; case WatchTimeKey::kAudioNativeControlsOff: case WatchTimeKey::kAudioVideoNativeControlsOff: case WatchTimeKey::kAudioVideoMutedNativeControlsOff: case WatchTimeKey::kVideoNativeControlsOff: ExpectUkmWatchTime({UkmEntry::kWatchTime_NativeControlsOffName}, kWatchTime2); break; } ResetMetricRecorders(); } } TEST_F(WatchTimeRecorderTest, TestRebufferingMetrics) { Initialize(true, false, true, true); constexpr base::TimeDelta kWatchTime = base::TimeDelta::FromSeconds(50); for (auto key : computation_keys_) wtr_->RecordWatchTime(key, kWatchTime); wtr_->UpdateUnderflowCount(1); wtr_->UpdateUnderflowCount(2); // Trigger finalization of everything. wtr_->FinalizeWatchTime({}); base::RunLoop().RunUntilIdle(); ExpectMtbrTime(mtbr_keys_, kWatchTime / 2); ExpectRebuffers(smooth_keys_, 2); // Now rerun the test without any rebuffering. ResetMetricRecorders(); for (auto key : computation_keys_) wtr_->RecordWatchTime(key, kWatchTime); wtr_->FinalizeWatchTime({}); base::RunLoop().RunUntilIdle(); ExpectMtbrTime({}, base::TimeDelta()); ExpectZeroRebuffers(smooth_keys_); // Now rerun the test with a small amount of watch time and ensure rebuffering // isn't recorded because we haven't met the watch time requirements. ResetMetricRecorders(); constexpr base::TimeDelta kWatchTimeShort = base::TimeDelta::FromSeconds(5); for (auto key : computation_keys_) wtr_->RecordWatchTime(key, kWatchTimeShort); wtr_->UpdateUnderflowCount(1); wtr_->UpdateUnderflowCount(2); wtr_->FinalizeWatchTime({}); base::RunLoop().RunUntilIdle(); // Nothing should be logged since this doesn't meet requirements. ExpectMtbrTime({}, base::TimeDelta()); for (auto key : smooth_keys_) histogram_tester_->ExpectTotalCount(key.as_string(), 0); } TEST_F(WatchTimeRecorderTest, TestDiscardMetrics) { Initialize(true, false, true, true); constexpr base::TimeDelta kWatchTime = base::TimeDelta::FromSeconds(5); for (auto key : computation_keys_) wtr_->RecordWatchTime(key, kWatchTime); // Trigger finalization of everything. wtr_.reset(); base::RunLoop().RunUntilIdle(); // No standard watch time should be recorded because it falls below the // reporting threshold. ExpectWatchTime({}, base::TimeDelta()); // Verify the time was instead logged to the discard keys. for (auto key : discard_keys_) { histogram_tester_->ExpectUniqueSample(key.as_string(), kWatchTime.InMilliseconds(), 1); } // UKM watch time won't be logged because we aren't sending "All" keys. ExpectUkmWatchTime({}, base::TimeDelta()); } #define EXPECT_UKM(name, value) \ test_recorder_->ExpectEntryMetric(entry, name, value) #define EXPECT_NO_UKM(name) \ EXPECT_FALSE(test_recorder_->EntryHasMetric(entry, name)) #define EXPECT_HAS_UKM(name) \ EXPECT_TRUE(test_recorder_->EntryHasMetric(entry, name)); TEST_F(WatchTimeRecorderTest, TestFinalizeNoDuplication) { mojom::PlaybackPropertiesPtr properties = mojom::PlaybackProperties::New( kCodecAAC, kCodecH264, true, true, false, false, false, false, false, gfx::Size(800, 600)); Initialize(properties.Clone()); // Verify that UKM is reported along with the watch time. constexpr base::TimeDelta kWatchTime = base::TimeDelta::FromSeconds(4); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoAll, kWatchTime); // Finalize everything. UKM is only recorded at destruction, so this should do // nothing. wtr_->FinalizeWatchTime({}); base::RunLoop().RunUntilIdle(); // No watch time should have been recorded since this is below the UMA report // threshold. ExpectWatchTime({}, base::TimeDelta()); ExpectMtbrTime({}, base::TimeDelta()); ExpectZeroRebuffers({}); ExpectNoUkmWatchTime(); const auto& empty_entries = test_recorder_->GetEntriesByName(UkmEntry::kEntryName); EXPECT_EQ(0u, empty_entries.size()); // Verify UKM is logged at destruction time. ResetMetricRecorders(); wtr_.reset(); base::RunLoop().RunUntilIdle(); const auto& entries = test_recorder_->GetEntriesByName(UkmEntry::kEntryName); EXPECT_EQ(1u, entries.size()); for (const auto* entry : entries) { test_recorder_->ExpectEntrySourceHasUrl(entry, GURL(kTestOrigin)); EXPECT_UKM(UkmEntry::kIsBackgroundName, properties->is_background); EXPECT_UKM(UkmEntry::kIsMutedName, properties->is_muted); EXPECT_UKM(UkmEntry::kAudioCodecName, properties->audio_codec); EXPECT_UKM(UkmEntry::kVideoCodecName, properties->video_codec); EXPECT_UKM(UkmEntry::kHasAudioName, properties->has_audio); EXPECT_UKM(UkmEntry::kHasVideoName, properties->has_video); EXPECT_UKM(UkmEntry::kIsEMEName, properties->is_eme); EXPECT_UKM(UkmEntry::kIsMSEName, properties->is_mse); EXPECT_UKM(UkmEntry::kLastPipelineStatusName, PIPELINE_OK); EXPECT_UKM(UkmEntry::kRebuffersCountName, 0); EXPECT_UKM(UkmEntry::kVideoNaturalWidthName, properties->natural_size.width()); EXPECT_UKM(UkmEntry::kVideoNaturalHeightName, properties->natural_size.height()); EXPECT_UKM(UkmEntry::kWatchTimeName, kWatchTime.InMilliseconds()); EXPECT_UKM(UkmEntry::kAudioDecoderNameName, 0); EXPECT_UKM(UkmEntry::kVideoDecoderNameName, 0); EXPECT_UKM(UkmEntry::kAutoplayInitiatedName, false); EXPECT_HAS_UKM(UkmEntry::kPlayerIDName); EXPECT_NO_UKM(UkmEntry::kMeanTimeBetweenRebuffersName); EXPECT_NO_UKM(UkmEntry::kWatchTime_ACName); EXPECT_NO_UKM(UkmEntry::kWatchTime_BatteryName); EXPECT_NO_UKM(UkmEntry::kWatchTime_NativeControlsOnName); EXPECT_NO_UKM(UkmEntry::kWatchTime_NativeControlsOffName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayFullscreenName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayInlineName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayPictureInPictureName); } } TEST_F(WatchTimeRecorderTest, FinalizeWithoutWatchTime) { mojom::PlaybackPropertiesPtr properties = mojom::PlaybackProperties::New( kCodecAAC, kCodecH264, true, true, false, false, false, false, false, gfx::Size(800, 600)); Initialize(properties.Clone()); // Finalize everything. UKM is only recorded at destruction, so this should do // nothing. wtr_->FinalizeWatchTime({}); base::RunLoop().RunUntilIdle(); // No watch time should have been recorded even though a finalize event will // be sent, however a UKM entry with the playback properties will still be // generated. ExpectWatchTime({}, base::TimeDelta()); ExpectMtbrTime({}, base::TimeDelta()); ExpectZeroRebuffers({}); ExpectNoUkmWatchTime(); const auto& empty_entries = test_recorder_->GetEntriesByName(UkmEntry::kEntryName); EXPECT_EQ(0u, empty_entries.size()); // Destructing the recorder should generate a UKM report though. ResetMetricRecorders(); wtr_.reset(); base::RunLoop().RunUntilIdle(); const auto& entries = test_recorder_->GetEntriesByName(UkmEntry::kEntryName); EXPECT_EQ(1u, entries.size()); for (const auto* entry : entries) { test_recorder_->ExpectEntrySourceHasUrl(entry, GURL(kTestOrigin)); EXPECT_UKM(UkmEntry::kIsBackgroundName, properties->is_background); EXPECT_UKM(UkmEntry::kIsMutedName, properties->is_muted); EXPECT_UKM(UkmEntry::kAudioCodecName, properties->audio_codec); EXPECT_UKM(UkmEntry::kVideoCodecName, properties->video_codec); EXPECT_UKM(UkmEntry::kHasAudioName, properties->has_audio); EXPECT_UKM(UkmEntry::kHasVideoName, properties->has_video); EXPECT_UKM(UkmEntry::kIsEMEName, properties->is_eme); EXPECT_UKM(UkmEntry::kIsMSEName, properties->is_mse); EXPECT_UKM(UkmEntry::kLastPipelineStatusName, PIPELINE_OK); EXPECT_UKM(UkmEntry::kRebuffersCountName, 0); EXPECT_UKM(UkmEntry::kVideoNaturalWidthName, properties->natural_size.width()); EXPECT_UKM(UkmEntry::kVideoNaturalHeightName, properties->natural_size.height()); EXPECT_UKM(UkmEntry::kAudioDecoderNameName, 0); EXPECT_UKM(UkmEntry::kVideoDecoderNameName, 0); EXPECT_UKM(UkmEntry::kAutoplayInitiatedName, false); EXPECT_HAS_UKM(UkmEntry::kPlayerIDName); EXPECT_NO_UKM(UkmEntry::kMeanTimeBetweenRebuffersName); EXPECT_NO_UKM(UkmEntry::kWatchTimeName); EXPECT_NO_UKM(UkmEntry::kWatchTime_ACName); EXPECT_NO_UKM(UkmEntry::kWatchTime_BatteryName); EXPECT_NO_UKM(UkmEntry::kWatchTime_NativeControlsOnName); EXPECT_NO_UKM(UkmEntry::kWatchTime_NativeControlsOffName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayFullscreenName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayInlineName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayPictureInPictureName); } } TEST_F(WatchTimeRecorderTest, BasicUkmAudioVideo) { mojom::PlaybackPropertiesPtr properties = mojom::PlaybackProperties::New( kCodecAAC, kCodecH264, true, true, false, false, false, false, false, gfx::Size(800, 600)); Initialize(properties.Clone()); constexpr base::TimeDelta kWatchTime = base::TimeDelta::FromSeconds(4); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoAll, kWatchTime); wtr_.reset(); base::RunLoop().RunUntilIdle(); const auto& entries = test_recorder_->GetEntriesByName(UkmEntry::kEntryName); EXPECT_EQ(1u, entries.size()); for (const auto* entry : entries) { test_recorder_->ExpectEntrySourceHasUrl(entry, GURL(kTestOrigin)); EXPECT_UKM(UkmEntry::kWatchTimeName, kWatchTime.InMilliseconds()); EXPECT_UKM(UkmEntry::kIsBackgroundName, properties->is_background); EXPECT_UKM(UkmEntry::kIsMutedName, properties->is_muted); EXPECT_UKM(UkmEntry::kAudioCodecName, properties->audio_codec); EXPECT_UKM(UkmEntry::kVideoCodecName, properties->video_codec); EXPECT_UKM(UkmEntry::kHasAudioName, properties->has_audio); EXPECT_UKM(UkmEntry::kHasVideoName, properties->has_video); EXPECT_UKM(UkmEntry::kIsEMEName, properties->is_eme); EXPECT_UKM(UkmEntry::kIsMSEName, properties->is_mse); EXPECT_UKM(UkmEntry::kLastPipelineStatusName, PIPELINE_OK); EXPECT_UKM(UkmEntry::kRebuffersCountName, 0); EXPECT_UKM(UkmEntry::kVideoNaturalWidthName, properties->natural_size.width()); EXPECT_UKM(UkmEntry::kVideoNaturalHeightName, properties->natural_size.height()); EXPECT_HAS_UKM(UkmEntry::kPlayerIDName); EXPECT_UKM(UkmEntry::kAudioDecoderNameName, 0); EXPECT_UKM(UkmEntry::kVideoDecoderNameName, 0); EXPECT_UKM(UkmEntry::kAutoplayInitiatedName, false); EXPECT_NO_UKM(UkmEntry::kMeanTimeBetweenRebuffersName); EXPECT_NO_UKM(UkmEntry::kWatchTime_ACName); EXPECT_NO_UKM(UkmEntry::kWatchTime_BatteryName); EXPECT_NO_UKM(UkmEntry::kWatchTime_NativeControlsOnName); EXPECT_NO_UKM(UkmEntry::kWatchTime_NativeControlsOffName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayFullscreenName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayInlineName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayPictureInPictureName); } } TEST_F(WatchTimeRecorderTest, BasicUkmAudioVideoWithExtras) { mojom::PlaybackPropertiesPtr properties = mojom::PlaybackProperties::New( kCodecOpus, kCodecVP9, true, true, false, false, true, true, false, gfx::Size(800, 600)); Initialize(properties.Clone()); constexpr base::TimeDelta kWatchTime = base::TimeDelta::FromSeconds(54); const base::TimeDelta kWatchTime2 = kWatchTime * 2; const base::TimeDelta kWatchTime3 = kWatchTime / 3; wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoAll, kWatchTime2); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoAc, kWatchTime); // Ensure partial finalize does not affect final report. wtr_->FinalizeWatchTime({WatchTimeKey::kAudioVideoAc}); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoBattery, kWatchTime); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoNativeControlsOn, kWatchTime); wtr_->FinalizeWatchTime({WatchTimeKey::kAudioVideoNativeControlsOn}); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoNativeControlsOff, kWatchTime); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoDisplayFullscreen, kWatchTime3); wtr_->FinalizeWatchTime({WatchTimeKey::kAudioVideoDisplayFullscreen}); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoDisplayInline, kWatchTime3); wtr_->FinalizeWatchTime({WatchTimeKey::kAudioVideoDisplayInline}); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoDisplayPictureInPicture, kWatchTime3); wtr_->UpdateUnderflowCount(3); wtr_->OnError(PIPELINE_ERROR_DECODE); const std::string kAudioDecoderName = "MojoAudioDecoder"; const std::string kVideoDecoderName = "MojoVideoDecoder"; wtr_->SetAudioDecoderName(kAudioDecoderName); wtr_->SetVideoDecoderName(kVideoDecoderName); wtr_->SetAutoplayInitiated(true); wtr_.reset(); base::RunLoop().RunUntilIdle(); const auto& entries = test_recorder_->GetEntriesByName(UkmEntry::kEntryName); EXPECT_EQ(1u, entries.size()); for (const auto* entry : entries) { test_recorder_->ExpectEntrySourceHasUrl(entry, GURL(kTestOrigin)); EXPECT_UKM(UkmEntry::kWatchTimeName, kWatchTime2.InMilliseconds()); EXPECT_UKM(UkmEntry::kWatchTime_ACName, kWatchTime.InMilliseconds()); EXPECT_UKM(UkmEntry::kWatchTime_BatteryName, kWatchTime.InMilliseconds()); EXPECT_UKM(UkmEntry::kWatchTime_NativeControlsOnName, kWatchTime.InMilliseconds()); EXPECT_UKM(UkmEntry::kWatchTime_NativeControlsOffName, kWatchTime.InMilliseconds()); EXPECT_UKM(UkmEntry::kWatchTime_DisplayFullscreenName, kWatchTime3.InMilliseconds()); EXPECT_UKM(UkmEntry::kWatchTime_DisplayInlineName, kWatchTime3.InMilliseconds()); EXPECT_UKM(UkmEntry::kWatchTime_DisplayPictureInPictureName, kWatchTime3.InMilliseconds()); EXPECT_UKM(UkmEntry::kMeanTimeBetweenRebuffersName, kWatchTime2.InMilliseconds() / 3); EXPECT_HAS_UKM(UkmEntry::kPlayerIDName); // Values taken from .cc private enumeration (and should never change). EXPECT_UKM(UkmEntry::kAudioDecoderNameName, 2); EXPECT_UKM(UkmEntry::kVideoDecoderNameName, 5); EXPECT_UKM(UkmEntry::kIsBackgroundName, properties->is_background); EXPECT_UKM(UkmEntry::kIsMutedName, properties->is_muted); EXPECT_UKM(UkmEntry::kAudioCodecName, properties->audio_codec); EXPECT_UKM(UkmEntry::kVideoCodecName, properties->video_codec); EXPECT_UKM(UkmEntry::kHasAudioName, properties->has_audio); EXPECT_UKM(UkmEntry::kHasVideoName, properties->has_video); EXPECT_UKM(UkmEntry::kIsEMEName, properties->is_eme); EXPECT_UKM(UkmEntry::kIsMSEName, properties->is_mse); EXPECT_UKM(UkmEntry::kLastPipelineStatusName, PIPELINE_ERROR_DECODE); EXPECT_UKM(UkmEntry::kRebuffersCountName, 3); EXPECT_UKM(UkmEntry::kVideoNaturalWidthName, properties->natural_size.width()); EXPECT_UKM(UkmEntry::kVideoNaturalHeightName, properties->natural_size.height()); EXPECT_UKM(UkmEntry::kAutoplayInitiatedName, true); } } TEST_F(WatchTimeRecorderTest, BasicUkmAudioVideoBackgroundMuted) { mojom::PlaybackPropertiesPtr properties = mojom::PlaybackProperties::New( kCodecAAC, kCodecH264, true, true, true, true, false, false, false, gfx::Size(800, 600)); Initialize(properties.Clone()); constexpr base::TimeDelta kWatchTime = base::TimeDelta::FromSeconds(54); wtr_->RecordWatchTime(WatchTimeKey::kAudioVideoBackgroundAll, kWatchTime); wtr_.reset(); base::RunLoop().RunUntilIdle(); const auto& entries = test_recorder_->GetEntriesByName(UkmEntry::kEntryName); EXPECT_EQ(1u, entries.size()); for (const auto* entry : entries) { test_recorder_->ExpectEntrySourceHasUrl(entry, GURL(kTestOrigin)); EXPECT_UKM(UkmEntry::kWatchTimeName, kWatchTime.InMilliseconds()); EXPECT_UKM(UkmEntry::kIsBackgroundName, properties->is_background); EXPECT_UKM(UkmEntry::kIsMutedName, properties->is_muted); EXPECT_UKM(UkmEntry::kAudioCodecName, properties->audio_codec); EXPECT_UKM(UkmEntry::kVideoCodecName, properties->video_codec); EXPECT_UKM(UkmEntry::kHasAudioName, properties->has_audio); EXPECT_UKM(UkmEntry::kHasVideoName, properties->has_video); EXPECT_UKM(UkmEntry::kIsEMEName, properties->is_eme); EXPECT_UKM(UkmEntry::kIsMSEName, properties->is_mse); EXPECT_UKM(UkmEntry::kLastPipelineStatusName, PIPELINE_OK); EXPECT_UKM(UkmEntry::kRebuffersCountName, 0); EXPECT_UKM(UkmEntry::kVideoNaturalWidthName, properties->natural_size.width()); EXPECT_UKM(UkmEntry::kVideoNaturalHeightName, properties->natural_size.height()); EXPECT_HAS_UKM(UkmEntry::kPlayerIDName); EXPECT_UKM(UkmEntry::kAudioDecoderNameName, 0); EXPECT_UKM(UkmEntry::kVideoDecoderNameName, 0); EXPECT_UKM(UkmEntry::kAutoplayInitiatedName, false); EXPECT_NO_UKM(UkmEntry::kMeanTimeBetweenRebuffersName); EXPECT_NO_UKM(UkmEntry::kWatchTime_ACName); EXPECT_NO_UKM(UkmEntry::kWatchTime_BatteryName); EXPECT_NO_UKM(UkmEntry::kWatchTime_NativeControlsOnName); EXPECT_NO_UKM(UkmEntry::kWatchTime_NativeControlsOffName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayFullscreenName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayInlineName); EXPECT_NO_UKM(UkmEntry::kWatchTime_DisplayPictureInPictureName); } } #undef EXPECT_UKM #undef EXPECT_NO_UKM #undef EXPECT_HAS_UKM TEST_F(WatchTimeRecorderTest, DISABLED_PrintExpectedDecoderNameHashes) { const std::string kDecoderNames[] = { "FFmpegAudioDecoder", "FFmpegVideoDecoder", "GpuVideoDecoder", "MojoVideoDecoder", "MojoAudioDecoder", "VpxVideoDecoder", "AomVideoDecoder", "DecryptingAudioDecoder", "DecryptingVideoDecoder"}; printf("%18s = 0\n", "None"); for (const auto& name : kDecoderNames) printf("%18s = 0x%x\n", name.c_str(), base::PersistentHash(name)); } } // namespace media
42.325284
80
0.730107
[ "vector" ]
a9eb1359fe3574a78fc01ec9a694b4c613ad51b8
9,297
hpp
C++
third_party/osmium/area/problem_reporter_ogr.hpp
cypox/devacus-backend
ba3d2ca8d72843560c4ff754780482dfe8a67c6b
[ "BSD-2-Clause" ]
1
2015-03-16T12:49:12.000Z
2015-03-16T12:49:12.000Z
third_party/osmium/area/problem_reporter_ogr.hpp
antoinegiret/osrm-backend
ebe34da5428c2bfdb2b227392248011c757822e5
[ "BSD-2-Clause" ]
1
2015-02-25T18:27:19.000Z
2015-02-25T18:27:19.000Z
third_party/osmium/area/problem_reporter_ogr.hpp
antoinegiret/osrm-backend
ebe34da5428c2bfdb2b227392248011c757822e5
[ "BSD-2-Clause" ]
null
null
null
#ifndef OSMIUM_AREA_PROBLEM_REPORTER_OGR_HPP #define OSMIUM_AREA_PROBLEM_REPORTER_OGR_HPP /* This file is part of Osmium (http://osmcode.org/libosmium). Copyright 2014 Jochen Topf <jochen@topf.org> and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define OSMIUM_COMPILE_WITH_CFLAGS_OGR `gdal-config --cflags` #define OSMIUM_LINK_WITH_LIBS_OGR `gdal-config --libs` #pragma GCC diagnostic push #ifdef __clang__ # pragma GCC diagnostic ignored "-Wdocumentation-unknown-command" #endif #pragma GCC diagnostic ignored "-Wfloat-equal" #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Wpadded" #pragma GCC diagnostic ignored "-Wredundant-decls" #pragma GCC diagnostic ignored "-Wshadow" # include <ogr_api.h> # include <ogrsf_frmts.h> #pragma GCC diagnostic pop #include <memory> #include <stdexcept> #include <osmium/area/problem_reporter.hpp> #include <osmium/geom/ogr.hpp> #include <osmium/osm/location.hpp> #include <osmium/osm/types.hpp> namespace osmium { namespace area { /** * Report problems when assembling areas by adding them to * layers in an OGR datasource. */ class ProblemReporterOGR : public ProblemReporter { osmium::geom::OGRFactory<> m_ogr_factory; OGRDataSource* m_data_source; OGRLayer* m_layer_perror; OGRLayer* m_layer_lerror; void write_point(const char* problem_type, osmium::object_id_type id1, osmium::object_id_type id2, osmium::Location location) { OGRFeature* feature = OGRFeature::CreateFeature(m_layer_perror->GetLayerDefn()); std::unique_ptr<OGRPoint> ogr_point = m_ogr_factory.create_point(location); feature->SetGeometry(ogr_point.get()); feature->SetField("id1", static_cast<double>(id1)); feature->SetField("id2", static_cast<double>(id2)); feature->SetField("problem_type", problem_type); if (m_layer_perror->CreateFeature(feature) != OGRERR_NONE) { std::runtime_error("Failed to create feature on layer 'perrors'"); } OGRFeature::DestroyFeature(feature); } void write_line(const char* problem_type, osmium::object_id_type id1, osmium::object_id_type id2, osmium::Location loc1, osmium::Location loc2) { std::unique_ptr<OGRPoint> ogr_point1 = m_ogr_factory.create_point(loc1); std::unique_ptr<OGRPoint> ogr_point2 = m_ogr_factory.create_point(loc2); std::unique_ptr<OGRLineString> ogr_linestring = std::unique_ptr<OGRLineString>(new OGRLineString()); ogr_linestring->addPoint(ogr_point1.get()); ogr_linestring->addPoint(ogr_point2.get()); OGRFeature* feature = OGRFeature::CreateFeature(m_layer_lerror->GetLayerDefn()); feature->SetGeometry(ogr_linestring.get()); feature->SetField("id1", static_cast<double>(id1)); feature->SetField("id2", static_cast<double>(id2)); feature->SetField("problem_type", problem_type); if (m_layer_lerror->CreateFeature(feature) != OGRERR_NONE) { std::runtime_error("Failed to create feature on layer 'lerrors'"); } OGRFeature::DestroyFeature(feature); } public: explicit ProblemReporterOGR(OGRDataSource* data_source) : m_data_source(data_source) { OGRSpatialReference sparef; sparef.SetWellKnownGeogCS("WGS84"); m_layer_perror = m_data_source->CreateLayer("perrors", &sparef, wkbPoint, nullptr); if (!m_layer_perror) { std::runtime_error("Layer creation failed for layer 'perrors'"); } OGRFieldDefn layer_perror_field_id1("id1", OFTReal); layer_perror_field_id1.SetWidth(10); if (m_layer_perror->CreateField(&layer_perror_field_id1) != OGRERR_NONE) { std::runtime_error("Creating field 'id1' failed for layer 'perrors'"); } OGRFieldDefn layer_perror_field_id2("id2", OFTReal); layer_perror_field_id2.SetWidth(10); if (m_layer_perror->CreateField(&layer_perror_field_id2) != OGRERR_NONE) { std::runtime_error("Creating field 'id2' failed for layer 'perrors'"); } OGRFieldDefn layer_perror_field_problem_type("problem_type", OFTString); layer_perror_field_problem_type.SetWidth(30); if (m_layer_perror->CreateField(&layer_perror_field_problem_type) != OGRERR_NONE) { std::runtime_error("Creating field 'problem_type' failed for layer 'perrors'"); } /**************/ m_layer_lerror = m_data_source->CreateLayer("lerrors", &sparef, wkbLineString, nullptr); if (!m_layer_lerror) { std::runtime_error("Layer creation failed for layer 'lerrors'"); } OGRFieldDefn layer_lerror_field_id1("id1", OFTReal); layer_lerror_field_id1.SetWidth(10); if (m_layer_lerror->CreateField(&layer_lerror_field_id1) != OGRERR_NONE) { std::runtime_error("Creating field 'id1' failed for layer 'lerrors'"); } OGRFieldDefn layer_lerror_field_id2("id2", OFTReal); layer_lerror_field_id2.SetWidth(10); if (m_layer_lerror->CreateField(&layer_lerror_field_id2) != OGRERR_NONE) { std::runtime_error("Creating field 'id2' failed for layer 'lerrors'"); } OGRFieldDefn layer_lerror_field_problem_type("problem_type", OFTString); layer_lerror_field_problem_type.SetWidth(30); if (m_layer_lerror->CreateField(&layer_lerror_field_problem_type) != OGRERR_NONE) { std::runtime_error("Creating field 'problem_type' failed for layer 'lerrors'"); } } virtual ~ProblemReporterOGR() = default; void report_duplicate_node(osmium::object_id_type node_id1, osmium::object_id_type node_id2, osmium::Location location) override { write_point("duplicate_node", node_id1, node_id2, location); } void report_intersection(osmium::object_id_type way1_id, osmium::Location way1_seg_start, osmium::Location way1_seg_end, osmium::object_id_type way2_id, osmium::Location way2_seg_start, osmium::Location way2_seg_end, osmium::Location intersection) override { write_point("intersection", m_object_id, 0, intersection); write_line("intersection", m_object_id, way1_id, way1_seg_start, way1_seg_end); write_line("intersection", m_object_id, way2_id, way2_seg_start, way2_seg_end); } void report_ring_not_closed(osmium::Location end1, osmium::Location end2) override { write_point("ring_not_closed", m_object_id, 0, end1); write_point("ring_not_closed", m_object_id, 0, end2); } void report_role_should_be_outer(osmium::object_id_type way_id, osmium::Location seg_start, osmium::Location seg_end) override { write_line("role_should_be_outer", m_object_id, way_id, seg_start, seg_end); } void report_role_should_be_inner(osmium::object_id_type way_id, osmium::Location seg_start, osmium::Location seg_end) override { write_line("role_should_be_inner", m_object_id, way_id, seg_start, seg_end); } }; // class ProblemReporterOGR } // namespace area } // namespace osmium #endif // OSMIUM_AREA_PROBLEM_REPORTER_OGR_HPP
44.913043
174
0.659568
[ "object" ]
a9ec18e017ac7eb9b4c40466b1e995b15d7af654
2,638
hpp
C++
watch.hpp
dhruvibm/phosphor-debug-collector
124d31f09cbb0eebd0f14aceade5c2fd290520fe
[ "Apache-2.0" ]
4
2017-12-01T19:36:26.000Z
2021-03-30T16:44:11.000Z
watch.hpp
dhruvibm/phosphor-debug-collector
124d31f09cbb0eebd0f14aceade5c2fd290520fe
[ "Apache-2.0" ]
17
2017-10-05T11:28:56.000Z
2022-02-21T05:27:31.000Z
watch.hpp
dhruvibm/phosphor-debug-collector
124d31f09cbb0eebd0f14aceade5c2fd290520fe
[ "Apache-2.0" ]
25
2021-09-03T19:04:36.000Z
2022-03-31T13:09:18.000Z
#pragma once #include "dump_utils.hpp" #include <sys/inotify.h> #include <systemd/sd-event.h> #include <filesystem> #include <functional> #include <map> namespace phosphor { namespace dump { namespace inotify { // User specific call back function input map(path:event) type. using UserMap = std::map<std::filesystem::path, uint32_t>; // User specific callback function wrapper type. using UserType = std::function<void(const UserMap&)>; /** @class Watch * * @brief Adds inotify watch on directory. * * The inotify watch is hooked up with sd-event, so that on call back, * appropriate actions are taken to collect files from the directory * initialized by the object. */ class Watch { public: /** @brief ctor - hook inotify watch with sd-event * * @param[in] eventObj - Event loop object * @param[in] flags - inotify flags * @param[in] mask - Mask of events * @param[in] events - Events to be watched * @param[in] path - File path to be watched * @param[in] userFunc - User specific callback fnction wrapper. * */ Watch(const EventPtr& eventObj, int flags, uint32_t mask, uint32_t events, const std::filesystem::path& path, UserType userFunc); Watch(const Watch&) = delete; Watch& operator=(const Watch&) = delete; Watch(Watch&&) = default; Watch& operator=(Watch&&) = default; /* @brief dtor - remove inotify watch and close fd's */ ~Watch(); private: /** @brief sd-event callback. * @details Collects the files and event info and call the * appropriate user function for further action. * * @param[in] s - event source, floating (unused) in our case * @param[in] fd - inotify fd * @param[in] revents - events that matched for fd * @param[in] userdata - pointer to Watch object * * @returns 0 on success, -1 on fail */ static int callback(sd_event_source* s, int fd, uint32_t revents, void* userdata); /** initialize an inotify instance and returns file descriptor */ int inotifyInit(); /** @brief inotify flags */ int flags; /** @brief Mask of events */ uint32_t mask; /** @brief Events to be watched */ uint32_t events; /** @brief File path to be watched */ std::filesystem::path path; /** @brief dump file directory watch descriptor */ int wd = -1; /** @brief file descriptor manager */ CustomFd fd; /** @brief The user level callback function wrapper */ UserType userFunc; }; } // namespace inotify } // namespace dump } // namespace phosphor
26.38
78
0.640637
[ "object" ]
a9fe3c752cd0f53b4b71e43df0b26eee358c408b
4,122
cpp
C++
src/engine/Game.cpp
holdenrehg/survivor
b95abec0ce874e51d8367767fcd01b0f9c3e9b7f
[ "MIT" ]
null
null
null
src/engine/Game.cpp
holdenrehg/survivor
b95abec0ce874e51d8367767fcd01b0f9c3e9b7f
[ "MIT" ]
null
null
null
src/engine/Game.cpp
holdenrehg/survivor
b95abec0ce874e51d8367767fcd01b0f9c3e9b7f
[ "MIT" ]
null
null
null
#include <chrono> #include <iostream> #include <type_traits> #include "raylib.h" #include "include/engine/time.h" #include "include/engine/Clock.h" #include "include/engine/Game.h" #include "include/engine/Scene.h" #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif using namespace std; using namespace Catcher::Survivor; Game::Game(Scene *initialScene) { clock = Clock(); shouldRun = false; timePerUpdate = 20; // ms currentScene = initialScene; Vector2 zeroPosition = { 0, 0 }; camera = { 0 }; camera.offset = zeroPosition; camera.target = zeroPosition; camera.rotation = 0.0f; camera.zoom = 1.5f; } Game::~Game() { delete currentScene; } void Game::run() { // Initialization ---------------------------------------------------------- shouldRun = true; const int screenWidth = 1920; const int screenHeight = 1280; const int targetWidth = 480; const int targetHeight = 320; InitWindow(screenWidth, screenHeight, "Survivor"); SetWindowState(FLAG_WINDOW_ALWAYS_RUN | FLAG_WINDOW_RESIZABLE); SetExitKey(KEY_ESCAPE); RenderTexture2D target = LoadRenderTexture(targetWidth, targetHeight); Rectangle source = {0, (float) -targetHeight, (float) targetWidth, (float) -targetHeight}; // OpenGL coordinates are inverted Rectangle dest = {0, 0, (float) screenWidth, (float) screenHeight}; int framesElapsed = 0; long int gameStart = timeSinceEpoch(); // Game Loop --------------------------------------------------------------- while(isRunning()) { long int frameStart = timeSinceEpoch(); clock.tick(); // Window Size Handling ------------------------------------------------ // Maintain the same aspect ratio if the window is resized if(IsWindowResized()) { // TODO: handle auto adjusting either width or height to maintain // the target aspect ratio } // Input Handling ------------------------------------------------------ currentScene->handleInput(this); // Update Cycles ------------------------------------------------------- currentScene->update(this); while(clock.getLag() >= timePerUpdate) { currentScene->fixedUpdate(this); clock.updateTick(timePerUpdate); } currentScene->lateUpdate(this); // Rendering ----------------------------------------------------------- // All draw functions will write to the render texture... BeginTextureMode(target); ClearBackground(WHITE); currentScene->draw(this); currentScene->drawGui(this); EndTextureMode(); // Then the render texture will get scaled up to the window size BeginDrawing(); BeginMode2D(camera); ClearBackground(WHITE); Vector2 position = { 0, 0 }; DrawTexturePro(target.texture, source, dest, position, 0.0f, WHITE); EndMode2D(); EndDrawing(); // Clamp The FPS ------------------------------------------------------- // Locks the fps to roughly 60 FPS long int toSleep = (frameStart + 16 - timeSinceEpoch()) * 1000; if(toSleep > 0) { usleep(static_cast<int>(toSleep)); } // Debugging frames per second // TODO: Put this is a better place, maybe the Clock class framesElapsed += 1; if(framesElapsed % 100 == 0) { long int msElapsed = timeSinceEpoch() - gameStart; long double framesPerSecond = (static_cast<long double>(framesElapsed) / static_cast<long double>(msElapsed)) * 1000; cout << framesPerSecond << " fps" << endl; } } // Cleanup ----------------------------------------------------------------- CloseWindow(); } void Game::stop() { shouldRun = false; } bool Game::isRunning() { return shouldRun && !WindowShouldClose(); } void Game::loadScene(Scene *scene) { delete currentScene; currentScene = scene; }
29.234043
129
0.544639
[ "render" ]
e700c50ead099c74f63a6c46911a4aa67a399c8b
1,163
cpp
C++
leetcode/Algorithms/SearchForARange/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
2
2015-07-03T03:05:30.000Z
2015-07-03T03:05:31.000Z
leetcode/Algorithms/SearchForARange/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
null
null
null
leetcode/Algorithms/SearchForARange/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
null
null
null
// double binary search solution by hxdone class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> ret; ret.push_back(lower_bound(nums, target)); ret.push_back(upper_bound(nums, target)); return ret; } private: int lower_bound(vector<int>& nums, int target) { int low = 0; int high = nums.size()-1; while (low < high) { int mid = (low+high)/2; if (nums[mid] > target) high = mid-1; else if (nums[mid] < target) low = mid+1; else high = mid; } return (low == high && nums[low] == target)? low: -1; } int upper_bound(vector<int>& nums, int target) { int low = 0; int high = nums.size()-1; while (low < high) { int mid = (low+high+1)/2; if (nums[mid] > target) high = mid-1; else if (nums[mid] < target) low = mid+1; else low = mid; } return (low == high && nums[low] == target)? low: -1; } };
27.690476
61
0.463457
[ "vector" ]
e710fc5f5379c48edf676ce1df4559f3c25f8efc
2,387
hpp
C++
include/Device.hpp
gaoyingie/libmediasoupclient
806a0385f76e953c6e5e12e1a761e3c54c01dc9e
[ "ISC" ]
null
null
null
include/Device.hpp
gaoyingie/libmediasoupclient
806a0385f76e953c6e5e12e1a761e3c54c01dc9e
[ "ISC" ]
null
null
null
include/Device.hpp
gaoyingie/libmediasoupclient
806a0385f76e953c6e5e12e1a761e3c54c01dc9e
[ "ISC" ]
null
null
null
#ifndef MSC_DEVICE_HPP #define MSC_DEVICE_HPP #include "Exception.hpp" #include "Handler.hpp" #include "Transport.hpp" #include "json.hpp" #include <map> #include <string> namespace mediasoupclient { class Device { public: Device() = default; ~Device() = default; bool IsLoaded() const; const nlohmann::json& GetRtpCapabilities() const; void Load( const nlohmann::json& routerRtpCapabilities, const PeerConnection::Options* peerConnectionOptions = nullptr); bool CanProduce(const std::string& kind); SendTransport* CreateSendTransport( SendTransport::Listener* listener, const std::string& id, const nlohmann::json& iceParameters, const nlohmann::json& iceCandidates, const nlohmann::json& dtlsParameters, const PeerConnection::Options* peerConnectionOptions = nullptr, nlohmann::json appData = nlohmann::json::object()) const; RecvTransport* CreateRecvTransport( RecvTransport::Listener* listener, const std::string& id, const nlohmann::json& iceParameters, const nlohmann::json& iceCandidates, const nlohmann::json& dtlsParameters, const PeerConnection::Options* peerConnectionOptions = nullptr, nlohmann::json appData = nlohmann::json::object()) const; private: // Loaded flag. bool loaded{ false }; // Extended RTP capabilities. nlohmann::json extendedRtpCapabilities; // Local RTP capabilities for receiving media. nlohmann::json recvRtpCapabilities; // Whether we can produce audio/video based on computed extended RTP capabilities. /* clang-format off */ std::map<std::string, bool> canProduceByKind = { { "audio", false }, { "video", false } }; /* clang-format on */ }; /* Inline methods */ /** * Whether the Device is loaded. */ inline bool Device::IsLoaded() const { return this->loaded; } /** * RTP capabilities of the Device for receiving media. */ inline const nlohmann::json& Device::GetRtpCapabilities() const { if (!this->loaded) throw Exception("Not loaded"); return this->recvRtpCapabilities; } /** * Whether we can produce audio/video. * */ inline bool Device::CanProduce(const std::string& kind) { if (!this->loaded) throw Exception("Not loaded"); if (kind != "audio" && kind != "video") throw Exception("Invalid kind"); return this->canProduceByKind[kind]; } } // namespace mediasoupclient #endif
23.401961
90
0.702137
[ "object" ]
e7113fc22687e6de275876bcce894d4ac4165e24
10,902
cc
C++
src/theia/sfm/reconstruction_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
3
2019-01-17T17:37:37.000Z
2021-03-26T09:21:38.000Z
src/theia/sfm/reconstruction_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
null
null
null
src/theia/sfm/reconstruction_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
3
2019-07-16T08:45:55.000Z
2020-02-11T05:32:16.000Z
// Copyright (C) 2014 The Regents of the University of California (Regents). // 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 The Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) #include "gtest/gtest.h" #include "theia/sfm/reconstruction.h" #include "theia/util/map_util.h" namespace theia { const std::vector<std::string> view_names = {"1", "2", "3"}; const std::vector<Feature> features = { Feature(1, 1), Feature(2, 2), Feature(3, 3) }; TEST(Reconstruction, ViewIdFromNameValid) { Reconstruction reconstruction; const ViewId gt_view_id = reconstruction.AddView(view_names[0]); const ViewId view_id = reconstruction.ViewIdFromName(view_names[0]); EXPECT_EQ(gt_view_id, view_id); } TEST(Reconstruction, ViewIdFromNameInvalid) { Reconstruction reconstruction; EXPECT_EQ(reconstruction.ViewIdFromName(view_names[0]), kInvalidViewId); } TEST(Reconstruction, AddView) { Reconstruction reconstruction; const ViewId view_id = reconstruction.AddView(view_names[0]); EXPECT_NE(view_id, kInvalidViewId); EXPECT_EQ(reconstruction.NumViews(), 1); EXPECT_EQ(reconstruction.NumTracks(), 0); EXPECT_EQ(reconstruction.AddView(view_names[0]), kInvalidViewId); EXPECT_EQ(reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id), 0); } TEST(Reconstruction, AddViewWithCameraIntrinsicsGroup) { Reconstruction reconstruction; const CameraIntrinsicsGroupId intrinsics_id = 1; const ViewId view_id = reconstruction.AddView(view_names[0], intrinsics_id); EXPECT_NE(view_id, kInvalidViewId); EXPECT_EQ(reconstruction.NumViews(), 1); EXPECT_EQ(reconstruction.NumTracks(), 0); EXPECT_EQ(reconstruction.NumCameraIntrinsicGroups(), 1); EXPECT_EQ(reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id), intrinsics_id); EXPECT_EQ(reconstruction.AddView(view_names[0]), kInvalidViewId); } TEST(Reconstruction, RemoveView) { Reconstruction reconstruction; const ViewId view_id1 = reconstruction.AddView(view_names[0]); const ViewId view_id2 = reconstruction.AddView(view_names[1]); EXPECT_EQ(reconstruction.NumViews(), 2); EXPECT_EQ(reconstruction.NumCameraIntrinsicGroups(), 2); const CameraIntrinsicsGroupId view1_group = reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id1); const CameraIntrinsicsGroupId view2_group = reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id2); EXPECT_TRUE(reconstruction.RemoveView(view_id1)); EXPECT_EQ(reconstruction.NumViews(), 1); EXPECT_EQ(reconstruction.ViewIdFromName(view_names[0]), kInvalidViewId); EXPECT_EQ(reconstruction.View(view_id1), nullptr); EXPECT_EQ(reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id1), kInvalidCameraIntrinsicsGroupId); EXPECT_EQ(reconstruction.NumCameraIntrinsicGroups(), 1); const std::unordered_set<ViewId> view1_camera_intrinsics_group = reconstruction.GetViewsInCameraIntrinsicGroup(view1_group); EXPECT_FALSE(ContainsKey(view1_camera_intrinsics_group, view_id1)); EXPECT_TRUE(reconstruction.RemoveView(view_id2)); EXPECT_EQ(reconstruction.NumViews(), 0); EXPECT_EQ(reconstruction.ViewIdFromName(view_names[1]), kInvalidViewId); EXPECT_EQ(reconstruction.View(view_id2), nullptr); EXPECT_EQ(reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id2), kInvalidCameraIntrinsicsGroupId); EXPECT_EQ(reconstruction.NumCameraIntrinsicGroups(), 0); const std::unordered_set<ViewId> view2_camera_intrinsics_group = reconstruction.GetViewsInCameraIntrinsicGroup(view2_group); EXPECT_FALSE(ContainsKey(view2_camera_intrinsics_group, view_id2)); EXPECT_FALSE(reconstruction.RemoveView(kInvalidViewId)); EXPECT_FALSE(reconstruction.RemoveView(view_id1)); } TEST(Reconstruction, GetViewValid) { Reconstruction reconstruction; const ViewId view_id = reconstruction.AddView(view_names[0]); EXPECT_NE(view_id, kInvalidViewId); const View* const_view = reconstruction.View(view_id); EXPECT_NE(const_view, nullptr); View* mutable_view = reconstruction.MutableView(view_id); EXPECT_NE(mutable_view, nullptr); } TEST(Reconstruction, GetViewValidInvalid) { Reconstruction reconstruction; static const ViewId view_id = 0; const View* const_view = reconstruction.View(view_id); EXPECT_EQ(const_view, nullptr); View* mutable_view = reconstruction.MutableView(view_id); EXPECT_EQ(mutable_view, nullptr); } TEST(Reconstruction, GetViewsInCameraIntrinsicGroup) { Reconstruction reconstruction; const ViewId view_id1 = reconstruction.AddView(view_names[0]); const CameraIntrinsicsGroupId intrinsics_id1 = reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id1); // Add a second view with to the same camera intrinsics group. const ViewId view_id2 = reconstruction.AddView(view_names[1], intrinsics_id1); const CameraIntrinsicsGroupId intrinsics_id2 = reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id2); EXPECT_EQ(intrinsics_id1, intrinsics_id2); // Add a third view that is in it's own camera intrinsics group. const ViewId view_id3 = reconstruction.AddView(view_names[2]); const CameraIntrinsicsGroupId intrinsics_id3 = reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id3); EXPECT_NE(intrinsics_id1, intrinsics_id3); EXPECT_EQ(reconstruction.NumCameraIntrinsicGroups(), 2); } TEST(Reconstruction, CameraIntrinsicsGroupIds) { Reconstruction reconstruction; const ViewId view_id1 = reconstruction.AddView(view_names[0]); const CameraIntrinsicsGroupId intrinsics_id1 = reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id1); // Add a second view with to the same camera intrinsics group. const ViewId view_id2 = reconstruction.AddView(view_names[1], intrinsics_id1); const CameraIntrinsicsGroupId intrinsics_id2 = reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id2); EXPECT_EQ(intrinsics_id1, intrinsics_id2); // Add a third view that is in it's own camera intrinsics group. const ViewId view_id3 = reconstruction.AddView(view_names[2]); const CameraIntrinsicsGroupId intrinsics_id3 = reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id3); EXPECT_NE(intrinsics_id1, intrinsics_id3); EXPECT_EQ(reconstruction.NumCameraIntrinsicGroups(), 2); // Ensure that the group ids are correct. const std::unordered_set<CameraIntrinsicsGroupId> group_ids = reconstruction.CameraIntrinsicsGroupIds(); EXPECT_EQ(group_ids.size(), 2); EXPECT_TRUE(ContainsKey(group_ids, intrinsics_id1)); EXPECT_TRUE(ContainsKey(group_ids, intrinsics_id3)); } TEST(Reconstruction, AddTrackValid) { Reconstruction reconstruction; const std::vector<std::pair<ViewId, Feature> > track = { { 0, features[0] }, { 1, features[1] } }; EXPECT_NE(reconstruction.AddView(view_names[0]), kInvalidViewId); EXPECT_NE(reconstruction.AddView(view_names[1]), kInvalidViewId); const TrackId track_id = reconstruction.AddTrack(track); EXPECT_NE(track_id, kInvalidTrackId); EXPECT_TRUE(reconstruction.Track(track_id) != nullptr); EXPECT_EQ(reconstruction.NumTracks(), 1); } TEST(Reconstruction, AddTrackInvalid) { Reconstruction reconstruction; // Should fail with less than two views. const std::vector<std::pair<ViewId, Feature> > small_track = { { 0, features[0] } }; EXPECT_NE(reconstruction.AddView(view_names[0]), kInvalidViewId); EXPECT_EQ(reconstruction.AddTrack(small_track), kInvalidTrackId); EXPECT_EQ(reconstruction.NumTracks(), 0); } TEST(Reconstruction, RemoveTrackValid) { Reconstruction reconstruction; const std::vector<std::pair<ViewId, Feature> > track = { { 0, features[0] }, { 1, features[1] } }; // Should be able to successfully remove the track. EXPECT_NE(reconstruction.AddView(view_names[0]), kInvalidViewId); EXPECT_NE(reconstruction.AddView(view_names[1]), kInvalidViewId); const TrackId track_id = reconstruction.AddTrack(track); EXPECT_TRUE(reconstruction.RemoveTrack(track_id)); } TEST(Reconstruction, RemoveTrackInvalid) { Reconstruction reconstruction; // Should return false when trying to remove a track not in the // reconstruction. EXPECT_FALSE(reconstruction.RemoveTrack(kInvalidTrackId)); } TEST(Reconstruction, GetTrackValid) { Reconstruction reconstruction; const std::vector<std::pair<ViewId, Feature> > track = { { 0, features[0] }, { 1, features[1] } }; EXPECT_NE(reconstruction.AddView(view_names[0]), kInvalidViewId); EXPECT_NE(reconstruction.AddView(view_names[1]), kInvalidViewId); const TrackId track_id = reconstruction.AddTrack(track); EXPECT_NE(track_id, kInvalidTrackId); const Track* const_track = reconstruction.Track(track_id); EXPECT_NE(const_track, nullptr); Track* mutable_track = reconstruction.MutableTrack(track_id); EXPECT_NE(mutable_track, nullptr); } TEST(Reconstruction, GetTrackInvalid) { Reconstruction reconstruction; const std::vector<std::pair<ViewId, Feature> > track = {}; const TrackId track_id = reconstruction.AddTrack(track); EXPECT_EQ(track_id, kInvalidTrackId); const Track* const_track = reconstruction.Track(track_id); EXPECT_EQ(const_track, nullptr); Track* mutable_track = reconstruction.MutableTrack(track_id); EXPECT_EQ(mutable_track, nullptr); } } // namespace theia
40.377778
80
0.772519
[ "vector" ]
e716cf5878e342130af79b5149a05db10c97bd95
2,846
cpp
C++
tests/testAlloc.cpp
frobnitzem/FastParticleToolkit
d5bc77f891d8aae18d777b8855ff4a6b3dd79761
[ "CC-BY-4.0" ]
null
null
null
tests/testAlloc.cpp
frobnitzem/FastParticleToolkit
d5bc77f891d8aae18d777b8855ff4a6b3dd79761
[ "CC-BY-4.0" ]
null
null
null
tests/testAlloc.cpp
frobnitzem/FastParticleToolkit
d5bc77f891d8aae18d777b8855ff4a6b3dd79761
[ "CC-BY-4.0" ]
null
null
null
#include <catch2/catch_all.hpp> #include <fpt/Alloc.hpp> #include "TestAlpaka.hpp" TEST_CASE( "allocator indices", "[allocator]") { uint32_t N = 540; SECTION( "fpt::searchNext returns in-range" ) { std::vector<uint32_t> trials{0,3,10,100,N-32,N-1}; for(uint32_t blockId : trials) { uint32_t next = blockId % N; REQUIRE(next < N); for(uint32_t j=0; j<10; j++) { next = fpt::searchNext(next, blockId, N); REQUIRE(next < N); } } } } template <typename Dev> class EmptyTestKernel { public: //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TAcc> ALPAKA_FN_ACC auto operator()( TAcc const & acc, bool * success, uint32_t N0, fpt::Alloc_d<int,Dev> alloc) const -> void { const auto idx = alpaka::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0]; //std::int32_t const warpExtent = alpaka::warp::getSize(acc); ALPAKA_CHECK(*success, false); for(int i=0; i<32; i++) { uint32_t k = idx*32 + i; ALPAKA_CHECK(*success, alloc.is_free(idx*32 + i) == (k >= N0) && (k < alloc.N)); } } }; //----------------------------------------------------------------------------- TEMPLATE_LIST_TEST_CASE( "fpt::Alloc returns empty block", "[warp]", alpaka::test::TestAccs) { using Acc = TestType; using Dev = alpaka::Dev<Acc>; using Pltf = alpaka::Pltf<Dev>; using Dim = alpaka::Dim<Acc>; using Idx = alpaka::Idx<Acc>; using Vec = alpaka::Vec<Dim, Idx>; using Queue = alpaka::Queue<Acc, alpaka::Blocking>; uint32_t N0 = 100; uint32_t N = 1029; Dev const dev = alpaka::getDevByIdx<Pltf>(0u); auto A = fpt::Alloc<int,Acc>(dev, N); auto Q = Queue(dev); A.reinit(N0, Q); alpaka::wait(Q); auto const warpExtent = alpaka::getWarpSize(dev); using ExecutionFixture = alpaka::test::KernelExecutionFixture<Acc,Queue>; // Enforce one warp per thread block auto workDiv = typename ExecutionFixture::WorkDiv{ Vec::all(A.M), Vec::all(warpExtent), Vec::ones()}; auto fixture = ExecutionFixture{ workDiv, Q }; SECTION( "fpt::Alloc.reinit initializes correctly" ) { EmptyTestKernel<Dev> kernel; REQUIRE( fixture( kernel, N0, A.device() ) ); } SECTION( "fpt::Alloc.alloc test" ) { //EmptyTestKernel<Dev> kernel; //REQUIRE( fixture( kernel, N0, A.device() ) ); } SECTION( "fpt::Alloc.free test" ) { //EmptyTestKernel<Dev> kernel; //REQUIRE( fixture( kernel, N0, A.device() ) ); } } // TODO: - test alloc.alloc(acc, start) // - create new allocated data-layout and test read-speed
29.957895
94
0.549543
[ "vector" ]
e7172ab59a1f2abf0ecc0dc5676d4c0df802c399
31,678
cpp
C++
src/gui/ossimPlanetQtApplication.cpp
ossimlabs/ossim-planet-gui
d5e63187111090f51920f7929c05b368a7e4a28d
[ "MIT" ]
2
2018-11-28T10:04:38.000Z
2019-07-12T14:13:53.000Z
src/gui/ossimPlanetQtApplication.cpp
ossimlabs/ossim-planet-gui
d5e63187111090f51920f7929c05b368a7e4a28d
[ "MIT" ]
2
2019-01-28T23:22:28.000Z
2021-11-11T09:35:24.000Z
src/gui/ossimPlanetQtApplication.cpp
ossimlabs/ossim-planet-gui
d5e63187111090f51920f7929c05b368a7e4a28d
[ "MIT" ]
null
null
null
#include <ossimPlanetQt/ossimPlanetQtApplication.h> #include <QtCore/QDir> #include <ossim/base/ossimEnvironmentUtility.h> #include <ossim/init/ossimInit.h> #include <iostream> #include <osgDB/Registry> #include <osg/ArgumentParser> #include <osg/Drawable> #include <osg/Texture> #include <osg/ApplicationUsage> #include <ossim/base/ossimArgumentParser.h> #include <wms/wms.h> #include <ossim/base/ossimEnvironmentUtility.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimDirectory.h> #include <ossim/base/ossimNotify.h> #include <ossim/base/ossimGeoidEgm96.h> #include <ossim/base/ossimGeoidManager.h> #include <ossim/elevation/ossimElevManager.h> #include <ossimPlanet/ossimPlanetInteractionController.h> #include <ossimPlanet/ossimPlanetAction.h> #include <ossimPlanet/ossimPlanetActionRouter.h> QSettings* ossimPlanetQtApplication::theSettings = 0; QString ossimPlanetQtApplication::theUserSupportDirectory; QString ossimPlanetQtApplication::theUserDirectory; ossimPlanetQtApplication::ReferenceImageListType ossimPlanetQtApplication::theReferenceImages; std::vector<ossimFilename> ossimPlanetQtApplication::thePlugins; // bool ossimPlanetQtApplication::theElevEnabled = true; // ossim_float32 ossimPlanetQtApplication::theElevExag = 1.0; // ossim_float32 ossimPlanetQtApplication::theSplitMetricRatio = 3.0; // ossim_uint32 ossimPlanetQtApplication::theElevEstimate = 16; // ossimFilename ossimPlanetQtApplication::theElevCache = ""; // ossimPlanetLandType ossimPlanetQtApplication::theLandType = ossimPlanetLandType_NORMALIZED_ELLIPSOID; // ossim_uint32 ossimPlanetQtApplication::theLevelOfDetail= 20; // bool ossimPlanetQtApplication::theHudEnabled = true; // bool ossimPlanetQtApplication::theMipMapping = true; ossimFilename ossimPlanetQtApplication::theThemePath = ""; ossimFilename ossimPlanetQtApplication::theCompassRing = ""; //ossimFilename ossimPlanetQtApplication::theCompassRose = ""; //#define OSSIMPLANET_3D_CONNEXION // NOTE THIS IS ONLY TEST CODE for ossimPlanet roadmap docs to enhance future versions #ifdef OSSIMPLANET_3D_CONNEXION #include "3DconnexionClient/ConnexionClientAPI.h" #ifdef __MACOSX__ // extern OSErr InstallConnexionHandlers() __attribute__((weak_import)); static void tdx_drv_handler(io_connect_t connection, natural_t messageType, void *messageArgument); typedef struct { UInt16 clientID; /* ID assigned by the driver */ Boolean showClientEventsOnly; } TdxDeviceWrapperInfo, *TdxDeviceWrapperInfoPtr; TdxDeviceWrapperInfo gDevWrapperInfo; /* ========================================================================== */ // #pragma mark - // #pragma mark * Façade of 3DconnexionClient framework APIs * /* -------------------------------------------------------------------------- */ long ossimPlanetQtApplication::initInputDevices() // (UInt32 appID, // Boolean showOnlyMyClientEvents, // UInt16 mode, // UInt32 mask) { OSStatus err; gDevWrapperInfo.clientID = 0; gDevWrapperInfo.showClientEventsOnly = true; // gDevWrapperInfo.mainEventQueue = GetMainEventQueue(); /* make sure the framework is installed */ if (InstallConnexionHandlers == NULL) { ossimNotify(ossimNotifyLevel_WARN) << "3Dconnexion framework not found!\n" << std::endl; // fprintf(stderr, "3Dconnexion framework not found!\n"); return -1; } /* install 3dx message handler in order to receive driver events */ err = InstallConnexionHandlers(tdx_drv_handler, 0L, 0L); // assert(err == 0); // if (err) // return err; /* register our app with the driver */ // gDevWrapperInfo.clientID = RegisterConnexionClient('osPt', (UInt8*)"ossimplanet", kConnexionClientModeTakeOver, kConnexionMaskAll); gDevWrapperInfo.clientID = RegisterConnexionClient('osPt', 0, kConnexionClientModeTakeOver, kConnexionMaskAll); // if (gDevWrapperInfo.clientID == 0) // return -2; // std::cout << "CLIENT ID = " << gDevWrapperInfo.clientID << std::endl; // fprintf(stderr, "3Dconnexion device initialized. Client ID: %d\n", //gDevWrapperInfo.clientID); ossimPlanetAction(":iac tie axis0 LON").execute(); ossimPlanetAction(":iac tie axis1 LAT").execute(); ossimPlanetAction(":iac tie axis2 ZOOM").execute(); ossimPlanetAction(":iac tie axis3 PITCH").execute(); // ossimPlanetAction(":iac tie axis4 ROLL").execute(); ossimPlanetAction(":iac tie axis5 YAW").execute(); return err; } void ossimPlanetQtApplication::terminateInputDevices() { UInt16 wasConnexionOpen = gDevWrapperInfo.clientID; if (InstallConnexionHandlers == NULL) { return; } /* make sure the framework is installed */ // if (InstallConnexionHandlers == NULL) // return; /* close the connection with the 3dx driver */ if (wasConnexionOpen) { UnregisterConnexionClient(gDevWrapperInfo.clientID); } CleanupConnexionHandlers(); ///fprintf(stderr, "Terminated connection with 3Dconnexion device.\n"); } // bool ossimPlanetQtApplication::macEventFilter ( EventHandlerCallRef caller, EventRef event ) // { // long kind = GetEventKind(event); // if(gDevWrapperInfo.mainEventQueue) // { // std::cout << GetNumEventsInQueue(gDevWrapperInfo.mainEventQueue) << std::endl; // } // return QApplication::macEventFilter(caller, event); // } inline double dampen(double value) { // return value; #if 1 if(value > 1.0 || value < -1.0) return value; if(value < 0.0) return -(value*value); return value*value; #endif } static void tdx_drv_handler(io_connect_t connection, natural_t messageType, void *messageArgument) { static double normalizer = 500.0; static int minAxisValue = 1; static ConnexionDeviceState lastState; ConnexionDeviceStatePtr state = (ConnexionDeviceStatePtr)messageArgument; ossimPlanetInteractionController* iac = ossimPlanetInteractionController::instance(); switch(messageType) { case kConnexionMsgDeviceState: // std::cout << "client = " << state->client << std::endl; // std::cout << "myclient = " << gDevWrapperInfo.clientID << std::endl; /* Device state messages are broadcast to all clients. It is up to * the client to figure out if the message is meant for them. This * is done by comparing the "client" id sent in the message to our * assigned id when the connection to the driver was established. * * There is a special mode wherein all events are sent to this * client regardless if it was meant for it or not. This mode is * determined by the showClientEventOnly flag. */ if (!gDevWrapperInfo.showClientEventsOnly || state->client == gDevWrapperInfo.clientID) { switch (state->command) { case kConnexionCmdHandleAxis: { if((std::abs(state->axis[0]) <= minAxisValue)&& (std::abs(state->axis[1]) <= minAxisValue)) { if((std::abs(lastState.axis[0]) > minAxisValue)|| (std::abs(lastState.axis[1]) > minAxisValue)) { iac->updateInteractionValuators("axis0", 0.0); iac->updateInteractionValuators("axis1", 0.0); ossimPlanetAction(":navigator rotatestop").execute(); } } else { if((std::abs(lastState.axis[0]) <= minAxisValue)&& (std::abs(lastState.axis[1]) <= minAxisValue)) { iac->updateInteractionValuators("axis0", 0.0); iac->updateInteractionValuators("axis1", 0.0); ossimPlanetAction(":navigator rotatestart").execute(); } } // now do axis z if(std::abs(state->axis[2]) <= minAxisValue) { if(std::abs(lastState.axis[2])> minAxisValue) { iac->updateInteractionValuators("axis2", 0.0); ossimPlanetAction(":navigator loszoomstop").execute(); } } else { if(std::abs(lastState.axis[2]) <= minAxisValue) { iac->updateInteractionValuators("axis2", 0.0); ossimPlanetAction(":navigator loszoomstart").execute(); } } // now handle yaw and pitch that are associate to losrotatestart if((std::abs(state->axis[3]) <= minAxisValue)&& (std::abs(state->axis[5]) <= minAxisValue)) { if((std::abs(lastState.axis[3]) > minAxisValue)|| (std::abs(lastState.axis[5]) > minAxisValue)) { iac->updateInteractionValuators("axis3", 0.0); iac->updateInteractionValuators("axis5", 0.0); ossimPlanetAction(":navigator losrotatestop").execute(); } } else { if((std::abs(lastState.axis[3]) < minAxisValue)&& (std::abs(lastState.axis[5]) < minAxisValue)) { iac->updateInteractionValuators("axis3", 0.0); iac->updateInteractionValuators("axis5", 0.0); ossimPlanetAction(":navigator losrotatestart").execute(); } } iac->updateInteractionValuators("axis0", dampen(state->axis[0]/normalizer)); iac->updateInteractionValuators("axis1", dampen(state->axis[1]/normalizer)); iac->updateInteractionValuators("axis2", dampen(state->axis[2]/normalizer)); iac->updateInteractionValuators("axis3", dampen(state->axis[3]/normalizer)); iac->updateInteractionValuators("axis5", dampen(state->axis[5]/normalizer)); break; } case kConnexionCmdHandleButtons: { break; } default: break; } /* switch */ } BlockMoveData(state, &lastState, (long)sizeof(ConnexionDeviceState)); break; default: /* other messageTypes can happen and should be ignored */ break; } /* printf("connection: %X\n", connection); printf("messageType: %X\n", messageType); printf("version: %d\n", msg->version); printf("front app client: %d ourID: %d\n", msg->client, gDevWrapperInfo.clientID); printf("command: %u\n", msg->command); printf("value: %ld\n", msg->value); printf("param: %hd\n", msg->param); for (int i=0; i<8; i++) printf("report[%d]: %d\n", i, msg->report[i]); printf("buttons: %d\n", msg->buttons); printf("TX: %d\n", msg->axis[0]); printf("TY: %d\n", msg->axis[1]); printf("TZ: %d\n", msg->axis[2]); printf("RX: %d\n", msg->axis[3]); printf("RY: %d\n", msg->axis[4]); printf("RZ: %d\n", msg->axis[5]); printf("-----------------------------------------\n\n"); */ // printf("TX: %d\n", state->axis[0]); // printf("TY: %d\n", state->axis[1]); // printf("TZ: %d\n", state->axis[2]); // printf("RX: %d\n", state->axis[3]); // printf("RY: %d\n", state->axis[4]); // printf("RZ: %d\n", state->axis[5]); } #else long ossimPlanetQtApplication::initInputDevices() { return 0; } void ossimPlanetQtApplication::terminateInputDevices() { return; } #endif // __MACOSX__ #else long ossimPlanetQtApplication::initInputDevices() { return 0; } void ossimPlanetQtApplication::terminateInputDevices() { return; } #endif //OSSIMPLANET_3D_CONNEXION #if !defined(_WIN32) && !defined(__WIN32__) && !defined(_MSC_VER) #include <unistd.h> #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/errno.h> int setMaximumFiles(int filecount) { struct rlimit lim; lim.rlim_cur = lim.rlim_max = (rlim_t)filecount; if ( setrlimit(RLIMIT_NOFILE, &lim) == 0 ) { return 0; } else { return errno; } } int getMaximumFiles() { struct rlimit lim; if ( getrlimit(RLIMIT_NOFILE, &lim) == 0 ) { return (long)lim.rlim_max; } return 0; } #else int setMaximumFiles(int /*filecount*/) { return 0; } int getMaximumFiles() { return 0; } #endif /*! \class ossimPlanetQtApplication \brief The ossimPlanetQtApplication class manages application-wide information. This is a subclass of QApplication and should be instantiated in place of QApplication. Most methods are static in keeping witn the design of QApplication. This class hides platform-specific path information and provides a portable way of referencing specific files and directories. Ideally, hard-coded paths should appear only here and not in other modules so that platform-conditional code is minimized and paths are easier to change due to centralization. */ ossimPlanetQtApplication::ossimPlanetQtApplication(int & argc, char ** argv, bool guiEnabled) : QApplication(argc, argv, guiEnabled) { setOrganizationName("OSSIM"); setOrganizationDomain("planet.ossim.org"); setApplicationName("OSSIM Planet"); theSettings = new QSettings("planet.ossim.org"); theUserSupportDirectory = ossimEnvironmentUtility::instance()->getUserOssimSupportDir(); theUserDirectory = ossimEnvironmentUtility::instance()->getUserDir(); } ossimPlanetQtApplication::~ossimPlanetQtApplication() { if(theSettings) { delete theSettings; theSettings = 0; } ossimPlanetActionRouter::instance()->shutdown(); } bool ossimPlanetQtApplication::initWithArgs(int& argc, char** argv) { //osg::Texture::setMinimumNumberOfTextureObjectsToRetainInCache(0); osg::Drawable::setMinimumNumberOfDisplayListsToRetainInCache(0); //osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts(1); if(getMaximumFiles() < 1024) { setMaximumFiles(1024); } // setMaximumFiles(25); //osgDB::DatabasePager* databasePager = osgDB::Registry::instance()->getOrCreateDatabasePager(); ossimArgumentParser argumentParser(&argc, argv); wmsInitialize(); ossimInit::instance()->setPluginLoaderEnabledFlag(false); ossimInit::instance()->initialize(argumentParser); osg::ArgumentParser arguments(&argumentParser.argc(),argumentParser.argv()); std::string tempString; osg::ArgumentParser::Parameter stringParam(tempString); addCommandLineOptions(arguments); if(arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return false; } // if(arguments.read("--enable-flatland")) // { // theLandType = ossimPlanetLandType_FLAT; // } if(arguments.read("--wms-timeout", stringParam)) { setWmsNetworkTimeoutInSeconds(ossimString(tempString).toDouble()); } if(arguments.read("--disable-elevation")) { // theElevEnabled = false; writePreferenceSetting("elev-flag", "false"); } if(arguments.read("--elev-estimation", stringParam)) { // theElevEstimate = 1<<ossimString(tempString.c_str()).toUInt32(); writePreferenceSetting("elev-patchsize", ossimString::toString(1<<ossimString(tempString.c_str()).toUInt32()).c_str()); } if(arguments.read("--elev-patchsize", stringParam)) { writePreferenceSetting("elev-patchsize", tempString.c_str()); // theElevEstimate = ossimString(tempString.c_str()).toUInt32(); } if(arguments.read("--elev-exag", stringParam)) { // theElevExag = ossimString(tempString.c_str()).toDouble(); writePreferenceSetting("elev-exag", tempString.c_str()); } if(arguments.read("--split-metric", stringParam)) { // theSplitMetricRatio = ossimString(tempString.c_str()).toDouble(); writePreferenceSetting("split-metric", tempString.c_str()); } if(arguments.read("--elev-cache", stringParam)) { // theElevCache = tempString.c_str(); writePreferenceSetting("elev-cache", tempString.c_str()); } if(arguments.read("--level-detail", stringParam)) { // theLevelOfDetail = ossimString(tempString.c_str()).toUInt32(); writePreferenceSetting("level-detail", tempString.c_str()); } if(arguments.read("--enable-hud")) { writePreferenceSetting("hud-flag", "true"); // theHudEnabled = true; } else if(arguments.read("--disable-hud")) { writePreferenceSetting("hud-flag", "false"); } // archive mapping enabled if( arguments.read("--enable-archive-mapping-enabled") ) { writePreferenceSetting("archive-mapping-enabled", "true"); } else if( arguments.read("--disable-archive-mapping-enabled") ) { writePreferenceSetting("archive-mapping-enabled", "false"); } if(arguments.read("--disable-mipmap")) { writePreferenceSetting("mipmap-flag", "false"); // theMipMapping = false; } if(arguments.read("--enable-mipmap")) { writePreferenceSetting("mipmap-flag", "true"); // theMipMapping = false; } arguments.reportRemainingOptionsAsUnrecognized(); if (arguments.errors()) { arguments.writeErrorMessages(std::cout); } ossimFilename currentPath = ossimFilename(argv[0]).path(); ossimFilename imageBundle; ossimFilename referenceImageBundle; ossimInit::instance()->setPluginLoaderEnabledFlag(true); // ossimString paths = ossimEnvironmentUtility::instance()->getEnvironmentVariable("OSSIM_ELEVATION_PATH"); // std::vector<ossimString> pathArray; // ossimString pathSeparator = ":"; osgDB::Registry::instance()->getDataFilePathList().push_back(theUserSupportDirectory.toStdString()); ossimFilename installDir = ossimEnvironmentUtility::instance()->getInstalledOssimSupportDir(); if(installDir.exists()) { osgDB::Registry::instance()->getDataFilePathList().push_back(installDir); } ossimFilename userDir = ossimEnvironmentUtility::instance()->getUserOssimSupportDir(); ossimFilename userImageDir = userDir.dirCat("images"); ossimFilename userDataDir = userDir.dirCat("data"); ossimFilename userImageReferenceDir = userImageDir.dirCat("reference"); ossimFilename installImageDir = installDir.dirCat("images"); ossimFilename installDataDir = installDir.dirCat("data"); ossimFilename instalImageReferenceDir = installImageDir.dirCat("reference"); userDir = userDir.dirCat("images"); userDir = userDir.dirCat("reference"); installDir = installDir.dirCat("images"); installDir = installDir.dirCat("reference"); // tmp drb // ossimFilename userStatePlaneFile = userDataDir.dirCat("state_plane.csv"); // ossimFilename installStatePlaneFile = installDataDir.dirCat("state_plane.csv"); // if(userStatePlaneFile.exists()) // { // allow state plane to override from user directory any installed state plane file. // ossimStatePlaneProjectionFactory::instance()->addCsvFile(userStatePlaneFile); // } #ifdef __MACOSX__ // test for a bundle // ossimFilename contentsFolder = currentPath.path(); // Check for embedded geoid grid nder the resource folder Resources/egm96.grd ossimFilename resourceFolder = contentsFolder.dirCat("Resources"); ossimFilename geoid1996File = resourceFolder.dirCat("egm96.grd"); ossimFilename statePlaneFile = resourceFolder.dirCat("state_plane.csv"); if(geoid1996File.exists()) { ossimRefPtr<ossimGeoid> geoid96 = new ossimGeoidEgm96; if(geoid96->open(geoid1996File, OSSIM_BIG_ENDIAN)) { ossimGeoidManager::instance()->addGeoid(geoid96.get()); } } // if(statePlaneFile.exists()) // { // ossimStatePlaneProjectionFactory::instance()->addCsvFile(statePlaneFile); // } // Check for embedded plugins and reference images ossimFilename resources = contentsFolder.dirCat("Resources"); ossimFilename ossimPluginsBundle = contentsFolder.dirCat("plugins"); ossimFilename osgPlugins = contentsFolder.dirCat("osgplugins"); referenceImageBundle = contentsFolder.dirCat("Resources"); imageBundle = referenceImageBundle.dirCat("images"); referenceImageBundle = imageBundle.dirCat("reference"); if(ossimPluginsBundle.exists()) { ossimInit::instance()->loadPlugins(ossimPluginsBundle); } if(osgPlugins.exists()) { osgDB::Registry::instance()->getLibraryFilePathList().push_front(osgPlugins); } if(resources.exists()) { osgDB::Registry::instance()->getDataFilePathList().push_front(resources); osgDB::Registry::instance()->getDataFilePathList().push_front(resources.dirCat("fonts")); } theThemePath = resourceFolder; theThemePath = theThemePath.dirCat("themes"); ossimFilename elevation = resourceFolder.dirCat("elevation"); if(elevation.exists()) { ossimElevManager::instance()->loadElevationPath(elevation); } // addLibraryPath(contentsFolder.dirCat("qtplugins").c_str()); #endif #ifdef WIN32 ossimFilename geoid = currentPath.dirCat("geoid1996"); ossimFilename geoid1996File = geoid.dirCat("egm96.grd"); if(!geoid1996File.exists()) { geoid = currentPath.dirCat("geoids"); geoid = geoid.dirCat("geoid1996"); geoid1996File = geoid.dirCat("egm96.grd"); } if(geoid1996File.exists()) { ossimRefPtr<ossimGeoid> geoid96 = new ossimGeoidEgm96; if(geoid96->open(geoid1996File, OSSIM_BIG_ENDIAN)) { ossimGeoidManager::instance()->addGeoid(geoid96.get()); } } ossimFilename osgPluginsBundle = currentPath.dirCat("osgplugins"); // ossimFilename ossimPluginsBundle = currentPath.dirCat("plugins"); referenceImageBundle = currentPath; imageBundle = referenceImageBundle.dirCat("images"); referenceImageBundle = imageBundle.dirCat("reference"); if(osgPluginsBundle.exists()) { osgDB::Registry::instance()->getLibraryFilePathList().push_back(osgPluginsBundle); } // if(ossimPluginsBundle.exists()) // { // ossimInit::instance()->loadPlugins(ossimPluginsBundle); // } ossimFilename elevation = currentPath.dirCat("elevation"); if(elevation.exists()) { ossimElevManager::instance()->loadElevationPath(elevation); } // pathSeparator = ";"; #endif ossimFilename dataDir = currentPath.dirCat("data"); // tmp drb // ossimFilename statePlane = dataDir.dirCat("state_plane.csv"); // if(statePlane.exists()) // { // ossimStatePlaneProjectionFactory::instance()->addCsvFile(statePlane); //} // we will now initialize any other plugins outside the bundle in standard locations // // if(installStatePlaneFile.exists()) // { // ossimStatePlaneProjectionFactory::instance()->addCsvFile(installStatePlaneFile); // } ossimInit::instance()->initializePlugins(); if(arguments.argc() > 1) { ossimKeywordlist kwl; if(kwl.addFile(arguments.argv()[1])) { osg::ref_ptr<ossimPlanetTextureLayer> layer = ossimPlanetTextureLayerRegistry::instance()->createLayer(kwl.toString()); if(layer.valid()) { layer->resetLookAt(); theReferenceImages.push_front(layer); } } } else { ossimFilename refFiles; if(userDir.exists()) { refFiles = userDir; } else if(installDir.exists()) { refFiles = installDir; } else if(referenceImageBundle.exists()) { refFiles = referenceImageBundle; } if(refFiles.exists()) { ossimDirectory dir; if(dir.open(refFiles)) { ossimFilename file; dir.getFirst(file); do { ossimString ext = file.ext(); if((ext != "ovr")&& (ext != "omd")&& (ext != "geom")&& (ext != "his")) { osg::ref_ptr<ossimPlanetTextureLayer> layer = ossimPlanetTextureLayerRegistry::instance()->createLayer(ossimString(file.c_str())); if(layer.valid()) { layer->resetLookAt(); theReferenceImages.push_front(layer); } } }while(dir.getNext(file)); } } } if(userImageDir.dirCat("compass.png").exists()) { theCompassRing = userImageDir.dirCat("compass.png"); } else if(imageBundle.dirCat("compass.png").exists()) { theCompassRing = imageBundle.dirCat("compass.png"); } else if(installImageDir.dirCat("compassring.png").exists()) { theCompassRing = installImageDir.dirCat("compassring.png"); //theCompassRose = installImageDir.dirCat("compassrose.png"); } else if(userImageDir.dirCat("compassring.png").exists()) { theCompassRing = userImageDir.dirCat("compassring.png"); //theCompassRose = userImageDir.dirCat("compassrose.png"); } else if(imageBundle.dirCat("compassring.png").exists()) { theCompassRing = imageBundle.dirCat("compassring.png"); //theCompassRose = imageBundle.dirCat("compassrose.png"); } else if(installImageDir.dirCat("compassring.png").exists()) { theCompassRing = installImageDir.dirCat("compassring.png"); //theCompassRose = installImageDir.dirCat("compassrose.png"); } if(autoHistogramStretchMode().isEmpty()) { setAutoHistogramStretchMode("Linear Auto Min Max"); } return true; } ossimFilename ossimPlanetQtApplication::compassRing() { return theCompassRing; } #if 0 ossimFilename ossimPlanetQtApplication::compassRose() { return theCompassRose; } #endif QStringList ossimPlanetQtApplication::wmsSettingsSubkeyList() { return settingsSubKeyList("/ossim/connections-wms"); } QString ossimPlanetQtApplication::readWmsSettingsEntry(const QString& key) { return readSettingsEntry("/ossim/connections-wms/" + key); } void ossimPlanetQtApplication::writeWmsSettingsEntry(const QString& key, const QString& value) { writeSettingsValue("/ossim/connections-wms/" + key, value); } void ossimPlanetQtApplication::removeWmsSettingsKey(const QString& key) { settingsRemoveKey("/ossim/connections-wms/" + key); } QStringList ossimPlanetQtApplication::preferenceSettingsSubkeyList(const QString& key) { if(key == "") { return settingsSubKeyList("/planet/preferences"); } return settingsSubKeyList("/planet/preferences/" + key); } void ossimPlanetQtApplication::removePreferenceSetting(const QString& key) { settingsRemoveKey("/planet/preferences/" + key); } QString ossimPlanetQtApplication::readPreferenceSetting(const QString& key) { return readSettingsEntry("/planet/preferences/" + key); } void ossimPlanetQtApplication::writePreferenceSetting(const QString& key, const QString& value) { writeSettingsValue("/planet/preferences/" + key, value); } QString ossimPlanetQtApplication::readSettingsEntry(const QString& entry) { return theSettings->value(entry, "").toString(); } QStringList ossimPlanetQtApplication::settingsSubKeyList(const QString& key) { theSettings->beginGroup(key); QStringList result = theSettings->childGroups(); theSettings->endGroup(); return result; } void ossimPlanetQtApplication::writeSettingsValue(const QString& key, const QString& value) { theSettings->setValue(key, value); } void ossimPlanetQtApplication::settingsRemoveKey(const QString& key) { theSettings->remove(key); } void ossimPlanetQtApplication::addCommandLineOptions(osg::ArgumentParser& args) { args.getApplicationUsage()->setApplicationName(args.getApplicationName()); args.getApplicationUsage()->setDescription(args.getApplicationName()+" is the test application for accessing wms servers."); args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName()+" [options] ..."); args.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); args.getApplicationUsage()->addCommandLineOption("--enable-flatland", "Uses the flat land model"); args.getApplicationUsage()->addCommandLineOption("--disable-elevation", "Uses elevation"); args.getApplicationUsage()->addCommandLineOption("--elev-estimation", "number of levels to estimate. A value of 4 will say 2^4 or 16 number of rows and cols."); args.getApplicationUsage()->addCommandLineOption("--split-metric", "set Split Metric Ratio. Default is 3.0"); args.getApplicationUsage()->addCommandLineOption("--elev-patchsize", "number of points in each chunk."); args.getApplicationUsage()->addCommandLineOption("--elev-exag", "Multiplier for the height values"); args.getApplicationUsage()->addCommandLineOption("--elev-cache", "Cache directory for elevation"); args.getApplicationUsage()->addCommandLineOption("--level-detail", "Maximum level of detail to split to. Default is 16 levels"); args.getApplicationUsage()->addCommandLineOption("--enable-hud", "Enables the lat lon read outs"); args.getApplicationUsage()->addCommandLineOption("--disable-hud", "Disable the lat lon read outs"); args.getApplicationUsage()->addCommandLineOption("--disable-mipmap", "Doesn't use MipMapping"); args.getApplicationUsage()->addCommandLineOption("--enable-mipmap", "Use MipMapping"); args.getApplicationUsage()->addCommandLineOption("--wms-timeout", "Time out for WMS get Capabiltites for the WmsDialog specified in seconds"); } QString ossimPlanetQtApplication::userSupportDirectory() { return theUserSupportDirectory; } QString ossimPlanetQtApplication::userDirectory() { return theUserDirectory; } QString ossimPlanetQtApplication::sessionDirectory() { QString result = currentOpenSessionDirectory(); if(result=="") { ossimFilename dir(userSupportDirectory().toStdString()); dir = dir.dirCat("planet"); dir = dir.dirCat("session"); result = dir.c_str(); } return result; } QString ossimPlanetQtApplication::defaultSession() { ossimFilename dir(sessionDirectory().toStdString()); dir = dir.dirCat("default.session"); return dir.c_str(); } QString ossimPlanetQtApplication::defaultWmsCacheDir() { ossimFilename dir(userSupportDirectory().toStdString()); dir = dir.dirCat("planet"); dir = dir.dirCat("wms"); dir = dir.dirCat("cache"); return dir.c_str(); }
35.633296
164
0.641328
[ "vector", "model" ]
e71a0bc5e850f60dcb53c8d1396c532dbbd7d35d
684
cpp
C++
leetcode/hash_table/contains_duplicate_II.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
leetcode/hash_table/contains_duplicate_II.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
leetcode/hash_table/contains_duplicate_II.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
#include <doctest/doctest.h> #include <unordered_map> #include <vector> // 219. Contains Duplicate II class Solution { public: bool containsNearbyDuplicate(const std::vector<int>& nums, int k) { std::unordered_map<int, int> map; for (int i = 0; i < static_cast<int>(nums.size()); ++i) { if (map.find(nums[i]) != map.end() && i - map[nums[i]] <= k) { return true; } map[nums[i]] = i; } return false; } }; TEST_CASE("Contains Duplicate II") { Solution s; REQUIRE(s.containsNearbyDuplicate({1, 2, 3, 1}, 3)); REQUIRE(s.containsNearbyDuplicate({1, 0, 1, 1}, 1)); REQUIRE_FALSE(s.containsNearbyDuplicate({1, 2, 3, 1, 2, 3}, 2)); }
25.333333
69
0.611111
[ "vector" ]
e71a10e269634d36c2ac635f8ae977473d256cd6
4,947
cpp
C++
src/base/ossimAdjustmentInfo.cpp
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
251
2015-10-20T09:08:11.000Z
2022-03-22T18:16:38.000Z
src/base/ossimAdjustmentInfo.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
73
2015-11-02T17:12:36.000Z
2021-11-15T17:41:47.000Z
src/base/ossimAdjustmentInfo.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
146
2015-10-15T16:00:15.000Z
2022-03-22T12:37:14.000Z
//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // LICENSE: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAdjustmentInfo.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include <ossim/base/ossimAdjustmentInfo.h> #include <ossim/base/ossimKeywordNames.h> static const char* PARAM_PREFIX = "adj_param_"; static const char* NUMBER_OF_PARAMS_KW = "number_of_params"; static const char* DIRTY_FLAG_KW = "dirty_flag"; std::ostream& operator <<(std::ostream& out, const ossimAdjustmentInfo& data) { ossim_int32 idx = 0; out << "Description: " << data.getDescription() << "\nNumber of Params: " << data.theParameterList.size() << "\nDirty flag: " << data.theDirtyFlag << std::endl; for(idx = 0; idx < (int)data.getNumberOfAdjustableParameters(); ++idx) { out << "Param " << idx << std::endl; out << data.theParameterList[idx] << std::endl; } return out; } ossimAdjustmentInfo::ossimAdjustmentInfo(int numberOfAdjustableParameters) :theParameterList(numberOfAdjustableParameters), theDescription(""), theDirtyFlag(false) { } ossimAdjustmentInfo::ossimAdjustmentInfo(const ossimAdjustmentInfo& rhs) :theParameterList(rhs.theParameterList), theDescription(rhs.theDescription), theDirtyFlag(rhs.theDirtyFlag) { } void ossimAdjustmentInfo::setNumberOfAdjustableParameters(ossim_uint32 numberOfAdjustableParameters) { std::vector<ossimAdjustableParameterInfo> temp = theParameterList; theParameterList.resize(numberOfAdjustableParameters); if(temp.size() < numberOfAdjustableParameters) { std::copy(temp.begin(), temp.end(), theParameterList.begin()); } else if(temp.size() > numberOfAdjustableParameters) { if(numberOfAdjustableParameters > 0) { std::copy(temp.begin(), temp.begin()+numberOfAdjustableParameters, theParameterList.begin()); } } } ossim_uint32 ossimAdjustmentInfo::getNumberOfAdjustableParameters()const { return (ossim_uint32)theParameterList.size(); } ossimString ossimAdjustmentInfo::getDescription()const { return theDescription; } void ossimAdjustmentInfo::setDescription(const ossimString& description) { theDescription = description; } bool ossimAdjustmentInfo::isDirty()const { return theDirtyFlag; } void ossimAdjustmentInfo::setDirtyFlag(bool flag) { theDirtyFlag = flag; } void ossimAdjustmentInfo::setLockFlag(bool flag, ossim_uint32 idx) { if(idx < theParameterList.size()) { theParameterList[idx].setLockFlag(flag); } } void ossimAdjustmentInfo::keep() { ossim_uint32 idx = 0; for(idx = 0; idx < theParameterList.size();++idx) { double center = theParameterList[idx].computeOffset(); theParameterList[idx].setParameter(0.0); theParameterList[idx].setCenter(center); } } std::vector<ossimAdjustableParameterInfo>& ossimAdjustmentInfo::getParameterList() { return theParameterList; } const std::vector<ossimAdjustableParameterInfo>& ossimAdjustmentInfo::getParameterList()const { return theParameterList; } bool ossimAdjustmentInfo::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { kwl.add(prefix, ossimKeywordNames::DESCRIPTION_KW, getDescription(), true); kwl.add(prefix.c_str(), NUMBER_OF_PARAMS_KW, static_cast<ossim_uint32>(theParameterList.size()), true); kwl.add(prefix, DIRTY_FLAG_KW, (short)theDirtyFlag, true); ossimString value; for(ossim_uint32 idx = 0; idx < theParameterList.size();++idx) { ossimString newPrefix = ossimString(prefix) + (ossimString(PARAM_PREFIX) + ossimString::toString(idx)+"."); theParameterList[idx].saveState(kwl, newPrefix.c_str()); } return true; } bool ossimAdjustmentInfo::loadState(const ossimKeywordlist& kwl, const ossimString& prefix) { setDescription(kwl.find(prefix, ossimKeywordNames::DESCRIPTION_KW)); setNumberOfAdjustableParameters(ossimString(kwl.find(prefix, NUMBER_OF_PARAMS_KW)).toUInt32()); const char *dirtyFlag = kwl.find(prefix, DIRTY_FLAG_KW); ossimString value; if(dirtyFlag) { theDirtyFlag = ossimString(dirtyFlag).toBool(); } else { theDirtyFlag = false; } for(ossim_uint32 idx = 0; idx < theParameterList.size();++idx) { ossimString newPrefix = ossimString(prefix) + (ossimString(PARAM_PREFIX) + ossimString::toString(idx)+"."); if(!theParameterList[idx].loadState(kwl, newPrefix.c_str())) { return false; } } return true; }
26.88587
113
0.653527
[ "vector" ]
e71c0dbecfc03d217f425dd307496e33747a8c1a
5,157
cc
C++
src/c4/C4_Req.cc
rspavel/Draco
b279b1afbfbb39f2d521579697172394c5efd81d
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/c4/C4_Req.cc
rspavel/Draco
b279b1afbfbb39f2d521579697172394c5efd81d
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/c4/C4_Req.cc
rspavel/Draco
b279b1afbfbb39f2d521579697172394c5efd81d
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
//----------------------------------*-C++-*----------------------------------// /*! * \file c4/C4_Req.cc * \author Thomas M. Evans, Geoffrey Furnish * \date Thu Jun 2 09:54:02 2005 * \brief C4_Req member definitions. * \note Copyright (C) 2016-2019 Triad National Security, LLC. * All rights reserved. */ //---------------------------------------------------------------------------// #include "C4_Req.hh" // #include <iostream> namespace rtt_c4 { //---------------------------------------------------------------------------// /*! * \brief Constructor. * * Register a new non blocking message request. */ //---------------------------------------------------------------------------// C4_Req::C4_Req() : p(new C4_ReqRefRep) { ++p->n; } //---------------------------------------------------------------------------// /*! * \brief Copy constructor. * * Attach to an existing message request. */ //---------------------------------------------------------------------------// C4_Req::C4_Req(const C4_Req &req) : p(NULL) { if (req.inuse()) p = req.p; else p = new C4_ReqRefRep; ++p->n; } //---------------------------------------------------------------------------// /*! * \brief Destructor. * * If we've been left holding the bag, make sure the message has completed. * This should plug a wide class of potential programming errors. */ //---------------------------------------------------------------------------// C4_Req::~C4_Req() { free_(); } //---------------------------------------------------------------------------// /*! * \brief Assignment. * * Detach from our prior message request, waiting on it if necessary. Then * attach to the new one. */ //---------------------------------------------------------------------------// C4_Req &C4_Req::operator=(const C4_Req &req) { free_(); if (req.inuse()) p = req.p; else p = new C4_ReqRefRep; ++p->n; return *this; } //---------------------------------------------------------------------------// /*! * Utility for cleaning up letter in letter/envelope idiom */ //----------------------------------------------------------------------------// /* private */ void C4_Req::free_() { --p->n; if (p->n <= 0) delete p; } void C4_ReqRefRep::free() { #ifdef C4_MPI if (assigned) { MPI_Cancel(&r); MPI_Request_free(&r); } #endif clear(); } //---------------------------------------------------------------------------// /*! * \brief Constructor. * * Register a new non blocking message request. */ //---------------------------------------------------------------------------// C4_ReqRefRep::C4_ReqRefRep() : n(0), assigned(false) #ifdef C4_MPI , r(MPI_Request()) #endif { // empty } //---------------------------------------------------------------------------// /*! * \brief Destructor. * * It is important that all existing requests are cleared before the destructor * is called. We used to have a wait() in here; however, this causes exception * safety problems. In any case, it is probably a bad idea to clean up * communication by going out of scope. */ //---------------------------------------------------------------------------// C4_ReqRefRep::~C4_ReqRefRep() { /* empty */ } //---------------------------------------------------------------------------// /*! * \brief Wait for an asynchronous message to complete. * \param status Status object. * * This function is non-const because it updates the underlying request data * member. */ // ---------------------------------------------------------------------------// #ifdef C4_MPI void C4_ReqRefRep::wait(C4_Status *status) { if (assigned) { MPI_Status *s = MPI_STATUS_IGNORE; if (status) { s = status->get_status_obj(); Check(s); } MPI_Wait(&r, s); } clear(); } #elif defined(C4_SCALAR) void C4_ReqRefRep::wait(C4_Status * /*status*/) { clear(); } #endif //---------------------------------------------------------------------------// /*! * \brief Tests for the completion of a non blocking operation. * \param status Status object. * * This function is non-const because it updates the underlying request data * member. */ //---------------------------------------------------------------------------// #ifdef C4_MPI bool C4_ReqRefRep::complete(C4_Status *status) { int flag = 0; bool indicator = false; if (assigned) { MPI_Status *s = MPI_STATUS_IGNORE; if (status) { s = status->get_status_obj(); Check(s); } MPI_Test(&r, &flag, s); } if (flag != 0) { clear(); Check(r == MPI_REQUEST_NULL); indicator = true; } return indicator; // throw "C4_Req::complete() has not been implemented for this communicator"; } #elif defined(C4_SCALAR) bool C4_ReqRefRep::complete(C4_Status * /*status*/) { return true; // throw "C4_Req::complete() has not been implemented in scalar mode."; } #endif } // end namespace rtt_c4 //---------------------------------------------------------------------------// // end of C4_Req.cc //---------------------------------------------------------------------------//
26.177665
80
0.421563
[ "object" ]
e71cd9cae7f6ef6cd3db69cb654aec5e92dc6bd3
2,782
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/IfcCurveInterpolationEnum.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
1
2018-10-23T09:43:07.000Z
2018-10-23T09:43:07.000Z
IfcPlusPlus/src/ifcpp/IFC4/IfcCurveInterpolationEnum.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/IfcCurveInterpolationEnum.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
null
null
null
/* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/shared_ptr.h" #include "ifcpp/model/IfcPPException.h" #include "include/IfcCurveInterpolationEnum.h" // TYPE IfcCurveInterpolationEnum = ENUMERATION OF (LINEAR ,LOG_LINEAR ,LOG_LOG ,NOTDEFINED); IfcCurveInterpolationEnum::IfcCurveInterpolationEnum() {} IfcCurveInterpolationEnum::~IfcCurveInterpolationEnum() {} shared_ptr<IfcPPObject> IfcCurveInterpolationEnum::getDeepCopy( IfcPPCopyOptions& options ) { shared_ptr<IfcCurveInterpolationEnum> copy_self( new IfcCurveInterpolationEnum() ); copy_self->m_enum = m_enum; return copy_self; } void IfcCurveInterpolationEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCCURVEINTERPOLATIONENUM("; } if( m_enum == ENUM_LINEAR ) { stream << ".LINEAR."; } else if( m_enum == ENUM_LOG_LINEAR ) { stream << ".LOG_LINEAR."; } else if( m_enum == ENUM_LOG_LOG ) { stream << ".LOG_LOG."; } else if( m_enum == ENUM_NOTDEFINED ) { stream << ".NOTDEFINED."; } if( is_select_type ) { stream << ")"; } } shared_ptr<IfcCurveInterpolationEnum> IfcCurveInterpolationEnum::createObjectFromSTEP( const std::wstring& arg ) { // read TYPE if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcCurveInterpolationEnum>(); } else if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcCurveInterpolationEnum>(); } shared_ptr<IfcCurveInterpolationEnum> type_object( new IfcCurveInterpolationEnum() ); if( boost::iequals( arg, L".LINEAR." ) ) { type_object->m_enum = IfcCurveInterpolationEnum::ENUM_LINEAR; } else if( boost::iequals( arg, L".LOG_LINEAR." ) ) { type_object->m_enum = IfcCurveInterpolationEnum::ENUM_LOG_LINEAR; } else if( boost::iequals( arg, L".LOG_LOG." ) ) { type_object->m_enum = IfcCurveInterpolationEnum::ENUM_LOG_LOG; } else if( boost::iequals( arg, L".NOTDEFINED." ) ) { type_object->m_enum = IfcCurveInterpolationEnum::ENUM_NOTDEFINED; } return type_object; }
36.12987
113
0.719986
[ "model" ]
e71e8c44857d75421a4a02d1f1420d9b1a4ab8f0
1,561
cpp
C++
problemes/probleme0xx/probleme070.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
6
2015-10-13T17:07:21.000Z
2018-05-08T11:50:22.000Z
problemes/probleme0xx/probleme070.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
null
null
null
problemes/probleme0xx/probleme070.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
null
null
null
#include "problemes.h" #include "chiffres.h" #include "premiers.h" #include "utilitaires.h" typedef unsigned long long nombre; typedef std::vector<nombre> vecteur; typedef boost::rational<nombre> fraction; ENREGISTRER_PROBLEME(70, "Totient permutation") { // Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the // number of positive numbers less than or equal to n which are relatively prime to n. For // example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6. // // The number 1 is considered to be relatively prime to every positive number, so φ(1)=1. // // Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of 79180. // // Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and the ratio n/φ(n) // produces a minimum. vecteur premiers; premiers::crible23<nombre>(5000, std::back_inserter(premiers)); fraction min_ratio(std::numeric_limits<nombre>::max()); nombre min_n = 0; for (auto p: premiers) { for (auto q: premiers) { if (q >= p) break; const nombre n = p * q; if (n > 10000000) break; const nombre phi = (p - 1) * (q - 1); fraction ratio(n, phi); if (ratio < min_ratio && chiffres::permutation_chiffres(n, phi)) { min_ratio = ratio; min_n = n; } } } return std::to_string(min_n); }
36.302326
101
0.598334
[ "vector" ]
e71ea21d172c8574c561809e697dd7345a67032b
1,118
hpp
C++
src/mlpack/methods/gmm/no_constraint.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4,216
2015-01-01T02:06:12.000Z
2022-03-31T19:12:06.000Z
src/mlpack/methods/gmm/no_constraint.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2,621
2015-01-01T01:41:47.000Z
2022-03-31T19:01:26.000Z
src/mlpack/methods/gmm/no_constraint.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1,972
2015-01-01T23:37:13.000Z
2022-03-28T06:03:41.000Z
/** * @file methods/gmm/no_constraint.hpp * @author Ryan Curtin * * No constraint on the covariance matrix. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_GMM_NO_CONSTRAINT_HPP #define MLPACK_METHODS_GMM_NO_CONSTRAINT_HPP #include <mlpack/prereqs.hpp> namespace mlpack { namespace gmm { /** * This class enforces no constraint on the covariance matrix. It's faster this * way, although depending on your situation you may end up with a * non-invertible covariance matrix. */ class NoConstraint { public: //! Do nothing, and do not modify the covariance matrix. static void ApplyConstraint(const arma::mat& /* covariance */) { } //! Serialize the object (nothing to do). template<typename Archive> static void serialize(Archive& /* ar */, const uint32_t /* version */) { } }; } // namespace gmm } // namespace mlpack #endif
27.95
80
0.72898
[ "object" ]
e720eb4c4cf0920cec3f3b5ed6fbe125d0a8abdf
15,997
cc
C++
dcmsr/tests/tsrcmr.cc
nikkoara/dcmtk
ef914cfb892c6bac9097cad50b5c889acbe6b7e5
[ "Apache-2.0" ]
3
2017-04-14T15:09:38.000Z
2020-05-08T10:09:22.000Z
dcmsr/tests/tsrcmr.cc
nikkoara/dcmtk
ef914cfb892c6bac9097cad50b5c889acbe6b7e5
[ "Apache-2.0" ]
null
null
null
dcmsr/tests/tsrcmr.cc
nikkoara/dcmtk
ef914cfb892c6bac9097cad50b5c889acbe6b7e5
[ "Apache-2.0" ]
3
2017-04-14T15:09:41.000Z
2022-01-27T23:23:35.000Z
/* * * Copyright (C) 2015, J. Riesmeier, Oldenburg, Germany * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation are maintained by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmsr * * Author: Joerg Riesmeier * * Purpose: * test program for various CIDxxx and TIDxxx classes from the "Content Mapping Resource" * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/ofstd/oftest.h" #include "dcmtk/dcmsr/dsrnumvl.h" #include "dcmtk/dcmsr/dsrnumtn.h" #include "dcmtk/dcmsr/codes/dcm.h" #include "dcmtk/dcmsr/cmr/init.h" #include "dcmtk/dcmsr/cmr/cid29e.h" #include "dcmtk/dcmsr/cmr/cid42.h" #include "dcmtk/dcmsr/cmr/cid244e.h" #include "dcmtk/dcmsr/cmr/cid4031e.h" #include "dcmtk/dcmsr/cmr/cid7445.h" #include "dcmtk/dcmsr/cmr/cid10013e.h" #include "dcmtk/dcmsr/cmr/cid10033e.h" #include "dcmtk/dcmsr/cmr/tid1001.h" #include "dcmtk/dcmsr/cmr/tid1204.h" #include "dcmtk/dcmsr/cmr/tid1600.h" #include "dcmtk/dcmsr/cmr/srnumvl.h" OFTEST(dcmsr_CID29e_AcquisitionModality) { CID29e_AcquisitionModality ctxGroup; DSRCodedEntryValue codedEntry; OFCHECK(!ctxGroup.hasSelectedValue()); OFCHECK(ctxGroup.mapModality("CT").isValid()); OFCHECK_EQUAL(ctxGroup.mapModality("MR").getCodeMeaning(), "Magnetic Resonance"); /* invalid/unknown defined terms */ OFCHECK(ctxGroup.mapModality("XYZ").isEmpty()); OFCHECK(ctxGroup.mapModality("ABC", codedEntry) == SR_EC_UnsupportedValue); OFCHECK(ctxGroup.selectValue("").bad()); } OFTEST(dcmsr_CID42_NumericValueQualifier) { DSRNumericMeasurementValue numValue; /* set coded entry from context group and check the value */ OFCHECK(numValue.setNumericValueQualifier(CID42_NumericValueQualifier(CID42_NumericValueQualifier::NotANumber)).good()); OFCHECK(numValue.getNumericValueQualifier() == CODE_DCM_NotANumber); /* perform some tests with invalid coded entries */ CID42_NumericValueQualifier ctxGroup; OFCHECK(ctxGroup.addCodedEntry(DSRBasicCodedEntry("0815", "99TEST", "Meaning")).good()); OFCHECK(ctxGroup.findCodedEntry(DSRBasicCodedEntry("", "99TEST", "Some invalid test code")).bad()); OFCHECK(ctxGroup.findCodedEntry(DSRBasicCodedEntry("0815", "99TEST", "-")).good()); OFCHECK(ctxGroup.findCodedEntry(DSRBasicCodedEntry("", "", "")).bad()); } OFTEST(dcmsr_CID244e_Laterality) { CID244e_Laterality ctxGroup; DSRCodedEntryValue codedEntry; OFCHECK(!ctxGroup.hasSelectedValue()); OFCHECK_EQUAL(ctxGroup.mapImageLaterality("R").getCodeValue(), "G-A100"); OFCHECK(ctxGroup.mapImageLaterality("B", codedEntry).good()); OFCHECK(ctxGroup.selectValue("L").good()); OFCHECK(DSRCodedEntryValue(ctxGroup).getCodeMeaning() == "Left"); /* invalid/unknown enumerated values */ OFCHECK(!ctxGroup.mapImageLaterality("XYZ").isValid()); OFCHECK(ctxGroup.mapImageLaterality("ABC", codedEntry) == SR_EC_InvalidValue); OFCHECK(ctxGroup.selectValue("").bad()); } OFTEST(dcmsr_CID4031e_CommonAnatomicRegions) { CID4031e_CommonAnatomicRegions ctxGroup("HEART"); DSRCodedEntryValue codedEntry = ctxGroup; OFCHECK(ctxGroup.hasSelectedValue()); OFCHECK(ctxGroup.getSelectedValue() == codedEntry); OFCHECK_EQUAL(CID4031e_CommonAnatomicRegions::mapBodyPartExamined("ABDOMEN").getCodeMeaning(), "Abdomen"); OFCHECK_EQUAL(CID4031e_CommonAnatomicRegions::mapBodyPartExamined("KNEE").getCodeMeaning(), "Knee"); OFCHECK_EQUAL(CID4031e_CommonAnatomicRegions::mapBodyPartExamined("ZYGOMA").getCodeMeaning(), "Zygoma"); /* invalid/unknown defined terms */ OFCHECK(CID4031e_CommonAnatomicRegions::mapBodyPartExamined("XYZ").isEmpty()); OFCHECK(CID4031e_CommonAnatomicRegions::mapBodyPartExamined("").isEmpty()); OFCHECK(ctxGroup.selectValue("XYZ").bad()); } OFTEST(dcmsr_CID7445_DeviceParticipatingRoles) { CID7445_DeviceParticipatingRoles ctxGroup1; OFCHECK(!ctxGroup1.hasSelectedValue()); OFCHECK(!ctxGroup1.hasCodedEntry(DSRBasicCodedEntry("0815", "99TEST", "Some test code"))); /* add an extended code to the context group */ OFCHECK(ctxGroup1.addCodedEntry(DSRBasicCodedEntry("0815", "99TEST", "Some test code")).good()); OFCHECK(ctxGroup1.hasCodedEntry(DSRBasicCodedEntry("0815", "99TEST", "Some test code"))); OFCHECK(ctxGroup1.findCodedEntry(CODE_DCM_Recording) == SR_EC_CodedEntryInStandardContextGroup); OFCHECK(ctxGroup1.findCodedEntry(DSRBasicCodedEntry("0815", "99TEST", "Some test code")) == SR_EC_CodedEntryIsExtensionOfContextGroup); /* try again with a non-extensible context group */ CID7445_DeviceParticipatingRoles ctxGroup2(DSRBasicCodedEntry("4711", "99TEST", "Some other test code")); ctxGroup2.setExtensible(OFFalse); OFCHECK(ctxGroup2.hasSelectedValue()); OFCHECK(ctxGroup2.addCodedEntry(DSRBasicCodedEntry("4711", "99TEST", "Some other test code")).bad()); /* check whether the currently selected code is valid */ OFCHECK(ctxGroup2.checkSelectedValue(OFFalse /*definedContextGroup*/).good()); OFCHECK(ctxGroup2.checkSelectedValue(OFTrue /*definedContextGroup*/).bad()); /* select another value (by two different ways) */ OFCHECK(ctxGroup2.selectValue(CODE_DCM_XRayReadingDevice).good()); OFCHECK(ctxGroup2.selectValue(CID7445_DeviceParticipatingRoles::IrradiatingDevice).good()); /* and finally, check the static get() function */ DSRCodedEntryValue codeValue = CID7445_DeviceParticipatingRoles::getCodedEntry(CID7445_DeviceParticipatingRoles::Recording, OFTrue /*enhancedEncodingMode*/); OFCHECK(codeValue == CODE_DCM_Recording); OFCHECK_EQUAL(codeValue.getContextIdentifier(), "7445"); OFCHECK_EQUAL(codeValue.getMappingResource(), "DCMR"); } OFTEST(dcmsr_CID10013e_CTAcquisitionType) { OFCHECK(CID10013e_CTAcquisitionType::mapAcquisitionType("SEQUENCED") == CODE_DCM_SequencedAcquisition); OFCHECK(CID10013e_CTAcquisitionType::mapAcquisitionType("CONSTANT_ANGLE") == CODE_DCM_ConstantAngleAcquisition); OFCHECK(CID10013e_CTAcquisitionType::mapAcquisitionType("FREE") == CODE_DCM_FreeAcquisition); /* invalid/unknown defined terms */ OFCHECK(CID10013e_CTAcquisitionType::mapAcquisitionType("XYZ").isEmpty()); } OFTEST(dcmsr_CID10033e_CTReconstructionAlgorithm) { OFCHECK(CID10033e_CTReconstructionAlgorithm::mapReconstructionAlgorithm("FILTER_BACK_PROJ") == CODE_DCM_FilteredBackProjection); OFCHECK(CID10033e_CTReconstructionAlgorithm::mapReconstructionAlgorithm("ITERATIVE") == CODE_DCM_IterativeReconstruction); /* invalid/unknown defined terms */ OFCHECK(CID10033e_CTReconstructionAlgorithm::mapReconstructionAlgorithm("XYZ").isEmpty()); } OFTEST(dcmsr_TID1001_ObservationContext) { TID1001_ObservationContext obsContext; OFList<CID7445_DeviceParticipatingRoles> procRoles; procRoles.push_back(CID7445_DeviceParticipatingRoles::IrradiatingDevice); procRoles.push_back(CID7445_DeviceParticipatingRoles::Recording); /* add person and device observers */ OFCHECK(obsContext.addPersonObserver("Doe^John", "", CID7452_OrganizationalRoles::Physician, CID7453_PerformingRoles::Referring).good()); OFCHECK(obsContext.addDeviceObserver("1.2.4.5.6.7.8.9.0").good()); OFCHECK(obsContext.addDeviceObserver("007", "Some Name", "Some Manufacturer", "Some Model Name", "", "", procRoles, OFFalse /*check*/).good()); OFCHECK(obsContext.addPersonObserver("Doe^Jane", "Some Organization").good()); /* check some additions that should fail */ OFCHECK(obsContext.addPersonObserver("").bad()); OFCHECK(obsContext.addDeviceObserver("").bad()); OFCHECK(obsContext.addDeviceObserver("01").bad()); /* check whether all nodes are present */ OFCHECK(obsContext.isValid()); OFCHECK_EQUAL(obsContext.countNodes(), 16); /* check whether annotations are as expected */ OFCHECK(obsContext.gotoAnnotatedNode("TID 1004 - Row 1") > 0); OFCHECK(obsContext.gotoNextAnnotatedNode("TID 1004 - Row 1") > 0); OFCHECK_EQUAL(obsContext.getCurrentContentItem().getStringValue(), "007"); /* now, clone the document tree of the template and check annotations again */ DSRDocumentSubTree *tree = obsContext.cloneTree(); if (tree != NULL) { OFCHECK(tree->gotoAnnotatedNode("TID 1004 - Row 1") > 0); OFCHECK(tree->gotoNextAnnotatedNode("TID 1004 - Row 1") > 0); } else OFCHECK_FAIL("could not create clone of subtree"); delete tree; } OFTEST(dcmsr_TID1204_LanguageOfContentItemAndDescendants) { TID1204_LanguageOfContentItemAndDescendants lang; /* add language */ OFCHECK(lang.setLanguage(CID5000_Languages::German_DE).good()); OFCHECK(lang.isValid()); OFCHECK_EQUAL(lang.countNodes(), 1); /* add language and separate country */ OFCHECK(lang.setLanguage(CID5000_Languages::German, CID5001_Countries::Germany).good()); OFCHECK(lang.isValid()); OFCHECK_EQUAL(lang.countNodes(), 2); } OFTEST(dcmsr_TID1600_ImageLibrary) { TID1600_ImageLibrary library; DcmItem *item1, *item2; /* create four image datasets */ DcmDataset dataset1; OFCHECK(dataset1.putAndInsertString(DCM_SOPClassUID, UID_CTImageStorage).good()); OFCHECK(dataset1.putAndInsertString(DCM_SOPInstanceUID, "1.2.3.4.5.6.7.8.9.0").good()); OFCHECK(dataset1.putAndInsertString(DCM_Modality, "CT").good()); OFCHECK(dataset1.putAndInsertString(DCM_StudyDate, "20150818").good()); OFCHECK(dataset1.putAndInsertUint16(DCM_Columns, 512).good()); OFCHECK(dataset1.putAndInsertUint16(DCM_Rows, 512).good()); OFCHECK(dataset1.putAndInsertString(DCM_PixelSpacing, "0.5\\1.5").good()); OFCHECK(dataset1.putAndInsertString(DCM_BodyPartExamined, "HEAD").good()); OFCHECK(dataset1.putAndInsertString(DCM_ImageOrientationPatient, "1.000000\\0.000000\\0.000000\\0.000000\\1.000000\\0.000000").good()); OFCHECK(dataset1.putAndInsertString(DCM_ImagePositionPatient, "-120.000000\\-120.000000\\-545.000000").good()); OFCHECK(dataset1.findOrCreateSequenceItem(DCM_SharedFunctionalGroupsSequence, item1, -2).good()); if (item1 != NULL) { OFCHECK(item1->findOrCreateSequenceItem(DCM_CTAcquisitionTypeSequence, item2, -2).good()); if (item2 != NULL) OFCHECK(item2->putAndInsertString(DCM_AcquisitionType, "SPIRAL").good()); OFCHECK(item1->findOrCreateSequenceItem(DCM_CTReconstructionSequence, item2, -2).good()); if (item2 != NULL) OFCHECK(item2->putAndInsertString(DCM_ReconstructionAlgorithm, "ITERATIVE").good()); } DcmDataset dataset2; OFCHECK(dataset2.putAndInsertString(DCM_SOPClassUID, UID_PositronEmissionTomographyImageStorage).good()); OFCHECK(dataset2.putAndInsertString(DCM_SOPInstanceUID, "1.2.3.4.5.6.7.8.9.1").good()); OFCHECK(dataset2.putAndInsertString(DCM_Modality, "PT").good()); OFCHECK(dataset2.putAndInsertString(DCM_ImageLaterality, "B").good()); OFCHECK(DSRCodedEntryValue("T-32000", "SRT", "Heart").writeSequence(dataset2, DCM_AnatomicRegionSequence).good()); OFCHECK(dataset2.findOrCreateSequenceItem(DCM_RadiopharmaceuticalInformationSequence, item1, -2).good()); if (item1 != NULL) { OFCHECK(DSRCodedEntryValue("C-128A2", "SRT", "^68^Germanium").writeSequence(*item1, DCM_RadionuclideCodeSequence).good()); OFCHECK(item1->putAndInsertString(DCM_RadiopharmaceuticalVolume, "50.5").good()); } DcmDataset dataset3; OFCHECK(dataset3.putAndInsertString(DCM_SOPClassUID, UID_SecondaryCaptureImageStorage).good()); OFCHECK(dataset3.putAndInsertString(DCM_SOPInstanceUID, "1.2.3.4.5.6.7.8.9.2").good()); OFCHECK(dataset3.putAndInsertString(DCM_Modality, "OT").good()); OFCHECK(dataset3.putAndInsertString(DCM_BodyPartExamined, "EAR").good()); OFCHECK(dataset3.putAndInsertString(DCM_FrameOfReferenceUID, "1.2.3.4.5.6.7.8.9.3").good()); DcmDataset dataset4; OFCHECK(dataset4.putAndInsertString(DCM_SOPClassUID, UID_DigitalXRayImageStorageForPresentation).good()); OFCHECK(dataset4.putAndInsertString(DCM_SOPInstanceUID, "1.2.3.4.5.6.7.8.9.4").good()); OFCHECK(dataset4.putAndInsertString(DCM_Modality, "DX").good()); OFCHECK(dataset4.putAndInsertString(DCM_PatientOrientation, "A\\F").good()); OFCHECK(dataset4.putAndInsertString(DCM_PositionerPrimaryAngle, "45").good()); OFCHECK(dataset4.putAndInsertString(DCM_PositionerSecondaryAngle, "-45").good()); OFCHECK(DSRCodedEntryValue("R-10202", "SRT", "frontal").writeSequence(dataset4, DCM_ViewCodeSequence).good()); OFCHECK(dataset4.findAndGetSequenceItem(DCM_ViewCodeSequence, item1).good()); if (item1 != NULL) { OFCHECK(item1->findOrCreateSequenceItem(DCM_ViewModifierCodeSequence, item2, -2).good()); if (item2 != NULL) OFCHECK(DSRCodedEntryValue("4711", "99TEST", "some strange modifier").writeSequenceItem(*item2, DCM_ViewModifierCodeSequence).good()); OFCHECK(item1->findOrCreateSequenceItem(DCM_ViewModifierCodeSequence, item2, -2).good()); if (item2 != NULL) OFCHECK(DSRCodedEntryValue("4711b", "99TEST", "some even more strange modifier").writeSequenceItem(*item2, DCM_ViewModifierCodeSequence).good()); } /* add two image groups */ OFCHECK(library.addImageGroup().good()); OFCHECK(library.addImageEntry(dataset1).good()); OFCHECK(library.addImageEntryDescriptors(dataset1).good()); OFCHECK(library.addImageGroup().good()); OFCHECK(library.addImageEntry(dataset2, TID1600_ImageLibrary::withAllDescriptors).good()); OFCHECK(library.addImageEntry(dataset1, TID1600_ImageLibrary::withAllDescriptors).good()); OFCHECK(library.addImageEntry(dataset3, TID1600_ImageLibrary::withoutDescriptors).good()); OFCHECK(library.addImageEntry(dataset4, TID1600_ImageLibrary::withAllDescriptors).good()); OFCHECK(library.addImageEntryDescriptors(dataset3).good()); /* try to add another invocation of TID 1602 */ OFCHECK(library.addImageEntryDescriptors(dataset4).bad()); /* check number of expected content items */ OFCHECK_EQUAL(library.countNodes(), 58); #ifdef DEBUG /* output content of the tree (in debug mode only) */ library.print(COUT, DSRTypes::PF_printTemplateIdentification | DSRTypes::PF_printAllCodes | DSRTypes::PF_printSOPInstanceUID | DSRTypes::PF_printNodeID | DSRTypes::PF_indicateEnhancedEncodingMode | DSRTypes::PF_printAnnotation); #endif } OFTEST(dcmsr_CMR_SRNumericMeasurementValue) { CMR_SRNumericMeasurementValue numValue; /* set coded entry from context group and check the value */ OFCHECK(numValue.setNumericValueQualifier(CID42_NumericValueQualifier(CID42_NumericValueQualifier::NotANumber)).good()); OFCHECK(numValue.getNumericValueQualifier() == CODE_DCM_NotANumber); OFCHECK(numValue.isValid()); /* set coded entry from context group (using its type) and check the value */ OFCHECK(numValue.setNumericValueQualifier(CID42_NumericValueQualifier::ValueUnknown).good()); OFCHECK(numValue.getNumericValueQualifier() == CODE_DCM_ValueUnknown); OFCHECK(numValue.isValid()); /* set numeric measurement value to tree node */ DSRNumTreeNode numNode(DSRTypes::RT_hasProperties); OFCHECK(numNode.setValue(numValue, OFTrue /*check*/).good()); /* set coded entry that is not part of the context group */ OFCHECK(numValue.setNumericValueQualifier(DSRBasicCodedEntry("0815", "99TEST", "Some test code"), OFTrue /*check*/) == SR_EC_CodedEntryNotInContextGroup); OFCHECK(numValue.isValid()); OFCHECK(numValue.setNumericValueQualifier(DSRBasicCodedEntry("0815", "99TEST", "Some test code"), OFFalse /*check*/).good()); OFCHECK(!numValue.isValid()); } OFTEST(dcmsr_cleanupContentMappingResource) { /* cleanup the internal code lists explicitly (should be the last test case) */ CMR_ContentMappingResource::cleanupAllContextGroups(); }
50.94586
161
0.746327
[ "model" ]
e726a522b4e90629f3a438554266bd09c8e3adb9
6,078
cc
C++
HeavyFlavorAnalysis/RecoDecay/src/BPHDecayVertex.cc
gputtley/cmssw
c1ef8454804e4ebea8b65f59c4a952a6c94fde3b
[ "Apache-2.0" ]
2
2020-01-27T15:21:37.000Z
2020-05-11T11:13:18.000Z
HeavyFlavorAnalysis/RecoDecay/src/BPHDecayVertex.cc
gputtley/cmssw
c1ef8454804e4ebea8b65f59c4a952a6c94fde3b
[ "Apache-2.0" ]
8
2020-03-20T23:18:36.000Z
2020-05-27T11:00:06.000Z
HeavyFlavorAnalysis/RecoDecay/src/BPHDecayVertex.cc
gputtley/cmssw
c1ef8454804e4ebea8b65f59c4a952a6c94fde3b
[ "Apache-2.0" ]
3
2017-06-07T15:22:28.000Z
2019-02-28T20:48:30.000Z
/* * See header file for a description of this class. * * \author Paolo Ronchese INFN Padova * */ //----------------------- // This Class' Header -- //----------------------- #include "HeavyFlavorAnalysis/RecoDecay/interface/BPHDecayVertex.h" //------------------------------- // Collaborating Class Headers -- //------------------------------- #include "HeavyFlavorAnalysis/RecoDecay/interface/BPHRecoCandidate.h" #include "HeavyFlavorAnalysis/RecoDecay/interface/BPHRecoBuilder.h" #include "HeavyFlavorAnalysis/RecoDecay/interface/BPHTrackReference.h" #include "FWCore/Framework/interface/EventSetup.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h" #include "TrackingTools/TransientTrack/interface/TransientTrack.h" #include "TrackingTools/Records/interface/TransientTrackRecord.h" #include "RecoVertex/VertexPrimitives/interface/TransientVertex.h" #include "RecoVertex/KalmanVertexFit/interface/KalmanVertexFitter.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" //--------------- // C++ Headers -- //--------------- #include <iostream> using namespace std; //------------------- // Initializations -- //------------------- //---------------- // Constructors -- //---------------- BPHDecayVertex::BPHDecayVertex(const edm::EventSetup* es) : evSetup(es), oldTracks(true), oldVertex(true), validTks(false) {} BPHDecayVertex::BPHDecayVertex(const BPHDecayVertex* ptr, const edm::EventSetup* es) : evSetup(es), oldTracks(true), oldVertex(true), validTks(false) { map<const reco::Candidate*, const reco::Candidate*> iMap; const vector<const reco::Candidate*>& daug = daughters(); const vector<Component>& list = ptr->componentList(); int i; int n = daug.size(); for (i = 0; i < n; ++i) { const reco::Candidate* cand = daug[i]; iMap[originalReco(cand)] = cand; } for (i = 0; i < n; ++i) { const Component& c = list[i]; searchMap[iMap[c.cand]] = c.searchList; } const vector<BPHRecoConstCandPtr>& dComp = daughComp(); int j; int m = dComp.size(); for (j = 0; j < m; ++j) { const map<const reco::Candidate*, string>& dMap = dComp[j]->searchMap; searchMap.insert(dMap.begin(), dMap.end()); } } //-------------- // Destructor -- //-------------- BPHDecayVertex::~BPHDecayVertex() {} //-------------- // Operations -- //-------------- bool BPHDecayVertex::validTracks() const { if (oldVertex) fitVertex(); return validTks; } bool BPHDecayVertex::validVertex() const { if (oldVertex) fitVertex(); return validTks && fittedVertex.isValid(); } const reco::Vertex& BPHDecayVertex::vertex() const { if (oldVertex) fitVertex(); return fittedVertex; } const vector<const reco::Track*>& BPHDecayVertex::tracks() const { if (oldTracks) tTracks(); return rTracks; } const reco::Track* BPHDecayVertex::getTrack(const reco::Candidate* cand) const { if (oldTracks) tTracks(); map<const reco::Candidate*, const reco::Track*>::const_iterator iter = tkMap.find(cand); map<const reco::Candidate*, const reco::Track*>::const_iterator iend = tkMap.end(); return (iter != iend ? iter->second : nullptr); } const vector<reco::TransientTrack>& BPHDecayVertex::transientTracks() const { if (oldTracks) tTracks(); return trTracks; } reco::TransientTrack* BPHDecayVertex::getTransientTrack(const reco::Candidate* cand) const { if (oldTracks) tTracks(); map<const reco::Candidate*, reco::TransientTrack*>::const_iterator iter = ttMap.find(cand); map<const reco::Candidate*, reco::TransientTrack*>::const_iterator iend = ttMap.end(); return (iter != iend ? iter->second : nullptr); } const string& BPHDecayVertex::getTrackSearchList(const reco::Candidate* cand) const { static string dum = ""; map<const reco::Candidate*, string>::const_iterator iter = searchMap.find(cand); if (iter != searchMap.end()) return iter->second; return dum; } void BPHDecayVertex::addV(const string& name, const reco::Candidate* daug, const string& searchList, double mass) { addP(name, daug, mass); searchMap[daughters().back()] = searchList; return; } void BPHDecayVertex::addV(const string& name, const BPHRecoConstCandPtr& comp) { addP(name, comp); const map<const reco::Candidate*, string>& dMap = comp->searchMap; searchMap.insert(dMap.begin(), dMap.end()); return; } void BPHDecayVertex::setNotUpdated() const { BPHDecayMomentum::setNotUpdated(); oldTracks = oldVertex = true; validTks = false; return; } void BPHDecayVertex::tTracks() const { oldTracks = false; rTracks.clear(); trTracks.clear(); tkMap.clear(); ttMap.clear(); edm::ESHandle<TransientTrackBuilder> ttB; evSetup->get<TransientTrackRecord>().get("TransientTrackBuilder", ttB); const vector<const reco::Candidate*>& dL = daughFull(); int n = dL.size(); trTracks.reserve(n); validTks = true; while (n--) { const reco::Candidate* rp = dL[n]; tkMap[rp] = nullptr; ttMap[rp] = nullptr; if (!rp->charge()) continue; const reco::Track* tp; const char* searchList = "cfhp"; map<const reco::Candidate*, string>::const_iterator iter = searchMap.find(rp); if (iter != searchMap.end()) searchList = iter->second.c_str(); tp = BPHTrackReference::getTrack(*rp, searchList); if (tp == nullptr) { edm::LogPrint("DataNotFound") << "BPHDecayVertex::tTracks: " << "no track for reco::(PF)Candidate"; validTks = false; continue; } rTracks.push_back(tp); trTracks.push_back(ttB->build(tp)); reco::TransientTrack* ttp = &trTracks.back(); tkMap[rp] = tp; ttMap[rp] = ttp; } return; } void BPHDecayVertex::fitVertex() const { oldVertex = false; if (oldTracks) tTracks(); if (trTracks.size() < 2) return; KalmanVertexFitter kvf(true); TransientVertex tv = kvf.vertex(trTracks); fittedVertex = tv; return; }
29.940887
115
0.660744
[ "vector" ]
e72b53d078bcc4a60f75c8ad18f7648c53e310e8
4,824
hpp
C++
src/ast/Node.hpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
1
2019-06-17T07:16:01.000Z
2019-06-17T07:16:01.000Z
src/ast/Node.hpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
null
null
null
src/ast/Node.hpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
null
null
null
/* * soyac - Soya Programming Language compiler * Copyright (c) 2009 Denis Washington <dwashington@gmx.net> * * This file is distributed under the terms of the MIT license. * See LICENSE.txt for details. */ #ifndef _AST_NODE_HPP #define _AST_NODE_HPP #include <boost/signals2/signal.hpp> #include <list> #include <sigc++/sigc++.h> #include "Location.hpp" namespace soyac { namespace ast { using boost::signals2::signal; class Visitor; /** * The base class of all classes whose instances represent abstract syntax * tree nodes. An abstract syntax node represents a specific element or * code section of a Soya source or interface file. * * The Node class provides the following features: * * - <b>Reference counting:</b> Each node begins with a reference count * of 0. Using the ref() and unref() methods, the count can be incremented * and decremented; a decrease to or beneath 0 destroys the node. In most * cases, reference count management is not done manually, but is automated * by wrapping Node references in Link objects. <em>Note that while it * is possible, you should NOT directly delete Node instances that are part * of an abstract syntax tree, as this might render the tree inconsistent!</em> * - <b>The replaceWith() method:</b> Using replaceWith(), all Link references * to a node can be replaced by references to another node, thus fully * substiting one node with another in the abstract syntax tree. This is * useful in several circumstances, for instance for replacing expressions * with semantically equivalent, but simpler versions for optimization * purposes. * - <b>Visitor hooks:</b> The Node class provides a visit() method, which * visits the node with a specified Visitor. visit() is overridden by every * concrete child class of Node to call the correct visit method of the * passed Visitor instance, which means that the caller does not need to know * the run-time type of a node to call the correct visitor method. */ class Node { public: /** * Creates an Node. */ Node(); /** * The destructor. */ virtual ~Node(); /** * Increases the reference count of the Node instance by one. */ void ref(); /** * Decreases the reference count of the Node instance by one, * which destroys the node if the count reaches zero. * * <strong>Do only manually call unref() after a manual call to ref()! * </strong> Otherwise a Node object still referred to by an abstract * syntax tree might be destroyed, which will render the tree * inconsistent! * */ void unref(); /** * Returns the location of the code element represented by the * Node instance. * * @return The node's location data. */ const Location& location() const; /** * Sets the location of the code element represented by the Node * instance. * * @param l The Node's location data */ void setLocation(const Location& l); /** * Replaces all abstract syntax tree references to the Node instance with * references to the passed other node. Replacing a node with null is not * allowed. * * @param node The node with which to replace. Null is ignored. */ template <class N> void replaceWith(N* node) { if (node != NULL) _replaceWith(node); } /** * Visits the node with the specified Visitor. * * Every concrete child class of Node should override this to call the * correct visitor method of the passed Visitor instance. * * @param v The Visitor with which the node should be visited. * @return The visitor method's return value. */ virtual void* visit(Visitor* v) { return NULL; } /** * Returns the "replaceRequested" signal, which is emitted when the * Node instance's replaceWith() method is called. * * Link instances pointing to the node subscribe to this signal to * do the be notified when a replacement operation is required. The * signal can also be subscribed to by other nodes or the signal-emitting * Node instance itself, though. * * Note that after the each time the "replaceRequested" signal has been * emitted, all signal handlers are disconnected. * * @par Callback Signature: * <tt>void onReplaceRequested(Node* oldNode, Node* newNode);</tt> * * @return The "replaceRequested" signal. */ signal<void(Node*, Node*)>& replaceRequested(); private: int mRefCount; Location mLocation; signal<void (Node*, Node*)> mReplaceRequested; /** * The concrete implementation of replaceWith(). */ void _replaceWith(Node* node); }; }} #endif
30.531646
81
0.667496
[ "render", "object" ]
e72f82e50e099182dbf26c938bd8c5dc9e4b474d
478
hpp
C++
src/Omega_h_egads.hpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
44
2019-01-23T03:37:18.000Z
2021-08-24T02:20:29.000Z
src/Omega_h_egads.hpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
67
2019-01-29T15:35:42.000Z
2021-08-17T20:42:40.000Z
src/Omega_h_egads.hpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
29
2019-01-14T21:33:32.000Z
2021-08-10T11:35:24.000Z
#ifndef OMEGA_H_EGADS_HPP #define OMEGA_H_EGADS_HPP #include <Omega_h_array.hpp> #include <string> namespace Omega_h { class Mesh; struct Egads; Egads* egads_load(std::string const& filename); void egads_classify(Egads* eg, int nadj_faces, int const adj_face_ids[], int* class_dim, int* class_id); void egads_free(Egads* eg); void egads_reclassify(Mesh* mesh, Egads* eg); Reals egads_get_snap_warp(Mesh* mesh, Egads* eg, bool verbose); } // namespace Omega_h #endif
20.782609
72
0.759414
[ "mesh" ]
e73111315019a1525f366cdb425d6cf91280454e
10,777
cpp
C++
demos/face_detection_mtcnn_demo/cpp_gapi/src/custom_kernels.cpp
kblaszczak-intel/open_model_zoo
e313674d35050d2a4721bbccd9bd4c404f1ba7f8
[ "Apache-2.0" ]
2,201
2018-10-15T14:37:19.000Z
2020-07-16T02:05:51.000Z
demos/face_detection_mtcnn_demo/cpp_gapi/src/custom_kernels.cpp
kblaszczak-intel/open_model_zoo
e313674d35050d2a4721bbccd9bd4c404f1ba7f8
[ "Apache-2.0" ]
759
2018-10-18T07:43:55.000Z
2020-07-16T01:23:12.000Z
demos/face_detection_mtcnn_demo/cpp_gapi/src/custom_kernels.cpp
kblaszczak-intel/open_model_zoo
e313674d35050d2a4721bbccd9bd4c404f1ba7f8
[ "Apache-2.0" ]
808
2018-10-16T14:03:49.000Z
2020-07-15T11:41:45.000Z
// Copyright (C) 2021-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "custom_kernels.hpp" #include <string> #include <utility> #include <opencv2/gapi/cpu/gcpukernel.hpp> #include <opencv2/imgproc.hpp> namespace { const float P_NET_WINDOW_SIZE = 12.0f; std::vector<custom::Face> buildFaces(const cv::Mat& scores, const cv::Mat& regressions, const float scaleFactor, const float threshold) { const auto w = scores.size[3]; const auto h = scores.size[2]; const auto size = w * h; const float* scores_data = scores.ptr<float>(); scores_data += size; const float* reg_data = regressions.ptr<float>(); const auto out_side = std::max(h, w); const auto in_side = 2 * out_side + 11; float stride = 0.0f; if (out_side != 1) { stride = static_cast<float>(in_side - P_NET_WINDOW_SIZE) / static_cast<float>(out_side - 1); } std::vector<custom::Face> boxes; for (int i = 0; i < size; i++) { if (scores_data[i] >= (threshold)) { const float y = static_cast<float>(i / w); const float x = static_cast<float>(i - w * y); custom::Face faceInfo; custom::BBox& faceBox = faceInfo.bbox; faceBox.x1 = std::max(0, static_cast<int>((x * stride) / scaleFactor)); faceBox.y1 = std::max(0, static_cast<int>((y * stride) / scaleFactor)); faceBox.x2 = static_cast<int>((x * stride + P_NET_WINDOW_SIZE - 1.0f) / scaleFactor); faceBox.y2 = static_cast<int>((y * stride + P_NET_WINDOW_SIZE - 1.0f) / scaleFactor); faceInfo.regression[0] = reg_data[i]; faceInfo.regression[1] = reg_data[i + size]; faceInfo.regression[2] = reg_data[i + 2 * size]; faceInfo.regression[3] = reg_data[i + 3 * size]; faceInfo.score = scores_data[i]; boxes.push_back(faceInfo); } } return boxes; } } // anonymous namespace // clang-format off // Custom kernels implementation GAPI_OCV_KERNEL(OCVBuildFaces, custom::BuildFaces) { static void run(const cv::Mat & in_scores, const cv::Mat & in_regresssions, const float scaleFactor, const float threshold, std::vector<custom::Face> &out_faces) { out_faces = buildFaces(in_scores, in_regresssions, scaleFactor, threshold); } }; // GAPI_OCV_KERNEL(BuildFaces) GAPI_OCV_KERNEL(OCVRunNMS, custom::RunNMS) { static void run(const std::vector<custom::Face> &in_faces, const float threshold, const bool useMin, std::vector<custom::Face> &out_faces) { std::vector<custom::Face> in_faces_copy = in_faces; out_faces = custom::Face::runNMS(in_faces_copy, threshold, useMin); } }; // GAPI_OCV_KERNEL(RunNMS) GAPI_OCV_KERNEL(OCVAccumulatePyramidOutputs, custom::AccumulatePyramidOutputs) { static void run(const std::vector<custom::Face> &total_faces, const std::vector<custom::Face> &in_faces, std::vector<custom::Face> &out_faces) { out_faces = total_faces; out_faces.insert(out_faces.end(), in_faces.begin(), in_faces.end()); } }; // GAPI_OCV_KERNEL(AccumulatePyramidOutputs) GAPI_OCV_KERNEL(OCVApplyRegression, custom::ApplyRegression) { static void run(const std::vector<custom::Face> &in_faces, const bool addOne, std::vector<custom::Face> &out_faces) { std::vector<custom::Face> in_faces_copy = in_faces; custom::Face::applyRegression(in_faces_copy, addOne); out_faces.clear(); out_faces.insert(out_faces.end(), in_faces_copy.begin(), in_faces_copy.end()); } }; // GAPI_OCV_KERNEL(ApplyRegression) GAPI_OCV_KERNEL(OCVBBoxesToSquares, custom::BBoxesToSquares) { static void run(const std::vector<custom::Face> &in_faces, std::vector<custom::Face> &out_faces) { std::vector<custom::Face> in_faces_copy = in_faces; custom::Face::bboxes2Squares(in_faces_copy); out_faces.clear(); out_faces.insert(out_faces.end(), in_faces_copy.begin(), in_faces_copy.end()); } }; // GAPI_OCV_KERNEL(BBoxesToSquares) GAPI_OCV_KERNEL(OCVR_O_NetPreProcGetROIs, custom::R_O_NetPreProcGetROIs) { static void run(const std::vector<custom::Face> &in_faces, const cv::Size & in_image_size, std::vector<cv::Rect> &outs) { outs.clear(); for (const auto& face : in_faces) { cv::Rect tmp_rect = face.bbox.getRect(); // Compare to transposed sizes width<->height tmp_rect &= cv::Rect(tmp_rect.x, tmp_rect.y, in_image_size.height - tmp_rect.x, in_image_size.width - tmp_rect.y) & cv::Rect(0, 0, in_image_size.height, in_image_size.width); outs.push_back(tmp_rect); } } }; // GAPI_OCV_KERNEL(R_O_NetPreProcGetROIs) GAPI_OCV_KERNEL(OCVRNetPostProc, custom::RNetPostProc) { static void run(const std::vector<custom::Face> &in_faces, const std::vector<cv::Mat> &in_scores, const std::vector<cv::Mat> &in_regresssions, const float threshold, std::vector<custom::Face> &out_faces) { out_faces.clear(); for (unsigned int k = 0; k < in_faces.size(); ++k) { const float* scores_data = in_scores[k].ptr<float>(); const float* reg_data = in_regresssions[k].ptr<float>(); if (scores_data[1] >= threshold) { custom::Face info = in_faces[k]; info.score = scores_data[1]; std::copy_n(reg_data, NUM_REGRESSIONS, info.regression.begin()); out_faces.push_back(info); } } } }; // GAPI_OCV_KERNEL(RNetPostProc) GAPI_OCV_KERNEL(OCVONetPostProc, custom::ONetPostProc) { static void run(const std::vector<custom::Face> &in_faces, const std::vector<cv::Mat> &in_scores, const std::vector<cv::Mat> &in_regresssions, const std::vector<cv::Mat> &in_landmarks, const float threshold, std::vector<custom::Face> &out_faces) { out_faces.clear(); for (unsigned int k = 0; k < in_faces.size(); ++k) { const float* scores_data = in_scores[k].ptr<float>(); const float* reg_data = in_regresssions[k].ptr<float>(); const float* landmark_data = in_landmarks[k].ptr<float>(); if (scores_data[1] >= threshold) { custom::Face info = in_faces[k]; info.score = scores_data[1]; for (size_t i = 0; i < 4; ++i) { info.regression[i] = reg_data[i]; } float w = info.bbox.x2 - info.bbox.x1 + 1.0f; float h = info.bbox.y2 - info.bbox.y1 + 1.0f; for (size_t p = 0; p < NUM_PTS; ++p) { info.ptsCoords[2 * p] = info.bbox.x1 + static_cast<float>(landmark_data[NUM_PTS + p]) * w - 1; info.ptsCoords[2 * p + 1] = info.bbox.y1 + static_cast<float>(landmark_data[p]) * h - 1; } out_faces.push_back(info); } } } }; // GAPI_OCV_KERNEL(ONetPostProc) GAPI_OCV_KERNEL(OCVSwapFaces, custom::SwapFaces) { static void run(const std::vector<custom::Face> &in_faces, std::vector<custom::Face> &out_faces) { std::vector<custom::Face> in_faces_copy = in_faces; out_faces.clear(); if (!in_faces_copy.empty()) { for (size_t i = 0; i < in_faces_copy.size(); ++i) { std::swap(in_faces_copy[i].bbox.x1, in_faces_copy[i].bbox.y1); std::swap(in_faces_copy[i].bbox.x2, in_faces_copy[i].bbox.y2); for (size_t p = 0; p < NUM_PTS; ++p) { std::swap(in_faces_copy[i].ptsCoords[2 * p], in_faces_copy[i].ptsCoords[2 * p + 1]); } } out_faces = in_faces_copy; } } }; // GAPI_OCV_KERNEL(SwapFaces) using rectPoints = std::pair<cv::Rect, std::vector<cv::Point>>; GAPI_OCV_KERNEL(OCVBoxesAndMarks, custom::BoxesAndMarks) { static void run(const cv::Mat & in, const std::vector<custom::Face> &in_faces, std::vector<cv::gapi::wip::draw::Prim>&out_prims) { out_prims.clear(); const auto rct = [](const cv::Rect& rc) { return cv::gapi::wip::draw::Rect(rc, cv::Scalar(255, 0, 0), 1); }; const auto txt = [](const std::string& ms, const cv::Rect& rc) { return cv::gapi::wip::draw::Text(ms, rc.tl(), cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(0, 255, 0)); }; const auto crl = [](const cv::Point& point) { return cv::gapi::wip::draw::Circle(point, 2, cv::Scalar(0, 255, 0)); }; std::vector<rectPoints> data; std::vector<float> confidence; // show the image with faces in it for (const auto& out_face : in_faces) { std::vector<cv::Point> pts; for (size_t p = 0; p < NUM_PTS; ++p) { pts.push_back( cv::Point(static_cast<int>(out_face.ptsCoords[2 * p]), static_cast<int>(out_face.ptsCoords[2 * p + 1]))); } const auto rect = out_face.bbox.getRect(); const auto d = std::make_pair(rect, pts); data.push_back(d); confidence.push_back(out_face.score); } for (size_t i = 0; i < data.size(); ++i) { out_prims.emplace_back(rct(data.at(i).first)); out_prims.emplace_back(txt(cv::format("confidence: %0.2f", confidence.at(i)), data.at(i).first)); for (const auto& point : data.at(i).second) { out_prims.emplace_back(crl(point)); } } } }; // GAPI_OCV_KERNEL(BoxesAndMarks) // clang-format on cv::gapi::GKernelPackage custom::kernels() { return cv::gapi::kernels<OCVBuildFaces, OCVRunNMS, OCVAccumulatePyramidOutputs, OCVApplyRegression, OCVBBoxesToSquares, OCVR_O_NetPreProcGetROIs, OCVRNetPostProc, OCVONetPostProc, OCVSwapFaces, OCVBoxesAndMarks>(); }
42.097656
112
0.559618
[ "vector" ]
e733314cfc3ba0d2c9e8828605afeb21e79672be
75,756
cpp
C++
chromium/third_party/WebKit/Source/core/editing/EditingStyle.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/core/editing/EditingStyle.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/core/editing/EditingStyle.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2007, 2008, 2009 Apple Computer, Inc. * Copyright (C) 2010, 2011 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: * 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 "core/editing/EditingStyle.h" #include "bindings/core/v8/ExceptionStatePlaceholder.h" #include "core/HTMLNames.h" #include "core/css/CSSColorValue.h" #include "core/css/CSSComputedStyleDeclaration.h" #include "core/css/CSSPropertyMetadata.h" #include "core/css/CSSRuleList.h" #include "core/css/CSSStyleRule.h" #include "core/css/CSSValueList.h" #include "core/css/CSSValuePool.h" #include "core/css/FontSize.h" #include "core/css/StylePropertySet.h" #include "core/css/StyleRule.h" #include "core/css/parser/CSSParser.h" #include "core/css/resolver/StyleResolver.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/Node.h" #include "core/dom/NodeTraversal.h" #include "core/dom/QualifiedName.h" #include "core/editing/EditingUtilities.h" #include "core/editing/Editor.h" #include "core/editing/FrameSelection.h" #include "core/editing/Position.h" #include "core/editing/commands/ApplyStyleCommand.h" #include "core/editing/serializers/HTMLInterchange.h" #include "core/frame/LocalFrame.h" #include "core/html/HTMLFontElement.h" #include "core/html/HTMLSpanElement.h" #include "core/layout/LayoutBox.h" #include "core/layout/LayoutObject.h" #include "core/style/ComputedStyle.h" namespace blink { static const CSSPropertyID& textDecorationPropertyForEditing() { static const CSSPropertyID property = RuntimeEnabledFeatures::css3TextDecorationsEnabled() ? CSSPropertyTextDecorationLine : CSSPropertyTextDecoration; return property; } // Editing style properties must be preserved during editing operation. // e.g. when a user inserts a new paragraph, all properties listed here must be copied to the new paragraph. // NOTE: Use either allEditingProperties() or inheritableEditingProperties() to // respect runtime enabling of properties. static const CSSPropertyID staticEditingProperties[] = { CSSPropertyBackgroundColor, CSSPropertyColor, CSSPropertyFontFamily, CSSPropertyFontSize, CSSPropertyFontStyle, CSSPropertyFontVariant, CSSPropertyFontWeight, CSSPropertyLetterSpacing, CSSPropertyLineHeight, CSSPropertyOrphans, CSSPropertyTextAlign, // FIXME: CSSPropertyTextDecoration needs to be removed when CSS3 Text // Decoration feature is no longer experimental. CSSPropertyTextDecoration, CSSPropertyTextDecorationLine, CSSPropertyTextIndent, CSSPropertyTextTransform, CSSPropertyWhiteSpace, CSSPropertyWidows, CSSPropertyWordSpacing, CSSPropertyWebkitTextDecorationsInEffect, CSSPropertyWebkitTextFillColor, CSSPropertyWebkitTextStrokeColor, CSSPropertyWebkitTextStrokeWidth, }; enum EditingPropertiesType { OnlyInheritableEditingProperties, AllEditingProperties }; static const Vector<CSSPropertyID>& allEditingProperties() { DEFINE_STATIC_LOCAL(Vector<CSSPropertyID>, properties, ()); if (properties.isEmpty()) { CSSPropertyMetadata::filterEnabledCSSPropertiesIntoVector(staticEditingProperties, WTF_ARRAY_LENGTH(staticEditingProperties), properties); if (RuntimeEnabledFeatures::css3TextDecorationsEnabled()) properties.remove(properties.find(CSSPropertyTextDecoration)); } return properties; } static const Vector<CSSPropertyID>& inheritableEditingProperties() { DEFINE_STATIC_LOCAL(Vector<CSSPropertyID>, properties, ()); if (properties.isEmpty()) { CSSPropertyMetadata::filterEnabledCSSPropertiesIntoVector(staticEditingProperties, WTF_ARRAY_LENGTH(staticEditingProperties), properties); for (size_t index = 0; index < properties.size();) { if (!CSSPropertyMetadata::isInheritedProperty(properties[index])) { properties.remove(index); continue; } ++index; } } return properties; } template <class StyleDeclarationType> static PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyEditingProperties(StyleDeclarationType* style, EditingPropertiesType type = OnlyInheritableEditingProperties) { if (type == AllEditingProperties) return style->copyPropertiesInSet(allEditingProperties()); return style->copyPropertiesInSet(inheritableEditingProperties()); } static inline bool isEditingProperty(int id) { return allEditingProperties().contains(static_cast<CSSPropertyID>(id)); } static PassRefPtrWillBeRawPtr<MutableStylePropertySet> editingStyleFromComputedStyle(PassRefPtrWillBeRawPtr<CSSComputedStyleDeclaration> style, EditingPropertiesType type = OnlyInheritableEditingProperties) { if (!style) return MutableStylePropertySet::create(HTMLQuirksMode); return copyEditingProperties(style.get(), type); } static PassRefPtrWillBeRawPtr<CSSComputedStyleDeclaration> ensureComputedStyle(const Position& position) { Element* elem = associatedElementOf(position); if (!elem) return nullptr; return CSSComputedStyleDeclaration::create(elem); } static PassRefPtrWillBeRawPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, CSSStyleDeclaration* baseStyle); enum LegacyFontSizeMode { AlwaysUseLegacyFontSize, UseLegacyFontSizeOnlyIfPixelValuesMatch }; static int legacyFontSizeFromCSSValue(Document*, CSSPrimitiveValue*, bool, LegacyFontSizeMode); static bool isTransparentColorValue(CSSValue*); static bool hasTransparentBackgroundColor(CSSStyleDeclaration*); static bool hasTransparentBackgroundColor(StylePropertySet*); static PassRefPtrWillBeRawPtr<CSSValue> backgroundColorValueInEffect(Node*); class HTMLElementEquivalent : public NoBaseWillBeGarbageCollected<HTMLElementEquivalent> { USING_FAST_MALLOC_WILL_BE_REMOVED(HTMLElementEquivalent); DECLARE_EMPTY_VIRTUAL_DESTRUCTOR_WILL_BE_REMOVED(HTMLElementEquivalent); public: static PassOwnPtrWillBeRawPtr<HTMLElementEquivalent> create(CSSPropertyID propertyID, CSSValueID primitiveValue, const HTMLQualifiedName& tagName) { return adoptPtrWillBeNoop(new HTMLElementEquivalent(propertyID, primitiveValue, tagName)); } virtual bool matches(const Element* element) const { return !m_tagName || element->hasTagName(*m_tagName); } virtual bool hasAttribute() const { return false; } virtual bool propertyExistsInStyle(const StylePropertySet* style) const { return style->getPropertyCSSValue(m_propertyID); } virtual bool valueIsPresentInStyle(HTMLElement*, StylePropertySet*) const; virtual void addToStyle(Element*, EditingStyle*) const; DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_primitiveValue); } protected: HTMLElementEquivalent(CSSPropertyID); HTMLElementEquivalent(CSSPropertyID, const HTMLQualifiedName& tagName); HTMLElementEquivalent(CSSPropertyID, CSSValueID primitiveValue, const HTMLQualifiedName& tagName); const CSSPropertyID m_propertyID; const RefPtrWillBeMember<CSSPrimitiveValue> m_primitiveValue; const HTMLQualifiedName* m_tagName; // We can store a pointer because HTML tag names are const global. }; DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(HTMLElementEquivalent); HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id) : m_propertyID(id) , m_tagName(0) { } HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id, const HTMLQualifiedName& tagName) : m_propertyID(id) , m_tagName(&tagName) { } HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id, CSSValueID primitiveValue, const HTMLQualifiedName& tagName) : m_propertyID(id) , m_primitiveValue(CSSPrimitiveValue::createIdentifier(primitiveValue)) , m_tagName(&tagName) { ASSERT(primitiveValue != CSSValueInvalid); } bool HTMLElementEquivalent::valueIsPresentInStyle(HTMLElement* element, StylePropertySet* style) const { RefPtrWillBeRawPtr<CSSValue> value = style->getPropertyCSSValue(m_propertyID); return matches(element) && value && value->isPrimitiveValue() && toCSSPrimitiveValue(value.get())->getValueID() == m_primitiveValue->getValueID(); } void HTMLElementEquivalent::addToStyle(Element*, EditingStyle* style) const { style->setProperty(m_propertyID, m_primitiveValue->cssText()); } class HTMLTextDecorationEquivalent final : public HTMLElementEquivalent { public: static PassOwnPtrWillBeRawPtr<HTMLElementEquivalent> create(CSSValueID primitiveValue, const HTMLQualifiedName& tagName) { return adoptPtrWillBeNoop(new HTMLTextDecorationEquivalent(primitiveValue, tagName)); } bool propertyExistsInStyle(const StylePropertySet*) const override; bool valueIsPresentInStyle(HTMLElement*, StylePropertySet*) const override; DEFINE_INLINE_VIRTUAL_TRACE() { HTMLElementEquivalent::trace(visitor); } private: HTMLTextDecorationEquivalent(CSSValueID primitiveValue, const HTMLQualifiedName& tagName); }; HTMLTextDecorationEquivalent::HTMLTextDecorationEquivalent(CSSValueID primitiveValue, const HTMLQualifiedName& tagName) : HTMLElementEquivalent(textDecorationPropertyForEditing(), primitiveValue, tagName) // m_propertyID is used in HTMLElementEquivalent::addToStyle { } bool HTMLTextDecorationEquivalent::propertyExistsInStyle(const StylePropertySet* style) const { return style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect) || style->getPropertyCSSValue(textDecorationPropertyForEditing()); } bool HTMLTextDecorationEquivalent::valueIsPresentInStyle(HTMLElement* element, StylePropertySet* style) const { RefPtrWillBeRawPtr<CSSValue> styleValue = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect); if (!styleValue) styleValue = style->getPropertyCSSValue(textDecorationPropertyForEditing()); return matches(element) && styleValue && styleValue->isValueList() && toCSSValueList(styleValue.get())->hasValue(m_primitiveValue.get()); } class HTMLAttributeEquivalent : public HTMLElementEquivalent { public: static PassOwnPtrWillBeRawPtr<HTMLAttributeEquivalent> create(CSSPropertyID propertyID, const HTMLQualifiedName& tagName, const QualifiedName& attrName) { return adoptPtrWillBeNoop(new HTMLAttributeEquivalent(propertyID, tagName, attrName)); } static PassOwnPtrWillBeRawPtr<HTMLAttributeEquivalent> create(CSSPropertyID propertyID, const QualifiedName& attrName) { return adoptPtrWillBeNoop(new HTMLAttributeEquivalent(propertyID, attrName)); } bool matches(const Element* element) const override { return HTMLElementEquivalent::matches(element) && element->hasAttribute(m_attrName); } bool hasAttribute() const override { return true; } bool valueIsPresentInStyle(HTMLElement*, StylePropertySet*) const override; void addToStyle(Element*, EditingStyle*) const override; virtual PassRefPtrWillBeRawPtr<CSSValue> attributeValueAsCSSValue(Element*) const; inline const QualifiedName& attributeName() const { return m_attrName; } DEFINE_INLINE_VIRTUAL_TRACE() { HTMLElementEquivalent::trace(visitor); } protected: HTMLAttributeEquivalent(CSSPropertyID, const HTMLQualifiedName& tagName, const QualifiedName& attrName); HTMLAttributeEquivalent(CSSPropertyID, const QualifiedName& attrName); const QualifiedName& m_attrName; // We can store a reference because HTML attribute names are const global. }; HTMLAttributeEquivalent::HTMLAttributeEquivalent(CSSPropertyID id, const HTMLQualifiedName& tagName, const QualifiedName& attrName) : HTMLElementEquivalent(id, tagName) , m_attrName(attrName) { } HTMLAttributeEquivalent::HTMLAttributeEquivalent(CSSPropertyID id, const QualifiedName& attrName) : HTMLElementEquivalent(id) , m_attrName(attrName) { } bool HTMLAttributeEquivalent::valueIsPresentInStyle(HTMLElement* element, StylePropertySet* style) const { RefPtrWillBeRawPtr<CSSValue> value = attributeValueAsCSSValue(element); RefPtrWillBeRawPtr<CSSValue> styleValue = style->getPropertyCSSValue(m_propertyID); return compareCSSValuePtr(value, styleValue); } void HTMLAttributeEquivalent::addToStyle(Element* element, EditingStyle* style) const { if (RefPtrWillBeRawPtr<CSSValue> value = attributeValueAsCSSValue(element)) style->setProperty(m_propertyID, value->cssText()); } PassRefPtrWillBeRawPtr<CSSValue> HTMLAttributeEquivalent::attributeValueAsCSSValue(Element* element) const { ASSERT(element); const AtomicString& value = element->getAttribute(m_attrName); if (value.isNull()) return nullptr; RefPtrWillBeRawPtr<MutableStylePropertySet> dummyStyle = nullptr; dummyStyle = MutableStylePropertySet::create(HTMLQuirksMode); dummyStyle->setProperty(m_propertyID, value); return dummyStyle->getPropertyCSSValue(m_propertyID); } class HTMLFontSizeEquivalent final : public HTMLAttributeEquivalent { public: static PassOwnPtrWillBeRawPtr<HTMLFontSizeEquivalent> create() { return adoptPtrWillBeNoop(new HTMLFontSizeEquivalent()); } PassRefPtrWillBeRawPtr<CSSValue> attributeValueAsCSSValue(Element*) const override; DEFINE_INLINE_VIRTUAL_TRACE() { HTMLAttributeEquivalent::trace(visitor); } private: HTMLFontSizeEquivalent(); }; HTMLFontSizeEquivalent::HTMLFontSizeEquivalent() : HTMLAttributeEquivalent(CSSPropertyFontSize, HTMLNames::fontTag, HTMLNames::sizeAttr) { } PassRefPtrWillBeRawPtr<CSSValue> HTMLFontSizeEquivalent::attributeValueAsCSSValue(Element* element) const { ASSERT(element); const AtomicString& value = element->getAttribute(m_attrName); if (value.isNull()) return nullptr; CSSValueID size; if (!HTMLFontElement::cssValueFromFontSizeNumber(value, size)) return nullptr; return CSSPrimitiveValue::createIdentifier(size); } float EditingStyle::NoFontDelta = 0.0f; EditingStyle::EditingStyle() : m_isMonospaceFont(false) , m_fontSizeDelta(NoFontDelta) { } EditingStyle::EditingStyle(ContainerNode* node, PropertiesToInclude propertiesToInclude) : m_isMonospaceFont(false) , m_fontSizeDelta(NoFontDelta) { init(node, propertiesToInclude); } EditingStyle::EditingStyle(const Position& position, PropertiesToInclude propertiesToInclude) : m_isMonospaceFont(false) , m_fontSizeDelta(NoFontDelta) { init(position.anchorNode(), propertiesToInclude); } EditingStyle::EditingStyle(const StylePropertySet* style) : m_mutableStyle(style ? style->mutableCopy() : nullptr) , m_isMonospaceFont(false) , m_fontSizeDelta(NoFontDelta) { extractFontSizeDelta(); } EditingStyle::EditingStyle(CSSPropertyID propertyID, const String& value) : m_mutableStyle(nullptr) , m_isMonospaceFont(false) , m_fontSizeDelta(NoFontDelta) { setProperty(propertyID, value); } EditingStyle::~EditingStyle() { } static Color cssValueToColor(CSSValue* colorValue) { if (!colorValue || (!colorValue->isColorValue() && !colorValue->isPrimitiveValue())) return Color::transparent; if (colorValue->isColorValue()) return toCSSColorValue(colorValue)->value(); Color color = 0; // FIXME: Why ignore the return value? CSSParser::parseColor(color, colorValue->cssText()); return color; } static inline Color getFontColor(CSSStyleDeclaration* style) { return cssValueToColor(style->getPropertyCSSValueInternal(CSSPropertyColor).get()); } static inline Color getFontColor(StylePropertySet* style) { return cssValueToColor(style->getPropertyCSSValue(CSSPropertyColor).get()); } static inline Color getBackgroundColor(CSSStyleDeclaration* style) { return cssValueToColor(style->getPropertyCSSValueInternal(CSSPropertyBackgroundColor).get()); } static inline Color getBackgroundColor(StylePropertySet* style) { return cssValueToColor(style->getPropertyCSSValue(CSSPropertyBackgroundColor).get()); } static inline Color backgroundColorInEffect(Node* node) { return cssValueToColor(backgroundColorValueInEffect(node).get()); } static int textAlignResolvingStartAndEnd(int textAlign, int direction) { switch (textAlign) { case CSSValueCenter: case CSSValueWebkitCenter: return CSSValueCenter; case CSSValueJustify: return CSSValueJustify; case CSSValueLeft: case CSSValueWebkitLeft: return CSSValueLeft; case CSSValueRight: case CSSValueWebkitRight: return CSSValueRight; case CSSValueStart: return direction != CSSValueRtl ? CSSValueLeft : CSSValueRight; case CSSValueEnd: return direction == CSSValueRtl ? CSSValueRight : CSSValueLeft; } return CSSValueInvalid; } template<typename T> static int textAlignResolvingStartAndEnd(T* style) { return textAlignResolvingStartAndEnd(getIdentifierValue(style, CSSPropertyTextAlign), getIdentifierValue(style, CSSPropertyDirection)); } void EditingStyle::init(Node* node, PropertiesToInclude propertiesToInclude) { if (isTabHTMLSpanElementTextNode(node)) node = tabSpanElement(node)->parentNode(); else if (isTabHTMLSpanElement(node)) node = node->parentNode(); RefPtrWillBeRawPtr<CSSComputedStyleDeclaration> computedStyleAtPosition = CSSComputedStyleDeclaration::create(node); m_mutableStyle = propertiesToInclude == AllProperties && computedStyleAtPosition ? computedStyleAtPosition->copyProperties() : editingStyleFromComputedStyle(computedStyleAtPosition); if (propertiesToInclude == EditingPropertiesInEffect) { if (RefPtrWillBeRawPtr<CSSValue> value = backgroundColorValueInEffect(node)) m_mutableStyle->setProperty(CSSPropertyBackgroundColor, value->cssText()); if (RefPtrWillBeRawPtr<CSSValue> value = computedStyleAtPosition->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect)) m_mutableStyle->setProperty(CSSPropertyTextDecoration, value->cssText()); } if (node && node->ensureComputedStyle()) { const ComputedStyle* computedStyle = node->ensureComputedStyle(); removeTextFillAndStrokeColorsIfNeeded(computedStyle); replaceFontSizeByKeywordIfPossible(computedStyle, computedStyleAtPosition.get()); } m_isMonospaceFont = computedStyleAtPosition->isMonospaceFont(); extractFontSizeDelta(); } void EditingStyle::removeTextFillAndStrokeColorsIfNeeded(const ComputedStyle* computedStyle) { // If a node's text fill color is currentColor, then its children use // their font-color as their text fill color (they don't // inherit it). Likewise for stroke color. if (computedStyle->textFillColor().isCurrentColor()) m_mutableStyle->removeProperty(CSSPropertyWebkitTextFillColor); if (computedStyle->textStrokeColor().isCurrentColor()) m_mutableStyle->removeProperty(CSSPropertyWebkitTextStrokeColor); } void EditingStyle::setProperty(CSSPropertyID propertyID, const String& value, bool important) { if (!m_mutableStyle) m_mutableStyle = MutableStylePropertySet::create(HTMLQuirksMode); m_mutableStyle->setProperty(propertyID, value, important); } void EditingStyle::replaceFontSizeByKeywordIfPossible(const ComputedStyle* computedStyle, CSSComputedStyleDeclaration* cssComputedStyle) { ASSERT(computedStyle); if (computedStyle->fontDescription().keywordSize()) m_mutableStyle->setProperty(CSSPropertyFontSize, cssComputedStyle->getFontSizeCSSValuePreferringKeyword()->cssText()); } void EditingStyle::extractFontSizeDelta() { if (!m_mutableStyle) return; if (m_mutableStyle->getPropertyCSSValue(CSSPropertyFontSize)) { // Explicit font size overrides any delta. m_mutableStyle->removeProperty(CSSPropertyWebkitFontSizeDelta); return; } // Get the adjustment amount out of the style. RefPtrWillBeRawPtr<CSSValue> value = m_mutableStyle->getPropertyCSSValue(CSSPropertyWebkitFontSizeDelta); if (!value || !value->isPrimitiveValue()) return; CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get()); // Only PX handled now. If we handle more types in the future, perhaps // a switch statement here would be more appropriate. if (!primitiveValue->isPx()) return; m_fontSizeDelta = primitiveValue->getFloatValue(); m_mutableStyle->removeProperty(CSSPropertyWebkitFontSizeDelta); } bool EditingStyle::isEmpty() const { return (!m_mutableStyle || m_mutableStyle->isEmpty()) && m_fontSizeDelta == NoFontDelta; } bool EditingStyle::textDirection(WritingDirection& writingDirection) const { if (!m_mutableStyle) return false; RefPtrWillBeRawPtr<CSSValue> unicodeBidi = m_mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi); if (!unicodeBidi || !unicodeBidi->isPrimitiveValue()) return false; CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID(); if (isEmbedOrIsolate(unicodeBidiValue)) { RefPtrWillBeRawPtr<CSSValue> direction = m_mutableStyle->getPropertyCSSValue(CSSPropertyDirection); if (!direction || !direction->isPrimitiveValue()) return false; writingDirection = toCSSPrimitiveValue(direction.get())->getValueID() == CSSValueLtr ? LeftToRightWritingDirection : RightToLeftWritingDirection; return true; } if (unicodeBidiValue == CSSValueNormal) { writingDirection = NaturalWritingDirection; return true; } return false; } void EditingStyle::overrideWithStyle(const StylePropertySet* style) { if (!style || style->isEmpty()) return; if (!m_mutableStyle) m_mutableStyle = MutableStylePropertySet::create(HTMLQuirksMode); m_mutableStyle->mergeAndOverrideOnConflict(style); extractFontSizeDelta(); } void EditingStyle::clear() { m_mutableStyle.clear(); m_isMonospaceFont = false; m_fontSizeDelta = NoFontDelta; } PassRefPtrWillBeRawPtr<EditingStyle> EditingStyle::copy() const { RefPtrWillBeRawPtr<EditingStyle> copy = EditingStyle::create(); if (m_mutableStyle) copy->m_mutableStyle = m_mutableStyle->mutableCopy(); copy->m_isMonospaceFont = m_isMonospaceFont; copy->m_fontSizeDelta = m_fontSizeDelta; return copy; } // This is the list of CSS properties that apply specially to block-level elements. static const CSSPropertyID staticBlockProperties[] = { CSSPropertyOrphans, CSSPropertyOverflow, // This can be also be applied to replaced elements CSSPropertyWebkitColumnCount, CSSPropertyWebkitColumnGap, CSSPropertyWebkitColumnRuleColor, CSSPropertyWebkitColumnRuleStyle, CSSPropertyWebkitColumnRuleWidth, CSSPropertyWebkitColumnBreakBefore, CSSPropertyWebkitColumnBreakAfter, CSSPropertyWebkitColumnBreakInside, CSSPropertyWebkitColumnWidth, CSSPropertyPageBreakAfter, CSSPropertyPageBreakBefore, CSSPropertyPageBreakInside, CSSPropertyTextAlign, CSSPropertyTextAlignLast, CSSPropertyTextIndent, CSSPropertyTextJustify, CSSPropertyWidows }; static const Vector<CSSPropertyID>& blockPropertiesVector() { DEFINE_STATIC_LOCAL(Vector<CSSPropertyID>, properties, ()); if (properties.isEmpty()) CSSPropertyMetadata::filterEnabledCSSPropertiesIntoVector(staticBlockProperties, WTF_ARRAY_LENGTH(staticBlockProperties), properties); return properties; } PassRefPtrWillBeRawPtr<EditingStyle> EditingStyle::extractAndRemoveBlockProperties() { RefPtrWillBeRawPtr<EditingStyle> blockProperties = EditingStyle::create(); if (!m_mutableStyle) return blockProperties; blockProperties->m_mutableStyle = m_mutableStyle->copyPropertiesInSet(blockPropertiesVector()); removeBlockProperties(); return blockProperties; } PassRefPtrWillBeRawPtr<EditingStyle> EditingStyle::extractAndRemoveTextDirection() { RefPtrWillBeRawPtr<EditingStyle> textDirection = EditingStyle::create(); textDirection->m_mutableStyle = MutableStylePropertySet::create(HTMLQuirksMode); textDirection->m_mutableStyle->setProperty(CSSPropertyUnicodeBidi, CSSValueIsolate, m_mutableStyle->propertyIsImportant(CSSPropertyUnicodeBidi)); textDirection->m_mutableStyle->setProperty(CSSPropertyDirection, m_mutableStyle->getPropertyValue(CSSPropertyDirection), m_mutableStyle->propertyIsImportant(CSSPropertyDirection)); m_mutableStyle->removeProperty(CSSPropertyUnicodeBidi); m_mutableStyle->removeProperty(CSSPropertyDirection); return textDirection; } void EditingStyle::removeBlockProperties() { if (!m_mutableStyle) return; m_mutableStyle->removePropertiesInSet(blockPropertiesVector().data(), blockPropertiesVector().size()); } void EditingStyle::removeStyleAddedByElement(Element* element) { if (!element || !element->parentNode()) return; RefPtrWillBeRawPtr<MutableStylePropertySet> parentStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(element->parentNode()), AllEditingProperties); RefPtrWillBeRawPtr<MutableStylePropertySet> nodeStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(element), AllEditingProperties); nodeStyle->removeEquivalentProperties(parentStyle.get()); m_mutableStyle->removeEquivalentProperties(nodeStyle.get()); } void EditingStyle::removeStyleConflictingWithStyleOfElement(Element* element) { if (!element || !element->parentNode() || !m_mutableStyle) return; RefPtrWillBeRawPtr<MutableStylePropertySet> parentStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(element->parentNode()), AllEditingProperties); RefPtrWillBeRawPtr<MutableStylePropertySet> nodeStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(element), AllEditingProperties); nodeStyle->removeEquivalentProperties(parentStyle.get()); unsigned propertyCount = nodeStyle->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) m_mutableStyle->removeProperty(nodeStyle->propertyAt(i).id()); } void EditingStyle::collapseTextDecorationProperties() { if (!m_mutableStyle) return; RefPtrWillBeRawPtr<CSSValue> textDecorationsInEffect = m_mutableStyle->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect); if (!textDecorationsInEffect) return; if (textDecorationsInEffect->isValueList()) m_mutableStyle->setProperty(textDecorationPropertyForEditing(), textDecorationsInEffect->cssText(), m_mutableStyle->propertyIsImportant(textDecorationPropertyForEditing())); else m_mutableStyle->removeProperty(textDecorationPropertyForEditing()); m_mutableStyle->removeProperty(CSSPropertyWebkitTextDecorationsInEffect); } // CSS properties that create a visual difference only when applied to text. static const CSSPropertyID textOnlyProperties[] = { // FIXME: CSSPropertyTextDecoration needs to be removed when CSS3 Text // Decoration feature is no longer experimental. CSSPropertyTextDecoration, CSSPropertyTextDecorationLine, CSSPropertyWebkitTextDecorationsInEffect, CSSPropertyFontStyle, CSSPropertyFontWeight, CSSPropertyColor, }; TriState EditingStyle::triStateOfStyle(EditingStyle* style) const { if (!style || !style->m_mutableStyle) return FalseTriState; return triStateOfStyle(style->m_mutableStyle->ensureCSSStyleDeclaration(), DoNotIgnoreTextOnlyProperties); } TriState EditingStyle::triStateOfStyle(CSSStyleDeclaration* styleToCompare, ShouldIgnoreTextOnlyProperties shouldIgnoreTextOnlyProperties) const { RefPtrWillBeRawPtr<MutableStylePropertySet> difference = getPropertiesNotIn(m_mutableStyle.get(), styleToCompare); if (shouldIgnoreTextOnlyProperties == IgnoreTextOnlyProperties) difference->removePropertiesInSet(textOnlyProperties, WTF_ARRAY_LENGTH(textOnlyProperties)); if (difference->isEmpty()) return TrueTriState; if (difference->propertyCount() == m_mutableStyle->propertyCount()) return FalseTriState; return MixedTriState; } TriState EditingStyle::triStateOfStyle(const VisibleSelection& selection) const { if (!selection.isCaretOrRange()) return FalseTriState; if (selection.isCaret()) return triStateOfStyle(EditingStyle::styleAtSelectionStart(selection).get()); TriState state = FalseTriState; bool nodeIsStart = true; for (Node& node : NodeTraversal::startsAt(selection.start().anchorNode())) { if (node.layoutObject() && node.hasEditableStyle()) { RefPtrWillBeRawPtr<CSSComputedStyleDeclaration> nodeStyle = CSSComputedStyleDeclaration::create(&node); if (nodeStyle) { TriState nodeState = triStateOfStyle(nodeStyle.get(), node.isTextNode() ? EditingStyle::DoNotIgnoreTextOnlyProperties : EditingStyle::IgnoreTextOnlyProperties); if (nodeIsStart) { state = nodeState; nodeIsStart = false; } else if (state != nodeState && node.isTextNode()) { state = MixedTriState; break; } } } if (&node == selection.end().anchorNode()) break; } return state; } bool EditingStyle::conflictsWithInlineStyleOfElement(HTMLElement* element, EditingStyle* extractedStyle, Vector<CSSPropertyID>* conflictingProperties) const { ASSERT(element); ASSERT(!conflictingProperties || conflictingProperties->isEmpty()); const StylePropertySet* inlineStyle = element->inlineStyle(); if (!m_mutableStyle || !inlineStyle) return false; unsigned propertyCount = m_mutableStyle->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { CSSPropertyID propertyID = m_mutableStyle->propertyAt(i).id(); // We don't override whitespace property of a tab span because that would collapse the tab into a space. if (propertyID == CSSPropertyWhiteSpace && isTabHTMLSpanElement(element)) continue; if (propertyID == CSSPropertyWebkitTextDecorationsInEffect && inlineStyle->getPropertyCSSValue(textDecorationPropertyForEditing())) { if (!conflictingProperties) return true; conflictingProperties->append(CSSPropertyTextDecoration); // Because text-decoration expands to text-decoration-line when CSS3 // Text Decoration is enabled, we also state it as conflicting. if (RuntimeEnabledFeatures::css3TextDecorationsEnabled()) conflictingProperties->append(CSSPropertyTextDecorationLine); if (extractedStyle) extractedStyle->setProperty(textDecorationPropertyForEditing(), inlineStyle->getPropertyValue(textDecorationPropertyForEditing()), inlineStyle->propertyIsImportant(textDecorationPropertyForEditing())); continue; } if (!inlineStyle->getPropertyCSSValue(propertyID)) continue; if (propertyID == CSSPropertyUnicodeBidi && inlineStyle->getPropertyCSSValue(CSSPropertyDirection)) { if (!conflictingProperties) return true; conflictingProperties->append(CSSPropertyDirection); if (extractedStyle) extractedStyle->setProperty(propertyID, inlineStyle->getPropertyValue(propertyID), inlineStyle->propertyIsImportant(propertyID)); } if (!conflictingProperties) return true; conflictingProperties->append(propertyID); if (extractedStyle) extractedStyle->setProperty(propertyID, inlineStyle->getPropertyValue(propertyID), inlineStyle->propertyIsImportant(propertyID)); } return conflictingProperties && !conflictingProperties->isEmpty(); } static const WillBeHeapVector<OwnPtrWillBeMember<HTMLElementEquivalent>>& htmlElementEquivalents() { DEFINE_STATIC_LOCAL(WillBePersistentHeapVector<OwnPtrWillBeMember<HTMLElementEquivalent>>, HTMLElementEquivalents, ()); if (!HTMLElementEquivalents.size()) { HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyFontWeight, CSSValueBold, HTMLNames::bTag)); HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyFontWeight, CSSValueBold, HTMLNames::strongTag)); HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyVerticalAlign, CSSValueSub, HTMLNames::subTag)); HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyVerticalAlign, CSSValueSuper, HTMLNames::supTag)); HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::iTag)); HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::emTag)); HTMLElementEquivalents.append(HTMLTextDecorationEquivalent::create(CSSValueUnderline, HTMLNames::uTag)); HTMLElementEquivalents.append(HTMLTextDecorationEquivalent::create(CSSValueLineThrough, HTMLNames::sTag)); HTMLElementEquivalents.append(HTMLTextDecorationEquivalent::create(CSSValueLineThrough, HTMLNames::strikeTag)); } return HTMLElementEquivalents; } bool EditingStyle::conflictsWithImplicitStyleOfElement(HTMLElement* element, EditingStyle* extractedStyle, ShouldExtractMatchingStyle shouldExtractMatchingStyle) const { if (!m_mutableStyle) return false; const WillBeHeapVector<OwnPtrWillBeMember<HTMLElementEquivalent>>& HTMLElementEquivalents = htmlElementEquivalents(); for (size_t i = 0; i < HTMLElementEquivalents.size(); ++i) { const HTMLElementEquivalent* equivalent = HTMLElementEquivalents[i].get(); if (equivalent->matches(element) && equivalent->propertyExistsInStyle(m_mutableStyle.get()) && (shouldExtractMatchingStyle == ExtractMatchingStyle || !equivalent->valueIsPresentInStyle(element, m_mutableStyle.get()))) { if (extractedStyle) equivalent->addToStyle(element, extractedStyle); return true; } } return false; } static const WillBeHeapVector<OwnPtrWillBeMember<HTMLAttributeEquivalent>>& htmlAttributeEquivalents() { DEFINE_STATIC_LOCAL(WillBePersistentHeapVector<OwnPtrWillBeMember<HTMLAttributeEquivalent>>, HTMLAttributeEquivalents, ()); if (!HTMLAttributeEquivalents.size()) { // elementIsStyledSpanOrHTMLEquivalent depends on the fact each HTMLAttriuteEquivalent matches exactly one attribute // of exactly one element except dirAttr. HTMLAttributeEquivalents.append(HTMLAttributeEquivalent::create(CSSPropertyColor, HTMLNames::fontTag, HTMLNames::colorAttr)); HTMLAttributeEquivalents.append(HTMLAttributeEquivalent::create(CSSPropertyFontFamily, HTMLNames::fontTag, HTMLNames::faceAttr)); HTMLAttributeEquivalents.append(HTMLFontSizeEquivalent::create()); HTMLAttributeEquivalents.append(HTMLAttributeEquivalent::create(CSSPropertyDirection, HTMLNames::dirAttr)); HTMLAttributeEquivalents.append(HTMLAttributeEquivalent::create(CSSPropertyUnicodeBidi, HTMLNames::dirAttr)); } return HTMLAttributeEquivalents; } bool EditingStyle::conflictsWithImplicitStyleOfAttributes(HTMLElement* element) const { ASSERT(element); if (!m_mutableStyle) return false; const WillBeHeapVector<OwnPtrWillBeMember<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents(); for (const auto& equivalent : HTMLAttributeEquivalents) { if (equivalent->matches(element) && equivalent->propertyExistsInStyle(m_mutableStyle.get()) && !equivalent->valueIsPresentInStyle(element, m_mutableStyle.get())) return true; } return false; } bool EditingStyle::extractConflictingImplicitStyleOfAttributes(HTMLElement* element, ShouldPreserveWritingDirection shouldPreserveWritingDirection, EditingStyle* extractedStyle, Vector<QualifiedName>& conflictingAttributes, ShouldExtractMatchingStyle shouldExtractMatchingStyle) const { ASSERT(element); // HTMLAttributeEquivalent::addToStyle doesn't support unicode-bidi and direction properties ASSERT(!extractedStyle || shouldPreserveWritingDirection == PreserveWritingDirection); if (!m_mutableStyle) return false; const WillBeHeapVector<OwnPtrWillBeMember<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents(); bool removed = false; for (const auto& attribute : HTMLAttributeEquivalents) { const HTMLAttributeEquivalent* equivalent = attribute.get(); // unicode-bidi and direction are pushed down separately so don't push down with other styles. if (shouldPreserveWritingDirection == PreserveWritingDirection && equivalent->attributeName() == HTMLNames::dirAttr) continue; if (!equivalent->matches(element) || !equivalent->propertyExistsInStyle(m_mutableStyle.get()) || (shouldExtractMatchingStyle == DoNotExtractMatchingStyle && equivalent->valueIsPresentInStyle(element, m_mutableStyle.get()))) continue; if (extractedStyle) equivalent->addToStyle(element, extractedStyle); conflictingAttributes.append(equivalent->attributeName()); removed = true; } return removed; } bool EditingStyle::styleIsPresentInComputedStyleOfNode(Node* node) const { return !m_mutableStyle || getPropertiesNotIn(m_mutableStyle.get(), CSSComputedStyleDeclaration::create(node).get())->isEmpty(); } bool EditingStyle::elementIsStyledSpanOrHTMLEquivalent(const HTMLElement* element) { ASSERT(element); bool elementIsSpanOrElementEquivalent = false; if (isHTMLSpanElement(*element)) { elementIsSpanOrElementEquivalent = true; } else { const WillBeHeapVector<OwnPtrWillBeMember<HTMLElementEquivalent>>& HTMLElementEquivalents = htmlElementEquivalents(); size_t i; for (i = 0; i < HTMLElementEquivalents.size(); ++i) { if (HTMLElementEquivalents[i]->matches(element)) { elementIsSpanOrElementEquivalent = true; break; } } } AttributeCollection attributes = element->attributes(); if (attributes.isEmpty()) return elementIsSpanOrElementEquivalent; // span, b, etc... without any attributes unsigned matchedAttributes = 0; const WillBeHeapVector<OwnPtrWillBeMember<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents(); for (const auto& equivalent : HTMLAttributeEquivalents) { if (equivalent->matches(element) && equivalent->attributeName() != HTMLNames::dirAttr) matchedAttributes++; } if (!elementIsSpanOrElementEquivalent && !matchedAttributes) return false; // element is not a span, a html element equivalent, or font element. if (element->getAttribute(HTMLNames::classAttr) == AppleStyleSpanClass) matchedAttributes++; if (element->hasAttribute(HTMLNames::styleAttr)) { if (const StylePropertySet* style = element->inlineStyle()) { unsigned propertyCount = style->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { if (!isEditingProperty(style->propertyAt(i).id())) return false; } } matchedAttributes++; } // font with color attribute, span with style attribute, etc... ASSERT(matchedAttributes <= attributes.size()); return matchedAttributes >= attributes.size(); } void EditingStyle::prepareToApplyAt(const Position& position, ShouldPreserveWritingDirection shouldPreserveWritingDirection) { if (!m_mutableStyle) return; // ReplaceSelectionCommand::handleStyleSpans() requires that this function only removes the editing style. // If this function was modified in the future to delete all redundant properties, then add a boolean value to indicate // which one of editingStyleAtPosition or computedStyle is called. RefPtrWillBeRawPtr<EditingStyle> editingStyleAtPosition = EditingStyle::create(position, EditingPropertiesInEffect); StylePropertySet* styleAtPosition = editingStyleAtPosition->m_mutableStyle.get(); RefPtrWillBeRawPtr<CSSValue> unicodeBidi = nullptr; RefPtrWillBeRawPtr<CSSValue> direction = nullptr; if (shouldPreserveWritingDirection == PreserveWritingDirection) { unicodeBidi = m_mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi); direction = m_mutableStyle->getPropertyCSSValue(CSSPropertyDirection); } m_mutableStyle->removeEquivalentProperties(styleAtPosition); if (textAlignResolvingStartAndEnd(m_mutableStyle.get()) == textAlignResolvingStartAndEnd(styleAtPosition)) m_mutableStyle->removeProperty(CSSPropertyTextAlign); if (getFontColor(m_mutableStyle.get()) == getFontColor(styleAtPosition)) m_mutableStyle->removeProperty(CSSPropertyColor); if (hasTransparentBackgroundColor(m_mutableStyle.get()) || cssValueToColor(m_mutableStyle->getPropertyCSSValue(CSSPropertyBackgroundColor).get()) == backgroundColorInEffect(position.computeContainerNode())) m_mutableStyle->removeProperty(CSSPropertyBackgroundColor); if (unicodeBidi && unicodeBidi->isPrimitiveValue()) { m_mutableStyle->setProperty(CSSPropertyUnicodeBidi, toCSSPrimitiveValue(unicodeBidi.get())->getValueID()); if (direction && direction->isPrimitiveValue()) m_mutableStyle->setProperty(CSSPropertyDirection, toCSSPrimitiveValue(direction.get())->getValueID()); } } void EditingStyle::mergeTypingStyle(Document* document) { ASSERT(document); RefPtrWillBeRawPtr<EditingStyle> typingStyle = document->frame()->selection().typingStyle(); if (!typingStyle || typingStyle == this) return; mergeStyle(typingStyle->style(), OverrideValues); } void EditingStyle::mergeInlineStyleOfElement(HTMLElement* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude) { ASSERT(element); if (!element->inlineStyle()) return; switch (propertiesToInclude) { case AllProperties: mergeStyle(element->inlineStyle(), mode); return; case OnlyEditingInheritableProperties: mergeStyle(copyEditingProperties(element->inlineStyle(), OnlyInheritableEditingProperties).get(), mode); return; case EditingPropertiesInEffect: mergeStyle(copyEditingProperties(element->inlineStyle(), AllEditingProperties).get(), mode); return; } } static inline bool elementMatchesAndPropertyIsNotInInlineStyleDecl(const HTMLElementEquivalent* equivalent, const Element* element, EditingStyle::CSSPropertyOverrideMode mode, StylePropertySet* style) { return equivalent->matches(element) && (!element->inlineStyle() || !equivalent->propertyExistsInStyle(element->inlineStyle())) && (mode == EditingStyle::OverrideValues || !equivalent->propertyExistsInStyle(style)); } static PassRefPtrWillBeRawPtr<MutableStylePropertySet> extractEditingProperties(const StylePropertySet* style, EditingStyle::PropertiesToInclude propertiesToInclude) { if (!style) return nullptr; switch (propertiesToInclude) { case EditingStyle::AllProperties: case EditingStyle::EditingPropertiesInEffect: return copyEditingProperties(style, AllEditingProperties); case EditingStyle::OnlyEditingInheritableProperties: return copyEditingProperties(style, OnlyInheritableEditingProperties); } ASSERT_NOT_REACHED(); return nullptr; } void EditingStyle::mergeInlineAndImplicitStyleOfElement(Element* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude) { RefPtrWillBeRawPtr<EditingStyle> styleFromRules = EditingStyle::create(); styleFromRules->mergeStyleFromRulesForSerialization(element); if (element->inlineStyle()) styleFromRules->m_mutableStyle->mergeAndOverrideOnConflict(element->inlineStyle()); styleFromRules->m_mutableStyle = extractEditingProperties(styleFromRules->m_mutableStyle.get(), propertiesToInclude); mergeStyle(styleFromRules->m_mutableStyle.get(), mode); const WillBeHeapVector<OwnPtrWillBeMember<HTMLElementEquivalent>>& elementEquivalents = htmlElementEquivalents(); for (const auto& equivalent : elementEquivalents) { if (elementMatchesAndPropertyIsNotInInlineStyleDecl(equivalent.get(), element, mode, m_mutableStyle.get())) equivalent->addToStyle(element, this); } const WillBeHeapVector<OwnPtrWillBeMember<HTMLAttributeEquivalent>>& attributeEquivalents = htmlAttributeEquivalents(); for (const auto& attribute : attributeEquivalents) { if (attribute->attributeName() == HTMLNames::dirAttr) continue; // We don't want to include directionality if (elementMatchesAndPropertyIsNotInInlineStyleDecl(attribute.get(), element, mode, m_mutableStyle.get())) attribute->addToStyle(element, this); } } PassRefPtrWillBeRawPtr<EditingStyle> EditingStyle::wrappingStyleForAnnotatedSerialization(ContainerNode* context) { RefPtrWillBeRawPtr<EditingStyle> wrappingStyle = EditingStyle::create(context, EditingStyle::EditingPropertiesInEffect); // Styles that Mail blockquotes contribute should only be placed on the Mail // blockquote, to help us differentiate those styles from ones that the user // has applied. This helps us get the color of content pasted into // blockquotes right. wrappingStyle->removeStyleAddedByElement(toHTMLElement(enclosingNodeOfType(firstPositionInOrBeforeNode(context), isMailHTMLBlockquoteElement, CanCrossEditingBoundary))); // Call collapseTextDecorationProperties first or otherwise it'll copy the value over from in-effect to text-decorations. wrappingStyle->collapseTextDecorationProperties(); return wrappingStyle.release(); } PassRefPtrWillBeRawPtr<EditingStyle> EditingStyle::wrappingStyleForSerialization(ContainerNode* context) { RefPtrWillBeRawPtr<EditingStyle> wrappingStyle = EditingStyle::create(); // When not annotating for interchange, we only preserve inline style declarations. for (ContainerNode* node = context; node && !node->isDocumentNode(); node = node->parentNode()) { if (node->isStyledElement() && !isMailHTMLBlockquoteElement(node)) { wrappingStyle->mergeInlineAndImplicitStyleOfElement(toElement(node), EditingStyle::DoNotOverrideValues, EditingStyle::EditingPropertiesInEffect); } } return wrappingStyle.release(); } static void mergeTextDecorationValues(CSSValueList* mergedValue, const CSSValueList* valueToMerge) { DEFINE_STATIC_REF_WILL_BE_PERSISTENT(CSSPrimitiveValue, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline))); DEFINE_STATIC_REF_WILL_BE_PERSISTENT(CSSPrimitiveValue, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough))); if (valueToMerge->hasValue(underline) && !mergedValue->hasValue(underline)) mergedValue->append(underline); if (valueToMerge->hasValue(lineThrough) && !mergedValue->hasValue(lineThrough)) mergedValue->append(lineThrough); } void EditingStyle::mergeStyle(const StylePropertySet* style, CSSPropertyOverrideMode mode) { if (!style) return; if (!m_mutableStyle) { m_mutableStyle = style->mutableCopy(); return; } unsigned propertyCount = style->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { StylePropertySet::PropertyReference property = style->propertyAt(i); RefPtrWillBeRawPtr<CSSValue> value = m_mutableStyle->getPropertyCSSValue(property.id()); // text decorations never override values if ((property.id() == textDecorationPropertyForEditing() || property.id() == CSSPropertyWebkitTextDecorationsInEffect) && property.value()->isValueList() && value) { if (value->isValueList()) { mergeTextDecorationValues(toCSSValueList(value.get()), toCSSValueList(property.value())); continue; } value = nullptr; // text-decoration: none is equivalent to not having the property } if (mode == OverrideValues || (mode == DoNotOverrideValues && !value)) m_mutableStyle->setProperty(property.id(), property.value()->cssText(), property.isImportant()); } } static PassRefPtrWillBeRawPtr<MutableStylePropertySet> styleFromMatchedRulesForElement(Element* element, unsigned rulesToInclude) { RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create(HTMLQuirksMode); RefPtrWillBeRawPtr<StyleRuleList> matchedRules = element->document().ensureStyleResolver().styleRulesForElement(element, rulesToInclude); if (matchedRules) { for (unsigned i = 0; i < matchedRules->size(); ++i) style->mergeAndOverrideOnConflict(&matchedRules->at(i)->properties()); } return style.release(); } void EditingStyle::mergeStyleFromRules(Element* element) { RefPtrWillBeRawPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element, StyleResolver::AuthorCSSRules | StyleResolver::CrossOriginCSSRules); // Styles from the inline style declaration, held in the variable "style", take precedence // over those from matched rules. if (m_mutableStyle) styleFromMatchedRules->mergeAndOverrideOnConflict(m_mutableStyle.get()); clear(); m_mutableStyle = styleFromMatchedRules; } void EditingStyle::mergeStyleFromRulesForSerialization(Element* element) { mergeStyleFromRules(element); // The property value, if it's a percentage, may not reflect the actual computed value. // For example: style="height: 1%; overflow: visible;" in quirksmode // FIXME: There are others like this, see <rdar://problem/5195123> Slashdot copy/paste fidelity problem RefPtrWillBeRawPtr<CSSComputedStyleDeclaration> computedStyleForElement = CSSComputedStyleDeclaration::create(element); RefPtrWillBeRawPtr<MutableStylePropertySet> fromComputedStyle = MutableStylePropertySet::create(HTMLQuirksMode); { unsigned propertyCount = m_mutableStyle->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { StylePropertySet::PropertyReference property = m_mutableStyle->propertyAt(i); CSSValue* value = property.value(); if (!value->isPrimitiveValue()) continue; if (toCSSPrimitiveValue(value)->isPercentage()) { if (RefPtrWillBeRawPtr<CSSValue> computedPropertyValue = computedStyleForElement->getPropertyCSSValue(property.id())) fromComputedStyle->addRespectingCascade(CSSProperty(property.id(), computedPropertyValue)); } } } m_mutableStyle->mergeAndOverrideOnConflict(fromComputedStyle.get()); } static void removePropertiesInStyle(MutableStylePropertySet* styleToRemovePropertiesFrom, StylePropertySet* style) { unsigned propertyCount = style->propertyCount(); Vector<CSSPropertyID> propertiesToRemove(propertyCount); for (unsigned i = 0; i < propertyCount; ++i) propertiesToRemove[i] = style->propertyAt(i).id(); styleToRemovePropertiesFrom->removePropertiesInSet(propertiesToRemove.data(), propertiesToRemove.size()); } void EditingStyle::removeStyleFromRulesAndContext(Element* element, ContainerNode* context) { ASSERT(element); if (!m_mutableStyle) return; // 1. Remove style from matched rules because style remain without repeating it in inline style declaration RefPtrWillBeRawPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element, StyleResolver::AllButEmptyCSSRules); if (styleFromMatchedRules && !styleFromMatchedRules->isEmpty()) m_mutableStyle = getPropertiesNotIn(m_mutableStyle.get(), styleFromMatchedRules->ensureCSSStyleDeclaration()); // 2. Remove style present in context and not overriden by matched rules. RefPtrWillBeRawPtr<EditingStyle> computedStyle = EditingStyle::create(context, EditingPropertiesInEffect); if (computedStyle->m_mutableStyle) { if (!computedStyle->m_mutableStyle->getPropertyCSSValue(CSSPropertyBackgroundColor)) computedStyle->m_mutableStyle->setProperty(CSSPropertyBackgroundColor, CSSValueTransparent); removePropertiesInStyle(computedStyle->m_mutableStyle.get(), styleFromMatchedRules.get()); m_mutableStyle = getPropertiesNotIn(m_mutableStyle.get(), computedStyle->m_mutableStyle->ensureCSSStyleDeclaration()); } // 3. If this element is a span and has display: inline or float: none, remove them unless they are overriden by rules. // These rules are added by serialization code to wrap text nodes. if (isStyleSpanOrSpanWithOnlyStyleAttribute(element)) { if (!styleFromMatchedRules->getPropertyCSSValue(CSSPropertyDisplay) && getIdentifierValue(m_mutableStyle.get(), CSSPropertyDisplay) == CSSValueInline) m_mutableStyle->removeProperty(CSSPropertyDisplay); if (!styleFromMatchedRules->getPropertyCSSValue(CSSPropertyFloat) && getIdentifierValue(m_mutableStyle.get(), CSSPropertyFloat) == CSSValueNone) m_mutableStyle->removeProperty(CSSPropertyFloat); } } void EditingStyle::removePropertiesInElementDefaultStyle(Element* element) { if (!m_mutableStyle || m_mutableStyle->isEmpty()) return; RefPtrWillBeRawPtr<StylePropertySet> defaultStyle = styleFromMatchedRulesForElement(element, StyleResolver::UAAndUserCSSRules); removePropertiesInStyle(m_mutableStyle.get(), defaultStyle.get()); } void EditingStyle::addAbsolutePositioningFromElement(const Element& element) { LayoutRect rect = element.boundingBox(); LayoutObject* layoutObject = element.layoutObject(); LayoutUnit x = rect.x(); LayoutUnit y = rect.y(); LayoutUnit width = rect.width(); LayoutUnit height = rect.height(); if (layoutObject && layoutObject->isBox()) { LayoutBox* layoutBox = toLayoutBox(layoutObject); x -= layoutBox->marginLeft(); y -= layoutBox->marginTop(); m_mutableStyle->setProperty(CSSPropertyBoxSizing, CSSValueBorderBox); } m_mutableStyle->setProperty(CSSPropertyPosition, CSSValueAbsolute); m_mutableStyle->setProperty(CSSPropertyLeft, cssValuePool().createValue(x, CSSPrimitiveValue::UnitType::Pixels)); m_mutableStyle->setProperty(CSSPropertyTop, cssValuePool().createValue(y, CSSPrimitiveValue::UnitType::Pixels)); m_mutableStyle->setProperty(CSSPropertyWidth, cssValuePool().createValue(width, CSSPrimitiveValue::UnitType::Pixels)); m_mutableStyle->setProperty(CSSPropertyHeight, cssValuePool().createValue(height, CSSPrimitiveValue::UnitType::Pixels)); } void EditingStyle::forceInline() { if (!m_mutableStyle) m_mutableStyle = MutableStylePropertySet::create(HTMLQuirksMode); const bool propertyIsImportant = true; m_mutableStyle->setProperty(CSSPropertyDisplay, CSSValueInline, propertyIsImportant); } int EditingStyle::legacyFontSize(Document* document) const { RefPtrWillBeRawPtr<CSSValue> cssValue = m_mutableStyle->getPropertyCSSValue(CSSPropertyFontSize); if (!cssValue || !cssValue->isPrimitiveValue()) return 0; return legacyFontSizeFromCSSValue(document, toCSSPrimitiveValue(cssValue.get()), m_isMonospaceFont, AlwaysUseLegacyFontSize); } PassRefPtrWillBeRawPtr<EditingStyle> EditingStyle::styleAtSelectionStart(const VisibleSelection& selection, bool shouldUseBackgroundColorInEffect) { if (selection.isNone()) return nullptr; Position position = adjustedSelectionStartForStyleComputation(selection); // If the pos is at the end of a text node, then this node is not fully selected. // Move it to the next deep equivalent position to avoid removing the style from this node. // e.g. if pos was at Position("hello", 5) in <b>hello<div>world</div></b>, we want Position("world", 0) instead. // We only do this for range because caret at Position("hello", 5) in <b>hello</b>world should give you font-weight: bold. Node* positionNode = position.computeContainerNode(); if (selection.isRange() && positionNode && positionNode->isTextNode() && position.computeOffsetInContainerNode() == positionNode->maxCharacterOffset()) position = nextVisuallyDistinctCandidate(position); Element* element = associatedElementOf(position); if (!element) return nullptr; RefPtrWillBeRawPtr<EditingStyle> style = EditingStyle::create(element, EditingStyle::AllProperties); style->mergeTypingStyle(&element->document()); // If background color is transparent, traverse parent nodes until we hit a different value or document root // Also, if the selection is a range, ignore the background color at the start of selection, // and find the background color of the common ancestor. if (shouldUseBackgroundColorInEffect && (selection.isRange() || hasTransparentBackgroundColor(style->m_mutableStyle.get()))) { const EphemeralRange range(selection.toNormalizedEphemeralRange()); if (PassRefPtrWillBeRawPtr<CSSValue> value = backgroundColorValueInEffect(Range::commonAncestorContainer(range.startPosition().computeContainerNode(), range.endPosition().computeContainerNode()))) style->setProperty(CSSPropertyBackgroundColor, value->cssText()); } return style; } static bool isUnicodeBidiNestedOrMultipleEmbeddings(CSSValueID valueID) { return valueID == CSSValueEmbed || valueID == CSSValueBidiOverride || valueID == CSSValueWebkitIsolate || valueID == CSSValueWebkitIsolateOverride || valueID == CSSValueWebkitPlaintext || valueID == CSSValueIsolate || valueID == CSSValueIsolateOverride || valueID == CSSValuePlaintext; } WritingDirection EditingStyle::textDirectionForSelection(const VisibleSelection& selection, EditingStyle* typingStyle, bool& hasNestedOrMultipleEmbeddings) { hasNestedOrMultipleEmbeddings = true; if (selection.isNone()) return NaturalWritingDirection; Position position = mostForwardCaretPosition(selection.start()); Node* node = position.anchorNode(); if (!node) return NaturalWritingDirection; Position end; if (selection.isRange()) { end = mostBackwardCaretPosition(selection.end()); ASSERT(end.document()); Node* pastLast = Range::create(*end.document(), position.parentAnchoredEquivalent(), end.parentAnchoredEquivalent())->pastLastNode(); for (Node* n = node; n && n != pastLast; n = NodeTraversal::next(*n)) { if (!n->isStyledElement()) continue; RefPtrWillBeRawPtr<CSSComputedStyleDeclaration> style = CSSComputedStyleDeclaration::create(n); RefPtrWillBeRawPtr<CSSValue> unicodeBidi = style->getPropertyCSSValue(CSSPropertyUnicodeBidi); if (!unicodeBidi || !unicodeBidi->isPrimitiveValue()) continue; CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID(); if (isUnicodeBidiNestedOrMultipleEmbeddings(unicodeBidiValue)) return NaturalWritingDirection; } } if (selection.isCaret()) { WritingDirection direction; if (typingStyle && typingStyle->textDirection(direction)) { hasNestedOrMultipleEmbeddings = false; return direction; } node = selection.visibleStart().deepEquivalent().anchorNode(); } // The selection is either a caret with no typing attributes or a range in which no embedding is added, so just use the start position // to decide. Node* block = enclosingBlock(node); WritingDirection foundDirection = NaturalWritingDirection; for (; node != block; node = node->parentNode()) { if (!node->isStyledElement()) continue; Element* element = toElement(node); RefPtrWillBeRawPtr<CSSComputedStyleDeclaration> style = CSSComputedStyleDeclaration::create(element); RefPtrWillBeRawPtr<CSSValue> unicodeBidi = style->getPropertyCSSValue(CSSPropertyUnicodeBidi); if (!unicodeBidi || !unicodeBidi->isPrimitiveValue()) continue; CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID(); if (unicodeBidiValue == CSSValueNormal) continue; if (unicodeBidiValue == CSSValueBidiOverride) return NaturalWritingDirection; ASSERT(isEmbedOrIsolate(unicodeBidiValue)); RefPtrWillBeRawPtr<CSSValue> direction = style->getPropertyCSSValue(CSSPropertyDirection); if (!direction || !direction->isPrimitiveValue()) continue; int directionValue = toCSSPrimitiveValue(direction.get())->getValueID(); if (directionValue != CSSValueLtr && directionValue != CSSValueRtl) continue; if (foundDirection != NaturalWritingDirection) return NaturalWritingDirection; // In the range case, make sure that the embedding element persists until the end of the range. if (selection.isRange() && !end.anchorNode()->isDescendantOf(element)) return NaturalWritingDirection; foundDirection = directionValue == CSSValueLtr ? LeftToRightWritingDirection : RightToLeftWritingDirection; } hasNestedOrMultipleEmbeddings = false; return foundDirection; } DEFINE_TRACE(EditingStyle) { visitor->trace(m_mutableStyle); } static void reconcileTextDecorationProperties(MutableStylePropertySet* style) { RefPtrWillBeRawPtr<CSSValue> textDecorationsInEffect = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect); RefPtrWillBeRawPtr<CSSValue> textDecoration = style->getPropertyCSSValue(textDecorationPropertyForEditing()); // We shouldn't have both text-decoration and -webkit-text-decorations-in-effect because that wouldn't make sense. ASSERT(!textDecorationsInEffect || !textDecoration); if (textDecorationsInEffect) { style->setProperty(textDecorationPropertyForEditing(), textDecorationsInEffect->cssText()); style->removeProperty(CSSPropertyWebkitTextDecorationsInEffect); textDecoration = textDecorationsInEffect; } // If text-decoration is set to "none", remove the property because we don't want to add redundant "text-decoration: none". if (textDecoration && !textDecoration->isValueList()) style->removeProperty(textDecorationPropertyForEditing()); } StyleChange::StyleChange(EditingStyle* style, const Position& position) : m_applyBold(false) , m_applyItalic(false) , m_applyUnderline(false) , m_applyLineThrough(false) , m_applySubscript(false) , m_applySuperscript(false) { Document* document = position.document(); if (!style || !style->style() || !document || !document->frame() || !associatedElementOf(position)) return; RefPtrWillBeRawPtr<CSSComputedStyleDeclaration> computedStyle = ensureComputedStyle(position); // FIXME: take care of background-color in effect RefPtrWillBeRawPtr<MutableStylePropertySet> mutableStyle = getPropertiesNotIn(style->style(), computedStyle.get()); ASSERT(mutableStyle); reconcileTextDecorationProperties(mutableStyle.get()); if (!document->frame()->editor().shouldStyleWithCSS()) extractTextStyles(document, mutableStyle.get(), computedStyle->isMonospaceFont()); // Changing the whitespace style in a tab span would collapse the tab into a space. if (isTabHTMLSpanElementTextNode(position.anchorNode()) || isTabHTMLSpanElement((position.anchorNode()))) mutableStyle->removeProperty(CSSPropertyWhiteSpace); // If unicode-bidi is present in mutableStyle and direction is not, then add direction to mutableStyle. // FIXME: Shouldn't this be done in getPropertiesNotIn? if (mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi) && !style->style()->getPropertyCSSValue(CSSPropertyDirection)) mutableStyle->setProperty(CSSPropertyDirection, style->style()->getPropertyValue(CSSPropertyDirection)); // Save the result for later m_cssStyle = mutableStyle->asText().stripWhiteSpace(); } static void setTextDecorationProperty(MutableStylePropertySet* style, const CSSValueList* newTextDecoration, CSSPropertyID propertyID) { if (newTextDecoration->length()) { style->setProperty(propertyID, newTextDecoration->cssText(), style->propertyIsImportant(propertyID)); } else { // text-decoration: none is redundant since it does not remove any text // decorations. style->removeProperty(propertyID); } } void StyleChange::extractTextStyles(Document* document, MutableStylePropertySet* style, bool isMonospaceFont) { ASSERT(style); if (getIdentifierValue(style, CSSPropertyFontWeight) == CSSValueBold) { style->removeProperty(CSSPropertyFontWeight); m_applyBold = true; } int fontStyle = getIdentifierValue(style, CSSPropertyFontStyle); if (fontStyle == CSSValueItalic || fontStyle == CSSValueOblique) { style->removeProperty(CSSPropertyFontStyle); m_applyItalic = true; } // Assuming reconcileTextDecorationProperties has been called, there should not be -webkit-text-decorations-in-effect // Furthermore, text-decoration: none has been trimmed so that text-decoration property is always a CSSValueList. RefPtrWillBeRawPtr<CSSValue> textDecoration = style->getPropertyCSSValue(textDecorationPropertyForEditing()); if (textDecoration && textDecoration->isValueList()) { DEFINE_STATIC_REF_WILL_BE_PERSISTENT(CSSPrimitiveValue, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline))); DEFINE_STATIC_REF_WILL_BE_PERSISTENT(CSSPrimitiveValue, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough))); RefPtrWillBeRawPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy(); if (newTextDecoration->removeAll(underline)) m_applyUnderline = true; if (newTextDecoration->removeAll(lineThrough)) m_applyLineThrough = true; // If trimTextDecorations, delete underline and line-through setTextDecorationProperty(style, newTextDecoration.get(), textDecorationPropertyForEditing()); } int verticalAlign = getIdentifierValue(style, CSSPropertyVerticalAlign); switch (verticalAlign) { case CSSValueSub: style->removeProperty(CSSPropertyVerticalAlign); m_applySubscript = true; break; case CSSValueSuper: style->removeProperty(CSSPropertyVerticalAlign); m_applySuperscript = true; break; } if (style->getPropertyCSSValue(CSSPropertyColor)) { m_applyFontColor = getFontColor(style).serialized(); style->removeProperty(CSSPropertyColor); } m_applyFontFace = style->getPropertyValue(CSSPropertyFontFamily); // Remove single quotes for Outlook 2007 compatibility. See https://bugs.webkit.org/show_bug.cgi?id=79448 m_applyFontFace.replaceWithLiteral('\'', ""); style->removeProperty(CSSPropertyFontFamily); if (RefPtrWillBeRawPtr<CSSValue> fontSize = style->getPropertyCSSValue(CSSPropertyFontSize)) { if (!fontSize->isPrimitiveValue()) { style->removeProperty(CSSPropertyFontSize); // Can't make sense of the number. Put no font size. } else if (int legacyFontSize = legacyFontSizeFromCSSValue(document, toCSSPrimitiveValue(fontSize.get()), isMonospaceFont, UseLegacyFontSizeOnlyIfPixelValuesMatch)) { m_applyFontSize = String::number(legacyFontSize); style->removeProperty(CSSPropertyFontSize); } } } static void diffTextDecorations(MutableStylePropertySet* style, CSSPropertyID propertID, CSSValue* refTextDecoration) { RefPtrWillBeRawPtr<CSSValue> textDecoration = style->getPropertyCSSValue(propertID); if (!textDecoration || !textDecoration->isValueList() || !refTextDecoration || !refTextDecoration->isValueList()) return; RefPtrWillBeRawPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy(); CSSValueList* valuesInRefTextDecoration = toCSSValueList(refTextDecoration); for (size_t i = 0; i < valuesInRefTextDecoration->length(); i++) newTextDecoration->removeAll(valuesInRefTextDecoration->item(i)); setTextDecorationProperty(style, newTextDecoration.get(), propertID); } static bool fontWeightIsBold(CSSValue* fontWeight) { if (!fontWeight->isPrimitiveValue()) return false; // Because b tag can only bold text, there are only two states in plain html: bold and not bold. // Collapse all other values to either one of these two states for editing purposes. switch (toCSSPrimitiveValue(fontWeight)->getValueID()) { case CSSValue100: case CSSValue200: case CSSValue300: case CSSValue400: case CSSValue500: case CSSValueNormal: return false; case CSSValueBold: case CSSValue600: case CSSValue700: case CSSValue800: case CSSValue900: return true; default: break; } ASSERT_NOT_REACHED(); // For CSSValueBolder and CSSValueLighter return false; } static bool fontWeightNeedsResolving(CSSValue* fontWeight) { if (!fontWeight->isPrimitiveValue()) return true; CSSValueID value = toCSSPrimitiveValue(fontWeight)->getValueID(); return value == CSSValueLighter || value == CSSValueBolder; } PassRefPtrWillBeRawPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, CSSStyleDeclaration* baseStyle) { ASSERT(styleWithRedundantProperties); ASSERT(baseStyle); RefPtrWillBeRawPtr<MutableStylePropertySet> result = styleWithRedundantProperties->mutableCopy(); result->removeEquivalentProperties(baseStyle); RefPtrWillBeRawPtr<CSSValue> baseTextDecorationsInEffect = baseStyle->getPropertyCSSValueInternal(CSSPropertyWebkitTextDecorationsInEffect); diffTextDecorations(result.get(), textDecorationPropertyForEditing(), baseTextDecorationsInEffect.get()); diffTextDecorations(result.get(), CSSPropertyWebkitTextDecorationsInEffect, baseTextDecorationsInEffect.get()); if (RefPtrWillBeRawPtr<CSSValue> baseFontWeight = baseStyle->getPropertyCSSValueInternal(CSSPropertyFontWeight)) { if (RefPtrWillBeRawPtr<CSSValue> fontWeight = result->getPropertyCSSValue(CSSPropertyFontWeight)) { if (!fontWeightNeedsResolving(fontWeight.get()) && !fontWeightNeedsResolving(baseFontWeight.get()) && (fontWeightIsBold(fontWeight.get()) == fontWeightIsBold(baseFontWeight.get()))) result->removeProperty(CSSPropertyFontWeight); } } if (baseStyle->getPropertyCSSValueInternal(CSSPropertyColor) && getFontColor(result.get()) == getFontColor(baseStyle)) result->removeProperty(CSSPropertyColor); if (baseStyle->getPropertyCSSValueInternal(CSSPropertyTextAlign) && textAlignResolvingStartAndEnd(result.get()) == textAlignResolvingStartAndEnd(baseStyle)) result->removeProperty(CSSPropertyTextAlign); if (baseStyle->getPropertyCSSValueInternal(CSSPropertyBackgroundColor) && getBackgroundColor(result.get()) == getBackgroundColor(baseStyle)) result->removeProperty(CSSPropertyBackgroundColor); return result.release(); } CSSValueID getIdentifierValue(StylePropertySet* style, CSSPropertyID propertyID) { if (!style) return CSSValueInvalid; RefPtrWillBeRawPtr<CSSValue> value = style->getPropertyCSSValue(propertyID); if (!value || !value->isPrimitiveValue()) return CSSValueInvalid; return toCSSPrimitiveValue(value.get())->getValueID(); } CSSValueID getIdentifierValue(CSSStyleDeclaration* style, CSSPropertyID propertyID) { if (!style) return CSSValueInvalid; RefPtrWillBeRawPtr<CSSValue> value = style->getPropertyCSSValueInternal(propertyID); if (!value || !value->isPrimitiveValue()) return CSSValueInvalid; return toCSSPrimitiveValue(value.get())->getValueID(); } int legacyFontSizeFromCSSValue(Document* document, CSSPrimitiveValue* value, bool isMonospaceFont, LegacyFontSizeMode mode) { CSSPrimitiveValue::LengthUnitType lengthType; if (CSSPrimitiveValue::unitTypeToLengthUnitType(value->typeWithCalcResolved(), lengthType) && lengthType == CSSPrimitiveValue::UnitTypePixels) { double conversion = CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(value->typeWithCalcResolved()); int pixelFontSize = clampTo<int>(value->getDoubleValue() * conversion); int legacyFontSize = FontSize::legacyFontSize(document, pixelFontSize, isMonospaceFont); // Use legacy font size only if pixel value matches exactly to that of legacy font size. if (mode == AlwaysUseLegacyFontSize || FontSize::fontSizeForKeyword(document, legacyFontSize, isMonospaceFont) == pixelFontSize) return legacyFontSize; return 0; } if (CSSValueXSmall <= value->getValueID() && value->getValueID() <= CSSValueWebkitXxxLarge) return value->getValueID() - CSSValueXSmall + 1; return 0; } bool isTransparentColorValue(CSSValue* cssValue) { if (!cssValue) return true; if (cssValue->isColorValue()) return !toCSSColorValue(cssValue)->value().alpha(); if (!cssValue->isPrimitiveValue()) return false; CSSPrimitiveValue* value = toCSSPrimitiveValue(cssValue); return value->getValueID() == CSSValueTransparent; } bool hasTransparentBackgroundColor(CSSStyleDeclaration* style) { RefPtrWillBeRawPtr<CSSValue> cssValue = style->getPropertyCSSValueInternal(CSSPropertyBackgroundColor); return isTransparentColorValue(cssValue.get()); } bool hasTransparentBackgroundColor(StylePropertySet* style) { RefPtrWillBeRawPtr<CSSValue> cssValue = style->getPropertyCSSValue(CSSPropertyBackgroundColor); return isTransparentColorValue(cssValue.get()); } PassRefPtrWillBeRawPtr<CSSValue> backgroundColorValueInEffect(Node* node) { for (Node* ancestor = node; ancestor; ancestor = ancestor->parentNode()) { RefPtrWillBeRawPtr<CSSComputedStyleDeclaration> ancestorStyle = CSSComputedStyleDeclaration::create(ancestor); if (!hasTransparentBackgroundColor(ancestorStyle.get())) return ancestorStyle->getPropertyCSSValue(CSSPropertyBackgroundColor); } return nullptr; } }
43.688581
217
0.753234
[ "vector" ]
e734fb95562a57f751726797157893514a87e0f2
24,053
cc
C++
src/lib/dns/name.cc
mcr/kea
7fbbfde2a0742a3d579d51ec94fc9b91687fb901
[ "Apache-2.0" ]
1
2019-08-10T21:52:58.000Z
2019-08-10T21:52:58.000Z
src/lib/dns/name.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
null
null
null
src/lib/dns/name.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2009-2018 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <cctype> #include <cassert> #include <iterator> #include <functional> #include <vector> #include <iostream> #include <algorithm> #include <util/buffer.h> #include <dns/exceptions.h> #include <dns/name.h> #include <dns/name_internal.h> #include <dns/messagerenderer.h> #include <dns/labelsequence.h> using namespace std; using namespace isc::util; using isc::dns::NameComparisonResult; using namespace isc::dns::name::internal; namespace isc { namespace dns { namespace { /// /// These are shortcut arrays for efficient character conversion. /// digitvalue converts a digit character to the corresponding integer. /// maptolower convert uppercase alphabets to their lowercase counterparts. /// We once used a helper non-local static object to avoid hardcoding the /// array members, but we then realized it's susceptible to static /// initialization order fiasco: Since these constants are used in a Name /// constructor, a non-local static Name object defined in another translation /// unit than this file may not be initialized correctly. /// There are several ways to address this issue, but in this specific case /// we chose the naive but simple hardcoding approach. /// /// These definitions are derived from BIND 9's libdns module. /// Note: we could use the standard tolower() function instead of the /// maptolower array, but a benchmark indicated that the private array could /// improve the performance of message rendering (which internally uses the /// array heavily) about 27%. Since we want to achieve very good performance /// for message rendering in some cases, we'll keep using it. const signed char digitvalue[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 16 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 32 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 48 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 64 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 80 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 96 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 112 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 128 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 256 }; } namespace name { namespace internal { const uint8_t maptolower[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, // ..., 'A' - 'G' 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, // 'H' - 'O' 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, // 'P' - 'W' 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, // 'X' - 'Z', ... 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; } // end of internal } // end of name namespace { /// /// Textual name parser states. /// typedef enum { ft_init = 0, // begin of the name ft_start, // begin of a label ft_ordinary, // parsing an ordinary label ft_initialescape, // just found '\' ft_escape, // begin of handling a '\'-escaped sequence ft_escdecimal // parsing a '\DDD' octet. } ft_state; // The parser of name from a string. It is a template, because // some parameters are used with two different types, while others // are private type aliases. template<class Iterator, class Offsets, class Data> void stringParse(Iterator s, Iterator send, bool downcase, Offsets& offsets, Data& ndata) { const Iterator orig_s(s); // // Initialize things to make the compiler happy; they're not required. // unsigned int digits = 0; unsigned int value = 0; unsigned int count = 0; // // Set up the state machine. // bool done = false; bool is_root = false; const bool empty = s == send; ft_state state = ft_init; // Prepare the output buffers. offsets.reserve(Name::MAX_LABELS); offsets.push_back(0); ndata.reserve(Name::MAX_WIRE); // should we refactor this code using, e.g, the state pattern? Probably // not at this point, as this is based on proved code (derived from BIND9) // and it's less likely that we'll have more variations in the domain name // syntax. If this ever happens next time, we should consider refactor // the code, rather than adding more states and cases below. while (ndata.size() < Name::MAX_WIRE && s != send && !done) { unsigned char c = *s++; switch (state) { case ft_init: // // Is this the root name? // if (c == '.') { if (s != send) { isc_throw(EmptyLabel, "non terminating empty label in " << string(orig_s, send)); } is_root = true; } else if (c == '@' && s == send) { // handle a single '@' as the root name. is_root = true; } if (is_root) { ndata.push_back(0); done = true; break; } // FALLTHROUGH case ft_start: ndata.push_back(0); // placeholder for the label length field count = 0; if (c == '\\') { state = ft_initialescape; break; } state = ft_ordinary; assert(ndata.size() < Name::MAX_WIRE); // FALLTHROUGH case ft_ordinary: if (c == '.') { if (count == 0) { isc_throw(EmptyLabel, "duplicate period in " << string(orig_s, send)); } ndata.at(offsets.back()) = count; offsets.push_back(ndata.size()); if (s == send) { ndata.push_back(0); done = true; } state = ft_start; } else if (c == '\\') { state = ft_escape; } else { if (++count > Name::MAX_LABELLEN) { isc_throw(TooLongLabel, "label is too long in " << string(orig_s, send)); } ndata.push_back(downcase ? maptolower[c] : c); } break; case ft_initialescape: if (c == '[') { // This looks like a bitstring label, which was deprecated. // Intentionally drop it. isc_throw(BadLabelType, "invalid label type in " << string(orig_s, send)); } // FALLTHROUGH case ft_escape: if (!isdigit(c & 0xff)) { if (++count > Name::MAX_LABELLEN) { isc_throw(TooLongLabel, "label is too long in " << string(orig_s, send)); } ndata.push_back(downcase ? maptolower[c] : c); state = ft_ordinary; break; } digits = 0; value = 0; state = ft_escdecimal; // FALLTHROUGH case ft_escdecimal: if (!isdigit(c & 0xff)) { isc_throw(BadEscape, "mixture of escaped digit and non-digit in " << string(orig_s, send)); } value *= 10; value += digitvalue[c]; digits++; if (digits == 3) { if (value > 255) { isc_throw(BadEscape, "escaped decimal is too large in " << string(orig_s, send)); } if (++count > Name::MAX_LABELLEN) { isc_throw(TooLongLabel, "label is too long in " << string(orig_s, send)); } ndata.push_back(downcase ? maptolower[value] : value); state = ft_ordinary; } break; default: // impossible case assert(false); } } if (!done) { // no trailing '.' was found. if (ndata.size() == Name::MAX_WIRE) { isc_throw(TooLongName, "name is too long for termination in " << string(orig_s, send)); } assert(s == send); if (state != ft_ordinary) { isc_throw(IncompleteName, "incomplete textual name in " << (empty ? "<empty>" : string(orig_s, send))); } if (state == ft_ordinary) { assert(count != 0); ndata.at(offsets.back()) = count; offsets.push_back(ndata.size()); // add a trailing \0 ndata.push_back('\0'); } } } } Name::Name(const std::string &namestring, bool downcase) { // Prepare inputs for the parser const std::string::const_iterator s = namestring.begin(); const std::string::const_iterator send = namestring.end(); // Prepare outputs NameOffsets offsets; NameString ndata; // To the parsing stringParse(s, send, downcase, offsets, ndata); // And get the output labelcount_ = offsets.size(); assert(labelcount_ > 0 && labelcount_ <= Name::MAX_LABELS); ndata_.assign(ndata.data(), ndata.size()); length_ = ndata_.size(); offsets_.assign(offsets.begin(), offsets.end()); } Name::Name(const char* namedata, size_t data_len, const Name* origin, bool downcase) { // Check validity of data if (namedata == NULL || data_len == 0) { isc_throw(isc::InvalidParameter, "No data provided to Name constructor"); } // If the last character is not a dot, it is a relative to origin. // It is safe to check now, we know there's at least one character. const bool absolute = (namedata[data_len - 1] == '.'); // If we are not absolute, we need the origin to complete the name. if (!absolute && origin == NULL) { isc_throw(MissingNameOrigin, "No origin available and name is relative"); } // Prepare inputs for the parser const char* end = namedata + data_len; // Prepare outputs NameOffsets offsets; NameString ndata; // Do the actual parsing stringParse(namedata, end, downcase, offsets, ndata); // Get the output labelcount_ = offsets.size(); assert(labelcount_ > 0 && labelcount_ <= Name::MAX_LABELS); ndata_.assign(ndata.data(), ndata.size()); length_ = ndata_.size(); offsets_.assign(offsets.begin(), offsets.end()); if (!absolute) { // Now, extend the data with the ones from origin. But eat the // last label (the empty one). // Drop the last character of the data (the \0) and append a copy of // the origin's data ndata_.erase(ndata_.end() - 1); ndata_.append(origin->ndata_); // Do a similar thing with offsets. However, we need to move them // so they point after the prefix we parsed before. size_t offset = offsets_.back(); offsets_.pop_back(); size_t offset_count = offsets_.size(); offsets_.insert(offsets_.end(), origin->offsets_.begin(), origin->offsets_.end()); for (NameOffsets::iterator it(offsets_.begin() + offset_count); it != offsets_.end(); ++it) { *it += offset; } // Adjust sizes. length_ = ndata_.size(); labelcount_ = offsets_.size(); // And check the sizes are OK. if (labelcount_ > Name::MAX_LABELS || length_ > Name::MAX_WIRE) { isc_throw(TooLongName, "Combined name is too long"); } } } namespace { /// /// Wire-format name parser states. /// typedef enum { fw_start = 0, // beginning of a label fw_ordinary, // inside an ordinary (non compressed) label fw_newcurrent // beginning of a compression pointer } fw_state; } Name::Name(InputBuffer& buffer, bool downcase) { NameOffsets offsets; offsets.reserve(Name::MAX_LABELS); /* * Initialize things to make the compiler happy; they're not required. */ unsigned int n = 0; // // Set up. // bool done = false; unsigned int nused = 0; bool seen_pointer = false; fw_state state = fw_start; unsigned int cused = 0; // Bytes of compressed name data used unsigned int current = buffer.getPosition(); unsigned int pos_begin = current; unsigned int biggest_pointer = current; // Make the compiler happy; this is not required. // XXX: bad style in that we initialize it with a dummy value and define // it far from where it's used. But alternatives seemed even worse. unsigned int new_current = 0; // // Note: The following code is not optimized for speed, but // rather for correctness. Speed will be addressed in the future. // while (current < buffer.getLength() && !done) { unsigned int c = buffer.readUint8(); current++; if (!seen_pointer) { cused++; } switch (state) { case fw_start: if (c <= MAX_LABELLEN) { offsets.push_back(nused); if (nused + c + 1 > Name::MAX_WIRE) { isc_throw(DNSMessageFORMERR, "wire name is too long: " << nused + c + 1 << " bytes"); } nused += c + 1; ndata_.push_back(c); if (c == 0) { done = true; } n = c; state = fw_ordinary; } else if ((c & COMPRESS_POINTER_MARK8) == COMPRESS_POINTER_MARK8) { // // Ordinary 14-bit pointer. // new_current = c & ~COMPRESS_POINTER_MARK8; n = 1; state = fw_newcurrent; } else { // this case includes local compression pointer, which hasn't // been standardized. isc_throw(DNSMessageFORMERR, "unknown label character: " << c); } break; case fw_ordinary: if (downcase) { c = maptolower[c]; } ndata_.push_back(c); if (--n == 0) { state = fw_start; } break; case fw_newcurrent: new_current *= 256; new_current += c; if (--n != 0) { break; } if (new_current >= biggest_pointer) { isc_throw(DNSMessageFORMERR, "bad compression pointer (out of range): " << new_current); } biggest_pointer = new_current; current = new_current; buffer.setPosition(current); seen_pointer = true; state = fw_start; break; default: assert(false); } } if (!done) { isc_throw(DNSMessageFORMERR, "incomplete wire-format name"); } labelcount_ = offsets.size(); length_ = nused; offsets_.assign(offsets.begin(), offsets.end()); buffer.setPosition(pos_begin + cused); } void Name::toWire(OutputBuffer& buffer) const { buffer.writeData(ndata_.data(), ndata_.size()); } void Name::toWire(AbstractMessageRenderer& renderer) const { renderer.writeName(*this); } std::string Name::toText(bool omit_final_dot) const { LabelSequence ls(*this); return (ls.toText(omit_final_dot)); } std::string Name::toRawText(bool omit_final_dot) const { LabelSequence ls(*this); return (ls.toRawText(omit_final_dot)); } NameComparisonResult Name::compare(const Name& other) const { const LabelSequence ls1(*this); const LabelSequence ls2(other); return (ls1.compare(ls2)); } bool Name::equals(const Name& other) const { if (length_ != other.length_ || labelcount_ != other.labelcount_) { return (false); } for (unsigned int l = labelcount_, pos = 0; l > 0; --l) { uint8_t count = ndata_[pos]; if (count != other.ndata_[pos]) { return (false); } ++pos; while (count-- > 0) { uint8_t label1 = ndata_[pos]; uint8_t label2 = other.ndata_[pos]; if (maptolower[label1] != maptolower[label2]) { return (false); } ++pos; } } return (true); } bool Name::leq(const Name& other) const { return (compare(other).getOrder() <= 0); } bool Name::geq(const Name& other) const { return (compare(other).getOrder() >= 0); } bool Name::lthan(const Name& other) const { return (compare(other).getOrder() < 0); } bool Name::gthan(const Name& other) const { return (compare(other).getOrder() > 0); } bool Name::isWildcard() const { return (length_ >= 2 && ndata_[0] == 1 && ndata_[1] == '*'); } Name Name::concatenate(const Name& suffix) const { assert(length_ > 0 && suffix.length_ > 0); assert(labelcount_ > 0 && suffix.labelcount_ > 0); unsigned int length = length_ + suffix.length_ - 1; if (length > Name::MAX_WIRE) { isc_throw(TooLongName, "names are too long to concatenate"); } Name retname; retname.ndata_.reserve(length); retname.ndata_.assign(ndata_, 0, length_ - 1); retname.ndata_.insert(retname.ndata_.end(), suffix.ndata_.begin(), suffix.ndata_.end()); assert(retname.ndata_.size() == length); retname.length_ = length; // // Setup the offsets vector. Copy the offsets of this (prefix) name, // excluding that for the trailing dot, and append the offsets of the // suffix name with the additional offset of the length of the prefix. // unsigned int labels = labelcount_ + suffix.labelcount_ - 1; assert(labels <= Name::MAX_LABELS); retname.offsets_.reserve(labels); retname.offsets_.assign(&offsets_[0], &offsets_[0] + labelcount_ - 1); transform(suffix.offsets_.begin(), suffix.offsets_.end(), back_inserter(retname.offsets_), bind2nd(plus<char>(), length_ - 1)); assert(retname.offsets_.size() == labels); retname.labelcount_ = labels; return (retname); } Name Name::reverse() const { Name retname; // // Set up offsets: The size of the string and number of labels will // be the same in as in the original. // retname.offsets_.reserve(labelcount_); retname.ndata_.reserve(length_); // Copy the original name, label by label, from tail to head. NameOffsets::const_reverse_iterator rit0 = offsets_.rbegin(); NameOffsets::const_reverse_iterator rit1 = rit0 + 1; NameString::const_iterator n0 = ndata_.begin(); retname.offsets_.push_back(0); while (rit1 != offsets_.rend()) { retname.ndata_.append(n0 + *rit1, n0 + *rit0); retname.offsets_.push_back(retname.ndata_.size()); ++rit0; ++rit1; } retname.ndata_.push_back(0); retname.labelcount_ = labelcount_; retname.length_ = length_; return (retname); } Name Name::split(const unsigned int first, const unsigned int n) const { if (n == 0 || n > labelcount_ || first > labelcount_ - n) { isc_throw(OutOfRange, "Name::split: invalid split range"); } Name retname; // If the specified range doesn't include the trailing dot, we need one // more label for that. unsigned int newlabels = (first + n == labelcount_) ? n : n + 1; // // Set up offsets: copy the corresponding range of the original offsets // with subtracting an offset of the prefix length. // retname.offsets_.reserve(newlabels); transform(offsets_.begin() + first, offsets_.begin() + first + newlabels, back_inserter(retname.offsets_), bind2nd(plus<char>(), -offsets_[first])); // // Set up the new name. At this point the tail of the new offsets specifies // the position of the trailing dot, which should be equal to the length of // the extracted portion excluding the dot. First copy that part from the // original name, and append the trailing dot explicitly. // retname.ndata_.reserve(retname.offsets_.back() + 1); retname.ndata_.assign(ndata_, offsets_[first], retname.offsets_.back()); retname.ndata_.push_back(0); retname.length_ = retname.ndata_.size(); retname.labelcount_ = retname.offsets_.size(); assert(retname.labelcount_ == newlabels); return (retname); } Name Name::split(const unsigned int level) const { if (level >= getLabelCount()) { isc_throw(OutOfRange, "invalid level for name split (" << level << ") for name " << *this); } return (split(level, getLabelCount() - level)); } Name& Name::downcase() { unsigned int nlen = length_; unsigned int labels = labelcount_; unsigned int pos = 0; while (labels > 0 && nlen > 0) { --labels; --nlen; // we assume a valid name, and do abort() if the assumption fails // rather than throwing an exception. unsigned int count = ndata_.at(pos++); assert(count <= MAX_LABELLEN); assert(nlen >= count); while (count > 0) { ndata_.at(pos) = maptolower[ndata_.at(pos)]; ++pos; --nlen; --count; } } return (*this); } std::ostream& operator<<(std::ostream& os, const Name& name) { os << name.toText(); return (os); } } }
33.176552
80
0.54962
[ "object", "vector", "transform" ]
e73987146fc97f7ea2c77e17e2f0b67a96618c13
1,379
hpp
C++
include/DeferredSpecialize.hpp
scribe-lang/scribe
28ee67cc5081aa3bdd0d4fc284c04738e3272687
[ "MIT" ]
13
2021-12-28T17:54:05.000Z
2022-03-19T16:13:03.000Z
include/DeferredSpecialize.hpp
scribe-lang/scribe
28ee67cc5081aa3bdd0d4fc284c04738e3272687
[ "MIT" ]
null
null
null
include/DeferredSpecialize.hpp
scribe-lang/scribe
28ee67cc5081aa3bdd0d4fc284c04738e3272687
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2022 Scribe Language Repositories 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. */ #ifndef DEFERRED_SPECIALIZE_HPP #define DEFERRED_SPECIALIZE_HPP #include "Parser/Stmts.hpp" namespace sc { struct DeferredSpecializeData { uint32_t id; // original struct id (just the type id) Type **loc; // update this type loc Vector<Type *> actualtypes; }; struct DeferredSpecializeDataInternal { uint32_t id; // original struct id (just the type id) Type **loc; // update this type location }; class DeferredSpecialize { Vector<DeferredSpecializeData> list; Vector<DeferredSpecializeDataInternal> listinternal; public: DeferredSpecialize(); inline void pushData(uint32_t id, Type **loc, const Vector<Type *> &actualtypes) { list.push_back({id, loc, actualtypes}); } inline void pushDataInternal(uint32_t id, Type **loc) { listinternal.push_back({id, loc}); } bool specialize(uint32_t id, Context &c, const ModuleLoc *loc); }; } // namespace sc #endif // DEFERRED_SPECIALIZE_HPP
27.039216
81
0.759246
[ "vector" ]
e73c5322bc06137f7bbc67b20e551e8838c1d05f
31,854
cc
C++
jni/sources/voice_engine/voe_network_impl.cc
guo19941204/c-jni
866a2bc3f1148824e1a5c270fdf452888cb06d2b
[ "MIT" ]
null
null
null
jni/sources/voice_engine/voe_network_impl.cc
guo19941204/c-jni
866a2bc3f1148824e1a5c270fdf452888cb06d2b
[ "MIT" ]
null
null
null
jni/sources/voice_engine/voe_network_impl.cc
guo19941204/c-jni
866a2bc3f1148824e1a5c270fdf452888cb06d2b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voe_network_impl.h" #include "channel.h" #include "critical_section_wrapper.h" #include "trace.h" #include "voe_errors.h" #include "voice_engine_impl.h" namespace webrtc { VoENetwork* VoENetwork::GetInterface(VoiceEngine* voiceEngine) { #ifndef WEBRTC_VOICE_ENGINE_NETWORK_API return NULL; #else if (NULL == voiceEngine) { return NULL; } VoiceEngineImpl* s = reinterpret_cast<VoiceEngineImpl*>(voiceEngine); s->AddRef(); return s; #endif } #ifdef WEBRTC_VOICE_ENGINE_NETWORK_API VoENetworkImpl::VoENetworkImpl(voe::SharedData* shared) : _shared(shared) { WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoENetworkImpl() - ctor"); } VoENetworkImpl::~VoENetworkImpl() { WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_shared->instance_id(), -1), "~VoENetworkImpl() - dtor"); } int VoENetworkImpl::RegisterExternalTransport(int channel, Transport& transport) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetExternalTransport(channel=%d, transport=0x%x)", channel, &transport); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetExternalTransport() failed to locate channel"); return -1; } return channelPtr->RegisterExternalTransport(transport); } int VoENetworkImpl::DeRegisterExternalTransport(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "DeRegisterExternalTransport(channel=%d)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "DeRegisterExternalTransport() failed to locate channel"); return -1; } return channelPtr->DeRegisterExternalTransport(); } int VoENetworkImpl::ReceivedRTPPacket(int channel, const void* data, unsigned int length) { WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_shared->instance_id(), -1), "ReceivedRTPPacket(channel=%d, length=%u)", channel, length); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if ((length < 12) || (length > 807)) { _shared->SetLastError(VE_INVALID_PACKET, kTraceError, "ReceivedRTPPacket() invalid packet length"); return -1; } if (NULL == data) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "ReceivedRTPPacket() invalid data vector"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "ReceivedRTPPacket() failed to locate channel"); return -1; } if (!channelPtr->ExternalTransport()) { _shared->SetLastError(VE_INVALID_OPERATION, kTraceError, "ReceivedRTPPacket() external transport is not enabled"); return -1; } return channelPtr->ReceivedRTPPacket((const WebRtc_Word8*) data, length); } int VoENetworkImpl::ReceivedRTCPPacket(int channel, const void* data, unsigned int length) { WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_shared->instance_id(), -1), "ReceivedRTCPPacket(channel=%d, length=%u)", channel, length); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (length < 4) { _shared->SetLastError(VE_INVALID_PACKET, kTraceError, "ReceivedRTCPPacket() invalid packet length"); return -1; } if (NULL == data) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "ReceivedRTCPPacket() invalid data vector"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "ReceivedRTCPPacket() failed to locate channel"); return -1; } if (!channelPtr->ExternalTransport()) { _shared->SetLastError(VE_INVALID_OPERATION, kTraceError, "ReceivedRTCPPacket() external transport is not enabled"); return -1; } return channelPtr->ReceivedRTCPPacket((const WebRtc_Word8*) data, length); } int VoENetworkImpl::GetSourceInfo(int channel, int& rtpPort, int& rtcpPort, char ipAddr[64]) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetSourceInfo(channel=%d, rtpPort=?, rtcpPort=?, ipAddr[]=?)", channel); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (NULL == ipAddr) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "GetSourceInfo() invalid IP-address buffer"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetSourceInfo() failed to locate channel"); return -1; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "GetSourceInfo() external transport is enabled"); return -1; } return channelPtr->GetSourceInfo(rtpPort, rtcpPort, ipAddr); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "GetSourceInfo() VoE is built for external transport"); return -1; #endif } int VoENetworkImpl::GetLocalIP(char ipAddr[64], bool ipv6) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetLocalIP(ipAddr[]=?, ipv6=%d)", ipv6); IPHONE_NOT_SUPPORTED(_shared->statistics()); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (NULL == ipAddr) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "GetLocalIP() invalid IP-address buffer"); return -1; } // Create a temporary socket module to ensure that this method can be // called also when no channels are created. WebRtc_UWord8 numSockThreads(1); UdpTransport* socketPtr = UdpTransport::Create( -1, numSockThreads); if (NULL == socketPtr) { _shared->SetLastError(VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceError, "GetLocalIP() failed to create socket module"); return -1; } // Use a buffer big enough for IPv6 addresses and initialize it with zeros. char localIPAddr[256] = {0}; if (ipv6) { char localIP[16]; if (socketPtr->LocalHostAddressIPV6(localIP) != 0) { _shared->SetLastError(VE_INVALID_IP_ADDRESS, kTraceError, "GetLocalIP() failed to retrieve local IP - 1"); UdpTransport::Destroy(socketPtr); return -1; } // Convert 128-bit address to character string (a:b:c:d:e:f:g:h) sprintf(localIPAddr, "%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x" "%.2x:%.2x%.2x", localIP[0], localIP[1], localIP[2], localIP[3], localIP[4], localIP[5], localIP[6], localIP[7], localIP[8], localIP[9], localIP[10], localIP[11], localIP[12], localIP[13], localIP[14], localIP[15]); } else { WebRtc_UWord32 localIP(0); // Read local IP (as 32-bit address) from the socket module if (socketPtr->LocalHostAddress(localIP) != 0) { _shared->SetLastError(VE_INVALID_IP_ADDRESS, kTraceError, "GetLocalIP() failed to retrieve local IP - 2"); UdpTransport::Destroy(socketPtr); return -1; } // Convert 32-bit address to character string (x.y.z.w) sprintf(localIPAddr, "%d.%d.%d.%d", (int) ((localIP >> 24) & 0x0ff), (int) ((localIP >> 16) & 0x0ff), (int) ((localIP >> 8) & 0x0ff), (int) (localIP & 0x0ff)); } strcpy(ipAddr, localIPAddr); UdpTransport::Destroy(socketPtr); WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetLocalIP() => ipAddr=%s", ipAddr); return 0; #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "GetLocalIP() VoE is built for external transport"); return -1; #endif } int VoENetworkImpl::EnableIPv6(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "EnableIPv6(channel=%d)", channel); ANDROID_NOT_SUPPORTED(_shared->statistics()); IPHONE_NOT_SUPPORTED(_shared->statistics()); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "EnableIPv6() failed to locate channel"); return -1; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "EnableIPv6() external transport is enabled"); return -1; } return channelPtr->EnableIPv6(); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "EnableIPv6() VoE is built for external transport"); return -1; #endif } bool VoENetworkImpl::IPv6IsEnabled(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "IPv6IsEnabled(channel=%d)", channel); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return false; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "IPv6IsEnabled() failed to locate channel"); return false; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "IPv6IsEnabled() external transport is enabled"); return false; } return channelPtr->IPv6IsEnabled(); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "IPv6IsEnabled() VoE is built for external transport"); return false; #endif } int VoENetworkImpl::SetSourceFilter(int channel, int rtpPort, int rtcpPort, const char ipAddr[64]) { (ipAddr == NULL) ? WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetSourceFilter(channel=%d, rtpPort=%d," " rtcpPort=%d)", channel, rtpPort, rtcpPort) : WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetSourceFilter(channel=%d, rtpPort=%d," " rtcpPort=%d, ipAddr=%s)", channel, rtpPort, rtcpPort, ipAddr); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if ((rtpPort < 0) || (rtpPort > 65535)) { _shared->SetLastError(VE_INVALID_PORT_NMBR, kTraceError, "SetSourceFilter() invalid RTP port"); return -1; } if ((rtcpPort < 0) || (rtcpPort > 65535)) { _shared->SetLastError(VE_INVALID_PORT_NMBR, kTraceError, "SetSourceFilter() invalid RTCP port"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetSourceFilter() failed to locate channel"); return -1; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "SetSourceFilter() external transport is enabled"); return -1; } return channelPtr->SetSourceFilter(rtpPort, rtcpPort, ipAddr); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "SetSourceFilter() VoE is built for external transport"); return -1; #endif } int VoENetworkImpl::GetSourceFilter(int channel, int& rtpPort, int& rtcpPort, char ipAddr[64]) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetSourceFilter(channel=%d, rtpPort=?, rtcpPort=?, " "ipAddr[]=?)", channel); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (NULL == ipAddr) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "GetSourceFilter() invalid IP-address buffer"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetSourceFilter() failed to locate channel"); return -1; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "GetSourceFilter() external transport is enabled"); return -1; } return channelPtr->GetSourceFilter(rtpPort, rtcpPort, ipAddr); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "GetSourceFilter() VoE is built for external transport"); return -1; #endif } int VoENetworkImpl::SetSendTOS(int channel, int DSCP, int priority, bool useSetSockopt) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetSendTOS(channel=%d, DSCP=%d, useSetSockopt=%d)", channel, DSCP, useSetSockopt); #if !defined(_WIN32) && !defined(WEBRTC_LINUX) && !defined(WEBRTC_MAC) _shared->SetLastError(VE_FUNC_NOT_SUPPORTED, kTraceWarning, "SetSendTOS() is not supported on this platform"); return -1; #endif #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if ((DSCP < 0) || (DSCP > 63)) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetSendTOS() Invalid DSCP value"); return -1; } #if defined(_WIN32) || defined(WEBRTC_LINUX) if ((priority < -1) || (priority > 7)) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetSendTOS() Invalid priority value"); return -1; } #else if (-1 != priority) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetSendTOS() priority not supported"); return -1; } #endif #if defined(_WIN32) if ((priority >= 0) && useSetSockopt) { // On Windows, priority and useSetSockopt cannot be combined _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetSendTOS() priority and useSetSockopt conflict"); return -1; } #endif voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetSendTOS() failed to locate channel"); return -1; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "SetSendTOS() external transport is enabled"); return -1; } #if defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) useSetSockopt = true; WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), " force useSetSockopt=true since there is no alternative" " implementation"); #endif return channelPtr->SetSendTOS(DSCP, priority, useSetSockopt); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "SetSendTOS() VoE is built for external transport"); return -1; #endif } int VoENetworkImpl::GetSendTOS(int channel, int& DSCP, int& priority, bool& useSetSockopt) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetSendTOS(channel=%d)", channel); #if !defined(_WIN32) && !defined(WEBRTC_LINUX) && !defined(WEBRTC_MAC) _shared->SetLastError(VE_FUNC_NOT_SUPPORTED, kTraceWarning, "GetSendTOS() is not supported on this platform"); return -1; #endif #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetSendTOS() failed to locate channel"); return -1; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "GetSendTOS() external transport is enabled"); return -1; } return channelPtr->GetSendTOS(DSCP, priority, useSetSockopt); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "GetSendTOS() VoE is built for external transport"); return -1; #endif } int VoENetworkImpl::SetSendGQoS(int channel, bool enable, int serviceType, int overrideDSCP) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetSendGQOS(channel=%d, enable=%d, serviceType=%d," " overrideDSCP=%d)", channel, (int) enable, serviceType, overrideDSCP); ANDROID_NOT_SUPPORTED(_shared->statistics()); IPHONE_NOT_SUPPORTED(_shared->statistics()); #if !defined(_WIN32) _shared->SetLastError(VE_FUNC_NOT_SUPPORTED, kTraceWarning, "SetSendGQOS() is not supported on this platform"); return -1; #elif !defined(WEBRTC_EXTERNAL_TRANSPORT) if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetSendGQOS() failed to locate channel"); return -1; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "SetSendGQOS() external transport is enabled"); return -1; } return channelPtr->SetSendGQoS(enable, serviceType, overrideDSCP); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "SetSendGQOS() VoE is built for external transport"); return -1; #endif } int VoENetworkImpl::GetSendGQoS(int channel, bool& enabled, int& serviceType, int& overrideDSCP) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetSendGQOS(channel=%d)", channel); ANDROID_NOT_SUPPORTED(_shared->statistics()); IPHONE_NOT_SUPPORTED(_shared->statistics()); #if !defined(_WIN32) _shared->SetLastError(VE_FUNC_NOT_SUPPORTED, kTraceWarning, "GetSendGQOS() is not supported on this platform"); return -1; #elif !defined(WEBRTC_EXTERNAL_TRANSPORT) if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetSendGQOS() failed to locate channel"); return -1; } if (channelPtr->ExternalTransport()) { _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceError, "GetSendGQOS() external transport is enabled"); return -1; } return channelPtr->GetSendGQoS(enabled, serviceType, overrideDSCP); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "GetSendGQOS() VoE is built for external transport"); return -1; #endif } int VoENetworkImpl::SetPacketTimeoutNotification(int channel, bool enable, int timeoutSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetPacketTimeoutNotification(channel=%d, enable=%d, " "timeoutSeconds=%d)", channel, (int) enable, timeoutSeconds); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (enable && ((timeoutSeconds < kVoiceEngineMinPacketTimeoutSec) || (timeoutSeconds > kVoiceEngineMaxPacketTimeoutSec))) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetPacketTimeoutNotification() invalid timeout size"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetPacketTimeoutNotification() failed to locate channel"); return -1; } return channelPtr->SetPacketTimeoutNotification(enable, timeoutSeconds); } int VoENetworkImpl::GetPacketTimeoutNotification(int channel, bool& enabled, int& timeoutSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetPacketTimeoutNotification(channel=%d, enabled=?," " timeoutSeconds=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetPacketTimeoutNotification() failed to locate channel"); return -1; } return channelPtr->GetPacketTimeoutNotification(enabled, timeoutSeconds); } int VoENetworkImpl::RegisterDeadOrAliveObserver(int channel, VoEConnectionObserver& observer) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "RegisterDeadOrAliveObserver(channel=%d, observer=0x%x)", channel, &observer); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "RegisterDeadOrAliveObserver() failed to locate channel"); return -1; } return channelPtr->RegisterDeadOrAliveObserver(observer); } int VoENetworkImpl::DeRegisterDeadOrAliveObserver(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "DeRegisterDeadOrAliveObserver(channel=%d)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "DeRegisterDeadOrAliveObserver() failed to locate channel"); return -1; } return channelPtr->DeRegisterDeadOrAliveObserver(); } int VoENetworkImpl::SetPeriodicDeadOrAliveStatus(int channel, bool enable, int sampleTimeSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetPeriodicDeadOrAliveStatus(channel=%d, enable=%d," " sampleTimeSeconds=%d)", channel, enable, sampleTimeSeconds); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (enable && ((sampleTimeSeconds < kVoiceEngineMinSampleTimeSec) || (sampleTimeSeconds > kVoiceEngineMaxSampleTimeSec))) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetPeriodicDeadOrAliveStatus() invalid sample time"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetPeriodicDeadOrAliveStatus() failed to locate channel"); return -1; } return channelPtr->SetPeriodicDeadOrAliveStatus(enable, sampleTimeSeconds); } int VoENetworkImpl::GetPeriodicDeadOrAliveStatus(int channel, bool& enabled, int& sampleTimeSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetPeriodicDeadOrAliveStatus(channel=%d, enabled=?," " sampleTimeSeconds=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetPeriodicDeadOrAliveStatus() failed to locate channel"); return -1; } return channelPtr->GetPeriodicDeadOrAliveStatus(enabled, sampleTimeSeconds); } int VoENetworkImpl::SendUDPPacket(int channel, const void* data, unsigned int length, int& transmittedBytes, bool useRtcpSocket) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SendUDPPacket(channel=%d, data=0x%x, length=%u, useRTCP=%d)", channel, data, length, useRtcpSocket); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (NULL == data) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SendUDPPacket() invalid data buffer"); return -1; } if (0 == length) { _shared->SetLastError(VE_INVALID_PACKET, kTraceError, "SendUDPPacket() invalid packet size"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SendUDPPacket() failed to locate channel"); return -1; } return channelPtr->SendUDPPacket(data, length, transmittedBytes, useRtcpSocket); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "SendUDPPacket() VoE is built for external transport"); return -1; #endif } #endif // WEBRTC_VOICE_ENGINE_NETWORK_API } // namespace webrtc
36.487973
81
0.597382
[ "vector" ]
e73ddd303458e956fbce09f81c000d3b2c9b928e
3,776
hpp
C++
oink/src/oink.hpp
trolando/oink-experiments
a58937b78fd0857a26b8ec0e985552e672405862
[ "Apache-2.0" ]
1
2019-03-04T14:24:17.000Z
2019-03-04T14:24:17.000Z
oink/src/oink.hpp
trolando/oink-experiments
a58937b78fd0857a26b8ec0e985552e672405862
[ "Apache-2.0" ]
null
null
null
oink/src/oink.hpp
trolando/oink-experiments
a58937b78fd0857a26b8ec0e985552e672405862
[ "Apache-2.0" ]
null
null
null
#ifndef OINK_HPP #define OINK_HPP #include <iostream> #include <vector> #include "game.hpp" namespace pg { class Solver; class Oink { public: Oink(Game &game, std::ostream &out=std::cout) : game(&game), logger(out) { } ~Oink() {} /** * After configuring Oink, use run() to run the solver. */ void run(); /** * Instruct Oink to use the given solver. */ void setSolver(int solverid); void setSolver(std::string label); /** * Instruct Oink to inflate as a preprocessing step. */ void setInflate() { inflate = true; renumber = false; compress = false; } /** * Instruct Oink to compress as a preprocessing step. */ void setCompress() { inflate = false; compress = true; renumber = false; } /** * Instruct Oink to renumber as a preprocessing step. */ void setRenumber() { inflate = false; compress = false; renumber = true; } /** * Instruct Oink whether to remove self-loops as a preprocessing step. (Default true) */ void setRemoveLoops(bool val) { removeLoops = val; } /** * Instruct Oink whether to solve winner-controlled winning cycles as a preprocessing step. (Default true) */ void setRemoveWCWC(bool val) { removeWCWC = val; } /** * Instruct Oink whether to solve single parity games. (Default true) */ void setSolveSingle(bool val) { solveSingle = val; } /** * Instruct Oink whether solve per bottom SCC. (Default false) */ void setBottomSCC(bool val) { bottomSCC = val; } /** * Set the number of workers for parallel solvers (psi and zielonka). * -1 for sequential code, 0 for autodetect. */ void setWorkers(int count) { workers = count; } /** * Set verbosity level (0 = normal, 1 = trace, 2 = debug) */ void setTrace(int level) { trace = level; } /** * Solve node <node> as won by <winner> with strategy <strategy>. * (Set <strategy> to -1 for no strategy. */ void solve(int node, int winner, int strategy); /** * After marking nodes as solved using solve(), use flush to attract to the solved dominion. */ void flush(); protected: /** * Solve winner-controlled winning cycles. */ int solveTrivialCycles(void); /** * Resolve self-loops. */ int solveSelfloops(void); /** * During flush(), attract to solved node <i>. */ void attractDominion(int i); Game *game; // game being solved std::ostream &logger; // logger for trace/debug messages int solver = -1; // which solver to use int workers = -1; // number of workers, 0 = autodetect, -1 = use non parallel int trace = 0; // verbosity (0 for normal, 1 for trace, 2 for debug) bool inflate = false; // inflate the game before solving bool compress = false; // compress the game before solving bool renumber = false; // renumber the game before solving (removes gaps) bool removeLoops = true; // resolve self-loops before solving bool removeWCWC = true; // solve winner-controlled winning cycles before solving bool solveSingle = true; // solve games with only 1 parity bool bottomSCC = false; // solve per bottom SCC std::vector<int> todo; // internal queue for solved nodes for flushing int *outcount; // number of unsolved outgoing edges per node (for fast attraction) int *outa; // index array for outgoing edges int *ina; // index array for incoming edges int *outs; // all outgoing edges int *ins; // all incoming edges friend class pg::Solver; // to allow access to edges }; } #endif
29.5
110
0.610434
[ "vector" ]
e73fdee3ee6d5af98e3bcda394ddba4b126481fd
35,164
cpp
C++
wxWidgets/samples/access/accesstest.cpp
VonaInc/lokl
83fbaa9c73d3112490edd042da812ceeb3cc9e53
[ "MIT" ]
86
2015-08-06T11:30:01.000Z
2022-02-28T04:50:22.000Z
wxWidgets/samples/access/accesstest.cpp
VonaInc/lokl
83fbaa9c73d3112490edd042da812ceeb3cc9e53
[ "MIT" ]
6
2016-01-04T19:36:22.000Z
2021-08-08T02:43:48.000Z
wxWidgets/samples/access/accesstest.cpp
VonaInc/lokl
83fbaa9c73d3112490edd042da812ceeb3cc9e53
[ "MIT" ]
22
2015-11-04T04:04:54.000Z
2022-02-28T04:50:24.000Z
///////////////////////////////////////////////////////////////////////////// // Name: accesstest.cpp // Purpose: wxWidgets accessibility sample // Author: Julian Smart // Modified by: // Created: 2002-02-12 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif #if wxUSE_ACCESSIBILITY #include "wx/access.h" #endif // wxUSE_ACCESSIBILITY #include "wx/splitter.h" #include "wx/cshelp.h" #ifdef __WXMSW__ #include "windows.h" #include <ole2.h> #include <oleauto.h> #if wxUSE_ACCESSIBILITY #include <oleacc.h> #endif // wxUSE_ACCESSIBILITY #include "wx/msw/ole/oleutils.h" #include "wx/msw/winundef.h" #ifndef OBJID_CLIENT #define OBJID_CLIENT 0xFFFFFFFC #endif #endif // ---------------------------------------------------------------------------- // resources // ---------------------------------------------------------------------------- // the application icon (under Windows it is in resources) #ifndef wxHAS_IMAGES_IN_RESOURCES #include "../sample.xpm" #endif // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- // Define a new application type, each program should derive a class from wxApp class MyApp : public wxApp { public: // override base class virtuals // ---------------------------- // this one is called on application startup and is a good place for the app // initialization (doing it here and not in the ctor allows to have an error // return: if OnInit() returns false, the application terminates) virtual bool OnInit() wxOVERRIDE; }; #if wxUSE_ACCESSIBILITY // Define a new frame type: this is going to be our main frame class MyFrame : public wxFrame { public: // ctor(s) MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size, long style = wxDEFAULT_FRAME_STYLE); // event handlers (these functions should _not_ be virtual) void OnQuit(wxCommandEvent& event); void OnQuery(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); // Log messages to the text control void Log(const wxString& text); // Recursively give information about an object void LogObject(int indent, IAccessible* obj); // Get info for a child (id > 0) or object (id == 0) void GetInfo(IAccessible* accessible, int id, wxString& name, wxString& role); private: wxTextCtrl* m_textCtrl; // any class wishing to process wxWidgets events must use this macro wxDECLARE_EVENT_TABLE(); }; // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // IDs for the controls and the menu commands enum { // menu items AccessTest_Quit = 1, // query the hierarchy AccessTest_Query, // it is important for the id corresponding to the "About" command to have // this standard value as otherwise it won't be handled properly under Mac // (where it is special and put into the "Apple" menu) AccessTest_About = wxID_ABOUT }; // ---------------------------------------------------------------------------- // event tables and other macros for wxWidgets // ---------------------------------------------------------------------------- // the event tables connect the wxWidgets events with the functions (event // handlers) which process them. It can be also done at run-time, but for the // simple menu events like this the static method is much simpler. wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(AccessTest_Quit, MyFrame::OnQuit) EVT_MENU(AccessTest_Query, MyFrame::OnQuery) EVT_MENU(AccessTest_About, MyFrame::OnAbout) wxEND_EVENT_TABLE() #endif // wxUSE_ACCESSIBILITY // Create a new application object: this macro will allow wxWidgets to create // the application object during program execution (it's better than using a // static object for many reasons) and also declares the accessor function // wxGetApp() which will return the reference of the right type (i.e. MyApp and // not wxApp) wxIMPLEMENT_APP(MyApp); // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // the application class // ---------------------------------------------------------------------------- // 'Main program' equivalent: the program execution "starts" here bool MyApp::OnInit() { if ( !wxApp::OnInit() ) return false; #if wxUSE_ACCESSIBILITY // Note: JAWS for Windows will only speak the context-sensitive // help if you use this help provider: // wxHelpProvider::Set(new wxHelpControllerHelpProvider(m_helpController)). // JAWS does not seem to be getting the help text from // the wxAccessible object. wxHelpProvider::Set(new wxSimpleHelpProvider()); // create the main application window MyFrame *frame = new MyFrame("AccessTest wxWidgets App", wxPoint(50, 50), wxSize(450, 340)); // and show it (the frames, unlike simple controls, are not shown when // created initially) frame->Show(true); // success: wxApp::OnRun() will be called which will enter the main message // loop and the application will run. If we returned false here, the // application would exit immediately. return true; #else wxMessageBox( "This sample has to be compiled with wxUSE_ACCESSIBILITY", "Building error", wxOK); return false; #endif // wxUSE_ACCESSIBILITY } #if wxUSE_ACCESSIBILITY class FrameAccessible: public wxWindowAccessible { public: FrameAccessible(wxWindow* win): wxWindowAccessible(win) {} // Gets the name of the specified object. virtual wxAccStatus GetName(int childId, wxString* name) wxOVERRIDE { if (childId == wxACC_SELF) { * name = "Julian's Frame"; return wxACC_OK; } else return wxACC_NOT_IMPLEMENTED; } }; class ScrolledWindowAccessible: public wxWindowAccessible { public: ScrolledWindowAccessible(wxWindow* win): wxWindowAccessible(win) {} // Gets the name of the specified object. virtual wxAccStatus GetName(int childId, wxString* name) wxOVERRIDE { if (childId == wxACC_SELF) { * name = "My scrolled window"; return wxACC_OK; } else return wxACC_NOT_IMPLEMENTED; } }; class SplitterWindowAccessible: public wxWindowAccessible { public: SplitterWindowAccessible(wxWindow* win): wxWindowAccessible(win) {} // Gets the name of the specified object. virtual wxAccStatus GetName(int childId, wxString* name) wxOVERRIDE; // Can return either a child object, or an integer // representing the child element, starting from 1. virtual wxAccStatus HitTest(const wxPoint& pt, int* childId, wxAccessible** childObject) wxOVERRIDE; // Returns the rectangle for this object (id = 0) or a child element (id > 0). virtual wxAccStatus GetLocation(wxRect& rect, int elementId) wxOVERRIDE; // Navigates from fromId to toId/toObject. virtual wxAccStatus Navigate(wxNavDir navDir, int fromId, int* toId, wxAccessible** toObject) wxOVERRIDE; // Gets the number of children. virtual wxAccStatus GetChildCount(int* childCount) wxOVERRIDE; // Gets the specified child (starting from 1). // If *child is NULL and return value is wxACC_OK, // this means that the child is a simple element and // not an accessible object. virtual wxAccStatus GetChild(int childId, wxAccessible** child) wxOVERRIDE; // Gets the parent, or NULL. virtual wxAccStatus GetParent(wxAccessible** parent) wxOVERRIDE; // Performs the default action. childId is 0 (the action for this object) // or > 0 (the action for a child). // Return wxACC_NOT_SUPPORTED if there is no default action for this // window (e.g. an edit control). virtual wxAccStatus DoDefaultAction(int childId) wxOVERRIDE; // Gets the default action for this object (0) or > 0 (the action for a child). // Return wxACC_OK even if there is no action. actionName is the action, or the empty // string if there is no action. // The retrieved string describes the action that is performed on an object, // not what the object does as a result. For example, a toolbar button that prints // a document has a default action of "Press" rather than "Prints the current document." virtual wxAccStatus GetDefaultAction(int childId, wxString* actionName) wxOVERRIDE; // Returns the description for this object or a child. virtual wxAccStatus GetDescription(int childId, wxString* description) wxOVERRIDE; // Returns help text for this object or a child, similar to tooltip text. virtual wxAccStatus GetHelpText(int childId, wxString* helpText) wxOVERRIDE; // Returns the keyboard shortcut for this object or child. // Return e.g. ALT+K virtual wxAccStatus GetKeyboardShortcut(int childId, wxString* shortcut) wxOVERRIDE; // Returns a role constant. virtual wxAccStatus GetRole(int childId, wxAccRole* role) wxOVERRIDE; // Returns a state constant. virtual wxAccStatus GetState(int childId, long* state) wxOVERRIDE; // Returns a localized string representing the value for the object // or child. virtual wxAccStatus GetValue(int childId, wxString* strValue) wxOVERRIDE; // Selects the object or child. virtual wxAccStatus Select(int childId, wxAccSelectionFlags selectFlags) wxOVERRIDE; // Gets the window with the keyboard focus. // If childId is 0 and child is NULL, no object in // this subhierarchy has the focus. // If this object has the focus, child should be 'this'. virtual wxAccStatus GetFocus(int* childId, wxAccessible** child) wxOVERRIDE; // Gets a variant representing the selected children // of this object. // Acceptable values: // - a null variant (IsNull() returns true) // - a list variant (GetType() == "list") // - an integer representing the selected child element, // or 0 if this object is selected (GetType() == "long") // - a "void*" pointer to a wxAccessible child object virtual wxAccStatus GetSelections(wxVariant* selections) wxOVERRIDE; }; // ---------------------------------------------------------------------------- // main frame // ---------------------------------------------------------------------------- // frame constructor MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxFrame(NULL, wxID_ANY, title, pos, size, style) { m_textCtrl = NULL; SetAccessible(new FrameAccessible(this)); // set the frame icon SetIcon(wxICON(sample)); #if wxUSE_MENUS // create a menu bar wxMenu *menuFile = new wxMenu; // the "About" item should be in the help menu wxMenu *helpMenu = new wxMenu; helpMenu->Append(AccessTest_About, "&About", "Show about dialog"); menuFile->Append(AccessTest_Query, "Query", "Query the window hierarchy"); menuFile->AppendSeparator(); menuFile->Append(AccessTest_Quit, "E&xit\tAlt-X", "Quit this program"); // now append the freshly created menu to the menu bar... wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(menuFile, "&File"); menuBar->Append(helpMenu, "&Help"); // ... and attach this menu bar to the frame SetMenuBar(menuBar); #endif // wxUSE_MENUS #if 0 // wxUSE_STATUSBAR // create a status bar just for fun (by default with 1 pane only) CreateStatusBar(2); SetStatusText("Welcome to wxWidgets!"); #endif // wxUSE_STATUSBAR wxSplitterWindow* splitter = new wxSplitterWindow(this, wxID_ANY); splitter->SetAccessible(new SplitterWindowAccessible(splitter)); wxListBox* listBox = new wxListBox(splitter, wxID_ANY); listBox->Append("Cabbages"); listBox->Append("Kings"); listBox->Append("Sealing wax"); listBox->Append("Strings"); listBox->CreateAccessible(); listBox->SetHelpText("This is a sample wxWidgets listbox, with a number of items in it."); m_textCtrl = new wxTextCtrl(splitter, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE); m_textCtrl->CreateAccessible(); m_textCtrl->SetHelpText("This is a sample wxWidgets multiline text control."); splitter->SplitHorizontally(listBox, m_textCtrl, 150); #if 0 wxScrolledWindow* scrolledWindow = new wxScrolledWindow(this, wxID_ANY); scrolledWindow->SetAccessible(new ScrolledWindowAccessible(scrolledWindow)); #endif } // event handlers void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { // true is to force the frame to close Close(true); } void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxString msg; msg.Printf( "This is the About dialog of the AccessTest sample.\n" "Welcome to %s", wxVERSION_STRING); wxMessageBox(msg, "About AccessTest", wxOK | wxICON_INFORMATION, this); } void MyFrame::OnQuery(wxCommandEvent& WXUNUSED(event)) { m_textCtrl->Clear(); IAccessible* accessibleFrame = NULL; if (S_OK != AccessibleObjectFromWindow((HWND) GetHWND(), (DWORD)OBJID_CLIENT, IID_IAccessible, (void**) & accessibleFrame)) { Log("Could not get object."); return; } if (accessibleFrame) { //Log("Got an IAccessible for the frame."); LogObject(0, accessibleFrame); Log("Checking children using AccessibleChildren()..."); // Now check the AccessibleChildren function works OK long childCount = 0; if (S_OK != accessibleFrame->get_accChildCount(& childCount)) { Log("Could not get number of children."); accessibleFrame->Release(); return; } else if (childCount == 0) { Log("No children."); accessibleFrame->Release(); return; } long obtained = 0; VARIANT *var = new VARIANT[childCount]; int i; for (i = 0; i < childCount; i++) { VariantInit(& (var[i])); var[i].vt = VT_DISPATCH; } if (S_OK == AccessibleChildren(accessibleFrame, 0, childCount, var, &obtained)) { for (i = 0; i < childCount; i++) { IAccessible* childAccessible = NULL; if (var[i].pdispVal) { if (var[i].pdispVal->QueryInterface(IID_IAccessible, (LPVOID*) & childAccessible) == S_OK) { var[i].pdispVal->Release(); wxString name, role; GetInfo(childAccessible, 0, name, role); wxString str; str.Printf("Found child %s/%s", name, role); Log(str); childAccessible->Release(); } else { var[i].pdispVal->Release(); } } } } else { Log("AccessibleChildren failed."); } delete[] var; accessibleFrame->Release(); } } // Log messages to the text control void MyFrame::Log(const wxString& text) { if (m_textCtrl) { wxString text2(text); text2.Replace("\n", " "); text2.Replace("\r", " "); m_textCtrl->SetInsertionPointEnd(); m_textCtrl->WriteText(text2 + "\n"); } } // Recursively give information about an object void MyFrame::LogObject(int indent, IAccessible* obj) { wxString name, role; if (indent == 0) { GetInfo(obj, 0, name, role); wxString str; str.Printf("Name = %s; Role = %s", name, role); str.Pad(indent, ' ', false); Log(str); } long childCount = 0; if (S_OK == obj->get_accChildCount(& childCount)) { wxString str; str.Printf("There are %d children.", (int) childCount); str.Pad(indent, ' ', false); Log(str); Log(""); } int i; for (i = 1; i <= childCount; i++) { GetInfo(obj, i, name, role); wxString str; str.Printf("%d) Name = %s; Role = %s", i, name, role); str.Pad(indent, ' ', false); Log(str); VARIANT var; VariantInit(& var); var.vt = VT_I4; var.lVal = i; IDispatch* pDisp = NULL; IAccessible* childObject = NULL; if (S_OK == obj->get_accChild(var, & pDisp) && pDisp) { str.Printf("This is a real object."); str.Pad(indent+4, ' ', false); Log(str); if (pDisp->QueryInterface(IID_IAccessible, (LPVOID*) & childObject) == S_OK) { LogObject(indent + 4, childObject); childObject->Release(); } pDisp->Release(); } else { str.Printf("This is an element."); str.Pad(indent+4, ' ', false); Log(str); } // Log(""); } } // Get info for a child (id > 0) or object (id == 0) void MyFrame::GetInfo(IAccessible* accessible, int id, wxString& name, wxString& role) { VARIANT var; VariantInit(& var); var.vt = VT_I4; var.lVal = id; BSTR bStrName = 0; HRESULT hResult = accessible->get_accName(var, & bStrName); if (hResult == S_OK) { name = wxConvertStringFromOle(bStrName); SysFreeString(bStrName); } else { name = "NO NAME"; } VARIANT varRole; VariantInit(& varRole); hResult = accessible->get_accRole(var, & varRole); if (hResult == S_OK && varRole.vt == VT_I4) { wxChar buf[256]; GetRoleText(varRole.lVal, buf, 256); role = buf; } else { role = "NO ROLE"; } } /* * SplitterWindowAccessible implementation */ // Gets the name of the specified object. wxAccStatus SplitterWindowAccessible::GetName(int childId, wxString* name) { if (childId == wxACC_SELF) { * name = "Splitter window"; return wxACC_OK; } wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter) { if (splitter->IsSplit()) { // Two windows, and the sash. if (childId == 1 || childId == 3) return wxACC_NOT_IMPLEMENTED; else if (childId == 2) { *name = "Sash"; return wxACC_OK; } } } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Can return either a child object, or an integer // representing the child element, starting from 1. wxAccStatus SplitterWindowAccessible::HitTest(const wxPoint& pt, int* childId, wxAccessible** WXUNUSED(childObject)) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter) { if (splitter->IsSplit()) { wxPoint clientPt = splitter->ScreenToClient(pt); if (splitter->SashHitTest(clientPt.x, clientPt.y)) { // We're over the sash *childId = 2; return wxACC_OK; } } } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Returns the rectangle for this object (id = 0) or a child element (id > 0). wxAccStatus SplitterWindowAccessible::GetLocation(wxRect& rect, int elementId) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter && elementId == 2 && splitter->IsSplit()) { wxSize clientSize = splitter->GetClientSize(); if (splitter->GetSplitMode() == wxSPLIT_VERTICAL) { rect.x = splitter->GetSashPosition(); rect.y = 0; rect.SetPosition(splitter->ClientToScreen(rect.GetPosition())); rect.width = splitter->GetSashSize(); rect.height = clientSize.y; } else { rect.x = 0; rect.y = splitter->GetSashPosition(); rect.SetPosition(splitter->ClientToScreen(rect.GetPosition())); rect.width = clientSize.x; rect.height = splitter->GetSashSize(); } return wxACC_OK; } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Navigates from fromId to toId/toObject. wxAccStatus SplitterWindowAccessible::Navigate(wxNavDir navDir, int fromId, int* toId, wxAccessible** toObject) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter && splitter->IsSplit()) { switch (navDir) { case wxNAVDIR_DOWN: { if (splitter->GetSplitMode() != wxSPLIT_VERTICAL) { if (fromId == 1) { *toId = 2; *toObject = NULL; return wxACC_OK; } else if (fromId == 2) { *toId = 3; *toObject = splitter->GetWindow2()->GetAccessible(); return wxACC_OK; } } return wxACC_FALSE; #if 0 // below line is not executed due to earlier return break; #endif } case wxNAVDIR_FIRSTCHILD: { if (fromId == 2) return wxACC_FALSE; } break; case wxNAVDIR_LASTCHILD: { if (fromId == 2) return wxACC_FALSE; } break; case wxNAVDIR_LEFT: { if (splitter->GetSplitMode() != wxSPLIT_HORIZONTAL) { if (fromId == 3) { *toId = 2; *toObject = NULL; return wxACC_OK; } else if (fromId == 2) { *toId = 1; *toObject = splitter->GetWindow1()->GetAccessible(); return wxACC_OK; } } return wxACC_FALSE; } #if 0 // below line is not executed due to earlier return break; #endif case wxNAVDIR_NEXT: { if (fromId == 1) { *toId = 2; *toObject = NULL; return wxACC_OK; } else if (fromId == 2) { *toId = 3; *toObject = splitter->GetWindow2()->GetAccessible(); return wxACC_OK; } return wxACC_FALSE; } #if 0 // below line is not executed due to earlier return break; #endif case wxNAVDIR_PREVIOUS: { if (fromId == 3) { *toId = 2; *toObject = NULL; return wxACC_OK; } else if (fromId == 2) { *toId = 1; *toObject = splitter->GetWindow1()->GetAccessible(); return wxACC_OK; } return wxACC_FALSE; } #if 0 // below line is not executed due to earlier return break; #endif case wxNAVDIR_RIGHT: { if (splitter->GetSplitMode() != wxSPLIT_HORIZONTAL) { if (fromId == 1) { *toId = 2; *toObject = NULL; return wxACC_OK; } else if (fromId == 2) { *toId = 3; *toObject = splitter->GetWindow2()->GetAccessible(); return wxACC_OK; } } // Can't go right spatially if split horizontally. return wxACC_FALSE; } #if 0 // below line is not executed due to earlier return break; #endif case wxNAVDIR_UP: { if (splitter->GetSplitMode() != wxSPLIT_VERTICAL) { if (fromId == 3) { *toId = 2; return wxACC_OK; } else if (fromId == 2) { *toId = 1; *toObject = splitter->GetWindow1()->GetAccessible(); return wxACC_OK; } } // Can't go up spatially if split vertically. return wxACC_FALSE; #if 0 // below line is not executed due to earlier return break; #endif } } } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Gets the number of children. wxAccStatus SplitterWindowAccessible::GetChildCount(int* childCount) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter) { if (splitter->IsSplit()) { // Two windows, and the sash. *childCount = 3; return wxACC_OK; } else { // No sash -- 1 or 0 windows. if (splitter->GetWindow1() || splitter->GetWindow2()) { *childCount = 1; return wxACC_OK; } else { *childCount = 0; return wxACC_OK; } } } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Gets the specified child (starting from 1). // If *child is NULL and return value is wxACC_OK, // this means that the child is a simple element and // not an accessible object. wxAccStatus SplitterWindowAccessible::GetChild(int childId, wxAccessible** child) { if (childId == wxACC_SELF) { *child = this; return wxACC_OK; } wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter) { if (splitter->IsSplit()) { // Two windows, and the sash. if (childId == 1) { *child = splitter->GetWindow1()->GetAccessible(); } else if (childId == 2) { *child = NULL; // Sash } else if (childId == 3) { *child = splitter->GetWindow2()->GetAccessible(); } else { return wxACC_FAIL; } return wxACC_OK; } else { // No sash -- 1 or 0 windows. if (childId == 1) { if (splitter->GetWindow1()) { *child = splitter->GetWindow1()->GetAccessible(); return wxACC_OK; } else if (splitter->GetWindow2()) { *child = splitter->GetWindow2()->GetAccessible(); return wxACC_OK; } else { return wxACC_FAIL; } } else return wxACC_FAIL; } } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Gets the parent, or NULL. wxAccStatus SplitterWindowAccessible::GetParent(wxAccessible** WXUNUSED(parent)) { return wxACC_NOT_IMPLEMENTED; } // Performs the default action. childId is 0 (the action for this object) // or > 0 (the action for a child). // Return wxACC_NOT_SUPPORTED if there is no default action for this // window (e.g. an edit control). wxAccStatus SplitterWindowAccessible::DoDefaultAction(int WXUNUSED(childId)) { return wxACC_NOT_IMPLEMENTED; } // Gets the default action for this object (0) or > 0 (the action for a child). // Return wxACC_OK even if there is no action. actionName is the action, or the empty // string if there is no action. // The retrieved string describes the action that is performed on an object, // not what the object does as a result. For example, a toolbar button that prints // a document has a default action of "Press" rather than "Prints the current document." wxAccStatus SplitterWindowAccessible::GetDefaultAction(int childId, wxString* WXUNUSED(actionName)) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter && splitter->IsSplit() && childId == 2) { // No default action for the splitter. return wxACC_FALSE; } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Returns the description for this object or a child. wxAccStatus SplitterWindowAccessible::GetDescription(int childId, wxString* description) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter) { if (splitter->IsSplit()) { if (childId == 2) { * description = _("The splitter window sash."); return wxACC_OK; } } } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Returns help text for this object or a child, similar to tooltip text. wxAccStatus SplitterWindowAccessible::GetHelpText(int childId, wxString* helpText) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter) { if (splitter->IsSplit()) { if (childId == 2) { * helpText = _("The splitter window sash."); return wxACC_OK; } } } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Returns the keyboard shortcut for this object or child. // Return e.g. ALT+K wxAccStatus SplitterWindowAccessible::GetKeyboardShortcut(int childId, wxString* WXUNUSED(shortcut)) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter && splitter->IsSplit() && childId == 2) { // No keyboard shortcut for the splitter. return wxACC_FALSE; } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Returns a role constant. wxAccStatus SplitterWindowAccessible::GetRole(int childId, wxAccRole* role) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter) { if (splitter->IsSplit()) { if (childId == 2) { * role = wxROLE_SYSTEM_GRIP; return wxACC_OK; } } } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Returns a state constant. wxAccStatus SplitterWindowAccessible::GetState(int childId, long* state) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter && splitter->IsSplit() && childId == 2) { // No particular state. Not sure what would be appropriate here. *state = wxACC_STATE_SYSTEM_UNAVAILABLE; return wxACC_OK; } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Returns a localized string representing the value for the object // or child. wxAccStatus SplitterWindowAccessible::GetValue(int childId, wxString* strValue) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter && splitter->IsSplit() && childId == 2) { // The sash position is the value. wxString pos; pos << splitter->GetSashPosition(); *strValue = pos; return wxACC_OK; } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Selects the object or child. wxAccStatus SplitterWindowAccessible::Select(int childId, wxAccSelectionFlags WXUNUSED(selectFlags)) { wxSplitterWindow* splitter = wxDynamicCast(GetWindow(), wxSplitterWindow); if (splitter && splitter->IsSplit() && childId == 2) { // Can't select the sash. return wxACC_FALSE; } // Let the framework handle the other cases. return wxACC_NOT_IMPLEMENTED; } // Gets the window with the keyboard focus. // If childId is 0 and child is NULL, no object in // this subhierarchy has the focus. // If this object has the focus, child should be 'this'. wxAccStatus SplitterWindowAccessible::GetFocus(int* WXUNUSED(childId), wxAccessible** WXUNUSED(child)) { return wxACC_NOT_IMPLEMENTED; } // Gets a variant representing the selected children // of this object. // Acceptable values: // - a null variant (IsNull() returns true) // - a list variant (GetType() == "list") // - an integer representing the selected child element, // or 0 if this object is selected (GetType() == "long") // - a "void*" pointer to a wxAccessible child object wxAccStatus SplitterWindowAccessible::GetSelections(wxVariant* WXUNUSED(selections)) { return wxACC_NOT_IMPLEMENTED; } #endif // wxUSE_ACCESSIBILITY
31.56553
116
0.555938
[ "object" ]
e740a69fbc0d8dc0cbe54e2986d9079fb6c906b0
9,224
cpp
C++
utils.cpp
rohankhanna/tensorflow-object-detection-cpp
a53395918e4a04fcbe1563b5dd02383b68904aa6
[ "MIT" ]
null
null
null
utils.cpp
rohankhanna/tensorflow-object-detection-cpp
a53395918e4a04fcbe1563b5dd02383b68904aa6
[ "MIT" ]
null
null
null
utils.cpp
rohankhanna/tensorflow-object-detection-cpp
a53395918e4a04fcbe1563b5dd02383b68904aa6
[ "MIT" ]
null
null
null
#include "utils.h" #include <math.h> #include <fstream> #include <utility> #include <vector> #include <iostream> #include <regex> #include "tensorflow/cc/ops/const_op.h" #include "tensorflow/cc/ops/image_ops.h" #include "tensorflow/cc/ops/standard_ops.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/graph/default_device.h" #include "tensorflow/core/graph/graph_def_builder.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/stringpiece.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/init_main.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/public/session.h" #include "tensorflow/core/util/command_line_flags.h" #include <opencv2/opencv.hpp> #include <opencv2/core/mat.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; using tensorflow::Flag; using tensorflow::Tensor; using tensorflow::Status; using tensorflow::string; using tensorflow::int32; /** Read a model graph definition (xxx.pb) from disk, and creates a session object you can use to run it. */ Status loadGraph(const string &graph_file_name, unique_ptr<tensorflow::Session> *session) { tensorflow::GraphDef graph_def; Status load_graph_status = ReadBinaryProto(tensorflow::Env::Default(), graph_file_name, &graph_def); if (!load_graph_status.ok()) { return tensorflow::errors::NotFound("Failed to load compute graph at '", graph_file_name, "'"); } session->reset(tensorflow::NewSession(tensorflow::SessionOptions())); Status session_create_status = (*session)->Create(graph_def); if (!session_create_status.ok()) { return session_create_status; } return Status::OK(); } /** Read a labels map file (xxx.pbtxt) from disk to translate class numbers into human-readable labels. */ Status readLabelsMapFile(const string &fileName, map<int, string> &labelsMap) { // Read file into a string ifstream t(fileName); if (t.bad()) return tensorflow::errors::NotFound("Failed to load labels map at '", fileName, "'"); stringstream buffer; buffer << t.rdbuf(); string fileString = buffer.str(); // Search entry patterns of type 'item { ... }' and parse each of them smatch matcherEntry; smatch matcherId; smatch matcherName; const regex reEntry("item \\{([\\S\\s]*?)\\}"); const regex reId("[0-9]+"); const regex reName("\'.+\'"); string entry; auto stringBegin = sregex_iterator(fileString.begin(), fileString.end(), reEntry); auto stringEnd = sregex_iterator(); int id; string name; for (sregex_iterator i = stringBegin; i != stringEnd; i++) { matcherEntry = *i; entry = matcherEntry.str(); regex_search(entry, matcherId, reId); if (!matcherId.empty()) id = stoi(matcherId[0].str()); else continue; regex_search(entry, matcherName, reName); if (!matcherName.empty()) name = matcherName[0].str().substr(1, matcherName[0].str().length() - 2); else continue; labelsMap.insert(pair<int, string>(id, name)); } return Status::OK(); } /** Convert Mat image into tensor of shape (1, height, width, d) where last three dims are equal to the original dims. */ Status readTensorFromMat(const Mat &mat, Tensor &outTensor) { auto root = tensorflow::Scope::NewRootScope(); using namespace ::tensorflow::ops; // Trick from https://github.com/tensorflow/tensorflow/issues/8033 float *p = outTensor.flat<float>().data(); Mat fakeMat(mat.rows, mat.cols, CV_32FC3, p); mat.convertTo(fakeMat, CV_32FC3); auto input_tensor = Placeholder(root.WithOpName("input"), tensorflow::DT_FLOAT); vector<pair<string, tensorflow::Tensor>> inputs = {{"input", outTensor}}; auto uint8Caster = Cast(root.WithOpName("uint8_Cast"), outTensor, tensorflow::DT_UINT8); // This runs the GraphDef network definition that we've just constructed, and // returns the results in the output outTensor. tensorflow::GraphDef graph; TF_RETURN_IF_ERROR(root.ToGraphDef(&graph)); vector<Tensor> outTensors; unique_ptr<tensorflow::Session> session(tensorflow::NewSession(tensorflow::SessionOptions())); TF_RETURN_IF_ERROR(session->Create(graph)); TF_RETURN_IF_ERROR(session->Run({inputs}, {"uint8_Cast"}, {}, &outTensors)); outTensor = outTensors.at(0); return Status::OK(); } /** Draw bounding box and add caption to the image. * Boolean flag _scaled_ shows if the passed coordinates are in relative units (true by default in tensorflow detection) */ void drawBoundingBoxOnImage(Mat &image, double yMin, double xMin, double yMax, double xMax, double score, string label, bool scaled=true) { cv::Point tl, br; if (scaled) { tl = cv::Point((int) (xMin * image.cols), (int) (yMin * image.rows)); br = cv::Point((int) (xMax * image.cols), (int) (yMax * image.rows)); } else { tl = cv::Point((int) xMin, (int) yMin); br = cv::Point((int) xMax, (int) yMax); } cv::rectangle(image, tl, br, cv::Scalar(0, 255, 255), 1); // Ceiling the score down to 3 decimals (weird!) float scoreRounded = floorf(score * 1000) / 1000; string scoreString = to_string(scoreRounded).substr(0, 5); string caption = label + " (" + scoreString + ")"; // Adding caption of type "LABEL (X.XXX)" to the top-left corner of the bounding box int fontCoeff = 12; cv::Point brRect = cv::Point(tl.x + caption.length() * fontCoeff / 1.6, tl.y + fontCoeff); cv::rectangle(image, tl, brRect, cv::Scalar(0, 255, 255), -1); cv::Point textCorner = cv::Point(tl.x, tl.y + fontCoeff * 0.9); cv::putText(image, caption, textCorner, FONT_HERSHEY_SIMPLEX, 0.4, cv::Scalar(255, 0, 0)); } /** Draw bounding boxes and add captions to the image. * Box is drawn only if corresponding score is higher than the _threshold_. */ void drawBoundingBoxesOnImage(Mat &image, tensorflow::TTypes<float>::Flat &scores, tensorflow::TTypes<float>::Flat &classes, tensorflow::TTypes<float,3>::Tensor &boxes, map<int, string> &labelsMap, vector<size_t> &idxs) { for (int j = 0; j < idxs.size(); j++) drawBoundingBoxOnImage(image, boxes(0,idxs.at(j),0), boxes(0,idxs.at(j),1), boxes(0,idxs.at(j),2), boxes(0,idxs.at(j),3), scores(idxs.at(j)), labelsMap[classes(idxs.at(j))]); } /** Calculate intersection-over-union (IOU) for two given bbox Rects. */ double IOU(Rect2f box1, Rect2f box2) { float xA = max(box1.tl().x, box2.tl().x); float yA = max(box1.tl().y, box2.tl().y); float xB = min(box1.br().x, box2.br().x); float yB = min(box1.br().y, box2.br().y); float intersectArea = abs((xB - xA) * (yB - yA)); float unionArea = abs(box1.area()) + abs(box2.area()) - intersectArea; return 1. * intersectArea / unionArea; } /** Return idxs of good boxes (ones with highest confidence score (>= thresholdScore) * and IOU <= thresholdIOU with others). */ vector<size_t> filterBoxes(tensorflow::TTypes<float>::Flat &scores, tensorflow::TTypes<float, 3>::Tensor &boxes, double thresholdIOU, double thresholdScore) { vector<size_t> sortIdxs(scores.size()); iota(sortIdxs.begin(), sortIdxs.end(), 0); // Create set of "bad" idxs set<size_t> badIdxs = set<size_t>(); size_t i = 0; while (i < sortIdxs.size()) { if (scores(sortIdxs.at(i)) < thresholdScore) badIdxs.insert(sortIdxs[i]); if (badIdxs.find(sortIdxs.at(i)) != badIdxs.end()) { i++; continue; } Rect2f box1 = Rect2f(Point2f(boxes(0, sortIdxs.at(i), 1), boxes(0, sortIdxs.at(i), 0)), Point2f(boxes(0, sortIdxs.at(i), 3), boxes(0, sortIdxs.at(i), 2))); for (size_t j = i + 1; j < sortIdxs.size(); j++) { if (scores(sortIdxs.at(j)) < thresholdScore) { badIdxs.insert(sortIdxs[j]); continue; } Rect2f box2 = Rect2f(Point2f(boxes(0, sortIdxs.at(j), 1), boxes(0, sortIdxs.at(j), 0)), Point2f(boxes(0, sortIdxs.at(j), 3), boxes(0, sortIdxs.at(j), 2))); if (IOU(box1, box2) > thresholdIOU) badIdxs.insert(sortIdxs[j]); } i++; } // Prepare "good" idxs for return vector<size_t> goodIdxs = vector<size_t>(); for (auto it = sortIdxs.begin(); it != sortIdxs.end(); it++) if (badIdxs.find(sortIdxs.at(*it)) == badIdxs.end()) goodIdxs.push_back(*it); return goodIdxs; }
38.594142
139
0.628144
[ "object", "shape", "vector", "model" ]
8d4525881c7f33bf9087b0d6f4740d564b5d86ac
470
cpp
C++
azioni/azioni.cpp
EndBug/olinfo-solutions
de278df0ad1c4995ac58a1ebc5d8902a0cc81ed3
[ "MIT" ]
null
null
null
azioni/azioni.cpp
EndBug/olinfo-solutions
de278df0ad1c4995ac58a1ebc5d8902a0cc81ed3
[ "MIT" ]
null
null
null
azioni/azioni.cpp
EndBug/olinfo-solutions
de278df0ad1c4995ac58a1ebc5d8902a0cc81ed3
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> using namespace std; int N, diff = 0; vector <int> Q; int main() { ifstream in("input.txt"); ofstream out("output.txt"); in >> N; for (int i = 0; i < N; i++) { int temp; in >> temp; Q.push_back(temp); } for (int i = 0; i < N-1; i++) { int current = abs(Q[i] - Q[i+1]); if (current > diff) diff = current; } out << diff; return 0; }
16.206897
43
0.493617
[ "vector" ]
8d4cbafcc4944311091bfe3b0ce915bd62ac3e91
12,786
cpp
C++
GATE_Engine/GeometryLoader.cpp
DocDonkeys/3D_Engine
bb2868884c6eec0ef619a45b7e21f5cf3857fe1b
[ "MIT" ]
1
2019-10-14T00:35:48.000Z
2019-10-14T00:35:48.000Z
GATE_Engine/GeometryLoader.cpp
DocDonkeys/3D_Engine
bb2868884c6eec0ef619a45b7e21f5cf3857fe1b
[ "MIT" ]
null
null
null
GATE_Engine/GeometryLoader.cpp
DocDonkeys/3D_Engine
bb2868884c6eec0ef619a45b7e21f5cf3857fe1b
[ "MIT" ]
3
2020-02-13T22:52:44.000Z
2020-10-21T06:55:45.000Z
#include "GeometryLoader.h" #include "Application.h" #include "ModuleRenderer3D.h" #include "ModuleSceneIntro.h" #include "ModuleFileSystem.h" #include "ModuleResources.h" #include "ModuleCamera3D.h" #include "TextureLoader.h" #include "Importer.h" #include "libs/SDL/include/SDL_assert.h" #include "libs/Assimp/include/cimport.h" #include "libs/Assimp/include/scene.h" #include "libs/Assimp/include/postprocess.h" #include "libs/Assimp/include/cfileio.h" #include "libs/MathGeoLib/include/MathGeoLib.h" #include "libs/MathGeoLib/include/MathBuildConfig.h" #pragma comment (lib, "libs/Assimp/libx86/assimp.lib") #include "libs/par/par_shapes.h" #include "ResourceMesh.h" #include "ResourceTexture.h" #include "GameObject.h" #include "ComponentTransform.h" #include "ComponentMesh.h" #include "ComponentMaterial.h" // Memory Leak Detection #include "MemLeaks.h" //#pragma comment (lib, "libs/assimp-5.0.0/libx86/assimp.lib") //CHANGE/FIX: Remove? @Didac do we need to keep this here just in case? /* #include "Assimp/include/cimport.h" #include "Assimp/include/scene.h" #include "Assimp/include/postprocess.h" #include "Assimp/include/cfileio.h" #pragma comment (lib, "Assimp/libx86/assimp.lib") */ GeometryLoader::GeometryLoader(Application * app, const char * name, bool start_enabled) : Module(app, name, start_enabled) { } GeometryLoader::~GeometryLoader() { } bool GeometryLoader::CleanUp() { bool ret = true; // detach log stream aiDetachAllLogStreams(); return ret; } void AssimpLOGCallback(const char * msg, char * userData) { //We LOG to Console LOG(msg,userData); } GameObject* GeometryLoader::Load3DFile(const char* full_path) { GameObject* ret = nullptr; float biggestMeshSize = -1.0f; //Default GameObject names based on trimmed filename std::string filename = App->SubtractString(std::string(full_path), "\\", true, false); std::string objName = App->SubtractString(std::string(filename), ".", false, true) + "_"; uint counter = 0; //We extract the Absolute path from the full path (everything until the actual file) std::string str = full_path; std::string absolute_path; std::size_t found = str.find_last_of("/\\"); //Find last\\ (right before the filename) // absolute_path = str.substr(0, found + 1); //App->file_system->DuplicateFile(full_path,ASSETS_FOLDER); //We call assimp to import the file const aiScene* scene = aiImportFile(full_path, aiProcessPreset_TargetRealtime_MaxQuality); if (scene != nullptr && scene->HasMeshes()) { //We loaded the 3D file successfully! //We load all nodes inside the root node, respecting parenting in gameobjects aiNode* root = scene->mRootNode; root->mName = objName; float biggestSize = 5.f; GameObject* go = LoadAssimpNode(scene, root, absolute_path.c_str(), filename.c_str(), full_path, objName.c_str(), counter, biggestSize); ret = go; if (biggestSize > 5.f) App->camera->LookAt(float3::zero, biggestSize); //Once finished we release the original file aiReleaseImport(scene); //Test gameobject saving as .model } else LOG("Error loading scene meshes %s", full_path); return ret; } GameObject* GeometryLoader::LoadAssimpNode(const aiScene* scene, const aiNode* node, const char* absolute_path, const char* filename, const char* full_path, const char* objName, uint counter, float& biggestSize) { float4x4 meshTrs; //Before creating Game Object, obtain local transformation respect parent for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { meshTrs[i][j] = node->mTransformation[i][j]; } } //We create the gameobject for the node GameObject* ret_go = App->scene_intro->CreateEmptyGameObject(node->mName.C_Str()); // Transform ComponentTransform* trs_component = (ComponentTransform*)ret_go->GetComponent(COMPONENT_TYPE::TRANSFORM); trs_component->SetLocalMat(meshTrs); if (node != nullptr && node->mNumMeshes > 0) { int nmeshes = node->mNumMeshes; for (int i = 0; i < nmeshes; ++i) { aiMesh* loaded_mesh = scene->mMeshes[node->mMeshes[i]]; bool has_mesh = false; for (int i = 0; i < loaded_meshes.size(); ++i) { if (loaded_mesh == loaded_meshes[i].assimp_mesh) //If this mesh has already been loaded get the reference instead { has_mesh = true; ComponentMesh* mesh_component = (ComponentMesh*)ret_go->CreateComponent(COMPONENT_TYPE::MESH); mesh_component->mesh = (ResourceMesh*)App->resources->Get(loaded_meshes[i].UID); mesh_component->mesh->AddReference(); break; } } if (has_mesh == false) //If the list of loaded meshes doesn't have this mesh, create a mesh { ResourceMesh* new_mesh = (ResourceMesh*)App->resources->CreateNewResource(Resource::MESH); //LOAD! new_mesh->LoadVertices(loaded_mesh); //Vertices new_mesh->LoadIndices(loaded_mesh); //Indices new_mesh->LoadNormals(loaded_mesh); //Normals new_mesh->LoadTexCoords(loaded_mesh); // UV's //Generate the buffers (Vertex and Index) for the VRAM & Drawing App->renderer3D->GenerateVertexBuffer(new_mesh->id_vertex, new_mesh->num_vertex, new_mesh->vertex); if (new_mesh->index != nullptr) App->renderer3D->GenerateIndexBuffer(new_mesh->id_index, new_mesh->num_index, new_mesh->index); //Generate the buffer for the tex_coordinates App->renderer3D->GenerateVertexBuffer(new_mesh->id_tex_coords, new_mesh->num_tex_coords * 2, new_mesh->tex_coords); // Mesh ComponentMesh* mesh_component = (ComponentMesh*)ret_go->CreateComponent(COMPONENT_TYPE::MESH); mesh_component->mesh = new_mesh; mesh_component->mesh->path = full_path; mesh_component->mesh->filename = filename; mesh_component->mesh->LoadMeshBounds(); ret_go->size = mesh_component->mesh->GetSize(); float meshSize = Length(new_mesh->GetSize()); if (biggestSize < meshSize) { biggestSize = meshSize; } //If this mesh was not in the vector we need to add it MeshWRef Mesh; Mesh.assimp_mesh = loaded_mesh; Mesh.UID = mesh_component->mesh->GetUID(); mesh_component->mesh->AddReference(); loaded_meshes.push_back(Mesh); } // Material ComponentMaterial* material_component = (ComponentMaterial*)ret_go->CreateComponent(COMPONENT_TYPE::MATERIAL); ResourceTexture* tex = LoadMaterial(scene, loaded_mesh, absolute_path); if (tex == nullptr || tex->id == 0) { LOG("[Warning]: The FBX has no embeded texture, was not found, or could not be loaded!"); } else { material_component->AssignTexture(tex); } } } if (node->mNumChildren > 0) for (int i = 0; i < node->mNumChildren; ++i) { GameObject* child = LoadAssimpNode(scene, node->mChildren[i], absolute_path, filename, full_path, objName, counter, biggestSize); GOFunctions::ReParentGameObject(child, ret_go); } return ret_go; } void GeometryLoader::LoadPrimitiveShape(const par_shapes_mesh_s * p_mesh, const char* name) { ResourceMesh* new_mesh = (ResourceMesh*)App->resources->CreateNewResource(Resource::MESH); //Get sizes new_mesh->num_vertex = p_mesh->npoints; new_mesh->num_index = p_mesh->ntriangles * 3; new_mesh->num_tex_coords = p_mesh->npoints; //Alloc memory new_mesh->vertex = new float3[new_mesh->num_vertex]; new_mesh->index = new uint[new_mesh->num_index]; new_mesh->tex_coords = new float[new_mesh->num_tex_coords * 2]; //Copy the par_shape_mesh vertex array and index array into Mesh_Data for (int i = 0; i < new_mesh->num_vertex; i++) { int j = i * 3; new_mesh->vertex[i].x = p_mesh->points[j]; new_mesh->vertex[i].y = p_mesh->points[j + 1]; new_mesh->vertex[i].z = p_mesh->points[j + 2]; } for (int i = 0; i < new_mesh->num_index; i++) { new_mesh->index[i] = (uint)p_mesh->triangles[i]; } LOG("Created Primitive with %d vertices & %d indices.", new_mesh->num_vertex, new_mesh->num_index); LoadPrimitiveNormals(new_mesh,p_mesh); //Copy the par_shapes texture coordinates for (int i = 0; i < new_mesh->num_tex_coords * 2; ++i) new_mesh->tex_coords[i] = p_mesh->tcoords[i]; //Generate Buffers App->renderer3D->GenerateVertexBuffer(new_mesh->id_vertex, new_mesh->num_vertex, new_mesh->vertex); App->renderer3D->GenerateIndexBuffer(new_mesh->id_index, new_mesh->num_index, new_mesh->index); App->renderer3D->GenerateVertexBuffer(new_mesh->id_tex_coords, new_mesh->num_tex_coords * 2,new_mesh->tex_coords); //We create a game object for the current mesh GameObject* go = App->scene_intro->CreateEmptyGameObject(name); ComponentMesh* mesh_component = (ComponentMesh*)go->CreateComponent(COMPONENT_TYPE::MESH); mesh_component->mesh = new_mesh; mesh_component->mesh->LoadMeshBounds(); go->size = mesh_component->mesh->GetSize(); go->UpdateBoundingBox(); go->CreateComponent(COMPONENT_TYPE::MATERIAL); //Create default material (will have checkers if Teacher wants to us it to check uv's) } void GeometryLoader::LoadPrimitiveNormals(ResourceMesh * new_mesh, const par_shapes_mesh_s * p_mesh) { //Load the Normals of the par_shape if (p_mesh->normals != NULL) { new_mesh->normals_vector = new float3[new_mesh->num_vertex]; memcpy(new_mesh->normals_vector, p_mesh->normals, sizeof(float3) * new_mesh->num_vertex); //Calculate the positions and vectors of the face Normals new_mesh->normals_faces = new float3[new_mesh->num_index]; new_mesh->normals_faces_vector = new float3[new_mesh->num_index]; for (int j = 0; j < new_mesh->num_index; j += 3) { // 3 points of the triangle/face float3 vert1 = new_mesh->vertex[new_mesh->index[j]]; float3 vert2 = new_mesh->vertex[new_mesh->index[j + 1]]; float3 vert3 = new_mesh->vertex[new_mesh->index[j + 2]]; //Calculate starting point of the normal new_mesh->normals_faces[j] = (vert1 + vert2 + vert3) / 3; //Calculate Cross product of 2 edges of the triangle to obtain Normal vector float3 edge_a = vert2 - vert1; float3 edge_b = vert3 - vert1; float3 normal; normal = Cross(edge_a, edge_b); normal.Normalize(); new_mesh->normals_faces_vector[j] = normal * 0.25f; } } } ResourceTexture* GeometryLoader::LoadMaterial(const aiScene * scene, const aiMesh * loaded_mesh, const std::string & absolute_path) { ResourceTexture* ret = nullptr; if (scene->HasMaterials()) { aiString tex_path; aiMaterial* material = scene->mMaterials[loaded_mesh->mMaterialIndex]; // For now we are just required to use 1 diffse texture material->GetTexture(aiTextureType_DIFFUSE, 0, &tex_path); if (tex_path.length > 0) { std::string relative_path = tex_path.C_Str(); std::size_t found = relative_path.find_last_of("/\\"); if (found > 0) { relative_path = relative_path.substr(found + 1, relative_path.size()); } std::string texture_path = absolute_path.data() + relative_path; uint32 uid = App->resources->ImportFile(texture_path.data()); //TODO: Didac ret = (ResourceTexture*)App->resources->Get(uid); //ret = App->texture_loader->LoadTextureFile(texture_path.data()); if (ret == nullptr || ret->id == 0) { LOG("[Error]: Texture loading failed in path %s.", absolute_path); } } else { LOG("[Error]: No diffuse texture or path loading failed."); } } else LOG("[Info]: File has no linked materials to load."); return ret; } void GeometryLoader::CreatePrimitive(PRIMITIVE p, int slices, int stacks, float radius) { par_shapes_mesh* primitive_mesh = nullptr; const char* name; switch (p) { case PRIMITIVE::PLANE: primitive_mesh = par_shapes_create_plane(slices,stacks); name = "Plane"; break; case PRIMITIVE::CUBE: primitive_mesh = par_shapes_create_primitive_cube(); name = "Cube"; break; case PRIMITIVE::SPHERE: primitive_mesh = par_shapes_create_parametric_sphere(slices, stacks); name = "Sphere"; break; case PRIMITIVE::HEMISPHERE: primitive_mesh = par_shapes_create_hemisphere(slices, stacks); name = "Hemisphere"; break; case PRIMITIVE::CYLINDER: primitive_mesh = par_shapes_create_cylinder(slices, stacks); name = "Cylinder"; break; case PRIMITIVE::CONE: primitive_mesh = par_shapes_create_cone(slices, stacks); name = "Cone"; break; case PRIMITIVE::TORUS: primitive_mesh = par_shapes_create_torus(slices, stacks,radius); name = "Torus"; break; default: break; } //Push into the meshes vector if (primitive_mesh != nullptr) LoadPrimitiveShape(primitive_mesh, name); else LOG("Failed to create primitive! Invalid primitive enum value received"); } bool GeometryLoader::Init() { // Stream log messages to Debug window //struct aiLogStream log_stream; //ASSIMP DEBUG IS CRASHING CODE for Joints message! //log_stream.callback = AssimpLOGCallback; //aiAttachLogStream(&log_stream); return true; } bool GeometryLoader::Start() { return true; } update_status GeometryLoader::Update(float dt) { return UPDATE_CONTINUE; }
31.415233
138
0.71985
[ "mesh", "object", "vector", "model", "transform", "3d" ]
8d5064daac8ee0320115924aa1ac44615cca540c
24,956
cc
C++
cc/tiles/image_controller_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
cc/tiles/image_controller_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
cc/tiles/image_controller_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 The Chromium 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 "cc/tiles/image_controller.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/run_loop.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_checker_impl.h" #include "cc/paint/paint_image_builder.h" #include "cc/test/skia_common.h" #include "cc/test/stub_decode_cache.h" #include "cc/test/test_paint_worklet_input.h" #include "cc/tiles/image_decode_cache.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace cc { namespace { class TestWorkerThread : public base::SimpleThread { public: TestWorkerThread() : base::SimpleThread("test_worker_thread"), condition_(&lock_) {} void Run() override { for (;;) { base::OnceClosure task; { base::AutoLock hold(lock_); if (shutdown_) break; if (queue_.empty()) { condition_.Wait(); continue; } task = std::move(queue_.front()); queue_.erase(queue_.begin()); } std::move(task).Run(); } } void Shutdown() { base::AutoLock hold(lock_); shutdown_ = true; condition_.Signal(); } void PostTask(base::OnceClosure task) { base::AutoLock hold(lock_); queue_.push_back(std::move(task)); condition_.Signal(); } private: base::Lock lock_; base::ConditionVariable condition_; std::vector<base::OnceClosure> queue_; bool shutdown_ = false; }; class WorkerTaskRunner : public base::SequencedTaskRunner { public: WorkerTaskRunner() { thread_.Start(); } bool PostNonNestableDelayedTask(const base::Location& from_here, base::OnceClosure task, base::TimeDelta delay) override { return PostDelayedTask(from_here, std::move(task), delay); } bool PostDelayedTask(const base::Location& from_here, base::OnceClosure task, base::TimeDelta delay) override { thread_.PostTask(std::move(task)); return true; } bool RunsTasksInCurrentSequence() const override { return false; } protected: ~WorkerTaskRunner() override { thread_.Shutdown(); thread_.Join(); } TestWorkerThread thread_; }; // Image decode cache with introspection! class TestableCache : public StubDecodeCache { public: ~TestableCache() override { EXPECT_EQ(number_of_refs_, 0); } TaskResult GetTaskForImageAndRef(const DrawImage& image, const TracingInfo& tracing_info) override { // Return false for large images to mimic "won't fit in memory" // behavior. if (image.paint_image() && image.paint_image().width() * image.paint_image().height() >= 1000 * 1000) { return TaskResult(/*need_unref=*/false, /*is_at_raster_decode=*/true, /*can_do_hardware_accelerated_decode=*/false); } ++number_of_refs_; if (task_to_use_) return TaskResult(task_to_use_, /*can_do_hardware_accelerated_decode=*/false); return TaskResult(/*need_unref=*/true, /*is_at_raster_decode=*/false, /*can_do_hardware_accelerated_decode=*/false); } TaskResult GetOutOfRasterDecodeTaskForImageAndRef( const DrawImage& image) override { return GetTaskForImageAndRef(image, TracingInfo()); } void UnrefImage(const DrawImage& image) override { ASSERT_GT(number_of_refs_, 0); --number_of_refs_; } size_t GetMaximumMemoryLimitBytes() const override { return 256 * 1024 * 1024; } int number_of_refs() const { return number_of_refs_; } void SetTaskToUse(scoped_refptr<TileTask> task) { task_to_use_ = task; } private: int number_of_refs_ = 0; scoped_refptr<TileTask> task_to_use_; }; // A simple class that can receive decode callbacks. class DecodeClient { public: DecodeClient() = default; void Callback(base::OnceClosure quit_closure, ImageController::ImageDecodeRequestId id, ImageController::ImageDecodeResult result) { id_ = id; result_ = result; std::move(quit_closure).Run(); } ImageController::ImageDecodeRequestId id() { return id_; } ImageController::ImageDecodeResult result() { return result_; } private: ImageController::ImageDecodeRequestId id_ = 0; ImageController::ImageDecodeResult result_ = ImageController::ImageDecodeResult::FAILURE; }; // A dummy task that does nothing. class SimpleTask : public TileTask { public: SimpleTask() : TileTask(TileTask::SupportsConcurrentExecution::kYes, TileTask::SupportsBackgroundThreadPriority::kYes) { EXPECT_TRUE(thread_checker_.CalledOnValidThread()); } SimpleTask(const SimpleTask&) = delete; SimpleTask& operator=(const SimpleTask&) = delete; void RunOnWorkerThread() override { EXPECT_FALSE(HasCompleted()); has_run_ = true; } void OnTaskCompleted() override { EXPECT_TRUE(thread_checker_.CalledOnValidThread()); } bool has_run() { return has_run_; } private: ~SimpleTask() override = default; base::ThreadChecker thread_checker_; bool has_run_ = false; }; // A task that blocks until instructed otherwise. class BlockingTask : public TileTask { public: BlockingTask() : TileTask(TileTask::SupportsConcurrentExecution::kYes, TileTask::SupportsBackgroundThreadPriority::kYes), run_cv_(&lock_) { EXPECT_TRUE(thread_checker_.CalledOnValidThread()); } BlockingTask(const BlockingTask&) = delete; BlockingTask& operator=(const BlockingTask&) = delete; void RunOnWorkerThread() override { EXPECT_FALSE(HasCompleted()); EXPECT_FALSE(thread_checker_.CalledOnValidThread()); base::AutoLock hold(lock_); while (!can_run_) run_cv_.Wait(); has_run_ = true; } void OnTaskCompleted() override { EXPECT_TRUE(thread_checker_.CalledOnValidThread()); } void AllowToRun() { base::AutoLock hold(lock_); can_run_ = true; run_cv_.Signal(); } bool has_run() { return has_run_; } private: ~BlockingTask() override = default; // Use ThreadCheckerImpl, so that release builds also get correct behavior. base::ThreadCheckerImpl thread_checker_; bool has_run_ = false; base::Lock lock_; base::ConditionVariable run_cv_; bool can_run_ = false; }; // For tests that exercise image controller's thread, this is the timeout value // to allow the worker thread to do its work. int kDefaultTimeoutSeconds = 10; DrawImage CreateDiscardableDrawImage(gfx::Size size) { return DrawImage(CreateDiscardablePaintImage(size), false, SkIRect::MakeWH(size.width(), size.height()), PaintFlags::FilterQuality::kNone, SkM44(), PaintImage::kDefaultFrameIndex, gfx::ColorSpace()); } DrawImage CreateBitmapDrawImage(gfx::Size size) { return DrawImage(CreateBitmapImage(size), false, SkIRect::MakeWH(size.width(), size.height()), PaintFlags::FilterQuality::kNone, SkM44(), PaintImage::kDefaultFrameIndex); } class ImageControllerTest : public testing::Test { public: ImageControllerTest() : task_runner_(base::SequencedTaskRunnerHandle::Get()) { image_ = CreateDiscardableDrawImage(gfx::Size(1, 1)); } ~ImageControllerTest() override = default; void SetUp() override { worker_task_runner_ = base::MakeRefCounted<WorkerTaskRunner>(); controller_ = std::make_unique<ImageController>(task_runner_.get(), worker_task_runner_); cache_ = TestableCache(); controller_->SetImageDecodeCache(&cache_); } void TearDown() override { controller_.reset(); worker_task_runner_ = nullptr; weak_ptr_factory_.InvalidateWeakPtrs(); } base::SequencedTaskRunner* task_runner() { return task_runner_.get(); } ImageController* controller() { return controller_.get(); } TestableCache* cache() { return &cache_; } const DrawImage& image() const { return image_; } // Timeout callback, which errors and exits the runloop. void Timeout(base::RunLoop* run_loop) { ADD_FAILURE() << "Timeout."; run_loop->Quit(); } // Convenience method to run the run loop with a timeout. void RunOrTimeout(base::RunLoop* run_loop) { task_runner_->PostDelayedTask(FROM_HERE, base::BindOnce(&ImageControllerTest::Timeout, weak_ptr_factory_.GetWeakPtr(), base::Unretained(run_loop)), base::Seconds(kDefaultTimeoutSeconds)); run_loop->Run(); } void ResetController() { controller_.reset(); } SkMatrix CreateMatrix(const SkSize& scale, bool is_decomposable) { SkMatrix matrix; matrix.setScale(scale.width(), scale.height()); if (!is_decomposable) { // Perspective is not decomposable, add it. matrix[SkMatrix::kMPersp0] = 0.1f; } return matrix; } PaintImage CreatePaintImage(int width, int height) { scoped_refptr<TestPaintWorkletInput> input = base::MakeRefCounted<TestPaintWorkletInput>(gfx::SizeF(width, height)); return CreatePaintWorkletPaintImage(input); } private: scoped_refptr<base::SequencedTaskRunner> task_runner_; scoped_refptr<WorkerTaskRunner> worker_task_runner_; TestableCache cache_; std::unique_ptr<ImageController> controller_; DrawImage image_; base::WeakPtrFactory<ImageControllerTest> weak_ptr_factory_{this}; }; TEST_F(ImageControllerTest, NullControllerUnrefsImages) { std::vector<DrawImage> images(10); ImageDecodeCache::TracingInfo tracing_info; ASSERT_EQ(10u, images.size()); auto tasks = controller()->SetPredecodeImages(std::move(images), tracing_info); EXPECT_EQ(0u, tasks.size()); EXPECT_EQ(10, cache()->number_of_refs()); controller()->SetImageDecodeCache(nullptr); EXPECT_EQ(0, cache()->number_of_refs()); } TEST_F(ImageControllerTest, QueueImageDecode) { base::RunLoop run_loop; DecodeClient decode_client; EXPECT_EQ(image().paint_image().width(), 1); ImageController::ImageDecodeRequestId expected_id = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client), run_loop.QuitClosure())); RunOrTimeout(&run_loop); EXPECT_EQ(expected_id, decode_client.id()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client.result()); } TEST_F(ImageControllerTest, QueueImageDecodeNonLazy) { base::RunLoop run_loop; DecodeClient decode_client; DrawImage image = CreateBitmapDrawImage(gfx::Size(1, 1)); ImageController::ImageDecodeRequestId expected_id = controller()->QueueImageDecode( image, base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client), run_loop.QuitClosure())); RunOrTimeout(&run_loop); EXPECT_EQ(expected_id, decode_client.id()); EXPECT_EQ(ImageController::ImageDecodeResult::DECODE_NOT_REQUIRED, decode_client.result()); } TEST_F(ImageControllerTest, QueueImageDecodeTooLarge) { base::RunLoop run_loop; DecodeClient decode_client; DrawImage image = CreateDiscardableDrawImage(gfx::Size(2000, 2000)); ImageController::ImageDecodeRequestId expected_id = controller()->QueueImageDecode( image, base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client), run_loop.QuitClosure())); RunOrTimeout(&run_loop); EXPECT_EQ(expected_id, decode_client.id()); EXPECT_EQ(ImageController::ImageDecodeResult::FAILURE, decode_client.result()); } TEST_F(ImageControllerTest, QueueImageDecodeMultipleImages) { base::RunLoop run_loop; DecodeClient decode_client1; ImageController::ImageDecodeRequestId expected_id1 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), base::DoNothing())); DecodeClient decode_client2; ImageController::ImageDecodeRequestId expected_id2 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client2), base::DoNothing())); DecodeClient decode_client3; ImageController::ImageDecodeRequestId expected_id3 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client3), run_loop.QuitClosure())); RunOrTimeout(&run_loop); EXPECT_EQ(expected_id1, decode_client1.id()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client1.result()); EXPECT_EQ(expected_id2, decode_client2.id()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client2.result()); EXPECT_EQ(expected_id3, decode_client3.id()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client3.result()); } TEST_F(ImageControllerTest, QueueImageDecodeWithTask) { scoped_refptr<SimpleTask> task(new SimpleTask); cache()->SetTaskToUse(task); base::RunLoop run_loop; DecodeClient decode_client; ImageController::ImageDecodeRequestId expected_id = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client), run_loop.QuitClosure())); RunOrTimeout(&run_loop); EXPECT_EQ(expected_id, decode_client.id()); EXPECT_TRUE(task->has_run()); EXPECT_TRUE(task->HasCompleted()); } TEST_F(ImageControllerTest, QueueImageDecodeMultipleImagesSameTask) { scoped_refptr<SimpleTask> task(new SimpleTask); cache()->SetTaskToUse(task); base::RunLoop run_loop; DecodeClient decode_client1; ImageController::ImageDecodeRequestId expected_id1 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), base::DoNothing())); DecodeClient decode_client2; ImageController::ImageDecodeRequestId expected_id2 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client2), base::DoNothing())); DecodeClient decode_client3; ImageController::ImageDecodeRequestId expected_id3 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client3), run_loop.QuitClosure())); RunOrTimeout(&run_loop); EXPECT_EQ(expected_id1, decode_client1.id()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client1.result()); EXPECT_EQ(expected_id2, decode_client2.id()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client2.result()); EXPECT_EQ(expected_id3, decode_client3.id()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client3.result()); EXPECT_TRUE(task->has_run()); EXPECT_TRUE(task->HasCompleted()); } TEST_F(ImageControllerTest, QueueImageDecodeChangeControllerWithTaskQueued) { scoped_refptr<BlockingTask> task_one(new BlockingTask); cache()->SetTaskToUse(task_one); DecodeClient decode_client1; ImageController::ImageDecodeRequestId expected_id1 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), base::DoNothing())); scoped_refptr<BlockingTask> task_two(new BlockingTask); cache()->SetTaskToUse(task_two); base::RunLoop run_loop; DecodeClient decode_client2; ImageController::ImageDecodeRequestId expected_id2 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client2), run_loop.QuitClosure())); task_one->AllowToRun(); task_two->AllowToRun(); controller()->SetImageDecodeCache(nullptr); ResetController(); RunOrTimeout(&run_loop); EXPECT_TRUE(task_one->state().IsCanceled() || task_one->HasCompleted()); EXPECT_TRUE(task_two->state().IsCanceled() || task_two->HasCompleted()); EXPECT_EQ(expected_id1, decode_client1.id()); EXPECT_EQ(expected_id2, decode_client2.id()); } TEST_F(ImageControllerTest, QueueImageDecodeImageAlreadyLocked) { scoped_refptr<SimpleTask> task(new SimpleTask); cache()->SetTaskToUse(task); base::RunLoop run_loop1; DecodeClient decode_client1; ImageController::ImageDecodeRequestId expected_id1 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), run_loop1.QuitClosure())); RunOrTimeout(&run_loop1); EXPECT_EQ(expected_id1, decode_client1.id()); EXPECT_TRUE(task->has_run()); cache()->SetTaskToUse(nullptr); base::RunLoop run_loop2; DecodeClient decode_client2; ImageController::ImageDecodeRequestId expected_id2 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client2), run_loop2.QuitClosure())); RunOrTimeout(&run_loop2); EXPECT_EQ(expected_id2, decode_client2.id()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client2.result()); } TEST_F(ImageControllerTest, QueueImageDecodeLockedImageControllerChange) { scoped_refptr<SimpleTask> task(new SimpleTask); cache()->SetTaskToUse(task); base::RunLoop run_loop1; DecodeClient decode_client1; ImageController::ImageDecodeRequestId expected_id1 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), run_loop1.QuitClosure())); RunOrTimeout(&run_loop1); EXPECT_EQ(expected_id1, decode_client1.id()); EXPECT_TRUE(task->has_run()); EXPECT_EQ(1, cache()->number_of_refs()); controller()->SetImageDecodeCache(nullptr); EXPECT_EQ(0, cache()->number_of_refs()); } TEST_F(ImageControllerTest, DispatchesDecodeCallbacksAfterCacheReset) { scoped_refptr<SimpleTask> task(new SimpleTask); cache()->SetTaskToUse(task); base::RunLoop run_loop1; DecodeClient decode_client1; base::RunLoop run_loop2; DecodeClient decode_client2; controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), run_loop1.QuitClosure())); controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client2), run_loop2.QuitClosure())); // Now reset the image cache before decode completed callbacks are posted to // the compositor thread. Ensure that the completion callbacks for the decode // is still run. controller()->SetImageDecodeCache(nullptr); ResetController(); RunOrTimeout(&run_loop1); RunOrTimeout(&run_loop2); EXPECT_EQ(ImageController::ImageDecodeResult::FAILURE, decode_client1.result()); EXPECT_EQ(ImageController::ImageDecodeResult::FAILURE, decode_client2.result()); } TEST_F(ImageControllerTest, DispatchesDecodeCallbacksAfterCacheChanged) { scoped_refptr<SimpleTask> task(new SimpleTask); cache()->SetTaskToUse(task); base::RunLoop run_loop1; DecodeClient decode_client1; base::RunLoop run_loop2; DecodeClient decode_client2; controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), run_loop1.QuitClosure())); controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client2), run_loop2.QuitClosure())); // Now reset the image cache before decode completed callbacks are posted to // the compositor thread. This should orphan the requests. controller()->SetImageDecodeCache(nullptr); EXPECT_EQ(0, cache()->number_of_refs()); TestableCache other_cache; other_cache.SetTaskToUse(task); controller()->SetImageDecodeCache(&other_cache); RunOrTimeout(&run_loop1); RunOrTimeout(&run_loop2); EXPECT_EQ(2, other_cache.number_of_refs()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client1.result()); EXPECT_EQ(ImageController::ImageDecodeResult::SUCCESS, decode_client2.result()); // Reset the controller since the order of destruction is wrong in this test // (|other_cache| should outlive the controller. This is normally done via // SetImageDecodeCache(nullptr) or it can be done in the dtor of the cache.) ResetController(); } TEST_F(ImageControllerTest, QueueImageDecodeLazyCancelImmediately) { DecodeClient decode_client1; DecodeClient decode_client2; // Create two images so that there is always one that is queued up and // not run yet. This prevents raciness in this test. DrawImage image1 = CreateDiscardableDrawImage(gfx::Size(1, 1)); DrawImage image2 = CreateDiscardableDrawImage(gfx::Size(1, 1)); ImageController::ImageDecodeRequestId expected_id1 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), base::DoNothing())); ImageController::ImageDecodeRequestId expected_id2 = controller()->QueueImageDecode( image(), base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client2), base::DoNothing())); // This needs a ref because it is lazy. EXPECT_EQ(2, cache()->number_of_refs()); // Instead of running, immediately cancel everything. controller()->SetImageDecodeCache(nullptr); // This should not crash, and nothing should have run. EXPECT_NE(expected_id1, decode_client1.id()); EXPECT_NE(expected_id2, decode_client2.id()); EXPECT_EQ(0u, decode_client1.id()); EXPECT_EQ(0u, decode_client2.id()); EXPECT_EQ(ImageController::ImageDecodeResult::FAILURE, decode_client1.result()); EXPECT_EQ(ImageController::ImageDecodeResult::FAILURE, decode_client2.result()); // Refs should still be cleaned up. EXPECT_EQ(0, cache()->number_of_refs()); // Explicitly reset the controller so that orphaned task callbacks run // while the decode clients still exist. ResetController(); } TEST_F(ImageControllerTest, QueueImageDecodeNonLazyCancelImmediately) { DecodeClient decode_client1; DecodeClient decode_client2; // Create two images so that there is always one that is queued up and // not run yet. This prevents raciness in this test. DrawImage image1 = CreateBitmapDrawImage(gfx::Size(1, 1)); DrawImage image2 = CreateBitmapDrawImage(gfx::Size(1, 1)); ImageController::ImageDecodeRequestId expected_id1 = controller()->QueueImageDecode( image1, base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client1), base::DoNothing())); ImageController::ImageDecodeRequestId expected_id2 = controller()->QueueImageDecode( image2, base::BindOnce(&DecodeClient::Callback, base::Unretained(&decode_client2), base::DoNothing())); // No ref needed here, because it is non-lazy. EXPECT_EQ(0, cache()->number_of_refs()); // Instead of running, immediately cancel everything. controller()->SetImageDecodeCache(nullptr); // This should not crash, and nothing should have run. EXPECT_NE(expected_id1, decode_client1.id()); EXPECT_NE(expected_id2, decode_client2.id()); EXPECT_EQ(0u, decode_client1.id()); EXPECT_EQ(0u, decode_client2.id()); EXPECT_EQ(ImageController::ImageDecodeResult::FAILURE, decode_client1.result()); EXPECT_EQ(ImageController::ImageDecodeResult::FAILURE, decode_client2.result()); EXPECT_EQ(0, cache()->number_of_refs()); // Explicitly reset the controller so that orphaned task callbacks run // while the decode clients still exist. ResetController(); } } // namespace } // namespace cc
34.374656
80
0.685527
[ "vector" ]
8d5c851f403f5c9734cde80ccac3e13253f4c3e8
2,938
cpp
C++
UnitTests/HostVectorTests.cpp
pmontalb/CudaLight
390efb41da88245b2f5909b84213fb5839d505cf
[ "MIT" ]
2
2020-03-25T17:54:50.000Z
2021-11-30T23:34:21.000Z
UnitTests/HostVectorTests.cpp
pmontalb/CudaLight
390efb41da88245b2f5909b84213fb5839d505cf
[ "MIT" ]
2
2018-03-04T22:26:42.000Z
2018-03-13T12:57:46.000Z
UnitTests/HostVectorTests.cpp
pmontalb/CudaLight
390efb41da88245b2f5909b84213fb5839d505cf
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <Vector.h> #include <algorithm> namespace clt { class HostVectorTests: public ::testing::Test { }; TEST_F(HostVectorTests, Allocation) { cl::test::vec v1(10, 1.2345f); cl::test::dvec v2(10, 1.2345); } TEST_F(HostVectorTests, Copy) { cl::test::vec v1(10, 1.2345f); cl::test::vec v2(v1); ASSERT_TRUE(v1 == v2); cl::test::dvec v3(10, 1.2345); cl::test::dvec v4(v3); ASSERT_TRUE(v3 == v4); cl::test::ivec v5(10, 10); cl::test::ivec v6(v5); ASSERT_TRUE(v5 == v6); } TEST_F(HostVectorTests, Linspace) { cl::test::vec v = cl::test::vec::LinSpace(0.0, 1.0, 10); auto _v = v.Get(); ASSERT_TRUE(std::fabs(_v[0] - 0.0f) <= 1e-7f); ASSERT_TRUE(std::fabs(_v[_v.size() - 1] - 1.0f) <= 1e-7f); } TEST_F(HostVectorTests, RandomUniform) { cl::test::vec v = cl::test::vec::RandomUniform(10, 1234); auto _v = v.Get(); for (const auto& iter : _v) ASSERT_TRUE(iter >= 0.0f && iter <= 1.0f); } TEST_F(HostVectorTests, RandomGaussian) { cl::test::vec v = cl::test::vec::RandomGaussian(10, 1234); v.Print(); } TEST_F(HostVectorTests, RandomShuffle) { cl::test::vec v = cl::test::vec::RandomGaussian(10, 1234); auto _v1 = v.Get(); cl::test::vec::RandomShuffle(v, 1273); auto _v2 = v.Get(); auto _v3 = v.Get(); std::sort(_v1.begin(), _v1.end()); std::sort(_v2.begin(), _v2.end()); for (size_t i = 0; i < _v2.size(); ++i) { ASSERT_DOUBLE_EQ(_v1[i], _v2[i]); ASSERT_NE(_v1[i], _v3[i]) << i; } } TEST_F(HostVectorTests, RandomShufflePair) { cl::test::vec u = cl::test::vec::RandomGaussian(10, 1234); cl::test::vec v = cl::test::vec::RandomGaussian(10, 1234); auto _u1 = v.Get(); auto _v1 = v.Get(); cl::test::vec::RandomShufflePair(u, v, 1273); auto _u2 = u.Get(); auto _u3 = u.Get(); auto _v2 = v.Get(); auto _v3 = v.Get(); std::sort(_v1.begin(), _v1.end()); std::sort(_v2.begin(), _v2.end()); std::sort(_u1.begin(), _u1.end()); std::sort(_u2.begin(), _u2.end()); for (size_t i = 0; i < _v2.size(); ++i) { ASSERT_DOUBLE_EQ(_u1[i], _u2[i]); ASSERT_DOUBLE_EQ(_v1[i], _v2[i]); ASSERT_NE(_u1[i], _u3[i]); ASSERT_NE(_v1[i], _v3[i]); // check permutation used the same indices unsigned j = 0; bool found = false; for (; j < _u2.size(); ++j) { if (std::fabs(_u3[j] - _u1[i]) < 1e-12f) { found = true; break; } } ASSERT_TRUE(found); unsigned k = 0; found = false; for (; k < _v2.size(); ++k) { if (std::fabs(_v3[k] - _v1[i]) < 1e-12f) { found = true; break; } } ASSERT_TRUE(found); ASSERT_EQ(j, k); } } TEST_F(HostVectorTests, EuclideanNorm) { cl::test::vec u = cl::test::vec::RandomGaussian(10, 1234); auto _u = u.Get(); auto norm = u.EuclideanNorm(); float normCpu = 0.0; for (auto& x : _u) normCpu += x * x; ASSERT_NEAR(normCpu, norm * norm, 1e-6); } } // namespace clt
20.545455
60
0.579646
[ "vector" ]
8d5eaed65a6f4d1c3064e2e8dc77d5e4a17b2938
5,344
cpp
C++
src/Graphics/GLSLProgram.cpp
shvrd/engine
88a8cd30bcdd6c815a16497e6ba54eea70b6c2df
[ "MIT" ]
null
null
null
src/Graphics/GLSLProgram.cpp
shvrd/engine
88a8cd30bcdd6c815a16497e6ba54eea70b6c2df
[ "MIT" ]
null
null
null
src/Graphics/GLSLProgram.cpp
shvrd/engine
88a8cd30bcdd6c815a16497e6ba54eea70b6c2df
[ "MIT" ]
null
null
null
// // Created by thekatze on 06/02/18. // #include "GLSLProgram.h" #include "../Util/Logger.h" #include "../Util/Constants.h" #include <fstream> #include <vector> GLSLProgram::GLSLProgram() : programID(0), vertexShaderID(0), fragmentShaderID(0), numAttributes(0), compileStatus(0x00) {} GLSLProgram::~GLSLProgram() = default; /** * Creates a GLSL Shaderprogram using a vertex- and a fragmentshader source file. * @param vertexShaderPath Relative file path to the vertex shader source file * @param fragmentShaderPath Relative file path to the fragment shader source file */ void GLSLProgram::compileShaders(const std::string &vertexShaderPath, const std::string &fragmentShaderPath) { programID = glCreateProgram(); vertexShaderID = glCreateShader(GL_VERTEX_SHADER); if (vertexShaderID == 0) { Logger::error("Creating vertex shader failed."); Logger::terminate(Constants::STATUS_FAILED); } fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); if (fragmentShaderID == 0) { Logger::error("Creating fragment shader failed."); Logger::terminate(Constants::STATUS_FAILED); compileStatus |= FRAGMENT_SHADER_FAILED; } compileShader(vertexShaderPath, vertexShaderID); compileShader(fragmentShaderPath, fragmentShaderID); } /** * Links the shader source files. Requires the shaders to be compiled first. */ void GLSLProgram::linkShaders() { if (vertexShaderID == 0 || fragmentShaderID == 0) { Logger::error("Shaders have no id, thus shaders were not allocated."); return; } //Attach shaders glAttachShader(programID, vertexShaderID); glAttachShader(programID, fragmentShaderID); glLinkProgram(programID); //Error Checking GLint isLinked = 0; glGetProgramiv(programID, GL_LINK_STATUS, &isLinked); if (isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &maxLength); std::vector<char> errorLog(maxLength); glGetProgramInfoLog(programID, maxLength, &maxLength, &errorLog[0]); Logger::error("Shaderprogram failed to link shaders"); Logger::error(std::string(errorLog.begin(), errorLog.end())); //Prevent Leaking glDeleteProgram(programID); glDeleteShader(vertexShaderID); glDeleteShader(fragmentShaderID); } else { compileStatus |= COMPILE_SUCCESS; } //Detach Shaders after successful link glDetachShader(programID, vertexShaderID); glDetachShader(programID, fragmentShaderID); glDeleteShader(vertexShaderID); glDeleteShader(fragmentShaderID); } /** * Helper function that reads a shaderfile and compiles it. * @param filePath Filepath for the shaderfile * @param shaderID The ID to bind the shader to */ void GLSLProgram::compileShader(const std::string &filePath, GLuint shaderID) { //Read the file std::ifstream shaderFile(filePath); if (shaderFile.fail()) { perror(filePath.c_str()); Logger::error("Failed to open " + filePath); Logger::terminate(Constants::STATUS_FAILED); } std::string fileContents; std::string line; while (std::getline(shaderFile, line)) { fileContents += line + "\n"; } shaderFile.close(); //Compile the shader //Jank - You can't pass the contents in one line const char *contentsPtr = fileContents.c_str(); glShaderSource(shaderID, 1, &contentsPtr, nullptr); glCompileShader(shaderID); GLint success = 0; glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { GLint maxLength; glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &maxLength); std::vector<char> errorLog(maxLength); glGetShaderInfoLog(shaderID, maxLength, &maxLength, &errorLog[0]); Logger::error(std::string(errorLog.begin(), errorLog.end())); Logger::error("Shader failed to compile"); glDeleteShader(shaderID); compileStatus |= SHADER_COMPILE_FAILED; if (shaderID == fragmentShaderID) { compileStatus |= FRAGMENT_SHADER_FAILED; } if (shaderID == vertexShaderID) { compileStatus |= VERTEX_SHADER_FAILED; } } } /** * Adds a vertex attribute * @param attributeName The attribute identifier */ void GLSLProgram::addAttribute(const std::string &attributeName) { glBindAttribLocation(programID, numAttributes++, attributeName.c_str()); } /** * Binds the GLSLProgram (Shader) */ void GLSLProgram::bind() { glUseProgram(programID); for (int i = 0; i < numAttributes; i++) { glEnableVertexAttribArray(i); } } /** * Unbinds the GLSLProgram */ void GLSLProgram::unbind() { glUseProgram(0); for (int i = 0; i < numAttributes; i++) { glDisableVertexAttribArray(i); } } /** * Finds a uniform variable in a shaderprogram and returns its location. * @param uniformName The uniform string to find. * @return Returns the identifier for the Uniform. */ GLint GLSLProgram::getUniformLocation(const std::string &uniformName) { GLint location = glGetUniformLocation(programID, uniformName.c_str()); if (location == GL_INVALID_INDEX) { Logger::warning("Uniform " + uniformName + " not found in shader!"); } return location; }
28.731183
123
0.680202
[ "vector" ]
8d697164b291e1b5b39c4b105626ce02c329fe47
17,980
cc
C++
cc/accounting/privacy_loss_distribution.cc
dibakch/differential-privacy
ae9c6b6d5b7e772837ae336d1b3092683481ec16
[ "Apache-2.0" ]
2,550
2019-09-04T13:13:24.000Z
2022-03-31T16:05:50.000Z
cc/accounting/privacy_loss_distribution.cc
fbalicchia/differential-privacy
099080e49c4c047802d785bc818898c0caf84d45
[ "Apache-2.0" ]
90
2019-09-10T15:37:10.000Z
2022-03-28T12:55:03.000Z
cc/accounting/privacy_loss_distribution.cc
fbalicchia/differential-privacy
099080e49c4c047802d785bc818898c0caf84d45
[ "Apache-2.0" ]
324
2019-09-05T11:52:06.000Z
2022-03-31T03:30:26.000Z
// Copyright 2020 Google LLC // // 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 // // https://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 "accounting/privacy_loss_distribution.h" #include <algorithm> #include <cmath> #include <vector> #include "absl/status/status.h" #include "base/statusor.h" #include "absl/strings/str_format.h" #include "accounting/common/common.h" #include "accounting/convolution.h" #include "accounting/privacy_loss_mechanism.h" #include "proto/accounting/privacy-loss-distribution.pb.h" #include "base/status_macros.h" namespace differential_privacy { namespace accounting { std::unique_ptr<PrivacyLossDistribution> PrivacyLossDistribution::Create( const ProbabilityMassFunction& pmf_lower, const ProbabilityMassFunction& pmf_upper, EstimateType estimate_type, double discretization_interval, double mass_truncation_bound) { double infinity_mass = 0; for (auto [outcome_upper, mass_upper] : pmf_upper) { if (pmf_lower.count(outcome_upper) == 0) { // When an outcome only appears in the upper distribution but not in the // lower distribution, it must be counted in infinity_mass as such an // outcome contributes to the hockey stick divergence. infinity_mass += mass_upper; } } // Compute non-discretized probability mass function for the PLD. ProbabilityMassFunctionOf<double> pmf; for (auto [outcome_lower, mass_lower] : pmf_lower) { if (pmf_upper.count(outcome_lower) != 0) { // This outcome is in both pmf_lower and pmf_upper. double logged_mass_lower = std::log(mass_lower); double logged_mass_upper = std::log(pmf_upper.at(outcome_lower)); if (logged_mass_upper > mass_truncation_bound) { // Adding this to the distribution. double privacy_loss_value = logged_mass_upper - logged_mass_lower; pmf[privacy_loss_value] += pmf_upper.at(outcome_lower); } else if (estimate_type == EstimateType::kPessimistic) { // When the probability mass of mu_upper at the outcome is no more than // the threshold and we would like to get a pessimistic estimate, // account for this in infinity_mass. infinity_mass += pmf_upper.at(outcome_lower); } } } // Discretize the probability mass so that the values are integer multiples // of value_discretization_interval. ProbabilityMassFunction rounded_pmf; for (auto [outcome, mass] : pmf) { int key; if (estimate_type == EstimateType::kPessimistic) { key = static_cast<int>(std::ceil(outcome / discretization_interval)); } else { key = static_cast<int>(std::floor(outcome / discretization_interval)); } rounded_pmf[key] += mass; } return absl::WrapUnique(new PrivacyLossDistribution( discretization_interval, infinity_mass, rounded_pmf, estimate_type)); } std::unique_ptr<PrivacyLossDistribution> PrivacyLossDistribution::CreateIdentity(double discretization_interval) { return absl::WrapUnique( new PrivacyLossDistribution(discretization_interval, /*infinity_mass=*/0, /*probability_mass_function=*/{{0, 1}})); } std::unique_ptr<PrivacyLossDistribution> PrivacyLossDistribution::CreateForAdditiveNoise( const AdditiveNoisePrivacyLoss& mechanism_privacy_loss, EstimateType estimate_type, double discretization_interval) { ProbabilityMassFunction pmf; auto round = [estimate_type](double x) { return estimate_type == EstimateType::kPessimistic ? std::ceil(x) : std::floor(x); }; PrivacyLossTail tail = mechanism_privacy_loss.PrivacyLossDistributionTail(); double infinity_mass = 0; for (auto [privacy_loss, probability_mass] : tail.probability_mass_function) { if (privacy_loss != std::numeric_limits<double>::infinity()) { double rounded_value = round(privacy_loss / discretization_interval); pmf[rounded_value] += probability_mass; } else { infinity_mass = probability_mass; } } if (mechanism_privacy_loss.Discrete() == NoiseType::kDiscrete) { for (int x = std::ceil(tail.lower_x_truncation); x <= std::floor(tail.upper_x_truncation); x++) { double rounded_value = round(mechanism_privacy_loss.PrivacyLoss(x) / discretization_interval); double probability_mass = mechanism_privacy_loss.NoiseCdf(x) - mechanism_privacy_loss.NoiseCdf(x - 1); pmf[rounded_value] += probability_mass; } } else { double lower_x = tail.lower_x_truncation; double upper_x; double rounded_down_value = std::floor( mechanism_privacy_loss.PrivacyLoss(lower_x) / discretization_interval); while (lower_x < tail.upper_x_truncation) { upper_x = std::min(tail.upper_x_truncation, mechanism_privacy_loss.InversePrivacyLoss( discretization_interval * rounded_down_value)); // Each x in [lower_x, upper_x] results in privacy loss that lies in // [discretization_interval * rounded_down_value, // discretization_interval * (rounded_down_value + 1)] double probability_mass = mechanism_privacy_loss.NoiseCdf(upper_x) - mechanism_privacy_loss.NoiseCdf(lower_x); double rounded_value = round(rounded_down_value + 0.5); pmf[rounded_value] += probability_mass; lower_x = upper_x; rounded_down_value -= 1; } } return absl::WrapUnique(new PrivacyLossDistribution( discretization_interval, infinity_mass, pmf, estimate_type)); } base::StatusOr<std::unique_ptr<PrivacyLossDistribution>> PrivacyLossDistribution::CreateForRandomizedResponse( double noise_parameter, int num_buckets, EstimateType estimate_type, double discretization_interval) { if (noise_parameter <= 0 || noise_parameter >= 1) { return absl::InvalidArgumentError(absl::StrFormat( "Noise parameter %lf should be strictly between 0 and 1.", noise_parameter)); } if (num_buckets <= 1) { return absl::InvalidArgumentError(absl::StrFormat( "Number of buckets %i should be strictly greater than 1.", num_buckets)); } ProbabilityMassFunction rounded_pmf; auto round = [estimate_type](double x) { return estimate_type == EstimateType::kPessimistic ? std::ceil(x) : std::floor(x); }; // Probability that the output is equal to the input, i.e., Pr[R(x) = x] double probability_output_equal_input = (1 - noise_parameter) + noise_parameter / num_buckets; // Probability that the output is equal to a specific bucket that is not the // input, i.e., Pr[R(x') = x] for x' != x. double probability_output_not_input = noise_parameter / num_buckets; // Add privacy loss for the case o = x. double rounded_value = round( std::log(probability_output_equal_input / probability_output_not_input) / discretization_interval); rounded_pmf[rounded_value] += probability_output_equal_input; // Add privacy loss for the case o = x' rounded_value = round( std::log(probability_output_not_input / probability_output_equal_input) / discretization_interval); rounded_pmf[rounded_value] += probability_output_not_input; // Add privacy loss for the case o != x, x' rounded_pmf[0] += probability_output_not_input * (num_buckets - 2); return absl::WrapUnique(new PrivacyLossDistribution( discretization_interval, /*infinity_mass=*/0, rounded_pmf, estimate_type)); } base::StatusOr<std::unique_ptr<PrivacyLossDistribution>> PrivacyLossDistribution::CreateForLaplaceMechanism( double parameter, double sensitivity, EstimateType estimate_type, double discretization_interval) { ASSIGN_OR_RETURN(std::unique_ptr<LaplacePrivacyLoss> privacy_loss, LaplacePrivacyLoss::Create(parameter, sensitivity)); return CreateForAdditiveNoise(*privacy_loss, estimate_type, discretization_interval); } base::StatusOr<std::unique_ptr<PrivacyLossDistribution>> PrivacyLossDistribution::CreateForDiscreteLaplaceMechanism( double parameter, int sensitivity, EstimateType estimate_type, double discretization_interval) { ASSIGN_OR_RETURN(std::unique_ptr<DiscreteLaplacePrivacyLoss> privacy_loss, DiscreteLaplacePrivacyLoss::Create(parameter, sensitivity)); return CreateForAdditiveNoise(*privacy_loss, estimate_type, discretization_interval); } base::StatusOr<std::unique_ptr<PrivacyLossDistribution>> PrivacyLossDistribution::CreateForGaussianMechanism( double standard_deviation, double sensitivity, EstimateType estimate_type, double discretization_interval, double mass_truncation_bound) { ASSIGN_OR_RETURN( std::unique_ptr<GaussianPrivacyLoss> privacy_loss, GaussianPrivacyLoss::Create(standard_deviation, sensitivity, estimate_type, mass_truncation_bound)); return CreateForAdditiveNoise(*privacy_loss, estimate_type, discretization_interval); } base::StatusOr<std::unique_ptr<PrivacyLossDistribution>> PrivacyLossDistribution::CreateForDiscreteGaussianMechanism( double sigma, int sensitivity, EstimateType estimate_type, double discretization_interval, absl::optional<int> truncation_bound) { ASSIGN_OR_RETURN(std::unique_ptr<DiscreteGaussianPrivacyLoss> privacy_loss, DiscreteGaussianPrivacyLoss::Create(sigma, sensitivity, truncation_bound)); return CreateForAdditiveNoise(*privacy_loss, estimate_type, discretization_interval); } std::unique_ptr<PrivacyLossDistribution> PrivacyLossDistribution::CreateForPrivacyParameters( EpsilonDelta epsilon_delta, double discretization_interval) { double epsilon = epsilon_delta.epsilon; double delta = epsilon_delta.delta; ProbabilityMassFunction rounded_pmf = { {std::ceil(epsilon / discretization_interval), (1 - delta) / (1 + std::exp(-epsilon))}, {std::ceil(-epsilon / discretization_interval), (1 - delta) / (1 + std::exp(epsilon))}, }; return absl::WrapUnique(new PrivacyLossDistribution( discretization_interval, /*infinity_mass=*/delta, rounded_pmf)); } absl::Status PrivacyLossDistribution::ValidateComposition( const PrivacyLossDistribution& other_pld) const { if (other_pld.DiscretizationInterval() != discretization_interval_) { return absl::InvalidArgumentError(absl::StrFormat( "Cannot compose, discretization intervals are different " "- %lf vs %lf", other_pld.DiscretizationInterval(), discretization_interval_)); } if (other_pld.GetEstimateType() != estimate_type_) { return absl::InvalidArgumentError( "Cannot compose, estimate types are different"); } return absl::OkStatus(); } absl::Status PrivacyLossDistribution::Compose( const PrivacyLossDistribution& other_pld, double tail_mass_truncation) { RETURN_IF_ERROR(ValidateComposition(other_pld)); double new_infinity_mass = infinity_mass_ + other_pld.InfinityMass() - infinity_mass_ * other_pld.InfinityMass(); if (estimate_type_ == EstimateType::kPessimistic) { // In the pessimistic case, the truncated probability mass needs to be // treated as if they were infinity. new_infinity_mass += tail_mass_truncation; } ProbabilityMassFunction new_pmf = Convolve( probability_mass_function_, other_pld.Pmf(), tail_mass_truncation); probability_mass_function_ = new_pmf; infinity_mass_ = new_infinity_mass; return absl::OkStatus(); } base::StatusOr<double> PrivacyLossDistribution::GetDeltaForEpsilonForComposedPLD( const PrivacyLossDistribution& other_pld, double epsilon) const { RETURN_IF_ERROR(ValidateComposition(other_pld)); UnpackedProbabilityMassFunction this_pmf = UnpackProbabilityMassFunction(probability_mass_function_); UnpackedProbabilityMassFunction other_pmf = UnpackProbabilityMassFunction(other_pld.probability_mass_function_); // Compute the hockey stick divergence using equation (2) in the // supplementary material. other_cumulative_upper_mass below represents the // summation in equation (3) and other_cumulative_lower_mass represents the // summation in equation (4). double other_cumulative_upper_mass = 0; double other_cumulative_lower_mass = 0; int current_idx = other_pmf.items.size() - 1; double delta = 0; for (int this_idx = 0; this_idx < this_pmf.items.size(); ++this_idx) { double this_privacy_loss = discretization_interval_ * (this_idx + this_pmf.min_key); double this_probability_mass = this_pmf.items[this_idx]; while (current_idx >= 0) { double other_privacy_loss = other_pld.discretization_interval_ * (current_idx + other_pmf.min_key); if (other_privacy_loss + this_privacy_loss <= epsilon) break; other_cumulative_upper_mass += other_pmf.items[current_idx]; other_cumulative_lower_mass += other_pmf.items[current_idx] / std::exp(other_privacy_loss); --current_idx; } delta += this_probability_mass * (other_cumulative_upper_mass - std::exp(epsilon - this_privacy_loss) * other_cumulative_lower_mass); } // The probability that the composed privacy loss is infinite. double composed_infinity_mass = infinity_mass_ + other_pld.InfinityMass() - infinity_mass_ * other_pld.InfinityMass(); return delta + composed_infinity_mass; } void PrivacyLossDistribution::Compose(int num_times, double tail_mass_truncation) { double new_infinity_mass = 1 - std::pow((1 - infinity_mass_), num_times); // Currently support truncation only for pessimistic estimates. double effective_tail_mass_truncation = estimate_type_ == EstimateType::kPessimistic ? tail_mass_truncation : 0.0; ProbabilityMassFunction new_pmf = Convolve( probability_mass_function_, num_times, effective_tail_mass_truncation); probability_mass_function_ = new_pmf; infinity_mass_ = new_infinity_mass + effective_tail_mass_truncation; } double PrivacyLossDistribution::GetDeltaForEpsilon(double epsilon) const { double divergence = infinity_mass_; for (auto [outcome, p] : probability_mass_function_) { auto val = outcome * discretization_interval_; if (val > epsilon && p > 0) { divergence += (1 - std::exp(epsilon - val)) * p; } } return divergence; } double PrivacyLossDistribution::GetEpsilonForDelta(double delta) const { if (infinity_mass_ > delta) return std::numeric_limits<double>::infinity(); double mass_upper = infinity_mass_; double mass_lower = 0; // Sort outcomes in reverse order. std::vector<int> outcomes; for (auto [outcome, p] : probability_mass_function_) { outcomes.push_back(outcome); } std::sort(outcomes.rbegin(), outcomes.rend()); for (int outcome : outcomes) { auto val = outcome * discretization_interval_; if (mass_upper > delta && mass_lower > 0 && mass_upper - std::exp(val) * mass_lower >= delta) { // Epsilon is greater than or equal to val. break; } double pmf_val = probability_mass_function_.at(outcome); mass_upper += pmf_val; mass_lower += std::exp(-val) * pmf_val; if (mass_upper >= delta && mass_lower == 0) { // This only occurs when val is very large, which results in exp(-val) // being treated as zero. return std::max(0.0, val); } } if (mass_upper <= mass_lower + delta) return 0; return std::log((mass_upper - delta) / mass_lower); } base::StatusOr<serialization::PrivacyLossDistribution> PrivacyLossDistribution::Serialize() const { if (estimate_type_ == EstimateType::kOptimistic) { return absl::InvalidArgumentError( "Serialization not supported for optimistic estimates."); } serialization::PrivacyLossDistribution output; serialization::ProbabilityMassFunction* serialized_pmf = output.mutable_pessimistic_pmf(); UnpackedProbabilityMassFunction unpacked_pmf = UnpackProbabilityMassFunction(probability_mass_function_); serialized_pmf->set_infinity_mass(infinity_mass_); serialized_pmf->set_discretization_interval(discretization_interval_); serialized_pmf->set_min_key(unpacked_pmf.min_key); *serialized_pmf->mutable_values() = {unpacked_pmf.items.begin(), unpacked_pmf.items.end()}; return output; } base::StatusOr<std::unique_ptr<PrivacyLossDistribution>> PrivacyLossDistribution::Deserialize( const serialization::PrivacyLossDistribution& proto) { if (!proto.has_pessimistic_pmf()) { return absl::InvalidArgumentError("PMF must be set."); } serialization::ProbabilityMassFunction pmf = proto.pessimistic_pmf(); UnpackedProbabilityMassFunction unpacked_pmf; unpacked_pmf.min_key = pmf.min_key(); unpacked_pmf.items = std::vector<double>(pmf.values().begin(), pmf.values().end()); return absl::WrapUnique(new PrivacyLossDistribution( pmf.discretization_interval(), pmf.infinity_mass(), /*probability_mass_function=*/ CreateProbabilityMassFunction(unpacked_pmf))); } } // namespace accounting } // namespace differential_privacy
40.863636
80
0.715072
[ "vector" ]
8d6bb0bc456dac55bc6c90b4ded43fdc6f09cb6e
8,617
cpp
C++
samples/bv3vlogic/bv3vlogic.cpp
coinhu/BitMagic
64b53a056e3fde88620fdedda3395eb48aadfadb
[ "Apache-2.0" ]
1
2021-07-25T10:50:36.000Z
2021-07-25T10:50:36.000Z
samples/bv3vlogic/bv3vlogic.cpp
coinhu/BitMagic
64b53a056e3fde88620fdedda3395eb48aadfadb
[ "Apache-2.0" ]
null
null
null
samples/bv3vlogic/bv3vlogic.cpp
coinhu/BitMagic
64b53a056e3fde88620fdedda3395eb48aadfadb
[ "Apache-2.0" ]
null
null
null
/* Copyright(c) 2002-2017 Anatoliy Kuznetsov(anatoliy_kuznetsov at yahoo.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For more information please visit: http://bitmagic.io */ /** \example bv3vlogic.cpp Example demonstrates variety three-valued logic. https://en.wikipedia.org/wiki/Three-valued_logic <a href="https://en.wikipedia.org/wiki/Three-valued_logic">Three-valued logic</a> */ /*! \file bv3vlogic.cpp \brief Example: Kleene algebra operations BitMagic implements 3-value (Kleene) logic using two separate bit-vectors: bit-vector of values and bit-vector of knowns. bit-vector of vlaues contains 1s in the positions of true bit-vector of NULLs contains 1s where values in known (or set) The convention is that unknown elements (0s in the NULL vector) MUST NOT have 1s in the corresponding positions of the value bit-vector so "unknown TRUE" is not a correct situation. */ #include <iostream> #include <vector> #include <cassert> #include "bm.h" #include "bm3vl.h" #include "bmundef.h" /* clear the pre-proc defines from BM */ using namespace std; /** Print 3-value vector */ static void PrintKleeneVector(const bm::bvector<>& bv_v, const bm::bvector<>& bv_null) { bm::bvector<>::enumerator en_n = bv_null.first(); auto prev = *en_n; if (prev > 0) prev = 0; for ( ;en_n.valid(); ++en_n) { auto curr = *en_n; for (auto i = prev; i < curr; ++i) cout << i << ": NULL" << endl; bool v = bv_v.test(curr); cout << curr << ": " << (v ? "true" : "false") << endl; prev = curr + 1; } // for en_n cout << endl; } /** This demo shows how to use bm::set_value_kleene and bm::get_value_kleene functions to set values into pair of vectors (value vector and knowns vector) Kleene algebra operates on 3 values, which are by convention read as: -1 (known false), 0 (unknown), 1 (known true). bm::set_value_kleene takes a pair of vectors, position and an int value to set value in a pair of bit-vectors representing value and knowns Please note that this is the easy but relatively slow method to init the vectors since because it uses random access initialization. */ static void Set3VL_ValueDemo() { bm::bvector<> bv_v; // (true/false) values bit-vector bm::bvector<> bv_null; // (known/unknown (or NULL) values bit-vector int v = 0; // start with the unknown for (unsigned i = 0; i < 10; ++i) { bm::set_value_kleene(bv_v, bv_null, i, v); auto v1 = bm::get_value_kleene(bv_v, bv_null, i); assert(v == v1); v += 1; if (v > 1) v = -1; } BM_DECLARE_TEMP_BLOCK(tb) bv_v.optimize(tb); bv_null.optimize(tb); PrintKleeneVector(bv_v, bv_null); } /** Faster way to initialize Kleene bit-vectors via bulk_insert_iterator */ static void Set3VL_ValueDemo2() { bm::bvector<> bv_v; // (true/false) values bit-vector bm::bvector<> bv_null; // (known/unknown (or NULL) values bit-vector // use insert iterators to load the vectors { bm::bvector<>::bulk_insert_iterator iit_v = bv_v.inserter(); bm::bvector<>::bulk_insert_iterator iit_n = bv_null.inserter(); for (unsigned i = 0; i < 13; i+=3) { if (i & 1) // add only true values as indexes of set bits via insert iterator { iit_v = i; } // set the known bit for both true AND false values iit_n = i; } // flush the insert iterators to empty the temp.buffers // it is best to do it explicitly (it can throw exceptions) iit_v.flush(); iit_n.flush(); } // init used to guarantee that value bit-vector would not contain // "unknown" true values, which is a requirement of BM library to be able to // correct 3-value logical ANDs and ORs // // If you are absolutely sure that you did not set true values for unknowns // then you do not need this call // bm::init_kleene(bv_v, bv_null); // optimize bit-vectors after initalization // BM_DECLARE_TEMP_BLOCK(tb) bv_v.optimize(tb); bv_null.optimize(tb); PrintKleeneVector(bv_v, bv_null); } /** Generate Kleene vector (as two bit-vectors) */ static void GenerateDemoVector(bm::bvector<>& bv_v, bm::bvector<>& bv_null) { int v = 0; // start with the unknown for (unsigned i = 0; i < 10; ++i) { bm::set_value_kleene(bv_v, bv_null, i, v); v += 1; if (v > 1) v = -1; } // for // optimize bit-vectors after initalization // BM_DECLARE_TEMP_BLOCK(tb) bv_v.optimize(tb); bv_null.optimize(tb); } /** Demo for 3-value logic (Kleene) NOT */ static void Set3VL_InvertDemo() { bm::bvector<> bv_v; // (true/false) values bit-vector bm::bvector<> bv_null; // (known/unknown (or NULL) values bit-vector GenerateDemoVector(bv_v, bv_null); cout << "Input vector:" << endl; PrintKleeneVector(bv_v, bv_null); bm::invert_kleene(bv_v, bv_null); // 3-value logic NOT cout << "Inverted vector:" << endl; PrintKleeneVector(bv_v, bv_null); } /** Demo for 3-value logic (Kleene) AND Kleene algebra AND produces known FALSE when known FALSE meets UNKNOWN (false) */ static void Set3VL_AndDemo() { bm::bvector<> bv_v1; // (true/false) values bit-vector bm::bvector<> bv_null1; // (known/unknown (or NULL) values bit-vector GenerateDemoVector(bv_v1, bv_null1); bm::bvector<> bv_v2; // (true/false) values bit-vector bm::bvector<> bv_null2; // (known/unknown (or NULL) values bit-vector bm::set_value_kleene(bv_v2, bv_null2, 0, 0); // idx = 0 (unknown) bm::set_value_kleene(bv_v2, bv_null2, 1, 1); // idx = 1 (known true) bm::set_value_kleene(bv_v2, bv_null2, 2, -1); // idx = 2 (known false) bm::bvector<> bv_v_t, bv_null_t; // bv_v_t := bv_v2 & bv_v1 bm::and_kleene(bv_v_t, bv_null_t, bv_v2, bv_null2, bv_v1, bv_null1); // 3-value logic AND // bv_v2 and bv_null2 are modified in place: // bv_v2 &= bv_v1 bm::and_kleene(bv_v2, bv_null2, bv_v1, bv_null1); // 3-value logic AND bool b = bv_v_t.equal(bv_v2); assert(b); b = bv_null_t.equal(bv_null2); assert(b); cout << "AND vector:" << endl; PrintKleeneVector(bv_v2, bv_null2); } /** Demo for 3-value logic (Kleene) OR Kleene algebra OR produces known TRUE when known TRUE meets UNKNOWN (false) */ static void Set3VL_ORDemo() { bm::bvector<> bv_v1; // (true/false) values bit-vector bm::bvector<> bv_null1; // (known/unknown (or NULL) values bit-vector GenerateDemoVector(bv_v1, bv_null1); bm::bvector<> bv_v2; // (true/false) values bit-vector bm::bvector<> bv_null2; // (known/unknown (or NULL) values bit-vector bm::set_value_kleene(bv_v2, bv_null2, 0, 1); // idx = 0 (known true) bm::set_value_kleene(bv_v2, bv_null2, 1, 0); // idx = 1 (NULL) bm::set_value_kleene(bv_v2, bv_null2, 2, -1); // idx = 2 (known false) bm::bvector<> bv_v_t, bv_null_t; // bv_v_t := bv_v2 | bv_v1 bm::or_kleene(bv_v_t, bv_null_t, bv_v2, bv_null2, bv_v1, bv_null1); // 3-value logic AND // bv_v2 and bv_null2 are modified in place: // bv_v2 |= bv_v1 bm::or_kleene(bv_v2, bv_null2, bv_v1, bv_null1); // 3-value logic OR bool b = bv_v_t.equal(bv_v2); assert(b); b = bv_null_t.equal(bv_null2); assert(b); cout << "OR vector:" << endl; PrintKleeneVector(bv_v2, bv_null2); } int main(void) { try { cout << endl << "3VL Set values:" << endl << endl; Set3VL_ValueDemo(); Set3VL_ValueDemo2(); cout << endl << "3VL Invert vector:" << endl << endl; Set3VL_InvertDemo(); cout << endl << "3VL AND:" << endl << endl; Set3VL_AndDemo(); cout << endl << "3VL OR:" << endl << endl; Set3VL_ORDemo(); } catch(std::exception& ex) { std::cerr << ex.what() << std::endl; } return 0; }
27.977273
93
0.632123
[ "vector" ]
8d714ba0384ba9b775ff9d1b48e63d4cc01d95df
71,251
cpp
C++
Source/Rendering/DirectX/vaRenderDeviceContextDX12.cpp
s-nase/vanilla
e2e26ed8037cff980ea86b5c6c21b979d82b1e36
[ "MIT" ]
8
2021-12-17T01:46:34.000Z
2022-03-25T09:29:45.000Z
Source/Rendering/DirectX/vaRenderDeviceContextDX12.cpp
s-nase/XeGTAO
11e439c33e3dd7c1e4ea0fc73733ca840bc95bec
[ "MIT" ]
null
null
null
Source/Rendering/DirectX/vaRenderDeviceContextDX12.cpp
s-nase/XeGTAO
11e439c33e3dd7c1e4ea0fc73733ca840bc95bec
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Original work Copyright (C) 2016-2021, Intel Corporation // Modified work Copyright (C) 2022, Vanilla Blue team // // SPDX-License-Identifier: MIT /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): Filip Strugar (filip.strugar@gmail.com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "vaRenderDeviceContextDX12.h" #include "vaTextureDX12.h" #include "vaRenderBuffersDX12.h" #include "Rendering/vaTextureHelpers.h" #include "Rendering/DirectX/vaSceneRaytracingDX12.h" #include "Rendering/DirectX/vaRenderMaterialDX12.h" #ifdef VA_TASKFLOW_INTEGRATION_ENABLED #include "IntegratedExternals/vaTaskflowIntegration.h" #endif // Attempt to solve this warning from PIX: // At one point during the capture there were over 2000001 shader - visible CBV / SRV / UAV descriptors in all CBV / SRV / UAV descriptor heaps.There were also over 128 shader - visible sampler descriptors at one( possibly different ) point during the capture. // On some hardware, having more than 1 million CBV / SRV / UAV descriptors or more than 2048 samplers across all descriptor heaps can make it expensive to switch between descriptor heaps.PIX has detected that the application switched between descriptor heaps at least once during an ExecuteCommandLists( ) call in this capture. // Consider reducing the number of descriptors in the application to avoid the risk of this. // #define FLUSH_ON_DESCRIPTOR_HEAP_CHANGE // #include "Rendering/DirectX/vaRenderGlobalsDX11.h" // #include "vaResourceFormatsDX11.h" #ifdef _DEBUG #define VA_SET_UNUSED_DESC_TO_NULL #endif using namespace Vanilla; // // used to make Gather using UV slightly off the border (so we get the 0,0 1,0 0,1 1,1 even if there's a minor calc error, without adding the half pixel offset) // static const float c_minorUVOffset = 0.00006f; // less than 0.5/8192 vaRenderDeviceContextBaseDX12::vaRenderDeviceContextBaseDX12( vaRenderDevice & device, const shared_ptr<vaRenderDeviceContextDX12> & master, int instanceIndex, bool useBundles ) : vaRenderDeviceContext( device, master, instanceIndex ), m_deviceDX12( AsDX12(device) ), m_useBundles( useBundles ) { //m_localGraphicsPSOCache.max_load_factor(0.5f); HRESULT hr; bool workerContext = master != nullptr; wstring commandListName = (workerContext)?(L"WorkerList"):(L"MasterList"); if( workerContext ) commandListName += vaStringTools::Format( L"%02d", instanceIndex ); if( m_useBundles ) { assert( workerContext ); } // only worker contexts can be bundle type D3D12_COMMAND_LIST_TYPE commandListType; if( m_useBundles ) commandListType = D3D12_COMMAND_LIST_TYPE_BUNDLE; else commandListType = D3D12_COMMAND_LIST_TYPE_DIRECT; auto& d3d12Device = AsDX12( device ).GetPlatformDevice( ); // Create command allocator for each frame. for( uint i = 0; i < vaRenderDeviceDX12::c_BackbufferCount; i++ ) { V( d3d12Device->CreateCommandAllocator( commandListType, IID_PPV_ARGS( &m_commandAllocators[i] ) ) ); wstring name = commandListName + vaStringTools::Format( L"Allocator%d", i ); V( m_commandAllocators[i]->SetName( name.c_str( ) ) ); } uint32 currentFrame = AsDX12( GetRenderDevice( ) ).GetCurrentFrameFlipIndex( ); // Create the command list. ComPtr<ID3D12GraphicsCommandList> commandList; V( d3d12Device->CreateCommandList( 0, commandListType, m_commandAllocators[currentFrame].Get( ), nullptr, IID_PPV_ARGS( &commandList ) ) ); commandList.As( &m_commandList ); assert( commandList != nullptr ); V( m_commandList->SetName( commandListName.c_str( ) ) ); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. V( m_commandList->Close( ) ); } vaRenderDeviceContextBaseDX12::~vaRenderDeviceContextBaseDX12( ) { m_commandList.Reset( ); for( uint i = 0; i < vaRenderDeviceDX12::c_BackbufferCount; i++ ) m_commandAllocators[i].Reset( ); } void vaRenderDeviceContextDX12::PreAllocateTransientDescriptors( ) { assert( vaThreading::IsMainThread() ); if( m_nextTransientDesc_GlobalUAVs == -1 || m_nextTransientDesc_OutputsUAVs == -1 || m_nextTransientDesc_GlobalSRVs == -1 ) m_nextTransientDesc_Globals = -1; if( m_nextTransientDesc_Globals != -1 ) return; // beware, this can trigger flush and sync! m_nextTransientDesc_Globals = m_deviceDX12.TransientDescHeapAllocate( vaRenderDeviceDX12::DefaultRootSignatureParams::GlobalUAVSRVRangeSize ); // these are now just offsets used for copying descriptors - don't set them individually as a root parameter, it's all set through one above (m_nextTransientDesc_Globals) m_nextTransientDesc_GlobalUAVs = m_nextTransientDesc_Globals + vaRenderDeviceDX12::DefaultRootSignatureParams::DescriptorOffsetGlobalUAV; m_nextTransientDesc_OutputsUAVs = m_nextTransientDesc_Globals + vaRenderDeviceDX12::DefaultRootSignatureParams::DescriptorOffsetOutputsUAV; m_nextTransientDesc_GlobalSRVs = m_nextTransientDesc_Globals + vaRenderDeviceDX12::DefaultRootSignatureParams::DescriptorOffsetGlobalSRV; // share these with workers - these are all the same for all workers so the only thing they // need to do is bind the heaps, no need to fill them up! for( int i = 0; i < m_workersActive; i++ ) { m_workers[i]->m_nextTransientDesc_Globals = m_nextTransientDesc_Globals; m_workers[i]->m_nextTransientDesc_GlobalSRVs = m_nextTransientDesc_GlobalSRVs; m_workers[i]->m_nextTransientDesc_GlobalUAVs = m_nextTransientDesc_GlobalUAVs; m_workers[i]->m_nextTransientDesc_OutputsUAVs = m_nextTransientDesc_OutputsUAVs; } } void vaRenderDeviceContextBaseDX12::CommitTransientDescriptors( ) { assert( m_itemsStarted != vaRenderTypeFlags::None ); D3D12_GPU_DESCRIPTOR_HANDLE baseDesc = m_deviceDX12.TransientDescHeapComputeGPUHandle( m_nextTransientDesc_Globals ); if( ( m_itemsStarted & vaRenderTypeFlags::Graphics ) != 0 ) m_commandList->SetGraphicsRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::GlobalUAVSRVBase, baseDesc ); if( ( m_itemsStarted & vaRenderTypeFlags::Compute ) != 0 ) m_commandList->SetComputeRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::GlobalUAVSRVBase, baseDesc ); m_nextTransientDesc_Globals = -1; m_nextTransientDesc_GlobalUAVs = -1; m_nextTransientDesc_OutputsUAVs = -1; m_nextTransientDesc_GlobalSRVs = -1; // bindless! D3D12_GPU_DESCRIPTOR_HANDLE bindlessDesc = m_deviceDX12.GetBindlessDescHeapGPUHandle(); if( ( m_itemsStarted & vaRenderTypeFlags::Graphics ) != 0 ) { m_commandList->SetGraphicsRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::Bindless1SRVBase, bindlessDesc ); m_commandList->SetGraphicsRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::Bindless2SRVBase, bindlessDesc ); } if( ( m_itemsStarted & vaRenderTypeFlags::Compute ) != 0 ) { m_commandList->SetComputeRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::Bindless1SRVBase, bindlessDesc ); m_commandList->SetComputeRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::Bindless2SRVBase, bindlessDesc ); } } void vaRenderDeviceContextBaseDX12::BindDefaultStates( ) { assert( m_commandListReady ); m_deviceDX12.BindDefaultDescriptorHeaps( m_commandList.Get() ); m_commandList->SetGraphicsRootSignature( m_deviceDX12.GetDefaultGraphicsRootSignature() ); m_commandList->SetComputeRootSignature( m_deviceDX12.GetDefaultComputeRootSignature() ); // // some other default states // FLOAT defBlendFactor[4] = { 1, 1, 1, 1 }; // m_commandList->OMSetBlendFactor( defBlendFactor ); // If you pass NULL, the runtime uses or stores a blend factor equal to { 1, 1, 1, 1 }. // m_commandList->OMSetStencilRef( 0 ); m_currentTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; m_commandList->IASetPrimitiveTopology( m_currentTopology ); m_currentIndexBuffer = nullptr; m_commandList->IASetIndexBuffer( nullptr ); m_currentVertexBuffer = nullptr; m_commandList->IASetVertexBuffers( 0, 0, nullptr ); m_currentPSO = nullptr; // 1x1 is the default m_currentShadingRate = D3D12_SHADING_RATE_1X1; const vaRenderDeviceCapabilities & caps = GetRenderDevice().GetCapabilities(); if( m_commandList != nullptr && caps.VariableShadingRate.Tier1 ) m_commandList->RSSetShadingRate( m_currentShadingRate, nullptr ); // this is not needed for worker thread with bundles I think? ResetCachedOutputs( ); } void vaRenderDeviceContextBaseDX12::ResetAndInitializeCommandList( int currentFrame ) { if( !IsWorker() ) { assert( m_itemsStarted == vaRenderTypeFlags::None ); } assert( !m_commandListReady ); HRESULT hr; { VA_TRACE_CPU_SCOPE( Reset ); V( m_commandList->Reset( m_commandAllocators[currentFrame].Get(), nullptr ) ); } m_commandListReady = true; BindDefaultStates(); } void vaRenderDeviceContextDX12::ExecuteCommandList( ) { assert( GetRenderDevice().IsRenderThread() ); assert( m_itemsStarted == vaRenderTypeFlags::None ); assert( GetRenderDevice( ).IsFrameStarted( ) ); HRESULT hr; uint32 currentFrame = m_deviceDX12.GetCurrentFrameFlipIndex( ) ; assert( m_commandListReady ); V( m_commandList->Close() ); m_commandListReady = false; // Execute the command list. ID3D12CommandList* ppCommandLists[] = { m_commandList.Get() }; m_deviceDX12.GetCommandQueue()->ExecuteCommandLists( _countof(ppCommandLists), ppCommandLists ); m_itemsSubmittedAfterLastExecute = 0; #ifdef VA_D3D12_USE_DEBUG_LAYER_DRED hr = AsDX12( GetRenderDevice() ).GetPlatformDevice()->GetDeviceRemovedReason( ); if( hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_HUNG ) AsDX12( GetRenderDevice() ).DeviceRemovedHandler( ); #endif ResetAndInitializeCommandList( currentFrame ); // these are no longer valid m_nextTransientDesc_GlobalSRVs = -1; m_nextTransientDesc_GlobalUAVs = -1; m_nextTransientDesc_OutputsUAVs = -1; for( int i = 0; i < m_workersActive; i++ ) { m_workers[i]->m_nextTransientDesc_GlobalSRVs = -1; m_workers[i]->m_nextTransientDesc_GlobalUAVs = -1; m_workers[i]->m_nextTransientDesc_OutputsUAVs = -1; } } void vaRenderDeviceContextDX12::Flush( ) { assert( !IsWorker() ); ExecuteCommandList(); } void vaRenderDeviceContextBaseDX12::CommitOutputsRaw( vaRenderTypeFlags typeFlags, const vaRenderOutputs & outputs ) { typeFlags; D3D12_CPU_DESCRIPTOR_HANDLE RTVs[vaRenderOutputs::c_maxRTs]; //ID3D11UnorderedAccessView * UAVs[ c_maxUAVs]; D3D12_CPU_DESCRIPTOR_HANDLE DSV = { 0 }; int numRTVs = 0; for( int i = 0; i < vaRenderOutputs::c_maxRTs; i++ ) { RTVs[i] = { 0 }; if( outputs.RenderTargets[i] != nullptr ) { assert( ( typeFlags & vaRenderTypeFlags::Graphics ) != 0 ); const vaRenderTargetViewDX12* rtv = AsDX12( *outputs.RenderTargets[i] ).GetRTV( ); if( rtv != nullptr && rtv->IsCreated( ) ) { AsDX12( *outputs.RenderTargets[i] ).TransitionResource( *this, D3D12_RESOURCE_STATE_RENDER_TARGET ); RTVs[i] = rtv->GetCPUHandle( ); numRTVs = i + 1; } else { assert( false ); } // error, texture has no rtv but set as a render target } } D3D12_CPU_DESCRIPTOR_HANDLE* pDSV = nullptr; if( outputs.DepthStencil != nullptr ) { assert( ( typeFlags & vaRenderTypeFlags::Graphics ) != 0 ); const vaDepthStencilViewDX12* dsv = AsDX12( *outputs.DepthStencil ).GetDSV( ); if( dsv != nullptr && dsv->IsCreated( ) ) { AsDX12( *outputs.DepthStencil ).TransitionResource( *this, D3D12_RESOURCE_STATE_DEPTH_WRITE ); DSV = dsv->GetCPUHandle( ); pDSV = &DSV; } else { assert( false ); } // error, texture has no dsv but set as a render target } const vaViewport& vavp = outputs.Viewport; D3D12_VIEWPORT viewport; viewport.TopLeftX = (float)vavp.X; viewport.TopLeftY = (float)vavp.Y; viewport.Width = (float)vavp.Width; viewport.Height = (float)vavp.Height; viewport.MinDepth = vavp.MinDepth; viewport.MaxDepth = vavp.MaxDepth; D3D12_RECT rect; if( vavp.ScissorRectEnabled ) { rect.left = vavp.ScissorRect.left; rect.top = vavp.ScissorRect.top; rect.right = vavp.ScissorRect.right; rect.bottom = vavp.ScissorRect.bottom; } else { // set the scissor to viewport size, for rasterizer states that have it enabled rect.left = vavp.X; rect.top = vavp.Y; rect.right = vavp.Width + vavp.X; rect.bottom = vavp.Height + vavp.Y; } m_commandList->OMSetRenderTargets( numRTVs, RTVs, FALSE, pDSV ); m_commandList->RSSetViewports( 1, &viewport ); m_commandList->RSSetScissorRects( 1, &rect ); } void vaRenderDeviceContextBaseDX12::CommitOutputs( const vaRenderOutputs & outputs ) { assert( m_commandListReady ); // if( outputs == m_currentOutputs ) // return; m_currentOutputs = outputs; CommitOutputsRaw( m_itemsStarted, outputs ); // Transitions & setup UAVs! Don't do this for the worker contexts because the main one will fill up the transient descriptors and workers will just select it if( m_itemsStarted != vaRenderTypeFlags::None && !IsWorker( ) ) { assert( m_nextTransientDesc_OutputsUAVs != -1 ); auto& d3d12Device = m_deviceDX12.GetPlatformDevice( ); const vaUnorderedAccessViewDX12& nullUAV = m_deviceDX12.GetNullUAV( ); nullUAV; assert( m_nextTransientDesc_OutputsUAVs != -1 ); for( uint32 i = 0; i < vaRenderOutputs::c_maxUAVs; i++ ) { if( outputs.UnorderedAccessViews[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *outputs.UnorderedAccessViews[i] ); const vaUnorderedAccessViewDX12* uav = res.GetUAV( ); if( uav != nullptr ) { res.TransitionResource( *this, D3D12_RESOURCE_STATE_UNORDERED_ACCESS ); d3d12Device->CopyDescriptorsSimple( 1, m_deviceDX12.TransientDescHeapComputeCPUHandle( m_nextTransientDesc_OutputsUAVs + i ), uav->GetCPUReadableCPUHandle( ), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); continue; } else { VA_WARN( "Texture set to vaRenderOutput::UAVs but UAV is nullptr?" ); assert( false ); // this is a bug that needs fixing } } #ifdef VA_SET_UNUSED_DESC_TO_NULL d3d12Device->CopyDescriptorsSimple( 1, m_deviceDX12.TransientDescHeapComputeCPUHandle( m_nextTransientDesc_OutputsUAVs + i ), nullUAV.GetCPUReadableCPUHandle( ), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); #endif } } } void vaRenderDeviceContextBaseDX12::CommitGlobals( vaRenderTypeFlags typeFlags, const vaShaderItemGlobals& shaderGlobals ) { shaderGlobals.Validate(); ////////////////////////////////////////////////////////////////////////// // set descriptor tables and prepare for copying // auto [gpuHeapSRVUAV, descHeapBaseIndexSRVUAV] = AllocateSRVUAVHeapDescriptors( vaRenderDeviceDX12::ExtendedRootSignatureIndexRanges::SRVUAVTotalCount ); // if( gpuHeapSRVUAV == nullptr ) // { assert( false ); return; } // ////////////////////////////////////////////////////////////////////////// // // // int descHeapSRVOffset = descHeapBaseIndexSRVUAV + vaRenderDeviceDX12::ExtendedRootSignatureIndexRanges::SRVBase; // int descHeapUAVOffset = descHeapBaseIndexSRVUAV + vaRenderDeviceDX12::ExtendedRootSignatureIndexRanges::UAVBase; ////////////////////////////////////////////////////////////////////////// auto & d3d12Device = m_deviceDX12.GetPlatformDevice( ); #ifdef VA_SET_UNUSED_DESC_TO_NULL // const vaConstantBufferViewDX12& nullCBV = m_deviceDX12.GetNullCBV( ); const vaShaderResourceViewDX12& nullSRV = m_deviceDX12.GetNullSRV( ); const vaUnorderedAccessViewDX12& nullUAV = m_deviceDX12.GetNullUAV( ); nullUAV; // const vaSamplerViewDX12& nullSamplerView = m_deviceDX12.GetNullSamplerView( ); nullSamplerView; #endif // Global constant buffers for( int i = 0; i < array_size( shaderGlobals.ConstantBuffers ); i++ ) { if( shaderGlobals.ConstantBuffers[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *shaderGlobals.ConstantBuffers[i] ); res.TransitionResource( *this, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER ); D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = res.GetGPUVirtualAddress(); //D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = AsDX12( *shaderGlobals.ConstantBuffers[i] ).GetGPUBufferLocation( ); if( ( typeFlags & vaRenderTypeFlags::Graphics ) != 0 ) m_commandList->SetGraphicsRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::GlobalDirectCBVBase + i, gpuAddr ); if( ( typeFlags & vaRenderTypeFlags::Compute ) != 0 ) m_commandList->SetComputeRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::GlobalDirectCBVBase + i, gpuAddr ); continue; } #ifdef VA_SET_UNUSED_DESC_TO_NULL if( ( typeFlags & vaRenderTypeFlags::Graphics ) != 0 ) m_commandList->SetGraphicsRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::GlobalDirectCBVBase + i, D3D12_GPU_VIRTUAL_ADDRESS{ 0 } );//nullCBV.GetDesc( ).BufferLocation; if( ( typeFlags & vaRenderTypeFlags::Compute ) != 0 ) m_commandList->SetComputeRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::GlobalDirectCBVBase + i, D3D12_GPU_VIRTUAL_ADDRESS{ 0 } );//nullCBV.GetDesc( ).BufferLocation; #endif } if( !IsWorker() ) // already set by the main context { // Global unordered access views assert( m_nextTransientDesc_GlobalUAVs != -1 ); for( int i = 0; i < array_size( vaShaderItemGlobals::UnorderedAccessViews ); i++ ) { if( shaderGlobals.UnorderedAccessViews[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *shaderGlobals.UnorderedAccessViews[i] ); const vaUnorderedAccessViewDX12* uav = res.GetUAV( ); if( uav != nullptr ) { res.TransitionResource( *this, D3D12_RESOURCE_STATE_UNORDERED_ACCESS ); d3d12Device->CopyDescriptorsSimple( 1, m_deviceDX12.TransientDescHeapComputeCPUHandle( m_nextTransientDesc_GlobalUAVs + i ), uav->GetCPUReadableCPUHandle( ), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); continue; } else { VA_WARN( "Shader resource set to shaderGlobals but UAV is nullptr?" ); assert( false ); // this is a bug that needs fixing } } #ifdef VA_SET_UNUSED_DESC_TO_NULL d3d12Device->CopyDescriptorsSimple( 1, m_deviceDX12.TransientDescHeapComputeCPUHandle( m_nextTransientDesc_GlobalUAVs + i ), nullUAV.GetCPUReadableCPUHandle( ), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); #endif } // Global shader resource views assert( m_nextTransientDesc_GlobalSRVs != -1 ); for( int i = 0; i < array_size( shaderGlobals.ShaderResourceViews ); i++ ) { if( shaderGlobals.ShaderResourceViews[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *shaderGlobals.ShaderResourceViews[i] ); const vaShaderResourceViewDX12* srv = res.GetSRV( ); if( srv != nullptr ) { res.TransitionResource( *this, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ); d3d12Device->CopyDescriptorsSimple( 1, m_deviceDX12.TransientDescHeapComputeCPUHandle( m_nextTransientDesc_GlobalSRVs + i ), srv->GetCPUReadableCPUHandle( ), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); continue; } else { VA_WARN( "Shader resource set to shaderGlobals but SRV is nullptr?" ); assert( false ); // this is a bug that needs fixing } } #ifdef VA_SET_UNUSED_DESC_TO_NULL d3d12Device->CopyDescriptorsSimple( 1, m_deviceDX12.TransientDescHeapComputeCPUHandle( m_nextTransientDesc_GlobalSRVs + i ), nullSRV.GetCPUReadableCPUHandle( ), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); #endif } if( shaderGlobals.RaytracingAcceleationStructSRV != nullptr ) m_commandList->SetComputeRootShaderResourceView( vaRenderDeviceDX12::DefaultRootSignatureParams::RaytracingStructDirectSRV, AsDX12(*shaderGlobals.RaytracingAcceleationStructSRV).GetGPUVirtualAddress() );//nullCBV.GetDesc( ).BufferLocation; } } void vaRenderDeviceContextDX12::BeginItems( vaRenderTypeFlags typeFlags, const vaRenderOutputs * renderOutputs, const vaShaderItemGlobals & shaderGlobals ) { assert( GetRenderDevice( ).IsRenderThread( ) ); //VA_TRACE_CPU_SCOPE( BeginItems ); // beware, this can trigger flush and sync! and flush and sync clears all of these, which is why we loop PreAllocateTransientDescriptors( ); vaRenderDeviceContext::BeginItems( typeFlags, renderOutputs, shaderGlobals ); assert( m_itemsStarted != vaRenderTypeFlags::None ); assert( m_itemsStarted == typeFlags ); // Outputs if( renderOutputs != nullptr ) CommitOutputs( *renderOutputs ); CommitGlobals( typeFlags, shaderGlobals ); if( !m_workersUseBundles ) { for( int i = 0; i < m_workersActive; i++ ) m_workers[i]->DeferredSetGlobals( shaderGlobals ); } CommitTransientDescriptors(); } void vaRenderDeviceContextDX12::EndItems( ) { assert( GetRenderDevice().IsRenderThread() ); assert( m_itemsStarted != vaRenderTypeFlags::None ); vaRenderDeviceContext::EndItems(); // clear it up so we don't keep any references m_scratchPSODesc= vaGraphicsPSODescDX12( ); m_currentIndexBuffer = nullptr; m_commandList->IASetIndexBuffer( nullptr ); m_currentVertexBuffer = nullptr; m_commandList->IASetVertexBuffers( 0, 0, nullptr ); m_currentPSO = nullptr; /// TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP m_currentSceneRaytracing = nullptr; /// TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP // UnsetSceneGlobals( m_currentSceneDrawContext ); // m_currentSceneDrawContext = nullptr; assert( m_itemsStarted == vaRenderTypeFlags::None ); assert( m_commandListReady ); if( m_itemsSubmittedAfterLastExecute > c_flushAfterItemCount ) Flush(); } vaDrawResultFlags vaRenderDeviceContextBaseDX12::ExecuteItem( const vaGraphicsItem & renderItem, vaExecuteItemFlags flags ) { renderItem.Validate(); // perhaps too fine grained to provide useful info but costly to run // VA_TRACE_CPU_SCOPE( ExecuteGraphicsItem ); m_itemsSubmittedAfterLastExecute++; // auto & d3d12Device = m_deviceDX12.GetPlatformDevice( ); const vaRenderDeviceCapabilities & caps = GetRenderDevice().GetCapabilities(); // if( m_currentSceneDrawContext != nullptr ) // { assert( AsDX12(&m_currentSceneDrawContext->RenderDeviceContext) == this ); } // re-add this if needed // // Graphics item (at the moment) requires at least some outputs to work // if( !(m_currentOutputs.RenderTargetCount > 0 || m_currentOutputs.DepthStencil != nullptr || m_currentOutputs.UAVCount > 0) ) // { assert( false ); return vaDrawResultFlags::UnspecifiedError; } // ExecuteTask can only be called in between BeginTasks and EndTasks - call ExecuteSingleItem assert( (m_itemsStarted & vaRenderTypeFlags::Graphics) != 0 ); if( (m_itemsStarted & vaRenderTypeFlags::Graphics) == 0 ) return vaDrawResultFlags::UnspecifiedError; // this is an unique index of the instance ('scene object' or etc.) which can be used to figure out anything about it (mesh, material, etc.) m_commandList->SetGraphicsRoot32BitConstant( vaRenderDeviceDX12::DefaultRootSignatureParams::InstanceIndexDirectUINT32, renderItem.InstanceIndex, 0 ); // a single uint root const useful for any purpose m_commandList->SetGraphicsRoot32BitConstant( vaRenderDeviceDX12::DefaultRootSignatureParams::GenericRootConstDirectUINT32, renderItem.GenericRootConst, 0 ); #ifdef VA_SET_UNUSED_DESC_TO_NULL const vaConstantBufferViewDX12 & nullCBV = m_deviceDX12.GetNullCBV (); nullCBV; const vaShaderResourceViewDX12 & nullSRV = m_deviceDX12.GetNullSRV (); nullSRV; const vaUnorderedAccessViewDX12& nullUAV = m_deviceDX12.GetNullUAV (); nullUAV; // const vaSamplerViewDX12 & nullSamplerView= m_deviceDX12.GetNullSamplerView(); nullSamplerView; #endif // Constants for( int i = 0; i < array_size( renderItem.ConstantBuffers ); i++ ) { if( renderItem.ConstantBuffers[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *renderItem.ConstantBuffers[i] ); res.TransitionResource( *this, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER ); D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = res.GetGPUVirtualAddress(); m_commandList->SetGraphicsRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawDirectCBVBase + i, gpuAddr ); } #ifdef VA_SET_UNUSED_DESC_TO_NULL else m_commandList->SetGraphicsRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawDirectCBVBase + i, D3D12_GPU_VIRTUAL_ADDRESS{0} ); #endif } // Shader resource views for( int i = 0; i < array_size( renderItem.ShaderResourceViews ); i++ ) { D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = { 0 }; if( renderItem.ShaderResourceViews[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *renderItem.ShaderResourceViews[i] ); const vaShaderResourceViewDX12* srv = res.GetSRV( ); if( srv != nullptr ) { res.TransitionResource( *this, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ); m_commandList->SetGraphicsRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawSRVBase + i, srv->GetGPUHandle( ) ); continue; } else VA_WARN( "Texture set to renderItem but SRV is nullptr?" ); } #ifdef VA_SET_UNUSED_DESC_TO_NULL m_commandList->SetGraphicsRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawSRVBase + i, nullSRV.GetGPUHandle() ); #endif } // VA_TRACE_CPU_SCOPE( ExecuteGraphicsItem2 ); vaGraphicsPSODescDX12 & psoDesc = m_scratchPSODesc; // draw call must always have a vertex shader (still, I guess) - check whether we've ever cached anything to begin with! if( psoDesc.VSUniqueContentsID == -1 ) flags &= ~vaExecuteItemFlags::ShadersUnchanged; if( (flags & vaExecuteItemFlags::ShadersUnchanged) == 0 ) { psoDesc.PartialReset( ); // perhaps too fine grained to provide useful info but costly to run // VA_TRACE_CPU_SCOPE( Shaders ) // must have a vertex shader at least if( renderItem.VertexShader == nullptr || renderItem.VertexShader->IsEmpty() ) { psoDesc.InvalidateCache(); assert( false ); return vaDrawResultFlags::UnspecifiedError; } vaShader::State shState; if( (shState = AsDX12(*renderItem.VertexShader).GetShader( psoDesc.VSBlob, psoDesc.VSInputLayout, psoDesc.VSUniqueContentsID ) ) != vaShader::State::Cooked ) { psoDesc.InvalidateCache(); assert( shState != vaShader::State::Empty ); // trying to render with empty compute shader & this happened between here and the check few lines above? this is VERY weird and possibly a bug return (shState == vaShader::State::Uncooked)?(vaDrawResultFlags::ShadersStillCompiling):(vaDrawResultFlags::UnspecifiedError); } // vaShader::State::Empty and vaShader::State::Cooked are both ok but we must abort for uncooked! if( renderItem.PixelShader != nullptr && AsDX12(*renderItem.PixelShader).GetShader( psoDesc.PSBlob, psoDesc.PSUniqueContentsID ) == vaShader::State::Uncooked ) { psoDesc.InvalidateCache(); return vaDrawResultFlags::ShadersStillCompiling; } if( renderItem.GeometryShader != nullptr && AsDX12(*renderItem.GeometryShader).GetShader( psoDesc.GSBlob, psoDesc.GSUniqueContentsID ) == vaShader::State::Uncooked ) { psoDesc.InvalidateCache(); return vaDrawResultFlags::ShadersStillCompiling; } if( renderItem.HullShader != nullptr && AsDX12(*renderItem.HullShader).GetShader( psoDesc.HSBlob, psoDesc.HSUniqueContentsID ) == vaShader::State::Uncooked ) { psoDesc.InvalidateCache(); return vaDrawResultFlags::ShadersStillCompiling; } if( renderItem.DomainShader != nullptr && AsDX12(*renderItem.DomainShader).GetShader( psoDesc.DSBlob, psoDesc.DSUniqueContentsID ) == vaShader::State::Uncooked ) { psoDesc.InvalidateCache(); return vaDrawResultFlags::ShadersStillCompiling; } } psoDesc.BlendMode = renderItem.BlendMode; psoDesc.FillMode = renderItem.FillMode; psoDesc.CullMode = renderItem.CullMode; psoDesc.FrontCounterClockwise = renderItem.FrontCounterClockwise; psoDesc.DepthEnable = renderItem.DepthEnable; psoDesc.DepthWriteEnable = renderItem.DepthWriteEnable; psoDesc.DepthFunc = renderItem.DepthFunc; psoDesc.Topology = renderItem.Topology; ////////////////////////////////////////////////////////////////////////// // TODO: all of this can be precomputed in CommitOutputs int sampleCount = 1; if( m_currentOutputs.RenderTargets[0] != nullptr ) sampleCount = m_currentOutputs.RenderTargets[0]->GetSampleCount( ); else if( m_currentOutputs.DepthStencil != nullptr ) sampleCount = m_currentOutputs.DepthStencil->GetSampleCount( ); // else { assert( false ); } // no render targets? no depth either? hmm? psoDesc.SampleDescCount = sampleCount; psoDesc.MultisampleEnable = sampleCount > 1; psoDesc.NumRenderTargets = m_currentOutputs.RenderTargetCount; for( int i = 0; i < _countof(psoDesc.RTVFormats); i++ ) psoDesc.RTVFormats[i] = ( m_currentOutputs.RenderTargets[i] != nullptr )?(m_currentOutputs.RenderTargets[i]->GetRTVFormat()):(vaResourceFormat::Unknown); psoDesc.DSVFormat = ( m_currentOutputs.DepthStencil != nullptr )?(m_currentOutputs.DepthStencil->GetDSVFormat()):(vaResourceFormat::Unknown); ////////////////////////////////////////////////////////////////////////// // VA_TRACE_CPU_SCOPE( ExecuteGraphicsItem4 ); // TOPOLOGY D3D_PRIMITIVE_TOPOLOGY topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; switch( renderItem.Topology ) { case vaPrimitiveTopology::PointList: topology = D3D_PRIMITIVE_TOPOLOGY_POINTLIST; break; case vaPrimitiveTopology::LineList: topology = D3D_PRIMITIVE_TOPOLOGY_LINELIST; break; case vaPrimitiveTopology::TriangleList: topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; case vaPrimitiveTopology::TriangleStrip: topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break; default: assert( false ); break; } if( topology != m_currentTopology ) { m_commandList->IASetPrimitiveTopology( topology ); m_currentTopology = topology; } // VA_TRACE_CPU_SCOPE( ExecuteGraphicsItem41 ); { // perhaps too fine grained to provide useful info but costly to run // VA_TRACE_CPU_SCOPE( IndexBuffers ) if( m_currentIndexBuffer != renderItem.IndexBuffer ) { m_currentIndexBuffer = renderItem.IndexBuffer; if( renderItem.IndexBuffer != nullptr ) { D3D12_INDEX_BUFFER_VIEW bufferView = { AsDX12(*renderItem.IndexBuffer).GetGPUVirtualAddress(), (UINT)AsDX12(*renderItem.IndexBuffer).GetSizeInBytes(), AsDX12(*renderItem.IndexBuffer).GetFormat() }; AsDX12(*renderItem.IndexBuffer).TransitionResource( *this, D3D12_RESOURCE_STATE_INDEX_BUFFER ); m_commandList->IASetIndexBuffer( &bufferView ); } else m_commandList->IASetIndexBuffer( nullptr ); } if( m_currentVertexBuffer != renderItem.VertexBuffer ) { m_currentVertexBuffer = renderItem.VertexBuffer; if( renderItem.VertexBuffer != nullptr ) { D3D12_VERTEX_BUFFER_VIEW bufferView = { AsDX12( *renderItem.VertexBuffer ).GetGPUVirtualAddress( ), (UINT)AsDX12( *renderItem.VertexBuffer ).GetSizeInBytes( ), AsDX12( *renderItem.VertexBuffer ).GetStrideInBytes() }; AsDX12( *renderItem.VertexBuffer ).TransitionResource( *this, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER ); m_commandList->IASetVertexBuffers( 0, 1, &bufferView ); } else m_commandList->IASetVertexBuffers( 0, 0, nullptr ); } } // VA_TRACE_CPU_SCOPE( ExecuteGraphicsItem42 ); //// these are the defaults set in BindDefaultStates - change this code if they need changing per-draw-call //FLOAT defBlendFactor[4] = { 1, 1, 1, 1 }; //m_commandList->OMSetBlendFactor( defBlendFactor ); // If you pass NULL, the runtime uses or stores a blend factor equal to { 1, 1, 1, 1 }. //m_commandList->OMSetStencilRef( 0 ); if( m_commandList != nullptr && caps.VariableShadingRate.Tier1 ) { // perhaps too fine grained to provide useful info but costly to run // VA_TRACE_CPU_SCOPE( ShadingRate ) D3D12_SHADING_RATE shadingRate = D3D12_SHADING_RATE_1X1; switch( renderItem.ShadingRate ) { case vaShadingRate::ShadingRate1X1: shadingRate = D3D12_SHADING_RATE_1X1; break; case vaShadingRate::ShadingRate1X2: shadingRate = D3D12_SHADING_RATE_1X2; break; case vaShadingRate::ShadingRate2X1: shadingRate = D3D12_SHADING_RATE_2X1; break; case vaShadingRate::ShadingRate2X2: shadingRate = D3D12_SHADING_RATE_2X2; break; case vaShadingRate::ShadingRate2X4: shadingRate = D3D12_SHADING_RATE_2X4; break; case vaShadingRate::ShadingRate4X2: shadingRate = D3D12_SHADING_RATE_4X2; break; case vaShadingRate::ShadingRate4X4: shadingRate = D3D12_SHADING_RATE_4X4; break; default: assert( false ); break; } if( !GetRenderDevice( ).GetCapabilities( ).VariableShadingRate.AdditionalShadingRatesSupported ) { if( shadingRate == D3D12_SHADING_RATE_2X4 || shadingRate == D3D12_SHADING_RATE_4X2 || shadingRate == D3D12_SHADING_RATE_4X4 ) shadingRate = D3D12_SHADING_RATE_1X1; } if( m_currentShadingRate != shadingRate ) { m_commandList->RSSetShadingRate( shadingRate, nullptr ); m_currentShadingRate = shadingRate; } } ID3D12PipelineState * pso = nullptr; { // VA_TRACE_CPU_SCOPE( PSOSearch ) vaGraphicsPSODX12 * psoOuter = m_deviceDX12.FindOrCreateGraphicsPipelineState( psoDesc, #ifdef VA_DX12_USE_LOCAL_PSO_CACHE &m_localGraphicsPSOCache #else nullptr #endif ); pso = (psoOuter!=nullptr)?(psoOuter->GetPSO()):(nullptr); } if( pso == nullptr ) return vaDrawResultFlags::ShadersStillCompiling; if( m_currentPSO != pso ) { m_commandList->SetPipelineState( pso ); m_currentPSO = pso; } // VA_TRACE_CPU_SCOPE( ExecuteGraphicsItem6 ); bool continueWithDraw = true; //if( renderItem.PreDrawHook != nullptr ) // continueWithDraw = renderItem.PreDrawHook( renderItem, *this ); if( continueWithDraw ) { // perhaps too fine grained to provide useful info but costly to run // VA_TRACE_CPU_SCOPE( Draw ) switch( renderItem.DrawType ) { case( vaGraphicsItem::DrawType::DrawSimple ): m_commandList->DrawInstanced( renderItem.DrawSimpleParams.VertexCount, 1, renderItem.DrawSimpleParams.StartVertexLocation, 0 ); break; case( vaGraphicsItem::DrawType::DrawIndexed ): m_commandList->DrawIndexedInstanced( renderItem.DrawIndexedParams.IndexCount, 1, renderItem.DrawIndexedParams.StartIndexLocation, renderItem.DrawIndexedParams.BaseVertexLocation, 0 ); break; default: assert( false ); break; } } // if( renderItem.PostDrawHook != nullptr ) // renderItem.PostDrawHook( renderItem, *this ); //// for caching - not really needed for now //// m_lastRenderItem = renderItem; return vaDrawResultFlags::None; } vaDrawResultFlags vaRenderDeviceContextBaseDX12::ExecuteItem( const vaComputeItem & computeItem, vaExecuteItemFlags flags ) { computeItem.Validate(); flags; // VA_TRACE_CPU_SCOPE( ExecuteComputeItem ); m_itemsSubmittedAfterLastExecute++; assert( GetRenderDevice().IsRenderThread() ); // ExecuteTask can only be called in between BeginTasks and EndTasks - call ExecuteSingleItem assert( (m_itemsStarted & vaRenderTypeFlags::Compute) != 0 ); if( (m_itemsStarted & vaRenderTypeFlags::Compute) == 0 ) return vaDrawResultFlags::UnspecifiedError; // must have compute shader at least if( computeItem.ComputeShader == nullptr || computeItem.ComputeShader->IsEmpty() ) { assert( false ); return vaDrawResultFlags::UnspecifiedError; } // there is no instance index during compute shading! m_commandList->SetComputeRoot32BitConstant( vaRenderDeviceDX12::DefaultRootSignatureParams::InstanceIndexDirectUINT32, 0xFFFFFFFF, 0 ); // a single uint root const useful for any purpose m_commandList->SetComputeRoot32BitConstant( vaRenderDeviceDX12::DefaultRootSignatureParams::GenericRootConstDirectUINT32, computeItem.GenericRootConst, 0 ); vaComputePSODescDX12 psoDesc; vaShader::State shState; if( ( shState = AsDX12(*computeItem.ComputeShader).GetShader( psoDesc.CSBlob, psoDesc.CSUniqueContentsID ) ) != vaShader::State::Cooked ) { assert( shState != vaShader::State::Empty ); // trying to render with empty compute shader & this happened between here and the check few lines above? this is VERY weird and possibly a bug return (shState == vaShader::State::Uncooked)?(vaDrawResultFlags::ShadersStillCompiling):(vaDrawResultFlags::UnspecifiedError); } #ifdef VA_SET_UNUSED_DESC_TO_NULL const vaShaderResourceViewDX12 & nullSRV = m_deviceDX12.GetNullSRV (); #endif // Constants for( int i = 0; i < array_size( computeItem.ConstantBuffers ); i++ ) { if( computeItem.ConstantBuffers[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *computeItem.ConstantBuffers[i] ); res.TransitionResource( *this, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER ); D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = res.GetGPUVirtualAddress(); //D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = AsDX12( *computeItem.ConstantBuffers[i] ).GetGPUBufferLocation( ); m_commandList->SetComputeRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawDirectCBVBase + i, gpuAddr ); } #ifdef VA_SET_UNUSED_DESC_TO_NULL else m_commandList->SetComputeRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawDirectCBVBase + i, D3D12_GPU_VIRTUAL_ADDRESS{0} ); #endif } // Shader resource views for( int i = 0; i < array_size( computeItem.ShaderResourceViews ); i++ ) { D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = { 0 }; if( computeItem.ShaderResourceViews[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *computeItem.ShaderResourceViews[i] ); const vaShaderResourceViewDX12* srv = res.GetSRV( ); if( srv != nullptr ) { res.TransitionResource( *this, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ); m_commandList->SetComputeRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawSRVBase + i, srv->GetGPUHandle( ) ); continue; } else VA_WARN( "Texture set to renderItem but SRV is nullptr?" ); } #ifdef VA_SET_UNUSED_DESC_TO_NULL m_commandList->SetComputeRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawSRVBase + i, nullSRV.GetGPUHandle() ); #endif } vaComputePSODX12 * psoOuter = m_deviceDX12.FindOrCreateComputePipelineState( psoDesc ); ID3D12PipelineState * pso = (psoOuter!=nullptr)?(psoOuter->GetPSO()):(nullptr); if( pso == nullptr ) { // this isn't valid for compute shader calls at the moment - figure out why it happened assert( false ); return vaDrawResultFlags::ShadersStillCompiling; } m_commandList->SetPipelineState( pso ); { auto NULLBARRIER = CD3DX12_RESOURCE_BARRIER::UAV( nullptr ); if( computeItem.GlobalUAVBarrierBefore ) m_commandList->ResourceBarrier(1, &NULLBARRIER ); switch( computeItem.ComputeType ) { case( vaComputeItem::Dispatch ): m_commandList->Dispatch( computeItem.DispatchParams.ThreadGroupCountX, computeItem.DispatchParams.ThreadGroupCountY, computeItem.DispatchParams.ThreadGroupCountZ ); break; case( vaComputeItem::DispatchIndirect ): { vaShaderResourceDX12 & res = AsDX12( *computeItem.DispatchIndirectParams.BufferForArgs ); res.TransitionResource( *this, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT ); m_commandList->ExecuteIndirect( m_deviceDX12.GetDispatchIndirectCommandSig().Get(), 1, res.GetResource(), computeItem.DispatchIndirectParams.AlignedOffsetForArgs, nullptr, 0 ); } break; default: assert( false ); break; } if( computeItem.GlobalUAVBarrierAfter ) m_commandList->ResourceBarrier( 1, &NULLBARRIER ); } return vaDrawResultFlags::None; } void vaRenderDeviceContextDX12::BeginRaytraceItems( const vaRenderOutputs & renderOutputs, const vaDrawAttributes * drawAttributes ) { assert( m_workersActive == 0 ); assert( drawAttributes != nullptr ); assert( drawAttributes->Raytracing != nullptr ); m_currentSceneRaytracing = dynamic_cast<vaSceneRaytracingDX12*>( drawAttributes->Raytracing ); assert( m_currentSceneRaytracing != nullptr ); return vaRenderDeviceContext::BeginRaytraceItems( renderOutputs, drawAttributes ); } vaDrawResultFlags vaRenderDeviceContextBaseDX12::ExecuteItem( const vaRaytraceItem & raytraceItem, vaExecuteItemFlags flags ) { raytraceItem.Validate(); // No threads will be dispatched, because at least one of {ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ} is 0. This is probably not intentional? assert( raytraceItem.DispatchWidth != 0 && raytraceItem.DispatchHeight != 0 && raytraceItem.DispatchDepth != 0 ); flags; // VA_TRACE_CPU_SCOPE( ExecuteRaytraceItem ); m_itemsSubmittedAfterLastExecute++; assert( GetRenderDevice( ).IsRenderThread( ) ); // ExecuteTask can only be called in between BeginTasks and EndTasks - call ExecuteSingleItem if( ( ( m_itemsStarted & vaRenderTypeFlags::Compute ) == 0 ) && ( ( m_itemsStarted & vaRenderTypeFlags::Raytrace ) == 0 ) ) { assert( false ); return vaDrawResultFlags::UnspecifiedError; } // Since we can't know in advance whether the compiling shaders are part of the requested PSO and recompiling raytracing PSOs is horribly // costly, let's just wait until all shaders are 'settled'. if( vaShader::GetNumberOfCompilingShaders( ) > 0 ) return vaDrawResultFlags::ShadersStillCompiling; // there is no instance index during raytracing! m_commandList->SetComputeRoot32BitConstant( vaRenderDeviceDX12::DefaultRootSignatureParams::InstanceIndexDirectUINT32, 0xFFFFFFFF, 0 ); // a single uint root const useful for any purpose m_commandList->SetComputeRoot32BitConstant( vaRenderDeviceDX12::DefaultRootSignatureParams::GenericRootConstDirectUINT32, raytraceItem.GenericRootConst, 0 ); vaRaytracePSODescDX12 psoDesc; psoDesc.ItemSLEntryRayGen = vaStringTools::SimpleWiden(raytraceItem.RayGen ); assert( raytraceItem.RayGen .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( raytraceItem.RayGen != "" ); psoDesc.ItemSLEntryMiss = vaStringTools::SimpleWiden(raytraceItem.Miss ); assert( raytraceItem.Miss .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); psoDesc.ItemSLEntryMissSecondary= vaStringTools::SimpleWiden(raytraceItem.MissSecondary ); assert( raytraceItem.MissSecondary .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); psoDesc.ItemSLEntryAnyHit = vaStringTools::SimpleWiden(raytraceItem.AnyHit ); assert( raytraceItem.AnyHit .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); psoDesc.ItemSLEntryClosestHit = vaStringTools::SimpleWiden(raytraceItem.ClosestHit); assert( raytraceItem.ClosestHit .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); // can have either shader item librasry entry or shader material library entry for these if( raytraceItem.AnyHit == "" ) { psoDesc.ItemMaterialAnyHit = vaStringTools::SimpleWiden(raytraceItem.MaterialAnyHit ); assert( psoDesc.ItemMaterialAnyHit .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); } else { assert( raytraceItem.MaterialAnyHit == "" ); } // most likely a bug in user code - you can either have a singular AnyHit or per-material ItemMaterialAnyHit but not both if( raytraceItem.ClosestHit == "" ) { psoDesc.ItemMaterialClosestHit = vaStringTools::SimpleWiden(raytraceItem.MaterialClosestHit ); assert( psoDesc.ItemMaterialClosestHit .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); } else { assert( raytraceItem.MaterialClosestHit == "" ); } // most likely a bug in user code - you can either have a singular ClosestHit or per-material ItemMaterialClosestHit but not both psoDesc.ItemMaterialCallable = vaStringTools::SimpleWiden(raytraceItem.ShaderEntryMaterialCallable ); assert( psoDesc.ItemMaterialCallable .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); psoDesc.ItemMaterialMissCallable = vaStringTools::SimpleWiden(raytraceItem.MaterialMissCallable ); assert( psoDesc.ItemMaterialMissCallable .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( psoDesc.ItemSLEntryRayGen != L"" ); // we always need a raygen shader! assert( psoDesc.ItemSLEntryMiss != L"" ); // we always need a miss shader! assert( psoDesc.ItemSLEntryAnyHit != L"" || psoDesc.ItemMaterialAnyHit != L"" ); // we always need a anyhit shader! assert( psoDesc.ItemSLEntryClosestHit != L"" || psoDesc.ItemMaterialClosestHit != L"" ); // we always need a closesthit shader! vaShader::State shState; if( ( shState = AsDX12( *raytraceItem.ShaderLibrary ).GetShader( psoDesc.ItemSLBlob, psoDesc.ItemSLUniqueContentsID ) ) != vaShader::State::Cooked ) { assert( shState != vaShader::State::Empty ); // trying to render with empty compute shader & this happened between here and the check few lines above? this is VERY weird and possibly a bug return ( shState == vaShader::State::Uncooked ) ? ( vaDrawResultFlags::ShadersStillCompiling ) : ( vaDrawResultFlags::UnspecifiedError ); } psoDesc.MaterialsSLUniqueContentsID = AsDX12(m_deviceDX12.GetMaterialManager()).GetCallablesTableID(); psoDesc.MaxRecursionDepth = raytraceItem.MaxRecursionDepth; assert( psoDesc.MaxRecursionDepth > 0 ); psoDesc.MaxPayloadSize = raytraceItem.MaxPayloadSize; assert( raytraceItem.MaxPayloadSize > 0 ); #ifdef VA_SET_UNUSED_DESC_TO_NULL const vaShaderResourceViewDX12 & nullSRV = m_deviceDX12.GetNullSRV( ); #endif // Constants for( int i = 0; i < array_size( raytraceItem.ConstantBuffers ); i++ ) { if( raytraceItem.ConstantBuffers[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *raytraceItem.ConstantBuffers[i] ); res.TransitionResource( *this, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER ); D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = res.GetGPUVirtualAddress(); //D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = AsDX12( *raytraceItem.ConstantBuffers[i] ).GetGPUBufferLocation( ); m_commandList->SetComputeRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawDirectCBVBase + i, gpuAddr ); } #ifdef VA_SET_UNUSED_DESC_TO_NULL else m_commandList->SetComputeRootConstantBufferView( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawDirectCBVBase + i, D3D12_GPU_VIRTUAL_ADDRESS{ 0 } ); #endif } // Shader resource views for( int i = 0; i < array_size( raytraceItem.ShaderResourceViews ); i++ ) { D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = { 0 }; if( raytraceItem.ShaderResourceViews[i] != nullptr ) { vaShaderResourceDX12& res = AsDX12( *raytraceItem.ShaderResourceViews[i] ); const vaShaderResourceViewDX12* srv = res.GetSRV( ); if( srv != nullptr ) { res.TransitionResource( *this, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ); m_commandList->SetComputeRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawSRVBase + i, srv->GetGPUHandle( ) ); continue; } else VA_WARN( "Texture set to renderItem but SRV is nullptr?" ); } #ifdef VA_SET_UNUSED_DESC_TO_NULL m_commandList->SetComputeRootDescriptorTable( vaRenderDeviceDX12::DefaultRootSignatureParams::PerDrawSRVBase + i, nullSRV.GetGPUHandle( ) ); #endif } vaRaytracePSODX12 * psoOuter = m_deviceDX12.FindOrCreateRaytracePipelineState( psoDesc ); vaRaytracePSODX12::Inner * pso = (psoOuter!=nullptr)?(psoOuter->GetPSO()):(nullptr); if( pso == nullptr ) { // this is OK for raytracing PSOs return vaDrawResultFlags::ShadersStillCompiling; } D3D12_DISPATCH_RAYS_DESC dispatchDesc = {}; // Since each shader table has only one shader record, the stride is same as the size. dispatchDesc.HitGroupTable.StartAddress = AsDX12(*pso->HitGroupShaderTable).GetGPUVirtualAddress( ); dispatchDesc.HitGroupTable.SizeInBytes = AsDX12(*pso->HitGroupShaderTable).GetDesc( ).Width; dispatchDesc.HitGroupTable.StrideInBytes = pso->HitGroupShaderTableStride; dispatchDesc.MissShaderTable.StartAddress = AsDX12(*pso->MissShaderTable).GetGPUVirtualAddress( ); dispatchDesc.MissShaderTable.SizeInBytes = AsDX12(*pso->MissShaderTable).GetDesc( ).Width; dispatchDesc.MissShaderTable.StrideInBytes = pso->MissShaderTableStride; dispatchDesc.RayGenerationShaderRecord.StartAddress = AsDX12(*pso->RayGenShaderTable).GetGPUVirtualAddress( ); dispatchDesc.RayGenerationShaderRecord.SizeInBytes = AsDX12(*pso->RayGenShaderTable).GetDesc( ).Width; dispatchDesc.CallableShaderTable.StartAddress = ( pso->CallableShaderTable != nullptr ) ? ( AsDX12(*pso->CallableShaderTable).GetGPUVirtualAddress( ) ) : ( 0 ); dispatchDesc.CallableShaderTable.SizeInBytes = ( pso->CallableShaderTable != nullptr ) ? ( AsDX12(*pso->CallableShaderTable).GetDesc( ).Width ) : ( 0 ); dispatchDesc.CallableShaderTable.StrideInBytes = ( pso->CallableShaderTable != nullptr ) ? ( pso->CallableShaderTableStride ) : ( 0 ); dispatchDesc.Width = raytraceItem.DispatchWidth; dispatchDesc.Height = raytraceItem.DispatchHeight; dispatchDesc.Depth = raytraceItem.DispatchDepth; m_commandList->SetPipelineState1( pso->PSO.Get( ) ); auto NULLBARRIER = CD3DX12_RESOURCE_BARRIER::UAV( nullptr ); if( raytraceItem.GlobalUAVBarrierBefore ) m_commandList->ResourceBarrier( 1, &NULLBARRIER ); m_commandList->DispatchRays( &dispatchDesc ); if( raytraceItem.GlobalUAVBarrierAfter ) m_commandList->ResourceBarrier( 1, &NULLBARRIER ); return (pso->Incomplete)?(vaDrawResultFlags::ShadersStillCompiling):(vaDrawResultFlags::None); } void vaRenderDeviceContextBaseDX12::BeginFrame( ) { assert( GetRenderDevice( ).IsRenderThread( ) ); assert( m_itemsStarted == vaRenderTypeFlags::None ); assert( !m_commandListReady ); // these are no longer valid m_nextTransientDesc_GlobalSRVs = -1; m_nextTransientDesc_GlobalUAVs = -1; m_nextTransientDesc_OutputsUAVs = -1; uint32 currentFrame = m_deviceDX12.GetCurrentFrameFlipIndex( ); HRESULT hr; // Command list allocators can only be reset when the associated // command lists have finished execution on the GPU; apps should use // fences to determine GPU execution progress. V( m_commandAllocators[currentFrame]->Reset( ) ); #ifdef VA_D3D12_USE_DEBUG_LAYER_DRED if( hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_HUNG ) m_deviceDX12.DeviceRemovedHandler( ); #endif if( !IsWorker() ) { ResetAndInitializeCommandList( m_deviceDX12.GetCurrentFrameFlipIndex( ) ); } vaRenderDeviceContext::BeginFrame( ); } void vaRenderDeviceContextBaseDX12::EndFrame( ) { vaRenderDeviceContext::EndFrame( ); assert( GetRenderDevice( ).IsRenderThread( ) ); assert( m_commandListReady || IsWorker() ); assert( m_itemsStarted == vaRenderTypeFlags::None ); m_localGraphicsPSOCache.Reset(); } void vaRenderDeviceContextWorkerDX12::BeginFrame( ) { vaRenderDeviceContextBaseDX12::BeginFrame( ); } void vaRenderDeviceContextWorkerDX12::EndFrame( ) { vaRenderDeviceContextBaseDX12::EndFrame( ); assert( m_localGPUFrameFinishedCallbacks.size() == 0 ); } void vaRenderDeviceContextDX12::BeginFrame( ) { vaRenderDeviceContextBaseDX12::BeginFrame( ); // However, when ExecuteCommandList() is called on a particular command // list, that command list can then be reset at any time and must be before // re-recording. for( int i = 0; i < m_workers.size(); i++ ) m_workers[i]->BeginFrame(); } void vaRenderDeviceContextDX12::EndFrame( ) { { VA_TRACE_CPU_SCOPE( WorkerContextsEndFrame ); for( int i = 0; i < m_workers.size( ); i++ ) m_workers[i]->EndFrame( ); } vaRenderDeviceContextBaseDX12::EndFrame( ); { // we can only start this scope here because vaRenderDeviceContextBaseDX12::EndFrame( ) above triggers a custom scope and we want to avoid ours overlapping with it // VA_TRACE_CPU_SCOPE( MainContextEndFrame ); assert( GetRenderDevice( ).IsRenderThread( ) ); assert( m_commandListReady ); assert( m_itemsStarted == vaRenderTypeFlags::None ); uint32 currentFrame = m_deviceDX12.GetCurrentFrameFlipIndex( ); currentFrame; HRESULT hr; { VA_TRACE_CPU_SCOPE( CommandListClose ); V( m_commandList->Close( ) ); } { // VA_TRACE_CPU_SCOPE( CommandListExecute ); // Execute the command list. ID3D12CommandList* ppCommandLists[] = { m_commandList.Get( ) }; m_deviceDX12.GetCommandQueue( )->ExecuteCommandLists( _countof( ppCommandLists ), ppCommandLists ); m_itemsSubmittedAfterLastExecute = 0; } #ifdef VA_D3D12_USE_DEBUG_LAYER_DRED hr = m_deviceDX12.GetPlatformDevice( )->GetDeviceRemovedReason( ); if( hr == DXGI_ERROR_DEVICE_REMOVED ) m_deviceDX12.DeviceRemovedHandler( ); #endif m_commandListReady = false; } } void vaRenderDeviceContextDX12::PostPresent( ) { assert( m_itemsSubmittedAfterLastExecute == 0 ); // Quick re-open of the command list to allow for perf tracing data collection HRESULT hr; uint32 currentFrame = AsDX12( GetRenderDevice( ) ).GetCurrentFrameFlipIndex( ); V( m_commandList->Reset( m_commandAllocators[currentFrame].Get( ), nullptr ) ); m_commandListReady = true; vaRenderDeviceContext::PostPresent( ); // Close and execute command list - this one only contains perf tracing stuff V( m_commandList->Close( ) ); ID3D12CommandList* ppCommandLists[] = { m_commandList.Get( ) }; m_deviceDX12.GetCommandQueue( )->ExecuteCommandLists( _countof( ppCommandLists ), ppCommandLists ); m_commandListReady = false; } void vaRenderDeviceContextDX12::QueueResourceStateTransition( const vaFramePtr<vaShaderResourceDX12> & resource, int workerIndex, D3D12_RESOURCE_STATES target, uint32 subResIndex ) { assert( subResIndex == -1 ); // subresources not supported for this assert( m_workersActive > 0 ); std::unique_lock lock(m_resourceTransitionQueueMutex); auto it = m_resourceTransitionQueue.find( resource ); if( it == m_resourceTransitionQueue.end( ) ) m_resourceTransitionQueue.emplace( std::pair<vaFramePtr<vaShaderResourceDX12>, ResourceStateTransitionItem>( resource, {workerIndex, target, subResIndex} ) ); else { const ResourceStateTransitionItem & data = it->second; if( data.Target != target || data.SubResIndex != subResIndex ) { // we've got a serious problemo - trying to change resource type to a different type from two different places - this isn't going to work, find the bug and fix it assert( false ); } } } // // this version returns the pre-allocated descriptors since this is expensive to do on every call! // std::pair< vaRenderDeviceDX12::TransientGPUDescriptorHeap*, int > vaRenderDeviceContextWorkerDX12::AllocateSRVUAVHeapDescriptors( int numberOfDescriptors ) // { // assert( m_preAllocatedSRVUAVHeapCount >= numberOfDescriptors ); // assert( m_preAllocatedSRVUAVHeap != nullptr ); // // std::pair< vaRenderDeviceDX12::TransientGPUDescriptorHeap*, int > retVal = { m_preAllocatedSRVUAVHeap, m_preAllocatedSRVUAVHeapBase }; // // m_preAllocatedSRVUAVHeapBase += numberOfDescriptors; // m_preAllocatedSRVUAVHeapCount -= numberOfDescriptors; // // return retVal; // } void vaRenderDeviceContextWorkerDX12::CommitOutputs( const vaRenderOutputs & outputs ) { if( m_useBundles ) m_currentOutputs = outputs; // bundles inherit output, so this is set only for internal tracking / validation else vaRenderDeviceContextBaseDX12::CommitOutputs( outputs ); } void vaRenderDeviceContextWorkerDX12::PreWorkPrepareMainThread( int workItemCount ) { workItemCount; } void vaRenderDeviceContextWorkerDX12::PreWorkPrepareWorkerThread( int workItemCount ) { workItemCount; ResetAndInitializeCommandList( m_deviceDX12.GetCurrentFrameFlipIndex( ) ); m_itemsStarted = GetMasterDX12( )->m_itemsStarted; // mostly for asserting/tracking CommitOutputs( GetMasterDX12( )->m_currentOutputs ); if( m_hasGlobals ) { CommitGlobals( m_itemsStarted, m_deferredGlobals ); #ifdef _DEBUG m_deferredGlobals = {}; #endif m_hasGlobals = false; } CommitTransientDescriptors( ); } void vaRenderDeviceContextWorkerDX12::PostWorkCleanupWorkerThread( ) { if( m_localGPUFrameFinishedCallbacks.size( ) > 0 ) { AsDX12(GetRenderDevice()).ExecuteAfterCurrentGPUFrameDone( m_localGPUFrameFinishedCallbacks ); m_localGPUFrameFinishedCallbacks.clear(); } assert( !m_commandListReady ); m_currentIndexBuffer = nullptr; m_currentVertexBuffer = nullptr; m_currentPSO = nullptr; // clear these up so we don't keep any references m_scratchPSODesc = vaGraphicsPSODescDX12( ); } void vaRenderDeviceContextWorkerDX12::PostWorkCleanupMainThread( ) { assert( GetRenderDevice( ).IsRenderThread( ) ); assert( !m_commandListReady ); } vaDrawResultFlags vaRenderDeviceContextDX12::ExecuteGraphicsItemsConcurrent( int itemCount, const vaRenderOutputs& renderOutputs, const vaDrawAttributes* drawAttributes, const GraphicsItemCallback& callback ) { VA_TRACE_CPU_SCOPE( ExecuteGraphicsItemsConcurrent ); assert( itemCount >= 0 ); if( itemCount <= 0 ) return vaDrawResultFlags::None; const uint32 currentFrame = m_deviceDX12.GetCurrentFrameFlipIndex( ); currentFrame; ////////////////////////////////////////////////////////////////////////// // compute number of workers / tasks const int minTasksPerWorker = 64; assert( m_workersActive == 0 ); m_workersActive = std::min( (int)m_workers.size(), (itemCount+minTasksPerWorker-1) / minTasksPerWorker ); ////////////////////////////////////////////////////////////////////////// // in case only 1 worker needed, no need to go through all the complexity below, just fall back to the single-threaded approach if( m_workersActive <= 1 ) { m_workersActive = 0; return vaRenderDeviceContext::ExecuteGraphicsItemsConcurrent( itemCount, renderOutputs, drawAttributes, callback ); } ////////////////////////////////////////////////////////////////////////// // initialize worker contexts vaDrawResultFlags ret = vaDrawResultFlags::None; const int batchCount = ( itemCount + c_maxItemsPerBeginEnd - 1 ) / c_maxItemsPerBeginEnd; const int itemsPerBatch = (itemCount + batchCount - 1) / batchCount; itemsPerBatch; for( int batch = 0; batch < batchCount; batch++ ) { // // option a: use max and what's left for the last // const int batchItemFrom = batch * c_maxItemsPerBeginEnd; const int batchItemCount = std::min( itemCount - batchItemFrom, c_maxItemsPerBeginEnd ); // option b: divide equally for each batch const int batchItemFrom = batch * itemsPerBatch; const int batchItemCount = std::min( itemCount - batchItemFrom, itemsPerBatch ); // BeginGraphicsItems( renderOutputs, drawAttributes ); // const int tasksPerWorker = ( batchItemCount + m_workersActive - 1 ) / m_workersActive; for( int w = 0; w < m_workersActive; w++ ) { int itemFirst = batchItemFrom + w * tasksPerWorker; int itemLast = batchItemFrom + std::min( ( w + 1 ) * tasksPerWorker - 1, batchItemCount - 1 ); m_workers[w]->PreWorkPrepareMainThread( itemLast - itemFirst + 1 ); } // ////////////////////////////////////////////////////////////////////////// // set up the worker callback function auto workerFunction = [ tasksPerWorker, batchItemFrom, batchItemCount, &workers = m_workers, &workerDrawResults = m_workerDrawResults, &callback ]( int w ) noexcept { const int itemFirst = batchItemFrom + w * tasksPerWorker; const int itemLast = batchItemFrom + std::min( ( w + 1 ) * tasksPerWorker - 1, batchItemCount - 1 ); workerDrawResults[w] = vaDrawResultFlags::None; { VA_TRACE_CPU_SCOPE( PrepareWorker ); workers[w]->PreWorkPrepareWorkerThread( itemLast - itemFirst + 1 ); } { VA_TRACE_CPU_SCOPE( ExecWorkerItems ); for( int i = itemFirst; i <= itemLast; i++ ) { // VA_TRACE_CPU_SCOPE( ExecWorkerItem ); workerDrawResults[w] |= callback( i, *workers[w] ); } } { // perhaps too fine grained to provide useful info but costly to run VA_TRACE_CPU_SCOPE( CommandListClose ); workers[w]->GetCommandList( ).Get( )->Close( ); } workers[w]->m_itemsStarted = vaRenderTypeFlags::None; workers[w]->m_commandListReady = false; workers[w]->PostWorkCleanupWorkerThread( ); }; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // !!! MULTITHREADED PART STARTS !!! // going wide! { VA_TRACE_CPU_SCOPE( GoWide ); #if !defined(VA_TASKFLOW_INTEGRATION_ENABLED) // just single-threaded loop! for( int w = 0; w < m_workersActive; w++ ) workerFunction( w ); #else #if 0 // tf style tf::Taskflow workFlow( "bosmang" ); workFlow.parallel_for( 0, int(m_workersActive-1), 1, workerFunction, 1Ui64 ).second; auto workFlowFuture = vaTF::GetInstance( ).Executor( ).run( workFlow ); #else // our tf style auto workFlowFuture = vaTF::parallel_for( 0, int(m_workersActive-1), workerFunction, 1, "RenderListBuild" ); #endif // busy ourselves with 1 job workerFunction( m_workersActive - 1 ); // wait for everything else to finish workFlowFuture.wait( ); #endif } // !!! MULTITHREADED PART ENDS !!! ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // apply deferred resource transitions { VA_TRACE_CPU_SCOPE( DeferredResourceTransitions ); // these can get collected std::unique_lock lock( m_resourceTransitionQueueMutex ); // <- this isn't needed but leaving it here to avoid any confusion for( auto it = m_resourceTransitionQueue.begin( ); it != m_resourceTransitionQueue.end( ); it++ ) it->first->TransitionResource( *this, it->second.Target ); m_resourceTransitionQueue.clear(); } ////////////////////////////////////////////////////////////////////////// // commit all! // { VA_TRACE_CPU_SCOPE( CommitAll ); HRESULT hr; hr; // submitting work is different based on whether we use bundles or direct command list workers if( m_workersUseBundles ) { { VA_TRACE_CPU_SCOPE( ExecuteAllBundles ); for( int w = 0; w < m_workersActive; w++ ) { //VA_TRACE_CPU_SCOPE( ExecuteBundle ); m_commandList->ExecuteBundle( m_workers[w]->GetCommandList( ).Get( ) ); ret |= m_workerDrawResults[w]; m_workerDrawResults[w] = vaDrawResultFlags::None; } } { VA_TRACE_CPU_SCOPE( PostWorkCleanup ); for( int w = 0; w < m_workersActive; w++ ) { //VA_TRACE_CPU_SCOPE( PostWorkCleanup ); m_workers[w]->PostWorkCleanupMainThread( ); } } } else { // our main command list is filled up, close it V( m_commandList->Close( ) ); m_commandListReady = false; // first execute the main command list (among other things it contains all transitions required so it has to be first) and then all workers ID3D12CommandList * commandLists[vaRenderDeviceDX12::c_maxWorkers+1]; int commandListsCount = 1 + (int64)m_workersActive; assert( commandListsCount <= countof(commandLists) ); commandLists[0] = m_commandList.Get( ); for( int w = 0; w < m_workersActive; w++ ) { commandLists[(int64)w+1] = m_workers[w]->GetCommandList().Get(); ret |= m_workerDrawResults[w]; m_workerDrawResults[w] = vaDrawResultFlags::None; } m_deviceDX12.GetCommandQueue( )->ExecuteCommandLists( commandListsCount, commandLists ); auto bkp = m_itemsStarted; m_itemsStarted = vaRenderTypeFlags::None; // to avoid asserts ResetAndInitializeCommandList( currentFrame ); m_itemsStarted = bkp; // to avoid asserts } #ifdef VA_D3D12_USE_DEBUG_LAYER_DRED hr = m_deviceDX12.GetPlatformDevice( )->GetDeviceRemovedReason( ); if( hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_HUNG ) m_deviceDX12.DeviceRemovedHandler( ); #endif } for( int w = 0; w < m_workersActive; w++ ) { m_itemsSubmittedAfterLastExecute += m_workers[w]->m_itemsSubmittedAfterLastExecute; m_workers[w]->m_itemsSubmittedAfterLastExecute = 0; } // minor cleanup EndItems( ); } m_workersActive = 0; return ret; } void vaRenderDeviceContextDX12::SetWorkers( const std::vector<shared_ptr<vaRenderDeviceContextWorkerDX12>> & workers, bool workersUseBundles ) { assert( !m_deviceDX12.IsFrameStarted() ); m_workers = workers; m_workersUseBundles = workersUseBundles; m_workerDrawResults.resize( workers.size( ), vaDrawResultFlags::None ); }
47.532355
328
0.669296
[ "mesh", "render", "object", "vector" ]
8d714e91bd815a0defaa6cb7040108e0f2978f99
243
hpp
C++
gearoenix/render/widget/gx-rnd-wdg-alignment.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/render/widget/gx-rnd-wdg-alignment.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/render/widget/gx-rnd-wdg-alignment.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_RENDER_WIDGET_ALIGNMENT_HPP #define GEAROENIX_RENDER_WIDGET_ALIGNMENT_HPP #include <cstdint> namespace gearoenix::render::widget { enum struct Alignment : std::uint8_t { Center = 1, Start = 2, End = 3, }; } #endif
22.090909
45
0.744856
[ "render" ]
8d72a4339ec6ec23af4c6d559ff5813e4c9ea2de
12,623
cpp
C++
flow/flat_buffers.cpp
marcmac/foundationdb
65b0b454cb21c5f02fc0b88db63c0c52f0bfb4db
[ "Apache-2.0" ]
null
null
null
flow/flat_buffers.cpp
marcmac/foundationdb
65b0b454cb21c5f02fc0b88db63c0c52f0bfb4db
[ "Apache-2.0" ]
2
2019-03-15T22:23:06.000Z
2019-03-17T18:45:04.000Z
flow/flat_buffers.cpp
marcmac/foundationdb
65b0b454cb21c5f02fc0b88db63c0c52f0bfb4db
[ "Apache-2.0" ]
1
2019-03-12T20:17:26.000Z
2019-03-12T20:17:26.000Z
/* * serialize.h * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors * * 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 "flow/flat_buffers.h" #include "flow/UnitTest.h" #include "flow/Arena.h" #include "flow/serialize.h" #include "flow/ObjectSerializer.h" #include <algorithm> #include <iomanip> #include <variant> namespace detail { bool TraverseMessageTypes::vtableGeneratedBefore(const std::type_index& idx) { return !f.known_types.insert(idx).second; } VTable generate_vtable(size_t numMembers, const std::vector<unsigned>& sizesAlignments) { if (numMembers == 0) { return VTable{ 4, 4 }; } // first is index, second is size std::vector<std::pair<unsigned, unsigned>> indexed; indexed.reserve(numMembers); for (unsigned i = 0; i < numMembers; ++i) { if (sizesAlignments[i] > 0) { indexed.emplace_back(i, sizesAlignments[i]); } } std::stable_sort(indexed.begin(), indexed.end(), [](const std::pair<unsigned, unsigned>& lhs, const std::pair<unsigned, unsigned>& rhs) { return lhs.second > rhs.second; }); VTable result; result.resize(numMembers + 2); // size of the vtable is // - 2 bytes per member + // - 2 bytes for the size entry + // - 2 bytes for the size of the object result[0] = 2 * numMembers + 4; int offset = 0; for (auto p : indexed) { auto align = sizesAlignments[numMembers + p.first]; auto& res = result[p.first + 2]; res = offset % align == 0 ? offset : ((offset / align) + 1) * align; offset = res + p.second; res += 4; } result[1] = offset + 4; return result; } } // namespace detail namespace unit_tests { TEST_CASE("flow/FlatBuffers/test") { auto* vtable1 = detail::get_vtable<int>(); auto* vtable2 = detail::get_vtable<uint8_t, uint8_t, int, int64_t, int>(); auto* vtable3 = detail::get_vtable<uint8_t, uint8_t, int, int64_t, int>(); auto* vtable4 = detail::get_vtable<uint32_t>(); ASSERT(vtable1 != vtable2); ASSERT(vtable2 == vtable3); ASSERT(vtable1 == vtable4); // Different types, but same vtable! Saves space in encoded messages ASSERT(vtable1->size() == 3); ASSERT(vtable2->size() == 7); ASSERT((*vtable2)[0] == 14); ASSERT((*vtable2)[1] == 22); ASSERT(((*vtable2)[4] - 4) % 4 == 0); ASSERT(((*vtable2)[5] - 4) % 8 == 0); ASSERT(((*vtable2)[6] - 4) % 4 == 0); return Void(); } TEST_CASE("flow/FlatBuffers/emptyVtable") { auto* vtable = detail::get_vtable<>(); ASSERT((*vtable)[0] == 4); ASSERT((*vtable)[1] == 4); return Void(); } struct Table2 { std::string m_p = {}; bool m_ujrnpumbfvc = {}; int64_t m_iwgxxt = {}; int64_t m_tjkuqo = {}; int16_t m_ed = {}; template <class Archiver> void serialize(Archiver& ar) { serializer(ar, m_p, m_ujrnpumbfvc, m_iwgxxt, m_tjkuqo, m_ed); } }; struct Table3 { uint16_t m_asbehdlquj = {}; uint16_t m_k = {}; uint16_t m_jib = {}; int64_t m_n = {}; template <class Archiver> void serialize(Archiver& ar) { serializer(ar, m_asbehdlquj, m_k, m_jib, m_n); } }; TEST_CASE("flow/FlatBuffers/vtable2") { const auto& vtable = *detail::get_vtable<uint64_t, bool, std::string, int64_t, std::vector<uint16_t>, Table2, Table3>(); ASSERT(!(vtable[2] <= vtable[4] && vtable[4] < vtable[2] + 8)); return Void(); } struct Nested2 { uint8_t a; std::vector<std::string> b; int c; template <class Archiver> void serialize(Archiver& ar) { serializer(ar, a, b, c); } friend bool operator==(const Nested2& lhs, const Nested2& rhs) { return lhs.a == rhs.a && lhs.b == rhs.b && lhs.c == rhs.c; } }; struct Nested { uint8_t a; std::string b; Nested2 nested; std::vector<uint64_t> c; template <class Archiver> void serialize(Archiver& ar) { serializer(ar, a, b, nested, c); } }; struct Root { uint8_t a; std::vector<Nested2> b; Nested c; template <class Archiver> void serialize(Archiver& ar) { serializer(ar, a, b, c); } }; TEST_CASE("flow/FlatBuffers/collectVTables") { Root root; const auto* vtables = detail::get_vtableset(root); ASSERT(vtables == detail::get_vtableset(root)); const auto& root_vtable = *detail::get_vtable<uint8_t, std::vector<Nested2>, Nested>(); const auto& nested_vtable = *detail::get_vtable<uint8_t, std::vector<std::string>, int>(); int root_offset = vtables->offsets.at(&root_vtable); int nested_offset = vtables->offsets.at(&nested_vtable); ASSERT(!memcmp((uint8_t*)&root_vtable[0], &vtables->packed_tables[root_offset], root_vtable.size())); ASSERT(!memcmp((uint8_t*)&nested_vtable[0], &vtables->packed_tables[nested_offset], nested_vtable.size())); return Void(); } void print_buffer(const uint8_t* out, int len) { std::cout << std::hex << std::setfill('0'); for (int i = 0; i < len; ++i) { if (i % 8 == 0) { std::cout << std::endl; std::cout << std::setw(4) << i << ": "; } std::cout << std::setw(2) << (int)out[i] << " "; } std::cout << std::endl << std::dec; } struct Arena { std::vector<std::pair<uint8_t*, size_t>> allocated; ~Arena() { for (auto b : allocated) { delete[] b.first; } } uint8_t* operator()(size_t sz) { auto res = new uint8_t[sz]; allocated.emplace_back(res, sz); return res; } size_t get_size(const uint8_t* ptr) const { for (auto& p : allocated) { if (p.first == ptr) { return p.second; } } return -1; } }; struct DummyContext { Arena a; Arena& arena() { return a; } }; TEST_CASE("flow/FlatBuffers/serializeDeserializeRoot") { Root root{ 1, { { 13, { "ghi", "jkl" }, 15 }, { 16, { "mnop", "qrstuv" }, 18 } }, { 3, "hello", { 6, { "abc", "def" }, 8 }, { 10, 11, 12 } } }; Root root2 = root; Arena arena; auto out = detail::save(arena, root, FileIdentifier{}); ASSERT(root.a == root2.a); ASSERT(root.b == root2.b); ASSERT(root.c.a == root2.c.a); ASSERT(root.c.b == root2.c.b); ASSERT(root.c.nested.a == root2.c.nested.a); ASSERT(root.c.nested.b == root2.c.nested.b); ASSERT(root.c.nested.c == root2.c.nested.c); ASSERT(root.c.c == root2.c.c); root2 = {}; DummyContext context; detail::load(root2, out, context); ASSERT(root.a == root2.a); ASSERT(root.b == root2.b); ASSERT(root.c.a == root2.c.a); ASSERT(root.c.b == root2.c.b); ASSERT(root.c.nested.a == root2.c.nested.a); ASSERT(root.c.nested.b == root2.c.nested.b); ASSERT(root.c.nested.c == root2.c.nested.c); ASSERT(root.c.c == root2.c.c); return Void(); } TEST_CASE("flow/FlatBuffers/serializeDeserializeMembers") { Root root{ 1, { { 13, { "ghi", "jkl" }, 15 }, { 16, { "mnop", "qrstuv" }, 18 } }, { 3, "hello", { 6, { "abc", "def" }, 8 }, { 10, 11, 12 } } }; Root root2 = root; Arena arena; const auto* out = save_members(arena, FileIdentifier{}, root.a, root.b, root.c); ASSERT(root.a == root2.a); ASSERT(root.b == root2.b); ASSERT(root.c.a == root2.c.a); ASSERT(root.c.b == root2.c.b); ASSERT(root.c.nested.a == root2.c.nested.a); ASSERT(root.c.nested.b == root2.c.nested.b); ASSERT(root.c.nested.c == root2.c.nested.c); ASSERT(root.c.c == root2.c.c); root2 = {}; DummyContext context; load_members(out, context, root2.a, root2.b, root2.c); ASSERT(root.a == root2.a); ASSERT(root.b == root2.b); ASSERT(root.c.a == root2.c.a); ASSERT(root.c.b == root2.c.b); ASSERT(root.c.nested.a == root2.c.nested.a); ASSERT(root.c.nested.b == root2.c.nested.b); ASSERT(root.c.nested.c == root2.c.nested.c); ASSERT(root.c.c == root2.c.c); return Void(); } } // namespace unit_tests namespace unit_tests { TEST_CASE("flow/FlatBuffers/variant") { using V = boost::variant<int, double, Nested2>; V v1; V v2; Arena arena; DummyContext context; const uint8_t* out; v1 = 1; out = save_members(arena, FileIdentifier{}, v1); // print_buffer(out, arena.get_size(out)); load_members(out, context, v2); ASSERT(boost::get<int>(v1) == boost::get<int>(v2)); v1 = 1.0; out = save_members(arena, FileIdentifier{}, v1); // print_buffer(out, arena.get_size(out)); load_members(out, context, v2); ASSERT(boost::get<double>(v1) == boost::get<double>(v2)); v1 = Nested2{ 1, { "abc", "def" }, 2 }; out = save_members(arena, FileIdentifier{}, v1); // print_buffer(out, arena.get_size(out)); load_members(out, context, v2); ASSERT(boost::get<Nested2>(v1).a == boost::get<Nested2>(v2).a); ASSERT(boost::get<Nested2>(v1).b == boost::get<Nested2>(v2).b); ASSERT(boost::get<Nested2>(v1).c == boost::get<Nested2>(v2).c); return Void(); } TEST_CASE("flow/FlatBuffers/vectorBool") { std::vector<bool> x1 = { true, false, true, false, true }; std::vector<bool> x2; Arena arena; DummyContext context; const uint8_t* out; out = save_members(arena, FileIdentifier{}, x1); // print_buffer(out, arena.get_size(out)); load_members(out, context, x2); ASSERT(x1 == x2); return Void(); } } // namespace unit_tests namespace unit_tests { struct Y1 { int a; template <class Archiver> void serialize(Archiver& ar) { serializer(ar, a); } }; struct Y2 { int a; boost::variant<int> b; template <class Archiver> void serialize(Archiver& ar) { serializer(ar, a, b); } }; template <class Y> struct X { int a; Y b; int c; template <class Archiver> void serialize(Archiver& ar) { serializer(ar, a, b, c); } }; TEST_CASE("/flow/FlatBuffers/nestedCompat") { X<Y1> x1 = { 1, { 2 }, 3 }; X<Y2> x2; Arena arena; DummyContext context; const uint8_t* out; out = save_members(arena, FileIdentifier{}, x1); load_members(out, context, x2); ASSERT(x1.a == x2.a); ASSERT(x1.b.a == x2.b.a); ASSERT(x1.c == x2.c); x1 = {}; x2.b.b = 4; out = save_members(arena, FileIdentifier{}, x2); load_members(out, context, x1); ASSERT(x1.a == x2.a); ASSERT(x1.b.a == x2.b.a); ASSERT(x1.c == x2.c); return Void(); } TEST_CASE("/flow/FlatBuffers/struct") { std::vector<std::tuple<int16_t, bool, int64_t>> x1 = { { 1, true, 2 }, { 3, false, 4 } }; decltype(x1) x2; Arena arena; DummyContext context; const uint8_t* out; out = save_members(arena, FileIdentifier{}, x1); // print_buffer(out, arena.get_size(out)); load_members(out, context, x2); ASSERT(x1 == x2); return Void(); } TEST_CASE("/flow/FlatBuffers/file_identifier") { Arena arena; const uint8_t* out; constexpr FileIdentifier file_identifier{ 1234 }; out = save_members(arena, file_identifier); // print_buffer(out, arena.get_size(out)); ASSERT(read_file_identifier(out) == file_identifier); return Void(); } TEST_CASE("/flow/FlatBuffers/VectorRef") { // this test tests a few weird memory properties of // serialized arenas. This is why it uses weird scoping // first we construct the data to serialize/deserialize // so we can compare it afterwards std::vector<std::string> src; src.push_back("Foo"); src.push_back("Bar"); ::Arena vecArena; VectorRef<StringRef> outVec; { ::Arena readerArena; StringRef serializedVector; { ::Arena arena; VectorRef<StringRef> vec; for (const auto& str : src) { vec.push_back(arena, str); } ObjectWriter writer; writer.serialize(FileIdentifierFor<decltype(vec)>::value, arena, vec); serializedVector = StringRef(readerArena, writer.toStringRef()); } ArenaObjectReader reader(readerArena, serializedVector); reader.deserialize(FileIdentifierFor<decltype(outVec)>::value, vecArena, outVec); } ASSERT(src.size() == outVec.size()); for (int i = 0; i < src.size(); ++i) { auto str = outVec[i].toString(); ASSERT(str == src[i]); } return Void(); } TEST_CASE("/flow/FlatBuffers/Standalone") { Standalone<VectorRef<StringRef>> vecIn; auto numElements = deterministicRandom()->randomInt(1, 20); for (int i = 0; i < numElements; ++i) { auto str = deterministicRandom()->randomAlphaNumeric(deterministicRandom()->randomInt(0, 30)); vecIn.push_back(vecIn.arena(), StringRef(vecIn.arena(), str)); } Standalone<StringRef> value = ObjectWriter::toValue(vecIn); ArenaObjectReader reader(value.arena(), value); VectorRef<Standalone<StringRef>> vecOut; reader.deserialize(vecOut); ASSERT(vecOut.size() == vecIn.size()); for (int i = 0; i < vecOut.size(); ++i) { ASSERT(vecOut[i] == vecIn[i]); } return Void(); } } // namespace unit_tests
26.914712
108
0.656738
[ "object", "vector" ]
8d75d6c94d1c00cf29431a829fbd5680acb7e75f
64,911
cpp
C++
compiler/writeAST_to_C.cpp
Bhare8972/Cyth
334194be4b00456ed3fbf279f18bb22458d4ca81
[ "Apache-2.0" ]
null
null
null
compiler/writeAST_to_C.cpp
Bhare8972/Cyth
334194be4b00456ed3fbf279f18bb22458d4ca81
[ "Apache-2.0" ]
1
2016-01-09T19:00:14.000Z
2016-01-09T19:00:14.000Z
compiler/writeAST_to_C.cpp
Bhare8972/Cyth
334194be4b00456ed3fbf279f18bb22458d4ca81
[ "Apache-2.0" ]
null
null
null
#include "writeAST_to_C.hpp" #include "AST_visitor.hpp" #include <random> #include <chrono> using namespace csu; using namespace std; //// HEADER WRITERS //// // writes import statements into header class header_writeImports_visitor : public AST_visitorTree { public: bool do_children; // set on way down to true to do_children, otherwise will be false; ofstream& header_fout; string header_fout_name; // is this REALLY needed? header_writeImports_visitor(ofstream& _header_fout, string _header_fout_name) : header_fout( _header_fout ) { // header_fout = _header_fout; header_fout_name = _header_fout_name; do_children = true; } header_writeImports_visitor(bool _do_children, ofstream& _header_fout, string _header_fout_name) : header_fout( _header_fout ) { header_fout_name = _header_fout_name; do_children = _do_children; } bool apply_to_children() override { return do_children; } shared_ptr< AST_visitor_base > make_child(int number) override { return make_shared<header_writeImports_visitor>( false, header_fout, header_fout_name ); // if we are here, then we are on module. // The modules children should not apply the visitor, as only top-level statements can be imports } void module_down(module_AST_node* module) override { auto seed = chrono::system_clock::now().time_since_epoch().count(); default_random_engine generator(seed); uniform_int_distribution<int> distribution(10000000, 99999999); string h_gaurd_ID = to_string( distribution(generator) ); header_fout << "#ifndef " << module->module_name << "_" << h_gaurd_ID << endl; header_fout << "#define " << module->module_name << "_" << h_gaurd_ID << endl; } void cImports_down(import_C_AST_node* ASTnode) override { if( ASTnode->file_name.get_length() != 0 ) { header_fout << "#include \"" << ASTnode->file_name << "\""<<endl; } } virtual void CythImports_down(import_cyth_AST_node* ASTnode) override { if( ASTnode->import_module_Cheader_fname.get_length() != 0 ) { header_fout << "#include \"" << ASTnode->import_module_Cheader_fname << "\""<<endl; } } void ClassDef_down( class_AST_node* class_node) { //do_children = true; // so we can handle the structures and methods inside a structure // ?? header_fout << "struct "<< class_node->type_ptr->C_name << ";" << endl; } }; // for defining the data members inside classes // mostly for variables. doesn't handle methods or other classes ... class Class_DataDefiner : public AST_visitorTree { public: ofstream& fout; bool do_children; Class_DataDefiner(ofstream& _fout, bool chillins=true) : fout( _fout ) { do_children = chillins; } bool apply_to_children() override { return do_children; } shared_ptr< AST_visitor_base > make_child(int number) override { return make_shared<Class_DataDefiner>( fout, false ); } void ClassVarDef_down( class_varDefinition_AST_node* class_var_def ) override { auto type = class_var_def->var_type->resolved_type; auto name = class_var_def->variable_symbol->C_name; type->C_definition_name(name, fout); fout<<';'<<endl; } }; // writes definitions of functions, variables, and structs into header // only visits top AST nodes... with exceptions (mainly methods)... class header_writeDefinitions_visitor : public AST_visitorTree { public: bool do_children; // set this to true on way down to do children. Set to false initially (except on module..) ofstream& header_fout; string header_fout_name; header_writeDefinitions_visitor(ofstream& _header_fout, string _header_fout_name) : header_fout( _header_fout ) { header_fout_name = _header_fout_name; do_children = true; } header_writeDefinitions_visitor(bool _do_children, ofstream& _header_fout, string _header_fout_name) : header_fout( _header_fout ) { header_fout_name = _header_fout_name; do_children = _do_children; } bool apply_to_children() override { return do_children; } shared_ptr< AST_visitor_base > make_child(int number) override { return make_shared<header_writeDefinitions_visitor>( false, header_fout, header_fout_name ); // if we are here, then we are on module. // The modules children should not apply the visitor, as only top-level statements can be have definitions } void funcDef_down(function_AST_node* funcDef) override { funcDef->specific_overload->write_C_prototype( header_fout ); header_fout << ';'<<endl; } void definitionStmt_down(definition_statement_AST_node* defStmt) override { header_fout << "extern "; defStmt->var_type->resolved_type->C_definition_name( defStmt->variable_symbol->C_name, header_fout ); header_fout << ";" << endl; } void definitionNconstructionStmt_down(definitionNconstruction_statement_AST_node* defStmt) override { header_fout << "extern "; defStmt->var_type->resolved_type->C_definition_name( defStmt->variable_symbol->C_name, header_fout ); header_fout << ";" << endl; } void autoDefStmt_down(auto_definition_statement_AST_node* autoStmt) override { header_fout << "extern "; autoStmt->variable_symbol->var_type->C_definition_name( autoStmt->variable_symbol->C_name, header_fout ); header_fout << ";" << endl; } void module_up(module_AST_node* module, std::list<AST_visitor_base*>& visitor_children) override { header_fout << "void " << module->module_name << "__init__(void);"<<endl; header_fout << "#endif" << endl; } /// CLASSES /// void ClassDef_down( class_AST_node* class_node) override { do_children = true; // so we can handle the structures and methods inside a structure // anouther, more correct approach, would be to use anouther visiter auto class_type = class_node->type_ptr; //auto class_symbols = class_type->class_symbol_table; // first we write ancilary structs/classes // // starting with the vtable // header_fout << "struct "<< class_type->vtableType_cname << "{" << endl; // Write all virtual methods that don't override and are defined in this class DefClassType::methodOverloadIter methoditer = class_type->methodOverloadIter_begin( false ); DefClassType::methodOverloadIter methoditer_end = class_type->methodOverloadIter_end(); for( ; methoditer!=methoditer_end; ++methoditer ) { auto overload = methoditer.overload_get(); if( overload->is_virtual and overload->overriden_method==nullptr )// virtual and does not overload { // first, define the offset header_fout << "long " << overload->c_reference << "_offset;" << endl; // then the function pointer stringstream OUT; OUT << "(*" << overload->c_reference << ")("; //overload->self_ptr_name->var_type->C_definition_name(overload->self_ptr_name->C_name, OUT); OUT << "void* " << overload->self_ptr_name->C_name << "_"; if( overload->parameters->total_size() > 0 ) { OUT << ","; } overload->parameters->write_to_C(OUT, false); OUT << ")"; utf8_string name = OUT.str(); overload->return_type->C_definition_name(name, header_fout); header_fout<<';'<<endl; } } header_fout << endl; header_fout << "};" << endl; // define the global vtable variable header_fout << "extern struct " << class_type->vtableType_cname << " " << class_type->global_vtableVar_cname << ";" << endl; // and parent tables for( unsigned int parent_i=0; parent_i< (class_type->full_inheritance_tree.size()); ++parent_i) { auto parent_type = class_type->full_inheritance_tree[ parent_i ]; auto vtable_name = class_type->global_parentVtable_cnames[ parent_i ]; header_fout << "extern struct " << parent_type->vtableType_cname << " " << vtable_name << ";" << endl; } // now we define the actual class struct header_fout << "struct "<< class_type->C_name << "{" << endl; //write vtable header_fout << "struct " << class_type->vtableType_cname << " *__cy_vtable;" << endl; // write parents for( auto &parent_name : class_type->parent_class_names) { parent_name->var_type->C_definition_name(parent_name->C_name, header_fout); header_fout<<';'<<endl; } //write members Class_DataDefiner internal_visitor(header_fout); class_node->apply_visitor( &internal_visitor ); header_fout << endl; header_fout << "};" << endl; // write automated functions // write default constructor? if(class_node->write_default_constructor) { class_node->default_constructor_overload->write_C_prototype( header_fout ); header_fout << ';'<<endl; } // write default destructor? if(class_node->write_default_deconstructor) { class_node->default_destructor_overload->write_C_prototype( header_fout ); header_fout << ';'<<endl; } // default copy constructor? if( class_node->write_selfCopy_constructor ) { class_node->default_CopyConstructor_overload->write_C_prototype( header_fout ); header_fout << ';'<<endl; } } void methodDef_down(method_AST_node* methodDef) override { methodDef->specific_overload->write_C_prototype( header_fout ); header_fout << ';'<<endl; } }; //// SOURCE WRITERS //// // writes the preamble. This includes import of header, simple functions, global variables, etc... // initializes the vtables class source_writePreamble_visitor : public AST_visitorTree { public: bool do_children; ofstream& source_fout; string header_fname; // only defined for module source_writePreamble_visitor(ofstream& _source_fout, string _header_fname) : source_fout(_source_fout) { header_fname = _header_fname; do_children = true; } source_writePreamble_visitor(bool _do_children, ofstream& _source_fout) : source_fout( _source_fout ) { do_children = _do_children; } bool apply_to_children() override { return do_children; } shared_ptr< AST_visitor_base > make_child(int number) override { return make_shared<source_writePreamble_visitor>( false, source_fout ); // if we are here, then we are on module. // The modules children should not apply the visitor, so far, only top-level statements are need for preamble! } void module_down(module_AST_node* module) override { source_fout << "#include \"" << header_fname << "\"" << endl; source_fout << endl; } void typed_VarDef_down(Typed_VarDefinition* vardef) override // hope this works?? { vardef->var_type->resolved_type->C_definition_name( vardef->variable_symbol->C_name, source_fout ); source_fout<< ";" << endl << endl; } void autoDefStmt_down(auto_definition_statement_AST_node* autoStmt) override { autoStmt->variable_symbol->var_type->C_definition_name( autoStmt->variable_symbol->C_name, source_fout ); source_fout << ";" << endl << endl; } void ClassDef_down( class_AST_node* class_node) override { // we defined the vtables! auto class_type = class_node->type_ptr; auto class_symbols = class_type->class_symbol_table; //we define the symbol table for each parent class, and work our way down. // loop over each parent for( int parent_class_index=0; parent_class_index<class_type->full_inheritance_tree.size(); ++parent_class_index ) { auto &parent_class_type = class_type->full_inheritance_tree[ parent_class_index ]; auto &vtable_name = class_type->global_parentVtable_cnames[ parent_class_index ]; auto &connection_map = class_type->method_connection_table[ parent_class_index ]; // define the struct source_fout << "struct "<< parent_class_type->vtableType_cname << " " << vtable_name << " = {" << endl; // now we loop over every vtabled method and its override for( auto &connection_pair : connection_map ) { auto &parent_method = connection_pair.second.methodOverload_to_override; auto &overriding_method = connection_pair.second.methodOverload_that_overrides; auto &overriding_class = connection_pair.second.class_that_overrides; // there are three options for the offset utf8_string offset("0"); int override_to_parent_index = overriding_class->get_parent_index( parent_class_type ); if( parent_method==overriding_method ) // never got overriden { //source_fout << " ." << parent_method->c_reference << "_offset =0,"<< endl; // offset is zero, nothing to do } else if( override_to_parent_index >= 0 ) // there is a simple relationship between the overriding class and the parent { // need to find the byte-offset between the parent and overriding_class auto parental_iterator = overriding_class->parentIter_begin( override_to_parent_index ); auto parental_iterator_end = overriding_class->parentIter_end( ); auto previous_parent = parental_iterator.get(); ++parental_iterator; for( ; parental_iterator!=parental_iterator_end; ++parental_iterator ) { auto child_class = parental_iterator.get(); auto parent_varname = child_class->parent_class_names[ child_class->get_immediate_parent_index(previous_parent) ]; utf8_string TMP; stringstream defClass_out; child_class->C_definition_name(TMP, defClass_out); offset = offset + "+offsetof(" + defClass_out.str() + ", " + parent_varname->C_name + ")"; previous_parent = child_class; } //source_fout << " ." << parent_method->c_reference << "_offset ="<< current_calculation << "," <<endl; } else // things are...... complicated { // is this correct?? how to check? // first we find the byte offset between this class and the overrideing class int this_to_override_index = class_type->get_parent_index( overriding_class ); auto parentalOverride_iterator = class_type->parentIter_begin( this_to_override_index ); auto parentalOverride_iterator_end = class_type->parentIter_begin( this_to_override_index ); auto previous_parent = parentalOverride_iterator.get(); ++parentalOverride_iterator; for( ; parentalOverride_iterator!=parentalOverride_iterator_end; ++parentalOverride_iterator ) { auto child_class = parentalOverride_iterator.get(); offset = offset + "+offsetof(" + child_class->C_name + ", " + previous_parent->C_name + ")"; previous_parent = child_class; } // then we subtract off the offset to the parent class int this_to_parent_index = class_type->get_parent_index( parent_class_type ); auto parentalParent_iterator = class_type->parentIter_begin( this_to_parent_index ); auto parentalParent_iterator_end = class_type->parentIter_begin( this_to_parent_index ); previous_parent = parentalParent_iterator.get(); ++parentalParent_iterator; for( ; parentalParent_iterator!=parentalParent_iterator_end; ++parentalParent_iterator ) { auto child_class = parentalParent_iterator.get(); offset = offset + "-offsetof(" + child_class->C_name + ", " + previous_parent->C_name + ")"; previous_parent = child_class; } } // write to the file source_fout << " ." << parent_method->c_reference << "_offset =" << offset << "," <<endl; source_fout << " ." << parent_method->c_reference << " =" << overriding_method->c_reference << ","<< endl; } source_fout << "};" << endl; } // now we set our own vtable source_fout << "struct "<< class_node->type_ptr->vtableType_cname << " " << class_node->type_ptr->global_vtableVar_cname << " = {" << endl; auto methoditer = class_type->methodOverloadIter_begin( false ); auto methoditer_end = class_type->methodOverloadIter_end(); for( ; methoditer!=methoditer_end; ++methoditer ) { auto overload = methoditer.overload_get(); if( overload->is_virtual and overload->overriden_method==nullptr) // IE, is part of this vtable { source_fout << " ." << overload->c_reference << "_offset = 0," <<endl; source_fout << " ." << overload->c_reference << " =" << overload->c_reference << ","<< endl; } } source_fout << "};" << endl; } }; /// source_LHSreference_visitor /// shared_ptr< AST_visitor_base > source_LHSreference_visitor::source_LHS_child::make_child(int number) { return make_shared<source_LHS_child>( source_fout ); } void source_LHSreference_visitor::source_LHS_child::LHS_varRef_up(LHS_varReference* varref) { //LHS_C_code = varref->variable_symbol->C_name; // assume its this simple for now. Hope it stays this way varref->writer = make_shared<simple_expression_writer>( varref->variable_symbol->C_name ); } void source_LHSreference_visitor::source_LHS_child::LHS_accessor_up(LHS_accessor_AST_node* LHSaccess, AST_visitor_base* LHSref_visitor) { //auto LHS_child = dynamic_cast<source_LHS_child*>( LHSref_visitor ); //utf8_string& child_LHS_Cref = LHS_child->LHS_C_code; //LHS_C_code = LHSaccess->reference_type->write_member_getref( child_LHS_Cref, LHSaccess->name, source_fout ); auto child_LHS_Cref = LHSaccess->LHS_exp->writer->get_C_expression(); LHSaccess->writer = LHSaccess->reference_type->write_member_getref( child_LHS_Cref, LHSaccess->name, source_fout ); } source_LHSreference_visitor::source_LHSreference_visitor(ofstream& _source_fout, expression_AST_node* _RHS_AST_node, utf8_string& RHS_exp, varType_ptr _RHS_type) : source_fout(_source_fout) { RHS_C_code = RHS_exp; RHS_type = _RHS_type; RHS_AST_node = _RHS_AST_node; } // note this will NEVER call 'up' visitors! void source_LHSreference_visitor::LHS_varRef_down(LHS_varReference* varref) { // note we are still assuming that var refs are always simple. This may change. source_LHS_child LHS( source_fout ); varref->apply_visitor( &LHS ); if( varref->reference_type->get_has_assignment(RHS_type.get()) ) { //varref->reference_type->write_assignment( RHS_type.get(), RHS_AST_node, LHS.LHS_C_code , RHS_C_code, source_fout ); auto Cexp = varref->writer->get_C_expression(); varref->reference_type->write_assignment( RHS_type.get(), RHS_AST_node, Cexp , RHS_C_code, source_fout ); } else if( RHS_type->get_has_assignTo( varref->reference_type.get() ) ) { auto Cexp = varref->writer->get_C_expression(); RHS_type->write_assignTo(varref->reference_type.get(), RHS_AST_node, Cexp , RHS_C_code, source_fout ); } else // trust! { throw gen_exception( "error in source_LHSreference_visitor::LHS_varRef_down. This should never be reached" ); //auto Cexp = varref->writer->get_C_expression(); //RHS_type->write_implicit_castTo( varref->reference_type.get(), RHS_AST_node, Cexp , RHS_C_code, source_fout ); } } void source_LHSreference_visitor::LHS_accessor_down(LHS_accessor_AST_node* LHSaccess) { source_LHS_child LHS( source_fout ); auto LHS_EXP = LHSaccess->LHS_exp; LHS_EXP->apply_visitor( &LHS ); // note we need the type of the child, not the final return type!!! auto child_type = LHSaccess->LHS_exp->reference_type; auto C_exp = LHS_EXP->writer->get_C_expression(); child_type->write_member_setter(RHS_AST_node, C_exp, LHSaccess->name, RHS_type.get(), RHS_C_code, source_fout ); } /// LHS expression_cleanup_visitor /// void LHSexpression_cleanup_visitor::LHSReference_down(LHS_reference_AST_node* LHS_ref) { if( LHS_ref->writer ) { LHS_ref->writer->write_cleanup(); } } /// source_expression_visitor /// shared_ptr< AST_visitor_base > source_expression_visitor::make_child(int number) { return make_shared<source_expression_visitor>( source_fout ); } void source_expression_visitor::intLiteral_up(intLiteral_expression_AST_node* intLitExp) { stringstream exp; exp << intLitExp->literal; //intLitExp->C_exp = exp.str(); intLitExp->writer = make_shared<simple_expression_writer>( exp.str() ); intLitExp->c_exp_can_be_referenced = false; } void source_expression_visitor::binOperator_up(binOperator_expression_AST_node* binOprExp, AST_visitor_base* LHS_exp_visitor, AST_visitor_base* RHS_exp_visitor) { // define addition //source_expression_visitor* LHS_visitor = dynamic_cast<source_expression_visitor*>(LHS_exp_visitor); //source_expression_visitor* RHS_visitor = dynamic_cast<source_expression_visitor*>(RHS_exp_visitor); auto LHS_ast = binOprExp->left_operand; auto RHS_ast = binOprExp->right_operand; auto LHS_Cexp = LHS_ast->writer->get_C_expression(); auto RHS_Cexp = RHS_ast->writer->get_C_expression(); if( binOprExp->expression_return_type->can_be_defined() ) { utf8_string var_name = "__cy__expTMP_" + binOprExp->symbol_table->get_unique_string(); binOprExp->expression_return_type->C_definition_name( var_name, source_fout ); source_fout << ';' << endl; binOprExp->expression_return_type->initialize( var_name, source_fout ); auto exp = LHS_ast->expression_return_type->write_LHSaddition(LHS_ast, LHS_Cexp, RHS_ast, RHS_Cexp, source_fout); source_fout << var_name << '=' << exp << ';' << endl; exp->write_cleanup(); // NOTE MOVE binOprExp->writer = make_shared<simple_expression_writer>( var_name ); binOprExp->c_exp_can_be_referenced = true; } else { binOprExp->writer = LHS_ast->expression_return_type->write_LHSaddition(LHS_ast, LHS_Cexp, RHS_ast, RHS_Cexp, source_fout); binOprExp->c_exp_can_be_referenced = false; } //binOprExp->writer = LHS_ast->expression_return_type->write_LHSaddition(LHS_ast, LHS_Cexp, RHS_ast, RHS_Cexp, //source_fout); //binOprExp->c_exp_can_be_referenced = false; } void source_expression_visitor::varReferance_up(varReferance_expression_AST_node* varRefExp) { varRefExp->writer = make_shared<simple_expression_writer>( varRefExp->variable_symbol->C_name ); varRefExp->c_exp_can_be_referenced = true; } void source_expression_visitor::ParenExpGrouping_up(ParenGrouped_expression_AST_node* parenGroupExp, AST_visitor_base* expChild_visitor) { //source_expression_visitor* EXP_visitor_PTR = dynamic_cast<source_expression_visitor*>(expChild_visitor); //C_expression_code = EXP_visitor_PTR->C_expression_code; parenGroupExp->writer = make_shared<simple_expression_writer>( parenGroupExp->expression->writer->get_C_expression() ); parenGroupExp->c_exp_can_be_referenced = parenGroupExp->expression->c_exp_can_be_referenced; } void source_expression_visitor::accessorExp_up(accessor_expression_AST_node* accessorExp, AST_visitor_base* expChild_visitor) { auto T = accessorExp->expression->expression_return_type; // source_expression_visitor* EXP_visitor_PTR = dynamic_cast<source_expression_visitor*>(expChild_visitor); // auto child_exp = accessorExp->expression->writer->get_C_expression(); accessorExp->writer = T->write_member_getter( child_exp, accessorExp->name, source_fout); //accessorExp->writer = make_shared<simple_expression_writer>( C_expression_code ); accessorExp->c_exp_can_be_referenced = true; } void source_expression_visitor::functionCall_Exp_up(functionCall_expression_AST_node* funcCall, AST_visitor_base* expression_child, AST_visitor_base* arguments_child) { vector< utf8_string > argument_C_expressions; auto num_args = funcCall->argument_list->total_size(); argument_C_expressions.reserve( num_args ); for( int i=0; i<num_args; i++) { argument_C_expressions.push_back( funcCall->argument_list->expression_from_index( i )->writer->get_C_expression() ); } if( funcCall->expression_return_type->can_be_defined() and funcCall->expression_return_type->type_of_type!=varType::empty ) //empty is because of the void type { auto var_name = "__cy__expTMP_" + funcCall->symbol_table->get_unique_string(); funcCall->expression_return_type->C_definition_name( var_name, source_fout ); source_fout << ';' << endl; funcCall->expression_return_type->initialize( var_name, source_fout ); auto writer = funcCall->expression->expression_return_type->write_call( funcCall->argument_list.get(), funcCall->expression->writer, argument_C_expressions, source_fout ); source_fout << var_name << '=' << (writer->get_C_expression()) << ';' << endl; // NOTE MOVE writer->write_cleanup(); funcCall->writer = make_shared<simple_expression_writer>( var_name ); funcCall->c_exp_can_be_referenced = true; } else { auto writer = funcCall->expression->expression_return_type->write_call( funcCall->argument_list.get(), funcCall->expression->writer, argument_C_expressions, source_fout ); funcCall->writer = writer; funcCall->c_exp_can_be_referenced = false; } } /// expression_cleanup_visitor /// void expression_cleanup_visitor::expression_down(expression_AST_node* expression) { expression->writer->write_cleanup(); } void expression_cleanup_visitor::binOperator_up(binOperator_expression_AST_node* binOprExp, AST_visitor_base* LHS_exp_visitor, AST_visitor_base* RHS_exp_visitor) { if( binOprExp->has_output_ownership and binOprExp->c_exp_can_be_referenced ) { auto name = binOprExp->writer->get_C_expression(); binOprExp->expression_return_type->write_destructor(name, source_fout, not binOprExp->expression_return_type->is_static_type()); } } void expression_cleanup_visitor::functionCall_Exp_up(functionCall_expression_AST_node* funcCall, AST_visitor_base* expression_child, AST_visitor_base* arguments_child) { if( funcCall->has_output_ownership and funcCall->c_exp_can_be_referenced ) { auto name = funcCall->writer->get_C_expression(); funcCall->expression_return_type->write_destructor(name, source_fout, not funcCall->expression_return_type->is_static_type()); } } //// some revisitors //// child_expression_accumulator //// //void child_expression_accumulator::callArguments_up(call_argument_list* callArgs, AST_visitor_base* unArgs_child, AST_visitor_base* namedArgs) //{ // child_expression_accumulator* unArgs_child_casted = nullptr; // child_expression_accumulator* namedArgs_casted = nullptr; // // int T = 0; // if( unArgs_child ) // { // unArgs_child_casted = dynamic_cast<child_expression_accumulator*>( unArgs_child ); // T += unArgs_child_casted->children_Ccodes.size(); // } // if( namedArgs ) // { // namedArgs_casted = dynamic_cast<child_expression_accumulator*>( namedArgs ); // T += namedArgs_casted->children_Ccodes.size(); // } // // children_Ccodes.reserve( T ); // // if( unArgs_child_casted ) // { // for(auto str_pnt : unArgs_child_casted->children_Ccodes ) // { // children_Ccodes.push_back( str_pnt ); // } // } // if( namedArgs_casted ) // { // for(auto str_pnt : namedArgs_casted->children_Ccodes ) // { // children_Ccodes.push_back( str_pnt ); // } // } //} // //void child_expression_accumulator::baseArguments_up(call_argument_list::base_arguments_T* argList, std::list<AST_visitor_base*>& visitor_children) //{ // children_Ccodes.reserve( visitor_children.size() ); // for( auto ptr : visitor_children ) // { // auto src_exp_ptr = dynamic_cast<child_expression_accumulator*>( ptr )->twin; // // children_Ccodes.push_back( &(src_exp_ptr->C_expression_code) ); // } //} /// source_statement_visitor /// source_statement_visitor::source_statement_visitor(ofstream& _source_fout, bool _write_definitions) : source_fout(_source_fout) { do_children = true; write_definitions = _write_definitions; } shared_ptr< AST_visitor_base > source_statement_visitor::make_child(int number) { return make_shared<source_statement_visitor>( source_fout ); } //// things that cause this visitor to stop //// void source_statement_visitor::funcDef_down(function_AST_node* funcDef) { do_children = false; } //// "normal" things //// void source_statement_visitor::block_up(block_AST_node* block, std::list<AST_visitor_base*>& visitor_children) { /// destructors /// // this skims all top-level nodes, looking variables class destructuble_finder : public AST_visitor_NoChildren { public: list< varName_ptr > names_to_destruct; void autoDefStmt_down(auto_definition_statement_AST_node* autoStmt) { names_to_destruct.push_back( autoStmt->variable_symbol ); } void definitionStmt_down(definition_statement_AST_node* defStmt) { names_to_destruct.push_back( defStmt->variable_symbol ); } void definitionNconstructionStmt_down(definitionNconstruction_statement_AST_node* defStmt) { names_to_destruct.push_back( defStmt->variable_symbol ); } }; // apply it destructuble_finder finder; for( auto &AST_node : block->contents ) { AST_node->apply_visitor( &finder ); } // now destruct it all! for( auto var_to_destruct : finder.names_to_destruct ) { var_to_destruct->var_type->write_destructor( var_to_destruct->C_name, source_fout, not var_to_destruct->var_type->is_static_type() ); } } void source_statement_visitor::statement_up(statement_AST_node* statment) { source_fout << endl; } void source_statement_visitor::expressionStatement_down(expression_statement_AST_node* expStmt) { source_expression_visitor expr_vistr( source_fout ); expStmt->expression->apply_visitor( &expr_vistr ); // write exp source_fout << (expStmt->expression->writer->get_C_expression() ) << ";" << endl; expression_cleanup_visitor cleanup( source_fout ); expStmt->expression->apply_visitor( &cleanup ); } void source_statement_visitor::typed_VarDef_up(Typed_VarDefinition* var_def, AST_visitor_base* var_type) { if( write_definitions ) { var_def->var_type->resolved_type->C_definition_name( var_def->variable_symbol->C_name, source_fout ); source_fout << ";" << endl; } var_def->var_type->resolved_type->initialize( var_def->variable_symbol->C_name, source_fout ); } void source_statement_visitor::definitionStmt_up(definition_statement_AST_node* defStmt, AST_visitor_base* varTypeRepr_child) { //defStmt->var_type->resolved_type->C_definition_name( defStmt->variable_symbol->C_name, source_fout ); //source_fout << ";" << endl; defStmt->var_type->resolved_type->write_default_constructor(defStmt->variable_symbol->C_name, source_fout); source_fout<< endl; } void source_statement_visitor::definitionNconstruction_up(definitionNconstruction_statement_AST_node* defStmt, AST_visitor_base* varTypeRepr_child, AST_visitor_base* argList_child) { source_expression_visitor arguments_visitor_PTR( source_fout ); defStmt->argument_list->apply_visitor( &arguments_visitor_PTR ); vector< utf8_string > argument_C_expressions; auto num_args = defStmt->argument_list->total_size(); argument_C_expressions.reserve( num_args ); for( int i=0; i<num_args; i++) { argument_C_expressions.push_back( defStmt->argument_list->expression_from_index( i )->writer->get_C_expression() ); } defStmt->var_type->resolved_type->write_explicit_constructor(defStmt->argument_list.get(), defStmt->variable_symbol->C_name, argument_C_expressions, source_fout); expression_cleanup_visitor cleanup( source_fout ); defStmt->argument_list->apply_visitor( &cleanup ); } void source_statement_visitor::assignmentStmt_up(assignment_statement_AST_node* assignStmt, AST_visitor_base* LHS_reference_child, AST_visitor_base* expression_child) { source_expression_visitor expr_vistr( source_fout ); assignStmt->expression->apply_visitor( &expr_vistr ); auto exp = assignStmt->expression->writer->get_C_expression(); source_LHSreference_visitor LHS_vistr( source_fout, assignStmt->expression.get(), exp, assignStmt->expression->expression_return_type); assignStmt->LHS->apply_visitor( &LHS_vistr ); source_fout << endl; expression_cleanup_visitor cleanup( source_fout ); assignStmt->expression->apply_visitor( &cleanup ); LHSexpression_cleanup_visitor LHScleanup( source_fout ); assignStmt->LHS->apply_visitor( &LHScleanup ); } void source_statement_visitor::autoDefStmt_up(auto_definition_statement_AST_node* autoStmt, AST_visitor_base* expression_child) { if( write_definitions ) { autoStmt->variable_symbol->var_type->C_definition_name( autoStmt->variable_symbol->C_name, source_fout ); source_fout << ";" << endl; } /// not sure why this isn't a generic definition type??? autoStmt->variable_symbol->var_type->initialize( autoStmt->variable_symbol->C_name, source_fout ); source_expression_visitor expr_vistr( source_fout ); autoStmt->expression->apply_visitor( &expr_vistr ); // // auto exp = autoStmt->expression->writer->get_C_expression(); // autoStmt->variable_symbol->var_type->write_implicit_copy_constructor( autoStmt->expression->expression_return_type.get(), // autoStmt->expression.get(), autoStmt->variable_symbol->C_name, exp, source_fout ); // // write_implicit_copy_constructor(varType* RHS_type, expression_AST_node* RHS_AST_node, csu::utf8_string& LHS, // csu::utf8_string& RHS_exp, std::ostream& output); auto unnamed_args = make_shared<call_argument_list::unnamed_arguments_T>(autoStmt->loc); unnamed_args->add_argument( autoStmt->expression, autoStmt->expression->loc ); call_argument_list argument_nodes(autoStmt->loc, unnamed_args, nullptr ); argument_nodes.symbol_table = autoStmt->symbol_table; vector<csu::utf8_string> args; args.emplace_back( autoStmt->expression->writer->get_C_expression() ); autoStmt->variable_symbol->var_type->write_explicit_constructor( &argument_nodes, autoStmt->variable_symbol->C_name, args, source_fout); source_fout << endl; expression_cleanup_visitor cleanup( source_fout ); autoStmt->expression->apply_visitor( &cleanup ); } void source_statement_visitor::returnStatement_down(return_statement_AST_node* returnStmt) { source_expression_visitor expr_vistr( source_fout ); returnStmt->expression->apply_visitor( &expr_vistr ); auto ret_exp = returnStmt->expression->writer->get_C_expression(); // check if we need casting // this can be optimized if we need no casting auto return_type = returnStmt->callable_to_escape->return_type; auto expression_type = returnStmt->expression->expression_return_type; utf8_string argument_vname = "__cy__retTMP_" + returnStmt->symbol_table->get_unique_string(); return_type->C_definition_name(argument_vname, source_fout); source_fout << ';'<<endl; return_type->initialize(argument_vname, source_fout); if( return_type->has_implicit_copy_constructor( expression_type.get() ) ) { return_type->write_implicit_copy_constructor(expression_type.get(), returnStmt->expression.get(), argument_vname, ret_exp, source_fout); } else if( expression_type->can_implicit_castTo( return_type.get() ) ) { expression_type->write_implicit_castTo(return_type.get(), returnStmt->expression.get(), argument_vname, ret_exp , source_fout); } else { throw gen_exception("this should never be reached. In source_statement_visitor::returnStatement_down"); } // cleanup expression expression_cleanup_visitor cleanup( source_fout ); returnStmt->expression->apply_visitor( &cleanup ); // call destructors on active variables // first, find variables to destruct list<varName_ptr> variables_to_destruct; sym_table_base* current_symbol_table = returnStmt->symbol_table; sym_table_base* outer_symbol_table = returnStmt->callable_to_escape->symbol_table; while( true ) { if( current_symbol_table == outer_symbol_table) { break; } for(auto& x : current_symbol_table->variable_table) { auto current_var_name = x.second; if( current_var_name->loc.strictly_LT( returnStmt->loc ) ) { variables_to_destruct.push_back( current_var_name ); } } auto __current_symbol_table__ = dynamic_cast<local_sym_table*>( current_symbol_table ); current_symbol_table = __current_symbol_table__->parent_table; } // then..... DESTROY!! for( auto& var : variables_to_destruct ) { var->var_type->write_destructor( var->C_name, source_fout, not var->var_type->is_static_type() ); } // write return source_fout << "return " << argument_vname << ";" << endl; } void source_statement_visitor::constructElement_up(constructElement_AST_node* constructBlock, AST_visitor_base* exp_child, AST_visitor_base* argList_child) { source_expression_visitor expr_vistr( source_fout ); constructBlock->expression->apply_visitor( &expr_vistr ); source_expression_visitor arguments_visitor_PTR( source_fout ); constructBlock->argument_list->apply_visitor( &arguments_visitor_PTR ); vector< utf8_string > argument_C_expressions; auto num_args = constructBlock->argument_list->total_size(); argument_C_expressions.reserve( num_args ); for( int i=0; i<num_args; i++) { auto arg_exp = constructBlock->argument_list->expression_from_index( i )->writer->get_C_expression(); argument_C_expressions.push_back( arg_exp ); } auto exp = constructBlock->expression->writer->get_C_expression(); constructBlock->expression->expression_return_type->write_explicit_constructor(constructBlock->argument_list.get(), exp, argument_C_expressions, source_fout); expression_cleanup_visitor cleanup( source_fout ); constructBlock->expression->apply_visitor( &cleanup ); expression_cleanup_visitor args_cleanup( source_fout ); constructBlock->argument_list->apply_visitor( &args_cleanup ); } // writes the module setup function class source_moduleExpresion_visitor : public AST_visitorTree { // essentially skims top-level AST for simple expressions, and writes them to the setup function. // uses source_statement_visitor to actually do the writing. // does not write functions, classes, or complex thingies public: ofstream& source_fout; bool do_children; //true for module (first node applied), false for next level. Lower levels not done bool do_writing; // default is true. Set on way down to false if nesisary source_moduleExpresion_visitor(ofstream& _source_fout) : source_fout(_source_fout) { do_children = true; do_writing = true; } source_moduleExpresion_visitor(bool _do_children, ofstream& _source_fout) : source_fout(_source_fout) { do_children = _do_children; do_writing = true; } bool apply_to_children() override { return do_children; } shared_ptr< AST_visitor_base > make_child(int number) override { return make_shared<source_moduleExpresion_visitor>( false, source_fout ); } void module_down(module_AST_node* module) override { source_fout << "void " << module->module_name << "__init__(void){" << endl; } void module_up(module_AST_node* module, std::list<AST_visitor_base*>& visitor_children) override { /// destructors /// // annoying we have to write this twice? // this skims all top-level nodes, looking variables class destructuble_finder : public AST_visitor_NoChildren { public: list< varName_ptr > names_to_destruct; void autoDefStmt_down(auto_definition_statement_AST_node* autoStmt) { names_to_destruct.push_back( autoStmt->variable_symbol ); } void definitionStmt_down(definition_statement_AST_node* defStmt) { names_to_destruct.push_back( defStmt->variable_symbol ); } void definitionNconstructionStmt_down(definitionNconstruction_statement_AST_node* defStmt) { names_to_destruct.push_back( defStmt->variable_symbol ); } }; // apply it destructuble_finder finder; for( auto &AST_node : module->module_contents ) { AST_node->apply_visitor( &finder ); } // now destruct it all! for( auto var_to_destruct : finder.names_to_destruct ) { var_to_destruct->var_type->write_destructor( var_to_destruct->C_name, source_fout, not var_to_destruct->var_type->is_static_type() ); } /// END THE FUNCTION source_fout << "}" << endl; } // void definitionStmt_down(definition_statement_AST_node* defStmt) override // { // defStmt->var_type->resolved_type->write_default_constructor(defStmt->variable_symbol->C_name, source_fout); // // do_writing = false; // DO NOT WRITE DEFS! // } // // void autoDefStmt_down(auto_definition_statement_AST_node* autoStmt) override // { // source_expression_visitor expr_vistr( source_fout ); // autoStmt->expression->apply_visitor( &expr_vistr ); // // autoStmt->variable_symbol->var_type->write_assignment( autoStmt->expression->expression_return_type.get(), // autoStmt->variable_symbol->C_name, expr_vistr.C_expression_code, source_fout ); // source_fout << endl; // // do_writing = false; // 'cause its weird!! // } void statement_down(statement_AST_node* statment) override { if(do_writing) { source_statement_visitor statement_writer( source_fout, false ); statment->apply_visitor( &statement_writer ); } } }; // __init__ methods need to search for which class members are constructed // this horid thing "helps" with that search // this is one of the worst peices of code I've written...... and I've written some doozies! class member_constructor_finder : public AST_visitorTree { public: // first we have a list of construct_names, which we accumulate accross this visitor tree list< utf8_string > constructed_names; utf8_string search_name; member_constructor_finder() : search_name( "self" ) { } member_constructor_finder(utf8_string& _search_name) : search_name( _search_name ) { } shared_ptr< AST_visitor_base > make_child(int number) override { return make_shared<member_constructor_finder>( ); } void ASTnode_up(AST_node* ASTnode) { for( auto child : children) { auto cast_child = dynamic_pointer_cast<member_constructor_finder>( child ); for(auto &new_construct_name : cast_child->constructed_names) { constructed_names.emplace_back(new_construct_name); } } } // if we find a constructElement, we check if it matches the right structor, then append name to the constructed_names list void constructElement_down(constructElement_AST_node* constructBlock) { // this checks the first expression is an "accessor" expression of a "self" variable class helper_one : public AST_visitor_NoChildren { public: utf8_string member_name; bool is_good; utf8_string& search_name; helper_one(utf8_string& _search_name) : search_name( _search_name ) { is_good=false; } void accessorExp_down(accessor_expression_AST_node* accessorExp) { // this checks the inner bit is a var name of type "self" class helper_two : public AST_visitor_NoChildren { public: bool is_good; utf8_string& search_name; helper_two(utf8_string& _search_name) : search_name( _search_name ) { is_good=false; } void varReferance_down(varReferance_expression_AST_node* varRefExp) { is_good = (varRefExp->var_name == search_name); } }; helper_two checkerA( search_name ); accessorExp->expression->apply_visitor( &checkerA ); if( checkerA.is_good ) { is_good = true; member_name = accessorExp->name; } } }; helper_one checkerB( search_name ); constructBlock->expression->apply_visitor( &checkerB ); if(checkerB.is_good) { constructed_names.emplace_back( checkerB.member_name ); } } }; class source_function_visitor : public AST_visitorTree { // looks for functions and methods! and writes their source using the above expression writer. // probably needs to be VERY recursive due to nested functions (not presently implemented due to scoping problems) public: ofstream& source_fout; source_function_visitor(ofstream& _source_fout) : source_fout(_source_fout) { } shared_ptr< AST_visitor_base > make_child(int number) override { return make_shared<source_function_visitor>( source_fout ); } void funcDef_up(function_AST_node* funcDef, AST_visitor_base* returnType_child, AST_visitor_base* paramList_child, AST_visitor_base* funcBody_child) override { funcDef->specific_overload->write_C_prototype( source_fout ); source_fout << endl; source_fout << "{" << endl; /// write stuff for default params here!!! if( funcDef->paramList->defaulted_list ) { auto default_params = funcDef->paramList->defaulted_list; int num_params = default_params->param_list.size(); auto param_name_iter = default_params->param_list.begin(); auto default_exp_iter = default_params->parameter_defaults.begin(); for( int i=0; i<num_params; i++ ) { source_fout << "if("<< param_name_iter->variable_symbol->definition_name<<"__use_default__"<<"){"<<endl; source_expression_visitor expr_vistr( source_fout ); auto default_exp = *default_exp_iter; default_exp->apply_visitor( &expr_vistr ); auto C_exp = default_exp->writer->get_C_expression(); param_name_iter->var_type_ASTnode->resolved_type->write_implicit_copy_constructor(default_exp->expression_return_type.get(), default_exp.get(), param_name_iter->variable_symbol->C_name, C_exp, source_fout ); //param_name_iter->var_type_ASTnode->resolved_type->write_assignment( default_exp->expression_return_type.get(), default_exp.get(), // param_name_iter->variable_symbol->C_name, C_exp, source_fout ); expression_cleanup_visitor cleanup( source_fout ); default_exp->apply_visitor( &cleanup ); source_fout << "}"<<endl; } } //TODO! inform_moved!! // write block of statements source_statement_visitor statement_writer( source_fout ); funcDef->block_AST->apply_visitor( &statement_writer ); source_fout << "}" << endl << endl; } void methodDef_up(method_AST_node* methodDef, AST_visitor_base* returnType_child, AST_visitor_base* paramList_child, AST_visitor_base* methodBody_child) { auto self_var = methodDef->funcType->self_ptr_name; methodDef->specific_overload->write_C_prototype( source_fout ); source_fout << endl; source_fout << "{" << endl; /// write self pointer cast self_var->var_type->C_definition_name(self_var->C_name, source_fout); source_fout << " = (" ; utf8_string TMP(""); self_var->var_type->C_definition_name( TMP, source_fout); // hope this works!! source_fout << ")" << self_var->C_name << "_;" << endl; /// write stuff for default params here!!! if( methodDef->paramList->defaulted_list ) { auto default_params = methodDef->paramList->defaulted_list; int num_params = default_params->param_list.size(); auto param_name_iter = default_params->param_list.begin(); auto default_exp_iter = default_params->parameter_defaults.begin(); for( int i=0; i<num_params; i++ ) { source_fout << "if("<< param_name_iter->variable_symbol->definition_name<<"__use_default__"<<"){"<<endl; source_expression_visitor expr_vistr( source_fout ); auto default_exp = (*default_exp_iter); default_exp->apply_visitor( &expr_vistr ); auto default_C_exp = default_exp->writer->get_C_expression(); param_name_iter->var_type_ASTnode->resolved_type->write_implicit_copy_constructor( default_exp->expression_return_type.get(), default_exp.get(), param_name_iter->variable_symbol->C_name, default_C_exp, source_fout ); //param_name_iter->var_type_ASTnode->resolved_type->write_assignment( default_exp->expression_return_type.get(), default_exp.get(), // param_name_iter->variable_symbol->C_name, default_C_exp, source_fout ); expression_cleanup_visitor cleanup( source_fout ); default_exp->apply_visitor( &cleanup ); source_fout << "}"<<endl; } } //TODO! inform_moved!! // special stuff for special methods // __init__ and __exInit__ if( (methodDef->funcType->type_of_method == MethodType::constructor) or (methodDef->funcType->type_of_method == MethodType::explicit_constructor) ) { // step one, invoke the devil member_constructor_finder find_constructed_members; methodDef->block_AST->apply_visitor( &find_constructed_members ); //step two, recover the "self" symbol table auto class_type = dynamic_pointer_cast<DefClassType>( methodDef->class_type ); auto class_sym_table = class_type->class_symbol_table; //step three, search through all data members // if not constructed, write default cosntructor here for( auto &varName_ptr_pair : class_sym_table->variable_table ) { // check if constructed bool is_constructed = false; for( auto &var_name : find_constructed_members.constructed_names ) { if( var_name == varName_ptr_pair.first ) { is_constructed = true; break; } } // it not, construct it! if(not is_constructed) { utf8_string var_name( varName_ptr_pair.first ); auto Cexp = self_var->var_type->write_member_getter( self_var->C_name, var_name , source_fout ); auto var_type = varName_ptr_pair.second->var_type; auto C_exp_str = Cexp->get_C_expression(); var_type->write_default_constructor( C_exp_str, source_fout ); Cexp->write_cleanup(); } } } // make sense? // __convert__ and __exConvert__ if( (methodDef->funcType->type_of_method == MethodType::conversion) or (methodDef->funcType->type_of_method == MethodType::explicit_conversion) ) { // check members need reconstructed. auto parameter_name = methodDef->specific_overload->parameters->required_parameters.front(); auto parameter_type = parameter_name->var_type; if( parameter_type->type_of_type == varType::defined_class_t ) { // step one, invoke the devil member_constructor_finder find_constructed_members( parameter_name->definition_name ); methodDef->block_AST->apply_visitor( &find_constructed_members ); //step two, recover the "self" symbol table auto class_type = dynamic_pointer_cast<DefClassType>( parameter_type ); auto class_sym_table = class_type->class_symbol_table; //step three, search through all data members // if not constructed, write default cosntructor here for( auto &varName_ptr_pair : class_sym_table->variable_table ) { // check if constructed bool is_constructed = false; for( auto &var_name : find_constructed_members.constructed_names ) { if( var_name == varName_ptr_pair.first ) { is_constructed = true; break; } } // it not, construct it! if(not is_constructed) { utf8_string var_name( varName_ptr_pair.first ); auto Cexp = parameter_type->write_member_getter( parameter_name->C_name, var_name, source_fout ); auto var_type = varName_ptr_pair.second->var_type; auto Cexp_str = Cexp->get_C_expression(); var_type->write_default_constructor( Cexp_str, source_fout ); Cexp->write_cleanup(); } } } } // write block of statements source_statement_visitor statement_writer( source_fout ); methodDef->block_AST->apply_visitor( &statement_writer ); // __del__ if( methodDef->funcType->type_of_method == MethodType::destructor ) { auto class_type = dynamic_pointer_cast<DefClassType>( methodDef->class_type ); auto class_sym_table = class_type->class_symbol_table; for( auto &varName_ptr_pair : class_sym_table->variable_table ) { utf8_string var_name( varName_ptr_pair.first ); auto Cexp = self_var->var_type->write_member_getter( self_var->C_name, var_name , source_fout ); auto Cexp_str = Cexp->get_C_expression(); auto var_type = varName_ptr_pair.second->var_type; var_type->write_destructor( Cexp_str, source_fout, not var_type->is_static_type() ); Cexp->write_cleanup(); } } source_fout << "}" << endl << endl; } void ClassDef_up( class_AST_node* clss_node, std::list<AST_visitor_base*>& var_def_children, std::list<AST_visitor_base*>& method_def_children, AST_visitor_base* inheritanceList_child ) { /// need to write out the defaulted methods /// auto self_var = clss_node->self_name; // defaulted constructor if( clss_node->write_default_constructor ) { clss_node->default_constructor_overload->write_C_prototype( source_fout ); source_fout << endl; source_fout << "{" << endl; /// write self pointer cast self_var->var_type->C_definition_name(self_var->C_name, source_fout); source_fout << " = (" ; utf8_string TMP(""); self_var->var_type->C_definition_name( TMP, source_fout); // hope this works!! source_fout << ")" << self_var->C_name << "_;" << endl; /// then initiate the members auto class_sym_table = clss_node->type_ptr->class_symbol_table; for( auto &varName_ptr_pair : class_sym_table->variable_table ) { if( varName_ptr_pair.first == "self" ) { continue; } utf8_string var_name( varName_ptr_pair.first ); // TODO, getref???? auto Cexp = self_var->var_type->write_member_getter( self_var->C_name, var_name , source_fout ); auto Cexp_str = Cexp->get_C_expression(); auto var_type = varName_ptr_pair.second->var_type; var_type->write_default_constructor( Cexp_str, source_fout ); Cexp->write_cleanup(); } source_fout << "}" << endl << endl; } // defaulted destructor if( clss_node->write_default_deconstructor ) { clss_node->default_destructor_overload->write_C_prototype( source_fout ); source_fout << endl; source_fout << "{" << endl; /// write self pointer cast self_var->var_type->C_definition_name(self_var->C_name, source_fout); source_fout << " = (" ; utf8_string TMP(""); self_var->var_type->C_definition_name( TMP, source_fout); // hope this works!! source_fout << ")" << self_var->C_name << "_;" << endl; /// and destruct all the other things auto class_sym_table = clss_node->type_ptr->class_symbol_table; for( auto &varName_ptr_pair : class_sym_table->variable_table ) { if( varName_ptr_pair.first == "self" ) { continue; } utf8_string var_name( varName_ptr_pair.first ); auto Cexp = self_var->var_type->write_member_getref( self_var->C_name, var_name , source_fout ); auto Cexp_str = Cexp->get_C_expression(); auto var_type = varName_ptr_pair.second->var_type; var_type->write_destructor( Cexp_str, source_fout, not var_type->is_static_type() ); Cexp->write_cleanup(); } source_fout << "}" << endl << endl; } //defaulted copy constructor if( clss_node->write_selfCopy_constructor ) { clss_node->default_CopyConstructor_overload->write_C_prototype( source_fout ); source_fout << endl; source_fout << "{" << endl; /// write self pointer cast self_var->var_type->C_definition_name(self_var->C_name, source_fout); source_fout << " = (" ; utf8_string TMP(""); self_var->var_type->C_definition_name( TMP, source_fout); // hope this works!! source_fout << ")" << self_var->C_name << "_;" << endl; //TODO! inform_moved!! /// copy other variables. auto class_sym_table = clss_node->type_ptr->class_symbol_table; for( auto &varName_ptr_pair : class_sym_table->variable_table ) { if( varName_ptr_pair.first == "self" ) { continue; } auto TYPE = varName_ptr_pair.second->var_type; if( TYPE->has_implicit_copy_constructor(TYPE.get()) ) { utf8_string name = varName_ptr_pair.first ; auto Cexp = self_var->var_type->write_member_getref( self_var->C_name, name, source_fout ); auto Cexp_str = Cexp->get_C_expression(); utf8_string RHS = "(__cy__arg_RHS->"+varName_ptr_pair.second->C_name; RHS += ")"; // I hope this works! varReferance_expression_AST_node RHS_ast(name, clss_node->loc ); RHS_ast.variable_symbol = varName_ptr_pair.second; RHS_ast.expression_return_type = TYPE; RHS_ast.symbol_table = clss_node->symbol_table; TYPE->write_implicit_copy_constructor(TYPE.get(), &RHS_ast, Cexp_str, RHS, source_fout); source_fout << endl; Cexp->write_cleanup(); } } source_fout << "}" << endl << endl; } } }; //// the main function //// void write_module_to_C(module_AST_ptr module) { //// first we write the header /// string header_fname = module->file_name + ".h"; string source_fname = module->file_name + ".c"; ofstream C_header_file(header_fname); module->C_header_fname = header_fname; module->C_source_fname = source_fname; //header_fname = "DELME_" + header_fname; //source_fname = "DELME_" + source_fname; // imports // header_writeImports_visitor import_writer(C_header_file, header_fname); module->apply_visitor( &import_writer ); // definitions // header_writeDefinitions_visitor definitions_writer(C_header_file, header_fname); module->apply_visitor( &definitions_writer ); //// now we write the source files //// ofstream C_source_file(source_fname); // preamble, anything that needs to come before main body source_writePreamble_visitor preamble_writer(C_source_file, header_fname); module->apply_visitor( &preamble_writer ); // main body // functions! source_function_visitor function_writer(C_source_file); module->apply_visitor( &function_writer ); // module setup (top level expressions, call other module setups) source_moduleExpresion_visitor initilizer_writer(C_source_file); module->apply_visitor( &initilizer_writer ); // write main function? if( module->main_status == 1 ) { string source_main_fname( module->file_name + "_main.c" ); module->C_mainSource_fname = source_main_fname; //source_main_fname = "DELME_" + source_main_fname; ofstream C_source_main_file(source_main_fname); C_source_main_file << "#include \"" << header_fname << "\"" <<endl; C_source_main_file << "void main(void){" <<endl; // write prep functions for all other modules here!! C_source_main_file << module->module_name << "__init__();" << endl; C_source_main_file << module->main_func_name << "();" << endl; C_source_main_file << '}' << endl; } }
37.826923
180
0.649874
[ "vector" ]
8d7cbdd3cd71eeb331383ca8cc1544ac18a32f19
17,588
cpp
C++
apps/tutorials/ospTutorialVolumePathTracer.cpp
ethan0911/ospray-tamr-fork
553d2e31a7e7ff165fcc70063652fa42d1082de4
[ "Apache-2.0" ]
null
null
null
apps/tutorials/ospTutorialVolumePathTracer.cpp
ethan0911/ospray-tamr-fork
553d2e31a7e7ff165fcc70063652fa42d1082de4
[ "Apache-2.0" ]
null
null
null
apps/tutorials/ospTutorialVolumePathTracer.cpp
ethan0911/ospray-tamr-fork
553d2e31a7e7ff165fcc70063652fa42d1082de4
[ "Apache-2.0" ]
null
null
null
// ======================================================================== // // Copyright 2018-2019 Intel Corporation // // // // 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 <memory> #include <random> #include "GLFWOSPRayWindow.h" #include "ospcommon/math/range.h" #include "ospcommon/math/box.h" #include "ospcommon/tasking/parallel_for.h" #include "ospcommon/utility/multidim_index_sequence.h" #include "ospray_testing.h" #include "tutorial_util.h" #include <imgui.h> using namespace ospcommon; static std::string renderer_type = "pathtracer"; /* heavily based on Perlin's Java reference implementation of * the improved perlin noise paper from Siggraph 2002 from here * https://mrl.nyu.edu/~perlin/noise/ **/ class PerlinNoise { struct PerlinNoiseData { PerlinNoiseData() { const int permutation[256] = { 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99, 37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32, 57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27, 166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245, 40,244, 102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130, 116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202, 38,147, 118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189, 28, 42,223,183,170,213, 119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108, 110,79,113,224,232,178,185,112,104,218,246,97,228,251, 34,242,193,238,210,144,12, 191,179,162,241,81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67, 29, 24, 72,243, 141,128,195,78,66,215,61,156,180 }; for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } inline int operator[](size_t idx) const { return p[idx]; } int p[512]; }; static PerlinNoiseData p; static inline float smooth(float t) { return t * t * t * (t * (t * 6.f - 15.f) + 10.f); } static inline float lerp (float t, float a, float b) { return a + t * (b - a); } static inline float grad(int hash, float x, float y, float z) { const int h = hash & 15; const float u = h < 8 ? x : y; const float v = h < 4 ? y : h == 12 || h == 14 ? x : z; return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); } public: static float noise(vec3f q, float frequency = 8.f) { float x = q.x * frequency; float y = q.y * frequency; float z = q.z * frequency; const int X = (int)floor(x) & 255; const int Y = (int)floor(y) & 255; const int Z = (int)floor(z) & 255; x -= floor(x); y -= floor(y); z -= floor(z); const float u = smooth(x); const float v = smooth(y); const float w = smooth(z); const int A = p[X] + Y; const int B = p[X + 1] + Y; const int AA = p[A] + Z; const int BA = p[B] + Z; const int BB = p[B + 1] + Z; const int AB = p[A + 1] + Z; return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)), lerp(u, grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z))), lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1)), lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1)))); } }; PerlinNoise::PerlinNoiseData PerlinNoise::p; OSPGeometry PlaneGeometry(const vec4f& color, const AffineSpace3f& M) { const vec3f normal = xfmNormal(M, vec3f(0.f, 1.f, 0.f)); std::vector<vec3f> positions { xfmPoint(M, vec3f(-1.f, 0.f, -1.f)), xfmPoint(M, vec3f(+1.f, 0.f, -1.f)), xfmPoint(M, vec3f(+1.f, 0.f, +1.f)), xfmPoint(M, vec3f(-1.f, 0.f, +1.f)), }; std::vector<vec3f> normals { normal, normal, normal, normal }; std::vector<vec4f> colors { color, color, color, color }; std::vector<vec4i> indices { vec4i(0, 1, 2, 3) }; //std::vector<vec3i> indices { vec3i(0, 1, 2) }; OSPData positionData = ospNewData(positions.size(), OSP_VEC3F, positions.data()); OSPData normalData = ospNewData(normals.size(), OSP_VEC3F, normals.data()); OSPData colorData = ospNewData(colors.size(), OSP_VEC4F, colors.data()); OSPData indexData = ospNewData(indices.size(), OSP_VEC4UI, indices.data()); OSPGeometry ospGeometry = ospNewGeometry("quads"); ospSetData(ospGeometry, "vertex.position", positionData); ospSetData(ospGeometry, "vertex.normal", normalData); ospSetData(ospGeometry, "vertex.color", colorData); ospSetData(ospGeometry, "index", indexData); ospCommit(ospGeometry); return ospGeometry; } OSPGeometry PlaneGeometry(const vec4f& color) { return PlaneGeometry(color, AffineSpace3f(one)); } OSPGeometry PlaneGeometry(const AffineSpace3f& M) { return PlaneGeometry(vec4f(0.8f, 0.8f, 0.8f, 1.f), M); } OSPGeometry PlaneGeometry() { return PlaneGeometry(vec4f(0.8f, 0.8f, 0.8f, 1.f), AffineSpace3f(one)); } OSPGeometry BoxGeometry(const box3f& box) { auto ospGeometry = ospNewGeometry("boxes"); auto ospData = ospNewData(1, OSP_BOX3F, &box); ospSetData(ospGeometry, "box", ospData); ospRelease(ospData); ospCommit(ospGeometry); return ospGeometry; } OSPVolumetricModel CreateProceduralVolumetricModel( std::function<bool(vec3f p)> D, std::vector<vec3f> colors, std::vector<float> opacities, float densityScale, float anisotropy) { vec3l dims{256, 256, 256}; // should be at least 2 const float spacing = 3.f/(reduce_max(dims)-1); OSPVolume volume = ospNewVolume("shared_structured_volume"); // generate volume data auto numVoxels = dims.product(); std::vector<float> voxels(numVoxels, 0); tasking::parallel_for(dims.z, [&](int64_t z) { for (int y = 0; y < dims.y; ++y) { for (int x = 0; x < dims.x; ++x) { vec3f p = vec3f(x+0.5f, y+0.5f, z+0.5f)/dims; if (D(p)) voxels[dims.x * dims.y * z + dims.x * y + x] = 0.5f + 0.5f * PerlinNoise::noise(p, 12); } } }); // calculate voxel range range1f voxelRange; std::for_each(voxels.begin(), voxels.end(), [&](float &v) { if (!std::isnan(v)) voxelRange.extend(v); }); OSPData voxelData = ospNewData(numVoxels, OSP_FLOAT, voxels.data()); ospSetObject(volume, "voxelData", voxelData); ospRelease(voxelData); ospSetInt(volume, "voxelType", OSP_FLOAT); ospSetVec3i(volume, "dimensions", dims.x, dims.y, dims.z); ospSetVec3f(volume, "gridOrigin", -1.5f, -1.5f, -1.5f); ospSetVec3f(volume, "gridSpacing", spacing, spacing, spacing); ospCommit(volume); OSPTransferFunction tfn = ospNewTransferFunction("piecewise_linear"); ospSetVec2f(tfn, "valueRange", voxelRange.lower, voxelRange.upper); OSPData tfColorData = ospNewData(colors.size(), OSP_VEC3F, colors.data()); ospSetData(tfn, "color", tfColorData); ospRelease(tfColorData); OSPData tfOpacityData = ospNewData(opacities.size(), OSP_FLOAT, opacities.data()); ospSetData(tfn, "opacity", tfOpacityData); ospRelease(tfOpacityData); ospCommit(tfn); auto volumeModel = ospNewVolumetricModel(volume); ospSetFloat(volumeModel, "densityScale", densityScale); ospSetFloat(volumeModel, "anisotropy", anisotropy); ospSetObject(volumeModel, "transferFunction", tfn); ospCommit(volumeModel); ospRelease(tfn); ospRelease(volume); return volumeModel; } OSPGeometricModel CreateGeometricModel(OSPGeometry geo, const vec3f& kd) { OSPGeometricModel geometricModel = ospNewGeometricModel(geo); OSPMaterial objMaterial = ospNewMaterial(renderer_type.c_str(), "OBJMaterial"); ospSetVec3f(objMaterial, "Kd", kd.x, kd.y, kd.z); ospCommit(objMaterial); ospSetObject(geometricModel, "material", objMaterial); ospRelease(objMaterial); return geometricModel; } OSPInstance CreateInstance(OSPGroup group, const AffineSpace3f& xfm) { OSPInstance instance = ospNewInstance(group); ospSetAffine3fv(instance, "xfm", &xfm.l.vx.x); return instance; } int main(int argc, const char **argv) { initializeOSPRay(argc, argv); for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "-r" || arg == "--renderer") renderer_type = argv[++i]; } float densityScale = 10.0f; float anisotropy = 0.0f; auto turbulence = [](const vec3f& p, float base_freqency, int octaves) { float value = 0.f; float scale = 1.f; for (int o = 0; o < octaves; ++o) { value += PerlinNoise::noise(scale*p, base_freqency)/scale; scale *= 2.f; } return value; }; auto torus = [](vec3f X, float R, float r) -> bool { const float tmp = sqrtf(X.x * X.x + X.z * X.z) - R; return tmp*tmp + X.y*X.y - r*r < 0.f; }; std::vector<OSPVolumetricModel> volumetricModels; volumetricModels.emplace_back(CreateProceduralVolumetricModel( [&](vec3f p) { vec3f X = 2.f * p - vec3f(1.f); return length((1.4f + 0.4 * turbulence(p, 12.f, 12)) * X) < 1.f; }, {vec3f(0.f, 0.0f, 0.f), vec3f(1.f, 0.f, 0.f), vec3f(0.f, 1.f, 1.f), vec3f(1.f, 1.f, 1.f)}, {0.f, 0.33f, 0.66f, 1.f}, densityScale, anisotropy)); volumetricModels.emplace_back(CreateProceduralVolumetricModel( [&](vec3f p) { vec3f X = 2.f * p - vec3f(1.f); return torus((1.4f + 0.4 * turbulence(p, 12.f, 12)) * X, 0.75f, 0.175f); }, {vec3f(0.0, 0.0, 0.0), vec3f(1.0, 0.65, 0.0), vec3f(0.12, 0.6, 1.0), vec3f(1.0, 1.0, 1.0)}, {0.f, 0.33f, 0.66f, 1.f}, densityScale, anisotropy)); for (auto volumetricModel : volumetricModels) { ospCommit(volumetricModel); } // create geometries auto box1 = BoxGeometry(box3f(vec3f(-1.5f, -1.f, -0.75f), vec3f(-0.5f, 0.f, 0.25f))); auto box2 = BoxGeometry(box3f(vec3f(0.0f, -1.5f, 0.f), vec3f(2.f, 1.5f, 2.f))); auto plane = PlaneGeometry(vec4f(vec3f(1.0f), 1.f), AffineSpace3f::translate(vec3f(0.f, -2.5f, 0.f)) * AffineSpace3f::scale(vec3f(10.f, 1.f, 10.f))); std::vector<OSPGeometricModel> geometricModels; geometricModels.emplace_back(CreateGeometricModel(box1, vec3f(0.2f, 0.2f, 0.2f))); geometricModels.emplace_back(CreateGeometricModel(box2, vec3f(0.2f, 0.2f, 0.2f))); geometricModels.emplace_back(CreateGeometricModel(plane, vec3f(0.2f, 0.2f, 0.2f))); ospRelease(box1); ospRelease(box2); ospRelease(plane); for (auto geometricModel : geometricModels) { ospCommit(geometricModel); } OSPWorld world = ospNewWorld(); OSPGroup group_geometry = ospNewGroup(); std::vector<OSPGroup> volumetricGroups; for (size_t i = 0; i < volumetricModels.size(); ++i) volumetricGroups.emplace_back(ospNewGroup()); std::vector<OSPInstance> instances; instances.emplace_back(CreateInstance(group_geometry, one)); instances.emplace_back(CreateInstance(volumetricGroups[0], AffineSpace3f::translate(vec3f(0.f, -0.5f, 0.f)) * AffineSpace3f::scale(vec3f(1.25f)))); instances.emplace_back(CreateInstance(volumetricGroups[1], AffineSpace3f::translate(vec3f(0.f, -0.5f, 0.f)) * AffineSpace3f::scale(vec3f(2.5)))); for (auto instance : instances) ospCommit(instance); OSPData instance_data = ospNewData(instances.size(), OSP_INSTANCE, instances.data()); ospSetData(world, "instance", instance_data); ospRelease(instance_data); // create OSPRay renderer int maxDepth = 1024; int rouletteDepth = 32; OSPRenderer renderer = ospNewRenderer(renderer_type.c_str()); ospSetInt(renderer, "maxDepth", maxDepth); ospSetInt(renderer, "rouletteDepth", rouletteDepth); ospSetFloat(renderer, "minContribution", 0.f); std::vector<OSPLight> light_handles; OSPLight quadLight = ospNewLight("quad"); ospSetVec3f(quadLight, "position", -4.0f, 3.0f, 1.0f); ospSetVec3f(quadLight, "edge1", 0.f, 0.0f, -1.0f); ospSetVec3f(quadLight, "edge2", 1.0f, 0.5, 0.0f); ospSetFloat(quadLight, "intensity", 50.0f); ospSetVec3f(quadLight, "color", 2.6f, 2.5f, 2.3f); ospCommit(quadLight); OSPLight ambientLight = ospNewLight("ambient"); ospSetFloat(ambientLight, "intensity", 0.4f); ospSetVec3f(ambientLight, "color", 1.f, 1.f, 1.f); ospCommit(ambientLight); bool showVolume = true; bool showGeometry = false; bool enableQuadLight = true; bool enableAmbientLight = false; auto updateScene = [&]() { ospRemoveParam(group_geometry, "geometry"); for (auto group : volumetricGroups) ospRemoveParam(group, "volume"); if (showVolume) { for (size_t i = 0; i < volumetricGroups.size(); ++i) { OSPData volumes = ospNewData(1, OSP_VOLUMETRIC_MODEL, &volumetricModels[i]); ospSetObject(volumetricGroups[i], "volume", volumes); ospRelease(volumes); } } if (showGeometry) { OSPData geometries = ospNewData( geometricModels.size(), OSP_GEOMETRIC_MODEL, geometricModels.data()); ospSetObject(group_geometry, "geometry", geometries); ospRelease(geometries); } light_handles.clear(); if (enableQuadLight) light_handles.push_back(quadLight); if (enableAmbientLight) light_handles.push_back(ambientLight); OSPData lights = ospNewData(light_handles.size(), OSP_LIGHT, light_handles.data(), 0); ospSetData(renderer, "light", lights); ospCommit(lights); ospRelease(lights); }; updateScene(); ospCommit(group_geometry); for (auto group : volumetricGroups) ospCommit(group); ospCommit(world); // create a GLFW OSPRay window: this object will create and manage the OSPRay // frame buffer and camera directly auto glfwOSPRayWindow = std::unique_ptr<GLFWOSPRayWindow>( new GLFWOSPRayWindow(vec2i{1024, 768}, box3f(vec3f(-2.2f, -1.2f, -3.2f), vec3f(1.2f, 1.2f, 1.2f)), world, renderer)); // ImGui // glfwOSPRayWindow->registerImGuiCallback([&]() { bool updateWorld = false; bool commitWorld = false; if (ImGui::SliderInt("maxDepth", &maxDepth, 0, 1024)) { commitWorld = true; ospSetInt(renderer, "maxDepth", maxDepth); glfwOSPRayWindow->addObjectToCommit(renderer); } if (ImGui::SliderInt("rouletteDepth", &rouletteDepth, 0, 1024)) { commitWorld = true; ospSetInt(renderer, "rouletteDepth", rouletteDepth); glfwOSPRayWindow->addObjectToCommit(renderer); } if (ImGui::Checkbox("Show Volume", &showVolume)) updateWorld = true; if (ImGui::Checkbox("Show Geometry", &showGeometry)) updateWorld = true; if (ImGui::Checkbox("Quad Light", &enableQuadLight)) updateWorld = true; if (ImGui::Checkbox("Ambient Light", &enableAmbientLight)) updateWorld = true; commitWorld = updateWorld; if (ImGui::SliderFloat("densityScale", &densityScale, 0.f, 50.f)) { commitWorld = true; for (auto vModel : volumetricModels) { ospSetFloat(vModel, "densityScale", densityScale); glfwOSPRayWindow->addObjectToCommit(vModel); } } if (ImGui::SliderFloat("anisotropy", &anisotropy, -1.f, 1.f)) { commitWorld = true; for (auto vModel : volumetricModels) { ospSetFloat(vModel, "anisotropy", anisotropy); glfwOSPRayWindow->addObjectToCommit(vModel); } } if (updateWorld) updateScene(); if (commitWorld) { glfwOSPRayWindow->addObjectToCommit(group_geometry); for (auto group : volumetricGroups) glfwOSPRayWindow->addObjectToCommit(group); glfwOSPRayWindow->addObjectToCommit(world); glfwOSPRayWindow->addObjectToCommit(renderer); } }); glfwOSPRayWindow->getArcballCamera()->setRotation(quaternionf(-0.91f, 0.34f, 0.22f, -0.08f)); glfwOSPRayWindow->updateCamera(); glfwOSPRayWindow->commitCamera(); // start the GLFW main loop, which will continuously render glfwOSPRayWindow->mainLoop(); // cleanup remaining objects for (auto volumetricModel : volumetricModels) ospRelease(volumetricModel); for(auto geometricModel : geometricModels) ospRelease(geometricModel); ospRelease(group_geometry); for (auto group : volumetricGroups) ospRelease(group); for (auto instance : instances) ospRelease(instance); // cleanly shut OSPRay down ospShutdown(); return 0; }
36.794979
151
0.623834
[ "geometry", "render", "object", "vector" ]
8d7fe9dd6ab5f03d9d34f0a4e0a82554be9c9b00
2,508
cpp
C++
source/utopian/core/renderer/jobs/BlurJob.cpp
simplerr/Papageno
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
[ "MIT" ]
null
null
null
source/utopian/core/renderer/jobs/BlurJob.cpp
simplerr/Papageno
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
[ "MIT" ]
null
null
null
source/utopian/core/renderer/jobs/BlurJob.cpp
simplerr/Papageno
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
[ "MIT" ]
null
null
null
#include "core/renderer/jobs/BlurJob.h" #include "core/renderer/jobs/SSAOJob.h" #include "core/renderer/CommonJobIncludes.h" #include "vulkan/EffectManager.h" namespace Utopian { BlurJob::BlurJob(Vk::Device* device, uint32_t width, uint32_t height) : BaseJob(device, width, height) { blurImage = std::make_shared<Vk::ImageColor>(device, width, height, VK_FORMAT_R16G16B16A16_SFLOAT, "Blur image"); mRenderTarget = std::make_shared<Vk::RenderTarget>(device, width, height); mRenderTarget->AddWriteOnlyColorAttachment(blurImage); mRenderTarget->SetClearColor(1, 1, 1, 1); mRenderTarget->Create(); /*const uint32_t size = 240; gScreenQuadUi().AddQuad(10, height - (size + 10), size, size, blurImage.get(), renderTarget->GetSampler());*/ } BlurJob::~BlurJob() { } void BlurJob::LoadResources() { auto loadShader = [&]() { Vk::EffectCreateInfo effectDesc; effectDesc.shaderDesc.vertexShaderPath = "data/shaders/common/fullscreen.vert"; effectDesc.shaderDesc.fragmentShaderPath = "data/shaders/blur/blur.frag"; mEffect = Vk::gEffectManager().AddEffect<Vk::Effect>(mDevice, mRenderTarget->GetRenderPass(), effectDesc); }; loadShader(); } void BlurJob::PostInit(const std::vector<BaseJob*>& jobs, const GBuffer& gbuffer) { SSAOJob* ssaoJob = static_cast<SSAOJob*>(jobs[JobGraph::SSAO_INDEX]); settingsBlock.Create(mDevice, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); mEffect->BindUniformBuffer("UBO_settings", settingsBlock); mEffect->BindCombinedImage("inputTexture", *ssaoJob->ssaoImage, *ssaoJob->renderTarget->GetSampler()); } void BlurJob::Init(const std::vector<BaseJob*>& jobs, const GBuffer& gbuffer) { } void BlurJob::Render(const JobInput& jobInput) { settingsBlock.data.blurRange = jobInput.renderingSettings.blurRadius; settingsBlock.UpdateMemory(); mRenderTarget->Begin("SSAO blur pass", glm::vec4(0.5, 1.0, 0.0, 1.0)); Vk::CommandBuffer* commandBuffer = mRenderTarget->GetCommandBuffer(); if (IsEnabled()) { // Todo: Should this be moved to the effect instead? commandBuffer->CmdBindPipeline(mEffect->GetPipeline()); commandBuffer->CmdBindDescriptorSets(mEffect); gRendererUtility().DrawFullscreenQuad(commandBuffer); } mRenderTarget->End(GetWaitSemahore(), GetCompletedSemahore()); } }
34.356164
119
0.688198
[ "render", "vector" ]
8d808c99ec26df917a573f882897ab83ec300f8c
2,253
cpp
C++
CSES/Dynamic Programming/GridPaths.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
CSES/Dynamic Programming/GridPaths.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
null
null
null
CSES/Dynamic Programming/GridPaths.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define deb(x) cout << #x << " is " << x << "\n" #define int long long const int mod = 1000000007; const int inf = 1e18; const long double pi = acos(-1); template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; template <typename T> using max_heap = priority_queue<T>; template <class T> using ordered_set = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>; template <typename... T> void read(T &...args) { ((cin >> args), ...); } template <typename... T> void write(T &&...args) { ((cout << args), ...); } template <typename T> void readContainer(T &t) { for (auto &e : t) { read(e); } } template <typename T> void writeContainer(T &t) { for (const auto &e : t) { write(e, " "); } write("\n"); } int findNumberOfPaths(const vector<vector<char>> &grid, int row, int col) { if (row >= grid.size() or col >= grid[0].size() or grid[row][col] == '*') { return 0; } else if (row == grid.size() - 1 and col == grid[0].size() - 1) { return 1; } else { int right = findNumberOfPaths(grid, row, col + 1); int bottom = findNumberOfPaths(grid, row + 1, col); return (right + bottom) % mod; } } void solve() { int n; read(n); vector<vector<char>> grid(n, vector<char>(n)); for (auto &row : grid) readContainer(row); vector<vector<int>> paths(n, vector<int>(n, 0)); paths[0][0] = (grid[0][0] == '.' ? 1 : 0); for (int row = 0; row < n; ++row) { for (int col = 0; col < n; ++col) { if (grid[row][col] == '*') continue; if (row - 1 >= 0) { paths[row][col] += paths[row - 1][col]; paths[row][col] %= mod; } if (col - 1 >= 0) { paths[row][col] += paths[row][col - 1]; paths[row][col] %= mod; } } } write(paths.back().back()); } signed main() { auto start = chrono::high_resolution_clock::now(); ios::sync_with_stdio(false); cin.tie(nullptr); int T = 1; // read(T); for (int t = 1; t <= T; ++t) { solve(); } auto end = chrono::high_resolution_clock::now(); chrono::duration<double, milli> duration = end - start; // write("Time Taken = ", duration.count(), " ms\n"); }
23.46875
102
0.600533
[ "vector" ]
8d856e344f6f2174b23747b1894a42e66b3ca33e
7,010
hpp
C++
engine/includes/graphics/transform.hpp
StuartDAdams/neon
d08a63b853801aec94390e50f2988d0217438061
[ "MIT" ]
1
2019-08-22T14:43:18.000Z
2019-08-22T14:43:18.000Z
engine/includes/graphics/transform.hpp
StuartDAdams/neon
d08a63b853801aec94390e50f2988d0217438061
[ "MIT" ]
null
null
null
engine/includes/graphics/transform.hpp
StuartDAdams/neon
d08a63b853801aec94390e50f2988d0217438061
[ "MIT" ]
null
null
null
/* =========================================================================== Moka Source Code Copyright 2019 Stuart Adams. All rights reserved. https://github.com/stuartdadams/moka stuartdadams | linkedin.com/in/stuartdadams This file is part of the Moka Real-Time Physically-Based Rendering Project. 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. =========================================================================== */ #pragma once #include <glm/glm.hpp> #include <glm/gtx/quaternion.hpp> namespace moka { /** * \brief A transform class enclosing a position, scale and rotation. */ class transform final { glm::vec3 position_; glm::vec3 scale_; glm::quat rotation_; public: /** * \brief Create a transform object. * \param position The transform position. * \param scale The transform scale. * \param rotation The transform rotation. */ transform(const glm::vec3& position, const glm::vec3& scale, const glm::quat& rotation); transform(); transform(const transform& rhs); transform& operator=(const transform& rhs); transform(transform&& rhs) noexcept; transform& operator=(transform&& rhs) noexcept; ~transform() = default; /** * \brief Get the transform's local position. * \return The transform's local position. */ const glm::vec3& get_position() const; /** * \brief Get the transform's world position. * \return The transform's world position. */ glm::vec3 get_world_position() const; /** * \brief Get the transform's local scale. * \return The transform's local scale. */ const glm::vec3& get_scale() const; /** * \brief Get the transform's local rotation. * \return The transform's local rotation. */ const glm::quat& get_rotation() const; /** * \brief Convert this transform to a mat4. * \return A mat4 defining the transform. */ glm::mat4 to_matrix() const; /** * \brief Convert this transform to a mat4. */ explicit operator glm::mat4() const; /** * \brief Set this transform's position. * \param position The new position. */ void set_position(const glm::vec3& position); /** * \brief Set this transform's scale. * \param scale The new scale. */ void set_scale(const glm::vec3& scale); /** * \brief Set this transform's rotation. * \param rotation The new rotation. */ void set_rotation(const glm::quat& rotation); /** * \brief Get the world front direction. * \return The world front direction. */ static glm::vec3 world_front(); /** * \brief Get the world back direction. * \return The world back direction. */ static glm::vec3 world_back(); /** * \brief Get the world up direction. * \return The world up direction. */ static glm::vec3 world_up(); /** * \brief Get the world down direction. * \return The world down direction. */ static glm::vec3 world_down(); /** * \brief Get the world right direction. * \return The world right direction. */ static glm::vec3 world_right(); /** * \brief Get the world left direction. * \return The world left direction. */ static glm::vec3 world_left(); /** * \brief Get the world origin. * \return The world origin. */ static glm::vec3 world_origin(); /** * \brief Get the transform's front direction. * \return The transform's front direction. */ glm::vec3 front() const; /** * \brief Get the transform's back direction. * \return The transform's back direction. */ glm::vec3 back() const; /** * \brief Get the transform's right direction. * \return The transform's right direction. */ glm::vec3 right() const; /** * \brief Get the transform's left direction. * \return The transform's left direction. */ glm::vec3 left() const; /** * \brief Get the transform's up direction. * \return The transform's up direction. */ glm::vec3 up() const; /** * \brief Get the transform's down direction. * \return The transform's down direction. */ glm::vec3 down() const; /** * \brief Rotate this transform around a point. * \param point The point you want to rotate around. * \param rotation The rotation. */ void rotate_around(const glm::vec3& point, const glm::quat& rotation); /** * \brief Rotate this transform around a point. * \param point The point you want to rotate around. * \param axis The rotation axis. * \param angle The rotation angle. */ void rotate_around(const glm::vec3& point, const glm::vec3& axis, float angle); /** * \brief Make the transform look at a point in world space. * \param world_location The point you want this transform to look at. * \param world_up The world up direction. */ void look_at(const glm::vec3& world_location, const glm::vec3& world_up = transform::world_up()); /** * \brief Generate a transform from a matrix. * \param m The matrix you want to turn into a transform. * \return The new transform object. */ static transform from_matrix(const glm::mat4& m); }; } // namespace moka
30.745614
105
0.577461
[ "object", "transform" ]
8d8bbd85b47b3fd7ce7db1a41ff74adb68f23556
32,292
cpp
C++
Engine/Source/Editor/DetailCustomizations/Private/DetailCustomizations.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Editor/DetailCustomizations/Private/DetailCustomizations.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Editor/DetailCustomizations/Private/DetailCustomizations.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "DetailCustomizations.h" #include "Modules/ModuleManager.h" #include "PropertyEditorModule.h" #include "StaticMeshComponentDetails.h" #include "LightComponentDetails.h" #include "PointLightComponentDetails.h" #include "DirectionalLightComponentDetails.h" #include "SceneComponentDetails.h" #include "BodyInstanceCustomization.h" #include "PrimitiveComponentDetails.h" #include "StaticMeshActorDetails.h" #include "SkinnedMeshComponentDetails.h" #include "SkeletalMeshComponentDetails.h" #include "SplineComponentDetails.h" #include "MeshComponentDetails.h" #include "MatineeActorDetails.h" #include "LevelSequenceActorDetails.h" #include "ReflectionCaptureDetails.h" #include "SkyLightComponentDetails.h" #include "BrushDetails.h" #include "ObjectDetails.h" #include "ActorDetails.h" #include "SkeletalControlNodeDetails.h" #include "AnimMontageSegmentDetails.h" #include "AnimSequenceDetails.h" #include "AnimTransitionNodeDetails.h" #include "AnimStateNodeDetails.h" #include "PoseAssetDetails.h" #include "AnimationAssetDetails.h" #include "AmbientSoundDetails.h" #include "MathStructCustomizations.h" #include "MathStructProxyCustomizations.h" #include "RangeStructCustomization.h" #include "IntervalStructCustomization.h" #include "SoftObjectPathCustomization.h" #include "SoftClassPathCustomization.h" #include "AttenuationSettingsCustomizations.h" #include "WorldSettingsDetails.h" #include "DialogueStructsCustomizations.h" #include "DataTableCustomization.h" #include "DataTableCategoryCustomization.h" #include "CurveTableCustomization.h" #include "DialogueWaveDetails.h" #include "BodySetupDetails.h" #include "Customizations/SlateBrushCustomization.h" #include "SlateSoundCustomization.h" #include "Customizations/SlateFontInfoCustomization.h" #include "MarginCustomization.h" #include "PhysicsConstraintComponentDetails.h" #include "GuidStructCustomization.h" #include "ParticleModuleDetails.h" #include "CameraDetails.h" #include "BlackboardEntryDetails.h" #include "AIDataProviderValueDetails.h" #include "EnvQueryParamInstanceCustomization.h" #include "SkeletonNotifyDetails.h" #include "ColorStructCustomization.h" #include "SlateColorCustomization.h" #include "CurveStructCustomization.h" #include "NavLinkStructCustomization.h" #include "NavAgentSelectorCustomization.h" #include "DirectoryPathStructCustomization.h" #include "FilePathStructCustomization.h" #include "DeviceProfileDetails.h" #include "KeyStructCustomization.h" #include "InternationalizationSettingsModelDetails.h" #include "InputSettingsDetails.h" #include "InputStructCustomization.h" #include "CollisionProfileDetails.h" #include "PhysicsSettingsDetails.h" #include "GeneralProjectSettingsDetails.h" #include "HardwareTargetingSettingsDetails.h" #include "LinuxTargetSettingsDetails.h" #include "WindowsTargetSettingsDetails.h" #include "MacTargetSettingsDetails.h" #include "MoviePlayerSettingsDetails.h" #include "SourceCodeAccessSettingsDetails.h" #include "ParticleSystemComponentDetails.h" #include "ParticleSysParamStructCustomization.h" #include "RawDistributionVectorStructCustomization.h" #include "CollisionProfileNameCustomization.h" #include "DocumentationActorDetails.h" #include "SoundBaseDetails.h" #include "SoundSourceBusDetails.h" #include "SoundWaveDetails.h" #include "AudioSettingsDetails.h" #include "DateTimeStructCustomization.h" #include "TimespanStructCustomization.h" #include "FbxImportUIDetails.h" #include "FbxSceneImportDataDetails.h" #include "RigDetails.h" #include "SceneCaptureDetails.h" // WaveWorks Start #include "WaveWorksShorelineCaptureDetails.h" // WaveWorks End #include "CurveColorCustomization.h" #include "ActorComponentDetails.h" #include "AutoReimportDirectoryCustomization.h" #include "DistanceDatumStructCustomization.h" #include "HierarchicalSimplificationCustomizations.h" #include "PostProcessSettingsCustomization.h" #include "ConfigEditorPropertyDetails.h" #include "AssetImportDataCustomization.h" #include "CaptureResolutionCustomization.h" #include "CaptureTypeCustomization.h" #include "RenderPassesCustomization.h" #include "MovieSceneCaptureCustomization.h" #include "MovieSceneEvalOptionsCustomization.h" #include "MovieSceneEventParametersCustomization.h" #include "MovieSceneSequencePlaybackSettingsCustomization.h" #include "MovieSceneCurveInterfaceKeyEditStructCustomization.h" #include "LevelSequenceBurnInOptionsCustomization.h" #include "MovieSceneBindingOverrideDataCustomization.h" #include "TextCustomization.h" #include "AnimTrailNodeDetails.h" #include "MaterialProxySettingsCustomizations.h" #include "ImportantToggleSettingCustomization.h" #include "CameraFilmbackSettingsCustomization.h" #include "CameraLensSettingsCustomization.h" #include "CameraFocusSettingsCustomization.h" #include "RotatorStructCustomization.h" #include "VectorStructCustomization.h" #include "Vector4StructCustomization.h" #include "AssetViewerSettingsCustomization.h" #include "MeshMergingSettingsCustomization.h" #include "MaterialAttributePropertyDetails.h" #include "CollectionReferenceStructCustomization.h" // @third party code - BEGIN HairWorks #include "HairWorksDetails.h" // @third party code - END HairWorks IMPLEMENT_MODULE( FDetailCustomizationsModule, DetailCustomizations ); void FDetailCustomizationsModule::StartupModule() { FPropertyEditorModule& PropertyModule = FModuleManager::GetModuleChecked<FPropertyEditorModule>("PropertyEditor"); RegisterPropertyTypeCustomizations(); RegisterObjectCustomizations(); PropertyModule.NotifyCustomizationModuleChanged(); } void FDetailCustomizationsModule::ShutdownModule() { if (FModuleManager::Get().IsModuleLoaded("PropertyEditor")) { FPropertyEditorModule& PropertyModule = FModuleManager::GetModuleChecked<FPropertyEditorModule>("PropertyEditor"); // Unregister all classes customized by name for (auto It = RegisteredClassNames.CreateConstIterator(); It; ++It) { if (It->IsValid()) { PropertyModule.UnregisterCustomClassLayout(*It); } } // Unregister all structures for (auto It = RegisteredPropertyTypes.CreateConstIterator(); It; ++It) { if(It->IsValid()) { PropertyModule.UnregisterCustomPropertyTypeLayout(*It); } } PropertyModule.NotifyCustomizationModuleChanged(); } } void FDetailCustomizationsModule::RegisterPropertyTypeCustomizations() { RegisterCustomPropertyTypeLayout("SoftObjectPath", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FSoftObjectPathCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("SoftClassPath", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FSoftClassPathCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("DataTableRowHandle", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDataTableCustomizationLayout::MakeInstance)); RegisterCustomPropertyTypeLayout("DataTableCategoryHandle", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDataTableCategoryCustomizationLayout::MakeInstance)); RegisterCustomPropertyTypeLayout("CurveTableRowHandle", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCurveTableCustomizationLayout::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_Vector, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FVectorStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_Vector4, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FVector4StructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_Vector2D, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMathStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_IntPoint, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMathStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_Rotator, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FRotatorStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_LinearColor, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FColorStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_Color, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FColorStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_Matrix, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMatrixStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_Transform, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FTransformStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout(NAME_Quat, FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FQuatStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("SlateColor", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FSlateColorCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("ForceFeedbackAttenuationSettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FForceFeedbackAttenuationSettingsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("SoundAttenuationSettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FSoundAttenuationSettingsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("DialogueContext", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDialogueContextStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("DialogueWaveParameter", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDialogueWaveParameterStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("BodyInstance", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FBodyInstanceCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("SlateBrush", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FSlateBrushStructCustomization::MakeInstance, true)); RegisterCustomPropertyTypeLayout("SlateSound", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FSlateSoundStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("SlateFontInfo", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FSlateFontInfoStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("Guid", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FGuidStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("Key", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FKeyStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("FloatRange", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FRangeStructCustomization<float>::MakeInstance)); RegisterCustomPropertyTypeLayout("Int32Range", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FRangeStructCustomization<int32>::MakeInstance)); RegisterCustomPropertyTypeLayout("FloatInterval", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FIntervalStructCustomization<float>::MakeInstance)); RegisterCustomPropertyTypeLayout("Int32Interval", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FIntervalStructCustomization<int32>::MakeInstance)); RegisterCustomPropertyTypeLayout("DateTime", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDateTimeStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("Timespan", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FTimespanStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("BlackboardEntry", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FBlackboardEntryDetails::MakeInstance)); RegisterCustomPropertyTypeLayout("AIDataProviderIntValue", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FAIDataProviderValueDetails::MakeInstance)); RegisterCustomPropertyTypeLayout("AIDataProviderFloatValue", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FAIDataProviderValueDetails::MakeInstance)); RegisterCustomPropertyTypeLayout("AIDataProviderBoolValue", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FAIDataProviderValueDetails::MakeInstance)); RegisterCustomPropertyTypeLayout("RuntimeFloatCurve", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCurveStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("EnvNamedValue", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FEnvQueryParamInstanceCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("NavigationLink", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FNavLinkStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("NavigationSegmentLink", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FNavLinkStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("NavAgentSelector", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FNavAgentSelectorCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("Margin", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMarginStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("TextProperty", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FTextCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("DirectoryPath", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDirectoryPathStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("FilePath", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FFilePathStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("IOSBuildResourceDirectory", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDirectoryPathStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("IOSBuildResourceFilePath", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FFilePathStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("InputAxisConfigEntry", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FInputAxisConfigCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("InputActionKeyMapping", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FInputActionMappingCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("InputAxisKeyMapping", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FInputAxisMappingCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("RuntimeCurveLinearColor", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCurveColorCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("ParticleSysParam", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FParticleSysParamStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("RawDistributionVector", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FRawDistributionVectorStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("CollisionProfileName", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCollisionProfileNameCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("AutoReimportDirectoryConfig", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FAutoReimportDirectoryCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("AutoReimportWildcard", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FAutoReimportWildcardCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("DistanceDatum", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDistanceDatumStructCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("HierarchicalSimplification", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FHierarchicalSimplificationCustomizations::MakeInstance)); RegisterCustomPropertyTypeLayout("PostProcessSettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FPostProcessSettingsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("AssetImportInfo", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FAssetImportDataCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("CaptureResolution", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCaptureResolutionCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("CaptureProtocolID", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCaptureTypeCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("CompositionGraphCapturePasses", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FRenderPassesCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("WeightedBlendable", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FWeightedBlendableCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("MaterialProxySettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMaterialProxySettingsCustomizations::MakeInstance)); RegisterCustomPropertyTypeLayout("CameraFilmbackSettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCameraFilmbackSettingsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("CameraLensSettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCameraLensSettingsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("CameraFocusSettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCameraFocusSettingsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("MovieSceneSequencePlaybackSettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMovieSceneSequencePlaybackSettingsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("MovieSceneBindingOverrideData", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMovieSceneBindingOverrideDataCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("MovieSceneTrackEvalOptions", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMovieSceneTrackEvalOptionsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("MovieSceneSectionEvalOptions", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMovieSceneSectionEvalOptionsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("MovieSceneEventParameters", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FMovieSceneEventParametersCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("LevelSequenceBurnInOptions", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FLevelSequenceBurnInOptionsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("LevelSequenceBurnInInitSettings", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FLevelSequenceBurnInInitSettingsCustomization::MakeInstance)); RegisterCustomPropertyTypeLayout("CollectionReference", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FCollectionReferenceStructCustomization::MakeInstance)); } void FDetailCustomizationsModule::RegisterObjectCustomizations() { // Note: By default properties are displayed in script defined order (i.e the order in the header). These layout detail classes are called in the order seen here which will display properties // in the order they are customized. This is only relevant for inheritance where both a child and a parent have properties that are customized. // In the order below, Actor will get a chance to display details first, followed by USceneComponent. RegisterCustomClassLayout("Object", FOnGetDetailCustomizationInstance::CreateStatic(&FObjectDetails::MakeInstance)); RegisterCustomClassLayout("Actor", FOnGetDetailCustomizationInstance::CreateStatic(&FActorDetails::MakeInstance)); RegisterCustomClassLayout("ActorComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FActorComponentDetails::MakeInstance)); RegisterCustomClassLayout("SceneComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FSceneComponentDetails::MakeInstance)); RegisterCustomClassLayout("PrimitiveComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FPrimitiveComponentDetails::MakeInstance)); RegisterCustomClassLayout("StaticMeshComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FStaticMeshComponentDetails::MakeInstance)); RegisterCustomClassLayout("SkeletalMeshComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FSkeletalMeshComponentDetails::MakeInstance)); RegisterCustomClassLayout("SkinnedMeshComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FSkinnedMeshComponentDetails::MakeInstance)); RegisterCustomClassLayout("SplineComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FSplineComponentDetails::MakeInstance)); RegisterCustomClassLayout("LightComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FLightComponentDetails::MakeInstance)); RegisterCustomClassLayout("PointLightComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FPointLightComponentDetails::MakeInstance)); RegisterCustomClassLayout("DirectionalLightComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FDirectionalLightComponentDetails::MakeInstance)); RegisterCustomClassLayout("StaticMeshActor", FOnGetDetailCustomizationInstance::CreateStatic(&FStaticMeshActorDetails::MakeInstance)); RegisterCustomClassLayout("MeshComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FMeshComponentDetails::MakeInstance)); RegisterCustomClassLayout("MatineeActor", FOnGetDetailCustomizationInstance::CreateStatic(&FMatineeActorDetails::MakeInstance)); RegisterCustomClassLayout("LevelSequenceActor", FOnGetDetailCustomizationInstance::CreateStatic(&FLevelSequenceActorDetails::MakeInstance)); RegisterCustomClassLayout("ReflectionCapture", FOnGetDetailCustomizationInstance::CreateStatic(&FReflectionCaptureDetails::MakeInstance)); RegisterCustomClassLayout("SceneCaptureComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FSceneCaptureDetails::MakeInstance)); // WaveWorks Start RegisterCustomClassLayout("WaveWorksShorelineCapture", FOnGetDetailCustomizationInstance::CreateStatic(&FWaveWorksShorelineCaptureDetails::MakeInstance)); // WaveWorks End RegisterCustomClassLayout("SkyLight", FOnGetDetailCustomizationInstance::CreateStatic(&FSkyLightComponentDetails::MakeInstance)); RegisterCustomClassLayout("Brush", FOnGetDetailCustomizationInstance::CreateStatic(&FBrushDetails::MakeInstance)); RegisterCustomClassLayout("AmbientSound", FOnGetDetailCustomizationInstance::CreateStatic(&FAmbientSoundDetails::MakeInstance)); RegisterCustomClassLayout("WorldSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FWorldSettingsDetails::MakeInstance)); RegisterCustomClassLayout("GeneralProjectSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FGeneralProjectSettingsDetails::MakeInstance)); RegisterCustomClassLayout("HardwareTargetingSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FHardwareTargetingSettingsDetails::MakeInstance)); RegisterCustomClassLayout("DocumentationActor", FOnGetDetailCustomizationInstance::CreateStatic(&FDocumentationActorDetails::MakeInstance)); //@TODO: A2REMOVAL: Rename FSkeletalControlNodeDetails to something more generic RegisterCustomClassLayout("K2Node_StructMemberGet", FOnGetDetailCustomizationInstance::CreateStatic(&FSkeletalControlNodeDetails::MakeInstance)); RegisterCustomClassLayout("K2Node_StructMemberSet", FOnGetDetailCustomizationInstance::CreateStatic(&FSkeletalControlNodeDetails::MakeInstance)); RegisterCustomClassLayout("K2Node_GetClassDefaults", FOnGetDetailCustomizationInstance::CreateStatic(&FSkeletalControlNodeDetails::MakeInstance)); RegisterCustomClassLayout("AnimSequence", FOnGetDetailCustomizationInstance::CreateStatic(&FAnimSequenceDetails::MakeInstance)); RegisterCustomClassLayout("Rig", FOnGetDetailCustomizationInstance::CreateStatic(&FRigDetails::MakeInstance)); RegisterCustomClassLayout("EditorAnimSegment", FOnGetDetailCustomizationInstance::CreateStatic(&FAnimMontageSegmentDetails::MakeInstance)); RegisterCustomClassLayout("EditorAnimCompositeSegment", FOnGetDetailCustomizationInstance::CreateStatic(&FAnimMontageSegmentDetails::MakeInstance)); RegisterCustomClassLayout("EditorSkeletonNotifyObj", FOnGetDetailCustomizationInstance::CreateStatic(&FSkeletonNotifyDetails::MakeInstance)); RegisterCustomClassLayout("AnimStateNode", FOnGetDetailCustomizationInstance::CreateStatic(&FAnimStateNodeDetails::MakeInstance)); RegisterCustomClassLayout("AnimStateTransitionNode", FOnGetDetailCustomizationInstance::CreateStatic(&FAnimTransitionNodeDetails::MakeInstance)); RegisterCustomClassLayout("AnimGraphNode_Trail", FOnGetDetailCustomizationInstance::CreateStatic(&FAnimTrailNodeDetails::MakeInstance)); RegisterCustomClassLayout("PoseAsset", FOnGetDetailCustomizationInstance::CreateStatic(&FPoseAssetDetails::MakeInstance)); RegisterCustomClassLayout("AnimationAsset", FOnGetDetailCustomizationInstance::CreateStatic(&FAnimationAssetDetails::MakeInstance)); RegisterCustomClassLayout("SoundBase", FOnGetDetailCustomizationInstance::CreateStatic(&FSoundBaseDetails::MakeInstance)); RegisterCustomClassLayout("SoundSourceBus", FOnGetDetailCustomizationInstance::CreateStatic(&FSoundSourceBusDetails::MakeInstance)); RegisterCustomClassLayout("SoundWave", FOnGetDetailCustomizationInstance::CreateStatic(&FSoundWaveDetails::MakeInstance)); RegisterCustomClassLayout("DialogueWave", FOnGetDetailCustomizationInstance::CreateStatic(&FDialogueWaveDetails::MakeInstance)); RegisterCustomClassLayout("BodySetup", FOnGetDetailCustomizationInstance::CreateStatic(&FBodySetupDetails::MakeInstance)); RegisterCustomClassLayout("SkeletalBodySetup", FOnGetDetailCustomizationInstance::CreateStatic(&FSkeletalBodySetupDetails::MakeInstance)); RegisterCustomClassLayout("PhysicsConstraintTemplate", FOnGetDetailCustomizationInstance::CreateStatic(&FPhysicsConstraintComponentDetails::MakeInstance)); RegisterCustomClassLayout("PhysicsConstraintComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FPhysicsConstraintComponentDetails::MakeInstance)); RegisterCustomClassLayout("CollisionProfile", FOnGetDetailCustomizationInstance::CreateStatic(&FCollisionProfileDetails::MakeInstance)); RegisterCustomClassLayout("PhysicsSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FPhysicsSettingsDetails::MakeInstance)); RegisterCustomClassLayout("AudioSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FAudioSettingsDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleRequired", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleRequiredDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleSubUV", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleSubUVDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleAccelerationDrag", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleAccelerationDragDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleAcceleration", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleAccelerationDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleAccelerationDragScaleOverLife", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleAccelerationDragScaleOverLifeDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleCollisionGPU", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleCollisionGPUDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleOrbit", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleOrbitDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleSizeMultiplyLife", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleSizeMultiplyLifeDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleSizeScale", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleSizeScaleDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleVectorFieldScale", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleVectorFieldScaleDetails::MakeInstance)); RegisterCustomClassLayout("ParticleModuleVectorFieldScaleOverLife", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleModuleVectorFieldScaleOverLifeDetails::MakeInstance)); RegisterCustomClassLayout("CameraComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FCameraDetails::MakeInstance)); RegisterCustomClassLayout("DeviceProfile", FOnGetDetailCustomizationInstance::CreateStatic(&FDeviceProfileDetails::MakeInstance)); RegisterCustomClassLayout("InternationalizationSettingsModel", FOnGetDetailCustomizationInstance::CreateStatic(&FInternationalizationSettingsModelDetails::MakeInstance)); RegisterCustomClassLayout("InputSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FInputSettingsDetails::MakeInstance)); RegisterCustomClassLayout("WindowsTargetSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FWindowsTargetSettingsDetails::MakeInstance)); RegisterCustomClassLayout("MacTargetSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FMacTargetSettingsDetails::MakeInstance)); RegisterCustomClassLayout("LinuxTargetSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FLinuxTargetSettingsDetails::MakeInstance)); RegisterCustomClassLayout("MoviePlayerSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FMoviePlayerSettingsDetails::MakeInstance)); RegisterCustomClassLayout("SourceCodeAccessSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FSourceCodeAccessSettingsDetails::MakeInstance)); RegisterCustomClassLayout("ParticleSystemComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FParticleSystemComponentDetails::MakeInstance)); RegisterCustomClassLayout("FbxImportUI", FOnGetDetailCustomizationInstance::CreateStatic(&FFbxImportUIDetails::MakeInstance)); RegisterCustomClassLayout("FbxSceneImportData", FOnGetDetailCustomizationInstance::CreateStatic(&FFbxSceneImportDataDetails::MakeInstance)); RegisterCustomClassLayout("ConfigHierarchyPropertyView", FOnGetDetailCustomizationInstance::CreateStatic(&FConfigPropertyHelperDetails::MakeInstance)); RegisterCustomClassLayout("MovieSceneCapture", FOnGetDetailCustomizationInstance::CreateStatic(&FMovieSceneCaptureCustomization::MakeInstance)); RegisterCustomClassLayout("MovieSceneCurveInterfaceKeyEditStruct", FOnGetDetailCustomizationInstance::CreateStatic(&FMovieSceneCurveInterfaceKeyEditStructCustomization::MakeInstance)); RegisterCustomClassLayout("AnalyticsPrivacySettings", FOnGetDetailCustomizationInstance::CreateStatic(&FImportantToggleSettingCustomization::MakeInstance)); RegisterCustomClassLayout("EndUserSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FImportantToggleSettingCustomization::MakeInstance)); RegisterCustomClassLayout("AssetViewerSettings", FOnGetDetailCustomizationInstance::CreateStatic(&FAssetViewerSettingsCustomization::MakeInstance)); RegisterCustomClassLayout("MeshMergingSettingsObject", FOnGetDetailCustomizationInstance::CreateStatic(&FMeshMergingSettingsObjectCustomization::MakeInstance)); RegisterCustomClassLayout("MaterialExpressionGetMaterialAttributes", FOnGetDetailCustomizationInstance::CreateStatic(&FMaterialAttributePropertyDetails::MakeInstance)); RegisterCustomClassLayout("MaterialExpressionSetMaterialAttributes", FOnGetDetailCustomizationInstance::CreateStatic(&FMaterialAttributePropertyDetails::MakeInstance)); // @third party code - BEGIN HairWorks RegisterCustomClassLayout("HairWorksMaterial", FOnGetDetailCustomizationInstance::CreateStatic(&FHairWorksMaterialDetails::MakeInstance)); RegisterCustomClassLayout("HairWorksComponent", FOnGetDetailCustomizationInstance::CreateStatic(&FHairWorksComponentDetails::MakeInstance)); // @third party code - END HairWorks } void FDetailCustomizationsModule::RegisterCustomClassLayout(FName ClassName, FOnGetDetailCustomizationInstance DetailLayoutDelegate ) { check(ClassName != NAME_None); RegisteredClassNames.Add(ClassName); static FName PropertyEditor("PropertyEditor"); FPropertyEditorModule& PropertyModule = FModuleManager::GetModuleChecked<FPropertyEditorModule>(PropertyEditor); PropertyModule.RegisterCustomClassLayout( ClassName, DetailLayoutDelegate ); } void FDetailCustomizationsModule::RegisterCustomPropertyTypeLayout(FName PropertyTypeName, FOnGetPropertyTypeCustomizationInstance PropertyTypeLayoutDelegate) { check(PropertyTypeName != NAME_None); RegisteredPropertyTypes.Add(PropertyTypeName); static FName PropertyEditor("PropertyEditor"); FPropertyEditorModule& PropertyModule = FModuleManager::GetModuleChecked<FPropertyEditorModule>(PropertyEditor); PropertyModule.RegisterCustomPropertyTypeLayout(PropertyTypeName, PropertyTypeLayoutDelegate); }
82.377551
193
0.878546
[ "object" ]
8d8e5d375dbc98772d30bb2c99d399e75fba6e33
9,228
cpp
C++
source/utils/Image.cpp
3096/Aether
bc547ec192d8a973a63a97eda2994b3c2bdfeef7
[ "MIT" ]
9
2020-05-06T20:23:22.000Z
2022-01-19T10:37:46.000Z
source/utils/Image.cpp
3096/Aether
bc547ec192d8a973a63a97eda2994b3c2bdfeef7
[ "MIT" ]
11
2020-03-22T03:40:50.000Z
2020-06-09T00:53:13.000Z
source/utils/Image.cpp
3096/Aether
bc547ec192d8a973a63a97eda2994b3c2bdfeef7
[ "MIT" ]
6
2020-05-03T06:59:36.000Z
2020-07-15T04:21:59.000Z
#include "Aether/ThreadPool.hpp" #include "Aether/utils/Image.hpp" #include <array> #include <cmath> #include <thread> namespace Aether::Utils::Image { // Calculates the interpolated value using a cubic hermite spline static double cubicHermite(const double a, const double b, const double c, const double d, const double t) { double A = -(a / 2.0d) + ((3.0d * b) / 2.0d) - ((3.0d * c) / 2.0d) + (d / 2.0d); double B = a - ((5.0d * b) / 2.0d) + (2.0d * c) - (d / 2.0d); double C = -(a / 2.0d) + (c / 2.0d); double D = b; return (A * t * t * t) + (B * t * t) + (C * t) + D; } // Ensures the requested coordinates are bounded within the image static std::pair<size_t, size_t> getClampedCoords(const ImageData * image, int x, int y) { x = (x > 0 ? (x >= image->width() ? image->width() - 1 : x) : 0); y = (y > 0 ? (y >= image->height() ? image->height() - 1 : y) : 0); return std::pair<size_t, size_t>(x, y); } ImageData * scaleBicubic(ImageData * image, const size_t width, const size_t height) { // Return copy if same dimensions if (image->width() == width && image->height() == height) { return new ImageData(image->toColourVector(), image->width(), image->height(), image->channels());; } // Set up scaled image ImageData * resized = new ImageData(std::vector<Colour>(), width, height, 4); // Pre-allocate arrays std::array<std::array<double, 4>, 4> columnValues; // Interpolated column values for pixel std::array<double, 4> interpolated; // Interpolated channels for pixel std::array<std::array<Colour *, 4>, 4> samples; // Pixels which are interpolated // Work down each row (x and y are coords) for (size_t y = 0; y < resized->height(); y++) { double v = y / (double)(resized->height() - 1); for (size_t x = 0; x < resized->width(); x++) { double u = x / (double)(resized->width() - 1); double xPos = (u * image->width() - 0.5d); int xPx = (int)xPos; double xRem = xPos - floor(xPos); double yPos = (v * image->height() - 0.5d); int yPx = (int)yPos; double yRem = yPos - floor(yPos); // Find colours to sample for (int row = -1; row <= 2; row++) { for (int col = -1; col <= 2; col++) { std::pair<size_t, size_t> coords = getClampedCoords(image, xPx + col, yPx + row); samples[col + 1][row + 1] = image->colourAt(coords.first, coords.second); } } // Interpolate vertically first for (size_t col = 0; col < 4; col++) { columnValues[col][0] = cubicHermite(samples[0][col]->r(), samples[1][col]->r(), samples[2][col]->r(), samples[3][col]->r(), xRem); columnValues[col][1] = cubicHermite(samples[0][col]->g(), samples[1][col]->g(), samples[2][col]->g(), samples[3][col]->g(), xRem); columnValues[col][2] = cubicHermite(samples[0][col]->b(), samples[1][col]->b(), samples[2][col]->b(), samples[3][col]->b(), xRem); columnValues[col][3] = cubicHermite(samples[0][col]->a(), samples[1][col]->a(), samples[2][col]->a(), samples[3][col]->a(), xRem); } // Then interpolate horizontally for (size_t channel = 0; channel < interpolated.size(); channel++) { double value = cubicHermite(columnValues[0][channel], columnValues[1][channel], columnValues[2][channel], columnValues[3][channel], yRem); value = (value > 0.0d ? (value < 255.0d ? value : 255.0d) : 0.0d); interpolated[channel] = value; } // Set pixel in resized image Colour * pixel = resized->colourAt(x, y); pixel->setColour(interpolated[0], interpolated[1], interpolated[2], interpolated[3]); } } return resized; } ImageData * scaleBoxSampling(ImageData * image, const size_t width, const size_t height) { // Set up scaled image ImageData * scaled = new ImageData(std::vector<Colour>(), width, height, 4); ImageData * tmp = new ImageData(std::vector<Colour>(), scaled->width(), image->height(), 4); // Scale horizontally first double rw = image->width() / (double)scaled->width(); double iw = 1.0d / rw; for (size_t y = 0; y < image->height(); y++) { for (size_t x = 0; x < scaled->width(); x++) { double pos = x * rw; int baseIdx = (int)pos; std::array<double, 4> channels; Colour * pixel = nullptr; double val; pixel = image->colourAt(baseIdx, y); val = (double)baseIdx + 1 - pos; channels[0] = pixel->r() * val; channels[1] = pixel->g() * val; channels[2] = pixel->b() * val; channels[3] = pixel->a() * val; double end = pos + rw; int endI = (int)end; val = end - (double)endI; if (val > 1e-4f) { pixel = image->colourAt(endI, y); channels[0] += pixel->r() * val; channels[1] += pixel->g() * val; channels[2] += pixel->b() * val; channels[3] += pixel->a() * val; } for (size_t i = baseIdx+1; i < endI; i++) { pixel = image->colourAt(i, y); channels[0] += pixel->r(); channels[1] += pixel->g(); channels[2] += pixel->b(); channels[3] += pixel->a(); } pixel = tmp->colourAt(x, y); pixel->setR((channels[0] * iw) + 0.5d); pixel->setG((channels[1] * iw) + 0.5d); pixel->setB((channels[2] * iw) + 0.5d); pixel->setA((channels[3] * iw) + 0.5d); } } // Then vertically double rh = image->height() / (double)scaled->height(); double ih = 1.0d / rh; for (size_t y = 0; y < scaled->height(); y++) { for (size_t x = 0; x < scaled->width(); x++) { double pos = y * rh; int baseIdx = (int)pos; std::array<double, 4> channels; Colour * pixel = nullptr; double val; pixel = tmp->colourAt(x, baseIdx); val = (double)baseIdx + 1 - pos; channels[0] = pixel->r() * val; channels[1] = pixel->g() * val; channels[2] = pixel->b() * val; channels[3] = pixel->a() * val; double end = pos + rh; int endI = (int)end; val = end - (double)endI; if (val > 1e-4f) { pixel = tmp->colourAt(x, endI); channels[0] += pixel->r() * val; channels[1] += pixel->g() * val; channels[2] += pixel->b() * val; channels[3] += pixel->a() * val; } for (size_t i = baseIdx+1; i < endI; i++) { pixel = tmp->colourAt(x, i); channels[0] += pixel->r(); channels[1] += pixel->g(); channels[2] += pixel->b(); channels[3] += pixel->a(); } pixel = scaled->colourAt(x, y); pixel->setR((channels[0] * ih) + 0.5d); pixel->setG((channels[1] * ih) + 0.5d); pixel->setB((channels[2] * ih) + 0.5d); pixel->setA((channels[3] * ih) + 0.5d); } } delete tmp; return scaled; } ImageData * scaleOptimal(ImageData * image, const size_t width, const size_t height) { // Sanity checks if (width == 0 || height == 0 || image == nullptr) { return nullptr; } else if (width == image->width() && height == image->height()) { // Copy even though same image as it has been "scaled" return new ImageData(image->toColourVector(), image->width(), image->height(), image->channels());; } // Use box sampling if one or more dimensions are being scaled down ImageData * scaled; if (width <= image->width() && height <= image->height()) { scaled = scaleBoxSampling(image, width, height); // Otherwise default to bicubic interpolation } else { scaled = scaleBicubic(image, width, height); } return scaled; } }
43.323944
159
0.458713
[ "vector" ]
8d931a4d1d1d44b3bf32f2ae8da32ae4ffc0b2f4
5,933
cc
C++
src/devices/spi/drivers/spi/spi-test.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/devices/spi/drivers/spi/spi-test.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/devices/spi/drivers/spi/spi-test.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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 "spi.h" #include <lib/fake_ddk/fake_ddk.h> #include <lib/spi/spi.h> #include <ddk/metadata.h> #include <ddk/metadata/spi.h> #include <ddktl/protocol/platform/bus.h> #include <zxtest/zxtest.h> namespace spi { class FakeDdkSpiImpl; using DeviceType = ddk::Device<FakeDdkSpiImpl, ddk::UnbindableDeprecated>; class FakeDdkSpiImpl : public fake_ddk::Bind, public DeviceType, public ddk::SpiImplProtocol<FakeDdkSpiImpl, ddk::base_protocol> { public: explicit FakeDdkSpiImpl() : DeviceType(fake_ddk::kFakeParent) { fbl::AllocChecker ac; fbl::Array<fake_ddk::ProtocolEntry> protocols(new (&ac) fake_ddk::ProtocolEntry[1](), 1); ASSERT_TRUE(ac.check()); protocols[0] = {ZX_PROTOCOL_SPI_IMPL, {&spi_impl_protocol_ops_, this}}; SetProtocols(std::move(protocols)); } zx_status_t DeviceAdd(zx_driver_t* drv, zx_device_t* parent, device_add_args_t* args, zx_device_t** out) { if (parent == fake_ddk::kFakeParent) { bus_device_ = reinterpret_cast<SpiDevice*>(args->ctx); } else if (parent == reinterpret_cast<zx_device_t*>(bus_device_)) { children_.push_back(reinterpret_cast<SpiChild*>(args->ctx)); auto fidl = new fake_ddk::FidlMessenger; const zx_protocol_device_t* ops = reinterpret_cast<const zx_protocol_device_t*>(args->ops); fidl->SetMessageOp(args->ctx, ops->message); fidl_clients_.push_back(fidl); } *out = reinterpret_cast<zx_device_t*>(args->ctx); return ZX_OK; } zx_status_t DeviceRemove(zx_device_t* device) { if (device == reinterpret_cast<zx_device_t*>(bus_device_)) { delete bus_device_; bus_device_ = nullptr; return ZX_OK; } else { for (size_t i = 0; i < children_.size(); i++) { if (children_[i] == reinterpret_cast<SpiChild*>(device)) { children_.erase(i); delete fidl_clients_[i]; fidl_clients_.erase(i); return ZX_OK; } } } return ZX_ERR_BAD_STATE; } zx_status_t DeviceGetMetadata(zx_device_t* dev, uint32_t type, void* buf, size_t buflen, size_t* actual) { switch (type) { case DEVICE_METADATA_SPI_CHANNELS: memcpy(buf, &spi_channels_, sizeof spi_channels_); *actual = sizeof spi_channels_; break; case DEVICE_METADATA_PRIVATE: memcpy(buf, &kTestBusId, sizeof kTestBusId); *actual = sizeof kTestBusId; break; default: return ZX_ERR_INTERNAL; } return ZX_OK; } zx_status_t DeviceGetMetadataSize(zx_device_t* dev, uint32_t type, size_t* out_size) { switch (type) { case DEVICE_METADATA_SPI_CHANNELS: *out_size = sizeof spi_channels_; break; case DEVICE_METADATA_PRIVATE: *out_size = sizeof kTestBusId; break; default: return ZX_ERR_INTERNAL; } return ZX_OK; } uint32_t SpiImplGetChipSelectCount() { return 2; } zx_status_t SpiImplExchange(uint32_t cs, const uint8_t* txdata, size_t txdata_size, uint8_t* out_rxdata, size_t rxdata_size, size_t* out_rxdata_actual) { EXPECT_EQ(cs, current_test_cs_, ""); switch (test_mode_) { case SpiTestMode::kTransmit: EXPECT_NE(txdata, nullptr, ""); EXPECT_NE(txdata_size, 0, ""); EXPECT_EQ(out_rxdata, nullptr, ""); EXPECT_EQ(rxdata_size, 0, ""); break; case SpiTestMode::kReceive: EXPECT_EQ(txdata, nullptr, ""); EXPECT_EQ(txdata_size, 0, ""); EXPECT_NE(out_rxdata, nullptr, ""); EXPECT_NE(rxdata_size, 0, ""); memset(out_rxdata, 0, rxdata_size); *out_rxdata_actual = rxdata_size; break; case SpiTestMode::kExchange: EXPECT_NE(txdata, nullptr, ""); EXPECT_NE(txdata_size, 0, ""); EXPECT_NE(out_rxdata, nullptr, ""); EXPECT_NE(rxdata_size, 0, ""); EXPECT_EQ(txdata_size, rxdata_size, ""); memset(out_rxdata, 0, rxdata_size); *out_rxdata_actual = rxdata_size; break; } return ZX_OK; } void DdkUnbindNew(ddk::UnbindTxn txn) { txn.Reply(); } void DdkRelease() { delete this; } SpiDevice* bus_device_; fbl::Vector<SpiChild*> children_; fbl::Vector<fake_ddk::FidlMessenger*> fidl_clients_; uint32_t current_test_cs_; enum class SpiTestMode { kTransmit, kReceive, kExchange, } test_mode_; static constexpr uint32_t kTestBusId = 0; static constexpr spi_channel_t spi_channels_[] = { {.bus_id = 0, .cs = 0, .vid = 0, .pid = 0, .did = 0}, {.bus_id = 0, .cs = 1, .vid = 0, .pid = 0, .did = 0}}; }; TEST(SpiDevice, SpiTest) { FakeDdkSpiImpl ddk; // make it SpiDevice::Create(nullptr, fake_ddk::kFakeParent); EXPECT_EQ(ddk.children_.size(), countof(ddk.spi_channels_), ""); // test it const uint8_t txbuf[] = {0, 1, 2, 3, 4, 5, 6}; uint8_t rxbuf[sizeof txbuf]; for (size_t i = 0; i < ddk.children_.size(); i++) { ddk.current_test_cs_ = static_cast<uint32_t>(i); auto channel = ddk.fidl_clients_[i]->local().get(); ddk.test_mode_ = FakeDdkSpiImpl::SpiTestMode::kTransmit; zx_status_t status = spilib_transmit(channel, txbuf, sizeof txbuf); EXPECT_OK(status, ""); ddk.test_mode_ = FakeDdkSpiImpl::SpiTestMode::kReceive; status = spilib_receive(channel, rxbuf, sizeof rxbuf); EXPECT_OK(status, ""); ddk.test_mode_ = FakeDdkSpiImpl::SpiTestMode::kExchange; status = spilib_exchange(channel, txbuf, rxbuf, sizeof txbuf); EXPECT_OK(status, ""); } // clean it up ddk.bus_device_->DdkUnbindDeprecated(); EXPECT_EQ(ddk.children_.size(), 0, ""); EXPECT_EQ(ddk.bus_device_, nullptr, ""); } } // namespace spi
31.727273
99
0.647902
[ "vector" ]
8d946d5121bb9b261c8f1d8bd1b74faee4dde96b
7,881
cpp
C++
MetalMockTests/MetalMock/ValueReturnerTests.cpp
NeilJustice/ZenUnitAndZenMock
bbcb4221d063fa04e4ef3a98143e0f123e3af8d5
[ "MIT" ]
2
2019-11-11T17:32:53.000Z
2020-04-22T20:42:56.000Z
MetalMockTests/MetalMock/ValueReturnerTests.cpp
NeilJustice/ZenUnitAndZenMock
bbcb4221d063fa04e4ef3a98143e0f123e3af8d5
[ "MIT" ]
1
2021-03-03T07:19:16.000Z
2021-03-28T21:46:32.000Z
MetalMockTests/MetalMock/ValueReturnerTests.cpp
NeilJustice/ZenUnitAndZenMock
bbcb4221d063fa04e4ef3a98143e0f123e3af8d5
[ "MIT" ]
null
null
null
#include "pch.h" struct NonDefaultConstructible { int field; explicit NonDefaultConstructible(int field) : field(field) {} }; namespace ZenUnit { template<> class Equalizer<NonDefaultConstructible> { public: static void AssertEqual(const NonDefaultConstructible& expected, const NonDefaultConstructible& actual) { ARE_EQUAL(expected.field, actual.field); } }; } namespace MetalMock { TESTS(ValueReturnerTests) AFACT(DefaultConstructor_SetsMetalMockedFunctionSignature_SetsReturnValueIndexTo0) AFACT(MetalMockNextReturnValue_NoReturnValueWasPreviouslySpecified_ThrowsReturnValueMustBeSpecifiedException__DefaultConstructibleReturnType) AFACT(MetalMockNextReturnValue_NoReturnValueWasPreviouslySpecified_ThrowsReturnValueMustBeSpecifiedException__NonDefaultConstructibleReturnType) AFACT(MetalMockNextReturnValue_ReturnValuesSpecified_ReturnsValuesThenLastValueThereafter__DefaultConstructibleReturnType) AFACT(MetalMockNextReturnValue_ReturnValuesSpecified_ReturnsValuesThenLastValueThereafter__NonDefaultConstructibleReturnType) AFACT(MetalMockAddContainerReturnValues_ReturnValuesAreEmpty_ThrowsInvalidArgument__ConstLValueReferenceTestCase) AFACT(MetalMockAddContainerReturnValues_ReturnValuesAreEmpty_ThrowsInvalidArgument__RValueReferenceTestCase) EVIDENCE string _metalMockedFunctionSignature; STARTUP { _metalMockedFunctionSignature = ZenUnit::Random<string>(); } TEST(DefaultConstructor_SetsMetalMockedFunctionSignature_SetsReturnValueIndexTo0) { const string metalMockedFunctionSignature = ZenUnit::Random<string>(); // const ValueReturner<int> valueReturner(metalMockedFunctionSignature); // ARE_EQUAL(metalMockedFunctionSignature, valueReturner._metalMockedFunctionSignature); IS_EMPTY(valueReturner._returnValues); IS_ZERO(valueReturner._returnValueIndex); } TEST(MetalMockNextReturnValue_NoReturnValueWasPreviouslySpecified_ThrowsReturnValueMustBeSpecifiedException__DefaultConstructibleReturnType) { ValueReturner<int> valueReturnerInt(_metalMockedFunctionSignature); THROWS_EXCEPTION(valueReturnerInt.MetalMockNextReturnValue(), ReturnValueMustBeSpecifiedException, ReturnValueMustBeSpecifiedException::MakeExceptionMessage(_metalMockedFunctionSignature)); ValueReturner<const string&> valueReturnerConstStringRef(_metalMockedFunctionSignature); THROWS_EXCEPTION(valueReturnerConstStringRef.MetalMockNextReturnValue(), ReturnValueMustBeSpecifiedException, ReturnValueMustBeSpecifiedException::MakeExceptionMessage(_metalMockedFunctionSignature)); } TEST(MetalMockNextReturnValue_NoReturnValueWasPreviouslySpecified_ThrowsReturnValueMustBeSpecifiedException__NonDefaultConstructibleReturnType) { ValueReturner<NonDefaultConstructible> valueReturner(_metalMockedFunctionSignature); THROWS_EXCEPTION(valueReturner.MetalMockNextReturnValue(), ReturnValueMustBeSpecifiedException, ReturnValueMustBeSpecifiedException::MakeExceptionMessage(_metalMockedFunctionSignature)); } TEST(MetalMockNextReturnValue_ReturnValuesSpecified_ReturnsValuesThenLastValueThereafter__DefaultConstructibleReturnType) { ValueReturner<int> valueReturner(_metalMockedFunctionSignature); valueReturner.MetalMockAddReturnValue(1); valueReturner.MetalMockAddReturnValues(2, 3); valueReturner.MetalMockAddContainerReturnValues(vector<int> { 4, 5 }); valueReturner.MetalMockAddContainerReturnValues(array<int, 2>{{ 6, 7 }}); const vector<int> vectorOfReturnValues{8, 9}; valueReturner.MetalMockAddContainerReturnValues(vectorOfReturnValues); const array<int, 1> arrayOfReturnValues{{10}}; valueReturner.MetalMockAddContainerReturnValues(arrayOfReturnValues); // ARE_EQUAL(1, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(2, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(3, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(4, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(5, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(6, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(7, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(8, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(9, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(10, valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(10, valueReturner.MetalMockNextReturnValue()); } TEST(MetalMockNextReturnValue_ReturnValuesSpecified_ReturnsValuesThenLastValueThereafter__NonDefaultConstructibleReturnType) { ValueReturner<NonDefaultConstructible> valueReturner(_metalMockedFunctionSignature); valueReturner.MetalMockAddReturnValue(NonDefaultConstructible(1)); valueReturner.MetalMockAddReturnValues(NonDefaultConstructible(2), NonDefaultConstructible(3)); valueReturner.MetalMockAddContainerReturnValues( vector<NonDefaultConstructible> { NonDefaultConstructible(4), NonDefaultConstructible(5) }); valueReturner.MetalMockAddContainerReturnValues( array<NonDefaultConstructible, 2>{ { NonDefaultConstructible(6), NonDefaultConstructible(7) }}); const vector<NonDefaultConstructible> vectorOfReturnValues = {NonDefaultConstructible(8), NonDefaultConstructible(9)}; valueReturner.MetalMockAddContainerReturnValues(vectorOfReturnValues); const array<NonDefaultConstructible, 1> arrayOfReturnValues = {NonDefaultConstructible(10)}; valueReturner.MetalMockAddContainerReturnValues(arrayOfReturnValues); // ARE_EQUAL(NonDefaultConstructible(1), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(2), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(3), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(4), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(5), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(6), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(7), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(8), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(9), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(10), valueReturner.MetalMockNextReturnValue()); ARE_EQUAL(NonDefaultConstructible(10), valueReturner.MetalMockNextReturnValue()); } TEST(MetalMockAddContainerReturnValues_ReturnValuesAreEmpty_ThrowsInvalidArgument__ConstLValueReferenceTestCase) { ValueReturner<int> valueReturner(_metalMockedFunctionSignature); const char* const expectedExceptionMessage = "MetalMock::ValueReturner::MetalMockAddContainerReturnValues(const ContainerType& returnValues): returnValues cannot be empty"; const vector<int> emptyReturnValues; THROWS_EXCEPTION(valueReturner.MetalMockAddContainerReturnValues(emptyReturnValues), invalid_argument, expectedExceptionMessage); } TEST(MetalMockAddContainerReturnValues_ReturnValuesAreEmpty_ThrowsInvalidArgument__RValueReferenceTestCase) { ValueReturner<int> valueReturner(_metalMockedFunctionSignature); const char* const expectedExceptionMessage = "MetalMock::ValueReturner::MetalMockAddContainerReturnValues(const ContainerType& returnValues): returnValues cannot be empty"; THROWS_EXCEPTION(valueReturner.MetalMockAddContainerReturnValues(vector<int>{}), invalid_argument, expectedExceptionMessage); } RUN_TESTS(ValueReturnerTests) }
54.729167
148
0.800025
[ "vector" ]
8d96be6ce9f6bc59566f8955fcf053feb258a7f5
3,206
hpp
C++
OptFrame/Commands/SystemPreprocessCommand.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
OptFrame/Commands/SystemPreprocessCommand.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
OptFrame/Commands/SystemPreprocessCommand.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework 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 v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_SYSTEM_PREPROCESS_MODULE_HPP_ #define OPTFRAME_SYSTEM_PREPROCESS_MODULE_HPP_ #include "../Command.hpp" #include "SystemUnsafeDefineCommand.hpp" namespace optframe { template<class R, class ADS = OPTFRAME_DEFAULT_ADS, class DS = OPTFRAME_DEFAULT_DS> class SystemPreprocessCommand: public Command<R, ADS, DS> { public: virtual ~SystemPreprocessCommand() { } string id() { return "system.preprocess"; } string usage() { return "system.preprocess return_value module_name input"; } Command<R, ADS, DS>* getCommand(vector<Command<R, ADS, DS>*>& modules, string module, string rest) { for (unsigned int i = 0; i < modules.size(); i++) { //cout << "run: testing module '" << modules[i]->id() << "'" << endl; if (modules[i]->canHandle(module, rest)) return modules[i]; } //cout << "run: NULL MODULE! module='" << module << "' rest='" << rest << "'" << endl; return NULL; } bool run(vector<Command<R, ADS, DS>*>& all_modules, vector<PreprocessFunction<R, ADS, DS>*>& allFunctions, HeuristicFactory<R, ADS, DS>& factory, map<string, string>& dictionary, map< string,vector<string> >& ldictionary, string input) { Scanner scanner(input); if (!scanner.hasNext()) { cout << "Usage: " << usage() << endl; return false; } string name = scanner.next(); if (!scanner.hasNext()) { cout << "Usage: " << usage() << endl; return false; } string module = scanner.next(); string inp = scanner.rest(); Command<R, ADS, DS>* m = getCommand(all_modules, module, ""); if(!m) { cout << "preprocess command: NULL module!" << endl; return false; } string* final = m->preprocess(allFunctions, factory, dictionary, ldictionary, inp); if(!final) return false; stringstream ss; ss << name << " " << (*final); delete final; return Command<R, ADS, DS>::run_module("system.unsafe_define", all_modules, allFunctions, factory, dictionary, ldictionary, ss.str()); } // runs raw module without preprocessing virtual string* preprocess(vector<PreprocessFunction<R, ADS, DS>*>& allFunctions, HeuristicFactory<R, ADS, DS>& hf, const map<string, string>& dictionary, const map<string, vector<string> >& ldictionary, string input) { return new string(input); // disable pre-processing } }; } #endif /* OPTFRAME_SYSTEM_PREPROCESS_MODULE_HPP_ */
27.401709
237
0.693387
[ "vector" ]
8d96d24090ed42c86f56455b99b27ae122aa1aa3
56,700
cpp
C++
install/TexGen/Core/Mesher.cpp
dalexa10/puma
ca02309c9f5c71e2e80ad8d64155dd6ca936c667
[ "NASA-1.3" ]
14
2021-06-17T17:17:07.000Z
2022-03-26T05:20:20.000Z
install/TexGen/Core/Mesher.cpp
dalexa10/puma
ca02309c9f5c71e2e80ad8d64155dd6ca936c667
[ "NASA-1.3" ]
6
2021-11-01T20:37:39.000Z
2022-03-11T17:18:53.000Z
install/TexGen/Core/Mesher.cpp
dalexa10/puma
ca02309c9f5c71e2e80ad8d64155dd6ca936c667
[ "NASA-1.3" ]
8
2021-07-20T09:24:23.000Z
2022-02-26T16:32:00.000Z
/*============================================================================= TexGen: Geometric textile modeller. Copyright (C) 2006 Martin Sherburn This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. =============================================================================*/ #include "PrecompiledHeaders.h" #include "Mesher.h" #include "TexGen.h" #include "PeriodicBoundaries.h" //#include "Yarn.h" extern "C" { #include "../Triangle/triangle.h" } using namespace TexGen; CMesher::CMesher( int iBoundaryConditions ) : m_bHybrid(false) , m_bQuadratic(false) , m_bProjectMidSideNodes(true) , m_dLayerMergeTolerance(1e-3) , m_iBoundaryConditions(iBoundaryConditions) { switch( iBoundaryConditions ) { case MATERIAL_CONTINUUM: case SINGLE_LAYER_RVE: m_PeriodicBoundaries = new CPeriodicBoundaries; break; case SHEARED_BC: m_PeriodicBoundaries = new CShearedPeriodicBoundaries; break; case NO_BOUNDARY_CONDITIONS: default: m_PeriodicBoundaries = NULL; break; } } CMesher::~CMesher(void) { if ( m_PeriodicBoundaries != NULL ) { delete m_PeriodicBoundaries; } } bool CMesherBase::CreateMesh(string TextileName) { CTextile* pTextile = TEXGEN.GetTextile(TextileName); if (pTextile) return CreateMesh(*pTextile); else return false; } bool CMesher::CreateMesh(CTextile &Textile) { m_ProjectedNodes.clear(); if (!CreateBasicVolumes(Textile)) return false; TGLOG("Meshing basic volumes in 3D"); CreateVolumeMesh(Textile); TGLOG("Getting element data"); FillYarnTangentsData(); if (m_bQuadratic) { TGLOG("Converting mesh to quadratic"); ConvertMeshToQuadratic(); if ( m_iBoundaryConditions != NO_BOUNDARY_CONDITIONS ) { AddQuadraticNodesToSets(); } } TGLOG("Meshing complete with " << m_VolumeMesh.GetNumElements() << " elements and " << m_VolumeMesh.GetNumNodes() << " nodes"); // SaveVolumeMeshToVTK("Volume"); return true; } void CMesher::SaveVolumeMeshToVTK(string Filename) { TGLOG("Save Volume Mesh to VTK"); CMeshData<unsigned short> RegionIndex("RegionIndex", CMeshDataBase::ELEMENT); CMeshData<unsigned char> Layer("Layer", CMeshDataBase::ELEMENT); CMeshData<char> YarnIndex("YarnIndex", CMeshDataBase::ELEMENT); CMeshData<XYZ> YarnTangent("YarnTangent", CMeshDataBase::ELEMENT); CMeshData<XY> Location("Location", CMeshDataBase::ELEMENT); CMeshData<double> VolumeFraction("VolumeFraction", CMeshDataBase::ELEMENT); CMeshData<double> SurfaceDistance("SurfaceDistance", CMeshDataBase::ELEMENT); CMeshData<XYZ> Orientation("Orientation", CMeshDataBase::ELEMENT); list<MESHER_ELEMENT_DATA>::iterator itElemData; int i; for (i = 0; i < CMesh::NUM_ELEMENT_TYPES; ++i) { for (itElemData = m_ElementData[i].begin(); itElemData != m_ElementData[i].end(); ++itElemData) { RegionIndex.m_Data.push_back(itElemData->iRegion); Layer.m_Data.push_back(itElemData->iLayer); YarnIndex.m_Data.push_back(itElemData->iYarnIndex); YarnTangent.m_Data.push_back(itElemData->YarnTangent); Location.m_Data.push_back(itElemData->Location); VolumeFraction.m_Data.push_back(itElemData->dVolumeFraction); SurfaceDistance.m_Data.push_back(itElemData->dSurfaceDistance); Orientation.m_Data.push_back(itElemData->Orientation); } } vector<CMeshDataBase*> MeshData; MeshData.push_back(&RegionIndex); MeshData.push_back(&Layer); MeshData.push_back(&YarnIndex); MeshData.push_back(&YarnTangent); MeshData.push_back(&Location); MeshData.push_back(&VolumeFraction); MeshData.push_back(&SurfaceDistance); MeshData.push_back(&Orientation); TGLOG("Calling SaveToVTK"); m_VolumeMesh.SaveToVTK(Filename, &MeshData); } void CMesher::SaveVolumeMeshToABAQUS(string Filename, string TextileName ) { CTextile* pTextile = TEXGEN.GetTextile(TextileName); if ( pTextile == NULL ) { TGERROR("Cannot save to ABAQUS: no textile created"); return; } SaveVolumeMeshToABAQUS( Filename, *pTextile ); } void CMesher::SaveVolumeMeshToABAQUS(string Filename, CTextile& Textile ) { TGLOG("Replacing spaces in filename with underscore for ABAQUS compatibility"); Filename = ReplaceFilenameSpaces( Filename ); vector<POINT_INFO> ElementsInfo; POINT_INFO Info; list<MESHER_ELEMENT_DATA>::const_iterator itData; int i; for (i = 0; i < CMesh::NUM_ELEMENT_TYPES; ++i) { for (itData = m_ElementData[i].begin(); itData != m_ElementData[i].end(); ++itData) { Info.iYarnIndex = itData->iYarnIndex; Info.Location = itData->Location; Info.YarnTangent = itData->YarnTangent; Info.dVolumeFraction = itData->dVolumeFraction; Info.dSurfaceDistance = itData->dSurfaceDistance; Info.Orientation = itData->Orientation; Info.Up = itData->Up; ElementsInfo.push_back(Info); } } m_VolumeMesh.SaveToABAQUS(Filename, &ElementsInfo, false, false); ofstream Output(Filename.c_str(), ofstream::app ); // Output material properties m_Materials = new CTextileMaterials; m_Materials->SetupMaterials( Textile ); m_Materials->OutputMaterials( Output, Textile.GetNumYarns(), false ); delete( m_Materials ); if ( m_iBoundaryConditions != NO_BOUNDARY_CONDITIONS ) { m_PeriodicBoundaries->SetDomainSize( Textile.GetDomain()->GetMesh() ); if (SaveNodeSets() ) { //ofstream Output(Filename.c_str(), ofstream::app ); Output << "*****************" << endl; Output << "*** NODE SETS ***" << endl; Output << "*****************" << endl; Output << "** AllNodes - Node set containing all elements" << endl; Output << "*NSet, NSet=AllNodes, Generate" << endl; Output << "1, " << m_VolumeMesh.GetNumNodes() << ", 1" << endl; m_PeriodicBoundaries->CreatePeriodicBoundaries( Output, m_VolumeMesh.GetNumNodes() + 1, Textile, m_iBoundaryConditions, false ); } else TGERROR("Unable to generate node sets"); } } void CMesher::CreateVolumeMesh(CTextile &Textile) { int iNumNodes = (int)m_ProjectedMesh.GetNumNodes(); m_ProjectedNodes.clear(); m_ProjectedNodes.resize(iNumNodes); NODE_PAIR_SETS EdgeNodePairSets; const vector<XYZ> &Repeats = Textile.GetYarn(0)->GetRepeats(); if ( m_bCreatePeriodic ) { // Find matching nodes on opposite edges of domain vector<XYZ>::const_iterator itRepeat; for (itRepeat=Repeats.begin(); itRepeat!=Repeats.end(); ++itRepeat) { NODE_PAIR_SET NodePairs; m_ProjectedMesh.GetNodePairs(*itRepeat, NodePairs, 1e-5); SortPairs( NodePairs, (*itRepeat).y == 0 ? true:false ); // If pairs with constant x, sort by y EdgeNodePairSets.push_back( NodePairs ); } } int i, j; set<int> CornerIndex; for (i=0; i<iNumNodes; ++i) { m_ProjectedNodes[i].Position = m_ProjectedMesh.GetNode(i); if ( m_bCreatePeriodic ) { // Set up so that columns of nodes on opposite faces match if ( m_ProjectedNodes[i].RaisedNodes.empty() ) // Might already have been filled if RaiseNode was called for node on opposite face { set<int> PairIndices; RaiseNodes(i); GetEdgePairIndices(EdgeNodePairSets, i, PairIndices); // Find matching nodes on opposite sides of domain. If it's a corner will return all 4 nodes if ( !PairIndices.empty() ) // If found matching pairs add them to the projected nodes array { if ( PairIndices.size() == 4 ) CornerIndex = PairIndices; set<int>::iterator itPairIndices; for ( itPairIndices = PairIndices.begin(); itPairIndices != PairIndices.end(); ++itPairIndices ) { if ( *itPairIndices != i ) m_ProjectedNodes[*itPairIndices].RaisedNodes = m_ProjectedNodes[i].RaisedNodes; } } } } else { RaiseNodes(i); } } m_VolumeMesh.Clear(); int iIndexCount=0; XYZ Pos; for (i=0; i<iNumNodes; ++i) { pair<int,vector<int> > ProjectedVolumeNode; vector<int> VolumeNodes; ProjectedVolumeNode.first = i; Pos = m_ProjectedNodes[i].Position; vector<RAISED_NODE> &RaisedNodes = m_ProjectedNodes[i].RaisedNodes; int iRaisedNum = (int)RaisedNodes.size(); for (j=0; j<iRaisedNum; ++j) { RaisedNodes[j].iIndex = iIndexCount++; Pos.z = RaisedNodes[j].dZ; m_VolumeMesh.AddNode(Pos); } } if ( m_bCreatePeriodic && m_iBoundaryConditions != NO_BOUNDARY_CONDITIONS ) { CreateNodeSets( EdgeNodePairSets, CornerIndex, Repeats ); } list<int>::iterator itIndex; list<int> &Indices = m_ProjectedMesh.GetIndices(CMesh::TRI); int iRegion; for (i = 0; i < CMesh::NUM_ELEMENT_TYPES; ++i) { m_ElementData[i].clear(); } m_EdgeConstraints.clear(); TRIANGLE Tri; for (itIndex = Indices.begin(), i=0; itIndex != Indices.end(); ++i) { for (j=0; j<3; ++j) Tri.i[j] = *(itIndex++); iRegion = m_TriangleRegions[i]; MeshColumn(Tri, iRegion); } } void CMesher::RaiseNodes(int iIndex) { set<int> YarnIndices; insert_iterator<set<int> > iiYarnIndices(YarnIndices, YarnIndices.end()); set<int>::iterator itYarnIndex; list<int>::iterator itIndex; list<int> &Indices = m_ProjectedMesh.GetIndices(CMesh::TRI); int i, j, iNode, iRegion; // Find projected triangles which have node (iIndex) as a corner for (itIndex = Indices.begin(), i=0; itIndex != Indices.end(); ++i) { for (j=0; j<3; ++j) { iNode = *(itIndex++); if (iNode == iIndex) { iRegion = m_TriangleRegions[i]; copy(m_ProjectedRegions[iRegion].YarnIndices.begin(), m_ProjectedRegions[iRegion].YarnIndices.end(), iiYarnIndices); } } } // Get the domain bounds XYZ Point = m_ProjectedMesh.GetNode(iIndex); pair<double, double> DomainBounds(0,0); bool bFound = GetMeshVerticalBounds(m_DomainMesh, Point, DomainBounds.first, DomainBounds.second, true); assert(bFound); // Get the yarn bounds map<int, pair<double, double> > YarnBounds; for (itYarnIndex=YarnIndices.begin(); itYarnIndex!=YarnIndices.end(); ++itYarnIndex) { pair<double, double> Bounds(0,0); bool bFound = GetMeshVerticalBounds(m_YarnMeshes[*itYarnIndex], Point, Bounds.first, Bounds.second, true); assert(bFound); //if ( bFound ) YarnBounds[*itYarnIndex] = Bounds; } // Remove overlaps that may exist between yarn boundaries map<int, pair<double, double> >::iterator itYarnBound, itCompareBound; pair<double, double> *pAbove, *pBelow; double dAverage; for (itYarnBound = YarnBounds.begin(); itYarnBound != YarnBounds.end(); ++itYarnBound) { // Make sure all the yarns fit within the domain if (itYarnBound->second.first < DomainBounds.first) itYarnBound->second.first = DomainBounds.first; if (itYarnBound->second.second > DomainBounds.second) itYarnBound->second.second = DomainBounds.second; // Make sure the yarns don't overlap each other for (itCompareBound = itYarnBound, ++itCompareBound; itCompareBound != YarnBounds.end(); ++itCompareBound) { if (itYarnBound->second.first+itYarnBound->second.second > // Check which yarn is on top itCompareBound->second.first+itCompareBound->second.second) { pAbove = &itYarnBound->second; pBelow = &itCompareBound->second; } else { pAbove = &itCompareBound->second; pBelow = &itYarnBound->second; } dAverage = 0.5*(pAbove->first + pBelow->second); // Average of overlapping edges pAbove->first = max(pAbove->first, dAverage); pAbove->second = max(pAbove->second, dAverage); pBelow->first = min(pBelow->first, dAverage); pBelow->second = min(pBelow->second, dAverage); } } // Domain bounds { RAISED_NODE RaisedNode; // RaisedNode.YarnBoundaryIndices.push_back(-1); // Not really necessary, and seems to be causing some bugs... RaisedNode.dZ = DomainBounds.first; m_ProjectedNodes[iIndex].RaisedNodes.push_back(RaisedNode); RaisedNode.dZ = DomainBounds.second; m_ProjectedNodes[iIndex].RaisedNodes.push_back(RaisedNode); } // Yarn bounds for (itYarnBound = YarnBounds.begin(); itYarnBound != YarnBounds.end(); ++itYarnBound) { RAISED_NODE RaisedNode; RaisedNode.YarnBoundaryIndices.push_back(itYarnBound->first); RaisedNode.dZ = itYarnBound->second.first; m_ProjectedNodes[iIndex].RaisedNodes.push_back(RaisedNode); RaisedNode.dZ = itYarnBound->second.second; m_ProjectedNodes[iIndex].RaisedNodes.push_back(RaisedNode); } SubdivideNodes(iIndex); } void CMesher::SubdivideNodes(int iIndex) { PROJECTED_NODE &ProjectedNode = m_ProjectedNodes[iIndex]; // Sort the nodes in ascending order of Z sort(ProjectedNode.RaisedNodes.begin(), ProjectedNode.RaisedNodes.end()); double dZ1, dZ2; int i, j; bool bBottom, bTop; for (i=0; i<(int)ProjectedNode.RaisedNodes.size()-1; ) { dZ1 = ProjectedNode.RaisedNodes[i].dZ; dZ2 = ProjectedNode.RaisedNodes[i+1].dZ; // Is Node1 the bottom-most node? bBottom = (i == 0); // Is Node2 the top-most node? bTop = (i == (int)ProjectedNode.RaisedNodes.size()-2); // Merge the boundaries that are less than a certain tolerance if (abs(dZ1 - dZ2) < m_dLayerMergeTolerance && !(bBottom && bTop)) { ProjectedNode.RaisedNodes[i].bMerged = true; if (bBottom) ProjectedNode.RaisedNodes[i].dZ = dZ1; else if (bTop) ProjectedNode.RaisedNodes[i].dZ = dZ2; else ProjectedNode.RaisedNodes[i].dZ = 0.5*(dZ1+dZ2); for (j=0; j<(int)ProjectedNode.RaisedNodes[i+1].YarnBoundaryIndices.size(); ++j) { ProjectedNode.RaisedNodes[i].YarnBoundaryIndices.push_back( ProjectedNode.RaisedNodes[i+1].YarnBoundaryIndices[j]); } ProjectedNode.RaisedNodes.erase(ProjectedNode.RaisedNodes.begin()+i+1); } else { ++i; } } // Divide these nodes up some.. // double dSeed = m_dSeed; double dSeed = GetBestSeed(iIndex); double dNumDivs; int iNumDivisions; RAISED_NODE RaisedNode; int iSize = (int)ProjectedNode.RaisedNodes.size(); for (i=0; i<iSize-1; ++i) { dZ1 = ProjectedNode.RaisedNodes[i].dZ; dZ2 = ProjectedNode.RaisedNodes[i+1].dZ; dNumDivs = (dZ2-dZ1)/dSeed; iNumDivisions = int(dNumDivs); if (dNumDivs-iNumDivisions > 0.5) ++iNumDivisions; for (j=0; j<iNumDivisions-1; ++j) { RaisedNode.dZ = dZ1 + (j+1)*((dZ2-dZ1)/iNumDivisions); ProjectedNode.RaisedNodes.push_back(RaisedNode); } } // Sort in the new nodes that where just pushed in on the end sort(ProjectedNode.RaisedNodes.begin(), ProjectedNode.RaisedNodes.end()); } double CMesher::GetBestSeed(int iIndex) { list<int>::iterator itIndex; list<int> &Indices = m_ProjectedMesh.GetIndices(CMesh::TRI); int iCorner[3]; int i; double dEdgeLength = 0; int iNumEdges = 0; for (itIndex = Indices.begin(), i=0; itIndex != Indices.end(); ++i) { for (i=0; i<3; ++i) { iCorner[i] = *(itIndex++); } for (i=0; i<3; ++i) { if (iCorner[i] == iIndex) { dEdgeLength += GetLength(m_ProjectedMesh.GetNode(iCorner[i]), m_ProjectedMesh.GetNode(iCorner[(i+1)%3])); dEdgeLength += GetLength(m_ProjectedMesh.GetNode(iCorner[i]), m_ProjectedMesh.GetNode(iCorner[(i+2)%3])); ++iNumEdges; ++iNumEdges; } } } double dSeed = m_dSeed; if (iNumEdges) dSeed = dEdgeLength/iNumEdges; return dSeed; } void CMesher::MeshColumn(TRIANGLE Triangle, int iRegion) { vector<int> &YarnIndices = m_ProjectedRegions[iRegion].YarnIndices; vector<vector<RAISED_NODE> > Column1, Column2, Column3; // Split each column into a number of smaller columns standing on top of each // other separated by the yarn boundaries SplitColumn(m_ProjectedNodes[Triangle.i[0]], YarnIndices, Column1); SplitColumn(m_ProjectedNodes[Triangle.i[1]], YarnIndices, Column2); SplitColumn(m_ProjectedNodes[Triangle.i[2]], YarnIndices, Column3); int i, iNumLayers = YarnIndices.size()*2+1; MESHER_ELEMENT_DATA ElemData; ElemData.iRegion = iRegion; int iTopYarnIndex, iBottomYarnIndex; for (i=0; i<iNumLayers; ++i) { ElemData.iLayer = i; if (i%2 == 0) { ElemData.iYarnIndex = -1; iBottomYarnIndex = -1; iTopYarnIndex = -1; if (i>0) iBottomYarnIndex = YarnIndices[(i/2)-1]; if (i/2<(int)YarnIndices.size()) iTopYarnIndex = YarnIndices[i/2]; } else { iBottomYarnIndex = iTopYarnIndex = ElemData.iYarnIndex = YarnIndices[i/2]; } vector<RAISED_NODE> Columns[3]; Columns[0] = Column1[i]; Columns[1] = Column2[i]; Columns[2] = Column3[i]; if (m_bQuadratic && m_bProjectMidSideNodes && iBottomYarnIndex==iTopYarnIndex && iBottomYarnIndex!=-1) BuildMidSideNodes(Columns, iBottomYarnIndex); set<pair<int, int> > EdgeConstraints[3]; BuildEdgeConstraints(Columns, EdgeConstraints); int iNumTets = TetMeshColumn(Columns, EdgeConstraints); m_ElementData[CMesh::TET].resize(m_ElementData[CMesh::TET].size()+iNumTets, ElemData); /* int iNumTets = m_VolumeMesh.GetNumElements(CMesh::TET); int iNumPyramids = m_VolumeMesh.GetNumElements(CMesh::PYRAMID); int iNumWedges = m_VolumeMesh.GetNumElements(CMesh::WEDGE); if (!m_bHybrid) { TetMeshColumn(Columns, EdgeConstraints); } else { MixedMeshColumn(Columns, EdgeConstraints); } iNumTets = m_VolumeMesh.GetNumElements(CMesh::TET) - iNumTets; iNumPyramids = m_VolumeMesh.GetNumElements(CMesh::PYRAMID) - iNumPyramids; iNumWedges = m_VolumeMesh.GetNumElements(CMesh::WEDGE) - iNumWedges; if (iNumTets) m_ElementData[CMesh::TET].resize(m_ElementData[CMesh::TET].size()+iNumTets, ElemData); if (iNumPyramids) m_ElementData[CMesh::PYRAMID].resize(m_ElementData[CMesh::PYRAMID].size()+iNumPyramids, ElemData); if (iNumWedges) m_ElementData[CMesh::WEDGE].resize(m_ElementData[CMesh::WEDGE].size()+iNumWedges, ElemData);*/ } } bool CMesher::SplitColumn(PROJECTED_NODE &Node, vector<int> &YarnIndices, vector<vector<RAISED_NODE> > &Column) { int i, j, iNumLayers = YarnIndices.size()*2+1; Column.clear(); Column.resize(iNumLayers); int iLayer = 0; for (i=0; i<(int)Node.RaisedNodes.size(); ++i) { Column[iLayer].push_back(Node.RaisedNodes[i]); for (j=0; j<(int)Node.RaisedNodes[i].YarnBoundaryIndices.size(); ++j) { if (count(YarnIndices.begin(), YarnIndices.end(), Node.RaisedNodes[i].YarnBoundaryIndices[j])) { ++iLayer; if (iLayer < iNumLayers) { Column[iLayer].push_back(Node.RaisedNodes[i]); } else { assert(false); return false; } } } } return true; } void CMesher::BuildMidSideNodes(vector<RAISED_NODE> Columns[3], int iYarnIndex) { int i, i1, i2; for (i=0; i<3; ++i) { i1 = i; i2 = (i+1)%3; if (!Columns[i1].empty() && !Columns[i2].empty()) { if (!Columns[i1].front().bMerged && !Columns[i2].front().bMerged) BuildMidSideNode(Columns[i1].front().iIndex, Columns[i2].front().iIndex, iYarnIndex, false); if (!Columns[i1].back().bMerged && !Columns[i2].back().bMerged) BuildMidSideNode(Columns[i1].back().iIndex, Columns[i2].back().iIndex, iYarnIndex, true); } } } void CMesher::BuildMidSideNode(int iNodeIndex1, int iNodeIndex2, int iYarnIndex, bool bTop) { if (iNodeIndex2 > iNodeIndex1) swap(iNodeIndex1, iNodeIndex2); pair<int, int> MidIndex(iNodeIndex1, iNodeIndex2); if (m_MidSideNodeLocations.count(MidIndex)) return; XYZ MidPos = 0.5 * (m_VolumeMesh.GetNode(iNodeIndex1) + m_VolumeMesh.GetNode(iNodeIndex2)); pair<double, double> YarnBounds; bool bFound = GetMeshVerticalBounds(m_YarnMeshes[iYarnIndex], MidPos, YarnBounds.first, YarnBounds.second, true); if (bFound) { if (bTop) MidPos.z = YarnBounds.second; else MidPos.z = YarnBounds.first; m_MidSideNodeLocations[MidIndex] = MidPos; } else assert(false); } XYZ CMesher::GetMidSideNode(int iNodeIndex1, int iNodeIndex2) { if (iNodeIndex2 > iNodeIndex1) swap(iNodeIndex1, iNodeIndex2); pair<int, int> MidIndex(iNodeIndex1, iNodeIndex2); map<pair<int, int>, XYZ>::iterator itNode = m_MidSideNodeLocations.find(MidIndex); if (itNode != m_MidSideNodeLocations.end()) return itNode->second; return 0.5 * (m_VolumeMesh.GetNode(iNodeIndex1) + m_VolumeMesh.GetNode(iNodeIndex2)); } void CMesher::ConvertMeshToQuadratic() { CMesh QuadraticMesh; QuadraticMesh.GetNodes() = m_VolumeMesh.GetNodes(); const list<int> &Indices = m_VolumeMesh.GetIndices(CMesh::TET); list<int>::const_iterator itIndex; int i1, i2, i3, i4; for (itIndex = Indices.begin(); itIndex != Indices.end(); ) { i1 = *(itIndex++); i2 = *(itIndex++); i3 = *(itIndex++); i4 = *(itIndex++); vector<int> QuadraticTet; QuadraticTet.push_back(i1); QuadraticTet.push_back(i2); QuadraticTet.push_back(i3); QuadraticTet.push_back(i4); QuadraticTet.push_back(QuadraticMesh.AddNode(GetMidSideNode(i1, i2))); QuadraticTet.push_back(QuadraticMesh.AddNode(GetMidSideNode(i2, i3))); QuadraticTet.push_back(QuadraticMesh.AddNode(GetMidSideNode(i3, i1))); QuadraticTet.push_back(QuadraticMesh.AddNode(GetMidSideNode(i1, i4))); QuadraticTet.push_back(QuadraticMesh.AddNode(GetMidSideNode(i2, i4))); QuadraticTet.push_back(QuadraticMesh.AddNode(GetMidSideNode(i3, i4))); QuadraticMesh.AddElement(CMesh::QUADRATIC_TET, QuadraticTet); } // Merge the nodes, because we added some new nodes that share the same location QuadraticMesh.MergeNodes(1e-9); m_VolumeMesh = QuadraticMesh; } void CMesher::BuildEdgeConstraints(vector<RAISED_NODE> Columns[3], set<pair<int, int> > EdgeConstraints[3]) { // This structure contains the list of edge constraints that must be // respected in order for the mesh edges to be well matched int k; int i1, i2; vector<RAISED_NODE>::iterator itRaisedNode1, itRaisedNode2; vector<int>::iterator itYarnBound1, itYarnBound2; map<int, int> BoundCount1; map<int, int> BoundCount2; // Conform to edge constraints caused by yarn boundaries for (k=0; k<3; ++k) { BoundCount1.clear(); for (i1 = 0; i1 < (int)Columns[k].size(); ++i1) { vector<int> &YarnBounds1 = Columns[k][i1].YarnBoundaryIndices; for (itYarnBound1 = YarnBounds1.begin(); itYarnBound1 != YarnBounds1.end(); ++itYarnBound1) { ++BoundCount1[*itYarnBound1]; BoundCount2.clear(); for (i2 = 0; i2 < (int)Columns[(k+1)%3].size(); ++i2) { vector<int> &YarnBounds2 = Columns[(k+1)%3][i2].YarnBoundaryIndices; for (itYarnBound2 = YarnBounds2.begin(); itYarnBound2 != YarnBounds2.end(); ++itYarnBound2) { ++BoundCount2[*itYarnBound2]; if (*itYarnBound1 == *itYarnBound2 && BoundCount1[*itYarnBound1] == BoundCount2[*itYarnBound2]) // *itYarnBound1 != iTopYarnIndex && // *itYarnBound1 != iBottomYarnIndex) { EdgeConstraints[k].insert(make_pair(i1, i2)); } } } } } } // Conform to edge constraints caused by existing elements pair<int, int> Edge; for (k=0; k<3; ++k) { for (i1 = 0; i1 < (int)Columns[k].size(); ++i1) { for (i2 = 0; i2 < (int)Columns[(k+1)%3].size(); ++i2) { Edge.first = Columns[k][i1].iIndex; Edge.second = Columns[(k+1)%3][i2].iIndex; if (Edge.first > Edge.second) swap(Edge.first, Edge.second); if (m_EdgeConstraints.count(Edge)) { EdgeConstraints[k].insert(make_pair(i1, i2)); } } } } } int CMesher::TetMeshColumn(vector<RAISED_NODE> Columns[3], set<pair<int, int> > EdgeConstraints[3]) { /* vector<PROJECTED_NODE*> Nodes; Nodes.push_back(&m_ProjectedNodes[iColumn1]); Nodes.push_back(&m_ProjectedNodes[iColumn2]); Nodes.push_back(&m_ProjectedNodes[iColumn3]);*/ int i, i1, i2; int h[3] = {0, 0, 0}; int Sizes[3]; for (i=0; i<3; ++i) { Sizes[i] = (int)Columns[i].size(); } double dZ, dZMin; int iMinIndex; int iNumElements = 0; set<pair<int, int> >::iterator itEdge; bool bEdgeConstraintViolation; while (h[0] < Sizes[0] && h[1] < Sizes[1] && h[2] < Sizes[2]) { iMinIndex = -1; for (i=0; i<3; ++i) { i1 = (i+1)%3; i2 = (i+2)%3; if (h[i]+1 < Sizes[i]) { dZ = Columns[i][h[i]+1].dZ; if (iMinIndex==-1 || dZ < dZMin) { // Check if adding this as a tetrahedron would violate any of the edge constraints bEdgeConstraintViolation = ViolatesEdgeConstraint(EdgeConstraints[i], EdgeConstraints[i2], h[i], h[i1], h[i2]); /* bEdgeConstraintViolation = false; for (itEdge = EdgeConstraints[i].begin(); itEdge != EdgeConstraints[i].end(); ++itEdge) { if (h[i] >= itEdge->first && h[(i+1)%3] < itEdge->second) { bEdgeConstraintViolation = true; } } for (itEdge = EdgeConstraints[(i+2)%3].begin(); itEdge != EdgeConstraints[(i+2)%3].end(); ++itEdge) { if (h[i] >= itEdge->second && h[(i+2)%3] < itEdge->first) { bEdgeConstraintViolation = true; } }*/ if (!bEdgeConstraintViolation) { dZMin = dZ; iMinIndex = i; } } } } if (iMinIndex == -1) { // This tet can't be meshed directly due to the edge constraints // if (h[0]+1 < Sizes[0] && h[1]+1 < Sizes[1] && h[2]+1 < Sizes[2]) { int Limits[6]; Limits[0] = Limits[3] = h[0]; Limits[1] = Limits[4] = h[1]; Limits[2] = Limits[5] = h[2]; bool bChanges; // Identify which region is going to be hard to mesh and store its limits in the Limits // array. do { bChanges = false; for (i=0; i<3; ++i) { for (itEdge = EdgeConstraints[i].begin(); itEdge != EdgeConstraints[i].end(); ++itEdge) { if (Limits[i] <= itEdge->first && itEdge->first < max(Limits[i+3], Limits[i]+1) && Limits[3+(i+1)%3] < itEdge->second) { Limits[3+(i+1)%3] = itEdge->second; bChanges = true; } } for (itEdge = EdgeConstraints[(i+2)%3].begin(); itEdge != EdgeConstraints[(i+2)%3].end(); ++itEdge) { if (Limits[i] <= itEdge->second && itEdge->second < max(Limits[i+3], Limits[i]+1) && Limits[3+(i+2)%3] < itEdge->first) { Limits[3+(i+2)%3] = itEdge->first; bChanges = true; } } } } while (bChanges); if (Limits[0] == Limits[3] && Limits[1] == Limits[4] && Limits[2] == Limits[5]) break; // We don't have anything to mesh here, game over... // Mesh it by adding an additional point to the mesh iNumElements += MeshDifficultRegion(Columns, Limits, EdgeConstraints); // Done! move up to the next layer h[0] = Limits[3]; h[1] = Limits[4]; h[2] = Limits[5]; } /* else { // assert(false); break; }*/ } else { vector<int> Indices; for (i=0; i<3; ++i) { Indices.push_back(Columns[i][h[i]].iIndex); } ++h[iMinIndex]; Indices.push_back(Columns[iMinIndex][h[iMinIndex]].iIndex); AddElement(CMesh::TET, Indices); // copy(Indices.begin(), Indices.end(), back_inserter(m_VolumeMesh.GetIndices(CMesh::TET))); ++iNumElements; } } return iNumElements; } int CMesher::MeshDifficultRegion(vector<RAISED_NODE> Columns[3], int Limits[6], set<pair<int, int> > EdgeConstraints[3]) { XYZ Center; int i, j; double dMinZ, dMaxZ; // Use projected triangle center for x and y components for (i=0; i<3; ++i) { Center += m_VolumeMesh.GetNode(Columns[i][Limits[i]].iIndex); } Center /= 3; // Find maximum and lowest Z, use the average as center z coordinate dMinZ = dMaxZ = Columns[0][Limits[0]].dZ; for (i=0; i<3; ++i) { for (j=Limits[i]; j<=Limits[i+3]; ++j) { if (Columns[i][j].dZ < dMinZ) dMinZ = Columns[i][j].dZ; else if (Columns[i][j].dZ > dMaxZ) dMaxZ = Columns[i][j].dZ; } } Center.z = 0.5*(dMinZ + dMaxZ); int iCenter = (int)m_VolumeMesh.GetNumNodes(); m_VolumeMesh.AddNode(Center); set<pair<int, int> >::iterator itEdge; int iElementsCreated = 0; // Bottom tet { vector<int> Indices; Indices.push_back(Columns[0][Limits[0]].iIndex); Indices.push_back(Columns[1][Limits[1]].iIndex); Indices.push_back(Columns[2][Limits[2]].iIndex); Indices.push_back(iCenter); AddElement(CMesh::TET, Indices); } ++iElementsCreated; int h1, h2; bool bEdgeConstraintViolation; // Side tets for (i=0; i<3; ++i) { h1 = Limits[i]; h2 = Limits[(i+1)%3]; while (h1 <= Limits[i+3]) { while (h2 < Limits[(i+1)%3+3]) { // If there is no edge constraint between higher than h1 to h2 or lower build a tet bEdgeConstraintViolation = false; for (itEdge = EdgeConstraints[i].begin(); itEdge != EdgeConstraints[i].end(); ++itEdge) { if (h1 < itEdge->first && h2 >= itEdge->second) { bEdgeConstraintViolation = true; } } if (bEdgeConstraintViolation) break; vector<int> Indices; Indices.push_back(iCenter); Indices.push_back(Columns[i][h1].iIndex); Indices.push_back(Columns[(i+1)%3][h2].iIndex); Indices.push_back(Columns[(i+1)%3][h2+1].iIndex); AddElement(CMesh::TET, Indices); ++iElementsCreated; ++h2; } if (h1 < Limits[i+3] && h2 <= Limits[(i+1)%3+3]) { // If there is no edge constraint between higher than h2 to h1 or lower build a tet bEdgeConstraintViolation = false; for (itEdge = EdgeConstraints[i].begin(); itEdge != EdgeConstraints[i].end(); ++itEdge) { if (h1 >= itEdge->first && h2 < itEdge->second) { bEdgeConstraintViolation = true; } } if (!bEdgeConstraintViolation) { vector<int> Indices; Indices.push_back(iCenter); Indices.push_back(Columns[i][h1].iIndex); Indices.push_back(Columns[(i+1)%3][h2].iIndex); Indices.push_back(Columns[i][h1+1].iIndex); AddElement(CMesh::TET, Indices); ++iElementsCreated; } else { assert(false); // should never get here } } ++h1; } } // Top tet { vector<int> Indices; Indices.push_back(iCenter); Indices.push_back(Columns[0][Limits[3]].iIndex); Indices.push_back(Columns[1][Limits[4]].iIndex); Indices.push_back(Columns[2][Limits[5]].iIndex); AddElement(CMesh::TET, Indices); } ++iElementsCreated; return iElementsCreated; } /* int CMesher::MixedMeshColumn(vector<RAISED_NODE> Columns[3], set<pair<int, int> > EdgeConstraints[3]) { int h[3] = {0, 0, 0}; int Sizes[3]; int i, i1, i2, j; for (i=0; i<3; ++i) { Sizes[i] = (int)Columns[i].size(); } set<pair<int, int> >::iterator itEdge; int iNumElements = 0; // while (h[0] < Sizes[0] && h[1] < Sizes[1] && h[2] < Sizes[2]) while (true) { bool up[3] = {true, true, true}; bool bChanges; do { bChanges = false; for (i=0; i<3; ++i) { if (!up[i]) continue; i1 = (i+1)%3; i2 = (i+2)%3; if (h[i]+1 >= Sizes[i] || ShouldConnect(Columns[i], Columns[i1], h[i], h[i1]+1) || ShouldConnect(Columns[i], Columns[i2], h[i], h[i2]+1) || ViolatesEdgeConstraint(EdgeConstraints[i], EdgeConstraints[i2], h[i], h[i1], h[i2])) { up[i] = false; bChanges = true; } } } while(bChanges); int UpCount = count(up, up+3, true); if (UpCount == 0) { for (i=0; i<3; ++i) { if (h[i]+1 != Sizes[i]) assert(false); } break; // THIS IS DIRECTLY PASTED FROM TETMESH, FIX IT UP... // // int Limits[6]; // Limits[0] = Limits[3] = h[0]; // Limits[1] = Limits[4] = h[1]; // Limits[2] = Limits[5] = h[2]; // bool bChanges; // // Identify which region is going to be hard to mesh and store its limits in the Limits // // array. // do // { // bChanges = false; // for (i=0; i<3; ++i) // { // for (itEdge = EdgeConstraints[i].begin(); itEdge != EdgeConstraints[i].end(); ++itEdge) // { // if (Limits[i] <= itEdge->first && itEdge->first < max(Limits[i+3], Limits[i]+1) && // Limits[3+(i+1)%3] < itEdge->second) // { // Limits[3+(i+1)%3] = itEdge->second; // bChanges = true; // } // } // for (itEdge = EdgeConstraints[(i+2)%3].begin(); itEdge != EdgeConstraints[(i+2)%3].end(); ++itEdge) // { // if (Limits[i] <= itEdge->second && itEdge->second < max(Limits[i+3], Limits[i]+1) && // Limits[3+(i+2)%3] < itEdge->first) // { // Limits[3+(i+2)%3] = itEdge->first; // bChanges = true; // } // } // } // } while (bChanges); // // if (Limits[0] == Limits[3] && // Limits[1] == Limits[4] && // Limits[2] == Limits[5]) // break; // We don't have anything to mesh here, game over... // // // Mesh it by adding an additional point to the mesh // iNumElements += MeshDifficultRegion(Columns, Limits, EdgeConstraints); // // // Done! move up to the next layer // h[0] = Limits[3]; // h[1] = Limits[4]; // h[2] = Limits[5]; // continue; } switch (UpCount) { case 3: { // Mesh with wedge elements // list<int> &Indices = m_VolumeMesh.GetIndices(CMesh::WEDGE); vector<int> Indices; for (i=0; i<3; ++i) { Indices.push_back(Columns[i][h[i]+1].iIndex); } for (i=0; i<3; ++i) { Indices.push_back(Columns[i][h[i]].iIndex); } AddElement(CMesh::WEDGE, Indices); } break; case 2: { // Mesh with pyramid elements // list<int> &Indices = m_VolumeMesh.GetIndices(CMesh::PYRAMID); vector<int> Indices; int iNoUp = 0; for (i=0; i<3; ++i) { if (!up[i]) iNoUp = i; } i1 = (iNoUp+2)%3; i2 = (iNoUp+1)%3; Indices.push_back(Columns[i1][h[i1]].iIndex); Indices.push_back(Columns[i2][h[i2]].iIndex); Indices.push_back(Columns[i2][h[i2]+1].iIndex); Indices.push_back(Columns[i1][h[i1]+1].iIndex); Indices.push_back(Columns[iNoUp][h[iNoUp]].iIndex); AddElement(CMesh::PYRAMID, Indices); } break; case 1: { // Mesh with wedge elements // list<int> &Indices = m_VolumeMesh.GetIndices(CMesh::TET); vector<int> Indices; for (i=0; i<3; ++i) { Indices.push_back(Columns[i][h[i]].iIndex); } for (i=0; i<3; ++i) { if (up[i]) { Indices.push_back(Columns[i][h[i]+1].iIndex); } } AddElement(CMesh::TET, Indices); } break; } ++iNumElements; for (i=0; i<3; ++i) { if (up[i]) ++h[i]; } } return iNumElements; } */ void CMesher::AddElement(CMesh::ELEMENT_TYPE Type, const vector<int> &Indices) { if (!m_VolumeMesh.AddElement(Type, Indices)) return; switch (Type) { case CMesh::TET: { NODE_PAIR NodePair; AddEdgeConstraint(Indices[0], Indices[1]); if ( GetPairIndices( Indices[0], Indices[1], NodePair ) ) AddEdgeConstraint( NodePair.first, NodePair.second ); AddEdgeConstraint(Indices[0], Indices[2]); if ( GetPairIndices( Indices[0], Indices[2], NodePair ) ) AddEdgeConstraint( NodePair.first, NodePair.second ); AddEdgeConstraint(Indices[0], Indices[3]); if ( GetPairIndices( Indices[0], Indices[3], NodePair ) ) AddEdgeConstraint( NodePair.first, NodePair.second ); AddEdgeConstraint(Indices[1], Indices[2]); if ( GetPairIndices( Indices[1], Indices[2], NodePair ) ) AddEdgeConstraint( NodePair.first, NodePair.second ); AddEdgeConstraint(Indices[1], Indices[3]); if ( GetPairIndices( Indices[1], Indices[3], NodePair ) ) AddEdgeConstraint( NodePair.first, NodePair.second ); AddEdgeConstraint(Indices[2], Indices[3]); if ( GetPairIndices( Indices[2], Indices[3], NodePair ) ) AddEdgeConstraint( NodePair.first, NodePair.second ); break; } case CMesh::PYRAMID: AddEdgeConstraint(Indices[0], Indices[1]); AddEdgeConstraint(Indices[1], Indices[2]); AddEdgeConstraint(Indices[2], Indices[3]); AddEdgeConstraint(Indices[3], Indices[0]); AddEdgeConstraint(Indices[0], Indices[4]); AddEdgeConstraint(Indices[1], Indices[4]); AddEdgeConstraint(Indices[2], Indices[4]); AddEdgeConstraint(Indices[3], Indices[4]); break; case CMesh::WEDGE: AddEdgeConstraint(Indices[0], Indices[1]); AddEdgeConstraint(Indices[1], Indices[2]); AddEdgeConstraint(Indices[2], Indices[0]); AddEdgeConstraint(Indices[3], Indices[4]); AddEdgeConstraint(Indices[4], Indices[5]); AddEdgeConstraint(Indices[5], Indices[3]); AddEdgeConstraint(Indices[0], Indices[3]); AddEdgeConstraint(Indices[1], Indices[4]); AddEdgeConstraint(Indices[2], Indices[5]); break; } } void CMesher::AddEdgeConstraint(int i1, int i2) { pair<int, int> EdgeConstraint(i1, i2); if (EdgeConstraint.first > EdgeConstraint.second) swap(EdgeConstraint.first, EdgeConstraint.second); m_EdgeConstraints.insert(EdgeConstraint); } bool CMesher::ViolatesEdgeConstraint(const set<pair<int, int> > &EdgeConstraints1, const set<pair<int, int> > &EdgeConstraints2, int h, int h1, int h2) { set<pair<int, int> >::const_iterator itEdge; for (itEdge = EdgeConstraints1.begin(); itEdge != EdgeConstraints1.end(); ++itEdge) { if (h >= itEdge->first && h1 < itEdge->second) { return true; } } for (itEdge = EdgeConstraints2.begin(); itEdge != EdgeConstraints2.end(); ++itEdge) { if (h >= itEdge->second && h2 < itEdge->first) { return true; } } return false; } bool CMesher::ShouldConnect(vector<RAISED_NODE> &Column1, vector<RAISED_NODE> &Column2, int h1, int h2) { if (h1 >= (int)Column1.size()) return false; if (h2 >= (int)Column2.size()) return false; double dDist = abs(Column1[h1].dZ - Column2[h2].dZ); bool bClosest = true; int j; for (j=0; j<(int)Column1.size(); ++j) { if (j == h1) continue; if (abs(Column1[j].dZ - Column2[h2].dZ) <= dDist) { bClosest = false; break; } } if (bClosest) return true; bClosest = true; for (j=0; j<(int)Column2.size(); ++j) { if (j == h2) continue; if (abs(Column1[h1].dZ - Column2[j].dZ) <= dDist) { bClosest = false; break; } } return bClosest; } void CMesher::FillYarnTangentsData() { if (!m_pTextile) return; const CDomain* pDomain = m_pTextile->GetDomain(); // This value may need tweaking //double dTolerance = 1e-1; double dTolerance = 1e-5; list<MESHER_ELEMENT_DATA>::iterator itElementData; list<int>::const_iterator itIndex; int i, iNumNodes; int iNumYarns = m_pTextile->GetNumYarns(); bool bInside; vector<vector<XYZ> > YarnTranslations; YarnTranslations.resize(iNumYarns); if (pDomain) { for (i=0; i<iNumYarns; ++i) { YarnTranslations[i] = pDomain->GetTranslations(*m_pTextile->GetYarn(i)); } } int j; for (j = 0; j < CMesh::NUM_ELEMENT_TYPES; ++j) { list<int> &Indices = m_VolumeMesh.GetIndices((CMesh::ELEMENT_TYPE)j); list<MESHER_ELEMENT_DATA> &ElementData = m_ElementData[(CMesh::ELEMENT_TYPE)j]; iNumNodes = CMesh::GetNumNodes((CMesh::ELEMENT_TYPE)j); for (itIndex = Indices.begin(), itElementData = ElementData.begin(); itIndex != Indices.end() && itElementData != ElementData.end(); ++itElementData) { XYZ AvgPos; for (i=0; i<iNumNodes; ++i) { AvgPos += m_VolumeMesh.GetNode(*(itIndex++)); } AvgPos /= iNumNodes; if (itElementData->iYarnIndex >= 0 && itElementData->iYarnIndex < iNumYarns) { CYarn* pYarn = m_pTextile->GetYarn(itElementData->iYarnIndex); bInside = pYarn->PointInsideYarn(AvgPos, YarnTranslations[itElementData->iYarnIndex], &itElementData->YarnTangent, &itElementData->Location, &itElementData->dVolumeFraction, &itElementData->dSurfaceDistance, dTolerance, &itElementData->Orientation, &itElementData->Up); //assert(bInside); if ( !bInside ) TGLOG("PointInsideYarn false"); } } } } const list<MESHER_ELEMENT_DATA> *CMesher::GetElementData(CMesh::ELEMENT_TYPE ElementType) { if (ElementType < 0 || ElementType >= CMesh::NUM_ELEMENT_TYPES) { TGERROR("Unable to get element data, invalid element type: " << ElementType); return NULL; } return &m_ElementData[ElementType]; } bool CMesher::GetPairIndices(int iIndex1, int iIndex2, NODE_PAIR &MatchPair) { NODE_PAIR_SETS::iterator itSets = m_NodePairSets.begin(); bool bFoundFirst = false, bFoundSecond = false; // Iterate through node pair sets until find one which contains both nodes (node pair set contains pairs on opposite boundaries) while ( itSets != m_NodePairSets.end() && !(bFoundFirst && bFoundSecond) ) { NODE_PAIR_SET::iterator itNodePairSet = (*itSets).begin(); bFoundFirst = false; bFoundSecond = false; while( itNodePairSet != (*itSets).end() && !(bFoundFirst && bFoundSecond) ) // Iterate through node pair set until found match for both nodes { if (!bFoundFirst) { if ( (*itNodePairSet).first == iIndex1 ) { MatchPair.first = (*itNodePairSet).second; bFoundFirst = true; } else if ( (*itNodePairSet).second == iIndex1 ) { MatchPair.first = (*itNodePairSet).first; bFoundFirst = true; } } if ( !bFoundSecond ) { if ( (*itNodePairSet).first == iIndex2 ) { MatchPair.second = (*itNodePairSet).second; bFoundSecond = true; } else if ( (*itNodePairSet).second == iIndex2 ) { MatchPair.second = (*itNodePairSet).first; bFoundSecond = true; } } ++itNodePairSet; } ++itSets; } return ( bFoundFirst && bFoundSecond ); } void CMesher::GetEdgePairIndices(const NODE_PAIR_SETS &NodePairSets, int iIndex, set<int> &Match) { NODE_PAIR_SETS::const_iterator itSets = NodePairSets.begin(); int iNumFound = 0; while ( itSets != NodePairSets.end() ) { NODE_PAIR_SET::const_iterator itNodePairSet = (*itSets).begin(); pair<set<int>::iterator, bool> ret; bool bFound = false; while( itNodePairSet != (*itSets).end() && !bFound ) { if ( (*itNodePairSet).first == iIndex ) { ret = Match.insert( (*itNodePairSet).second ); if ( ret.second ) // Returns true in second if new element was added { bFound = true; iNumFound++; } } else if ( (*itNodePairSet).second == iIndex ) { ret = Match.insert( (*itNodePairSet).first ); if ( ret.second ) { bFound = true; iNumFound++; } } ++itNodePairSet; } ++itSets; } if ( iNumFound > 1 ) // If found more than one must be a corner so call function again to get other corner node { GetEdgePairIndices( NodePairSets, *(Match.begin()), Match ); } } void CMesher::SortPairs( NODE_PAIR_SET &NodePairs, bool bSwapY ) { NODE_PAIR_SET::iterator itNodePairs; for ( itNodePairs = NodePairs.begin(); itNodePairs != NodePairs.end(); ++itNodePairs ) { XYZ Node1 = m_ProjectedMesh.GetNode((*itNodePairs).first); XYZ Node2 = m_ProjectedMesh.GetNode((*itNodePairs).second); if (bSwapY ) { if ( Node1.y > Node2.y ) { swap( (*itNodePairs).first, (*itNodePairs).first ); } } else { if ( Node1.x > Node2.x ) { swap( (*itNodePairs).first, (*itNodePairs).first ); } } } } void CMesher::CreateNodeSets( NODE_PAIR_SETS &EdgeNodePairSets, set<int> &CornerIndex, const vector<XYZ> &Repeats ) { // Find boundary node pair sets m_NodePairSets.clear(); NODE_PAIR_SETS::iterator itEdgeNodeSets; set<int> CompletedCorners; set<int> EdgeIndices; m_Edges.resize(12); m_Vertices.resize(8); int j = 0; for ( itEdgeNodeSets = EdgeNodePairSets.begin(); itEdgeNodeSets != EdgeNodePairSets.end(); ++itEdgeNodeSets ) { NODE_PAIR_SET::iterator itNodePairs; NODE_PAIR_SET VolMeshPairs; VolMeshPairs.clear(); bool bConstX = (Repeats[j++].y == 0); for ( itNodePairs = (*itEdgeNodeSets).begin(); itNodePairs != (*itEdgeNodeSets).end(); ++itNodePairs ) { // Indices in the pairs in the edge node sets correspond to index into m_Projected Nodes NODE_PAIR NodePair; vector<RAISED_NODE>::iterator itRaisedNodes; int ind1 = (*itNodePairs).first; int ind2 = (*itNodePairs).second; int size = m_ProjectedNodes[ind1].RaisedNodes.size(); EdgeIndices.insert(ind1); EdgeIndices.insert(ind2); assert( size == m_ProjectedNodes[ind2].RaisedNodes.size() ); if ( CornerIndex.find(ind1) != CornerIndex.end() ) // Is corner node { if ( CompletedCorners.find(ind1) == CompletedCorners.end() ) // Check if already entered nodes { vector<int> Edge1, Edge2; for ( int i = 1; i < size-1; ++i ) { Edge1.push_back(m_ProjectedNodes[ind1].RaisedNodes[i].iIndex + 1); Edge2.push_back(m_ProjectedNodes[ind2].RaisedNodes[i].iIndex + 1); } if ( m_Edges[0].empty() ) { m_Edges[0] = Edge1; m_Edges[1] = Edge2; } else { m_Edges[2] = Edge2; m_Edges[3] = Edge1; } int StartInd = 0; if ( !CompletedCorners.empty() ) { StartInd = 2; swap(ind1,ind2); } m_Vertices[StartInd++] = (m_ProjectedNodes[ind1].RaisedNodes[0].iIndex + 1); m_Vertices[StartInd++] = (m_ProjectedNodes[ind2].RaisedNodes[0].iIndex + 1); StartInd += 2; m_Vertices[StartInd++] = (m_ProjectedNodes[ind1].RaisedNodes[size-1].iIndex + 1); m_Vertices[StartInd] = (m_ProjectedNodes[ind2].RaisedNodes[size-1].iIndex + 1); CompletedCorners.insert(ind1); CompletedCorners.insert(ind2); } } else { int StartInd = bConstX ? 4 : 8; m_Edges[StartInd++].push_back(m_ProjectedNodes[ind1].RaisedNodes[0].iIndex + 1); m_Edges[StartInd++].push_back(m_ProjectedNodes[ind2].RaisedNodes[0].iIndex + 1); m_Edges[StartInd++].push_back(m_ProjectedNodes[ind2].RaisedNodes[size-1].iIndex + 1); m_Edges[StartInd++].push_back(m_ProjectedNodes[ind1].RaisedNodes[size-1].iIndex + 1); for ( int i = 1; i < size-1; ++i ) { if ( bConstX ) { m_FaceA.push_back(m_ProjectedNodes[ind2].RaisedNodes[i].iIndex + 1); m_FaceB.push_back(m_ProjectedNodes[ind1].RaisedNodes[i].iIndex + 1); } else { m_FaceC.push_back(m_ProjectedNodes[ind2].RaisedNodes[i].iIndex + 1); m_FaceD.push_back(m_ProjectedNodes[ind1].RaisedNodes[i].iIndex + 1); } } } // Iterate through the column of nodes and match up the corresponding nodes for each of the pair for ( int i = 0; i < m_ProjectedNodes[ind1].RaisedNodes.size(); ++i ) { NodePair.first = m_ProjectedNodes[ind1].RaisedNodes[i].iIndex + 1; // RaisedNodes[i].iIndex contains index in the volume mesh NodePair.second = m_ProjectedNodes[ind2].RaisedNodes[i].iIndex + 1; VolMeshPairs.push_back( NodePair ); } } m_NodePairSets.push_back( VolMeshPairs ); } int Size = m_ProjectedNodes.size(); for ( int i = 0; i < Size; ++i ) { if ( EdgeIndices.find(i) == EdgeIndices.end() ) { m_FaceE.push_back(m_ProjectedNodes[i].RaisedNodes[m_ProjectedNodes[i].RaisedNodes.size()-1].iIndex + 1); m_FaceF.push_back(m_ProjectedNodes[i].RaisedNodes[0].iIndex + 1); } } } bool CMesher::SaveNodeSets() { if (m_Vertices.size() != 8 ) return false; for ( int i = 0; i < 8; ++i ) { m_PeriodicBoundaries->SetVertex(m_Vertices[i]); } if ( m_Edges.size() != 12 ) return false; for ( int i = 0; i < 12; ++i ) { m_PeriodicBoundaries->SetEdges( m_Edges[i] ); } if ( m_FaceA.size() == 0 || m_FaceB.size() == 0 || m_FaceC.size() == 0 || m_FaceD.size() == 0 || m_FaceE.size() == 0 || m_FaceF.size() == 0 ) return false; m_PeriodicBoundaries->SetFaceA(m_FaceA, m_FaceB); m_PeriodicBoundaries->SetFaceB(m_FaceC, m_FaceD); m_PeriodicBoundaries->SetFaceC(m_FaceE, m_FaceF); return true; } void CMesher::AddQuadraticNodesToSets() { vector< set<int> > FaceSets; SetupFaceSets( FaceSets ); int NumNodes = m_VolumeMesh.GetNumNodes(); map<int,vector<int> > FaceSetIndices; for ( int i = 1; i <= NumNodes; ++i ) { vector<int> FaceSet = FindFaceSets( FaceSets, i ); if ( FaceSet.size() > 0 ) { FaceSetIndices[i] = FaceSet; } } const list<int> &Indices = m_VolumeMesh.GetIndices(CMesh::QUADRATIC_TET); NumNodes = CMesh::GetNumNodes(CMesh::QUADRATIC_TET); list<int>::const_iterator itIndex; map<int,vector<int> >::iterator itEndIndices = FaceSetIndices.end(); vector<int> iIndex; for (itIndex = Indices.begin(); itIndex != Indices.end(); ) { list<int> Faces; iIndex.clear(); list<int>::const_iterator itEndIndex = itIndex; advance( itEndIndex, NumNodes); iIndex.insert( iIndex.begin(), itIndex, itEndIndex ); for ( int i = 0; i < 4; ++i ) { if ( FaceSetIndices.find(iIndex[i]+1) == itEndIndices ) continue; // Node not on surface therefore mid node won't be either for ( int j = i+1; j < 4; ++j ) { if ( FaceSetIndices.find(iIndex[j]+1) == itEndIndices ) continue; // Node not on surface AddQuadNodeToSet( i, j, FaceSetIndices[iIndex[i]+1], FaceSetIndices[iIndex[j]+1], iIndex ); } } advance(itIndex, NumNodes); } RemoveDuplicateNodes(); } void CMesher::SetupFaceSets( vector< set<int> >& FaceSets ) { set<int> FaceSet; FaceSet.insert( m_FaceA.begin(), m_FaceA.end() ); FaceSet.insert( m_Edges[1].begin(), m_Edges[1].end() ); FaceSet.insert( m_Edges[2].begin(), m_Edges[2].end() ); FaceSet.insert( m_Edges[5].begin(), m_Edges[5].end() ); FaceSet.insert(m_Edges[6].begin(), m_Edges[6].end() ); FaceSet.insert( m_Vertices[1] ); FaceSet.insert( m_Vertices[2] ); FaceSet.insert( m_Vertices[5] ); FaceSet.insert( m_Vertices[6] ); FaceSets.push_back( FaceSet ); FaceSet.clear(); FaceSet.insert( m_FaceB.begin(), m_FaceB.end() ); FaceSet.insert( m_Edges[0].begin(), m_Edges[0].end() ); FaceSet.insert( m_Edges[3].begin(), m_Edges[3].end() ); FaceSet.insert( m_Edges[4].begin(), m_Edges[4].end() ); FaceSet.insert( m_Edges[7].begin(), m_Edges[7].end() ); FaceSet.insert( m_Vertices[0] ); FaceSet.insert( m_Vertices[3] ); FaceSet.insert( m_Vertices[4] ); FaceSet.insert( m_Vertices[7] ); FaceSets.push_back( FaceSet ); FaceSet.clear(); FaceSet.insert( m_FaceC.begin(), m_FaceC.end() ); FaceSet.insert( m_Edges[2].begin(), m_Edges[2].end() ); FaceSet.insert( m_Edges[3].begin(), m_Edges[3].end() ); FaceSet.insert( m_Edges[9].begin(), m_Edges[9].end() ); FaceSet.insert( m_Edges[10].begin(), m_Edges[10].end() ); FaceSet.insert( m_Vertices[2] ); FaceSet.insert( m_Vertices[3] ); FaceSet.insert( m_Vertices[6] ); FaceSet.insert( m_Vertices[7] ); FaceSets.push_back( FaceSet ); FaceSet.clear(); FaceSet.insert( m_FaceD.begin(), m_FaceD.end() ); FaceSet.insert( m_Edges[0].begin(), m_Edges[0].end() ); FaceSet.insert( m_Edges[1].begin(), m_Edges[1].end() ); FaceSet.insert( m_Edges[8].begin(), m_Edges[8].end() ); FaceSet.insert( m_Edges[11].begin(), m_Edges[11].end() ); FaceSet.insert( m_Vertices[0] ); FaceSet.insert( m_Vertices[1] ); FaceSet.insert( m_Vertices[4] ); FaceSet.insert( m_Vertices[5] ); FaceSets.push_back( FaceSet ); FaceSet.clear(); FaceSet.insert( m_FaceE.begin(), m_FaceE.end() ); FaceSet.insert( m_Edges[6].begin(), m_Edges[6].end() ); FaceSet.insert( m_Edges[7].begin(), m_Edges[7].end() ); FaceSet.insert( m_Edges[10].begin(), m_Edges[10].end() ); FaceSet.insert( m_Edges[11].begin(), m_Edges[11].end() ); FaceSet.insert( m_Vertices[4] ); FaceSet.insert( m_Vertices[5] ); FaceSet.insert( m_Vertices[6] ); FaceSet.insert( m_Vertices[7] ); FaceSets.push_back( FaceSet ); FaceSet.clear(); FaceSet.insert( m_FaceF.begin(), m_FaceF.end() ); FaceSet.insert( m_Edges[4].begin(), m_Edges[4].end() ); FaceSet.insert( m_Edges[5].begin(), m_Edges[5].end() ); FaceSet.insert( m_Edges[8].begin(), m_Edges[8].end() ); FaceSet.insert( m_Edges[9].begin(), m_Edges[9].end() ); FaceSet.insert( m_Vertices[0] ); FaceSet.insert( m_Vertices[1] ); FaceSet.insert( m_Vertices[2] ); FaceSet.insert( m_Vertices[3] ); FaceSets.push_back( FaceSet ); } vector<int> CMesher::FindFaceSets( vector< set<int> >& FaceSets, int iIndex ) { int i; vector<int> Indices; for ( i = 0; i < FaceSets.size(); ++i ) { if ( FaceSets[i].find( iIndex ) != FaceSets[i].end() ) Indices.push_back(i); } return( Indices ); } void CMesher::AddQuadNodeToSet( int i, int j, vector<int>& FaceSet1, vector<int>& FaceSet2, vector<int> &Indices ) { int iSize1 = FaceSet1.size(); int iSize2 = FaceSet2.size(); if ( iSize1 == 1 && iSize2 == 1 ) // Both face sets { if ( FaceSet1[0] == FaceSet2[0] ) // Same face, add mid node to it AddQuadNodeToFace( i, j, FaceSet1[0], Indices ); return; } else if ( (iSize1 == 1 && iSize2 == 2) || (iSize1 == 2 && iSize2 == 1) ) // One face, one edge { if ( iSize1 == 1 ) { if ( FaceSet1[0] == FaceSet2[0] || FaceSet1[0] == FaceSet2[1] ) AddQuadNodeToFace( i, j, FaceSet1[0], Indices ); } else { if ( FaceSet2[0] == FaceSet1[0] || FaceSet2[0] == FaceSet1[1] ) AddQuadNodeToFace( i, j, FaceSet2[0], Indices ); } } else if ( iSize1 == 2 && iSize2 == 2 ) // Both edges { if ( (FaceSet1[0] == FaceSet2[0]) && (FaceSet1[1] == FaceSet2[1]) ) // Created from sets so assume sorted { AddQuadNodeToEdge( i, j, GetEdge(FaceSet1[0], FaceSet1[1]), Indices ); // Faces same so both have common edge } else if ( (FaceSet1[0] == FaceSet2[0]) || (FaceSet1[0] == FaceSet2[1]) ) // One face in common so node on face between two edges { AddQuadNodeToFace( i, j, FaceSet1[0], Indices ); } else if ( (FaceSet1[1] == FaceSet2[0]) || (FaceSet1[1] == FaceSet2[1]) ) { AddQuadNodeToFace( i, j, FaceSet1[1], Indices ); } } else if ( (iSize1 == 1 && iSize2 == 3) || (iSize1 == 3 && iSize2 == 1) ) // One face, one corner { if ( iSize1 == 1 ) { if ( (FaceSet1[0] == FaceSet2[0]) || (FaceSet1[0] == FaceSet2[1]) || (FaceSet1[0] == FaceSet2[2]) ) AddQuadNodeToFace( i, j, FaceSet1[0], Indices ); } else { if ( (FaceSet2[0] == FaceSet1[0]) || (FaceSet2[0] == FaceSet1[1]) || (FaceSet2[0] == FaceSet1[2]) ) AddQuadNodeToFace( i, j, FaceSet2[0], Indices ); } } else if ( (iSize1 == 2 && iSize2 == 3) || (iSize1 == 3 && iSize2 == 2) ) // One edge, one corner { vector<int> Face1 = iSize1 == 2 ? FaceSet1 : FaceSet2; vector<int> Face2 = iSize1 == 2 ? FaceSet2 : FaceSet1; if ( Face1[0] == Face2[0] ) { if ( Face1[1] == Face2[1] || Face1[1] == Face2[2] ) { AddQuadNodeToEdge( i, j, GetEdge( Face1[0], Face1[1]), Indices ); } else AddQuadNodeToFace( i, j, Face1[0], Indices ); } else if ( Face1[0] == Face2[1] ) { if ( Face1[1] == Face2[2] ) { AddQuadNodeToEdge( i, j, GetEdge( Face1[0], Face1[1] ), Indices); } else AddQuadNodeToFace( i, j, Face1[0], Indices ); } else if ( Face1[0] == Face2[2] ) { AddQuadNodeToFace( i, j, Face1[0], Indices ); } else if ( Face1[1] == Face2[0] || Face1[1] == Face2[1] || Face1[1] == Face2[2] ) { AddQuadNodeToFace( i, j, Face1[1], Indices ); } } else if ( iSize1 == 3 && iSize2 == 3 ) // Both corners { // Will only occur if mesh is one element wide between corners - need to code? See notes for 26-11-13 } } void CMesher::AddQuadNodeToFace( int i, int j, int iFace, vector<int> &Indices ) { int iNode = GetQuadNodeToAdd( i, j ); switch (iFace) { case FACE_A: m_FaceA.push_back( Indices[iNode]+1 ); break; case FACE_B: m_FaceB.push_back( Indices[iNode]+1 ); break; case FACE_C: m_FaceC.push_back( Indices[iNode]+1 ); break; case FACE_D: m_FaceD.push_back( Indices[iNode]+1 ); break; case FACE_E: m_FaceE.push_back( Indices[iNode]+1 ); break; case FACE_F: m_FaceF.push_back( Indices[iNode]+1 ); break; } } void CMesher::AddQuadNodeToEdge( int i, int j, int iEdge, vector<int> &Indices ) { int iNode = GetQuadNodeToAdd( i, j ); m_Edges[iEdge].push_back( Indices[iNode]+1); } int CMesher::GetEdge( int iFace1, int iFace2 ) { switch ( iFace1 ) { case FACE_A: { switch ( iFace2 ) { case FACE_C: return 2; case FACE_D: return 1; case FACE_E: return 6; case FACE_F: return 5; } break; } case FACE_B: { switch ( iFace2 ) { case FACE_C: return 3; case FACE_D: return 0; case FACE_E: return 7; case FACE_F: return 4; } break; } case FACE_C: { switch ( iFace2 ) { case FACE_E: return 10; case FACE_F: return 9; } break; } case FACE_D: { switch ( iFace2 ) { case FACE_E: return 11; case FACE_F: return 8; } break; } default: break; } return -1; } int CMesher::GetQuadNodeToAdd( int i, int j ) { if ( i == 0 ) { if ( j == 1 ) return 4; if ( j == 2 ) return 6; if ( j == 3 ) return 7; } if ( i == 1 ) { if ( j == 2 ) return 5; if ( j == 3 ) return 8; } return 9; } void CMesher::RemoveDuplicateNodes() { vector<vector<int> >::iterator itEdge; RemoveDuplicateFaceNodes( m_FaceA ); RemoveDuplicateFaceNodes( m_FaceB ); RemoveDuplicateFaceNodes( m_FaceC ); RemoveDuplicateFaceNodes( m_FaceD ); RemoveDuplicateFaceNodes( m_FaceE ); RemoveDuplicateFaceNodes( m_FaceF ); for ( itEdge = m_Edges.begin(); itEdge != m_Edges.end(); ++itEdge ) { RemoveDuplicateFaceNodes( *itEdge ); } } void CMesher::RemoveDuplicateFaceNodes( vector<int>& FaceSet ) { vector<int>::iterator itNewEnd; sort( FaceSet.begin(), FaceSet.end() ); itNewEnd = unique(FaceSet.begin(), FaceSet.end()); // remove duplicates FaceSet.erase(itNewEnd, FaceSet.end()); }
28.708861
273
0.657795
[ "mesh", "vector", "3d" ]
8d9c7f0af84588b3018be717e473ac303f842f51
1,007
cpp
C++
Codemonk/Basics of Greedy Algorithms/Hunger Games.cpp
amarlearning/CodeForces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
3
2016-02-20T12:14:51.000Z
2016-03-18T20:09:36.000Z
Codemonk/Basics of Greedy Algorithms/Hunger Games.cpp
amarlearning/Codeforces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
null
null
null
Codemonk/Basics of Greedy Algorithms/Hunger Games.cpp
amarlearning/Codeforces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
2
2018-07-26T21:00:42.000Z
2019-11-30T19:33:57.000Z
/* Author : Amar Prakash Pandey contact : http://amarpandey.me */ #include <bits/stdc++.h> using namespace std; #ifndef ll #define ll long long #endif vector <ll int> vec; int main(int argc, char const *argv[]) { ll int N, temp, cnt = 0; scanf("%lld", &N); for(int i=0; i < N; i++) { cin >> temp; vec.push_back(temp); } sort(vec.begin(), vec.end()); temp = 0; for(int i=0; i < vec.size()-3; i++) { if(i == 0) { if(temp < (vec.at(i+1) - vec.at(i))) temp = vec.at(i+1) - vec.at(i); else if(temp < (vec.at(i+2) - vec.at(i))) temp = vec.at(i+2) - vec.at(i); } else { if(temp < (vec.at(i+2) - vec.at(i))) temp = vec.at(i+2) - vec.at(i); } } if(temp < (vec.at(vec.size()-1) - vec.at(vec.size()-2) )) temp = vec.at(vec.size()-1) - vec.at(vec.size()-2); if(temp < (vec.at(vec.size()-1) - vec.at(vec.size()-3) )) temp = vec.at(vec.size()-1) - vec.at(vec.size()-3); cout << temp << endl; vec.clear(); return 0; }
20.14
59
0.514399
[ "vector" ]
8da101e99bbdf722fea9eaaedc0cc4b628202ff7
9,652
cpp
C++
test/cpp/jit/test_utils.cpp
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
60,067
2017-01-18T17:21:31.000Z
2022-03-31T21:37:45.000Z
test/cpp/jit/test_utils.cpp
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
66,955
2017-01-18T17:21:38.000Z
2022-03-31T23:56:11.000Z
test/cpp/jit/test_utils.cpp
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
19,210
2017-01-18T17:45:04.000Z
2022-03-31T23:51:56.000Z
#include <gtest/gtest.h> #include <test/cpp/jit/test_utils.h> #include <torch/csrc/jit/jit_log.h> #include <torch/csrc/jit/passes/clear_undefinedness.h> #include <torch/csrc/jit/runtime/custom_operator.h> namespace torch { namespace jit { Stack createStack(std::vector<at::Tensor>&& list) { return Stack( std::make_move_iterator(list.begin()), std::make_move_iterator(list.end())); } void assertAllClose(const tensor_list& a, const tensor_list& b) { ASSERT_EQ(a.size(), b.size()); for (size_t i = 0; i < a.size(); ++i) { ASSERT_TRUE(a[i].is_same_size(b[i])); ASSERT_TRUE(a[i].allclose(b[i])); } } std::vector<at::Tensor> run( InterpreterState& interp, const std::vector<at::Tensor>& inputs) { std::vector<IValue> stack(inputs.begin(), inputs.end()); interp.run(stack); return fmap(stack, [](const IValue& i) { return i.toTensor(); }); } static void unpackReturnTuple(Stack& stack) { auto tuple = pop(stack).toTuple(); stack.insert(stack.end(), tuple->elements().begin(), tuple->elements().end()); } std::pair<tensor_list, tensor_list> runGradient( Gradient& grad_spec, tensor_list& tensors_in, tensor_list& tensor_grads_in) { static const auto as_tensorlist = [](const Stack& stack) { return fmap(stack, [](const IValue& i) { return i.toTensor(); }); }; ClearUndefinedness(grad_spec.df); Code f_code{grad_spec.f, ""}, df_code{grad_spec.df, ""}; InterpreterState f_interpreter{f_code}, df_interpreter{df_code}; auto f_stack = fmap<IValue>(tensors_in); f_interpreter.run(f_stack); Stack df_stack; df_stack.insert( df_stack.end(), tensor_grads_in.begin(), tensor_grads_in.end()); for (auto offset : grad_spec.df_input_captured_inputs) df_stack.push_back(tensors_in[offset]); for (auto offset : grad_spec.df_input_captured_outputs) df_stack.push_back(f_stack[offset]); df_interpreter.run(df_stack); unpackReturnTuple(df_stack); // Outputs of f needs to be sliced f_stack.erase(f_stack.begin() + grad_spec.f_real_outputs, f_stack.end()); return std::make_pair(as_tensorlist(f_stack), as_tensorlist(df_stack)); } std::shared_ptr<Graph> build_lstm() { const auto graph_string = R"IR( graph(%0 : Tensor, %1 : Tensor, %2 : Tensor, %3 : Tensor, %4 : Tensor): %5 : Tensor = aten::mm(%0, %3) %6 : Tensor = aten::mm(%1, %4) %7 : int = prim::Constant[value=1]() %8 : Tensor = aten::add(%5, %6, %7) %9 : Tensor, %10 : Tensor, %11 : Tensor, %12 : Tensor = prim::ConstantChunk[chunks=4, dim=1](%8) %13 : Tensor = aten::sigmoid(%9) %14 : Tensor = aten::sigmoid(%12) %15 : Tensor = aten::tanh(%11) %16 : Tensor = aten::sigmoid(%10) %17 : Tensor = aten::mul(%16, %2) %18 : Tensor = aten::mul(%13, %15) %19 : int = prim::Constant[value=1]() %20 : Tensor = aten::add(%17, %18, %19) %21 : Tensor = aten::tanh(%20) %22 : Tensor = aten::mul(%14, %21) return (%22, %20))IR"; auto g = std::make_shared<Graph>(); torch::jit::parseIR(graph_string, g.get()); g->lint(); return g; } std::shared_ptr<Graph> build_mobile_export_analysis_graph() { // We use following two schemas for this graph: // 1. slice.Tensor(Tensor(a) self, int dim=0, int? start=None, // int? end=None, int step=1) -> Tensor(a) // 2. slice.str(str string, int? start=None, int? end=None, // int step=1) -> str // %3 and %4 use slice.Tensor while %5 use slice.str. // Since we can see %3 and %4 have the same last argument that is never used // (same as default value of schema), we know we can ignore that last arg. For // %5, we see that last three args are same as schema default, hence // unnecessary. const auto graph_string = R"IR( graph(%0 : Tensor): %1 : int = prim::Constant[value=1]() %2 : int = prim::Constant[value=2]() %20 : int = prim::Constant[value=0]() %21 : int = prim::Constant[value=9223372036854775807]() %22 : str = prim::Constant[value="value"]() %3 : Tensor = aten::slice(%0, %1, %20, %2, %1) %4 : Tensor = aten::slice(%0, %2, %20, %21, %1) %5 : str = aten::slice(%22, %20, %21, %2) return (%3, %4, %5))IR"; auto g = std::make_shared<Graph>(); torch::jit::parseIR(graph_string, g.get()); g->lint(); return g; } std::shared_ptr<Graph> build_mobile_export_with_out() { const auto graph_string = R"IR( graph(%x.1 : Tensor, %y.1 : Tensor): %8 : NoneType = prim::Constant() %6 : int = prim::Constant[value=1]() %7 : Tensor = aten::add(%x.1, %y.1, %6, %y.1) return (%8))IR"; auto g = std::make_shared<Graph>(); torch::jit::parseIR(graph_string, g.get()); g->lint(); return g; } std::shared_ptr<Graph> build_mobile_export_analysis_graph_nested() { // this is pretty much same test as build_mobile_export_analysis_graph(), // but some aten::slice operators are hidden under block statement to check // if we are correctly recursing all the nodes in graph. const auto graph_string = R"IR( graph(%0 : Tensor): %1 : int = prim::Constant[value=1]() %2 : int = prim::Constant[value=2]() %20 : int = prim::Constant[value=0]() %21 : int = prim::Constant[value=9223372036854775807]() %22 : str = prim::Constant[value="value"]() %3 : Tensor = aten::slice(%0, %1, %20, %2, %1) %23 : bool = aten::Bool(%3) %c : Tensor = prim::If(%23) block0(): %4 : Tensor = aten::slice(%0, %2, %20, %21, %1) %5 : str = aten::slice(%22, %20, %21, %2) %c.1 : Tensor = aten::slice(%0, %1, %20, %2, %1) -> (%c.1) block1(): -> (%3) return (%3, %3))IR"; auto g = std::make_shared<Graph>(); torch::jit::parseIR(graph_string, g.get()); g->lint(); return g; } std::shared_ptr<Graph> build_mobile_export_analysis_graph_with_vararg() { const auto graph_string = R"IR( graph(%0 : Tensor): %1 : int = prim::Constant[value=1]() %2 : int = prim::Constant[value=2]() %3 : int = prim::Constant[value=3]() %4 : int[] = prim::tolist(%1, %2) %5 : int[] = prim::tolist(%1, %2, %3) return (%4, %5))IR"; auto g = std::make_shared<Graph>(); torch::jit::parseIR(graph_string, g.get()); g->lint(); return g; } std::shared_ptr<Graph> build_mobile_export_analysis_graph_non_const() { const auto graph_string = R"IR( graph(%input.1 : Tensor): %7 : int = prim::Constant[value=1]() # <string>:3:58 %9 : int = prim::Constant[value=0]() # <string>:3:66 %8 : int[] = prim::ListConstruct(%7, %7) %10 : int[] = prim::ListConstruct(%9, %9) %11 : int[] = prim::ListConstruct(%7, %7) %12 : Tensor = aten::conv2d(%input.1, %input.1, %input.1, %8, %10, %11, %7) return (%12))IR"; auto g = std::make_shared<Graph>(); torch::jit::parseIR(graph_string, g.get()); g->lint(); return g; } at::Tensor t_use(at::Tensor x) { return x; } at::Tensor t_def(at::Tensor x) { return x.t(); } bool checkRtol(const at::Tensor& diff, const std::vector<at::Tensor> inputs) { double maxValue = 0.0; for (auto& tensor : inputs) { maxValue = fmax(tensor.abs().max().item<float>(), maxValue); } return diff.abs().max().item<float>() < 2e-6 * maxValue; } bool almostEqual(const at::Tensor& a, const at::Tensor& b) { return checkRtol(a - b, {a, b}); } bool exactlyEqual(const at::Tensor& a, const at::Tensor& b) { return (a - b).abs().max().item<float>() == 0.f; } bool exactlyEqual( const std::vector<at::Tensor>& a, const std::vector<at::Tensor>& b) { if (a.size() != b.size()) { return false; } for (size_t i = 0; i < a.size(); ++i) { if (!exactlyEqual(a[i], b[i])) { return false; } } return true; } std::pair<at::Tensor, at::Tensor> lstm( at::Tensor input, at::Tensor hx, at::Tensor cx, at::Tensor w_ih, at::Tensor w_hh) { auto gates = input.mm(t_use(w_ih)) + hx.mm(t_use(w_hh)); auto chunked_gates = gates.chunk(4, 1); auto ingate = chunked_gates[0]; auto forgetgate = chunked_gates[1]; auto cellgate = chunked_gates[2]; auto outgate = chunked_gates[3]; ingate = ingate.sigmoid(); outgate = outgate.sigmoid(); cellgate = cellgate.tanh(); forgetgate = forgetgate.sigmoid(); auto cy = (forgetgate * cx) + (ingate * cellgate); auto hy = outgate * cy.tanh(); return {hy, cy}; } inline c10::AliasAnalysisKind aliasAnalysisFromSchema() { return c10::AliasAnalysisKind::FROM_SCHEMA; } namespace { RegisterOperators reg({ // This operator is intended to be used in JIT analysis and transformation // pass unit tests in which Values with type Tensor are often required. It // should not be used in situations in which the graph is actually executed // because it always produces empty Tensors. Operator( "prim::MakeTestTensor() -> Tensor", [](Stack& stack) { push(stack, at::Tensor()); }, aliasAnalysisFromSchema()), }); } // namespace std::vector<at::Tensor> runGraph( std::shared_ptr<Graph> graph, const std::vector<at::Tensor>& inputs) { std::vector<IValue> stack = fmap<IValue>(inputs); Code code(graph, "test"); InterpreterState(code).run(stack); TORCH_INTERNAL_ASSERT(!stack.empty()); // Graph outputs that are handled below: // * A list of Tensors. // * 1 Tensor. if (stack.front().isTensorList()) { return stack.front().toTensorVector(); } TORCH_INTERNAL_ASSERT(stack.front().isTensor()); return {stack.front().toTensor()}; } } // namespace jit } // namespace torch
32.173333
102
0.611169
[ "vector" ]
8da614f47cc2c487f58ac59f7afd8a4183032dc8
111,187
cpp
C++
Source/bindings/v8/SerializedScriptValue.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Source/bindings/v8/SerializedScriptValue.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
Source/bindings/v8/SerializedScriptValue.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
/* * Copyright (C) 2010 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 "config.h" #include "bindings/v8/SerializedScriptValue.h" #include "bindings/core/v8/V8Blob.h" #include "bindings/core/v8/V8File.h" #include "bindings/core/v8/V8FileList.h" #include "bindings/core/v8/V8ImageData.h" #include "bindings/core/v8/V8MessagePort.h" #include "bindings/modules/v8/V8DOMFileSystem.h" #include "bindings/modules/v8/V8Key.h" #include "bindings/v8/ExceptionState.h" #include "bindings/v8/V8Binding.h" #include "bindings/v8/WorkerScriptController.h" #include "bindings/v8/custom/V8ArrayBufferCustom.h" #include "bindings/v8/custom/V8ArrayBufferViewCustom.h" #include "bindings/v8/custom/V8DataViewCustom.h" #include "bindings/v8/custom/V8Float32ArrayCustom.h" #include "bindings/v8/custom/V8Float64ArrayCustom.h" #include "bindings/v8/custom/V8Int16ArrayCustom.h" #include "bindings/v8/custom/V8Int32ArrayCustom.h" #include "bindings/v8/custom/V8Int8ArrayCustom.h" #include "bindings/v8/custom/V8Uint16ArrayCustom.h" #include "bindings/v8/custom/V8Uint32ArrayCustom.h" #include "bindings/v8/custom/V8Uint8ArrayCustom.h" #include "bindings/v8/custom/V8Uint8ClampedArrayCustom.h" #include "core/dom/ExceptionCode.h" #include "core/dom/MessagePort.h" #include "core/fileapi/Blob.h" #include "core/fileapi/File.h" #include "core/fileapi/FileList.h" #include "core/html/ImageData.h" #include "core/html/canvas/DataView.h" #include "platform/SharedBuffer.h" #include "platform/heap/Handle.h" #include "public/platform/Platform.h" #include "public/platform/WebBlobInfo.h" #include "public/platform/WebCrypto.h" #include "public/platform/WebCryptoKey.h" #include "public/platform/WebCryptoKeyAlgorithm.h" #include "wtf/ArrayBuffer.h" #include "wtf/ArrayBufferContents.h" #include "wtf/ArrayBufferView.h" #include "wtf/Assertions.h" #include "wtf/ByteOrder.h" #include "wtf/Float32Array.h" #include "wtf/Float64Array.h" #include "wtf/Int16Array.h" #include "wtf/Int32Array.h" #include "wtf/Int8Array.h" #include "wtf/RefCounted.h" #include "wtf/Uint16Array.h" #include "wtf/Uint32Array.h" #include "wtf/Uint8Array.h" #include "wtf/Uint8ClampedArray.h" #include "wtf/Vector.h" #include "wtf/text/StringBuffer.h" #include "wtf/text/StringUTF8Adaptor.h" // FIXME: consider crashing in debug mode on deserialization errors // NOTE: be sure to change wireFormatVersion as necessary! namespace WebCore { namespace { // This code implements the HTML5 Structured Clone algorithm: // http://www.whatwg.org/specs/web-apps/current-work/multipage/urls.html#safe-passing-of-structured-data // V8ObjectMap is a map from V8 objects to arbitrary values of type T. // V8 objects (or handles to V8 objects) cannot be used as keys in ordinary wtf::HashMaps; // this class should be used instead. GCObject must be a subtype of v8::Object. // Suggested usage: // V8ObjectMap<v8::Object, int> map; // v8::Handle<v8::Object> obj = ...; // map.set(obj, 42); template<typename GCObject, typename T> class V8ObjectMap { public: bool contains(const v8::Handle<GCObject>& handle) { return m_map.contains(*handle); } bool tryGet(const v8::Handle<GCObject>& handle, T* valueOut) { typename HandleToT::iterator result = m_map.find(*handle); if (result != m_map.end()) { *valueOut = result->value; return true; } return false; } void set(const v8::Handle<GCObject>& handle, const T& value) { m_map.set(*handle, value); } private: // This implementation uses GetIdentityHash(), which sets a hidden property on the object containing // a random integer (or returns the one that had been previously set). This ensures that the table // never needs to be rebuilt across garbage collections at the expense of doing additional allocation // and making more round trips into V8. Note that since GetIdentityHash() is defined only on // v8::Objects, this V8ObjectMap cannot be used to map v8::Strings to T (because the public V8 API // considers a v8::String to be a v8::Primitive). // If V8 exposes a way to get at the address of the object held by a handle, then we can produce // an alternate implementation that does not need to do any V8-side allocation; however, it will // need to rehash after every garbage collection because a key object may have been moved. template<typename G> struct V8HandlePtrHash { static v8::Handle<G> unsafeHandleFromRawValue(const G* value) { const v8::Handle<G>* handle = reinterpret_cast<const v8::Handle<G>*>(&value); return *handle; } static unsigned hash(const G* key) { return static_cast<unsigned>(unsafeHandleFromRawValue(key)->GetIdentityHash()); } static bool equal(const G* a, const G* b) { return unsafeHandleFromRawValue(a) == unsafeHandleFromRawValue(b); } // For HashArg. static const bool safeToCompareToEmptyOrDeleted = false; }; typedef WTF::HashMap<GCObject*, T, V8HandlePtrHash<GCObject> > HandleToT; HandleToT m_map; }; typedef UChar BufferValueType; // Serialization format is a sequence of tags followed by zero or more data arguments. // Tags always take exactly one byte. A serialized stream first begins with // a complete VersionTag. If the stream does not begin with a VersionTag, we assume that // the stream is in format 0. // This format is private to the implementation of SerializedScriptValue. Do not rely on it // externally. It is safe to persist a SerializedScriptValue as a binary blob, but this // code should always be used to interpret it. // WebCoreStrings are read as (length:uint32_t, string:UTF8[length]). // RawStrings are read as (length:uint32_t, string:UTF8[length]). // RawUCharStrings are read as (length:uint32_t, string:UChar[length/sizeof(UChar)]). // RawFiles are read as (path:WebCoreString, url:WebCoreStrng, type:WebCoreString). // There is a reference table that maps object references (uint32_t) to v8::Values. // Tokens marked with (ref) are inserted into the reference table and given the next object reference ID after decoding. // All tags except InvalidTag, PaddingTag, ReferenceCountTag, VersionTag, GenerateFreshObjectTag // and GenerateFreshArrayTag push their results to the deserialization stack. // There is also an 'open' stack that is used to resolve circular references. Objects or arrays may // contain self-references. Before we begin to deserialize the contents of these values, they // are first given object reference IDs (by GenerateFreshObjectTag/GenerateFreshArrayTag); // these reference IDs are then used with ObjectReferenceTag to tie the recursive knot. enum SerializationTag { InvalidTag = '!', // Causes deserialization to fail. PaddingTag = '\0', // Is ignored (but consumed). UndefinedTag = '_', // -> <undefined> NullTag = '0', // -> <null> TrueTag = 'T', // -> <true> FalseTag = 'F', // -> <false> StringTag = 'S', // string:RawString -> string StringUCharTag = 'c', // string:RawUCharString -> string Int32Tag = 'I', // value:ZigZag-encoded int32 -> Integer Uint32Tag = 'U', // value:uint32_t -> Integer DateTag = 'D', // value:double -> Date (ref) MessagePortTag = 'M', // index:int -> MessagePort. Fills the result with transferred MessagePort. NumberTag = 'N', // value:double -> Number BlobTag = 'b', // uuid:WebCoreString, type:WebCoreString, size:uint64_t -> Blob (ref) BlobIndexTag = 'i', // index:int32_t -> Blob (ref) FileTag = 'f', // file:RawFile -> File (ref) FileIndexTag = 'e', // index:int32_t -> File (ref) DOMFileSystemTag = 'd', // type:int32_t, name:WebCoreString, uuid:WebCoreString -> FileSystem (ref) FileListTag = 'l', // length:uint32_t, files:RawFile[length] -> FileList (ref) FileListIndexTag = 'L', // length:uint32_t, files:int32_t[length] -> FileList (ref) ImageDataTag = '#', // width:uint32_t, height:uint32_t, pixelDataLength:uint32_t, data:byte[pixelDataLength] -> ImageData (ref) ObjectTag = '{', // numProperties:uint32_t -> pops the last object from the open stack; // fills it with the last numProperties name,value pairs pushed onto the deserialization stack SparseArrayTag = '@', // numProperties:uint32_t, length:uint32_t -> pops the last object from the open stack; // fills it with the last numProperties name,value pairs pushed onto the deserialization stack DenseArrayTag = '$', // numProperties:uint32_t, length:uint32_t -> pops the last object from the open stack; // fills it with the last length elements and numProperties name,value pairs pushed onto deserialization stack RegExpTag = 'R', // pattern:RawString, flags:uint32_t -> RegExp (ref) ArrayBufferTag = 'B', // byteLength:uint32_t, data:byte[byteLength] -> ArrayBuffer (ref) ArrayBufferTransferTag = 't', // index:uint32_t -> ArrayBuffer. For ArrayBuffer transfer ArrayBufferViewTag = 'V', // subtag:byte, byteOffset:uint32_t, byteLength:uint32_t -> ArrayBufferView (ref). Consumes an ArrayBuffer from the top of the deserialization stack. CryptoKeyTag = 'K', // subtag:byte, props, usages:uint32_t, keyDataLength:uint32_t, keyData:byte[keyDataLength] // If subtag=AesKeyTag: // props = keyLengthBytes:uint32_t, algorithmId:uint32_t // If subtag=HmacKeyTag: // props = keyLengthBytes:uint32_t, hashId:uint32_t // If subtag=RsaHashedKeyTag: // props = algorithmId:uint32_t, type:uint32_t, modulusLengthBits:uint32_t, publicExponentLength:uint32_t, publicExponent:byte[publicExponentLength], hashId:uint32_t ObjectReferenceTag = '^', // ref:uint32_t -> reference table[ref] GenerateFreshObjectTag = 'o', // -> empty object allocated an object ID and pushed onto the open stack (ref) GenerateFreshSparseArrayTag = 'a', // length:uint32_t -> empty array[length] allocated an object ID and pushed onto the open stack (ref) GenerateFreshDenseArrayTag = 'A', // length:uint32_t -> empty array[length] allocated an object ID and pushed onto the open stack (ref) ReferenceCountTag = '?', // refTableSize:uint32_t -> If the reference table is not refTableSize big, fails. StringObjectTag = 's', // string:RawString -> new String(string) (ref) NumberObjectTag = 'n', // value:double -> new Number(value) (ref) TrueObjectTag = 'y', // new Boolean(true) (ref) FalseObjectTag = 'x', // new Boolean(false) (ref) VersionTag = 0xFF // version:uint32_t -> Uses this as the file version. }; enum ArrayBufferViewSubTag { ByteArrayTag = 'b', UnsignedByteArrayTag = 'B', UnsignedByteClampedArrayTag = 'C', ShortArrayTag = 'w', UnsignedShortArrayTag = 'W', IntArrayTag = 'd', UnsignedIntArrayTag = 'D', FloatArrayTag = 'f', DoubleArrayTag = 'F', DataViewTag = '?' }; enum CryptoKeySubTag { AesKeyTag = 1, HmacKeyTag = 2, // ID 3 was used by RsaKeyTag, while still behind experimental flag. RsaHashedKeyTag = 4, // Maximum allowed value is 255 }; enum AssymetricCryptoKeyType { PublicKeyType = 1, PrivateKeyType = 2, // Maximum allowed value is 2^32-1 }; enum CryptoKeyAlgorithmTag { AesCbcTag = 1, HmacTag = 2, RsaSsaPkcs1v1_5Tag = 3, // ID 4 was used by RsaEs, while still behind experimental flag. Sha1Tag = 5, Sha256Tag = 6, Sha384Tag = 7, Sha512Tag = 8, AesGcmTag = 9, RsaOaepTag = 10, AesCtrTag = 11, AesKwTag = 12, // Maximum allowed value is 2^32-1 }; enum CryptoKeyUsage { // Extractability is not a "usage" in the WebCryptoKeyUsages sense, however // it fits conveniently into this bitfield. ExtractableUsage = 1 << 0, EncryptUsage = 1 << 1, DecryptUsage = 1 << 2, SignUsage = 1 << 3, VerifyUsage = 1 << 4, DeriveKeyUsage = 1 << 5, WrapKeyUsage = 1 << 6, UnwrapKeyUsage = 1 << 7, DeriveBitsUsage = 1 << 8, // Maximum allowed value is 1 << 31 }; static bool shouldCheckForCycles(int depth) { ASSERT(depth >= 0); // Since we are not required to spot the cycle as soon as it // happens we can check for cycles only when the current depth // is a power of two. return !(depth & (depth - 1)); } static const int maxDepth = 20000; // VarInt encoding constants. static const int varIntShift = 7; static const int varIntMask = (1 << varIntShift) - 1; // ZigZag encoding helps VarInt encoding stay small for negative // numbers with small absolute values. class ZigZag { public: static uint32_t encode(uint32_t value) { if (value & (1U << 31)) value = ((~value) << 1) + 1; else value <<= 1; return value; } static uint32_t decode(uint32_t value) { if (value & 1) value = ~(value >> 1); else value >>= 1; return value; } private: ZigZag(); }; // Writer is responsible for serializing primitive types and storing // information used to reconstruct composite types. class Writer { WTF_MAKE_NONCOPYABLE(Writer); public: Writer() : m_position(0) { } // Write functions for primitive types. void writeUndefined() { append(UndefinedTag); } void writeNull() { append(NullTag); } void writeTrue() { append(TrueTag); } void writeFalse() { append(FalseTag); } void writeBooleanObject(bool value) { append(value ? TrueObjectTag : FalseObjectTag); } void writeOneByteString(v8::Handle<v8::String>& string) { int stringLength = string->Length(); int utf8Length = string->Utf8Length(); ASSERT(stringLength >= 0 && utf8Length >= 0); append(StringTag); doWriteUint32(static_cast<uint32_t>(utf8Length)); ensureSpace(utf8Length); // ASCII fast path. if (stringLength == utf8Length) string->WriteOneByte(byteAt(m_position), 0, utf8Length, v8StringWriteOptions()); else { char* buffer = reinterpret_cast<char*>(byteAt(m_position)); string->WriteUtf8(buffer, utf8Length, 0, v8StringWriteOptions()); } m_position += utf8Length; } void writeUCharString(v8::Handle<v8::String>& string) { int length = string->Length(); ASSERT(length >= 0); int size = length * sizeof(UChar); int bytes = bytesNeededToWireEncode(static_cast<uint32_t>(size)); if ((m_position + 1 + bytes) & 1) append(PaddingTag); append(StringUCharTag); doWriteUint32(static_cast<uint32_t>(size)); ensureSpace(size); ASSERT(!(m_position & 1)); uint16_t* buffer = reinterpret_cast<uint16_t*>(byteAt(m_position)); string->Write(buffer, 0, length, v8StringWriteOptions()); m_position += size; } void writeStringObject(const char* data, int length) { ASSERT(length >= 0); append(StringObjectTag); doWriteString(data, length); } void writeWebCoreString(const String& string) { // Uses UTF8 encoding so we can read it back as either V8 or // WebCore string. append(StringTag); doWriteWebCoreString(string); } void writeVersion() { append(VersionTag); doWriteUint32(SerializedScriptValue::wireFormatVersion); } void writeInt32(int32_t value) { append(Int32Tag); doWriteUint32(ZigZag::encode(static_cast<uint32_t>(value))); } void writeUint32(uint32_t value) { append(Uint32Tag); doWriteUint32(value); } void writeDate(double numberValue) { append(DateTag); doWriteNumber(numberValue); } void writeNumber(double number) { append(NumberTag); doWriteNumber(number); } void writeNumberObject(double number) { append(NumberObjectTag); doWriteNumber(number); } void writeBlob(const String& uuid, const String& type, unsigned long long size) { append(BlobTag); doWriteWebCoreString(uuid); doWriteWebCoreString(type); doWriteUint64(size); } void writeBlobIndex(int blobIndex) { ASSERT(blobIndex >= 0); append(BlobIndexTag); doWriteUint32(blobIndex); } void writeDOMFileSystem(int type, const String& name, const String& url) { append(DOMFileSystemTag); doWriteUint32(type); doWriteWebCoreString(name); doWriteWebCoreString(url); } void writeFile(const File& file) { append(FileTag); doWriteFile(file); } void writeFileIndex(int blobIndex) { append(FileIndexTag); doWriteUint32(blobIndex); } void writeFileList(const FileList& fileList) { append(FileListTag); uint32_t length = fileList.length(); doWriteUint32(length); for (unsigned i = 0; i < length; ++i) doWriteFile(*fileList.item(i)); } void writeFileListIndex(const Vector<int>& blobIndices) { append(FileListIndexTag); uint32_t length = blobIndices.size(); doWriteUint32(length); for (unsigned i = 0; i < length; ++i) doWriteUint32(blobIndices[i]); } bool writeCryptoKey(const blink::WebCryptoKey& key) { append(static_cast<uint8_t>(CryptoKeyTag)); switch (key.algorithm().paramsType()) { case blink::WebCryptoKeyAlgorithmParamsTypeAes: doWriteAesKey(key); break; case blink::WebCryptoKeyAlgorithmParamsTypeHmac: doWriteHmacKey(key); break; case blink::WebCryptoKeyAlgorithmParamsTypeRsaHashed: doWriteRsaHashedKey(key); break; case blink::WebCryptoKeyAlgorithmParamsTypeNone: ASSERT_NOT_REACHED(); return false; } doWriteKeyUsages(key.usages(), key.extractable()); blink::WebVector<uint8_t> keyData; if (!blink::Platform::current()->crypto()->serializeKeyForClone(key, keyData)) return false; doWriteUint32(keyData.size()); append(keyData.data(), keyData.size()); return true; } void writeArrayBuffer(const ArrayBuffer& arrayBuffer) { append(ArrayBufferTag); doWriteArrayBuffer(arrayBuffer); } void writeArrayBufferView(const ArrayBufferView& arrayBufferView) { append(ArrayBufferViewTag); #ifndef NDEBUG const ArrayBuffer& arrayBuffer = *arrayBufferView.buffer(); ASSERT(static_cast<const uint8_t*>(arrayBuffer.data()) + arrayBufferView.byteOffset() == static_cast<const uint8_t*>(arrayBufferView.baseAddress())); #endif ArrayBufferView::ViewType type = arrayBufferView.type(); if (type == ArrayBufferView::TypeInt8) append(ByteArrayTag); else if (type == ArrayBufferView::TypeUint8Clamped) append(UnsignedByteClampedArrayTag); else if (type == ArrayBufferView::TypeUint8) append(UnsignedByteArrayTag); else if (type == ArrayBufferView::TypeInt16) append(ShortArrayTag); else if (type == ArrayBufferView::TypeUint16) append(UnsignedShortArrayTag); else if (type == ArrayBufferView::TypeInt32) append(IntArrayTag); else if (type == ArrayBufferView::TypeUint32) append(UnsignedIntArrayTag); else if (type == ArrayBufferView::TypeFloat32) append(FloatArrayTag); else if (type == ArrayBufferView::TypeFloat64) append(DoubleArrayTag); else if (type == ArrayBufferView::TypeDataView) append(DataViewTag); else ASSERT_NOT_REACHED(); doWriteUint32(arrayBufferView.byteOffset()); doWriteUint32(arrayBufferView.byteLength()); } void writeImageData(uint32_t width, uint32_t height, const uint8_t* pixelData, uint32_t pixelDataLength) { append(ImageDataTag); doWriteUint32(width); doWriteUint32(height); doWriteUint32(pixelDataLength); append(pixelData, pixelDataLength); } void writeRegExp(v8::Local<v8::String> pattern, v8::RegExp::Flags flags) { append(RegExpTag); v8::String::Utf8Value patternUtf8Value(pattern); doWriteString(*patternUtf8Value, patternUtf8Value.length()); doWriteUint32(static_cast<uint32_t>(flags)); } void writeTransferredMessagePort(uint32_t index) { append(MessagePortTag); doWriteUint32(index); } void writeTransferredArrayBuffer(uint32_t index) { append(ArrayBufferTransferTag); doWriteUint32(index); } void writeObjectReference(uint32_t reference) { append(ObjectReferenceTag); doWriteUint32(reference); } void writeObject(uint32_t numProperties) { append(ObjectTag); doWriteUint32(numProperties); } void writeSparseArray(uint32_t numProperties, uint32_t length) { append(SparseArrayTag); doWriteUint32(numProperties); doWriteUint32(length); } void writeDenseArray(uint32_t numProperties, uint32_t length) { append(DenseArrayTag); doWriteUint32(numProperties); doWriteUint32(length); } String takeWireString() { COMPILE_ASSERT(sizeof(BufferValueType) == 2, BufferValueTypeIsTwoBytes); fillHole(); String data = String(m_buffer.data(), m_buffer.size()); data.impl()->truncateAssumingIsolated((m_position + 1) / sizeof(BufferValueType)); return data; } void writeReferenceCount(uint32_t numberOfReferences) { append(ReferenceCountTag); doWriteUint32(numberOfReferences); } void writeGenerateFreshObject() { append(GenerateFreshObjectTag); } void writeGenerateFreshSparseArray(uint32_t length) { append(GenerateFreshSparseArrayTag); doWriteUint32(length); } void writeGenerateFreshDenseArray(uint32_t length) { append(GenerateFreshDenseArrayTag); doWriteUint32(length); } private: void doWriteFile(const File& file) { doWriteWebCoreString(file.hasBackingFile() ? file.path() : ""); doWriteWebCoreString(file.name()); doWriteWebCoreString(file.webkitRelativePath()); doWriteWebCoreString(file.uuid()); doWriteWebCoreString(file.type()); // FIXME don't use 4 bytes to encode a flag. if (file.hasValidSnapshotMetadata()) { doWriteUint32(static_cast<uint8_t>(1)); long long size; double lastModified; file.captureSnapshot(size, lastModified); doWriteUint64(static_cast<uint64_t>(size)); doWriteNumber(lastModified); } else { append(static_cast<uint8_t>(0)); } } void doWriteArrayBuffer(const ArrayBuffer& arrayBuffer) { uint32_t byteLength = arrayBuffer.byteLength(); doWriteUint32(byteLength); append(static_cast<const uint8_t*>(arrayBuffer.data()), byteLength); } void doWriteString(const char* data, int length) { doWriteUint32(static_cast<uint32_t>(length)); append(reinterpret_cast<const uint8_t*>(data), length); } void doWriteWebCoreString(const String& string) { StringUTF8Adaptor stringUTF8(string); doWriteString(stringUTF8.data(), stringUTF8.length()); } void doWriteHmacKey(const blink::WebCryptoKey& key) { ASSERT(key.algorithm().paramsType() == blink::WebCryptoKeyAlgorithmParamsTypeHmac); append(static_cast<uint8_t>(HmacKeyTag)); ASSERT(!(key.algorithm().hmacParams()->lengthBits() % 8)); doWriteUint32(key.algorithm().hmacParams()->lengthBits() / 8); doWriteAlgorithmId(key.algorithm().hmacParams()->hash().id()); } void doWriteAesKey(const blink::WebCryptoKey& key) { ASSERT(key.algorithm().paramsType() == blink::WebCryptoKeyAlgorithmParamsTypeAes); append(static_cast<uint8_t>(AesKeyTag)); doWriteAlgorithmId(key.algorithm().id()); // Converting the key length from bits to bytes is lossless and makes // it fit in 1 byte. ASSERT(!(key.algorithm().aesParams()->lengthBits() % 8)); doWriteUint32(key.algorithm().aesParams()->lengthBits() / 8); } void doWriteRsaHashedKey(const blink::WebCryptoKey& key) { ASSERT(key.algorithm().rsaHashedParams()); append(static_cast<uint8_t>(RsaHashedKeyTag)); doWriteAlgorithmId(key.algorithm().id()); switch (key.type()) { case blink::WebCryptoKeyTypePublic: doWriteUint32(PublicKeyType); break; case blink::WebCryptoKeyTypePrivate: doWriteUint32(PrivateKeyType); break; case blink::WebCryptoKeyTypeSecret: ASSERT_NOT_REACHED(); } const blink::WebCryptoRsaHashedKeyAlgorithmParams* params = key.algorithm().rsaHashedParams(); doWriteUint32(params->modulusLengthBits()); doWriteUint32(params->publicExponent().size()); append(params->publicExponent().data(), params->publicExponent().size()); doWriteAlgorithmId(key.algorithm().rsaHashedParams()->hash().id()); } void doWriteAlgorithmId(blink::WebCryptoAlgorithmId id) { switch (id) { case blink::WebCryptoAlgorithmIdAesCbc: return doWriteUint32(AesCbcTag); case blink::WebCryptoAlgorithmIdHmac: return doWriteUint32(HmacTag); case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5: return doWriteUint32(RsaSsaPkcs1v1_5Tag); case blink::WebCryptoAlgorithmIdSha1: return doWriteUint32(Sha1Tag); case blink::WebCryptoAlgorithmIdSha256: return doWriteUint32(Sha256Tag); case blink::WebCryptoAlgorithmIdSha384: return doWriteUint32(Sha384Tag); case blink::WebCryptoAlgorithmIdSha512: return doWriteUint32(Sha512Tag); case blink::WebCryptoAlgorithmIdAesGcm: return doWriteUint32(AesGcmTag); case blink::WebCryptoAlgorithmIdRsaOaep: return doWriteUint32(RsaOaepTag); case blink::WebCryptoAlgorithmIdAesCtr: return doWriteUint32(AesCtrTag); case blink::WebCryptoAlgorithmIdAesKw: return doWriteUint32(AesKwTag); } ASSERT_NOT_REACHED(); } void doWriteKeyUsages(const blink::WebCryptoKeyUsageMask usages, bool extractable) { // Reminder to update this when adding new key usages. COMPILE_ASSERT(blink::EndOfWebCryptoKeyUsage == (1 << 7) + 1, UpdateMe); uint32_t value = 0; if (extractable) value |= ExtractableUsage; if (usages & blink::WebCryptoKeyUsageEncrypt) value |= EncryptUsage; if (usages & blink::WebCryptoKeyUsageDecrypt) value |= DecryptUsage; if (usages & blink::WebCryptoKeyUsageSign) value |= SignUsage; if (usages & blink::WebCryptoKeyUsageVerify) value |= VerifyUsage; if (usages & blink::WebCryptoKeyUsageDeriveKey) value |= DeriveKeyUsage; if (usages & blink::WebCryptoKeyUsageWrapKey) value |= WrapKeyUsage; if (usages & blink::WebCryptoKeyUsageUnwrapKey) value |= UnwrapKeyUsage; if (usages & blink::WebCryptoKeyUsageDeriveBits) value |= DeriveBitsUsage; doWriteUint32(value); } int bytesNeededToWireEncode(uint32_t value) { int bytes = 1; while (true) { value >>= varIntShift; if (!value) break; ++bytes; } return bytes; } template<class T> void doWriteUintHelper(T value) { while (true) { uint8_t b = (value & varIntMask); value >>= varIntShift; if (!value) { append(b); break; } append(b | (1 << varIntShift)); } } void doWriteUint32(uint32_t value) { doWriteUintHelper(value); } void doWriteUint64(uint64_t value) { doWriteUintHelper(value); } void doWriteNumber(double number) { append(reinterpret_cast<uint8_t*>(&number), sizeof(number)); } void append(SerializationTag tag) { append(static_cast<uint8_t>(tag)); } void append(uint8_t b) { ensureSpace(1); *byteAt(m_position++) = b; } void append(const uint8_t* data, int length) { ensureSpace(length); memcpy(byteAt(m_position), data, length); m_position += length; } void ensureSpace(unsigned extra) { COMPILE_ASSERT(sizeof(BufferValueType) == 2, BufferValueTypeIsTwoBytes); m_buffer.resize((m_position + extra + 1) / sizeof(BufferValueType)); // "+ 1" to round up. } void fillHole() { COMPILE_ASSERT(sizeof(BufferValueType) == 2, BufferValueTypeIsTwoBytes); // If the writer is at odd position in the buffer, then one of // the bytes in the last UChar is not initialized. if (m_position % 2) *byteAt(m_position) = static_cast<uint8_t>(PaddingTag); } uint8_t* byteAt(int position) { return reinterpret_cast<uint8_t*>(m_buffer.data()) + position; } int v8StringWriteOptions() { return v8::String::NO_NULL_TERMINATION; } Vector<BufferValueType> m_buffer; unsigned m_position; }; static v8::Handle<v8::Object> toV8Object(MessagePort* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { if (!impl) return v8::Handle<v8::Object>(); v8::Handle<v8::Value> wrapper = toV8(impl, creationContext, isolate); ASSERT(wrapper->IsObject()); return wrapper.As<v8::Object>(); } static v8::Handle<v8::ArrayBuffer> toV8Object(ArrayBuffer* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { if (!impl) return v8::Handle<v8::ArrayBuffer>(); v8::Handle<v8::Value> wrapper = toV8(impl, creationContext, isolate); ASSERT(wrapper->IsArrayBuffer()); return wrapper.As<v8::ArrayBuffer>(); } class Serializer { class StateBase; public: enum Status { Success, InputError, DataCloneError, JSException }; Serializer(Writer& writer, MessagePortArray* messagePorts, ArrayBufferArray* arrayBuffers, WebBlobInfoArray* blobInfo, BlobDataHandleMap& blobDataHandles, v8::TryCatch& tryCatch, ScriptState* scriptState) : m_scriptState(scriptState) , m_writer(writer) , m_tryCatch(tryCatch) , m_depth(0) , m_status(Success) , m_nextObjectReference(0) , m_blobInfo(blobInfo) , m_blobDataHandles(blobDataHandles) { ASSERT(!tryCatch.HasCaught()); v8::Handle<v8::Object> creationContext = m_scriptState->context()->Global(); if (messagePorts) { for (size_t i = 0; i < messagePorts->size(); i++) m_transferredMessagePorts.set(toV8Object(messagePorts->at(i).get(), creationContext, isolate()), i); } if (arrayBuffers) { for (size_t i = 0; i < arrayBuffers->size(); i++) { v8::Handle<v8::Object> v8ArrayBuffer = toV8Object(arrayBuffers->at(i).get(), creationContext, isolate()); // Coalesce multiple occurences of the same buffer to the first index. if (!m_transferredArrayBuffers.contains(v8ArrayBuffer)) m_transferredArrayBuffers.set(v8ArrayBuffer, i); } } } v8::Isolate* isolate() { return m_scriptState->isolate(); } Status serialize(v8::Handle<v8::Value> value) { v8::HandleScope scope(isolate()); m_writer.writeVersion(); StateBase* state = doSerialize(value, 0); while (state) state = state->advance(*this); return m_status; } String errorMessage() { return m_errorMessage; } // Functions used by serialization states. StateBase* doSerialize(v8::Handle<v8::Value>, StateBase* next); StateBase* doSerializeArrayBuffer(v8::Handle<v8::Value> arrayBuffer, StateBase* next) { return doSerialize(arrayBuffer, next); } StateBase* checkException(StateBase* state) { return m_tryCatch.HasCaught() ? handleError(JSException, "", state) : 0; } StateBase* writeObject(uint32_t numProperties, StateBase* state) { m_writer.writeObject(numProperties); return pop(state); } StateBase* writeSparseArray(uint32_t numProperties, uint32_t length, StateBase* state) { m_writer.writeSparseArray(numProperties, length); return pop(state); } StateBase* writeDenseArray(uint32_t numProperties, uint32_t length, StateBase* state) { m_writer.writeDenseArray(numProperties, length); return pop(state); } private: class StateBase { WTF_MAKE_NONCOPYABLE(StateBase); public: virtual ~StateBase() { } // Link to the next state to form a stack. StateBase* nextState() { return m_next; } // Composite object we're processing in this state. v8::Handle<v8::Value> composite() { return m_composite; } // Serializes (a part of) the current composite and returns // the next state to process or null when this is the final // state. virtual StateBase* advance(Serializer&) = 0; protected: StateBase(v8::Handle<v8::Value> composite, StateBase* next) : m_composite(composite) , m_next(next) { } private: v8::Handle<v8::Value> m_composite; StateBase* m_next; }; // Dummy state that is used to signal serialization errors. class ErrorState FINAL : public StateBase { public: ErrorState() : StateBase(v8Undefined(), 0) { } virtual StateBase* advance(Serializer&) OVERRIDE { delete this; return 0; } }; template <typename T> class State : public StateBase { public: v8::Handle<T> composite() { return v8::Handle<T>::Cast(StateBase::composite()); } protected: State(v8::Handle<T> composite, StateBase* next) : StateBase(composite, next) { } }; class AbstractObjectState : public State<v8::Object> { public: AbstractObjectState(v8::Handle<v8::Object> object, StateBase* next) : State<v8::Object>(object, next) , m_index(0) , m_numSerializedProperties(0) , m_nameDone(false) { } protected: virtual StateBase* objectDone(unsigned numProperties, Serializer&) = 0; StateBase* serializeProperties(bool ignoreIndexed, Serializer& serializer) { while (m_index < m_propertyNames->Length()) { if (!m_nameDone) { v8::Local<v8::Value> propertyName = m_propertyNames->Get(m_index); if (StateBase* newState = serializer.checkException(this)) return newState; if (propertyName.IsEmpty()) return serializer.handleError(InputError, "Empty property names cannot be cloned.", this); bool hasStringProperty = propertyName->IsString() && composite()->HasRealNamedProperty(propertyName.As<v8::String>()); if (StateBase* newState = serializer.checkException(this)) return newState; bool hasIndexedProperty = !hasStringProperty && propertyName->IsUint32() && composite()->HasRealIndexedProperty(propertyName->Uint32Value()); if (StateBase* newState = serializer.checkException(this)) return newState; if (hasStringProperty || (hasIndexedProperty && !ignoreIndexed)) m_propertyName = propertyName; else { ++m_index; continue; } } ASSERT(!m_propertyName.IsEmpty()); if (!m_nameDone) { m_nameDone = true; if (StateBase* newState = serializer.doSerialize(m_propertyName, this)) return newState; } v8::Local<v8::Value> value = composite()->Get(m_propertyName); if (StateBase* newState = serializer.checkException(this)) return newState; m_nameDone = false; m_propertyName.Clear(); ++m_index; ++m_numSerializedProperties; // If we return early here, it's either because we have pushed a new state onto the // serialization state stack or because we have encountered an error (and in both cases // we are unwinding the native stack). if (StateBase* newState = serializer.doSerialize(value, this)) return newState; } return objectDone(m_numSerializedProperties, serializer); } v8::Local<v8::Array> m_propertyNames; private: v8::Local<v8::Value> m_propertyName; unsigned m_index; unsigned m_numSerializedProperties; bool m_nameDone; }; class ObjectState FINAL : public AbstractObjectState { public: ObjectState(v8::Handle<v8::Object> object, StateBase* next) : AbstractObjectState(object, next) { } virtual StateBase* advance(Serializer& serializer) OVERRIDE { if (m_propertyNames.IsEmpty()) { m_propertyNames = composite()->GetPropertyNames(); if (StateBase* newState = serializer.checkException(this)) return newState; if (m_propertyNames.IsEmpty()) return serializer.handleError(InputError, "Empty property names cannot be cloned.", nextState()); } return serializeProperties(false, serializer); } protected: virtual StateBase* objectDone(unsigned numProperties, Serializer& serializer) OVERRIDE { return serializer.writeObject(numProperties, this); } }; class DenseArrayState FINAL : public AbstractObjectState { public: DenseArrayState(v8::Handle<v8::Array> array, v8::Handle<v8::Array> propertyNames, StateBase* next, v8::Isolate* isolate) : AbstractObjectState(array, next) , m_arrayIndex(0) , m_arrayLength(array->Length()) { m_propertyNames = v8::Local<v8::Array>::New(isolate, propertyNames); } virtual StateBase* advance(Serializer& serializer) OVERRIDE { while (m_arrayIndex < m_arrayLength) { v8::Handle<v8::Value> value = composite().As<v8::Array>()->Get(m_arrayIndex); m_arrayIndex++; if (StateBase* newState = serializer.checkException(this)) return newState; if (StateBase* newState = serializer.doSerialize(value, this)) return newState; } return serializeProperties(true, serializer); } protected: virtual StateBase* objectDone(unsigned numProperties, Serializer& serializer) OVERRIDE { return serializer.writeDenseArray(numProperties, m_arrayLength, this); } private: uint32_t m_arrayIndex; uint32_t m_arrayLength; }; class SparseArrayState FINAL : public AbstractObjectState { public: SparseArrayState(v8::Handle<v8::Array> array, v8::Handle<v8::Array> propertyNames, StateBase* next, v8::Isolate* isolate) : AbstractObjectState(array, next) { m_propertyNames = v8::Local<v8::Array>::New(isolate, propertyNames); } virtual StateBase* advance(Serializer& serializer) OVERRIDE { return serializeProperties(false, serializer); } protected: virtual StateBase* objectDone(unsigned numProperties, Serializer& serializer) OVERRIDE { return serializer.writeSparseArray(numProperties, composite().As<v8::Array>()->Length(), this); } }; StateBase* push(StateBase* state) { ASSERT(state); ++m_depth; return checkComposite(state) ? state : handleError(InputError, "Value being cloned is either cyclic or too deeply nested.", state); } StateBase* pop(StateBase* state) { ASSERT(state); --m_depth; StateBase* next = state->nextState(); delete state; return next; } StateBase* handleError(Status errorStatus, const String& message, StateBase* state) { ASSERT(errorStatus != Success); m_status = errorStatus; m_errorMessage = message; while (state) { StateBase* tmp = state->nextState(); delete state; state = tmp; } return new ErrorState; } bool checkComposite(StateBase* top) { ASSERT(top); if (m_depth > maxDepth) return false; if (!shouldCheckForCycles(m_depth)) return true; v8::Handle<v8::Value> composite = top->composite(); for (StateBase* state = top->nextState(); state; state = state->nextState()) { if (state->composite() == composite) return false; } return true; } void writeString(v8::Handle<v8::Value> value) { v8::Handle<v8::String> string = value.As<v8::String>(); if (!string->Length() || string->IsOneByte()) m_writer.writeOneByteString(string); else m_writer.writeUCharString(string); } void writeStringObject(v8::Handle<v8::Value> value) { v8::Handle<v8::StringObject> stringObject = value.As<v8::StringObject>(); v8::String::Utf8Value stringValue(stringObject->ValueOf()); m_writer.writeStringObject(*stringValue, stringValue.length()); } void writeNumberObject(v8::Handle<v8::Value> value) { v8::Handle<v8::NumberObject> numberObject = value.As<v8::NumberObject>(); m_writer.writeNumberObject(numberObject->ValueOf()); } void writeBooleanObject(v8::Handle<v8::Value> value) { v8::Handle<v8::BooleanObject> booleanObject = value.As<v8::BooleanObject>(); m_writer.writeBooleanObject(booleanObject->ValueOf()); } StateBase* writeBlob(v8::Handle<v8::Value> value, StateBase* next) { Blob* blob = V8Blob::toNative(value.As<v8::Object>()); if (!blob) return 0; if (blob->hasBeenClosed()) return handleError(DataCloneError, "A Blob object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.set(blob->uuid(), blob->blobDataHandle()); if (appendBlobInfo(blob->uuid(), blob->type(), blob->size(), &blobIndex)) m_writer.writeBlobIndex(blobIndex); else m_writer.writeBlob(blob->uuid(), blob->type(), blob->size()); return 0; } StateBase* writeDOMFileSystem(v8::Handle<v8::Value> value, StateBase* next) { DOMFileSystem* fs = V8DOMFileSystem::toNative(value.As<v8::Object>()); if (!fs) return 0; if (!fs->clonable()) return handleError(DataCloneError, "A FileSystem object could not be cloned.", next); m_writer.writeDOMFileSystem(fs->type(), fs->name(), fs->rootURL().string()); return 0; } StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next) { File* file = V8File::toNative(value.As<v8::Object>()); if (!file) return 0; if (file->hasBeenClosed()) return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.set(file->uuid(), file->blobDataHandle()); if (appendFileInfo(file, &blobIndex)) { ASSERT(blobIndex >= 0); m_writer.writeFileIndex(blobIndex); } else { m_writer.writeFile(*file); } return 0; } StateBase* writeFileList(v8::Handle<v8::Value> value, StateBase* next) { FileList* fileList = V8FileList::toNative(value.As<v8::Object>()); if (!fileList) return 0; unsigned length = fileList->length(); Vector<int> blobIndices; for (unsigned i = 0; i < length; ++i) { int blobIndex = -1; const File* file = fileList->item(i); if (file->hasBeenClosed()) return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next); m_blobDataHandles.set(file->uuid(), file->blobDataHandle()); if (appendFileInfo(file, &blobIndex)) { ASSERT(!i || blobIndex > 0); ASSERT(blobIndex >= 0); blobIndices.append(blobIndex); } } if (!blobIndices.isEmpty()) m_writer.writeFileListIndex(blobIndices); else m_writer.writeFileList(*fileList); return 0; } bool writeCryptoKey(v8::Handle<v8::Value> value) { Key* key = V8Key::toNative(value.As<v8::Object>()); if (!key) return false; return m_writer.writeCryptoKey(key->key()); } void writeImageData(v8::Handle<v8::Value> value) { ImageData* imageData = V8ImageData::toNative(value.As<v8::Object>()); if (!imageData) return; Uint8ClampedArray* pixelArray = imageData->data(); m_writer.writeImageData(imageData->width(), imageData->height(), pixelArray->data(), pixelArray->length()); } void writeRegExp(v8::Handle<v8::Value> value) { v8::Handle<v8::RegExp> regExp = value.As<v8::RegExp>(); m_writer.writeRegExp(regExp->GetSource(), regExp->GetFlags()); } StateBase* writeAndGreyArrayBufferView(v8::Handle<v8::Object> object, StateBase* next) { ASSERT(!object.IsEmpty()); ArrayBufferView* arrayBufferView = V8ArrayBufferView::toNative(object); if (!arrayBufferView) return 0; if (!arrayBufferView->buffer()) return handleError(DataCloneError, "An ArrayBuffer could not be cloned.", next); v8::Handle<v8::Value> underlyingBuffer = toV8(arrayBufferView->buffer(), m_scriptState->context()->Global(), isolate()); if (underlyingBuffer.IsEmpty()) return handleError(DataCloneError, "An ArrayBuffer could not be cloned.", next); StateBase* stateOut = doSerializeArrayBuffer(underlyingBuffer, next); if (stateOut) return stateOut; m_writer.writeArrayBufferView(*arrayBufferView); // This should be safe: we serialize something that we know to be a wrapper (see // the toV8 call above), so the call to doSerializeArrayBuffer should neither // cause the system stack to overflow nor should it have potential to reach // this ArrayBufferView again. // // We do need to grey the underlying buffer before we grey its view, however; // ArrayBuffers may be shared, so they need to be given reference IDs, and an // ArrayBufferView cannot be constructed without a corresponding ArrayBuffer // (or without an additional tag that would allow us to do two-stage construction // like we do for Objects and Arrays). greyObject(object); return 0; } StateBase* writeArrayBuffer(v8::Handle<v8::Value> value, StateBase* next) { ArrayBuffer* arrayBuffer = V8ArrayBuffer::toNative(value.As<v8::Object>()); if (!arrayBuffer) return 0; if (arrayBuffer->isNeutered()) return handleError(DataCloneError, "An ArrayBuffer is neutered and could not be cloned.", next); ASSERT(!m_transferredArrayBuffers.contains(value.As<v8::Object>())); m_writer.writeArrayBuffer(*arrayBuffer); return 0; } StateBase* writeTransferredArrayBuffer(v8::Handle<v8::Value> value, uint32_t index, StateBase* next) { ArrayBuffer* arrayBuffer = V8ArrayBuffer::toNative(value.As<v8::Object>()); if (!arrayBuffer) return 0; if (arrayBuffer->isNeutered()) return handleError(DataCloneError, "An ArrayBuffer is neutered and could not be cloned.", next); m_writer.writeTransferredArrayBuffer(index); return 0; } static bool shouldSerializeDensely(uint32_t length, uint32_t propertyCount) { // Let K be the cost of serializing all property values that are there // Cost of serializing sparsely: 5*propertyCount + K (5 bytes per uint32_t key) // Cost of serializing densely: K + 1*(length - propertyCount) (1 byte for all properties that are not there) // so densely is better than sparsly whenever 6*propertyCount > length return 6 * propertyCount >= length; } StateBase* startArrayState(v8::Handle<v8::Array> array, StateBase* next) { v8::Handle<v8::Array> propertyNames = array->GetPropertyNames(); if (StateBase* newState = checkException(next)) return newState; uint32_t length = array->Length(); if (shouldSerializeDensely(length, propertyNames->Length())) { m_writer.writeGenerateFreshDenseArray(length); return push(new DenseArrayState(array, propertyNames, next, isolate())); } m_writer.writeGenerateFreshSparseArray(length); return push(new SparseArrayState(array, propertyNames, next, isolate())); } StateBase* startObjectState(v8::Handle<v8::Object> object, StateBase* next) { m_writer.writeGenerateFreshObject(); // FIXME: check not a wrapper return push(new ObjectState(object, next)); } // Marks object as having been visited by the serializer and assigns it a unique object reference ID. // An object may only be greyed once. void greyObject(const v8::Handle<v8::Object>& object) { ASSERT(!m_objectPool.contains(object)); uint32_t objectReference = m_nextObjectReference++; m_objectPool.set(object, objectReference); } bool appendBlobInfo(const String& uuid, const String& type, unsigned long long size, int* index) { if (!m_blobInfo) return false; *index = m_blobInfo->size(); m_blobInfo->append(blink::WebBlobInfo(uuid, type, size)); return true; } bool appendFileInfo(const File* file, int* index) { if (!m_blobInfo) return false; long long size = -1; double lastModified = invalidFileTime(); file->captureSnapshot(size, lastModified); *index = m_blobInfo->size(); m_blobInfo->append(blink::WebBlobInfo(file->uuid(), file->path(), file->name(), file->type(), lastModified, size)); return true; } RefPtr<ScriptState> m_scriptState; Writer& m_writer; v8::TryCatch& m_tryCatch; int m_depth; Status m_status; String m_errorMessage; typedef V8ObjectMap<v8::Object, uint32_t> ObjectPool; ObjectPool m_objectPool; ObjectPool m_transferredMessagePorts; ObjectPool m_transferredArrayBuffers; uint32_t m_nextObjectReference; WebBlobInfoArray* m_blobInfo; BlobDataHandleMap& m_blobDataHandles; }; // Returns true if the provided object is to be considered a 'host object', as used in the // HTML5 structured clone algorithm. static bool isHostObject(v8::Handle<v8::Object> object) { // If the object has any internal fields, then we won't be able to serialize or deserialize // them; conveniently, this is also a quick way to detect DOM wrapper objects, because // the mechanism for these relies on data stored in these fields. We should // catch external array data as a special case. return object->InternalFieldCount() || object->HasIndexedPropertiesInExternalArrayData(); } Serializer::StateBase* Serializer::doSerialize(v8::Handle<v8::Value> value, StateBase* next) { m_writer.writeReferenceCount(m_nextObjectReference); uint32_t objectReference; uint32_t arrayBufferIndex; if ((value->IsObject() || value->IsDate() || value->IsRegExp()) && m_objectPool.tryGet(value.As<v8::Object>(), &objectReference)) { // Note that IsObject() also detects wrappers (eg, it will catch the things // that we grey and write below). ASSERT(!value->IsString()); m_writer.writeObjectReference(objectReference); } else if (value.IsEmpty()) { return handleError(InputError, "The empty property name cannot be cloned.", next); } else if (value->IsUndefined()) m_writer.writeUndefined(); else if (value->IsNull()) m_writer.writeNull(); else if (value->IsTrue()) m_writer.writeTrue(); else if (value->IsFalse()) m_writer.writeFalse(); else if (value->IsInt32()) m_writer.writeInt32(value->Int32Value()); else if (value->IsUint32()) m_writer.writeUint32(value->Uint32Value()); else if (value->IsNumber()) m_writer.writeNumber(value.As<v8::Number>()->Value()); else if (V8ArrayBufferView::hasInstance(value, isolate())) return writeAndGreyArrayBufferView(value.As<v8::Object>(), next); else if (value->IsString()) writeString(value); else if (V8MessagePort::hasInstance(value, isolate())) { uint32_t messagePortIndex; if (m_transferredMessagePorts.tryGet(value.As<v8::Object>(), &messagePortIndex)) m_writer.writeTransferredMessagePort(messagePortIndex); else return handleError(DataCloneError, "A MessagePort could not be cloned.", next); } else if (V8ArrayBuffer::hasInstance(value, isolate()) && m_transferredArrayBuffers.tryGet(value.As<v8::Object>(), &arrayBufferIndex)) return writeTransferredArrayBuffer(value, arrayBufferIndex, next); else { v8::Handle<v8::Object> jsObject = value.As<v8::Object>(); if (jsObject.IsEmpty()) return handleError(DataCloneError, "An object could not be cloned.", next); greyObject(jsObject); if (value->IsDate()) m_writer.writeDate(value->NumberValue()); else if (value->IsStringObject()) writeStringObject(value); else if (value->IsNumberObject()) writeNumberObject(value); else if (value->IsBooleanObject()) writeBooleanObject(value); else if (value->IsArray()) { return startArrayState(value.As<v8::Array>(), next); } else if (V8File::hasInstance(value, isolate())) return writeFile(value, next); else if (V8Blob::hasInstance(value, isolate())) return writeBlob(value, next); else if (V8DOMFileSystem::hasInstance(value, isolate())) return writeDOMFileSystem(value, next); else if (V8FileList::hasInstance(value, isolate())) return writeFileList(value, next); else if (V8Key::hasInstance(value, isolate())) { if (!writeCryptoKey(value)) return handleError(DataCloneError, "Couldn't serialize key data", next); } else if (V8ImageData::hasInstance(value, isolate())) writeImageData(value); else if (value->IsRegExp()) writeRegExp(value); else if (V8ArrayBuffer::hasInstance(value, isolate())) return writeArrayBuffer(value, next); else if (value->IsObject()) { if (isHostObject(jsObject) || jsObject->IsCallable() || value->IsNativeError()) return handleError(DataCloneError, "An object could not be cloned.", next); return startObjectState(jsObject, next); } else return handleError(DataCloneError, "A value could not be cloned.", next); } return 0; } // Interface used by Reader to create objects of composite types. class CompositeCreator { public: virtual ~CompositeCreator() { } virtual bool consumeTopOfStack(v8::Handle<v8::Value>*) = 0; virtual uint32_t objectReferenceCount() = 0; virtual void pushObjectReference(const v8::Handle<v8::Value>&) = 0; virtual bool tryGetObjectFromObjectReference(uint32_t reference, v8::Handle<v8::Value>*) = 0; virtual bool tryGetTransferredMessagePort(uint32_t index, v8::Handle<v8::Value>*) = 0; virtual bool tryGetTransferredArrayBuffer(uint32_t index, v8::Handle<v8::Value>*) = 0; virtual bool newSparseArray(uint32_t length) = 0; virtual bool newDenseArray(uint32_t length) = 0; virtual bool newObject() = 0; virtual bool completeObject(uint32_t numProperties, v8::Handle<v8::Value>*) = 0; virtual bool completeSparseArray(uint32_t numProperties, uint32_t length, v8::Handle<v8::Value>*) = 0; virtual bool completeDenseArray(uint32_t numProperties, uint32_t length, v8::Handle<v8::Value>*) = 0; }; // Reader is responsible for deserializing primitive types and // restoring information about saved objects of composite types. class Reader { public: Reader(const uint8_t* buffer, int length, const WebBlobInfoArray* blobInfo, BlobDataHandleMap& blobDataHandles, ScriptState* scriptState) : m_scriptState(scriptState) , m_buffer(buffer) , m_length(length) , m_position(0) , m_version(0) , m_blobInfo(blobInfo) , m_blobDataHandles(blobDataHandles) { ASSERT(!(reinterpret_cast<size_t>(buffer) & 1)); ASSERT(length >= 0); } bool isEof() const { return m_position >= m_length; } ScriptState* scriptState() const { return m_scriptState.get(); } private: v8::Isolate* isolate() const { return m_scriptState->isolate(); } public: bool read(v8::Handle<v8::Value>* value, CompositeCreator& creator) { SerializationTag tag; if (!readTag(&tag)) return false; switch (tag) { case ReferenceCountTag: { if (!m_version) return false; uint32_t referenceTableSize; if (!doReadUint32(&referenceTableSize)) return false; // If this test fails, then the serializer and deserializer disagree about the assignment // of object reference IDs. On the deserialization side, this means there are too many or too few // calls to pushObjectReference. if (referenceTableSize != creator.objectReferenceCount()) return false; return true; } case InvalidTag: return false; case PaddingTag: return true; case UndefinedTag: *value = v8::Undefined(isolate()); break; case NullTag: *value = v8::Null(isolate()); break; case TrueTag: *value = v8Boolean(true, isolate()); break; case FalseTag: *value = v8Boolean(false, isolate()); break; case TrueObjectTag: *value = v8::BooleanObject::New(true); creator.pushObjectReference(*value); break; case FalseObjectTag: *value = v8::BooleanObject::New(false); creator.pushObjectReference(*value); break; case StringTag: if (!readString(value)) return false; break; case StringUCharTag: if (!readUCharString(value)) return false; break; case StringObjectTag: if (!readStringObject(value)) return false; creator.pushObjectReference(*value); break; case Int32Tag: if (!readInt32(value)) return false; break; case Uint32Tag: if (!readUint32(value)) return false; break; case DateTag: if (!readDate(value)) return false; creator.pushObjectReference(*value); break; case NumberTag: if (!readNumber(value)) return false; break; case NumberObjectTag: if (!readNumberObject(value)) return false; creator.pushObjectReference(*value); break; case BlobTag: case BlobIndexTag: if (!readBlob(value, tag == BlobIndexTag)) return false; creator.pushObjectReference(*value); break; case FileTag: case FileIndexTag: if (!readFile(value, tag == FileIndexTag)) return false; creator.pushObjectReference(*value); break; case DOMFileSystemTag: if (!readDOMFileSystem(value)) return false; creator.pushObjectReference(*value); break; case FileListTag: case FileListIndexTag: if (!readFileList(value, tag == FileListIndexTag)) return false; creator.pushObjectReference(*value); break; case CryptoKeyTag: if (!readCryptoKey(value)) return false; creator.pushObjectReference(*value); break; case ImageDataTag: if (!readImageData(value)) return false; creator.pushObjectReference(*value); break; case RegExpTag: if (!readRegExp(value)) return false; creator.pushObjectReference(*value); break; case ObjectTag: { uint32_t numProperties; if (!doReadUint32(&numProperties)) return false; if (!creator.completeObject(numProperties, value)) return false; break; } case SparseArrayTag: { uint32_t numProperties; uint32_t length; if (!doReadUint32(&numProperties)) return false; if (!doReadUint32(&length)) return false; if (!creator.completeSparseArray(numProperties, length, value)) return false; break; } case DenseArrayTag: { uint32_t numProperties; uint32_t length; if (!doReadUint32(&numProperties)) return false; if (!doReadUint32(&length)) return false; if (!creator.completeDenseArray(numProperties, length, value)) return false; break; } case ArrayBufferViewTag: { if (!m_version) return false; if (!readArrayBufferView(value, creator)) return false; creator.pushObjectReference(*value); break; } case ArrayBufferTag: { if (!m_version) return false; if (!readArrayBuffer(value)) return false; creator.pushObjectReference(*value); break; } case GenerateFreshObjectTag: { if (!m_version) return false; if (!creator.newObject()) return false; return true; } case GenerateFreshSparseArrayTag: { if (!m_version) return false; uint32_t length; if (!doReadUint32(&length)) return false; if (!creator.newSparseArray(length)) return false; return true; } case GenerateFreshDenseArrayTag: { if (!m_version) return false; uint32_t length; if (!doReadUint32(&length)) return false; if (!creator.newDenseArray(length)) return false; return true; } case MessagePortTag: { if (!m_version) return false; uint32_t index; if (!doReadUint32(&index)) return false; if (!creator.tryGetTransferredMessagePort(index, value)) return false; break; } case ArrayBufferTransferTag: { if (!m_version) return false; uint32_t index; if (!doReadUint32(&index)) return false; if (!creator.tryGetTransferredArrayBuffer(index, value)) return false; break; } case ObjectReferenceTag: { if (!m_version) return false; uint32_t reference; if (!doReadUint32(&reference)) return false; if (!creator.tryGetObjectFromObjectReference(reference, value)) return false; break; } default: return false; } return !value->IsEmpty(); } bool readVersion(uint32_t& version) { SerializationTag tag; if (!readTag(&tag)) { // This is a nullary buffer. We're still version 0. version = 0; return true; } if (tag != VersionTag) { // Versions of the format past 0 start with the version tag. version = 0; // Put back the tag. undoReadTag(); return true; } // Version-bearing messages are obligated to finish the version tag. return doReadUint32(&version); } void setVersion(uint32_t version) { m_version = version; } private: bool readTag(SerializationTag* tag) { if (m_position >= m_length) return false; *tag = static_cast<SerializationTag>(m_buffer[m_position++]); return true; } void undoReadTag() { if (m_position > 0) --m_position; } bool readArrayBufferViewSubTag(ArrayBufferViewSubTag* tag) { if (m_position >= m_length) return false; *tag = static_cast<ArrayBufferViewSubTag>(m_buffer[m_position++]); return true; } bool readString(v8::Handle<v8::Value>* value) { uint32_t length; if (!doReadUint32(&length)) return false; if (m_position + length > m_length) return false; *value = v8::String::NewFromUtf8(isolate(), reinterpret_cast<const char*>(m_buffer + m_position), v8::String::kNormalString, length); m_position += length; return true; } bool readUCharString(v8::Handle<v8::Value>* value) { uint32_t length; if (!doReadUint32(&length) || (length & 1)) return false; if (m_position + length > m_length) return false; ASSERT(!(m_position & 1)); *value = v8::String::NewFromTwoByte(isolate(), reinterpret_cast<const uint16_t*>(m_buffer + m_position), v8::String::kNormalString, length / sizeof(UChar)); m_position += length; return true; } bool readStringObject(v8::Handle<v8::Value>* value) { v8::Handle<v8::Value> stringValue; if (!readString(&stringValue) || !stringValue->IsString()) return false; *value = v8::StringObject::New(stringValue.As<v8::String>()); return true; } bool readWebCoreString(String* string) { uint32_t length; if (!doReadUint32(&length)) return false; if (m_position + length > m_length) return false; *string = String::fromUTF8(reinterpret_cast<const char*>(m_buffer + m_position), length); m_position += length; return true; } bool readInt32(v8::Handle<v8::Value>* value) { uint32_t rawValue; if (!doReadUint32(&rawValue)) return false; *value = v8::Integer::New(isolate(), static_cast<int32_t>(ZigZag::decode(rawValue))); return true; } bool readUint32(v8::Handle<v8::Value>* value) { uint32_t rawValue; if (!doReadUint32(&rawValue)) return false; *value = v8::Integer::NewFromUnsigned(isolate(), rawValue); return true; } bool readDate(v8::Handle<v8::Value>* value) { double numberValue; if (!doReadNumber(&numberValue)) return false; *value = v8DateOrNaN(numberValue, isolate()); return true; } bool readNumber(v8::Handle<v8::Value>* value) { double number; if (!doReadNumber(&number)) return false; *value = v8::Number::New(isolate(), number); return true; } bool readNumberObject(v8::Handle<v8::Value>* value) { double number; if (!doReadNumber(&number)) return false; *value = v8::NumberObject::New(isolate(), number); return true; } bool readImageData(v8::Handle<v8::Value>* value) { uint32_t width; uint32_t height; uint32_t pixelDataLength; if (!doReadUint32(&width)) return false; if (!doReadUint32(&height)) return false; if (!doReadUint32(&pixelDataLength)) return false; if (m_position + pixelDataLength > m_length) return false; RefPtrWillBeRawPtr<ImageData> imageData = ImageData::create(IntSize(width, height)); Uint8ClampedArray* pixelArray = imageData->data(); ASSERT(pixelArray); ASSERT(pixelArray->length() >= pixelDataLength); memcpy(pixelArray->data(), m_buffer + m_position, pixelDataLength); m_position += pixelDataLength; *value = toV8(imageData.release(), m_scriptState->context()->Global(), isolate()); return true; } PassRefPtr<ArrayBuffer> doReadArrayBuffer() { uint32_t byteLength; if (!doReadUint32(&byteLength)) return nullptr; if (m_position + byteLength > m_length) return nullptr; const void* bufferStart = m_buffer + m_position; RefPtr<ArrayBuffer> arrayBuffer = ArrayBuffer::create(bufferStart, byteLength); arrayBuffer->setDeallocationObserver(V8ArrayBufferDeallocationObserver::instanceTemplate()); m_position += byteLength; return arrayBuffer.release(); } bool readArrayBuffer(v8::Handle<v8::Value>* value) { RefPtr<ArrayBuffer> arrayBuffer = doReadArrayBuffer(); if (!arrayBuffer) return false; *value = toV8(arrayBuffer.release(), m_scriptState->context()->Global(), isolate()); return true; } bool readArrayBufferView(v8::Handle<v8::Value>* value, CompositeCreator& creator) { ArrayBufferViewSubTag subTag; uint32_t byteOffset; uint32_t byteLength; RefPtr<ArrayBuffer> arrayBuffer; v8::Handle<v8::Value> arrayBufferV8Value; if (!readArrayBufferViewSubTag(&subTag)) return false; if (!doReadUint32(&byteOffset)) return false; if (!doReadUint32(&byteLength)) return false; if (!creator.consumeTopOfStack(&arrayBufferV8Value)) return false; if (arrayBufferV8Value.IsEmpty()) return false; arrayBuffer = V8ArrayBuffer::toNative(arrayBufferV8Value.As<v8::Object>()); if (!arrayBuffer) return false; v8::Handle<v8::Object> creationContext = m_scriptState->context()->Global(); switch (subTag) { case ByteArrayTag: *value = toV8(Int8Array::create(arrayBuffer.release(), byteOffset, byteLength), creationContext, isolate()); break; case UnsignedByteArrayTag: *value = toV8(Uint8Array::create(arrayBuffer.release(), byteOffset, byteLength), creationContext, isolate()); break; case UnsignedByteClampedArrayTag: *value = toV8(Uint8ClampedArray::create(arrayBuffer.release(), byteOffset, byteLength), creationContext, isolate()); break; case ShortArrayTag: { uint32_t shortLength = byteLength / sizeof(int16_t); if (shortLength * sizeof(int16_t) != byteLength) return false; *value = toV8(Int16Array::create(arrayBuffer.release(), byteOffset, shortLength), creationContext, isolate()); break; } case UnsignedShortArrayTag: { uint32_t shortLength = byteLength / sizeof(uint16_t); if (shortLength * sizeof(uint16_t) != byteLength) return false; *value = toV8(Uint16Array::create(arrayBuffer.release(), byteOffset, shortLength), creationContext, isolate()); break; } case IntArrayTag: { uint32_t intLength = byteLength / sizeof(int32_t); if (intLength * sizeof(int32_t) != byteLength) return false; *value = toV8(Int32Array::create(arrayBuffer.release(), byteOffset, intLength), creationContext, isolate()); break; } case UnsignedIntArrayTag: { uint32_t intLength = byteLength / sizeof(uint32_t); if (intLength * sizeof(uint32_t) != byteLength) return false; *value = toV8(Uint32Array::create(arrayBuffer.release(), byteOffset, intLength), creationContext, isolate()); break; } case FloatArrayTag: { uint32_t floatLength = byteLength / sizeof(float); if (floatLength * sizeof(float) != byteLength) return false; *value = toV8(Float32Array::create(arrayBuffer.release(), byteOffset, floatLength), creationContext, isolate()); break; } case DoubleArrayTag: { uint32_t floatLength = byteLength / sizeof(double); if (floatLength * sizeof(double) != byteLength) return false; *value = toV8(Float64Array::create(arrayBuffer.release(), byteOffset, floatLength), creationContext, isolate()); break; } case DataViewTag: *value = toV8(DataView::create(arrayBuffer.release(), byteOffset, byteLength), creationContext, isolate()); break; default: return false; } // The various *Array::create() methods will return null if the range the view expects is // mismatched with the range the buffer can provide or if the byte offset is not aligned // to the size of the element type. return !value->IsEmpty(); } bool readRegExp(v8::Handle<v8::Value>* value) { v8::Handle<v8::Value> pattern; if (!readString(&pattern)) return false; uint32_t flags; if (!doReadUint32(&flags)) return false; *value = v8::RegExp::New(pattern.As<v8::String>(), static_cast<v8::RegExp::Flags>(flags)); return true; } bool readBlob(v8::Handle<v8::Value>* value, bool isIndexed) { if (m_version < 3) return false; RefPtrWillBeRawPtr<Blob> blob; if (isIndexed) { if (m_version < 6) return false; ASSERT(m_blobInfo); uint32_t index; if (!doReadUint32(&index) || index >= m_blobInfo->size()) return false; const blink::WebBlobInfo& info = (*m_blobInfo)[index]; blob = Blob::create(getOrCreateBlobDataHandle(info.uuid(), info.type(), info.size())); } else { ASSERT(!m_blobInfo); String uuid; String type; uint64_t size; ASSERT(!m_blobInfo); if (!readWebCoreString(&uuid)) return false; if (!readWebCoreString(&type)) return false; if (!doReadUint64(&size)) return false; blob = Blob::create(getOrCreateBlobDataHandle(uuid, type, size)); } *value = toV8(blob.release(), m_scriptState->context()->Global(), isolate()); return true; } bool readDOMFileSystem(v8::Handle<v8::Value>* value) { uint32_t type; String name; String url; if (!doReadUint32(&type)) return false; if (!readWebCoreString(&name)) return false; if (!readWebCoreString(&url)) return false; DOMFileSystem* fs = DOMFileSystem::create(m_scriptState->executionContext(), name, static_cast<WebCore::FileSystemType>(type), KURL(ParsedURLString, url)); *value = toV8(fs, m_scriptState->context()->Global(), isolate()); return true; } bool readFile(v8::Handle<v8::Value>* value, bool isIndexed) { RefPtrWillBeRawPtr<File> file; if (isIndexed) { if (m_version < 6) return false; file = readFileIndexHelper(); } else { file = readFileHelper(); } if (!file) return false; *value = toV8(file.release(), m_scriptState->context()->Global(), isolate()); return true; } bool readFileList(v8::Handle<v8::Value>* value, bool isIndexed) { if (m_version < 3) return false; uint32_t length; if (!doReadUint32(&length)) return false; RefPtrWillBeRawPtr<FileList> fileList = FileList::create(); for (unsigned i = 0; i < length; ++i) { RefPtrWillBeRawPtr<File> file; if (isIndexed) { if (m_version < 6) return false; file = readFileIndexHelper(); } else { file = readFileHelper(); } if (!file) return false; fileList->append(file.release()); } *value = toV8(fileList.release(), m_scriptState->context()->Global(), isolate()); return true; } bool readCryptoKey(v8::Handle<v8::Value>* value) { uint32_t rawKeyType; if (!doReadUint32(&rawKeyType)) return false; blink::WebCryptoKeyAlgorithm algorithm; blink::WebCryptoKeyType type = blink::WebCryptoKeyTypeSecret; switch (static_cast<CryptoKeySubTag>(rawKeyType)) { case AesKeyTag: if (!doReadAesKey(algorithm, type)) return false; break; case HmacKeyTag: if (!doReadHmacKey(algorithm, type)) return false; break; case RsaHashedKeyTag: if (!doReadRsaHashedKey(algorithm, type)) return false; break; default: return false; } blink::WebCryptoKeyUsageMask usages; bool extractable; if (!doReadKeyUsages(usages, extractable)) return false; uint32_t keyDataLength; if (!doReadUint32(&keyDataLength)) return false; if (m_position + keyDataLength > m_length) return false; const uint8_t* keyData = m_buffer + m_position; m_position += keyDataLength; blink::WebCryptoKey key = blink::WebCryptoKey::createNull(); if (!blink::Platform::current()->crypto()->deserializeKeyForClone( algorithm, type, extractable, usages, keyData, keyDataLength, key)) { return false; } *value = toV8(Key::create(key), m_scriptState->context()->Global(), isolate()); return true; } PassRefPtrWillBeRawPtr<File> readFileHelper() { if (m_version < 3) return nullptr; ASSERT(!m_blobInfo); String path; String name; String relativePath; String uuid; String type; uint32_t hasSnapshot = 0; uint64_t size = 0; double lastModified = 0; if (!readWebCoreString(&path)) return nullptr; if (m_version >= 4 && !readWebCoreString(&name)) return nullptr; if (m_version >= 4 && !readWebCoreString(&relativePath)) return nullptr; if (!readWebCoreString(&uuid)) return nullptr; if (!readWebCoreString(&type)) return nullptr; if (m_version >= 4 && !doReadUint32(&hasSnapshot)) return nullptr; if (hasSnapshot) { if (!doReadUint64(&size)) return nullptr; if (!doReadNumber(&lastModified)) return nullptr; } return File::create(path, name, relativePath, hasSnapshot > 0, size, lastModified, getOrCreateBlobDataHandle(uuid, type)); } PassRefPtrWillBeRawPtr<File> readFileIndexHelper() { if (m_version < 3) return nullptr; ASSERT(m_blobInfo); uint32_t index; if (!doReadUint32(&index) || index >= m_blobInfo->size()) return nullptr; const blink::WebBlobInfo& info = (*m_blobInfo)[index]; return File::create(info.filePath(), info.fileName(), info.size(), info.lastModified(), getOrCreateBlobDataHandle(info.uuid(), info.type(), info.size())); } template<class T> bool doReadUintHelper(T* value) { *value = 0; uint8_t currentByte; int shift = 0; do { if (m_position >= m_length) return false; currentByte = m_buffer[m_position++]; *value |= ((currentByte & varIntMask) << shift); shift += varIntShift; } while (currentByte & (1 << varIntShift)); return true; } bool doReadUint32(uint32_t* value) { return doReadUintHelper(value); } bool doReadUint64(uint64_t* value) { return doReadUintHelper(value); } bool doReadNumber(double* number) { if (m_position + sizeof(double) > m_length) return false; uint8_t* numberAsByteArray = reinterpret_cast<uint8_t*>(number); for (unsigned i = 0; i < sizeof(double); ++i) numberAsByteArray[i] = m_buffer[m_position++]; return true; } PassRefPtr<BlobDataHandle> getOrCreateBlobDataHandle(const String& uuid, const String& type, long long size = -1) { // The containing ssv may have a BDH for this uuid if this ssv is just being // passed from main to worker thread (for example). We use those values when creating // the new blob instead of cons'ing up a new BDH. // // FIXME: Maybe we should require that it work that way where the ssv must have a BDH for any // blobs it comes across during deserialization. Would require callers to explicitly populate // the collection of BDH's for blobs to work, which would encourage lifetimes to be considered // when passing ssv's around cross process. At present, we get 'lucky' in some cases because // the blob in the src process happens to still exist at the time the dest process is deserializing. // For example in sharedWorker.postMessage(...). BlobDataHandleMap::const_iterator it = m_blobDataHandles.find(uuid); if (it != m_blobDataHandles.end()) { // make assertions about type and size? return it->value; } return BlobDataHandle::create(uuid, type, size); } bool doReadHmacKey(blink::WebCryptoKeyAlgorithm& algorithm, blink::WebCryptoKeyType& type) { uint32_t lengthBytes; if (!doReadUint32(&lengthBytes)) return false; blink::WebCryptoAlgorithmId hash; if (!doReadAlgorithmId(hash)) return false; algorithm = blink::WebCryptoKeyAlgorithm::createHmac(hash, lengthBytes * 8); type = blink::WebCryptoKeyTypeSecret; return !algorithm.isNull(); } bool doReadAesKey(blink::WebCryptoKeyAlgorithm& algorithm, blink::WebCryptoKeyType& type) { blink::WebCryptoAlgorithmId id; if (!doReadAlgorithmId(id)) return false; uint32_t lengthBytes; if (!doReadUint32(&lengthBytes)) return false; algorithm = blink::WebCryptoKeyAlgorithm::createAes(id, lengthBytes * 8); type = blink::WebCryptoKeyTypeSecret; return !algorithm.isNull(); } bool doReadRsaHashedKey(blink::WebCryptoKeyAlgorithm& algorithm, blink::WebCryptoKeyType& type) { blink::WebCryptoAlgorithmId id; if (!doReadAlgorithmId(id)) return false; uint32_t rawType; if (!doReadUint32(&rawType)) return false; switch (static_cast<AssymetricCryptoKeyType>(rawType)) { case PublicKeyType: type = blink::WebCryptoKeyTypePublic; break; case PrivateKeyType: type = blink::WebCryptoKeyTypePrivate; break; default: return false; } uint32_t modulusLengthBits; if (!doReadUint32(&modulusLengthBits)) return false; uint32_t publicExponentSize; if (!doReadUint32(&publicExponentSize)) return false; if (m_position + publicExponentSize > m_length) return false; const uint8_t* publicExponent = m_buffer + m_position; m_position += publicExponentSize; blink::WebCryptoAlgorithmId hash; if (!doReadAlgorithmId(hash)) return false; algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed(id, modulusLengthBits, publicExponent, publicExponentSize, hash); return !algorithm.isNull(); } bool doReadAlgorithmId(blink::WebCryptoAlgorithmId& id) { uint32_t rawId; if (!doReadUint32(&rawId)) return false; switch (static_cast<CryptoKeyAlgorithmTag>(rawId)) { case AesCbcTag: id = blink::WebCryptoAlgorithmIdAesCbc; return true; case HmacTag: id = blink::WebCryptoAlgorithmIdHmac; return true; case RsaSsaPkcs1v1_5Tag: id = blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5; return true; case Sha1Tag: id = blink::WebCryptoAlgorithmIdSha1; return true; case Sha256Tag: id = blink::WebCryptoAlgorithmIdSha256; return true; case Sha384Tag: id = blink::WebCryptoAlgorithmIdSha384; return true; case Sha512Tag: id = blink::WebCryptoAlgorithmIdSha512; return true; case AesGcmTag: id = blink::WebCryptoAlgorithmIdAesGcm; return true; case RsaOaepTag: id = blink::WebCryptoAlgorithmIdRsaOaep; return true; case AesCtrTag: id = blink::WebCryptoAlgorithmIdAesCtr; return true; case AesKwTag: id = blink::WebCryptoAlgorithmIdAesKw; return true; } return false; } bool doReadKeyUsages(blink::WebCryptoKeyUsageMask& usages, bool& extractable) { // Reminder to update this when adding new key usages. COMPILE_ASSERT(blink::EndOfWebCryptoKeyUsage == (1 << 7) + 1, UpdateMe); const uint32_t allPossibleUsages = ExtractableUsage | EncryptUsage | DecryptUsage | SignUsage | VerifyUsage | DeriveKeyUsage | WrapKeyUsage | UnwrapKeyUsage | DeriveBitsUsage; uint32_t rawUsages; if (!doReadUint32(&rawUsages)) return false; // Make sure it doesn't contain an unrecognized usage value. if (rawUsages & ~allPossibleUsages) return false; usages = 0; extractable = rawUsages & ExtractableUsage; if (rawUsages & EncryptUsage) usages |= blink::WebCryptoKeyUsageEncrypt; if (rawUsages & DecryptUsage) usages |= blink::WebCryptoKeyUsageDecrypt; if (rawUsages & SignUsage) usages |= blink::WebCryptoKeyUsageSign; if (rawUsages & VerifyUsage) usages |= blink::WebCryptoKeyUsageVerify; if (rawUsages & DeriveKeyUsage) usages |= blink::WebCryptoKeyUsageDeriveKey; if (rawUsages & WrapKeyUsage) usages |= blink::WebCryptoKeyUsageWrapKey; if (rawUsages & UnwrapKeyUsage) usages |= blink::WebCryptoKeyUsageUnwrapKey; if (rawUsages & DeriveBitsUsage) usages |= blink::WebCryptoKeyUsageDeriveBits; return true; } RefPtr<ScriptState> m_scriptState; const uint8_t* m_buffer; const unsigned m_length; unsigned m_position; uint32_t m_version; const WebBlobInfoArray* m_blobInfo; const BlobDataHandleMap& m_blobDataHandles; }; typedef Vector<WTF::ArrayBufferContents, 1> ArrayBufferContentsArray; class Deserializer FINAL : public CompositeCreator { public: Deserializer(Reader& reader, MessagePortArray* messagePorts, ArrayBufferContentsArray* arrayBufferContents) : m_reader(reader) , m_transferredMessagePorts(messagePorts) , m_arrayBufferContents(arrayBufferContents) , m_arrayBuffers(arrayBufferContents ? arrayBufferContents->size() : 0) , m_version(0) { } v8::Handle<v8::Value> deserialize() { v8::Isolate* isolate = m_reader.scriptState()->isolate(); if (!m_reader.readVersion(m_version) || m_version > SerializedScriptValue::wireFormatVersion) return v8::Null(isolate); m_reader.setVersion(m_version); v8::EscapableHandleScope scope(isolate); while (!m_reader.isEof()) { if (!doDeserialize()) return v8::Null(isolate); } if (stackDepth() != 1 || m_openCompositeReferenceStack.size()) return v8::Null(isolate); v8::Handle<v8::Value> result = scope.Escape(element(0)); return result; } virtual bool newSparseArray(uint32_t) OVERRIDE { v8::Local<v8::Array> array = v8::Array::New(m_reader.scriptState()->isolate(), 0); openComposite(array); return true; } virtual bool newDenseArray(uint32_t length) OVERRIDE { v8::Local<v8::Array> array = v8::Array::New(m_reader.scriptState()->isolate(), length); openComposite(array); return true; } virtual bool consumeTopOfStack(v8::Handle<v8::Value>* object) OVERRIDE { if (stackDepth() < 1) return false; *object = element(stackDepth() - 1); pop(1); return true; } virtual bool newObject() OVERRIDE { v8::Local<v8::Object> object = v8::Object::New(m_reader.scriptState()->isolate()); if (object.IsEmpty()) return false; openComposite(object); return true; } virtual bool completeObject(uint32_t numProperties, v8::Handle<v8::Value>* value) OVERRIDE { v8::Local<v8::Object> object; if (m_version > 0) { v8::Local<v8::Value> composite; if (!closeComposite(&composite)) return false; object = composite.As<v8::Object>(); } else { object = v8::Object::New(m_reader.scriptState()->isolate()); } if (object.IsEmpty()) return false; return initializeObject(object, numProperties, value); } virtual bool completeSparseArray(uint32_t numProperties, uint32_t length, v8::Handle<v8::Value>* value) OVERRIDE { v8::Local<v8::Array> array; if (m_version > 0) { v8::Local<v8::Value> composite; if (!closeComposite(&composite)) return false; array = composite.As<v8::Array>(); } else { array = v8::Array::New(m_reader.scriptState()->isolate()); } if (array.IsEmpty()) return false; return initializeObject(array, numProperties, value); } virtual bool completeDenseArray(uint32_t numProperties, uint32_t length, v8::Handle<v8::Value>* value) OVERRIDE { v8::Local<v8::Array> array; if (m_version > 0) { v8::Local<v8::Value> composite; if (!closeComposite(&composite)) return false; array = composite.As<v8::Array>(); } if (array.IsEmpty()) return false; if (!initializeObject(array, numProperties, value)) return false; if (length > stackDepth()) return false; for (unsigned i = 0, stackPos = stackDepth() - length; i < length; i++, stackPos++) { v8::Local<v8::Value> elem = element(stackPos); if (!elem->IsUndefined()) array->Set(i, elem); } pop(length); return true; } virtual void pushObjectReference(const v8::Handle<v8::Value>& object) OVERRIDE { m_objectPool.append(object); } virtual bool tryGetTransferredMessagePort(uint32_t index, v8::Handle<v8::Value>* object) OVERRIDE { if (!m_transferredMessagePorts) return false; if (index >= m_transferredMessagePorts->size()) return false; v8::Handle<v8::Object> creationContext = m_reader.scriptState()->context()->Global(); *object = toV8(m_transferredMessagePorts->at(index).get(), creationContext, m_reader.scriptState()->isolate()); return true; } virtual bool tryGetTransferredArrayBuffer(uint32_t index, v8::Handle<v8::Value>* object) OVERRIDE { if (!m_arrayBufferContents) return false; if (index >= m_arrayBuffers.size()) return false; v8::Handle<v8::Object> result = m_arrayBuffers.at(index); if (result.IsEmpty()) { RefPtr<ArrayBuffer> buffer = ArrayBuffer::create(m_arrayBufferContents->at(index)); buffer->setDeallocationObserver(V8ArrayBufferDeallocationObserver::instanceTemplate()); v8::Isolate* isolate = m_reader.scriptState()->isolate(); v8::Handle<v8::Object> creationContext = m_reader.scriptState()->context()->Global(); isolate->AdjustAmountOfExternalAllocatedMemory(buffer->byteLength()); result = toV8Object(buffer.get(), creationContext, isolate); m_arrayBuffers[index] = result; } *object = result; return true; } virtual bool tryGetObjectFromObjectReference(uint32_t reference, v8::Handle<v8::Value>* object) OVERRIDE { if (reference >= m_objectPool.size()) return false; *object = m_objectPool[reference]; return object; } virtual uint32_t objectReferenceCount() OVERRIDE { return m_objectPool.size(); } private: bool initializeObject(v8::Handle<v8::Object> object, uint32_t numProperties, v8::Handle<v8::Value>* value) { unsigned length = 2 * numProperties; if (length > stackDepth()) return false; for (unsigned i = stackDepth() - length; i < stackDepth(); i += 2) { v8::Local<v8::Value> propertyName = element(i); v8::Local<v8::Value> propertyValue = element(i + 1); object->Set(propertyName, propertyValue); } pop(length); *value = object; return true; } bool doDeserialize() { v8::Local<v8::Value> value; if (!m_reader.read(&value, *this)) return false; if (!value.IsEmpty()) push(value); return true; } void push(v8::Local<v8::Value> value) { m_stack.append(value); } void pop(unsigned length) { ASSERT(length <= m_stack.size()); m_stack.shrink(m_stack.size() - length); } unsigned stackDepth() const { return m_stack.size(); } v8::Local<v8::Value> element(unsigned index) { ASSERT_WITH_SECURITY_IMPLICATION(index < m_stack.size()); return m_stack[index]; } void openComposite(const v8::Local<v8::Value>& object) { uint32_t newObjectReference = m_objectPool.size(); m_openCompositeReferenceStack.append(newObjectReference); m_objectPool.append(object); } bool closeComposite(v8::Handle<v8::Value>* object) { if (!m_openCompositeReferenceStack.size()) return false; uint32_t objectReference = m_openCompositeReferenceStack[m_openCompositeReferenceStack.size() - 1]; m_openCompositeReferenceStack.shrink(m_openCompositeReferenceStack.size() - 1); if (objectReference >= m_objectPool.size()) return false; *object = m_objectPool[objectReference]; return true; } Reader& m_reader; Vector<v8::Local<v8::Value> > m_stack; Vector<v8::Handle<v8::Value> > m_objectPool; Vector<uint32_t> m_openCompositeReferenceStack; MessagePortArray* m_transferredMessagePorts; ArrayBufferContentsArray* m_arrayBufferContents; Vector<v8::Handle<v8::Object> > m_arrayBuffers; uint32_t m_version; }; } // namespace PassRefPtr<SerializedScriptValue> SerializedScriptValue::create(v8::Handle<v8::Value> value, MessagePortArray* messagePorts, ArrayBufferArray* arrayBuffers, ExceptionState& exceptionState, v8::Isolate* isolate) { return adoptRef(new SerializedScriptValue(value, messagePorts, arrayBuffers, 0, exceptionState, isolate)); } PassRefPtr<SerializedScriptValue> SerializedScriptValue::createAndSwallowExceptions(v8::Handle<v8::Value> value, v8::Isolate* isolate) { TrackExceptionState exceptionState; return adoptRef(new SerializedScriptValue(value, 0, 0, 0, exceptionState, isolate)); } PassRefPtr<SerializedScriptValue> SerializedScriptValue::create(const ScriptValue& value, WebBlobInfoArray* blobInfo, ExceptionState& exceptionState, v8::Isolate* isolate) { ASSERT(isolate->InContext()); return adoptRef(new SerializedScriptValue(value.v8Value(), 0, 0, blobInfo, exceptionState, isolate)); } PassRefPtr<SerializedScriptValue> SerializedScriptValue::createFromWire(const String& data) { return adoptRef(new SerializedScriptValue(data)); } PassRefPtr<SerializedScriptValue> SerializedScriptValue::createFromWireBytes(const Vector<uint8_t>& data) { // Decode wire data from big endian to host byte order. ASSERT(!(data.size() % sizeof(UChar))); size_t length = data.size() / sizeof(UChar); StringBuffer<UChar> buffer(length); const UChar* src = reinterpret_cast<const UChar*>(data.data()); UChar* dst = buffer.characters(); for (size_t i = 0; i < length; i++) dst[i] = ntohs(src[i]); return createFromWire(String::adopt(buffer)); } PassRefPtr<SerializedScriptValue> SerializedScriptValue::create(const String& data) { return create(data, v8::Isolate::GetCurrent()); } PassRefPtr<SerializedScriptValue> SerializedScriptValue::create(const String& data, v8::Isolate* isolate) { Writer writer; writer.writeWebCoreString(data); String wireData = writer.takeWireString(); return adoptRef(new SerializedScriptValue(wireData)); } PassRefPtr<SerializedScriptValue> SerializedScriptValue::create() { return adoptRef(new SerializedScriptValue()); } PassRefPtr<SerializedScriptValue> SerializedScriptValue::nullValue() { Writer writer; writer.writeNull(); String wireData = writer.takeWireString(); return adoptRef(new SerializedScriptValue(wireData)); } // Convert serialized string to big endian wire data. void SerializedScriptValue::toWireBytes(Vector<char>& result) const { ASSERT(result.isEmpty()); size_t length = m_data.length(); result.resize(length * sizeof(UChar)); UChar* dst = reinterpret_cast<UChar*>(result.data()); if (m_data.is8Bit()) { const LChar* src = m_data.characters8(); for (size_t i = 0; i < length; i++) dst[i] = htons(static_cast<UChar>(src[i])); } else { const UChar* src = m_data.characters16(); for (size_t i = 0; i < length; i++) dst[i] = htons(src[i]); } } SerializedScriptValue::SerializedScriptValue() : m_externallyAllocatedMemory(0) { } static void neuterArrayBufferInAllWorlds(ArrayBuffer* object) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); if (isMainThread()) { Vector<RefPtr<DOMWrapperWorld> > worlds; DOMWrapperWorld::allWorldsInMainThread(worlds); for (size_t i = 0; i < worlds.size(); i++) { v8::Handle<v8::Object> wrapper = worlds[i]->domDataStore().get<V8ArrayBuffer>(object, isolate); if (!wrapper.IsEmpty()) { ASSERT(wrapper->IsArrayBuffer()); v8::Handle<v8::ArrayBuffer>::Cast(wrapper)->Neuter(); } } } else { v8::Handle<v8::Object> wrapper = DOMWrapperWorld::current(isolate).domDataStore().get<V8ArrayBuffer>(object, isolate); if (!wrapper.IsEmpty()) { ASSERT(wrapper->IsArrayBuffer()); v8::Handle<v8::ArrayBuffer>::Cast(wrapper)->Neuter(); } } } PassOwnPtr<SerializedScriptValue::ArrayBufferContentsArray> SerializedScriptValue::transferArrayBuffers(ArrayBufferArray& arrayBuffers, ExceptionState& exceptionState, v8::Isolate* isolate) { ASSERT(arrayBuffers.size()); for (size_t i = 0; i < arrayBuffers.size(); i++) { if (arrayBuffers[i]->isNeutered()) { exceptionState.throwDOMException(DataCloneError, "ArrayBuffer at index " + String::number(i) + " is already neutered."); return nullptr; } } OwnPtr<ArrayBufferContentsArray> contents = adoptPtr(new ArrayBufferContentsArray(arrayBuffers.size())); HashSet<ArrayBuffer*> visited; for (size_t i = 0; i < arrayBuffers.size(); i++) { if (visited.contains(arrayBuffers[i].get())) continue; visited.add(arrayBuffers[i].get()); bool result = arrayBuffers[i]->transfer(contents->at(i)); if (!result) { exceptionState.throwDOMException(DataCloneError, "ArrayBuffer at index " + String::number(i) + " could not be transferred."); return nullptr; } neuterArrayBufferInAllWorlds(arrayBuffers[i].get()); } return contents.release(); } SerializedScriptValue::SerializedScriptValue(v8::Handle<v8::Value> value, MessagePortArray* messagePorts, ArrayBufferArray* arrayBuffers, WebBlobInfoArray* blobInfo, ExceptionState& exceptionState, v8::Isolate* isolate) : m_externallyAllocatedMemory(0) { Writer writer; Serializer::Status status; String errorMessage; { v8::TryCatch tryCatch; Serializer serializer(writer, messagePorts, arrayBuffers, blobInfo, m_blobDataHandles, tryCatch, ScriptState::current(isolate)); status = serializer.serialize(value); if (status == Serializer::JSException) { // If there was a JS exception thrown, re-throw it. exceptionState.rethrowV8Exception(tryCatch.Exception()); return; } errorMessage = serializer.errorMessage(); } switch (status) { case Serializer::InputError: case Serializer::DataCloneError: exceptionState.throwDOMException(DataCloneError, errorMessage); return; case Serializer::Success: m_data = writer.takeWireString(); ASSERT(m_data.impl()->hasOneRef()); if (arrayBuffers && arrayBuffers->size()) m_arrayBufferContentsArray = transferArrayBuffers(*arrayBuffers, exceptionState, isolate); return; case Serializer::JSException: ASSERT_NOT_REACHED(); break; } ASSERT_NOT_REACHED(); } SerializedScriptValue::SerializedScriptValue(const String& wireData) : m_externallyAllocatedMemory(0) { m_data = wireData.isolatedCopy(); } v8::Handle<v8::Value> SerializedScriptValue::deserialize(MessagePortArray* messagePorts) { return deserialize(v8::Isolate::GetCurrent(), messagePorts, 0); } v8::Handle<v8::Value> SerializedScriptValue::deserialize(v8::Isolate* isolate, MessagePortArray* messagePorts, const WebBlobInfoArray* blobInfo) { if (!m_data.impl()) return v8::Null(isolate); COMPILE_ASSERT(sizeof(BufferValueType) == 2, BufferValueTypeIsTwoBytes); m_data.ensure16Bit(); // FIXME: SerializedScriptValue shouldn't use String for its underlying // storage. Instead, it should use SharedBuffer or Vector<uint8_t>. The // information stored in m_data isn't even encoded in UTF-16. Instead, // unicode characters are encoded as UTF-8 with two code units per UChar. Reader reader(reinterpret_cast<const uint8_t*>(m_data.impl()->characters16()), 2 * m_data.length(), blobInfo, m_blobDataHandles, ScriptState::current(isolate)); Deserializer deserializer(reader, messagePorts, m_arrayBufferContentsArray.get()); // deserialize() can run arbitrary script (e.g., setters), which could result in |this| being destroyed. // Holding a RefPtr ensures we are alive (along with our internal data) throughout the operation. RefPtr<SerializedScriptValue> protect(this); return deserializer.deserialize(); } bool SerializedScriptValue::extractTransferables(v8::Local<v8::Value> value, int argumentIndex, MessagePortArray& ports, ArrayBufferArray& arrayBuffers, ExceptionState& exceptionState, v8::Isolate* isolate) { if (isUndefinedOrNull(value)) { ports.resize(0); arrayBuffers.resize(0); return true; } uint32_t length = 0; if (value->IsArray()) { v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(value); length = array->Length(); } else if (toV8Sequence(value, length, isolate).IsEmpty()) { exceptionState.throwTypeError(ExceptionMessages::notAnArrayTypeArgumentOrValue(argumentIndex + 1)); return false; } v8::Local<v8::Object> transferrables = v8::Local<v8::Object>::Cast(value); // Validate the passed array of transferrables. for (unsigned i = 0; i < length; ++i) { v8::Local<v8::Value> transferrable = transferrables->Get(i); // Validation of non-null objects, per HTML5 spec 10.3.3. if (isUndefinedOrNull(transferrable)) { exceptionState.throwDOMException(DataCloneError, "Value at index " + String::number(i) + " is an untransferable " + (transferrable->IsUndefined() ? "'undefined'" : "'null'") + " value."); return false; } // Validation of Objects implementing an interface, per WebIDL spec 4.1.15. if (V8MessagePort::hasInstance(transferrable, isolate)) { RefPtr<MessagePort> port = V8MessagePort::toNative(v8::Handle<v8::Object>::Cast(transferrable)); // Check for duplicate MessagePorts. if (ports.contains(port)) { exceptionState.throwDOMException(DataCloneError, "Message port at index " + String::number(i) + " is a duplicate of an earlier port."); return false; } ports.append(port.release()); } else if (V8ArrayBuffer::hasInstance(transferrable, isolate)) { RefPtr<ArrayBuffer> arrayBuffer = V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(transferrable)); if (arrayBuffers.contains(arrayBuffer)) { exceptionState.throwDOMException(DataCloneError, "ArrayBuffer at index " + String::number(i) + " is a duplicate of an earlier ArrayBuffer."); return false; } arrayBuffers.append(arrayBuffer.release()); } else { exceptionState.throwDOMException(DataCloneError, "Value at index " + String::number(i) + " does not have a transferable type."); return false; } } return true; } void SerializedScriptValue::registerMemoryAllocatedWithCurrentScriptContext() { if (m_externallyAllocatedMemory) return; m_externallyAllocatedMemory = static_cast<intptr_t>(m_data.length()); v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(m_externallyAllocatedMemory); } SerializedScriptValue::~SerializedScriptValue() { // If the allocated memory was not registered before, then this class is likely // used in a context other then Worker's onmessage environment and the presence of // current v8 context is not guaranteed. Avoid calling v8 then. if (m_externallyAllocatedMemory) { ASSERT(v8::Isolate::GetCurrent()); v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(-m_externallyAllocatedMemory); } } } // namespace WebCore
36.300033
219
0.621709
[ "object", "vector" ]
8da7b6b265dc40d880ee429973e0ceb58de4a2db
13,299
cc
C++
chromeos/services/secure_channel/bluetooth_helper_impl_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chromeos/services/secure_channel/bluetooth_helper_impl_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chromeos/services/secure_channel/bluetooth_helper_impl_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium 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 "chromeos/services/secure_channel/bluetooth_helper_impl.h" #include <memory> #include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" #include "chromeos/components/multidevice/remote_device_cache.h" #include "chromeos/components/multidevice/remote_device_test_util.h" #include "chromeos/services/secure_channel/ble_advertisement_generator.h" #include "chromeos/services/secure_channel/device_id_pair.h" #include "chromeos/services/secure_channel/fake_background_eid_generator.h" #include "chromeos/services/secure_channel/fake_ble_advertisement_generator.h" #include "chromeos/services/secure_channel/mock_foreground_eid_generator.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace secure_channel { namespace { const size_t kNumTestDevices = 3; const size_t kNumBytesInBackgroundAdvertisementServiceData = 2; const size_t kMinNumBytesInForegroundAdvertisementServiceData = 4; const char current_eid_data[] = "currentEidData"; const int64_t current_eid_start_ms = 1000L; const int64_t current_eid_end_ms = 2000L; const char adjacent_eid_data[] = "adjacentEidData"; const int64_t adjacent_eid_start_ms = 2000L; const int64_t adjacent_eid_end_ms = 3000L; const char fake_beacon_seed1_data[] = "fakeBeaconSeed1Data"; const int64_t fake_beacon_seed1_start_ms = current_eid_start_ms; const int64_t fake_beacon_seed1_end_ms = current_eid_end_ms; const char fake_beacon_seed2_data[] = "fakeBeaconSeed2Data"; const int64_t fake_beacon_seed2_start_ms = adjacent_eid_start_ms; const int64_t fake_beacon_seed2_end_ms = adjacent_eid_end_ms; std::unique_ptr<ForegroundEidGenerator::EidData> CreateFakeBackgroundScanFilter() { DataWithTimestamp current(current_eid_data, current_eid_start_ms, current_eid_end_ms); std::unique_ptr<DataWithTimestamp> adjacent = std::make_unique<DataWithTimestamp>( adjacent_eid_data, adjacent_eid_start_ms, adjacent_eid_end_ms); return std::make_unique<ForegroundEidGenerator::EidData>(current, std::move(adjacent)); } std::vector<multidevice::BeaconSeed> CreateFakeBeaconSeeds(int id) { std::string id_str = std::to_string(id); multidevice::BeaconSeed seed1( fake_beacon_seed1_data + id_str /* data */, base::Time::FromJavaTime(fake_beacon_seed1_start_ms * id) /* start_time */, base::Time::FromJavaTime(fake_beacon_seed1_end_ms * id) /* end_time */); multidevice::BeaconSeed seed2( fake_beacon_seed2_data + id_str /* data */, base::Time::FromJavaTime(fake_beacon_seed2_start_ms * id) /* start_time */, base::Time::FromJavaTime(fake_beacon_seed2_end_ms * id) /* end_time */); std::vector<multidevice::BeaconSeed> seeds = {seed1, seed2}; return seeds; } multidevice::RemoteDeviceRef CreateLocalDevice(int id) { return multidevice::RemoteDeviceRefBuilder() .SetInstanceId("local instance id " + base::NumberToString(id)) .SetPublicKey("local public key " + base::NumberToString(id)) .SetBeaconSeeds(CreateFakeBeaconSeeds(id)) .SetBluetoothPublicAddress(base::NumberToString(id)) .Build(); } } // namespace class SecureChannelBluetoothHelperImplTest : public testing::Test { public: SecureChannelBluetoothHelperImplTest( const SecureChannelBluetoothHelperImplTest&) = delete; SecureChannelBluetoothHelperImplTest& operator=( const SecureChannelBluetoothHelperImplTest&) = delete; protected: SecureChannelBluetoothHelperImplTest() : test_local_device_1_(CreateLocalDevice(1)), test_local_device_2_(CreateLocalDevice(2)), test_remote_devices_( multidevice::CreateRemoteDeviceRefListForTest(kNumTestDevices)), fake_advertisement_(DataWithTimestamp("advertisement1", 1000L, 2000L)) { device_id_pair_set_.emplace(test_remote_devices_[0].GetDeviceId(), test_local_device_1_.GetDeviceId()); device_id_pair_set_.emplace(test_remote_devices_[1].GetDeviceId(), test_local_device_1_.GetDeviceId()); device_id_pair_set_.emplace(test_remote_devices_[2].GetDeviceId(), test_local_device_2_.GetDeviceId()); } ~SecureChannelBluetoothHelperImplTest() override = default; // testing::Test: void SetUp() override { fake_ble_advertisement_generator_ = std::make_unique<FakeBleAdvertisementGenerator>(); BleAdvertisementGenerator::SetInstanceForTesting( fake_ble_advertisement_generator_.get()); fake_ble_advertisement_generator_->set_advertisement( std::make_unique<DataWithTimestamp>(fake_advertisement_)); auto mock_foreground_eid_generator = std::make_unique<MockForegroundEidGenerator>(); mock_foreground_eid_generator_ = mock_foreground_eid_generator.get(); mock_foreground_eid_generator_->set_background_scan_filter( CreateFakeBackgroundScanFilter()); auto fake_background_eid_generator = std::make_unique<FakeBackgroundEidGenerator>(); fake_background_eid_generator_ = fake_background_eid_generator.get(); remote_device_cache_ = multidevice::RemoteDeviceCache::Factory::Create(); multidevice::RemoteDeviceList devices; devices.push_back( *multidevice::GetMutableRemoteDevice(test_local_device_1_)); devices.push_back( *multidevice::GetMutableRemoteDevice(test_local_device_2_)); std::transform( test_remote_devices_.begin(), test_remote_devices_.end(), std::back_inserter(devices), [](auto remote_device_ref) { return *multidevice::GetMutableRemoteDevice(remote_device_ref); }); remote_device_cache_->SetRemoteDevices(devices); helper_ = BluetoothHelperImpl::Factory::Create(remote_device_cache_.get()); static_cast<BluetoothHelperImpl*>(helper_.get()) ->SetTestDoubles(std::move(fake_background_eid_generator), std::move(mock_foreground_eid_generator)); } void TearDown() override { BleAdvertisementGenerator::SetInstanceForTesting(nullptr); } std::unique_ptr<FakeBleAdvertisementGenerator> fake_ble_advertisement_generator_; MockForegroundEidGenerator* mock_foreground_eid_generator_; FakeBackgroundEidGenerator* fake_background_eid_generator_; std::unique_ptr<multidevice::RemoteDeviceCache> remote_device_cache_; std::unique_ptr<BluetoothHelper> helper_; multidevice::RemoteDeviceRef test_local_device_1_; multidevice::RemoteDeviceRef test_local_device_2_; multidevice::RemoteDeviceRefList test_remote_devices_; DeviceIdPairSet device_id_pair_set_; DataWithTimestamp fake_advertisement_; }; TEST_F(SecureChannelBluetoothHelperImplTest, TestGenerateForegroundAdvertisement_CannotGenerateAdvertisement) { fake_ble_advertisement_generator_->set_advertisement(nullptr); EXPECT_FALSE(helper_->GenerateForegroundAdvertisement( DeviceIdPair(test_remote_devices_[0].GetDeviceId() /* remote_device_id */, test_local_device_1_.GetDeviceId() /* local_device_id */))); } TEST_F(SecureChannelBluetoothHelperImplTest, TestGenerateForegroundAdvertisement) { auto data_with_timestamp = helper_->GenerateForegroundAdvertisement( DeviceIdPair(test_remote_devices_[0].GetDeviceId() /* remote_device_id */, test_local_device_1_.GetDeviceId() /* local_device_id */)); EXPECT_EQ(fake_advertisement_, *data_with_timestamp); } TEST_F(SecureChannelBluetoothHelperImplTest, TestGenerateForegroundAdvertisement_InvalidLocalDevice) { EXPECT_FALSE(helper_->GenerateForegroundAdvertisement( DeviceIdPair(test_remote_devices_[0].GetDeviceId() /* remote_device_id */, "invalid local device id" /* local_device_id */))); } TEST_F(SecureChannelBluetoothHelperImplTest, TestGenerateForegroundAdvertisement_InvalidRemoteDevice) { EXPECT_FALSE(helper_->GenerateForegroundAdvertisement( DeviceIdPair("invalid remote device id" /* remote_device_id */, test_local_device_1_.GetDeviceId() /* local_device_id */))); } TEST_F(SecureChannelBluetoothHelperImplTest, TestIdentifyRemoteDevice_InvalidAdvertisementLength) { std::string invalid_service_data = "a"; mock_foreground_eid_generator_->set_identified_device_id( test_remote_devices_[0].GetDeviceId()); auto device_with_background_bool = helper_->IdentifyRemoteDevice(invalid_service_data, device_id_pair_set_); EXPECT_EQ(0, mock_foreground_eid_generator_->num_identify_calls()); EXPECT_EQ(0, fake_background_eid_generator_->num_identify_calls()); EXPECT_FALSE(device_with_background_bool); } TEST_F(SecureChannelBluetoothHelperImplTest, TestIdentifyRemoteDevice_ForegroundAdvertisement) { std::string valid_service_data_for_registered_device = "abcde"; ASSERT_TRUE(valid_service_data_for_registered_device.size() >= kMinNumBytesInForegroundAdvertisementServiceData); mock_foreground_eid_generator_->set_identified_device_id( test_remote_devices_[0].GetDeviceId()); auto device_with_background_bool = helper_->IdentifyRemoteDevice( valid_service_data_for_registered_device, device_id_pair_set_); EXPECT_EQ(1, mock_foreground_eid_generator_->num_identify_calls()); EXPECT_EQ(0, fake_background_eid_generator_->num_identify_calls()); EXPECT_EQ(test_remote_devices_[0].GetDeviceId(), device_with_background_bool->first.GetDeviceId()); EXPECT_FALSE(device_with_background_bool->second); // Ensure that other local device IDs in device_id_pair_set_ are considered. mock_foreground_eid_generator_->set_identified_device_id( test_remote_devices_[2].GetDeviceId()); device_with_background_bool = helper_->IdentifyRemoteDevice( valid_service_data_for_registered_device, device_id_pair_set_); EXPECT_EQ(0, fake_background_eid_generator_->num_identify_calls()); EXPECT_EQ(test_remote_devices_[2].GetDeviceId(), device_with_background_bool->first.GetDeviceId()); EXPECT_FALSE(device_with_background_bool->second); } TEST_F(SecureChannelBluetoothHelperImplTest, TestIdentifyRemoteDevice_ForegroundAdvertisement_NoRegisteredDevice) { std::string valid_service_data = "abcde"; ASSERT_TRUE(valid_service_data.size() >= kMinNumBytesInForegroundAdvertisementServiceData); auto device_with_background_bool = helper_->IdentifyRemoteDevice(valid_service_data, device_id_pair_set_); EXPECT_EQ(2, mock_foreground_eid_generator_->num_identify_calls()); EXPECT_EQ(0, fake_background_eid_generator_->num_identify_calls()); EXPECT_FALSE(device_with_background_bool); } TEST_F(SecureChannelBluetoothHelperImplTest, TestIdentifyRemoteDevice_BackgroundAdvertisement) { std::string valid_service_data_for_registered_device = "ab"; ASSERT_TRUE(valid_service_data_for_registered_device.size() >= kNumBytesInBackgroundAdvertisementServiceData); fake_background_eid_generator_->set_identified_device_id( test_remote_devices_[0].GetDeviceId()); auto device_with_background_bool = helper_->IdentifyRemoteDevice( valid_service_data_for_registered_device, device_id_pair_set_); EXPECT_EQ(0, mock_foreground_eid_generator_->num_identify_calls()); EXPECT_EQ(1, fake_background_eid_generator_->num_identify_calls()); EXPECT_EQ(test_remote_devices_[0].GetDeviceId(), device_with_background_bool->first.GetDeviceId()); EXPECT_TRUE(device_with_background_bool->second); // Ensure that other local device IDs in device_id_pair_set_ are considered. fake_background_eid_generator_->set_identified_device_id( test_remote_devices_[2].GetDeviceId()); device_with_background_bool = helper_->IdentifyRemoteDevice( valid_service_data_for_registered_device, device_id_pair_set_); EXPECT_EQ(0, mock_foreground_eid_generator_->num_identify_calls()); EXPECT_EQ(test_remote_devices_[2].GetDeviceId(), device_with_background_bool->first.GetDeviceId()); EXPECT_TRUE(device_with_background_bool->second); } TEST_F(SecureChannelBluetoothHelperImplTest, TestIdentifyRemoteDevice_BackgroundAdvertisement_NoRegisteredDevice) { std::string valid_service_data_for_registered_device = "ab"; ASSERT_TRUE(valid_service_data_for_registered_device.size() >= kNumBytesInBackgroundAdvertisementServiceData); auto device_with_background_bool = helper_->IdentifyRemoteDevice( valid_service_data_for_registered_device, device_id_pair_set_); EXPECT_EQ(0, mock_foreground_eid_generator_->num_identify_calls()); EXPECT_EQ(2, fake_background_eid_generator_->num_identify_calls()); EXPECT_FALSE(device_with_background_bool); } TEST_F(SecureChannelBluetoothHelperImplTest, BluetoothPublicAddress) { EXPECT_EQ("1", test_local_device_1_.bluetooth_public_address()); EXPECT_EQ("1", helper_->GetBluetoothPublicAddress( test_local_device_1_.GetDeviceId())); } } // namespace secure_channel } // namespace chromeos
41.689655
80
0.7766
[ "vector", "transform" ]
8da8fed354ed7b66648cb356825da37bba1b3187
7,718
cpp
C++
Extensions/Template/Extension.cpp
rickomax/VoxObject
f788e484fa060c00a29867f25192f3fbda8c63b1
[ "MIT" ]
1
2021-02-01T03:24:12.000Z
2021-02-01T03:24:12.000Z
Extensions/Template/Extension.cpp
rickomax/VoxObject
f788e484fa060c00a29867f25192f3fbda8c63b1
[ "MIT" ]
null
null
null
Extensions/Template/Extension.cpp
rickomax/VoxObject
f788e484fa060c00a29867f25192f3fbda8c63b1
[ "MIT" ]
null
null
null
/* Extension.cpp * This file contains the definitions for * your extension's general runtime functions, * such as the constructor and destructor, * handling routines, etc. * Functions defined here: * Extension::Extension <constructor> * Extension::~Extension <destructor> * Extension::Handle * Extension::Display * Extension::Pause * Extension::Continue * Extension::Save * Extension::Load * Extension::Action <--| * Extension::Condition <--|- not what you think! * Extension::Expression <--| */ #include "Common.h" #include "EffectEx.h" #include <comdef.h> /* <constructor> * This is your extension's constructor, which * is the replacement for the old CreateRunObject * function. You don't need to manually call * constructors or pointlessly initialize * pointers with dynamic memory. Just link * your A/C/Es, perform initialization steps, and * you're good to go. */ Extension::Extension(RD *rd, SerializedED *SED, createObjectInfo *COB) : rd(rd) , rh(rd->rHo.hoAdRunHeader) , Runtime(rd) { //Link all your action/condition/expression functions //to their IDs to match the IDs in the JSON here. LinkAction(0, SetLocalAngleX); LinkAction(1, SetLocalAngleY); LinkAction(2, SetLocalAngleZ); LinkAction(3, SetLocalScale); LinkAction(4, SetCurrentFrame); LinkAction(5, ProjectPosition); LinkAction(6, LoadLight); LinkCondition(0, IsProjectedZBehind); LinkCondition(1, IsProjectedZInTheFront) LinkExpression(0, GetLocalAngleX); LinkExpression(1, GetLocalAngleY); LinkExpression(2, GetLocalAngleZ); LinkExpression(3, GetCurrentFrame); LinkExpression(4, GetDepthSize); LinkExpression(5, GetProjectedX); LinkExpression(6, GetProjectedY); LPRH rhPtr = rd->rHo.hoAdRunHeader; mv* mV = rhPtr->rh4.rh4Mv; vox = new Vox(); EditData ed(SED, mV, false, vox); LPSURFACE windowSurface = WinGetSurface((int)rhPtr->rhIdEditWin); LPSURFACE proto = NULL; GetSurfacePrototype(&proto, windowSurface->GetDepth(), ST_MEMORYWITHDC, SD_DIB); vox->surface = NewSurface(); vox->surface->Create(vox->width, vox->height, proto); vox->surface->CreateAlpha(); VoxLight::surface = NewSurface(); VoxLight::surface->Create(8, 8, proto); LPSURFACE hwaProto = NULL; GetSurfacePrototype(&hwaProto, windowSurface->GetDepth(), ST_HWA_ROMTEXTURE, SD_D3D9); VoxLight::hwaSurface = NewSurface(); VoxLight::hwaSurface->Create(8, 8, hwaProto); //VoxLight::surface->CreateAlpha(); rd->rHo.hoImgWidth = vox->width; rd->rHo.hoImgHeight = vox->height; } /* <destructor> * This is your extension's destructor, the * replacement for DestroyRunObject. No calling * destructors manually or deallocating pointless * dynamic memory - in most cases this function * won't need any code written. */ Extension::~Extension() { // } /* Handle * Fusion calls this function to let your extension * "live" - if you want, you can have Fusion call this * every frame. This is where you'd, for instance, * simulate physics or move an object. This is * the analagous function to the old HandleRunObject. */ short Extension::Handle() { if (vox->animateMovements) { float desiredAngle = ((rd->rc->rcDir / 32.0f) * 360.0f) - vox->angleOffsetY; vox->localAngleY = Vox::LerpAngle(vox->localAngleY, desiredAngle, 0.25f); if (vox->voxAnimation != nullptr) { if (rd->rc->rcSpeed > 0) { vox->SetAnimation(rd->rc->rcAnim); } else { vox->SetAnimation(0); } float speedFactor = InverseLerp((float)rd->rc->rcMinSpeed, (float)rd->rc->rcMaxSpeed, (float)rd->rc->rcSpeed); float frameInterval = (1.0f / mathfu::Lerp<float>(vox->voxAnimation->minSpeed, vox->voxAnimation->maxSpeed, speedFactor)) * 1000.0f; float passedFrames = rd->rHo.hoAdRunHeader->rhTimerDelta / frameInterval; vox->voxAnimation->currentFrame += passedFrames; } } return REFLAG_DISPLAY; } /* Display * This is the analagous function to * DisplayRunObject. If you return * REFLAG_DISPLAY in Handle() this * routine will run. If you want Fusion * to apply ink effects for you, then * implement GetRunObjectSurface in * Runtime.cpp instead. */ short Extension::Display() { if (vox->voxAnimation == nullptr || !vox->voxAnimation->loaded) { return 0; } LPRH rhPtr = rd->rHo.hoAdRunHeader; LPSURFACE windowSurface = WinGetSurface((int)rhPtr->rhIdEditWin); RECT* rect = &rd->rHo.hoRect; int x = rect->left; int y = rect->top; int width = rd->rHo.hoImgWidth; int height = rd->rHo.hoImgHeight; BlitMode bm = (rd->rs->rsEffect & EFFECTFLAG_TRANSPARENT) ? BMODE_TRANSP : BMODE_OPAQUE; BOOL bAntiA = (rd->rs->rsEffect & EFFECTFLAG_ANTIALIAS) ? TRUE : FALSE; BlitOp bo = (BlitOp)(rd->rs->rsEffect & EFFECT_MASK); DWORD effectParam = rd->rs->rsEffectParam; if (rd->rs->rsEffect & BOP_EFFECTEX && vox->depthAsAlpha) { CEffectEx* pEffectEx = (CEffectEx*)effectParam; if (pEffectEx != nullptr) { #ifdef _UNICODE _bstr_t a(vox->positionParameterX.c_str()); _bstr_t b(vox->positionParameterY.c_str()); _bstr_t c(vox->depthSizeParameter.c_str()); int positionXParamIndex = pEffectEx->GetParamIndex(a); int positionYParamIndex = pEffectEx->GetParamIndex(b); int depthSizeParamIndex = pEffectEx->GetParamIndex(c); #else int positionXParamIndex = pEffectEx->GetParamIndex(vox->positionParameterX.c_str()); int positionYParamIndex = pEffectEx->GetParamIndex(vox->positionParameterY.c_str()); int depthSizeParamIndex = pEffectEx->GetParamIndex(vox->depthSizeParameter.c_str()); #endif if (positionXParamIndex >= 0) pEffectEx->SetParamFloatValue(positionXParamIndex, x); if (positionYParamIndex >= 0) pEffectEx->SetParamFloatValue(positionYParamIndex, y); if (depthSizeParamIndex >= 0) pEffectEx->SetParamFloatValue(depthSizeParamIndex, vox->voxAnimation->depthSize); int lightSurfaceParamIndex = pEffectEx->GetParamIndex("lightSurface"); if (lightSurfaceParamIndex >= 0) pEffectEx->SetParamSurfaceValue(lightSurfaceParamIndex, GetSurfaceImplementation(*VoxLight::hwaSurface)); } } vox->DrawToSurface(windowSurface, x, y, width, height, bAntiA, bm, bo, (int)effectParam, false); WinAddZone(rhPtr->rhIdEditWin, rect); return 0; } /* Pause * If your extension plays sound, for * example, then Fusion calls this to * let you know to pause the music, * usually by another extension's request * or by the player pausing the applcation. */ short Extension::Pause() { return 0; } /* Continue * Opposite to the above, Fusion lets * you know that the silence is over; * your extension may live again. */ short Extension::Continue() { return 0; } /* Save * When the user uses the Save * Frame Position action, you need * so serialize your runtime data to * the File given. It is a Windows * file handle, but you can use some * of Fusion's built-in functions for * writing files. Check the MMF2SDK * Help file for more information. */ bool Extension::Save(HANDLE File) { return true; } /* Load * As opposed to above, here you need to * restore your extension's runtime state * from the given file. Only read what you * wrote! */ bool Extension::Load(HANDLE File) { return true; } /* Action, Condition, Expression * These are called if there's no function linked * to an ID. You may want to put MessageBox calls * to let you know that the ID is unlinked, or you * may just want to use unlinked A/C/Es as a feature. */ void Extension::Action(int ID, RD *rd, long param1, long param2) { } long Extension::Condition(int ID, RD *rd, long param1, long param2) { return false; //hopefully StringComparison (PARAM_CMPSTRING) is not used, or this may crash } long Extension::Expression(int ID, RD *rd, long param) { return long(_T("")); //so that unlinked expressions that return strings won't crash }
30.505929
141
0.725058
[ "object" ]
8dab3b0bfae0cf1da097dd0d511f10b794ea48bc
2,487
cpp
C++
Uva/Uva_AC/10189-Minesweeper.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
3
2018-05-11T07:33:20.000Z
2020-08-30T11:02:02.000Z
Uva/Uva_AC/10189-Minesweeper.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
1
2018-05-11T18:10:26.000Z
2018-05-12T18:00:28.000Z
Uva/Uva_AC/10189-Minesweeper.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
null
null
null
/*************************************************** * Problem name : 10189-Minesweeper.cpp * Problem Link : https://uva.onlinejudge.org/external/101/10189.pdf * OJ : Uva * Verdict : AC * Date : 2018-04-29 * Problem Type : Adhoc * Author Name : Saikat Sharma * University : CSE,MBSTU ***************************************************/ #include<iostream> #include<cstdio> #include<algorithm> #include<climits> #include<cstring> #include<string> #include<sstream> #include<cmath> #include<vector> #include<queue> #include<cstdlib> #include<deque> #include<stack> #include<map> #include<set> #define __FastIO ios_base::sync_with_stdio(false); cin.tie(0) #define SET(a,v) memset(a,v,sizeof(a)) #define pii pair<int,int> #define pll pair <int, int> #define debug printf("#########\n") #define nl printf("\n") #define sp printf(" ") #define sl(n) scanf("%lld", &n) #define sf(n) scanf("%lf", &n) #define si(n) scanf("%d", &n) #define ss(n) scanf("%s", n) #define pf(n) scanf("%d", n) #define pfl(n) scanf("%lld", n) #define pb push_back #define MAX 105 #define INF 1000000000 using namespace std; typedef long long ll; typedef unsigned long long ull; template <typename T> std::string NumberToString ( T Number ) { std::ostringstream ss; ss << Number; return ss.str(); } ll lcm(ll a, ll b) { return a * b / __gcd(a, b); } /************************************ Code Start Here ******************************************************/ int fx[] = {1, -1, 0, 0, 1, -1, -1, 1}; int fy[] = {0, 0, 1, -1, 1, -1, 1, -1}; int n, m; string str[MAX]; bool isValid(int x, int y) { if ( x >= 0 && y >= 0 && x < n && y < m) return true; return false; } int howMany(int x, int y) { int cnt = 0; for (int i = 0; i < 8; i++) { int xx = x + fx[i]; int yy = y + fy[i]; if (isValid(xx, yy) && str[xx][yy] == '*')cnt++; } return cnt; } int main () { int t = 1; while (scanf("%d %d", &n, &m) == 2 && n != 0 && m != 0) { for(int i = 0; i<n; i++){ cin >> str[i]; } if(t != 1) nl; printf("Field #%d:\n", t++); for(int i = 0; i<n; i++){ for(int j = 0; j<m; j++){ if(str[i][j] == '*') { //~ ans[i][j] = '*'; cout << str[i][j]; } else { cout << howMany(i, j); } } nl; } } return 0; }
25.90625
109
0.469642
[ "vector" ]
8dab49c063a0800a6b1768600b81ce9210c9f82e
974
hpp
C++
include/game/StarField.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
2
2022-03-17T18:11:07.000Z
2022-03-17T19:55:35.000Z
include/game/StarField.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
null
null
null
include/game/StarField.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
null
null
null
#pragma once //#include <random> #include "Maths.hpp" #include "GraphicsObjects.hpp" struct Star { Framework::vec2 position; // Size also dictates speed of movement uint8_t size; Framework::Colour colour; }; class StarField { public: struct StarFieldConstants { uint32_t large_stars = 10; uint32_t medium_stars = 20; uint32_t small_stars = 40; uint8_t large_star_size = 4; uint8_t medium_star_size = 2; uint8_t small_star_size = 1; float distance_scale = 0.001f; uint8_t colour_change_from_white = 0x40; }; StarField(); StarField(Framework::Graphics* graphics, Framework::vec2 size); void set_constants(const StarFieldConstants& constants); void render(); // Set the position of the centre of the StarField void move(Framework::vec2 distance); private: void make_stars(uint32_t count, uint8_t size); Framework::Graphics* _graphics = nullptr; std::vector<Star> _stars; Framework::vec2 _size; StarFieldConstants _constants; };
18.730769
64
0.743326
[ "render", "vector" ]
8db037a258fde6baa73283871b9448dfaad9192e
27,878
cc
C++
src/yb/tablet/tablet_metadata.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
1
2021-01-15T00:24:31.000Z
2021-01-15T00:24:31.000Z
src/yb/tablet/tablet_metadata.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/tablet/tablet_metadata.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, Inc. // // 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 "yb/tablet/tablet_metadata.h" #include <algorithm> #include <mutex> #include <string> #include <gflags/gflags.h> #include <boost/optional.hpp> #include "yb/rocksdb/db.h" #include "yb/rocksdb/options.h" #include "yb/common/wire_protocol.h" #include "yb/consensus/opid_util.h" #include "yb/docdb/docdb_rocksdb_util.h" #include "yb/gutil/atomicops.h" #include "yb/gutil/bind.h" #include "yb/gutil/dynamic_annotations.h" #include "yb/gutil/map-util.h" #include "yb/gutil/stl_util.h" #include "yb/gutil/strings/substitute.h" #include "yb/rocksutil/yb_rocksdb.h" #include "yb/rocksutil/yb_rocksdb_logger.h" #include "yb/server/metadata.h" #include "yb/tablet/rowset_metadata.h" #include "yb/tablet/tablet_options.h" #include "yb/util/debug/trace_event.h" #include "yb/util/flag_tags.h" #include "yb/util/logging.h" #include "yb/util/pb_util.h" #include "yb/util/random.h" #include "yb/util/status.h" #include "yb/util/trace.h" DEFINE_bool(enable_tablet_orphaned_block_deletion, true, "Whether to enable deletion of orphaned blocks from disk. " "Note: This is only exposed for debugging purposes!"); TAG_FLAG(enable_tablet_orphaned_block_deletion, advanced); TAG_FLAG(enable_tablet_orphaned_block_deletion, hidden); TAG_FLAG(enable_tablet_orphaned_block_deletion, runtime); using std::shared_ptr; using base::subtle::Barrier_AtomicIncrement; using strings::Substitute; using yb::consensus::MinimumOpId; using yb::consensus::RaftConfigPB; namespace yb { namespace tablet { const int64 kNoDurableMemStore = -1; // ============================================================================ // Tablet Metadata // ============================================================================ Status TabletMetadata::CreateNew(FsManager* fs_manager, const string& table_id, const string& tablet_id, const string& table_name, const TableType table_type, const Schema& schema, const PartitionSchema& partition_schema, const Partition& partition, const TabletDataState& initial_tablet_data_state, scoped_refptr<TabletMetadata>* metadata, const string& data_root_dir, const string& wal_root_dir) { // Verify that no existing tablet exists with the same ID. if (fs_manager->env()->FileExists(fs_manager->GetTabletMetadataPath(tablet_id))) { return STATUS(AlreadyPresent, "Tablet already exists", tablet_id); } auto wal_top_dir = wal_root_dir; auto data_top_dir = data_root_dir; // Use the original randomized logic if the indices are not explicitly passed in yb::Random rand(GetCurrentTimeMicros()); if (data_root_dir.empty()) { auto data_root_dirs = fs_manager->GetDataRootDirs(); CHECK(!data_root_dirs.empty()) << "No data root directories found"; data_top_dir = data_root_dirs[rand.Uniform(data_root_dirs.size())]; } if (wal_root_dir.empty()) { auto wal_root_dirs = fs_manager->GetWalRootDirs(); CHECK(!wal_root_dirs.empty()) << "No wal root directories found"; wal_top_dir = wal_root_dirs[rand.Uniform(wal_root_dirs.size())]; } auto wal_table_top_dir = JoinPathSegments(wal_top_dir, Substitute("table-$0", table_id)); auto wal_dir = JoinPathSegments(wal_table_top_dir, Substitute("tablet-$0", tablet_id)); auto rocksdb_top_dir = JoinPathSegments(data_top_dir, FsManager::kRocksDBDirName); auto rocksdb_table_top_dir = JoinPathSegments(rocksdb_top_dir, Substitute("table-$0", table_id)); auto rocksdb_dir = JoinPathSegments(rocksdb_table_top_dir, Substitute("tablet-$0", tablet_id)); scoped_refptr<TabletMetadata> ret(new TabletMetadata(fs_manager, table_id, tablet_id, table_name, table_type, rocksdb_dir, wal_dir, schema, partition_schema, partition, initial_tablet_data_state)); RETURN_NOT_OK(ret->Flush()); metadata->swap(ret); return Status::OK(); } Status TabletMetadata::Load(FsManager* fs_manager, const string& tablet_id, scoped_refptr<TabletMetadata>* metadata) { scoped_refptr<TabletMetadata> ret(new TabletMetadata(fs_manager, tablet_id)); RETURN_NOT_OK(ret->LoadFromDisk()); metadata->swap(ret); return Status::OK(); } Status TabletMetadata::LoadOrCreate(FsManager* fs_manager, const string& table_id, const string& tablet_id, const string& table_name, TableType table_type, const Schema& schema, const PartitionSchema& partition_schema, const Partition& partition, const TabletDataState& initial_tablet_data_state, scoped_refptr<TabletMetadata>* metadata) { Status s = Load(fs_manager, tablet_id, metadata); if (s.ok()) { if (!(*metadata)->schema().Equals(schema)) { return STATUS(Corruption, Substitute("Schema on disk ($0) does not " "match expected schema ($1)", (*metadata)->schema().ToString(), schema.ToString())); } return Status::OK(); } else if (s.IsNotFound()) { return CreateNew(fs_manager, table_id, tablet_id, table_name, table_type, schema, partition_schema, partition, initial_tablet_data_state, metadata); } else { return s; } } Status TabletMetadata::TEST_CreateDummyWithSchema(scoped_refptr<TabletMetadata>* metadata, const Schema& schema) { scoped_refptr<TabletMetadata> ret(new TabletMetadata(nullptr, "test_tablet")); RETURN_NOT_OK(ret->Flush()); metadata->swap(ret); metadata->get()->SetSchema(schema, 0); return Status::OK(); } void TabletMetadata::CollectBlockIdPBs(const TabletSuperBlockPB& superblock, std::vector<BlockIdPB>* block_ids) { for (const RowSetDataPB& rowset : superblock.rowsets()) { for (const ColumnDataPB& column : rowset.columns()) { block_ids->push_back(column.block()); } for (const DeltaDataPB& redo : rowset.redo_deltas()) { block_ids->push_back(redo.block()); } for (const DeltaDataPB& undo : rowset.undo_deltas()) { block_ids->push_back(undo.block()); } if (rowset.has_bloom_block()) { block_ids->push_back(rowset.bloom_block()); } if (rowset.has_adhoc_index_block()) { block_ids->push_back(rowset.adhoc_index_block()); } } } Status TabletMetadata::DeleteTabletData(TabletDataState delete_type, const boost::optional<consensus::OpId>& last_logged_opid) { CHECK(delete_type == TABLET_DATA_DELETED || delete_type == TABLET_DATA_TOMBSTONED) << "DeleteTabletData() called with unsupported delete_type on tablet " << tablet_id_ << ": " << TabletDataState_Name(delete_type) << " (" << delete_type << ")"; // First add all of our blocks to the orphan list // and clear our rowsets. This serves to erase all the data. // // We also set the state in our persisted metadata to indicate that // we have been deleted. { std::lock_guard<LockType> l(data_lock_); for (const shared_ptr<RowSetMetadata>& rsmd : rowsets_) { AddOrphanedBlocksUnlocked(rsmd->GetAllBlocks()); } rowsets_.clear(); tablet_data_state_ = delete_type; if (last_logged_opid) { tombstone_last_logged_opid_ = *last_logged_opid; } } if (table_type_ != TableType::KUDU_COLUMNAR_TABLE_TYPE) { rocksdb::Options rocksdb_options; TabletOptions tablet_options; docdb::InitRocksDBOptions( &rocksdb_options, tablet_id_, nullptr /* statistics */, tablet_options); LOG(INFO) << "Destroying RocksDB at: " << rocksdb_dir_; rocksdb::Status status = rocksdb::DestroyDB(rocksdb_dir_, rocksdb_options); if (!status.ok()) { LOG(ERROR) << "Failed to destroy RocksDB at: " << rocksdb_dir_ << ": " << status.ToString(); } else { LOG(INFO) << "Successfully destroyed RocksDB at: " << rocksdb_dir_; } } // Flushing will sync the new tablet_data_state_ to disk and will now also // delete all the data. RETURN_NOT_OK(Flush()); // Re-sync to disk one more time. // This call will typically re-sync with an empty orphaned blocks list // (unless deleting any orphans failed during the last Flush()), so that we // don't try to re-delete the deleted orphaned blocks on every startup. return Flush(); } Status TabletMetadata::DeleteSuperBlock() { std::lock_guard<LockType> l(data_lock_); if (!orphaned_blocks_.empty()) { return STATUS(InvalidArgument, "The metadata for tablet " + tablet_id_ + " still references orphaned blocks. " "Call DeleteTabletData() first"); } if (tablet_data_state_ != TABLET_DATA_DELETED) { return STATUS(IllegalState, Substitute("Tablet $0 is not in TABLET_DATA_DELETED state. " "Call DeleteTabletData(TABLET_DATA_DELETED) first. " "Tablet data state: $1 ($2)", tablet_id_, TabletDataState_Name(tablet_data_state_), tablet_data_state_)); } string path = fs_manager_->GetTabletMetadataPath(tablet_id_); RETURN_NOT_OK_PREPEND(fs_manager_->env()->DeleteFile(path), "Unable to delete superblock for tablet " + tablet_id_); return Status::OK(); } TabletMetadata::TabletMetadata(FsManager* fs_manager, string table_id, string tablet_id, string table_name, TableType table_type, const string rocksdb_dir, const string wal_dir, const Schema& schema, PartitionSchema partition_schema, Partition partition, const TabletDataState& tablet_data_state) : state_(kNotWrittenYet), table_id_(std::move(table_id)), tablet_id_(std::move(tablet_id)), partition_(std::move(partition)), fs_manager_(fs_manager), next_rowset_idx_(0), last_durable_mrs_id_(kNoDurableMemStore), schema_(new Schema(schema)), schema_version_(0), table_name_(std::move(table_name)), table_type_(table_type), rocksdb_dir_(rocksdb_dir), wal_dir_(wal_dir), partition_schema_(std::move(partition_schema)), tablet_data_state_(tablet_data_state), tombstone_last_logged_opid_(MinimumOpId()), num_flush_pins_(0), needs_flush_(false), pre_flush_callback_(Bind(DoNothingStatusClosure)) { CHECK(schema_->has_column_ids()); CHECK_GT(schema_->num_key_columns(), 0); } TabletMetadata::~TabletMetadata() { STLDeleteElements(&old_schemas_); delete schema_; } TabletMetadata::TabletMetadata(FsManager* fs_manager, string tablet_id) : state_(kNotLoadedYet), tablet_id_(std::move(tablet_id)), fs_manager_(fs_manager), next_rowset_idx_(0), schema_(nullptr), tombstone_last_logged_opid_(MinimumOpId()), num_flush_pins_(0), needs_flush_(false), pre_flush_callback_(Bind(DoNothingStatusClosure)) {} Status TabletMetadata::LoadFromDisk() { TRACE_EVENT1("tablet", "TabletMetadata::LoadFromDisk", "tablet_id", tablet_id_); CHECK_EQ(state_, kNotLoadedYet); TabletSuperBlockPB superblock; RETURN_NOT_OK(ReadSuperBlockFromDisk(&superblock)); RETURN_NOT_OK_PREPEND(LoadFromSuperBlock(superblock), "Failed to load data from superblock protobuf"); state_ = kInitialized; return Status::OK(); } Status TabletMetadata::LoadFromSuperBlock(const TabletSuperBlockPB& superblock) { vector<BlockId> orphaned_blocks; VLOG(2) << "Loading TabletMetadata from SuperBlockPB:" << std::endl << superblock.DebugString(); { std::lock_guard<LockType> l(data_lock_); // Verify that the tablet id matches with the one in the protobuf if (superblock.tablet_id() != tablet_id_) { return STATUS(Corruption, "Expected id=" + tablet_id_ + " found " + superblock.tablet_id(), superblock.DebugString()); } table_id_ = superblock.table_id(); last_durable_mrs_id_ = superblock.last_durable_mrs_id(); table_name_ = superblock.table_name(); table_type_ = superblock.table_type(); rocksdb_dir_ = superblock.rocksdb_dir(); wal_dir_ = superblock.wal_dir(); uint32_t schema_version = superblock.schema_version(); gscoped_ptr<Schema> schema(new Schema()); RETURN_NOT_OK_PREPEND(SchemaFromPB(superblock.schema(), schema.get()), "Failed to parse Schema from superblock " + superblock.ShortDebugString()); SetSchemaUnlocked(schema.Pass(), schema_version); // This check provides backwards compatibility with the // flexible-partitioning changes introduced in KUDU-818. if (superblock.has_partition()) { RETURN_NOT_OK(PartitionSchema::FromPB(superblock.partition_schema(), *schema_, &partition_schema_)); Partition::FromPB(superblock.partition(), &partition_); } else { LOG(FATAL) << "partition field must be set in superblock: " << superblock.ShortDebugString(); } tablet_data_state_ = superblock.tablet_data_state(); deleted_cols_.clear(); for (const DeletedColumnPB& deleted_col : superblock.deleted_cols()) { DeletedColumn col; RETURN_NOT_OK(DeletedColumn::FromPB(deleted_col, &col)); deleted_cols_.push_back(col); } rowsets_.clear(); for (const RowSetDataPB& rowset_pb : superblock.rowsets()) { gscoped_ptr<RowSetMetadata> rowset_meta; RETURN_NOT_OK(RowSetMetadata::Load(this, rowset_pb, &rowset_meta)); next_rowset_idx_ = std::max(next_rowset_idx_, rowset_meta->id() + 1); rowsets_.push_back(shared_ptr<RowSetMetadata>(rowset_meta.release())); } for (const BlockIdPB& block_pb : superblock.orphaned_blocks()) { orphaned_blocks.push_back(BlockId::FromPB(block_pb)); } AddOrphanedBlocksUnlocked(orphaned_blocks); if (superblock.has_tombstone_last_logged_opid()) { tombstone_last_logged_opid_ = superblock.tombstone_last_logged_opid(); } else { tombstone_last_logged_opid_ = MinimumOpId(); } } // Now is a good time to clean up any orphaned blocks that may have been // left behind from a crash just after replacing the superblock. if (!fs_manager()->read_only()) { DeleteOrphanedBlocks(orphaned_blocks); } return Status::OK(); } Status TabletMetadata::UpdateAndFlush(const RowSetMetadataIds& to_remove, const RowSetMetadataVector& to_add, int64_t last_durable_mrs_id) { { std::lock_guard<LockType> l(data_lock_); RETURN_NOT_OK(UpdateUnlocked(to_remove, to_add, last_durable_mrs_id)); } return Flush(); } void TabletMetadata::AddOrphanedBlocks(const vector<BlockId>& blocks) { std::lock_guard<LockType> l(data_lock_); AddOrphanedBlocksUnlocked(blocks); } void TabletMetadata::AddOrphanedBlocksUnlocked(const vector<BlockId>& blocks) { DCHECK(data_lock_.is_locked()); orphaned_blocks_.insert(blocks.begin(), blocks.end()); } void TabletMetadata::DeleteOrphanedBlocks(const vector<BlockId>& blocks) { if (PREDICT_FALSE(!FLAGS_enable_tablet_orphaned_block_deletion)) { LOG_WITH_PREFIX(WARNING) << "Not deleting " << blocks.size() << " block(s) from disk. Block deletion disabled via " << "--enable_tablet_orphaned_block_deletion=false"; return; } vector<BlockId> deleted; for (const BlockId& b : blocks) { Status s = fs_manager()->DeleteBlock(b); // If we get NotFound, then the block was actually successfully // deleted before. So, we can remove it from our orphaned block list // as if it was a success. if (!s.ok() && !s.IsNotFound()) { WARN_NOT_OK(s, Substitute("Could not delete block $0", b.ToString())); continue; } deleted.push_back(b); } // Remove the successfully-deleted blocks from the set. { std::lock_guard<LockType> l(data_lock_); for (const BlockId& b : deleted) { orphaned_blocks_.erase(b); } } } void TabletMetadata::PinFlush() { std::lock_guard<LockType> l(data_lock_); CHECK_GE(num_flush_pins_, 0); num_flush_pins_++; VLOG(1) << "Number of flush pins: " << num_flush_pins_; } Status TabletMetadata::UnPinFlush() { std::unique_lock<LockType> l(data_lock_); CHECK_GT(num_flush_pins_, 0); num_flush_pins_--; if (needs_flush_) { l.unlock(); RETURN_NOT_OK(Flush()); } return Status::OK(); } Status TabletMetadata::Flush() { TRACE_EVENT1("tablet", "TabletMetadata::Flush", "tablet_id", tablet_id_); MutexLock l_flush(flush_lock_); vector<BlockId> orphaned; TabletSuperBlockPB pb; { std::lock_guard<LockType> l(data_lock_); CHECK_GE(num_flush_pins_, 0); if (num_flush_pins_ > 0) { needs_flush_ = true; LOG(INFO) << "Not flushing: waiting for " << num_flush_pins_ << " pins to be released."; return Status::OK(); } needs_flush_ = false; RETURN_NOT_OK(ToSuperBlockUnlocked(&pb, rowsets_)); // Make a copy of the orphaned blocks list which corresponds to the superblock // that we're writing. It's important to take this local copy to avoid a race // in which another thread may add new orphaned blocks to the 'orphaned_blocks_' // set while we're in the process of writing the new superblock to disk. We don't // want to accidentally delete those blocks before that next metadata update // is persisted. See KUDU-701 for details. orphaned.assign(orphaned_blocks_.begin(), orphaned_blocks_.end()); } pre_flush_callback_.Run(); RETURN_NOT_OK(ReplaceSuperBlockUnlocked(pb)); TRACE("Metadata flushed"); l_flush.Unlock(); // Now that the superblock is written, try to delete the orphaned blocks. // // If we crash just before the deletion, we'll retry when reloading from // disk; the orphaned blocks were persisted as part of the superblock. DeleteOrphanedBlocks(orphaned); return Status::OK(); } Status TabletMetadata::UpdateUnlocked( const RowSetMetadataIds& to_remove, const RowSetMetadataVector& to_add, int64_t last_durable_mrs_id) { DCHECK(data_lock_.is_locked()); CHECK_NE(state_, kNotLoadedYet); if (last_durable_mrs_id != kNoMrsFlushed) { DCHECK_GE(last_durable_mrs_id, last_durable_mrs_id_); last_durable_mrs_id_ = last_durable_mrs_id; } RowSetMetadataVector new_rowsets = rowsets_; auto it = new_rowsets.begin(); while (it != new_rowsets.end()) { if (ContainsKey(to_remove, (*it)->id())) { AddOrphanedBlocksUnlocked((*it)->GetAllBlocks()); it = new_rowsets.erase(it); } else { it++; } } for (const shared_ptr<RowSetMetadata>& meta : to_add) { new_rowsets.push_back(meta); } rowsets_ = new_rowsets; TRACE("TabletMetadata updated"); return Status::OK(); } Status TabletMetadata::ReplaceSuperBlock(const TabletSuperBlockPB &pb) { { MutexLock l(flush_lock_); RETURN_NOT_OK_PREPEND(ReplaceSuperBlockUnlocked(pb), "Unable to replace superblock"); } RETURN_NOT_OK_PREPEND(LoadFromSuperBlock(pb), "Failed to load data from superblock protobuf"); return Status::OK(); } Status TabletMetadata::ReplaceSuperBlockUnlocked(const TabletSuperBlockPB &pb) { flush_lock_.AssertAcquired(); string path = fs_manager_->GetTabletMetadataPath(tablet_id_); RETURN_NOT_OK_PREPEND(pb_util::WritePBContainerToPath( fs_manager_->env(), path, pb, pb_util::OVERWRITE, pb_util::SYNC), Substitute("Failed to write tablet metadata $0", tablet_id_)); return Status::OK(); } Status TabletMetadata::ReadSuperBlockFromDisk(TabletSuperBlockPB* superblock) const { string path = fs_manager_->GetTabletMetadataPath(tablet_id_); RETURN_NOT_OK_PREPEND( pb_util::ReadPBContainerFromPath(fs_manager_->env(), path, superblock), Substitute("Could not load tablet metadata from $0", path)); return Status::OK(); } Status TabletMetadata::ToSuperBlock(TabletSuperBlockPB* super_block) const { // acquire the lock so that rowsets_ doesn't get changed until we're finished. std::lock_guard<LockType> l(data_lock_); return ToSuperBlockUnlocked(super_block, rowsets_); } Status TabletMetadata::ToSuperBlockUnlocked(TabletSuperBlockPB* super_block, const RowSetMetadataVector& rowsets) const { DCHECK(data_lock_.is_locked()); // Convert to protobuf TabletSuperBlockPB pb; pb.set_table_id(table_id_); pb.set_tablet_id(tablet_id_); partition_.ToPB(pb.mutable_partition()); pb.set_last_durable_mrs_id(last_durable_mrs_id_); pb.set_schema_version(schema_version_); partition_schema_.ToPB(pb.mutable_partition_schema()); pb.set_table_name(table_name_); pb.set_table_type(table_type_); pb.set_rocksdb_dir(rocksdb_dir_); pb.set_wal_dir(wal_dir_); for (const shared_ptr<RowSetMetadata>& meta : rowsets) { meta->ToProtobuf(pb.add_rowsets()); } DCHECK(schema_->has_column_ids()); RETURN_NOT_OK_PREPEND(SchemaToPB(*schema_, pb.mutable_schema()), "Couldn't serialize schema into superblock"); pb.set_tablet_data_state(tablet_data_state_); if (!consensus::OpIdEquals(tombstone_last_logged_opid_, MinimumOpId())) { *pb.mutable_tombstone_last_logged_opid() = tombstone_last_logged_opid_; } for (const BlockId& block_id : orphaned_blocks_) { block_id.CopyToPB(pb.mutable_orphaned_blocks()->Add()); } for (const DeletedColumn& deleted_col : deleted_cols_) { deleted_col.CopyToPB(pb.mutable_deleted_cols()->Add()); } super_block->Swap(&pb); return Status::OK(); } Status TabletMetadata::CreateRowSet(shared_ptr<RowSetMetadata> *rowset, const Schema& schema) { AtomicWord rowset_idx = Barrier_AtomicIncrement(&next_rowset_idx_, 1) - 1; gscoped_ptr<RowSetMetadata> scoped_rsm; RETURN_NOT_OK(RowSetMetadata::CreateNew(this, rowset_idx, &scoped_rsm)); rowset->reset(DCHECK_NOTNULL(scoped_rsm.release())); return Status::OK(); } const RowSetMetadata *TabletMetadata::GetRowSetForTests(int64_t id) const { for (const shared_ptr<RowSetMetadata>& rowset_meta : rowsets_) { if (rowset_meta->id() == id) { return rowset_meta.get(); } } return nullptr; } RowSetMetadata *TabletMetadata::GetRowSetForTests(int64_t id) { std::lock_guard<LockType> l(data_lock_); for (const shared_ptr<RowSetMetadata>& rowset_meta : rowsets_) { if (rowset_meta->id() == id) { return rowset_meta.get(); } } return nullptr; } void TabletMetadata::SetSchema(const Schema& schema, uint32_t version) { gscoped_ptr<Schema> new_schema(new Schema(schema)); std::lock_guard<LockType> l(data_lock_); SetSchemaUnlocked(new_schema.Pass(), version); } void TabletMetadata::SetSchemaUnlocked(gscoped_ptr<Schema> new_schema, uint32_t version) { DCHECK(new_schema->has_column_ids()); Schema* old_schema = schema_; // "Release" barrier ensures that, when we publish the new Schema object, // all of its initialization is also visible. base::subtle::Release_Store(reinterpret_cast<AtomicWord*>(&schema_), reinterpret_cast<AtomicWord>(new_schema.release())); if (PREDICT_TRUE(old_schema)) { old_schemas_.push_back(old_schema); } schema_version_ = version; } void TabletMetadata::SetTableName(const string& table_name) { std::lock_guard<LockType> l(data_lock_); table_name_ = table_name; } string TabletMetadata::table_name() const { std::lock_guard<LockType> l(data_lock_); DCHECK_NE(state_, kNotLoadedYet); return table_name_; } TableType TabletMetadata::table_type() const { std::lock_guard<LockType> l(data_lock_); DCHECK_NE(state_, kNotLoadedYet); return table_type_; } uint32_t TabletMetadata::schema_version() const { std::lock_guard<LockType> l(data_lock_); DCHECK_NE(state_, kNotLoadedYet); return schema_version_; } string TabletMetadata::data_root_dir() const { if (rocksdb_dir_.empty()) { return ""; } else { auto data_root_dir = DirName(DirName(rocksdb_dir_)); if (strcmp(BaseName(data_root_dir).c_str(), FsManager::kRocksDBDirName) == 0) { data_root_dir = DirName(data_root_dir); } return data_root_dir; } } string TabletMetadata::wal_root_dir() const { if (wal_dir_.empty()) { return ""; } else { auto wal_root_dir = DirName(wal_dir_); if (strcmp(BaseName(wal_root_dir).c_str(), FsManager::kWalDirName) != 0) { wal_root_dir = DirName(wal_root_dir); } return wal_root_dir; } } void TabletMetadata::set_tablet_data_state(TabletDataState state) { std::lock_guard<LockType> l(data_lock_); tablet_data_state_ = state; } string TabletMetadata::LogPrefix() const { return Substitute("T $0 P $1: ", tablet_id_, fs_manager_->uuid()); } TabletDataState TabletMetadata::tablet_data_state() const { std::lock_guard<LockType> l(data_lock_); return tablet_data_state_; } } // namespace tablet } // namespace yb
36.585302
100
0.662386
[ "object", "vector" ]
8db3066892534260c2da42a5d39a3045027df047
1,264
hpp
C++
arucoMap/src/PresetFiles/PresetSurfaceClass.hpp
imec-int/team_scheire_OK
65ffce48fc8d2ed2a11f2b63f5293c97f05b86cf
[ "MIT" ]
3
2020-10-13T14:24:48.000Z
2020-10-15T09:20:14.000Z
arucoMap/src/PresetFiles/PresetSurfaceClass.hpp
imec-int/team_scheire_OK
65ffce48fc8d2ed2a11f2b63f5293c97f05b86cf
[ "MIT" ]
null
null
null
arucoMap/src/PresetFiles/PresetSurfaceClass.hpp
imec-int/team_scheire_OK
65ffce48fc8d2ed2a11f2b63f5293c97f05b86cf
[ "MIT" ]
5
2020-10-13T14:55:12.000Z
2021-05-29T21:39:04.000Z
// // PresetSurfaceClass.hpp // TeamScheireV2 // // Created by Jan Everaert on 09/10/2019. // #ifndef PresetSurfaceClass_hpp #define PresetSurfaceClass_hpp #include <stdio.h> #include "ofMain.h" #include "ofxXmlSettings.h" #include "PresetFileClass.hpp" #include "PresetItemClass.hpp" #include "PresetFileClass.hpp" #include "SurfaceGenerator.hpp" class PresetSurfaceClass { public: void setup(ofxOscSender s); void update(int PRESET_NUM); void draw(SurfaceGenerator* surfaces, bool DISPLAY_INTERACTION, bool DISPLAY_LOUIS); void setupPresets(); void handleOSC(ofxOscMessage msg); void sendMessage(string channel, int value); ofxXmlSettings xmlPresets; vector<PresetFileClass> presetFiles; int PRESET_NUM = 0; bool EDIT_MODE = false; ofxOscSender sender; PresetItemClass item; int OSCHeight = 768; int OSCWidth = 1024; int OSCOutputX = 0; int OSCOutputY = 0; int OSCOutputZ = 0; int OSCOutputRX = 0; int OSCOutputRY = 0; int OSCOutputRZ = 0; int OSCOutputWidth = 200; int OSCOutputHeight = 200; int OSCVideoX = 0; int OSCVideoY = 0; int OSCVideoWidth = 1024; int OSCVideoHeight = 512; int OSCPosition = 0; bool managePresets = false; int selectedPresetNum = -1; }; #endif /* PresetSurfaceClass_hpp */
20.721311
88
0.736551
[ "vector" ]
8db8971d6a7c6aaeccf35e74fd1773dd19953b6b
8,890
cpp
C++
init/init_sec.cpp
NusantaraROM-Devices/device_samsung_universal7420-common
f905c9dcbe41e2b21bdfbed4e32f0cecb20076e3
[ "Apache-2.0" ]
null
null
null
init/init_sec.cpp
NusantaraROM-Devices/device_samsung_universal7420-common
f905c9dcbe41e2b21bdfbed4e32f0cecb20076e3
[ "Apache-2.0" ]
null
null
null
init/init_sec.cpp
NusantaraROM-Devices/device_samsung_universal7420-common
f905c9dcbe41e2b21bdfbed4e32f0cecb20076e3
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2015, The Dokdo Project. 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 The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT 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. File Name : init_sec.c Create Date : 2015.11.03 Author : Sunghun Ra */ #define LOG_TAG "libinit_sec" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <android-base/properties.h> #include <log/log.h> #include "property_service.h" #include "vendor_init.h" #include "init_sec.h" using namespace std; using namespace android; namespace android { namespace init { void vendor_load_properties() { string device_orig = base::GetProperty("ro.product.device", ""); string bootloader = base::GetProperty("ro.bootloader", ""); string model, device, product; bool dualsim = false; /* * Flat */ if (bootloader.find("G920") != string::npos) { product = "zeroflte"; if (bootloader.find("G920F") != string::npos) { if (device_orig != "zeroflteduo") { model = "SM-G920F"; device = "zerofltexx"; } } else if (bootloader.find("G920I") != string::npos) { model = "SM-G920I"; device = "zerofltexx"; } else if (bootloader.find("G920K") != string::npos) { model = "SM-G920K"; device = "zerofltektt"; } else if (bootloader.find("G920L") != string::npos) { model = "SM-G920L"; device = "zerofltelgt"; } else if (bootloader.find("G920P") != string::npos) { model = "SM-G920P"; device = "zerofltespr"; } else if (bootloader.find("G920S") != string::npos) { model = "SM-G920S"; device = "zeroflteskt"; } else if (bootloader.find("G920T") != string::npos) { model = "SM-G920T"; device = "zerofltetmo"; } else if (bootloader.find("G920W8") != string::npos) { model = "SM-G920W8"; device = "zerofltecan"; } } /* * Edge */ else if (bootloader.find("G925") != string::npos) { product = "zerolte"; if (bootloader.find("G925F") != string::npos) { if (device_orig != "zeroflteduo") { model = "SM-G925F"; device = "zeroltexx"; } } else if (bootloader.find("G925I") != string::npos) { model = "SM-G925I"; device = "zeroltexx"; } else if (bootloader.find("G925K") != string::npos) { model = "SM-G925K"; device = "zeroltektt"; } else if (bootloader.find("G925L") != string::npos) { model = "SM-G925L"; device = "zeroltelgt"; } else if (bootloader.find("G925P") != string::npos) { model = "SM-G925P"; device = "zeroltespr"; } else if (bootloader.find("G925S") != string::npos) { model = "SM-G925S"; device = "zerolteskt"; } else if (bootloader.find("G925T") != string::npos) { model = "SM-G925T"; device = "zeroltetmo"; } else if (bootloader.find("G925W8") != string::npos) { model = "SM-G925W8"; device = "zeroltecan"; } } /* * Edge Plus */ else if (bootloader.find("G928") != string::npos) { product = "zenlte"; if (bootloader.find("G928F") != string::npos) { if (device_orig != "zenltexx") { model = "SM-G928F"; device = "zenltexx"; } } else if (bootloader.find("G928C") != string::npos) { model = "SM-G928C"; device = "zenltejv"; } else if (bootloader.find("G928I") != string::npos) { model = "SM-G928I"; device = "zenltedv"; } else if (bootloader.find("G928G") != string::npos) { model = "SM-G928G"; device = "zenltedd"; } else if (bootloader.find("G928K") != string::npos) { model = "SM-G928K"; device = "zenltektt"; } else if (bootloader.find("G928L") != string::npos) { model = "SM-G928L"; device = "zenltelgt"; } else if (bootloader.find("G928S") != string::npos) { model = "SM-G928S"; device = "zenlteskt"; } else if (bootloader.find("G928T") != string::npos) { model = "SM-G928T"; device = "zenltetmo"; } else if (bootloader.find("G928W8") != string::npos) { model = "SM-G928W8"; device = "zenltecan"; } else if (bootloader.find("G9287C") != string::npos) { model = "SM-G9287C"; device = "zenltezt"; dualsim = true; } } /* * Note 5 */ else if (bootloader.find("N920") != string::npos) { product = "noblelte"; if (bootloader.find("N920C") != string::npos) { if (device_orig != "nobleltejv") { model = "SM-N920C"; device = "nobleltejv"; dualsim = true; } } else if (bootloader.find("N9208") != string::npos) { model = "SM-N9208"; device = "nobleltezt"; dualsim = true; } else if (bootloader.find("N920G") != string::npos) { model = "SM-N920G"; device = "nobleltedd"; } else if (bootloader.find("N920I") != string::npos) { model = "SM-N920I"; device = "nobleltedv"; } else if (bootloader.find("N920P") != string::npos) { model = "SM-N920P"; device = "nobleltespr"; } else if (bootloader.find("N920S") != string::npos) { model = "SM-N920S"; device = "noblelteskt"; } else if (bootloader.find("N920K") != string::npos) { model = "SM-N920K"; device = "nobleltektt"; } else if (bootloader.find("N920L") != string::npos) { model = "SM-N920L"; device = "nobleltelgt"; } else if (bootloader.find("N920T") != string::npos) { model = "SM-N920T"; device = "nobleltetmo"; } else if (bootloader.find("N920W8") != string::npos) { model = "SM-N920W8"; device = "nobleltecan"; } } // load original properties string description_orig = base::GetProperty("ro.build.description", ""); string fingerprint_orig = base::GetProperty("ro.build.fingerprint", ""); // replace device-names with correct one if (device_orig != "") { if (description_orig != "") replace(description_orig, device_orig, device); if (fingerprint_orig != "") replace(fingerprint_orig, device_orig, device); } // update properties property_override("ro.product.model", model); property_override("ro.product.device", device); property_override("ro.build.product", product); property_override("ro.lineage.device", device); property_override("ro.vendor.product.device", device); property_override("ro.build.description", description_orig); property_override("ro.build.fingerprint", fingerprint_orig); property_override("ro.boot.warranty_bit", "0"); property_override("ro.warranty_bit", "0"); property_override("ro.boot.veritymode", "enforcing"); property_override("ro.boot.verifiedbootstate", "green"); property_override("ro.boot.flash.locked", "1"); property_override("ro.boot.ddrinfo", "00000001"); property_override("ro.build.selinux", "1"); property_override("ro.fmp_config", "1"); property_override("ro.boot.fmp_config", "1"); property_override("sys.oem_unlock_allowed", "0"); // set model-specific properties if (dualsim == true) { property_override("persist.multisim.config", "dsds"); property_override("persist.radio.multisim.config", "dsds"); property_override("ro.multisim.simslotcount", "2"); property_override("ro.telephony.default_network", "9,9"); } } } }
34.324324
76
0.607874
[ "model" ]
8dbba8129069aca304791bfd529f336a0f06e887
3,735
cpp
C++
examples/algae.cpp
Romop5/procgen
35d6e8e81b6fa0597b8a79863c1552edaa0219a0
[ "MIT" ]
5
2018-02-19T21:25:15.000Z
2018-05-11T19:06:51.000Z
examples/algae.cpp
Romop5/procgen
35d6e8e81b6fa0597b8a79863c1552edaa0219a0
[ "MIT" ]
null
null
null
examples/algae.cpp
Romop5/procgen
35d6e8e81b6fa0597b8a79863c1552edaa0219a0
[ "MIT" ]
null
null
null
#include <procgen/derivation/derivation.h> #include <procgen/derivation/appender.h> class AlwaysTrue : public Function { public: virtual bool operator()(RunStatus& rs) { *(bool*) getOutput()->getData() = true; return false; } }; class ruleInt: public Function { Derivation* der; public: ruleInt(Derivation* der) { this->der = der; } virtual bool operator()(RunStatus& rs) { std::cout << "Producing int and float \n"; // Producing int this->der->appendNextSymbol(_getInput(0)->getOutput()); // Producing float this->der->appendNextSymbol(der->tr->sharedResource("float")); return false; } }; void ruleInt(std::shared_ptr<Derivation> der, std::shared_ptr<TypeRegister> tr, std::shared_ptr<FunctionReg> fr) { auto typeInt = tr->sharedResource("int"); auto typeFloat= tr->sharedResource("float"); auto appendA = std::make_shared<AppendSymbol>(der); appendA->bindInput(0, fr->getHandler(typeInt)); auto appendB = std::make_shared<AppendSymbol>(der); appendB->bindInput(0, fr->getHandler(typeFloat)); auto body = std::make_shared<Body>(); body->appendStatement(appendA); body->appendStatement(appendB); fr->addCompositeFunction("ruleInt", body,{typeInt}, nullptr); } void ruleFloat(std::shared_ptr<Derivation> der, std::shared_ptr<TypeRegister> tr, std::shared_ptr<FunctionReg> fr) { auto typeFloat = tr->sharedResource("float"); auto typeInt = tr->sharedResource("int"); auto append = std::make_shared<AppendSymbol>(der); append->bindInput(0, fr->getHandler(typeInt)); auto body = std::make_shared<Body>(); body->appendStatement(append); fr->addCompositeFunction("ruleFloat", body,{typeFloat}, nullptr); } class ruleFloat: public Function { Derivation* der; public: ruleFloat(Derivation* der) { this->der = der; } virtual bool operator()(RunStatus& rs) { // Producing A std::cout << "Producing int from float \n"; this->der->appendNextSymbol(der->tr->sharedResource("int")); return false; } }; std::string convertSymbolsToString(TypeId typeInt, const std::vector<std::shared_ptr<Resource>> symbols) { std::string result = ""; for(auto &x: symbols) { if(x->getBaseId() == typeInt) result += "A"; else result += "B"; } return result; } int main(int argc, char **argv) { std::cerr << "Produces Nth generation of algae string" << std::endl; if(argc < 2) { std::cout << "Format: <iteration-count>" << std::endl; } srandom(time(NULL)); auto tr = std::make_shared<TypeRegister>(); auto fr = std::make_shared<FunctionReg>(tr); registerStandardTypes(tr.get()); registerStandardFunctions(fr.get()); auto derivation = std::make_shared<Derivation>(tr,fr); /* L-sys grammar */ // int -> int float // float -> int auto intValue = tr->sharedResource("int"); auto floatValue = tr->sharedResource("float"); std::vector<std::shared_ptr<Resource>> symbols = {intValue}; derivation->setStartSymbols(symbols); // Add rule ruleInt(derivation,tr,fr); ruleFloat(derivation,tr,fr); auto ruleForInt = fr->getFunc("ruleInt"); auto ruleForFloat = fr->getFunc("ruleFloat"); //derivation.addRule(tr->getTypeId("int"), std::make_shared<AlwaysTrue>(), std::make_shared<ruleInt>(&derivation)); //derivation.addRule(tr->getTypeId("float"), std::make_shared<AlwaysTrue>(), std::make_shared<ruleFloat>(&derivation)); derivation->addRule(tr->getTypeId("int"), std::make_shared<AlwaysTrue>(),ruleForInt ); derivation->addRule(tr->getTypeId("float"), std::make_shared<AlwaysTrue>(), ruleForFloat); derivation->generate(atoi(argv[1])); //derivation._debug(); // auto syms= derivation->getCurrentSymbolList(); auto str = convertSymbolsToString(tr->getTypeId("int"), syms); std::cout << str << std::endl; return 0; }
23.789809
120
0.696118
[ "vector" ]
8dbd0dc766574c60a547173df34d556678df66ca
1,708
cpp
C++
src/Config.cpp
nugins99/cdtags
591d2f39c60f04498adec2fd1ca1acac8bd73ca6
[ "MIT" ]
null
null
null
src/Config.cpp
nugins99/cdtags
591d2f39c60f04498adec2fd1ca1acac8bd73ca6
[ "MIT" ]
null
null
null
src/Config.cpp
nugins99/cdtags
591d2f39c60f04498adec2fd1ca1acac8bd73ca6
[ "MIT" ]
null
null
null
#include "Config.h" #include "Debug.h" #include <boost/algorithm/string.hpp> #include <iostream> #include <fstream> namespace cdtags { fs::path configFile() { static const fs::path file = ".config/cdtags/config"; // Read configuration fs::path home(getenv("HOME")); return home / file; } Config parseConfig() { namespace alg = boost::algorithm; // Check to see if the file exits... if (!fs::is_regular_file(configFile())) { return Config(); } Config cfg; std::ifstream in(configFile().c_str()); std::string line; size_t lineNo = 0; while (std::getline(in, line)) { lineNo++; alg::trim(line); // ignore blank lines or comments. if (line.empty() || line[0] == '#') { continue; } std::vector<std::string> fields; alg::split(fields, line, alg::is_any_of(",")); if (fields.size() < 2) { std::cerr << "Warning : (" << lineNo << ") Insufficient fields" << line << std::endl; continue; } for (int i = 1; i < fields.size(); ++i) { if (fields[i].empty()) continue; // ignore empty tags cfg.paths[fields[i]] = fields[0]; cfg.aliases[fields[0]].insert(fields[i]); } } return cfg; } void saveConfig(const Config& m) { if (!fs::is_directory(configFile().parent_path())) { std::cout << "Creating: " << configFile().parent_path() << std::endl; fs::create_directories(configFile().parent_path()); } std::ofstream out(configFile().c_str()); for (const auto& path : m.aliases) { DEBUG("Path: " << path.first); out << path.first.string() << ","; for (const auto& p : path.second) { DEBUG(p); out << p << ","; } out << '\n'; } } }
21.620253
77
0.574356
[ "vector" ]
8dbe62cdf5e73628256bab3759c0c9ce890352dc
4,330
hpp
C++
include/utils/point.hpp
JoseFilipeFerreira/CG-1920
88e7827e26cccba37f1de463e09510bcbe496016
[ "MIT" ]
null
null
null
include/utils/point.hpp
JoseFilipeFerreira/CG-1920
88e7827e26cccba37f1de463e09510bcbe496016
[ "MIT" ]
null
null
null
include/utils/point.hpp
JoseFilipeFerreira/CG-1920
88e7827e26cccba37f1de463e09510bcbe496016
[ "MIT" ]
1
2021-04-27T10:52:05.000Z
2021-04-27T10:52:05.000Z
#ifndef POINT_H #define POINT_H #include <cmath> #include <string> class Point; class PointSpherical; class Vector; class VectorSpherical; class Vector { private: float _x, _y, _z; public: Vector(): _x(0), _y(0), _z(0){}; Vector(float, float, float); Vector(Point const&, Point const&); Vector(Point const&); Vector(VectorSpherical const&); auto friend operator<<(std::ostream&, Vector const&) -> std::ostream&; auto constexpr x() const noexcept -> float { return _x; } auto constexpr y() const noexcept -> float { return _y; } auto constexpr z() const noexcept -> float { return _z; } auto mirror_x() const -> Vector { return Vector(-1 * _x, _y, _z); } auto mirror_y() const -> Vector { return Vector(_x, -1 * _y, _z); } auto mirror_z() const -> Vector { return Vector(_x, _y, -1 * _z); } auto normalize() const -> Vector; auto cross(Vector) const -> Vector; auto operator+(Vector const& v) const -> Vector { return Vector(_x + v.x(), _y + v.y(), _z + v.z()); } auto operator*(float s) const -> Vector { return Vector(_x * s, _y * s, _z * s); } auto operator/(int s) const -> Vector { return Vector(_x / s, _y / s, _z / s); } }; class VectorSpherical { private: float _radius, _inclination, _azimuth; public: VectorSpherical(float, float, float); VectorSpherical(Vector const&); VectorSpherical(Point const&, Point const&); auto friend operator<<(std::ostream&, VectorSpherical const&) -> std::ostream&; auto constexpr radius() const noexcept -> float { return _radius; } auto constexpr inclination() const noexcept -> float { return _inclination; } auto constexpr azimuth() const noexcept -> float { return _azimuth; } auto add_radius(float) const -> VectorSpherical; auto normalize() const -> VectorSpherical; auto add_inclination(float) const -> VectorSpherical; auto add_azimuth(float) const -> VectorSpherical; auto operator+(VectorSpherical const& v) const -> VectorSpherical { return VectorSpherical(Vector(*this) + Vector(v)); } auto operator*(float s) const -> VectorSpherical { return VectorSpherical(_radius * s, _inclination, _azimuth); } }; class Point { private: float _x, _y, _z; public: Point(): _x(0), _y(0), _z(0){}; Point(float, float, float); Point(PointSpherical const&); auto friend operator<<(std::ostream&, Point const&) -> std::ostream&; auto constexpr x() const noexcept -> float { return _x; } auto constexpr y() const noexcept -> float { return _y; } auto constexpr z() const noexcept -> float { return _z; } auto mirror_x() const -> Point { return Point(-1 * _x, _y, _z); } auto mirror_y() const -> Point { return Point(_x, -1 * _y, _z); } auto mirror_z() const -> Point { return Point(_x, _y, -1 * _z); } auto add_x(float) const -> Point; auto add_y(float) const -> Point; auto add_z(float) const -> Point; auto normalized_vector() const -> Vector; auto operator+(Vector const& p) const -> Point { return Point(_x + p.x(), _y + p.y(), _z + p.z()); } auto operator+(VectorSpherical const& vs) const -> Point { Vector v = Vector(vs); return Point(_x + v.x(), _y + v.y(), _z + v.z()); } }; class PointSpherical { private: float _radius, _inclination, _azimuth; public: PointSpherical(float, float, float); PointSpherical(Point const&); auto friend operator<<(std::ostream&, PointSpherical const&) -> std::ostream&; auto constexpr radius() const noexcept -> float { return _radius; } auto constexpr inclination() const noexcept -> float { return _inclination; } auto constexpr azimuth() const noexcept -> float { return _azimuth; } auto add_radius(float) const -> PointSpherical; auto add_inclination(float) const -> PointSpherical; auto add_azimuth(float) const -> PointSpherical; auto normalized_vector() const -> VectorSpherical; auto operator+(Vector const& v) const -> PointSpherical { return PointSpherical(Point(*this) + v); } auto operator+(VectorSpherical const& v) const -> PointSpherical { return PointSpherical(Point(*this) + Vector(v)); } }; #endif // POINT_H
35.203252
74
0.636259
[ "vector" ]
8dbf38605f34700ac8510c968dc7c3018b717681
4,622
cpp
C++
Libs/qtlockedfile/qtlockedfile.cpp
SCOTT-HAMILTON/OTPGen
706ba9a3546abddc1d1eb8f4edac710fe35a0b22
[ "BSD-2-Clause" ]
8
2018-12-21T12:04:19.000Z
2022-03-20T04:11:44.000Z
Libs/qtlockedfile/qtlockedfile.cpp
SCOTT-HAMILTON/OTPGen
706ba9a3546abddc1d1eb8f4edac710fe35a0b22
[ "BSD-2-Clause" ]
8
2019-11-24T19:51:10.000Z
2021-01-23T19:02:57.000Z
Libs/qtlockedfile/qtlockedfile.cpp
SCOTT-HAMILTON/OTPGen
706ba9a3546abddc1d1eb8f4edac710fe35a0b22
[ "BSD-2-Clause" ]
5
2019-01-28T03:36:02.000Z
2020-11-04T07:27:05.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "qtlockedfile.h" /*! \class QtLockedFile \brief The QtLockedFile class extends QFile with advisory locking functions. A file may be locked in read or write mode. Multiple instances of \e QtLockedFile, created in multiple processes running on the same machine, may have a file locked in read mode. Exactly one instance may have it locked in write mode. A read and a write lock cannot exist simultaneously on the same file. The file locks are advisory. This means that nothing prevents another process from manipulating a locked file using QFile or file system functions offered by the OS. Serialization is only guaranteed if all processes that access the file use QtLockedFile. Also, while holding a lock on a file, a process must not open the same file again (through any API), or locks can be unexpectedly lost. The lock provided by an instance of \e QtLockedFile is released whenever the program terminates. This is true even when the program crashes and no destructors are called. */ /*! \enum QtLockedFile::LockMode This enum describes the available lock modes. \value ReadLock A read lock. \value WriteLock A write lock. \value NoLock Neither a read lock nor a write lock. */ /*! Constructs an unlocked \e QtLockedFile object. This constructor behaves in the same way as \e QFile::QFile(). \sa QFile::QFile() */ QtLockedFile::QtLockedFile() : QFile() { #ifdef Q_OS_WIN m_semaphore_hnd = 0; m_mutex_hnd = 0; #endif m_lock_mode = NoLock; } /*! Constructs an unlocked QtLockedFile object with file \a name. This constructor behaves in the same way as \e QFile::QFile(const QString&). \sa QFile::QFile() */ QtLockedFile::QtLockedFile(const QString &name) : QFile(name) { #ifdef Q_OS_WIN m_semaphore_hnd = 0; m_mutex_hnd = 0; #endif m_lock_mode = NoLock; } /*! Returns \e true if this object has a in read or write lock; otherwise returns \e false. \sa lockMode() */ bool QtLockedFile::isLocked() const { return m_lock_mode != NoLock; } /*! Returns the type of lock currently held by this object, or \e QtLockedFile::NoLock. \sa isLocked() */ QtLockedFile::LockMode QtLockedFile::lockMode() const { return m_lock_mode; } /*! \fn bool QtLockedFile::lock(LockMode mode, bool block = true) Obtains a lock of type \a mode. If \a block is true, this function will block until the lock is acquired. If \a block is false, this function returns \e false immediately if the lock cannot be acquired. If this object already has a lock of type \a mode, this function returns \e true immediately. If this object has a lock of a different type than \a mode, the lock is first released and then a new lock is obtained. This function returns \e true if, after it executes, the file is locked by this object, and \e false otherwise. \sa unlock(), isLocked(), lockMode() */ /*! \fn bool QtLockedFile::unlock() Releases a lock. If the object has no lock, this function returns immediately. This function returns \e true if, after it executes, the file is not locked by this object, and \e false otherwise. \sa lock(), isLocked(), lockMode() */ /*! \fn QtLockedFile::~QtLockedFile() Destroys the \e QtLockedFile object. If any locks were held, they are released. */
30.609272
166
0.690826
[ "object" ]
8dc076a604e218b42c9e4ae16454f6b8abeee72b
15,589
cpp
C++
lib/mirror_rb/mirror_circuit_rb.cpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
lib/mirror_rb/mirror_circuit_rb.cpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
lib/mirror_rb/mirror_circuit_rb.cpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (c) 2018-, UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the BSD 3-Clause License * which accompanies this distribution. * * Contributors: * Alexander J. McCaskey - initial API and implementation * Thien Nguyen - implementation *******************************************************************************/ #include "mirror_circuit_rb.hpp" #include "AllGateVisitor.hpp" #include "clifford_gate_utils.hpp" #include "qcor_ir.hpp" #include "qcor_pimpl_impl.hpp" #include "xacc.hpp" #include "xacc_plugin.hpp" #include "xacc_service.hpp" #include <cassert> #include <random> namespace { std::vector<std::shared_ptr<xacc::Instruction>> getLayer(std::shared_ptr<xacc::CompositeInstruction> circuit, int layerId) { std::vector<std::shared_ptr<xacc::Instruction>> result; assert(layerId < circuit->depth()); auto graphView = circuit->toGraph(); for (int i = 1; i < graphView->order() - 1; i++) { auto node = graphView->getVertexProperties(i); if (node.get<int>("layer") == layerId) { result.emplace_back( circuit->getInstruction(node.get<std::size_t>("id") - 1)->clone()); } } assert(!result.empty()); return result; } } // namespace namespace xacc { namespace quantum { // Helper to convert a gate class GateConverterVisitor : public AllGateVisitor { public: GateConverterVisitor() { m_gateRegistry = xacc::getService<xacc::IRProvider>("quantum"); m_program = m_gateRegistry->createComposite("temp_composite"); } // Keep these 2 gates: void visit(CNOT &cnot) override { m_program->addInstruction(cnot.clone()); } void visit(U &u) override { m_program->addInstruction(u.clone()); } // Rotation gates: void visit(Ry &ry) override { const double theta = InstructionParameterToDouble(ry.getParameter(0)); m_program->addInstruction(m_gateRegistry->createInstruction( "U", {ry.bits()[0]}, {theta, 0.0, 0.0})); } void visit(Rx &rx) override { const double theta = InstructionParameterToDouble(rx.getParameter(0)); m_program->addInstruction(m_gateRegistry->createInstruction( "U", {rx.bits()[0]}, {theta, -1.0 * M_PI / 2.0, M_PI / 2.0})); } void visit(Rz &rz) override { const double theta = InstructionParameterToDouble(rz.getParameter(0)); m_program->addInstruction(m_gateRegistry->createInstruction( "U", {rz.bits()[0]}, {0.0, theta, 0.0})); } void visit(X &x) override { Rx rx(x.bits()[0], M_PI); visit(rx); } void visit(Y &y) override { Ry ry(y.bits()[0], M_PI); visit(ry); } void visit(Z &z) override { Rz rz(z.bits()[0], M_PI); visit(rz); } void visit(S &s) override { Rz rz(s.bits()[0], M_PI / 2.0); visit(rz); } void visit(Sdg &sdg) override { Rz rz(sdg.bits()[0], -M_PI / 2.0); visit(rz); } void visit(T &t) override { Rz rz(t.bits()[0], M_PI / 4.0); visit(rz); } void visit(Tdg &tdg) override { Rz rz(tdg.bits()[0], -M_PI / 4.0); visit(rz); } void visit(Hadamard &h) override { m_program->addInstruction(m_gateRegistry->createInstruction( "U", {h.bits()[0]}, {M_PI / 2.0, 0.0, M_PI})); } void visit(Measure &measure) override { // Ignore measure } void visit(Identity &i) override {} void visit(CY &cy) override { // controlled-Y = Sdg(target) - CX - S(target) CNOT c1(cy.bits()); Sdg sdg(cy.bits()[1]); S s(cy.bits()[1]); visit(sdg); visit(c1); visit(s); } void visit(CZ &cz) override { // CZ = H(target) - CX - H(target) CNOT c1(cz.bits()); Hadamard h1(cz.bits()[1]); Hadamard h2(cz.bits()[1]); visit(h1); visit(c1); visit(h2); } void visit(CRZ &crz) override { const auto theta = InstructionParameterToDouble(crz.getParameter(0)); // Decompose Rz rz1(crz.bits()[1], theta / 2); CNOT c1(crz.bits()); Rz rz2(crz.bits()[1], -theta / 2); CNOT c2(crz.bits()); // Revisit: visit(rz1); visit(c1); visit(rz2); visit(c2); } void visit(CH &ch) override { // controlled-H = Ry(pi/4, target) - CX - Ry(-pi/4, target) CNOT c1(ch.bits()); Ry ry1(ch.bits()[1], M_PI_4); Ry ry2(ch.bits()[1], -M_PI_4); visit(ry1); visit(c1); visit(ry2); } std::shared_ptr<CompositeInstruction> getProgram() { return balanceLayer(); } private: std::shared_ptr<CompositeInstruction> balanceLayer() { // Balance all layers // The mirroring protocol doesn't work well when there are layers that has // no gate on a qubit line, hence, just add an Identity there: auto program = m_gateRegistry->createComposite("temp_composite"); const auto d = m_program->depth(); const auto nbQubits = m_program->nPhysicalBits(); for (int layer = 0; layer < d; ++layer) { std::set<int> qubits; auto current_layers = getLayer(m_program, layer); for (const auto &gate : current_layers) { program->addInstruction(gate); for (const auto &bit : gate->bits()) { qubits.emplace(bit); } } if (qubits.size() < nbQubits) { for (int i = 0; i < nbQubits; ++i) { if (!xacc::container::contains(qubits, i)) { program->addInstruction( m_gateRegistry->createInstruction("U", {(size_t)i}, {0.0, 0.0, 0.0})); } } } } return program; } std::shared_ptr<CompositeInstruction> m_program; std::shared_ptr<xacc::IRProvider> m_gateRegistry; }; } // namespace quantum } // namespace xacc namespace qcor { std::pair<bool, xacc::HeterogeneousMap> MirrorCircuitValidator::validate( std::shared_ptr<xacc::Accelerator> qpu, std::shared_ptr<qcor::CompositeInstruction> program, xacc::HeterogeneousMap options) { // Some default values int n_trials = 1000; // 10% error allowed... (away from the expected bitstring) double eps = 0.1; int n_shots = 1024; if (options.keyExists<int>("trials")) { n_trials = options.get<int>("trials"); } if (options.keyExists<double>("epsilon")) { eps = options.get<double>("epsilon"); } qpu->updateConfiguration({{"shots", n_shots}}); std::vector<double> trial_success_probs; auto provider = xacc::getIRProvider("quantum"); for (int i = 0; i < n_trials; ++i) { auto mirror_data = qcor::MirrorCircuitValidator::createMirrorCircuit(program); auto mirror_circuit = mirror_data.first; auto expected_result = mirror_data.second; const std::string expectedBitString = [&]() { std::string bitStr; if (qpu->getBitOrder() == xacc::Accelerator::BitOrder::MSB) { std::reverse(expected_result.begin(), expected_result.end()); } for (const auto &bit : expected_result) { bitStr += std::to_string(bit); } return bitStr; }(); for (size_t qId = 0; qId < mirror_circuit->nPhysicalBits(); ++qId) { mirror_circuit->addInstruction( provider->createInstruction("Measure", {qId})); } auto mc_buffer = xacc::qalloc(mirror_circuit->nPhysicalBits()); qpu->execute(mc_buffer, mirror_circuit->as_xacc()); { std::stringstream ss; ss << "Trial " << i << "\n"; ss << "Circuit:\n" << mirror_circuit->toString() << "\n"; ss << "Result:\n" << mc_buffer->toString() << "\n"; ss << "Expected bitstring:" << expectedBitString << "\n"; xacc::info(ss.str()); } const auto bitStrProb = mc_buffer->computeMeasurementProbability(expectedBitString); trial_success_probs.emplace_back(bitStrProb); } xacc::HeterogeneousMap data; data.insert("trial-success-probabilities", trial_success_probs); const bool pass_fail_result = std::all_of(trial_success_probs.begin(), trial_success_probs.end(), [&eps](double val) { return val > 1.0 - eps; }); return std::make_pair(pass_fail_result, data); } std::pair<std::shared_ptr<CompositeInstruction>, std::vector<bool>> MirrorCircuitValidator::createMirrorCircuit( std::shared_ptr<CompositeInstruction> in_circuit) { std::vector<std::shared_ptr<xacc::Instruction>> mirrorCircuit; auto gateProvider = xacc::getService<xacc::IRProvider>("quantum"); // Gate conversion: xacc::quantum::GateConverterVisitor visitor; xacc::InstructionIterator it(in_circuit->as_xacc()); while (it.hasNext()) { auto nextInst = it.next(); if (nextInst->isEnabled() && !nextInst->isComposite()) { nextInst->accept(&visitor); } } auto program = visitor.getProgram(); const int n = program->nPhysicalBits(); // Tracking the Pauli layer as it is commuted through std::vector<qcor::utils::PauliLabel> net_paulis(n, qcor::utils::PauliLabel::I); // Sympletic group const auto srep_dict = qcor::utils::computeGateSymplecticRepresentations(); const auto pauliListToLayer = [](const std::vector<qcor::utils::PauliLabel> &in_paulis) { qcor::utils::CliffordGateLayer_t result; for (int i = 0; i < in_paulis.size(); ++i) { const auto pauli = in_paulis[i]; switch (pauli) { case qcor::utils::PauliLabel::I: result.emplace_back(std::make_pair("I", std::vector<int>{i})); break; case qcor::utils::PauliLabel::X: result.emplace_back(std::make_pair("X", std::vector<int>{i})); break; case qcor::utils::PauliLabel::Y: result.emplace_back(std::make_pair("Y", std::vector<int>{i})); break; case qcor::utils::PauliLabel::Z: result.emplace_back(std::make_pair("Z", std::vector<int>{i})); break; default: __builtin_unreachable(); } } return result; }; // program->as_xacc()->toGraph()->write(std::cout); const auto decomposeU3Angle = [](xacc::InstPtr u3_gate) { const double theta = InstructionParameterToDouble(u3_gate->getParameter(0)); const double phi = InstructionParameterToDouble(u3_gate->getParameter(1)); const double lam = InstructionParameterToDouble(u3_gate->getParameter(2)); // Convert to 3 rz angles: const double theta1 = lam; const double theta2 = theta + M_PI; const double theta3 = phi + 3.0 * M_PI; return std::make_tuple(theta1, theta2, theta3); }; const auto createU3GateFromAngle = [](size_t qubit, double theta1, double theta2, double theta3) { auto gateProvider = xacc::getService<xacc::IRProvider>("quantum"); return gateProvider->createInstruction( "U", {qubit}, {theta2 - M_PI, theta3 - 3.0 * M_PI, theta1}); }; const auto d = program->depth(); for (int layer = d - 1; layer >= 0; --layer) { auto current_layers = getLayer(program, layer); for (const auto &gate : current_layers) { if (gate->bits().size() == 1) { assert(gate->name() == "U"); const auto u3_angles = decomposeU3Angle(gate); const auto [theta1_inv, theta2_inv, theta3_inv] = qcor::utils::invU3Gate(u3_angles); const size_t qubit = gate->bits()[0]; program->addInstruction(gateProvider->createInstruction( "U", {qubit}, {theta2_inv - M_PI, theta1_inv - 3.0 * M_PI, theta3_inv})); } else { assert(gate->name() == "CNOT"); program->addInstruction(gate->clone()); } } } const int newDepth = program->depth(); for (int layer = 0; layer < newDepth; ++layer) { auto current_layers = getLayer(program, layer); // New random Pauli layer const std::vector<qcor::utils::PauliLabel> new_paulis = [](int nQubits) { static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<size_t> dis( 0, qcor::utils::ALL_PAULI_OPS.size() - 1); std::vector<qcor::utils::PauliLabel> random_paulis; for (int i = 0; i < nQubits; ++i) { random_paulis.emplace_back(qcor::utils::ALL_PAULI_OPS[dis(gen)]); } { std::stringstream ss; ss << "Random Pauli: "; for (const auto &p : random_paulis) { ss << p << " "; } xacc::info(ss.str()); } return random_paulis; }(n); const auto gateToLayerInfo = [](xacc::InstPtr gate, int nbQubits) { qcor::utils::CliffordGateLayer_t result; std::vector<int> operands; for (const auto &bit : gate->bits()) { operands.emplace_back(bit); } for (int i = 0; i < nbQubits; ++i) { if (!xacc::container::contains(operands, i)) { result.emplace_back(std::make_pair("I", std::vector<int>{i})); } } result.emplace_back(std::make_pair(gate->name(), operands)); return result; }; const auto current_net_paulis_as_layer = pauliListToLayer(net_paulis); for (const auto &gate : current_layers) { if (gate->bits().size() == 1) { assert(gate->name() == "U"); const auto new_paulis_as_layer = pauliListToLayer(new_paulis); const auto new_net_paulis_reps = qcor::utils::computeCircuitSymplecticRepresentations( {new_paulis_as_layer, current_net_paulis_as_layer}, n, srep_dict); // Update the tracking net net_paulis = qcor::utils::find_pauli_labels(new_net_paulis_reps.second); { std::stringstream ss; ss << "Net Pauli: "; for (const auto &p : net_paulis) { ss << p << " "; } xacc::info(ss.str()); } const size_t qubit = gate->bits()[0]; const auto [theta1, theta2, theta3] = decomposeU3Angle(gate); // Compute the pseudo_inverse gate: const auto [theta1_new, theta2_new, theta3_new] = qcor::utils::computeRotationInPauliFrame( std::make_tuple(theta1, theta2, theta3), new_paulis[qubit], net_paulis[qubit]); mirrorCircuit.emplace_back( createU3GateFromAngle(qubit, theta1_new, theta2_new, theta3_new)); } else { mirrorCircuit.emplace_back(gate->clone()); // we need to account for how the net pauli changes when it gets passed // through the clifford layers const auto new_net_paulis_reps = qcor::utils::computeCircuitSymplecticRepresentations( {gateToLayerInfo(gate, n), current_net_paulis_as_layer, gateToLayerInfo(gate, n)}, n, srep_dict); // Update the tracking net net_paulis = qcor::utils::find_pauli_labels(new_net_paulis_reps.second); { std::stringstream ss; ss << "Net Pauli: "; for (const auto &p : net_paulis) { ss << p << " "; } xacc::info(ss.str()); } } } } const auto [telp_s, telp_p] = qcor::utils::computeLayerSymplecticRepresentations( pauliListToLayer(net_paulis), n, srep_dict); std::vector<bool> target_bitString; for (int i = n; i < telp_p.size(); ++i) { target_bitString.emplace_back(telp_p[i] == 2); } auto mirror_comp = gateProvider->createComposite(program->name() + "_MIRROR"); mirror_comp->addInstructions(mirrorCircuit); return std::make_pair(std::make_shared<CompositeInstruction>(mirror_comp), target_bitString); } } // namespace qcor REGISTER_PLUGIN(qcor::MirrorCircuitValidator, qcor::BackendValidator)
34.111597
86
0.611329
[ "vector" ]
8dc14524d67366be1b1cc610be0ee490419e7b35
3,005
hpp
C++
src/Common/LoggerImpl.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2017-02-17T13:01:13.000Z
2017-02-17T13:01:13.000Z
src/Common/LoggerImpl.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
null
null
null
src/Common/LoggerImpl.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2018-07-23T00:05:58.000Z
2018-07-23T00:05:58.000Z
/*! * \file LoggerImpl.hpp * \brief Simple logging object * \author mstefanc * \date 2010-06-10 */ #ifndef LOGGERIMPL_HPP_ #define LOGGERIMPL_HPP_ #include <iostream> #include <sstream> #include <string> #include <boost/ptr_container/ptr_vector.hpp> #include <Singleton.hpp> #include "LoggerAux.hpp" #include "LoggerOutput.hpp" #if defined (_WIN32) #if defined(COMPILING_DLL) #define MYLIB_EXPORT __declspec(dllexport) #else #define MYLIB_EXPORT __declspec(dllimport) #endif /* defined(COMPILING_DLL) */ #else /* defined (_WIN32) */ #define MYLIB_EXPORT #endif namespace Utils { namespace Logger { /*! * \class Logger * \brief Class for loggind messages. * * Example usage of this class is available in \ref using_logger. */ class MYLIB_EXPORT Logger: public Base::Singleton <Logger> { /*! * Singleton class must be a friend, because only it can call protected constructor. */ friend class Base::Singleton <Logger>; public: virtual ~Logger(); /*! * Start message. Prints severity info and - if required - file name and line number * from where printing is called. */ Logger & log(const std::string & file, int line, Severity sev, const std::string & msg, int bump); /*static Logger& instance() { if (!inst) { inst = new Logger; } return *inst; }*/ /*! * Template stream operator used for printing any type of data. */ template <class T> Logger & operator<<(const T & data) { if (curr_lvl >= level) print(data); return *this; } /*! * Template method used to print any kind of data. * * To print custom types you can either overload operator<< in that class * or specialize this method. */ template <class T> void print(const T & data) const { std::cout << data; } /*! * Set logging severity level. * * All messages that has severity below set level are ignored. At default level * is set to NOTICE. */ void setLevel(Severity lvl) { level = lvl; } /*! * Binary dump */ void dump(Severity sev, const std::string & msg, void * data, int length); /*! * Print out summary (number of warnings, errors etc). */ void summary() const { std::cout << sum[Trace] << " traces\n" << sum[Debug] << " debugs\n" << sum[Info] << " informations\n" << sum[Notice] << " notices\n" << sum[Warning] << " warnings\n" << sum[Error] << " errors\n" << sum[Critical] << " critical errors\n" << sum[Fatal] << " fatal errors\n"; } /*! * Add new logger output. */ void addOutput(LoggerOutput * out, Severity lvl); protected: Logger() { sum[0] = sum[1] = sum[2] = sum[3] = sum[4] = sum[5] = sum[6] = sum[7] = sum[8] = sum[9] = 0; level = Notice; curr_lvl = Notice; } Logger(const Logger &) { level = 0; curr_lvl = 0; } /// sum of messages of each type int sum[10]; /// current logging level int level; /// level of actually printed message int curr_lvl; boost::ptr_vector<LoggerOutput> outputs; //static Logger * inst; }; } } #endif /* LOGGERIMPL_HPP_ */
19.900662
103
0.648253
[ "object" ]
44efd7e0dc30cffa744ab2af86a8955cce9d8177
732
cpp
C++
source/LCS.cpp
bpieszko/CopyTextFromVideo
f6722322c67da8ceb18d72be0241005b21a0f580
[ "MIT" ]
12
2019-01-30T11:59:03.000Z
2022-03-30T23:02:34.000Z
source/LCS.cpp
bpieszko/CopyTextFromVideo
f6722322c67da8ceb18d72be0241005b21a0f580
[ "MIT" ]
1
2019-11-01T11:30:22.000Z
2019-11-03T19:08:21.000Z
source/LCS.cpp
bpieszko/CopyTextFromVideo
f6722322c67da8ceb18d72be0241005b21a0f580
[ "MIT" ]
6
2019-03-13T16:37:17.000Z
2022-03-28T05:16:37.000Z
#include "LCS.hpp" const int LCS::getPercentSimilarity(const std::string & a, const std::string & b) { return getSimilarity(a, b) * 100 / std::max(a.size(), b.size()); } const int LCS::getSimilarity(const std::string & a, const std::string & b) { std::vector<std::vector<int>> dp(a.size() + 1, std::vector<int>(b.size() + 1, 0)); for (int i = 0; i <= a.size(); ++i) { for (int j = 0; j <= b.size(); ++j) { if (i == 0 || j == 0) dp[i][j] = 0; else if (a[i - 1] == b[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]); } } return dp[a.size()][b.size()]; }
28.153846
86
0.439891
[ "vector" ]
44f1414614a29b309421fac8f1502e1f61421b1c
3,092
cpp
C++
Modules/CppMicroServices/core/examples/eventlistener/Activator.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Modules/CppMicroServices/core/examples/eventlistener/Activator.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Modules/CppMicroServices/core/examples/eventlistener/Activator.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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. =============================================================================*/ //! [Activator] #include <usModuleActivator.h> #include <usModuleContext.h> US_USE_NAMESPACE namespace { /** * This class implements a simple module that utilizes the CppMicroServices's * event mechanism to listen for service events. Upon receiving a service event, * it prints out the event's details. */ class Activator : public ModuleActivator { private: /** * Implements ModuleActivator::Load(). Prints a message and adds a member * function to the module context as a service listener. * * @param context the framework context for the module. */ void Load(ModuleContext* context) { std::cout << "Starting to listen for service events." << std::endl; context->AddServiceListener(this, &Activator::ServiceChanged); } /** * Implements ModuleActivator::Unload(). Prints a message and removes the * member function from the module context as a service listener. * * @param context the framework context for the module. */ void Unload(ModuleContext* context) { context->RemoveServiceListener(this, &Activator::ServiceChanged); std::cout << "Stopped listening for service events." << std::endl; // Note: It is not required that we remove the listener here, // since the framework will do it automatically anyway. } /** * Prints the details of any service event from the framework. * * @param event the fired service event. */ void ServiceChanged(const ServiceEvent event) { std::string objectClass = ref_any_cast<std::vector<std::string> >(event.GetServiceReference().GetProperty(ServiceConstants::OBJECTCLASS())).front(); if (event.GetType() == ServiceEvent::REGISTERED) { std::cout << "Ex1: Service of type " << objectClass << " registered." << std::endl; } else if (event.GetType() == ServiceEvent::UNREGISTERING) { std::cout << "Ex1: Service of type " << objectClass << " unregistered." << std::endl; } else if (event.GetType() == ServiceEvent::MODIFIED) { std::cout << "Ex1: Service of type " << objectClass << " modified." << std::endl; } } }; } US_EXPORT_MODULE_ACTIVATOR(Activator) //! [Activator]
32.547368
153
0.643273
[ "vector" ]
44f149de30c0b54ad8e7c38116675cc1bfe3e1f7
3,744
cpp
C++
src/scene/shaders.cpp
markreidvfx/glprojectiontool
d03495dfb461ad1487a2b18c21a1eabdd744105a
[ "BSD-3-Clause" ]
null
null
null
src/scene/shaders.cpp
markreidvfx/glprojectiontool
d03495dfb461ad1487a2b18c21a1eabdd744105a
[ "BSD-3-Clause" ]
null
null
null
src/scene/shaders.cpp
markreidvfx/glprojectiontool
d03495dfb461ad1487a2b18c21a1eabdd744105a
[ "BSD-3-Clause" ]
null
null
null
#include "shaders.h" #include <GL/glew.h> #include <string> #include "rc_helper.h" #include <iostream> #include <vector> bool compile_shader(const char *shader_code, GLenum shader_type, GLuint &shaderId) { shaderId = glCreateShader(shader_type); glShaderSource(shaderId, 1, &shader_code, NULL); glCompileShader(shaderId); // Check if compiled properly GLint result = GL_FALSE; int log_length; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &result); glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &log_length); if (log_length > 0) { std::vector<char> error_message(log_length+1); glGetShaderInfoLog(shaderId, log_length, NULL, &error_message[0]); fprintf(stderr, "%s\n", &error_message[0]); } if(result != GL_TRUE) return false; return true; } bool build_shader_from_rc(const char *vertex_shader_path, const char *fragment_shader_path, unsigned int &programId) { return build_shader_from_rc(vertex_shader_path, NULL, fragment_shader_path, programId); } bool build_shader_from_rc(const char *vertex_shader_path, const char *geometry_shader_path, const char *fragment_shader_path, unsigned int &programId) { GLuint vertexShaderId; GLuint geometryShaderId; GLuint fragmentShaderId; std::string vertex_shader_code; std::string geometry_shader_code; std::string fragment_shader_code; GLuint tmp_programId; GLint result = GL_FALSE; int log_length; if (!read_rc_data(vertex_shader_path, vertex_shader_code)) { std::cerr << "unable to read vertex shader code\n"; goto fail; } if (geometry_shader_path) { if (!read_rc_data(geometry_shader_path, geometry_shader_code) ){ std::cerr << "unable to read geometry shader code\n"; goto fail; } } if (!read_rc_data(fragment_shader_path, fragment_shader_code)) { std::cerr << "unable to read fragment shader code\n"; goto fail; } if(!compile_shader(vertex_shader_code.c_str(), GL_VERTEX_SHADER, vertexShaderId)) { std::cerr << "unable to compile vertex shader code\n"; goto fail; } if (geometry_shader_path) { if(!compile_shader(geometry_shader_code.c_str(), GL_GEOMETRY_SHADER, geometryShaderId)) { std::cerr << "unable to compile geometry shader code\n"; goto fail; } } if(!compile_shader(fragment_shader_code.c_str(), GL_FRAGMENT_SHADER, fragmentShaderId)) { std::cerr << "unable to compile fragment shader code\n"; goto fail; } tmp_programId = glCreateProgram(); glAttachShader(tmp_programId, vertexShaderId); glAttachShader(tmp_programId, fragmentShaderId); if (geometry_shader_path) glAttachShader(tmp_programId, geometryShaderId); glLinkProgram(tmp_programId); // Check the program glGetProgramiv(tmp_programId, GL_LINK_STATUS, &result); glGetProgramiv(tmp_programId, GL_INFO_LOG_LENGTH, &log_length); if ( log_length > 0 ) { std::vector<char> error_message(log_length+1); glGetProgramInfoLog(tmp_programId, log_length, NULL, &error_message[0]); printf("%s\n", &error_message[0]); } if(result != GL_TRUE) goto fail; glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); programId = tmp_programId; return true; fail: std::cerr << "failed to build shader\n"; glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); glDeleteProgram(tmp_programId); return false; }
28.363636
97
0.659188
[ "geometry", "vector" ]
44f2384694f5fe3aacd59738fdc1900aaa8a0626
3,129
cpp
C++
30 - days of code/Scope/scope.cpp
kiptechie/hackerank
a1f827a3a8c494b0461b0e8d77e23aaa16d201b8
[ "MIT" ]
1
2020-07-06T12:50:30.000Z
2020-07-06T12:50:30.000Z
30 - days of code/Scope/scope.cpp
kiptechie/hackerank
a1f827a3a8c494b0461b0e8d77e23aaa16d201b8
[ "MIT" ]
null
null
null
30 - days of code/Scope/scope.cpp
kiptechie/hackerank
a1f827a3a8c494b0461b0e8d77e23aaa16d201b8
[ "MIT" ]
null
null
null
// Day 14: Scope // Objective // Today we’re discussing scope. Check out the Tutorial tab for learning materials and an instructional video! // The absolute difference between two integers, a and b, is written as |a - b|. The maximum absolute difference between two integers in a set of positive integers, elements, is the largest absolute difference between any two integers in elements. // The Difference class is started for you in the editor. It has a private integer array (elements) for storing N non-negative integers, and a public integer (maximumDifference) for storing the maximum absolute difference. // Task // Complete the Difference class by writing the following: // A class constructor that takes an array of integers as a parameter and saves it to the elements instance variable. // A computeDifference method that finds the maximum absolute difference between any 2 numbers in N and stores it in the maximumDifference instance variable. // Input Format // You are not responsible for reading any input from stdin. The locked Solution class in your editor reads in 2 lines of input; the first line contains N, and the second line describes the elements array. // Constraints // 1 <= N <= 10 // 1 <= elements[i] <= 100, where 0 <= i <= N - 1 // Output Format // You are not responsible for printing any output; the Solution class will print the value of the maximumDifference instance variable. // Sample Input // 1 // 2 // 3 // 1 2 5 // Sample Output // 1 // 4 // Explanation // The scope of the elements array and maximumDifference integer is the entire class instance. The class constructor saves the argument passed to the constructor as the elements instance variable (where the computeDifference method can access it). // To find the maximum difference, computeDifference checks each element in the array and finds the maximum difference between any 2 elements: |1 - 2| = 1 // |1 - 5| = 4 // |2 - 5| = 3 // The maximum of these differences is 4, so it saves the value 4 as the maximumDifference instance variable. The locked stub code in the editor then prints the value stored as maximumDifference, which is 4. #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Difference { private: vector<int> elements; public: int maximumDifference; // Add your code here Difference(vector<int> a){ elements = a; maximumDifference = 0; } void computeDifference(){ int n = elements.size()-1; for(int i = 0; i < n; i++){ for(int j = i; j < n; j++){ if(maximumDifference < abs(elements[i]-elements[j+1])){ maximumDifference = abs(elements[i]-elements[j+1]); } } } } }; // End of Difference class int main() { int N; cin >> N; vector<int> a; for (int i = 0; i < N; i++) { int e; cin >> e; a.push_back(e); } Difference d(a); d.computeDifference(); cout << d.maximumDifference; return 0; }
32.59375
247
0.677213
[ "vector" ]
44f94a10326af2129a74fb7a3d1bff8eaea7b7f6
4,530
cpp
C++
src/cascadia/TerminalApp/TabBase.cpp
paramsiddharth/terminal
e4a9c00f863db1ccb84fae43aaa786a2d0c02651
[ "MIT" ]
3
2020-12-17T21:46:18.000Z
2020-12-24T23:00:50.000Z
src/cascadia/TerminalApp/TabBase.cpp
paramsiddharth/terminal
e4a9c00f863db1ccb84fae43aaa786a2d0c02651
[ "MIT" ]
null
null
null
src/cascadia/TerminalApp/TabBase.cpp
paramsiddharth/terminal
e4a9c00f863db1ccb84fae43aaa786a2d0c02651
[ "MIT" ]
1
2021-04-07T16:59:45.000Z
2021-04-07T16:59:45.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "pch.h" #include <LibraryResources.h> #include "TabBase.h" #include "TabBase.g.cpp" using namespace winrt; using namespace winrt::Windows::UI::Xaml; using namespace winrt::Windows::UI::Core; using namespace winrt::Microsoft::Terminal::TerminalControl; using namespace winrt::Microsoft::Terminal::Settings::Model; using namespace winrt::Windows::System; namespace winrt { namespace MUX = Microsoft::UI::Xaml; namespace WUX = Windows::UI::Xaml; } namespace winrt::TerminalApp::implementation { WUX::FocusState TabBase::FocusState() const noexcept { return _focusState; } // Method Description: // - Prepares this tab for being removed from the UI hierarchy void TabBase::Shutdown() { Content(nullptr); _ClosedHandlers(nullptr, nullptr); } // Method Description: // - Creates a context menu attached to the tab. // Currently contains elements allowing the user to close the selected tab // Arguments: // - <none> // Return Value: // - <none> void TabBase::_CreateContextMenu() { auto weakThis{ get_weak() }; // Close Controls::MenuFlyoutItem closeTabMenuItem; Controls::FontIcon closeSymbol; closeSymbol.FontFamily(Media::FontFamily{ L"Segoe MDL2 Assets" }); closeSymbol.Glyph(L"\xE8BB"); closeTabMenuItem.Click([weakThis](auto&&, auto&&) { if (auto tab{ weakThis.get() }) { tab->_ClosedHandlers(nullptr, nullptr); } }); closeTabMenuItem.Text(RS_(L"TabClose")); closeTabMenuItem.Icon(closeSymbol); // Build the menu Controls::MenuFlyout newTabFlyout; newTabFlyout.Items().Append(_CreateCloseSubMenu()); newTabFlyout.Items().Append(closeTabMenuItem); TabViewItem().ContextFlyout(newTabFlyout); } // Method Description: // - Creates a sub-menu containing menu items to close multiple tabs // Arguments: // - <none> // Return Value: // - the created MenuFlyoutSubItem Controls::MenuFlyoutSubItem TabBase::_CreateCloseSubMenu() { auto weakThis{ get_weak() }; // Close tabs after _closeTabsAfterMenuItem.Click([weakThis](auto&&, auto&&) { if (auto tab{ weakThis.get() }) { tab->_CloseTabsAfter(); } }); _closeTabsAfterMenuItem.Text(RS_(L"TabCloseAfter")); // Close other tabs _closeOtherTabsMenuItem.Click([weakThis](auto&&, auto&&) { if (auto tab{ weakThis.get() }) { tab->_CloseOtherTabs(); } }); _closeOtherTabsMenuItem.Text(RS_(L"TabCloseOther")); Controls::MenuFlyoutSubItem closeSubMenu; closeSubMenu.Text(RS_(L"TabCloseSubMenu")); closeSubMenu.Items().Append(_closeTabsAfterMenuItem); closeSubMenu.Items().Append(_closeOtherTabsMenuItem); return closeSubMenu; } // Method Description: // - Enable the Close menu items based on tab index and total number of tabs // Arguments: // - <none> // Return Value: // - <none> void TabBase::_EnableCloseMenuItems() { // close other tabs is enabled only if there are other tabs _closeOtherTabsMenuItem.IsEnabled(TabViewNumTabs() > 1); // close tabs after is enabled only if there are other tabs on the right _closeTabsAfterMenuItem.IsEnabled(TabViewIndex() < TabViewNumTabs() - 1); } void TabBase::_CloseTabsAfter() { CloseTabsAfterArgs args{ _TabViewIndex }; ActionAndArgs closeTabsAfter{ ShortcutAction::CloseTabsAfter, args }; _dispatch.DoAction(closeTabsAfter); } void TabBase::_CloseOtherTabs() { CloseOtherTabsArgs args{ _TabViewIndex }; ActionAndArgs closeOtherTabs{ ShortcutAction::CloseOtherTabs, args }; _dispatch.DoAction(closeOtherTabs); } void TabBase::UpdateTabViewIndex(const uint32_t idx, const uint32_t numTabs) { TabViewIndex(idx); TabViewNumTabs(numTabs); _EnableCloseMenuItems(); } void TabBase::SetDispatch(const winrt::TerminalApp::ShortcutActionDispatch& dispatch) { _dispatch = dispatch; } }
30.608108
90
0.615232
[ "model" ]
44fb0fe5f28adb2655630cfc24caaffde50f78e6
3,331
hpp
C++
include/System/IO/SearchResultHandler_1.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/IO/SearchResultHandler_1.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/IO/SearchResultHandler_1.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: SearchResult class SearchResult; } // Completed forward declares // Type namespace: System.IO namespace System::IO { // WARNING Size may be invalid! // Autogenerated type: System.IO.SearchResultHandler`1 // [TokenAttribute] Offset: FFFFFFFF template<typename TSource> class SearchResultHandler_1 : public ::Il2CppObject { public: // Creating value type constructor for type: SearchResultHandler_1 SearchResultHandler_1() noexcept {} // System.Boolean IsResultIncluded(System.IO.SearchResult result) // Offset: 0xFFFFFFFF bool IsResultIncluded(System::IO::SearchResult* result) { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::SearchResultHandler_1::IsResultIncluded"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsResultIncluded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)}))); auto ___instance_arg = this; return ::il2cpp_utils::RunMethodThrow<bool, false>(___instance_arg, ___internal__method, result); } // TSource CreateObject(System.IO.SearchResult result) // Offset: 0xFFFFFFFF TSource CreateObject(System::IO::SearchResult* result) { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::SearchResultHandler_1::CreateObject"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CreateObject", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)}))); auto ___instance_arg = this; return ::il2cpp_utils::RunMethodThrow<TSource, false>(___instance_arg, ___internal__method, result); } // protected System.Void .ctor() // Offset: 0xFFFFFFFF // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static SearchResultHandler_1<TSource>* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::SearchResultHandler_1::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<SearchResultHandler_1<TSource>*, creationType>())); } }; // System.IO.SearchResultHandler`1 // Could not write size check! Type: System.IO.SearchResultHandler`1 is generic, or has no fields that are valid for size checks! } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(System::IO::SearchResultHandler_1, "System.IO", "SearchResultHandler`1"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
55.516667
204
0.719304
[ "object", "vector" ]