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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3a2ce10da59060d81e6d226adf7fd9610a73eae5 | 18,367 | cpp | C++ | src/settings_dialog.cpp | Brawlence/WiseTagger | fe4467bfee98ba77c0ceac3db0fc4f9826370c77 | [
"WTFPL"
] | null | null | null | src/settings_dialog.cpp | Brawlence/WiseTagger | fe4467bfee98ba77c0ceac3db0fc4f9826370c77 | [
"WTFPL"
] | null | null | null | src/settings_dialog.cpp | Brawlence/WiseTagger | fe4467bfee98ba77c0ceac3db0fc4f9826370c77 | [
"WTFPL"
] | null | null | null | /* Copyright © 2016 cat <cat@wolfgirl.org>
* This program is free software. It comes without any warranty, to the extent
* permitted by applicable law. You can redistribute it and/or modify it under
* the terms of the Do What The Fuck You Want To Public License, Version 2, as
* published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
#include "settings_dialog.h"
#include "ui_settings.h"
#include "util/misc.h"
#include "util/project_info.h"
#include "util/command_placeholders.h"
#include <QApplication>
#include <QDataWidgetMapper>
#include <QDirIterator>
#include <QFileDialog>
#include <QKeyEvent>
#include <QLoggingCategory>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QSettings>
#include <QStandardItemModel>
#include <QtDebug>
#include <QThread>
#define S_LOCALE QStringLiteral("window/language")
#define S_STYLE QStringLiteral("window/style")
#define S_FONT QStringLiteral("window/font")
#define S_FONT_SIZE QStringLiteral("window/font-size")
#define S_SHOW_DIR QStringLiteral("window/show-current-directory")
#define S_STATISTICS QStringLiteral("stats/enabled")
#define S_VERCHECK QStringLiteral("version-check-enabled")
#define S_TRACK_TAGS QStringLiteral("track-added-tags")
#define S_PROXY_ENABLED QStringLiteral("proxy/enabled")
#define S_PROXY_USE_SYS QStringLiteral("proxy/use_system")
#define S_PROXY_HOST QStringLiteral("proxy/host")
#define S_PROXY_PORT QStringLiteral("proxy/port")
#define S_PROXY_PROTO QStringLiteral("proxy/protocol")
#define S_PRELOAD QStringLiteral("performance/pixmap_precache_enabled")
#define S_PRELOAD_CNT QStringLiteral("performance/pixmap_precache_count")
#define S_PRELOAD_MEM QStringLiteral("performance/pixmap_cache_size")
#define D_LOCALE QStringLiteral("English")
#define D_STYLE QStringLiteral("Default")
#define D_FONT QStringLiteral("Consolas")
#define D_FONT_SIZE 14
#define D_SHOW_DIR true
#define D_STATISTICS true
#define D_VERCHECK true
#define D_TRACK_TAGS true
#define D_PROXY_ENABLED false
#define D_PROXY_USE_SYS false
#define D_PROXY_HOST QStringLiteral("")
#define D_PROXY_PORT 9050
#define D_PROXY_PROTO QStringLiteral("SOCKS5")
#define D_PRELOAD true
#define D_PRELOAD_CNT std::max(QThread::idealThreadCount() / 2, 1)
#define D_PRELOAD_MEM 64
#ifdef Q_OS_WIN
#define EXECUTABLE_EXTENSION SettingsDialog::tr("Executable Files (*.exe)")
#else
#define EXECUTABLE_EXTENSION QStringLiteral("")
#endif
namespace logging_category {
Q_LOGGING_CATEGORY(settdialog, "SettingsDialog")
}
#define pdbg qCDebug(logging_category::settdialog)
#define pwarn qCWarning(logging_category::settdialog)
SettingsDialog::SettingsDialog(QWidget * parent_) : QDialog(parent_), ui(new Ui::SettingsDialog), m_cmdl(nullptr), m_dmpr(nullptr)
{
ui->setupUi(this);
#ifndef Q_OS_WIN
ui->vercheckEnabled->hide();
#endif
connect(ui->dialogButtonBox, &QDialogButtonBox::accepted, this, &SettingsDialog::apply);
connect(ui->dialogButtonBox, &QDialogButtonBox::rejected, this, &SettingsDialog::reset);
connect(ui->dialogButtonBox, &QDialogButtonBox::clicked, this, [this](QAbstractButton* btn){
if(qobject_cast<QPushButton*>(btn) == ui->dialogButtonBox->button(QDialogButtonBox::Apply)) {
apply();
}
if(qobject_cast<QPushButton*>(btn) == ui->dialogButtonBox->button(QDialogButtonBox::RestoreDefaults)) {
restoreDefaults();
}
});
connect(ui->useSystemProxy, &QCheckBox::toggled, this, [this](bool toggled)
{
ui->proxyHost->setDisabled(toggled);
ui->proxyPort->setDisabled(toggled);
ui->proxyProtocol->setDisabled(toggled);
});
connect(ui->exportSettingsBtn, &QPushButton::clicked, this, [this](){
QSettings settings;
auto portable = settings.value(QStringLiteral("settings-portable"), false).toBool();
auto path = QFileDialog::getSaveFileName(this,
tr("Export settings to file"),
portable
? qApp->applicationDirPath()+QStringLiteral("/settings/catgirl/WiseTagger.ini")
: QDir::homePath()+QStringLiteral("/WiseTagger.ini"),
tr("Settings Files (*.ini)"));
if(path.isEmpty()) {
return;
}
if(util::backup_settings_to_file(path)) {
QMessageBox::information(this, tr("Export success"),
tr("Successfully exported settings!"));
} else {
QMessageBox::critical(this, tr("Export failed"),
tr("Could not export settings to file <b>%1</b>. Check directory permissions and try again.").arg(path));
}
});
connect(ui->importSettingsBtn, &QPushButton::clicked, this, [this](){
auto path = QFileDialog::getOpenFileName(this,
tr("Import settings from file"), QDir::homePath()+QStringLiteral("/WiseTagger.ini"),
tr("Settings Files (*.ini)"));
if(path.isEmpty()) {
return;
}
if(util::restore_settings_from_file(path)) {
QMessageBox::information(this, tr("Import success"),
tr("Successfully imported settings!"));
} else {
QMessageBox::critical(this, tr("Export failed"),
tr("Could not import settings from file <b>%1</b>. File may be corrupt or no read permissions.").arg(path));
}
});
connect(ui->cmdExecutableBrowse, &QPushButton::clicked, this, [this](){
auto dir = QFileInfo(ui->cmdExecutableEdit->text()).absolutePath();
auto n = QFileDialog::getOpenFileName(this,tr("Select Executable"),dir, EXECUTABLE_EXTENSION);
if(!n.isEmpty()) {
ui->cmdExecutableEdit->setText(n);
m_dmpr->submit(); // NOTE: it's not doing it automatically for some reason
}
});
// Placeholder inserters
connect(ui->p_filepath, &QAction::triggered, this, [this](bool){
ui->cmdArgsEdit->insert(QStringLiteral(" " CMD_PLDR_PATH " "));
});
connect(ui->p_filedir, &QAction::triggered, this, [this](bool){
ui->cmdArgsEdit->insert(QStringLiteral(" " CMD_PLDR_DIR " "));
});
connect(ui->p_filename, &QAction::triggered, this, [this](bool){
ui->cmdArgsEdit->insert(QStringLiteral(" " CMD_PLDR_FULLNAME " "));
});
connect(ui->p_basename, &QAction::triggered, this, [this](bool){
ui->cmdArgsEdit->insert(QStringLiteral(" " CMD_PLDR_BASENAME " "));
});
// Move down
connect(ui->downCmd, &QPushButton::clicked, this, [this](){
auto row = ui->cmdView->currentIndex().row();
if(row < ui->cmdView->model()->rowCount()-1) {
auto list = m_cmdl->takeRow(row);
m_cmdl->insertRow(row+1, list);
ui->cmdView->selectRow(row+1);
}
ui->cmdView->setFocus();
});
// Move up
connect(ui->upCmd, &QPushButton::clicked, this, [this](){
auto row = ui->cmdView->currentIndex().row();
if(row > 0) {
auto list = m_cmdl->takeRow(row);
m_cmdl->insertRow(row-1, list);
ui->cmdView->selectRow(row-1);
}
ui->cmdView->setFocus();
});
// Add new command
connect(ui->a_newcmd, &QAction::triggered, this, [this](bool){
auto row = ui->cmdView->currentIndex().row();
auto new_row = row + 1;
m_cmdl->insertRow(new_row, QList<QStandardItem*>());
m_cmdl->setData(m_cmdl->index(new_row, 3), CMD_PLDR_PATH);
ui->cmdView->selectRow(new_row);
ui->cmdView->setFocus();
ui->cmdView->edit(ui->cmdView->model()->index(new_row,0));
});
// Add new separator
connect(ui->a_newsep, &QAction::triggered, this, [this](bool){
auto row = ui->cmdView->currentIndex().row();
m_cmdl->insertRow(row+1, QList<QStandardItem*>{new QStandardItem(CMD_SEPARATOR)});
ui->cmdView->selectRow(row+1);
ui->cmdView->setFocus();
});
// Remove button
connect(ui->removeCmd, &QPushButton::clicked, this, [this](){
ui->a_removeitem->setData(ui->cmdView->currentIndex());
ui->a_removeitem->trigger();
});
// Remove action
connect(ui->a_removeitem, &QAction::triggered, this, [this](bool){
if(!ui->a_removeitem->data().isNull()) {
auto index = ui->a_removeitem->data().toModelIndex();
if(!index.isValid()) return;
auto row = index.row();
auto cmd = m_cmdl->data(m_cmdl->index(row, 0)).toString();
int reply = -1;
if(cmd != CMD_SEPARATOR) {
if(cmd.isEmpty()) cmd = tr("Unknown command");
reply = QMessageBox::question(this,
tr("Remove command?"),
tr("<p>Remove <b>%1</b>?</p><p>This action cannot be undone!</p>").arg(cmd),
QMessageBox::Yes, QMessageBox::No);
}
if(reply == -1 || reply == QMessageBox::Yes) {
m_cmdl->removeRow(row);
}
}
});
// Setup context menu for table view
auto menu_ctx = new QMenu(this);
menu_ctx->addAction(ui->a_newcmd);
menu_ctx->addAction(ui->a_newsep);
menu_ctx->addSeparator();
menu_ctx->addAction(ui->a_removeitem);
connect(ui->cmdView, &QTableView::customContextMenuRequested, this, [this, menu_ctx](const QPoint& p) {
auto index = ui->cmdView->indexAt(p);
ui->a_removeitem->setData(index);
menu_ctx->exec(ui->cmdView->mapToGlobal(p));
});
// Setup menu for add command button
auto menu_acts = new QMenu(this);
menu_acts->addAction(ui->a_newcmd);
menu_acts->addAction(ui->a_newsep);
// Setup menu for placeholders button
auto menu_ph = new QMenu(this);
menu_ph->addAction(ui->p_filepath);
menu_ph->addAction(ui->p_filedir);
menu_ph->addAction(ui->p_filename);
menu_ph->addAction(ui->p_basename);
// Attach menus
ui->newCmd->setMenu(menu_acts);
ui->cmdArgsPlaceholderShow->setMenu(menu_ph);
ui->cmdView->setContextMenuPolicy(Qt::CustomContextMenu);
reset();
}
SettingsDialog::~SettingsDialog()
{
delete ui;
}
void SettingsDialog::reset()
{
QSettings settings;
QDirIterator it_style(QStringLiteral(":/css"), {"*.css"});
QDirIterator it_locale(QStringLiteral(":/i18n/"), {"*.qm"});
auto curr_language = util::language_name(util::language_from_settings());
ui->appLanguage->clear();
ui->appStyle->clear();
while (it_style.hasNext() && !it_style.next().isEmpty()) {
const auto title = it_style.fileInfo().baseName();
ui->appStyle->addItem(title);
}
while(it_locale.hasNext() && !it_locale.next().isEmpty()) {
const auto name = it_locale.fileInfo().completeBaseName();
ui->appLanguage->addItem(name);
}
ui->appLanguage-> setCurrentText(curr_language);
ui->appStyle-> setCurrentText(settings.value(S_STYLE, D_STYLE).toString());
ui->fontFamily-> setCurrentText(settings.value(S_FONT, D_FONT).toString());
ui->proxyProtocol->setCurrentText(settings.value(S_PROXY_PROTO, D_PROXY_PROTO).toString());
ui->showCurrentDir->setChecked( settings.value(S_SHOW_DIR, D_SHOW_DIR).toBool());
ui->statsEnabled-> setChecked( settings.value(S_STATISTICS, D_STATISTICS).toBool());
ui->vercheckEnabled->setChecked( settings.value(S_VERCHECK, D_VERCHECK).toBool());
ui->trackAddedTags->setChecked( settings.value(S_TRACK_TAGS, D_TRACK_TAGS).toBool());
ui->proxyGroup-> setChecked( settings.value(S_PROXY_ENABLED, D_PROXY_ENABLED).toBool());
ui->useSystemProxy->setChecked( settings.value(S_PROXY_USE_SYS, D_PROXY_USE_SYS).toBool());
ui->fontSize-> setValue( settings.value(S_FONT_SIZE, D_FONT_SIZE).toUInt());
ui->proxyPort-> setValue( settings.value(S_PROXY_PORT, D_PROXY_PORT).toUInt());
ui->proxyHost-> setText( settings.value(S_PROXY_HOST, D_PROXY_HOST).toString());
ui->preloadGroup-> setChecked( settings.value(S_PRELOAD, D_PRELOAD).toBool());
ui->preloadCount-> setValue( settings.value(S_PRELOAD_CNT, D_PRELOAD_CNT).toUInt());
ui->cacheMemory-> setValue( settings.value(S_PRELOAD_MEM, D_PRELOAD_MEM).toUInt());
resetModel();
delete m_dmpr;
m_dmpr = new QDataWidgetMapper(this);
m_dmpr->setModel(m_cmdl);
m_dmpr->addMapping(ui->cmdExecutableEdit, 2);
m_dmpr->addMapping(ui->cmdArgsEdit, 3);
m_dmpr->toFirst();
auto fmd = new HideColumnsFilter(m_cmdl);
fmd->setSourceModel(m_cmdl);
ui->cmdView->setModel(fmd);
ui->cmdView->setItemDelegate(new SeparatorDelegate(m_cmdl));
ui->cmdView->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Stretch);
auto disable_widgets = [this](bool val)
{
ui->cmdExecutableEdit->setDisabled(val);
ui->cmdExecutableBrowse->setDisabled(val);
ui->cmdArgsEdit->setDisabled(val);
ui->cmdArgsPlaceholderShow->setDisabled(val);
};
connect(ui->cmdView->selectionModel(), &QItemSelectionModel::currentRowChanged,
this, [this, disable_widgets](auto a, auto){
m_dmpr->setCurrentIndex(a.row());
bool disabled = false;
if(m_cmdl->data(m_cmdl->index(a.row(), 0)) == CMD_SEPARATOR) {
disabled = true;
}
disable_widgets(disabled);
});
}
void SettingsDialog::resetModel()
{
auto join_args = [](const QStringList& args) {
QString r;
for(auto arg : args) {
if(arg.indexOf(' ') != -1) {
arg.prepend('"');
arg.append('"');
}
r.append(arg);
r.append(" ");
}
return r;
};
QSettings st;
auto size = st.beginReadArray(SETT_COMMANDS_KEY);
delete m_cmdl;
m_cmdl = new QStandardItemModel(size, 4, this);
m_cmdl->setHeaderData(0, Qt::Horizontal,tr("Command Name"));
m_cmdl->setHeaderData(1, Qt::Horizontal,tr("Hotkey"));
for(int i = 0; i < size; ++i) {
st.setArrayIndex(i);
auto path = st.value(SETT_COMMAND_CMD).toStringList();
m_cmdl->setItem(i, 0, new QStandardItem(st.value(SETT_COMMAND_NAME).toString()));
m_cmdl->setItem(i, 1, new QStandardItem(st.value(SETT_COMMAND_HOTKEY).toString()));
if(!path.isEmpty())
m_cmdl->setItem(i,2, new QStandardItem(path.first()));
if(path.size() > 1) {
path.removeFirst();
m_cmdl->setItem(i, 3, new QStandardItem(join_args(path)));
}
}
st.endArray();
}
void SettingsDialog::apply()
{
QSettings settings;
auto language_code = util::language_code(ui->appLanguage->currentText());
auto previous_code = util::language_from_settings();
if(language_code != previous_code) {
QMessageBox::information(this,
tr("Language Changed"),
tr("<p>Please restart %1 to apply language change.</p>")
.arg(QStringLiteral(TARGET_PRODUCT)));
}
settings.setValue(S_LOCALE, language_code);
settings.setValue(S_STYLE, ui->appStyle->currentText());
settings.setValue(S_FONT, ui->fontFamily->currentText());
settings.setValue(S_FONT_SIZE, ui->fontSize->value());
settings.setValue(S_SHOW_DIR, ui->showCurrentDir->isChecked());
settings.setValue(S_STATISTICS, ui->statsEnabled->isChecked());
settings.setValue(S_VERCHECK, ui->vercheckEnabled->isChecked());
settings.setValue(S_TRACK_TAGS, ui->trackAddedTags->isChecked());
settings.setValue(S_PROXY_PROTO, ui->proxyProtocol->currentText());
settings.setValue(S_PROXY_PORT, ui->proxyPort->text());
settings.setValue(S_PROXY_HOST, ui->proxyHost->text());
settings.setValue(S_PROXY_ENABLED, ui->proxyGroup->isChecked());
settings.setValue(S_PROXY_USE_SYS, ui->useSystemProxy->isChecked());
settings.setValue(S_PRELOAD, ui->preloadGroup->isChecked());
settings.setValue(S_PRELOAD_CNT, ui->preloadCount->value());
settings.setValue(S_PRELOAD_MEM, ui->cacheMemory->value());
auto parse_arguments = [](const QString & args)
{
QStringList ret;
QString curr_arg;
bool open_quote = false;
for(auto c : qAsConst(args)) {
if(c == '"') {
open_quote = !open_quote;
continue;
}
if(c.isSpace() && !open_quote) {
if(!curr_arg.isEmpty()) {
ret.push_back(curr_arg);
curr_arg.clear();
}
continue;
}
curr_arg.push_back(c);
}
if(!curr_arg.isEmpty()) {
ret.push_back(curr_arg);
}
return ret;
};
int invalid_num = 0;
settings.beginWriteArray(SETT_COMMANDS_KEY);
for(int i = 0; i < m_cmdl->rowCount(); ++i) {
settings.setArrayIndex(i);
auto name = m_cmdl->data(m_cmdl->index(i,0)).toString();
if(name.isEmpty())
name = tr("Unknown command %1").arg(++invalid_num);
auto hotkey = m_cmdl->data(m_cmdl->index(i,1)).toString();
auto exec_path = m_cmdl->data(m_cmdl->index(i,2)).toString();
auto args = parse_arguments(m_cmdl->data(m_cmdl->index(i,3)).toString());
args.prepend(exec_path);
settings.setValue(SETT_COMMAND_NAME, name);
settings.setValue(SETT_COMMAND_HOTKEY, hotkey);
settings.setValue(SETT_COMMAND_CMD, args);
}
settings.endArray();
emit updated();
}
void SettingsDialog::restoreDefaults()
{
ui->appLanguage-> setCurrentText(D_LOCALE);
ui->appStyle-> setCurrentText(D_STYLE);
ui->fontFamily-> setCurrentText(D_FONT);
ui->proxyProtocol->setCurrentText(D_PROXY_PROTO);
ui->showCurrentDir->setChecked( D_SHOW_DIR);
ui->statsEnabled-> setChecked( D_STATISTICS);
ui->vercheckEnabled->setChecked( D_VERCHECK);
ui->trackAddedTags->setChecked( D_TRACK_TAGS);
ui->proxyGroup-> setChecked( D_PROXY_ENABLED);
ui->useSystemProxy->setChecked( D_PROXY_USE_SYS);
ui->preloadGroup-> setChecked( D_PRELOAD);
ui->proxyHost-> setText( D_PROXY_HOST);
ui->proxyPort-> setValue( D_PROXY_PORT);
ui->fontSize-> setValue( D_FONT_SIZE);
ui->preloadCount-> setValue( D_PRELOAD_CNT);
ui->cacheMemory-> setValue( D_PRELOAD_MEM);
}
bool HideColumnsFilter::filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const
{
if(source_column > 1) return false;
return QSortFilterProxyModel::filterAcceptsColumn(source_column, source_parent);
}
QWidget* SeparatorDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(index.sibling(index.row(), 0).data() == CMD_SEPARATOR) {
return nullptr;
}
if(index.column() == 1) {
auto editor = new HotkeyEdit(parent);
return editor;
}
return QStyledItemDelegate::createEditor(parent, option, index);
}
QString SeparatorDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
if(value == CMD_SEPARATOR) {
return QString(100, QChar(0x23AF)); // unicode horizontal line
}
return QStyledItemDelegate::displayText(value, locale);
}
void HotkeyEdit::keyPressEvent(QKeyEvent *e)
{
if(!e) return;
if(e->key() == Qt::Key_Escape || e->key() == Qt::Key_Enter) {
return;
}
int keys = 0;
bool has_modifier = false;
auto addkey = [&keys, &has_modifier](int key) {
has_modifier = true;
keys += key;
};
if(e->modifiers() & Qt::AltModifier) {
addkey(Qt::ALT);
}
if(e->modifiers() & Qt::ControlModifier) {
addkey(Qt::CTRL);
}
if(e->modifiers() & Qt::ShiftModifier) {
addkey(Qt::SHIFT);
}
auto key = e->key();
if(key != Qt::Key_Control && key != Qt::Key_Shift && key != Qt::Key_Alt)
{
if(has_modifier) addkey(e->key());
}
m_sequence = QKeySequence(keys);
QLineEdit::setText(m_sequence.toString());
}
HotkeyEdit::HotkeyEdit(QWidget *parent)
: QLineEdit(parent)
{
}
HotkeyEdit::~HotkeyEdit()
{
}
| 34.012963 | 130 | 0.704742 | [
"model"
] |
3a309604751b7f3178163f9697d25e7be5e7787b | 3,379 | cpp | C++ | sandbox/main.cpp | PitEG/poppingamer | 1eade7430b77ddf35098d4e500e2f75aaabbf891 | [
"MIT"
] | null | null | null | sandbox/main.cpp | PitEG/poppingamer | 1eade7430b77ddf35098d4e500e2f75aaabbf891 | [
"MIT"
] | null | null | null | sandbox/main.cpp | PitEG/poppingamer | 1eade7430b77ddf35098d4e500e2f75aaabbf891 | [
"MIT"
] | null | null | null | #include <poppingamer/poppingamer.hpp>
#include <SFML/System.hpp>
#include <vector>
#include <string>
#include <iostream>
class RDR : public pg::Renderable {
public:
RDR() : RDR(1) {}
RDR(unsigned int layer)
: pg::Renderable(layer), rs(sf::Vector2f(10,10)){
}
virtual void Draw(const pg::Camera& camera) {
sf::RenderTexture* rt = camera.m_rTexture;
rt->draw(rs);
}
sf::RectangleShape rs;
};
class App : public pg::Application {
public:
App(int width, int height, std::string name)
: pg::Application(width, height, name) {
}
virtual void Start() override {
}
virtual void WindowResize() override {
}
virtual void Run() override {
RDR rdr(10);
RDR rdr2(11);
RDR rdr3(10);
int randNum = 1000;
RDR* rand = new RDR[randNum];
rdr.rs.setFillColor(sf::Color(240, 230, 0));
rdr2.rs.setFillColor(sf::Color(100, 100, 100));
rdr2.rs.setPosition(rdr2.rs.getPosition() + sf::Vector2f(1.f,1.f));
rdr3.rs.setFillColor(sf::Color(0, 190, 0));
rdr3.rs.setPosition(rdr2.rs.getPosition() + sf::Vector2f(4.f,4.f));
int w = m_window->getSize().x / 3;
int h = m_window->getSize().y / 3;
sf::RenderTexture rt;
rt.create(w,h);
sf::RenderTexture rt2;
rt2.create(w,h);
sf::View view(sf::Vector2f(0, 0), sf::Vector2f(w, h));
sf::View view2(sf::Vector2f(30, 10), sf::Vector2f(w, h));
std::vector<pg::Renderable*> renderables(pg::Renderer::INITIAL_LAYER_LIST_SIZE, 0);
//framerate
m_window->setFramerateLimit(0);
m_window->setVerticalSyncEnabled(false);
unsigned int frame = 0;
sf::Clock clock;
sf::Int64 framerate = 120;
sf::Int64 frametime = 1'000'000 / framerate;
sf::Int64 lastFrameTime = clock.getElapsedTime().asMicroseconds();
while (m_window->isOpen()) {
if (m_window->hasFocus()) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
m_window->close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
rdr.rs.move(1.f,0.f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
rdr.rs.move(-1.f,0.f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
rdr.rs.move(0.f,-1.f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
rdr.rs.move(0.f,1.f);
}
}
//Render
pg::Camera camera(NULL, view, &rt, 3);
pg::Camera camera2(NULL, view2, &rt2, 3);
pg::Camera cameras[10] = {camera,camera2};
renderables[1] = &rdr;
renderables[2] = &rdr2;
renderables[0] = &rdr3;
for (int i = 3; i < randNum; i++) {
RDR* rP = rand + i;
if (i >= renderables.size()) {
renderables.push_back(rP);
}
else {
renderables[i] = rP;
}
}
m_renderer->PushRenderables(renderables);
m_renderer->PushCameras(cameras);
m_renderer->Draw();
//framerate
frame++;
while(clock.getElapsedTime().asMicroseconds() - lastFrameTime < frametime);
lastFrameTime = clock.getElapsedTime().asMicroseconds();
std::cout << "time: " << lastFrameTime / (float)1000'000 << "s; frame: " << frame << std::endl;
}
}
virtual void Stop() override {
}
};
int main() {
int width = 520;
int height = 810;
App app(width, height, "What's Poppin, Gamer?");
app.Start();
app.Run();
app.Stop();
}
| 26.81746 | 101 | 0.591595 | [
"render",
"vector"
] |
3a32bdb558d54f02e0f7e0345d43d236c51a1f0a | 8,582 | hpp | C++ | include/public/coherence/lang/SynchronizedMemberReadBlock.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | include/public/coherence/lang/SynchronizedMemberReadBlock.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | include/public/coherence/lang/SynchronizedMemberReadBlock.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_SYNCHRONIZED_MEMBER_READ_BLOCK_HPP
#define COH_SYNCHRONIZED_MEMBER_READ_BLOCK_HPP
#include "coherence/lang/compatibility.hpp"
#include "coherence/lang/Object.hpp"
#include "coherence/lang/FinalizableBlock.hpp"
#include <iostream>
COH_OPEN_NAMESPACE2(coherence,lang)
/**
* The SynchronizedMemberReadBlock class allows for easy creation of
* synchronized code blocks based on an Object's member level read/write lock.
* The SynchronizedMemberBlock object will ensure that the locks are acquired
* and released as part of starting and ending the code block.
*
* Member read/write locks are not a general purpose feature, and should not
* be used to protect blocking calls. They are intended to protect reads and
* writes to data member primitives, and other short non-blocking code
* blocks.
*
* Example usage:
* @code
* // outside of sync block
* {
* SynchronizedMemberReadBlock syncRead(self()); // read lock acquired
* // critical section goes here
* // ...
* } // read lock released
* // outside of sync block
* @endcode
*
* A more friendly form is to use the COH_SYNCHRONIZED_MEMBER_READ
* macros. Example usage:
*
* @code
* // outside of sync block
* COH_SYNCHRONIZED_MEMBER_READ // read lock acquired
* {
* // critical section goes here
* // ...
* // ...
* } // read lock released
* // outside of sync block
* @endcode
*
* The SynchronizedMemberReadBlock class relies on its creator to ensure that
* the associated Object outlives the scope of the block. The helper macro
* ensures this by only allowing you to create a block for the encompassing
* Object, i.e. "this". If the blocks are manually created then the caller
* must ensure that the associated Object outlives the block.
* '
* Note: This class derives from FinalizableBlock, allowing custom finalizers
* to be registered. The finalizers will execute after the lock has been
* released.
*
* @author mf 2008.01.29
*/
class COH_EXPORT SynchronizedMemberReadBlock
: public FinalizableBlock
{
// ----- constructors ---------------------------------------------------
public:
/**
* Construct a synchronized SynchronizedMemberReadBlock, acquiring the
* Object's member read lock.
*
* @param o the Object to lock
* @param pDelegate SynchronizedMemberReadBlock to delegate to, or
* NULL for no delegate
*
* @throws IllegalArgumentException if pSyncDelegate is non-NULL and
* references a different Object.
*/
SynchronizedMemberReadBlock(const Object& o,
SynchronizedMemberReadBlock* pDelegate = NULL)
: FinalizableBlock(), m_cpObject(NULL)
{
initialize(o, pDelegate);
if (isTerminal())
{
o._acquireMemberReadLock();
}
m_cpObject = &o;
}
/**
* Destroy a SynchronizedMemberReadBlock.
*
* This is a no-op for a delegating block, otherwise the read lock is
* released.
*/
~SynchronizedMemberReadBlock()
{
const Object* cpObject = m_cpObject;
if (NULL != cpObject && isTerminal())
{
try
{
cpObject->_releaseMemberReadLock();
}
catch (const std::exception& e)
{
std::cerr << "Error releasing MemberReadLock: " <<
e.what() << std::endl;
}
}
}
protected:
/**
* Construct an uninitialized SynchronizedMemberReadBlock.
*/
SynchronizedMemberReadBlock()
: FinalizableBlock(), m_cpObject(NULL)
{
}
// ----- operators ------------------------------------------------------
public:
/**
* Validate that the lock is held. The boolean conversion is utilized
* by the COH_SYNCHRONIZED_MEMBER_READ macro.
*
* @throw IllegalStateException if the lock is not held.
*
* @return false always
*/
operator bool() const
{
if (NULL == m_cpObject)
{
coh_throw_illegal_state("lock not held");
}
return FinalizableBlock::operator bool();
}
// -------- SynchronizedMemberReadBlock interface -----------------------
public:
/**
* Get the value of the specified member, without obtaining
* additional synchronization.
*
* This helper function is only supported on "members" which
* supply a custom two-parameter "get" method utilizing the
* SynchronizedMemberBlock::SynchronizedMemberReadBlock facility.
*
* @param member the member whose value to get
*
* @return the member's value
*/
template<class M> typename M::ConstGetType getMember(const M& member)
{
return member.get(this);
}
/**
* Get the value of the specified member, without obtaining
* additional synchronization.
*
* This helper function is only supported on "members" which
* supply a custom parameterized "get" method utilizing the
* SynchronizedMemberBlock::SynchronizedMemberReadBlock facility.
*
* @param member the member whose value to get
*
* @return the member's value
*/
template<class M> typename M::GetType getMember(M& member)
{
return member.get(this);
}
protected:
/**
* Initialize a synchronized SynchronizedMemberReadBlock.
*
* @param o the Object associated with the block
* @param pDelegate SynchronizedMemberReadBlock to delegate to, or
* NULL for no delegate
*
* @throws IllegalArgumentException if pSyncDelegate is non-NULL and
* references a different Object.
*/
void initialize(const Object& o,
SynchronizedMemberReadBlock* pDelegate = NULL)
{
FinalizableBlock::initialize(pDelegate);
if (!isTerminal() && &o != pDelegate->m_cpObject)
{
coh_throw_illegal_argument("Object differs from delegate");
}
}
// ----- nested class: Guard --------------------------------------------
public:
/**
* Simple read lock structure for use in inlining.
*/
class COH_EXPORT Guard
{
public:
Guard(const Object& o)
: m_o(o)
{
acquireMemberReadLock(o);
}
~Guard()
{
releaseMemberReadLock(m_o);
}
private:
const Object& m_o;
};
// ----- helper methods -------------------------------------------------
protected:
/*
* Acquire an Object's read lock
*/
static void acquireMemberReadLock(const Object& o)
{
o._acquireMemberReadLock();
}
/*
* Release an Object's read lock
*/
static void releaseMemberReadLock(const Object& o)
{
o._releaseMemberReadLock();
}
// ----- data members ---------------------------------------------------
protected:
/**
* The Object on which the lock is applied.
*/
const Object* m_cpObject;
};
COH_CLOSE_NAMESPACE2
/**
* Macro for making more readable synchronized member read code blocks See the
* documentation of SynchronizedMemberReadBlock for a usage example.
*
* @see coherence::lang::SynchronizedMemberReadBlock
*/
#define COH_SYNCHRONIZED_MEMBER_READ \
if (coherence::lang::SynchronizedMemberReadBlock coh_synchronized_member_read \
= coherence::lang::SynchronizedMemberReadBlock(Object::self())) \
{ \
COH_THROW(coherence::lang::IllegalStateException::create()); \
} \
else
#endif // COH_SYNCHRONIZED_MEMBER_READ_BLOCK_HPP
| 30.432624 | 83 | 0.560592 | [
"object"
] |
3a34c1f0aad284b70b387472b40561150defa319 | 10,933 | cpp | C++ | src/slideio/drivers/scn/scnscene.cpp | Booritas/slideio | fdee97747cc73f087a5538aef6a0315ec75becca | [
"BSD-3-Clause"
] | 6 | 2021-01-25T15:21:31.000Z | 2022-03-07T09:23:37.000Z | src/slideio/drivers/scn/scnscene.cpp | Booritas/slideio | fdee97747cc73f087a5538aef6a0315ec75becca | [
"BSD-3-Clause"
] | 3 | 2020-12-30T16:21:42.000Z | 2022-03-07T09:23:18.000Z | src/slideio/drivers/scn/scnscene.cpp | Booritas/slideio | fdee97747cc73f087a5538aef6a0315ec75becca | [
"BSD-3-Clause"
] | null | null | null | // This file is part of slideio project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://slideio.com/license.html.
#include "slideio/drivers/scn/scnscene.hpp"
#include "slideio/imagetools/tifftools.hpp"
#include "slideio/xmltools.hpp"
#include "slideio/imagetools/imagetools.hpp"
#include "slideio/imagetools/tools.hpp"
#include "slideio/libtiff.hpp"
#include <boost/format.hpp>
using namespace slideio;
using namespace tinyxml2;
SCNScene::SCNScene(const std::string& filePath, const tinyxml2::XMLElement* xmlImage):
m_filePath(filePath),
m_compression(Compression::Unknown),
m_resolution(0., 0.),
m_magnification(0.),
m_interleavedChannels(false)
{
init(xmlImage);
}
SCNScene::~SCNScene()
{
}
cv::Rect SCNScene::getRect() const
{
return m_rect;
}
int SCNScene::getNumChannels() const
{
return m_numChannels;
}
void SCNScene::readResampledBlockChannels(const cv::Rect& blockRect, const cv::Size& blockSize,
const std::vector<int>& channelIndicesIn, cv::OutputArray output)
{
auto hFile = getFileHandle();
if (hFile == nullptr)
throw std::runtime_error("SCNImageDriver: Invalid file handle by raster reading operation");
double zoomX = static_cast<double>(blockSize.width) / static_cast<double>(blockRect.width);
double zoomY = static_cast<double>(blockSize.height) / static_cast<double>(blockRect.height);
double zoom = std::max(zoomX, zoomY);
SCNTilingInfo info;
double zoomDirX(-1), zoomDirY(-1);
auto channelIndices(channelIndicesIn);
if(channelIndices.empty())
{
for(int channelIndex=0; channelIndex<m_numChannels; ++channelIndex)
{
channelIndices.push_back(channelIndex);
}
}
for(auto channelIndex: channelIndices)
{
const slideio::TiffDirectory& dir = findZoomDirectory(channelIndex, zoom);
info.channel2ifd[channelIndex] = &dir;
if(zoomDirX<0 || zoomDirY<0)
{
zoomDirX = static_cast<double>(dir.width) / static_cast<double>(m_rect.width);
zoomDirY = static_cast<double>(dir.height) / static_cast<double>(m_rect.height);
}
}
cv::Rect resizedBlock;
ImageTools::scaleRect(blockRect, zoomDirX, zoomDirY, resizedBlock);
TileComposer::composeRect(this, channelIndices, resizedBlock, blockSize, output, (void*)&info);
}
std::string SCNScene::getChannelName(int channel) const
{
return m_channelNames[channel];
}
std::vector<SCNDimensionInfo> SCNScene::parseDimensions(const XMLElement* xmlPixels)
{
std::vector<SCNDimensionInfo> dimensions;
for (const auto* xmlDimension = xmlPixels->FirstChildElement("dimension");
xmlDimension != nullptr; xmlDimension = xmlDimension->NextSiblingElement())
{
SCNDimensionInfo dim = {};
dim.width = xmlDimension->IntAttribute("sizeX", -1);
dim.height = xmlDimension->IntAttribute("sizeY", -1);
dim.r = xmlDimension->IntAttribute("r", -1);
dim.c = xmlDimension->IntAttribute("c", -1);
dim.ifd = xmlDimension->IntAttribute("ifd", -1);
dimensions.push_back(dim);
}
return dimensions;
}
void SCNScene::parseGeometry(const XMLElement* xmlImage)
{
const XMLElement* xmlPixels = xmlImage->FirstChildElement("pixels");
m_rect.width = xmlPixels->IntAttribute("sizeX");
m_rect.height = xmlPixels->IntAttribute("sizeY");
const tinyxml2::XMLElement* xmlView = xmlImage->FirstChildElement("view");
if (xmlView)
{
const int widthNm = xmlView->IntAttribute("sizeX");
const int heightNm = xmlView->IntAttribute("sizeY");
const int xNm = xmlView->IntAttribute("offsetX");
const int yNm = xmlView->IntAttribute("offsetY");
const double pixelWidthNm = (double)widthNm / (double)m_rect.width;
const double pixelHeightNm = (double)heightNm / (double)m_rect.height;
m_resolution.x = 1.e-9 * pixelWidthNm;
m_resolution.y = 1.e-9 * pixelHeightNm;
if (pixelWidthNm > 0)
m_rect.x = (int)std::round(xNm / pixelWidthNm);
if (pixelHeightNm > 0)
m_rect.y = (int)std::round(yNm / pixelHeightNm);
}
}
void SCNScene::parseChannelNames(const XMLElement* xmlImage)
{
m_channelNames.resize(m_numChannels);
const std::vector<std::string> channelSettingsPath = { "scanSettings", "channelSettings" };
const XMLElement* xmlChannelSettings = XMLTools::getElementByPath(xmlImage, channelSettingsPath);
if (xmlChannelSettings)
{
for (const auto* xmlChannel = xmlChannelSettings->FirstChildElement("channel");
xmlChannel != nullptr; xmlChannel = xmlChannel->NextSiblingElement())
{
const char* name = xmlChannel->Attribute("name");
if (name)
{
const int channelIndex = xmlChannel->IntAttribute("index", -1);
if (channelIndex >= 0)
{
m_channelNames[channelIndex] = name;
}
}
}
}
}
void SCNScene::parseMagnification(const XMLElement* xmlImage)
{
const std::vector<std::string> objectivePath = { "scanSettings", "objectiveSettings", "objective" };
const XMLElement* xmlObjective = XMLTools::getElementByPath(xmlImage, objectivePath);
if (xmlObjective) {
m_magnification = xmlObjective->DoubleText(0);
}
}
void SCNScene::defineChannelDataType()
{
m_channelDataType.resize(m_numChannels);
for (int channelIndex = 0; channelIndex < m_numChannels; ++channelIndex)
{
DataType dataType = getChannelDirectories(channelIndex)[0].dataType;
m_channelDataType[channelIndex] = dataType==DataType::DT_None?DataType::DT_Byte:dataType;
}
}
void SCNScene::setupChannels(const XMLElement* xmlImage)
{
const XMLElement* xmlPixels = xmlImage->FirstChildElement("pixels");
int maxChannelIndex = -1;
std::vector<SCNDimensionInfo> dimensions = parseDimensions(xmlPixels);
std::for_each(dimensions.begin(), dimensions.end(),
[&maxChannelIndex](const SCNDimensionInfo& dim){
maxChannelIndex = std::max(dim.c, maxChannelIndex);
});
m_channelDirectories.resize(std::max(1, maxChannelIndex + 1));
for(auto & dim: dimensions) {
int channel = dim.c < 0 ? 0 : dim.c;
TiffDirectory channelDir;
TiffTools::scanTiffDir(m_tiff, dim.ifd, 0, channelDir);
m_channelDirectories[channel].push_back(channelDir);
}
for(auto & dirs:m_channelDirectories) {
std::sort(dirs.begin(), dirs.end(), [](const TiffDirectory& left, const TiffDirectory& right)->bool {
return left.width > right.width;
});
}
if (maxChannelIndex > 0) {
m_numChannels = maxChannelIndex + 1;
}
else {
m_numChannels = m_channelDirectories[0][0].channels;
m_interleavedChannels = true;
}
}
void SCNScene::init(const XMLElement* xmlImage)
{
m_tiff = libtiff::TIFFOpen(m_filePath.c_str(), "r");
if (!m_tiff.isValid())
{
throw std::runtime_error(std::string("SCNImageDriver: Cannot open file:") + m_filePath);
}
const char* name = xmlImage->Attribute("name");
m_name = name ? name : "unknown";
XMLPrinter printer;
xmlImage->Accept(&printer);
std::stringstream imageDoc;
imageDoc << printer.CStr();
m_reawMetadata = imageDoc.str();
parseGeometry(xmlImage);
setupChannels(xmlImage);
parseChannelNames(xmlImage);
parseMagnification(xmlImage);
parseChannelNames(xmlImage);
defineChannelDataType();
}
const TiffDirectory& SCNScene::findZoomDirectory(int channelIndex, double zoom) const
{
const cv::Rect sceneRect = getRect();
const double sceneWidth = static_cast<double>(sceneRect.width);
const auto& directories = getChannelDirectories(channelIndex);
int index = Tools::findZoomLevel(zoom, (int)directories.size(), [&directories, sceneWidth](int index) {
return directories[index].width / sceneWidth;
});
return directories[index];
}
int SCNScene::getTileCount(void* userData)
{
const SCNTilingInfo* info = (const SCNTilingInfo*)userData;
const TiffDirectory* dir = info->channel2ifd.begin()->second;
int tilesX = (dir->width - 1) / dir->tileWidth + 1;
int tilesY = (dir->height - 1) / dir->tileHeight + 1;
return tilesX * tilesY;
}
bool SCNScene::getTileRect(int tileIndex, cv::Rect& tileRect, void* userData)
{
const SCNTilingInfo* info = (const SCNTilingInfo*)userData;
const TiffDirectory* dir = info->channel2ifd.begin()->second;
const int tilesX = (dir->width - 1) / dir->tileWidth + 1;
const int tilesY = (dir->height - 1) / dir->tileHeight + 1;
const int tileY = tileIndex / tilesX;
const int tileX = tileIndex % tilesX;
tileRect.x = tileX * dir->tileWidth;
tileRect.y = tileY * dir->tileHeight;
tileRect.width = dir->tileWidth;
tileRect.height = dir->tileHeight;
return true;
}
bool SCNScene::readTile(int tileIndex, const std::vector<int>& channelIndices, cv::OutputArray tileRaster,
void* userData)
{
const SCNTilingInfo* info = (const SCNTilingInfo*)userData;
if(m_interleavedChannels)
{
const TiffDirectory* dir = info->channel2ifd.begin()->second;
TiffTools::readTile(getFileHandle(), *dir, tileIndex, channelIndices, tileRaster);
}
else if(channelIndices.size()==1)
{
const std::vector<int> localChannelIndices = { 0 };
const TiffDirectory* dir = info->channel2ifd.begin()->second;
TiffTools::readTile(getFileHandle(), *dir, tileIndex, localChannelIndices, tileRaster);
}
else
{
const std::vector<int> localChannelIndices = { 0 };
std::vector<cv::Mat> channelRasters;
channelRasters.resize(channelIndices.size());
for(int channelIndex:channelIndices)
{
auto it = info->channel2ifd.find(channelIndex);
if (it == info->channel2ifd.end())
throw std::runtime_error(
(boost::format(
"SCNImageDriver: invalid channel index (%1%) received during tile reading. File %2%.")
% channelIndex % m_filePath).str());
const TiffDirectory* dir = it->second;
TiffTools::readTile(getFileHandle(), *dir, tileIndex, localChannelIndices, channelRasters[channelIndex]);
}
cv::merge(channelRasters, tileRaster);
}
//{
// cv::Rect tileRect;
// getTileRect(tileIndex, tileRect, userData);
// const std::string path = (boost::format("D:/Temp/tiles/tile_x%1%_y%2%.png") % tileRect.x % tileRect.y).str();
// slideio::ImageTools::writeRGBImage(path, slideio::Compression::Png, tileRaster.getMat());
//}
return true;
}
| 36.322259 | 119 | 0.659929 | [
"vector"
] |
3a4064007416763d77307cef390786c2ad924144 | 2,514 | cpp | C++ | Single_Kinect/KinectV2_Acquisition/KinectV2_Acquisition.cpp | BristolVisualPFT/Double_Kinect_3D_Data_Acquisition_Registration | d81a3ddd6804aa12be8ef440eb6ccb3545c3af53 | [
"Intel",
"MIT"
] | 20 | 2016-11-02T18:20:03.000Z | 2022-03-14T02:29:24.000Z | Single_Kinect/KinectV2_Acquisition/KinectV2_Acquisition.cpp | BristolVisualPFT/Double_Kinect_3D_Data_Acquisition_Registration | d81a3ddd6804aa12be8ef440eb6ccb3545c3af53 | [
"Intel",
"MIT"
] | 8 | 2016-09-23T14:16:44.000Z | 2016-10-29T17:31:55.000Z | Single_Kinect/KinectV2_Acquisition/KinectV2_Acquisition.cpp | BristolVisualPFT/Double_Kinect_3D_Data_Acquisition_Registration | d81a3ddd6804aa12be8ef440eb6ccb3545c3af53 | [
"Intel",
"MIT"
] | 2 | 2019-06-13T00:52:39.000Z | 2019-06-22T20:57:15.000Z | ///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////// University of Bristol ////////////////
////////////// Computer Science Department ////////////////
//===================================================================================================//
/////// This is an open source code for: ///////
//////// "3D Data Acquisition and Registration using Two Opposing Kinects" //////////
//////////////// V. Soleimani, M. Mirmehdi, D. Damen, S. Hannuna, M. Camplani /////////////////
//////////////// International Conference on 3D Vision, Stanford, 2016 /////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Form1.h"
using namespace KinectV2_Acquisition;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew Form1());
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////// University of Bristol ////////////////
////////////// Computer Science Department ////////////////
//===================================================================================================//
/////// This is an open source code for: ///////
//////// "3D Data Acquisition and Registration using Two Opposing Kinects" //////////
//////////////// V. Soleimani, M. Mirmehdi, D. Damen, S. Hannuna, M. Camplani /////////////////
//////////////// International Conference on 3D Vision, Stanford, 2016 /////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
| 62.85 | 104 | 0.287192 | [
"3d"
] |
3a444a119b649655e88d2f5a64017c5d60e42106 | 2,948 | cpp | C++ | src/Base/String.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | 2 | 2015-01-14T20:20:51.000Z | 2015-09-08T15:49:18.000Z | src/Base/String.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | null | null | null | src/Base/String.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | 1 | 2015-11-03T13:58:58.000Z | 2015-11-03T13:58:58.000Z | /*
Phobos 3d
January 2010
Copyright (c) 2005-2011 Bruno Sanches http://code.google.com/p/phobos3d
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "Phobos/String.h"
#include <boost/algorithm/string/trim.hpp>
namespace Phobos
{
using namespace std;
size_t StringReplaceAll(String_t &str, char search, char replace)
{
size_t count = 0;
for(string::iterator it = str.begin(), end = str.end(); it != end; ++it)
{
if(*it == search)
{
++count;
*it = replace;
}
}
return count;
}
void StringReplaceAll(String_t &out, const String_t &src, char search, char replace)
{
out.clear();
for(string::const_iterator it = src.begin(), end = src.end(); it != end; ++it)
{
out += *it == search ? replace : *it;
}
}
void StringTrim(String_t &str, int mode)
{
using namespace boost;
if(mode & STRING_TRIM_LEFT)
{
trim_left(str);
}
if(mode & STRING_TRIM_RIGHT)
{
trim_right(str);
}
}
bool StringIsBlank(const String_t &src)
{
const std::locale& loc=std::locale();
for(string::const_iterator it = src.begin(), end = src.end(); it != end; ++it)
{
if(!std::isspace(*it, loc))
return false;
}
return true;
}
bool StringSplitBy(String_t &out, const String_t &src, char ch, size_t pos, size_t *outPos)
{
const size_t sz = src.length();
size_t startPos = pos;
size_t len = 0;
out.clear();
for(;pos < sz; ++pos)
{
if(src[pos] == ch)
{
len = pos - startPos;
if(len == 0)
{
startPos = pos + 1;
continue;
}
++pos;
goto COPY_SUB;
}
}
//When the loop ends normally, we need to compute len
len = pos - startPos;
//end of the string?
if((pos >= sz) && (len == 0))
return(false);
//no split char found, check if we can return he full string
if(startPos == 0)
{
out = src;
}
else
{
COPY_SUB:
//out.SetSub(this, startPos, len);
out.assign(src, startPos, len);
}
if(outPos)
*outPos = pos;
return(true);
}
bool StringToBoolean(const String_t &a)
{
if(a.compare("true") == 0)
return true;
else if(a.compare("false") == 0)
return false;
else
{
return std::stoi (a) ? true : false;
}
}
}
| 21.676471 | 243 | 0.654342 | [
"3d"
] |
3a4528ba886b4ad078c5e09865e12f994a41369f | 6,212 | cc | C++ | node_modules/aerospike/src/main/client.cc | pygupta/tweetaspike | bc15d20fe7111cabc6e6d0e2e84784cd44bd734f | [
"Apache-2.0"
] | 1 | 2021-08-09T04:47:07.000Z | 2021-08-09T04:47:07.000Z | node_modules/aerospike/src/main/client.cc | pygupta/tweetaspike | bc15d20fe7111cabc6e6d0e2e84784cd44bd734f | [
"Apache-2.0"
] | null | null | null | node_modules/aerospike/src/main/client.cc | pygupta/tweetaspike | bc15d20fe7111cabc6e6d0e2e84784cd44bd734f | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2013-2014 Aerospike, 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.
******************************************************************************/
extern "C" {
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/as_config.h>
#include <aerospike/as_key.h>
#include <aerospike/as_record.h>
}
#include <node.h>
#include "client.h"
#include "util/conversions.h"
using namespace v8;
/*******************************************************************************
* Fields
******************************************************************************/
/**
* JavaScript constructor for AerospikeClient
*/
Persistent<Function> AerospikeClient::constructor;
/*******************************************************************************
* Constructor and Destructor
******************************************************************************/
AerospikeClient::AerospikeClient() {}
AerospikeClient::~AerospikeClient() {}
/*******************************************************************************
* Methods
******************************************************************************/
/**
* Initialize a client object.
* This creates a constructor function, and sets up the prototype.
*/
void AerospikeClient::Init()
{
// Prepare constructor template
Local<FunctionTemplate> cons = FunctionTemplate::New(New);
cons->SetClassName(String::NewSymbol("AerospikeClient"));
cons->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
cons->PrototypeTemplate()->Set(String::NewSymbol("batchGet"), FunctionTemplate::New(BatchGet)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("batchExists"), FunctionTemplate::New(BatchExists)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("close"), FunctionTemplate::New(Close)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("connect"), FunctionTemplate::New(Connect)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("exists"), FunctionTemplate::New(Exists)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("get"), FunctionTemplate::New(Get)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("info"), FunctionTemplate::New(Info)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("operate"), FunctionTemplate::New(Operate)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("put"), FunctionTemplate::New(Put)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("remove"), FunctionTemplate::New(Remove)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("select"), FunctionTemplate::New(Select)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("udfRegister"), FunctionTemplate::New(Register)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("execute"), FunctionTemplate::New(Execute)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("udfRemove"), FunctionTemplate::New(UDFRemove)->GetFunction());
cons->PrototypeTemplate()->Set(String::NewSymbol("updateLogging"), FunctionTemplate::New(SetLogLevel)->GetFunction());
constructor = Persistent<Function>::New(NODE_ISOLATE_PRE cons->GetFunction());
}
/**
* Instantiate a new 'Aerospike(config)'
*/
Handle<Value> AerospikeClient::New(const Arguments& args)
{
NODE_ISOLATE_DECL;
HANDLESCOPE;
AerospikeClient * client = new AerospikeClient();
client->as = (aerospike*) cf_malloc(sizeof(aerospike));
client->log = (LogInfo*) cf_malloc(sizeof(LogInfo));
// initialize the log to default values.
LogInfo * log = client->log;
log->fd = 2;
log->severity = AS_LOG_LEVEL_INFO;
// initialize the config to default values.
as_config config;
as_config_init(&config);
// Assume by default log is not set
if(args[0]->IsObject()) {
int default_log_set = 0;
if (args[0]->ToObject()->Has(String::NewSymbol("log")))
{
Local<Value> log_val = args[0]->ToObject()->Get(String::NewSymbol("log")) ;
if (log_from_jsobject( client->log, log_val->ToObject()) == AS_NODE_PARAM_OK) {
default_log_set = 1; // Log is passed as an argument. set the default value
} else {
//log info is set to default level
}
}
if ( default_log_set == 0 ) {
LogInfo * log = client->log;
log->fd = 2;
}
}
if (args[0]->IsObject() ) {
config_from_jsobject(&config, args[0]->ToObject(), client->log);
}
aerospike_init(client->as, &config);
as_v8_debug(client->log, "Aerospike object initialization : success");
client->Wrap(args.This());
return scope.Close(args.This());
}
/**
* Instantiate a new 'Aerospike(config)'
*/
Handle<Value> AerospikeClient::NewInstance(const Arguments& args)
{
HANDLESCOPE;
const unsigned argc = 1;
Handle<Value> argv[argc] = { args[0] };
Local<Object> instance = constructor->NewInstance(argc, argv);
return scope.Close(instance);
}
Handle<Value> AerospikeClient::SetLogLevel(const Arguments& args)
{
HANDLESCOPE;
AerospikeClient * client = ObjectWrap::Unwrap<AerospikeClient>(args.This());
if (args[0]->IsObject()){
LogInfo * log = client->log;
if ( log_from_jsobject(log, args[0]->ToObject()) != AS_NODE_PARAM_OK ) {
log->severity = AS_LOG_LEVEL_INFO;
log->fd = 2;
}
}
return scope.Close(client->handle_);
}
| 37.648485 | 122 | 0.609627 | [
"object"
] |
3a4655aec901aa9c19f4bf78480fd6700b8e8eda | 2,052 | cc | C++ | src/connectivity/bluetooth/core/bt-host/gatt/connection.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | src/connectivity/bluetooth/core/bt-host/gatt/connection.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | src/connectivity/bluetooth/core/bt-host/gatt/connection.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2017 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 "connection.h"
#include <zircon/assert.h>
#include <numeric>
#include "client.h"
#include "server.h"
#include "src/connectivity/bluetooth/core/bt-host/att/database.h"
#include "src/connectivity/bluetooth/core/bt-host/common/log.h"
#include "src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.h"
namespace bt::gatt::internal {
Connection::Connection(std::unique_ptr<Client> client, std::unique_ptr<Server> server,
RemoteServiceWatcher svc_watcher, async_dispatcher_t* gatt_dispatcher)
: server_(std::move(server)), weak_ptr_factory_(this) {
ZX_ASSERT(svc_watcher);
remote_service_manager_ =
std::make_unique<RemoteServiceManager>(std::move(client), gatt_dispatcher);
remote_service_manager_->set_service_watcher(std::move(svc_watcher));
}
void Connection::Initialize(std::vector<UUID> service_uuids) {
ZX_ASSERT(remote_service_manager_);
auto uuids_count = service_uuids.size();
// status_cb must not capture att_ in order to prevent reference cycle.
auto status_cb = [self = weak_ptr_factory_.GetWeakPtr(), uuids_count](att::Result<> status) {
if (!self) {
return;
}
if (bt_is_error(status, ERROR, "gatt", "client setup failed")) {
// Signal a link error.
self->ShutDown();
} else if (uuids_count > 0) {
bt_log(DEBUG, "gatt", "primary service discovery complete for (%zu) service uuids",
uuids_count);
} else {
bt_log(DEBUG, "gatt", "primary service discovery complete");
}
};
remote_service_manager_->Initialize(std::move(status_cb), std::move(service_uuids));
}
void Connection::ShutDown() {
// We shut down the connection from the server not for any technical reason, but just because it
// was simpler to expose the att::Bearer's ShutDown behavior from the server.
server_->ShutDown();
}
} // namespace bt::gatt::internal
| 34.779661 | 98 | 0.716862 | [
"vector"
] |
3a46fdff4baa9b4f32321a9b34c35dcfe8d54e27 | 23,406 | hpp | C++ | sick_ldmrs_driver/src/driver/src/datatypes/Object.hpp | sgermanserrano/drivers | e29f6e13a71e8af4d70def3f2844acc878c77204 | [
"Apache-2.0"
] | 14 | 2020-06-02T10:25:47.000Z | 2021-08-04T06:28:07.000Z | sick_ldmrs_driver/src/driver/src/datatypes/Object.hpp | sgermanserrano/drivers | e29f6e13a71e8af4d70def3f2844acc878c77204 | [
"Apache-2.0"
] | 1 | 2020-09-03T18:26:59.000Z | 2020-09-03T19:16:14.000Z | sick_ldmrs_driver/src/driver/src/datatypes/Object.hpp | sgermanserrano/drivers | e29f6e13a71e8af4d70def3f2844acc878c77204 | [
"Apache-2.0"
] | 18 | 2020-05-29T07:52:07.000Z | 2022-02-12T00:54:49.000Z | //
// Object.hpp
//
// Container for objects.
//
#ifndef OBJECT_HPP
#define OBJECT_HPP
#include <vector>
#include "../BasicDatatypes.hpp"
#include "Point2D.hpp"
#include "Polygon2D.hpp"
#include "Box2D.hpp"
#include "../tools/Time.hpp"
namespace datatypes
{
// Represents a tracked object in our environmental model.
/**
* This class contains all that is known about objects in the
* environmental model: %Object position, velocity, course angle, and
* classification.
*
* \image html objectcoords.png "Tracked object at position A, Course Angle Psi, Velocity vector vh, and Size sx, xy"
*
* The available information about each object is shown in the figure
* above. The host vehicle's axis system is X, Y with the origin at
* H. The center point A of the object is given in the host vehicle's
* axis system X, Y by getCenterPoint(). (In exact ISO 8855
* terminology, the used axis system X,Y is the host vehicle's
* "intermediate axis system")
*
* The orientation of the object is given by the course angle Psi
* (\f$\psi\f$) by getCourseAngle(), which is the angle from the host
* vehicle's X axis to the object's Xo axis. Other names for this
* angle are the "object's yaw angle" \f$\psi\f$ or heading or
* orientation. This defines the object's axis system Xo, Yo.
*
* The velocity of the object is given by the velocity vector vh
* (\f$v_h\f$) by getAbsoluteVelocity(), which gives the object's
* velocity specified in the host vehicle's axis system. (In exact ISO
* 8855 terminology, the vector vh is the object's "horizontal
* velocity".)
*
* The size of the object is given by the side lengths sx, sy of the
* rectangle in the object's axis system by getObjectBox(). Position,
* orientation, and size are given altogether by getBox().
*
* (Note: In exact ISO 8855 terminology, the object's axis system
* Xo,Yo might point into a slightly different direction than the
* velocity vector, in which case \f$v_h\f$ is rotated from X_o by the
* sideslip angle \f$\beta\f$. The rotation of the velocity vector
* compared to the host vehicle's axis system, the course angle
* \f$\nu\f$, is then given by \f$\nu=\psi+\beta\f$. However,
* depending on the used tracking algorithms the sideslip angle is
* neglected and \f$\nu=\psi\f$, so there should be no difference
* between the course angle and the yaw angle.)
*
* Note: The current %Laserscanner tracking algorithms can fill in only
* a subset of the data fields that exist in this class. But those
* additional data fields are needed as soon as we deal with data
* fusion from WLAN data sources. Since those fusion algorithms are of
* importance to our algorithms as well, we already have reserved the
* member variables for those fields.
*
* Internal note to self: For the next revision one might consider
* adding the following data fields:
*
* - centerOfGravity as opposed to center of geometry in getCenterPoint()
* - maybe a list of available referencePoints
* - maybe an enum of the referencePoint types
* - centerOfGeometry BoundingBox
*/
class Object
{
public:
enum ObjectClassification
{
Unclassified = 0,
UnknownSmall = 1,
UnknownBig = 2,
Pedestrian = 3,
Bike = 4,
Car = 5,
Truck = 6,
Structure_Pylon = 7,
Structure_Beacon = 8,
Structure_GuardRail = 9,
Structure_ConcreteBarrier = 10,
NumClasses,
Unknown = 15
};
public:
Object();
~Object();
/// Equality predicate
bool operator==(const Object& other) const;
/** Returns the index number of this object.
*
* Watch out: In some algorithms, the object id 0 (Null) is used
* as the special value of a non-valid object, but in other
* algorithms the id 0 is regarded as just a normal value as any
* other. However, invalid objects should be marked with
* setValid() instead of a Null-Value here.
*/
UINT16 getObjectId() const { return m_objectId; }
/** Sets the index number of this object.
*
* For setting an object to invalid, use setValid().
*/
void setObjectId(UINT16 v) { m_objectId = v; }
/** Returns the flags that have been set in this object. Currently
* used bits are as follows: bit#0 = basic information is available;
* bit#1 = contour information has been set, bit#2 = boundingBox
* has been set; bit#3 = object contains fused data from other
* sources (WLAN etc.); bit#4 = relative velocity has been set;
* bit#5 = CAN Object Data only (protocol version: 1; either
* bounding box or object box is available (see bit#2);
* analog see bit#4 if relative or absolute velocity has been set);
* bit#6...15 = reserved */
UINT16 getFlags() const { return m_flags; }
void setFlags(UINT16 v) { m_flags = v; }
/** Returns the number of scans in which this object has been
* tracked. */
UINT32 getObjectAge() const { return m_objectAge; }
void setObjectAge(UINT32 v) { m_objectAge = v; }
/** Returns the number of scans in which the object has not been
* observed by measurement (i.e. it was hidden) but instead it has
* only been predicted. */
UINT16 getHiddenStatusAge() const { return m_hiddenStatusAge; }
/** Returns true if the object is not being observed in the very
* last measurement (i.e. it was hidden) but instead it has only
* been predicted. */
bool isHiddenStatus() const { return m_hiddenStatusAge > 0; }
void setHiddenStatusAge(UINT16 v) { m_hiddenStatusAge = v; }
/** Returns the time of when the center point of this object was
* observed. */
const Time& getTimestamp() const { return m_timestamp; }
void setTimestamp(const Time& v) { m_timestamp = v; }
/** Returns the object class that is most likely for this
* object. */
ObjectClassification getClassification() const { return m_classification; }
void setClassification(ObjectClassification v) { m_classification = v; }
/** Returns the number of scans in which the object has has been
* classified in the current classification. */
UINT32 getClassificationAge() const { return m_classificationAge; }
void setClassificationAge(UINT32 v) { m_classificationAge = v; }
/** Returns the quality measure ("Guete") of the current
* classification in [0 .. 1]. */
double getClassificationQuality() const { return m_classificationQuality; }
void setClassificationQuality(double v);
/**
* Returns the tracked center point of geometry ("Mittelpunkt") of
* this object in [meter], relative to our vehicle's coordinate
* system.
*
* This estimated center point is as close to the actual center
* point as possible with the respective tracking algorithm. To be
* more precise, if the tracking algorithm tracks the center of
* gravity (COG) point, the COG point will be given here instead
* of the actual center of geometry. In those cases the actual
* center of geometry is unknown, unfortunately.
*
* More information about the position of the object might be
* obtained from the getContourPoints() pointlist or through
* accessing the SegmentList by getSegment(), but those will
* always give unfiltered (non-tracked) results.
*/
const Point2D& getCenterPoint() const { return m_centerPoint; }
void setCenterPoint(const Point2D& v) { m_centerPoint = v; }
/** Returns the standard deviation (i.e. the uncertainty,
* "Mittelpunkt-Standardabweichung") of the center point of geometry
* estimation of this object, given in Vehicle coordinates in
* [meter]. */
const Point2D& getCenterPointSigma() const { return m_centerPointSigma; }
void setCenterPointSigma(const Point2D& v);
/** Returns the course angle ("Kurswinkel") of this object's
* movement in [radian], in the interval [-pi, pi). This is named
* conforming to ISO 8855; elsewhere this value is also called the
* Orientation or the Heading.
*
* This angle is the angle from the host vehicle's x-coordinate
* axis to the object's x-coordinate axis (which in most cases is
* identical to the object's velocity vector). It is also the sum
* of yaw angle ("Gierwinkel") and sideslip angle
* ("Schwimmwinkel") of this object. */
double getCourseAngle() const { return m_courseAngle; }
/** Sets the course angle ("Kurswinkel") of this object's
* movement in [radian], in the interval [-pi, pi). This is named
* conforming to ISO 8855; elsewhere this value is also called the
* Orientation or the Heading.
*
* If the new course angle is outside of the defined interval
* [-pi, pi), a warning message will be printed and the value will
* be normalized into that interval by normalizeRadians().
*/
void setCourseAngle(double newCourseAngle);
/** Returns the course angle standard deviation (i.e. the
* uncertainty, "Kurswinkel-Standardabweichung") in [radian]. This
* is named conforming to ISO 8855; elsewhere this value is also
* called the Orientation or the Heading. */
double getCourseAngleSigma() const { return m_courseAngleSigma; }
void setCourseAngleSigma(double v);
/** (Usually Unused.) Returns the velocity vector ("Geschwindigkeitsvektor") of this
* object in [meter/seconds], relative to our vehicle's coordinate
* system. Note: The currently implemented tracking will always
* track only the absolute velocity; hence, this field
* relativeVelocity will be unset and simply be zero (or some other irrelevant values). */
const Point2D& getRelativeVelocity() const { return m_relativeVelocity; }
void setRelativeVelocity(const Point2D& v) { m_relativeVelocity = v; }
/** (Usually Unused.) Returns the velocity vector standard deviation (i.e. the
* uncertainty) of this object in [meter/seconds], relative to our
* vehicle's coordinate system. Note: The currently implemented
* tracking will always track only the absolute velocity; hence,
* this field relativeVelocity will be unset and simply be
* zero (or some other irrelevant values). */
const Point2D& getRelativeVelocitySigma() const { return m_relativeVelocitySigma; }
void setRelativeVelocitySigma(const Point2D& v) { m_relativeVelocitySigma = v; }
/** Returns the velocity vector ("Geschwindigkeitsvektor") of this
* object in [meter/seconds] as absolute value. The orientation is
* relative to our vehicle's coordinate system. */
const Point2D& getAbsoluteVelocity() const { return m_absoluteVelocity; }
/** Sets the velocity vector as absolute value. Note: This also updates setMaxAbsoluteVelocity() accordingly. */
void setAbsoluteVelocity(const Point2D& v);
/** Returns the velocity vector standard deviation (i.e. the
* uncertainty) of this object in [meter/seconds], absolute. */
const Point2D& getAbsoluteVelocitySigma() const { return m_absoluteVelocitySigma; }
void setAbsoluteVelocitySigma(const Point2D& v);
/** Returns the estimated size of the object in [meter].
*
* The returned size estimation models a rotated rectangular box
* around the object's center point (hence the name "object
* box"). Point2D::getX() returns the size of this object in
* x-direction of the object's coordinate system (i.e. the object
* length), Point2D::getY() the size in the y-direction (i.e. the
* object width). This value is the filtered size estimation of
* this object.
*
* This box contains (bounds) all of this object's scanpoints and
* is in parallel to the object's coordinate system, i.e. it is using
* the getCourseAngle() orientation. [meter]
*
* \see getCourseAngle(), getCenterPoint(), setObjectBox()
*/
const Point2D& getObjectBox() const { return m_objectBox; }
/** Set the size of the rectangular box of this object. \see
* getObjectBox() */
void setObjectBox(const Point2D& v);
/** Returns a rectangular box around the object's center point in
* [meter]. This method is just shorthand for obtaining the center
* point by getCenterPoint(), the course angle (orientation) by
* getCourseAngle(), and the size of the object by
* getObjectBox(). Box2D::getSize()::getX() returns the size of
* this object in x-direction of the object's coordinate system
* (i.e. the object length), Box2D::getSize()::getY() the size of
* this object in y-direction (i.e. the object width).
*
* \see getCenterPoint(), getCenterPoint(), getObjectBox()
*/
Box2D getBox() const;
/** Returns the object size estimation's standard deviation [meter].
*
* This is given in the object's coordinate system! Watch out for
* necessary coordinate transformations (rotations) if you want to
* use this value in the host vehicle's coordinate system. */
const Point2D& getObjectBoxSigma() const { return m_objectBoxSigma; }
void setObjectBoxSigma(const Point2D& v);
/** Writes the object box x and y variance (squared standard
* deviation) and their covariance into the given variables in the
* host vehicle's coordinate system [meter^2].
*
* In contrast to getObjectBoxSigma(), here the x and y variance
* is rotated from the object coordinate system into the host
* system. Hence, if there was a zero covariance beforehand, a
* non-zero covariance will result after the rotation. */
void getObjectBoxVarCovar(double &var_x, double &var_y, double &covar_xy) const;
/** Returns the size of a rectangle around the object's/bounding box center
* point that contains (bounds) all of this object's scanpoints,
* in parallel to our vehicle's coordinate system axis (also
* called a paraxial rectangle). */
const Point2D& getBoundingBox() const { return m_boundingBox; }
void setBoundingBox(const Point2D& v);
/**
* Returns the center of the bounding box. \sa{getBoundingBox}
*/
const Point2D& getBoundingBoxCenter() const { return m_boundingBoxCenter; }
void setBoundingBoxCenter(const Point2D& v);
/** Returns the point of this object that is closest to the origin
* of our vehicle's coordinate system.
*
* If this is not set, returns a zero-valued point.
*/
const Point2D& getClosestPoint() const { return m_closestPoint; }
void setClosestPoint(const Point2D& v) { m_closestPoint = v; }
/** Returns a vector of points that describes a polygon outline of
* the current object's measurement points. */
const Polygon2D& getContourPoints() const { return m_contourPoints; }
void setContourPoints(const Polygon2D& v);
void addContourPoint(const Point2D cp);
/** An identifier to be used by WLAN fusion algorithms */
UINT64 getVehicleWLANid() const { return m_vehicleWLANid; }
void setVehicleWLANid(UINT64 v) { m_vehicleWLANid = v; }
/** The height of this object in [m] (most probably received
* through WLAN data) */
double getObjectHeight() const { return m_objectHeight; }
void setObjectHeight(double v) { m_objectHeight = v; }
/** The standard deviation of the height of this object in [m]
* (most probably received through WLAN data) */
double getObjectHeightSigma() const { return m_objectHeightSigma; }
void setObjectHeightSigma(double v);
/** The mass of this object in [kilogram] (as received
* e.g. through WLAN data) */
double getObjectMass() const { return m_objectMass; }
void setObjectMass(double v);
/** True, if this object is valid.
*
* This flag will only be used to decide whether this Object is
* included in the serialization, i.e. if an Object has "false"
* here, it will not be serialized and will not be received by a
* receiver. Hence, this flag by itself is not included in the
* serialization.
*
* Again: Invalid objects (those which return false here) will
* *not* be included in the serialization!
*/
bool isValid() const { return m_isValid; }
/** Set whether this object is valid.
*
* This flag will only be used to decide whether this Object is
* included in the serialization, i.e. if an Object has "false"
* here, it will not be serialized and will not be received by a
* receiver. Hence, this flag by itself is not included in the
* serialization.
*
* Again: Invalid objects (those which have false here) will
* *not* be included in the serialization!
*/
void setValid(bool newValue = true) { m_isValid = newValue; }
/** Returns the maximum observed absolute velocity [m/s]
* (Classification feature). The value is NaN if it hasn't been
* set so far. The value is always non-negative, or NaN. */
double getMaxAbsoluteVelocity() const { return m_maxAbsoluteVelocity; }
void setMaxAbsoluteVelocity(double v);
/** Returns the normalized mean distance [m] between scanpoints in
* the segment, or zero if the object is currently hidden.
* (Classification feature) Always non-negative. */
double getNormalizedMeanPointDist() const { return m_normalizedMeanPointDist; }
void setNormalizedMeanPointDist(double v);
/** Returns the total duration for which this object has been
* tracked in [seconds]. (Classification feature, needed for mean
* velocity) Always non-negative. */
double getTotalTrackingDuration() const { return m_totalTrackingDuration; }
void setTotalTrackingDuration(double v);
/** Returns the total path length of object movement that has been
* tracked [m]. (Classification feature) Always non-negative. */
double getTotalTrackedPathLength() const { return m_totalTrackedPathLength; }
void setTotalTrackedPathLength(double v);
/** Returns the mean velocity during the whole time over which the
* object has been tracked [m/s], which is basically just
* getTotalTrackedPathLength() divided by
* getTotalTrackingDuration(). Always non-negative. */
double getMeanAbsoluteVelocity() const;
// Size of the object in memory
const UINT32 getUsedMemory() const { return sizeof(Object); };
/// Size of the serialized representation of this object
/**
* \param version 1,2 == compressed meter values; 3,4 == double values
*/
std::streamsize getSerializedSize(UINT32 version) const;
/** Returns a human-readable form of the content of this object (for debugging output)
* The actual output is merely a conversion to string of the
* return value of toConfigValues().
*/
std::string toString() const;
//\}
/// Returns the given classification value as a string.
static const char* objectClassificationToString(ObjectClassification v);
/// Returns the given classification value as a string with the integer number included.
static std::string objectClassificationToStringWithNum(ObjectClassification v);
/// Returns the given classification value as a short string.
static const char* objectClassificationToShortString(ObjectClassification v);
/// Returns the classification value as converted from the given
/// string. This accepts the output of both
/// objectClassificationToString() and
/// objectClassificationToShortString().
static Object::ObjectClassification stringToObjectClassification(const std::string& s);
/// Just increment objectAge by one.
void incrementObjectAge();
private:
UINT16 m_objectId;
UINT16 m_flags; ///< reserved
// Data from the tracking/classification:
UINT32 m_objectAge; ///< number of scans in which this object has been tracked, or instead time?
UINT16 m_hiddenStatusAge; ///< Counts how long the object has not been observed but only predicted.
Time m_timestamp; ///< Time of when the center point of this object was observed.
ObjectClassification m_classification; ///< The object class that is most likely for this object.
UINT32 m_classificationAge; ///< Counts how long the object has been classified in the current classification.
double m_classificationQuality; ///< The quality of the current classification.
Point2D m_centerPoint; ///< Center point of object rectangle, given in Vehicle coordinate system.
Point2D m_centerPointSigma;
double m_courseAngle; ///< named by ISO 8855; also called Orientation or Heading [rad]
double m_courseAngleSigma; // in [rad]
Point2D m_relativeVelocity; ///< Velocity of this object [meter/seconds], relative to the vehicle coordinate system.
Point2D m_relativeVelocitySigma;
Point2D m_absoluteVelocity; ///< Velocity of this object [meter/seconds] as absolute velocity; the orientation is relative to the vehicle coordinate system.
Point2D m_absoluteVelocitySigma;
Point2D m_objectBox; ///< The object's length and width as a rectangle, relative to the object's coordinate system.
Point2D m_objectBoxSigma;
Point2D m_boundingBoxCenter; ///< Center of the bounding box.
Point2D m_boundingBox; ///< A rectangle in parallel to the vehicle coordinate system (a paraxial rectangle) that contains (bounds) all of this object's points
// These components are also proposed
Point2D m_closestPoint; ///< The point of this object that is closest to the origin of the vehicle coordinate system.
// This can also be calculated
Polygon2D m_contourPoints; ///< A poly-line that describes the outline of the current object measurement.
UINT64 m_vehicleWLANid; ///< An identifier to be used by WLAN fusion algorithms.
double m_objectHeight; ///< The height of this object in [m] (most probably received through WLAN data).
double m_objectHeightSigma; ///< The standard deviation of the height of this object in [m] (most probably received through WLAN data).
double m_objectMass; ///< The mass of this object in [kilogram] (as received e.g. through WLAN data)
/// Classification feature: The maximum observed absolute velocity [m/s]
double m_maxAbsoluteVelocity;
/// Classification feature: Normalized mean distance [m] between
/// scanpoints in the segment, or zero if the object is currently
/// hidden.
double m_normalizedMeanPointDist;
/// Classification feature (needed for mean velocity): Duration of
/// object being tracked in [s]
double m_totalTrackingDuration;
/// Classification feature: Total accumulated path length over which this
/// object has moved during being tracked. [m]
double m_totalTrackedPathLength;
/** Pointer to the Segment that belongs to this object. (Note:
* This assumes that each object was associated to only one
* segment. If more than one segment is associated to this object,
* we're out of luck and need a new data structure.) */
// const Segment *m_segment;
// True, if this object is valid.
bool m_isValid;
};
// ////////////////////////////////////////////////////////////
//
// List of Objects
//
//
class ObjectList : public std::vector<Object>,
public BasicData
{
public:
typedef std::vector<Object> base_class;
ObjectList();
/// Equality predicate
bool operator==(const ObjectList& other) const;
// Size of the object in memory
const UINT32 getUsedMemory() const { return sizeof(*this) + size()*sizeof(Object); };
// Get the timestamp of the object list. Typically it should be the midTimestamp of the corresponding scan.
const Time& getTimestamp() const { return m_timestamp; }
// Set the timestamp of the object list. Typically it should be the midTimestamp of the corresponding scan.
void setTimestamp(const Time& timestamp);
/// Just increment objectAge of all objects by one.
void incrementObjectAge();
protected:
// The timestamp of the ObjectList
Time m_timestamp;
};
} // namespace datatypes
#endif // OBJECT_HPP
| 42.402174 | 166 | 0.721353 | [
"geometry",
"object",
"vector",
"model"
] |
3a49428ccb40bda0d680b854663c4327cc12413f | 7,684 | cpp | C++ | getting_started/dataflow/dataflow_pipes_ocl/src/host.cpp | drankincms/SDAccel_Examples | 5e8f7ee307d27d8268f097fcf902f63eecd4c22d | [
"BSD-3-Clause"
] | null | null | null | getting_started/dataflow/dataflow_pipes_ocl/src/host.cpp | drankincms/SDAccel_Examples | 5e8f7ee307d27d8268f097fcf902f63eecd4c22d | [
"BSD-3-Clause"
] | null | null | null | getting_started/dataflow/dataflow_pipes_ocl/src/host.cpp | drankincms/SDAccel_Examples | 5e8f7ee307d27d8268f097fcf902f63eecd4c22d | [
"BSD-3-Clause"
] | null | null | null | /**********
Copyright (c) 2018, Xilinx, 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.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********/
/*******************************************************************************
Description: SDx Vector Addition using Blocking Pipes Operation
*******************************************************************************/
#define INCR_VALUE 10
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <vector>
//OpenCL utility layer include
#include "xcl.h"
#include "oclHelper.h"
#define OCL_CHECK(call) \
do { \
cl_int err = call; \
if (err != CL_SUCCESS) { \
printf("Error calling " #call ", error: %s\n", oclErrorCode(err)); \
exit(EXIT_FAILURE); \
} \
} while (0);
template <typename T>
struct aligned_allocator
{
using value_type = T;
T* allocate(std::size_t num)
{
void* ptr = nullptr;
if (posix_memalign(&ptr,4096,num*sizeof(T)))
throw std::bad_alloc();
return reinterpret_cast<T*>(ptr);
}
void deallocate(T* p, std::size_t num)
{
free(p);
}
};
int main(int argc, char** argv)
{
size_t data_size = 1024*1024;
/* Reducing the data size for emulation mode */
char *xcl_mode = getenv("XCL_EMULATION_MODE");
if (xcl_mode != NULL){
data_size = 1024;
}
//Allocate Memory in Host Memory
size_t vector_size_bytes = sizeof(int) * data_size;
std::vector<int,aligned_allocator<int>> source_input (data_size);
std::vector<int,aligned_allocator<int>> source_hw_results(data_size);
std::vector<int,aligned_allocator<int>> source_sw_results(data_size);
// Create the test data and Software Result
for(size_t i = 0 ; i < data_size; i++){
source_input[i] = i;
source_sw_results[i] = i + INCR_VALUE;
source_hw_results[i] = 0;
}
//OPENCL HOST CODE AREA START
//Create Program and Kernels.
xcl_world world = xcl_world_single();
cl_program program = xcl_import_binary(world,"adder");
cl_kernel krnl_adder_stage = xcl_get_kernel(program, "adder_stage");
//Creating additional Kernels
cl_kernel krnl_input_stage = xcl_get_kernel(program, "input_stage");
cl_kernel krnl_output_stage = xcl_get_kernel(program, "output_stage");
// By-default xcl_world_single create command queues with sequential command.
// For this example, user to replace command queue with out of order command queue
clReleaseCommandQueue(world.command_queue);
int err;
world.command_queue = clCreateCommandQueue(world.context, world.device_id,
CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_PROFILING_ENABLE,
&err);
if (err != CL_SUCCESS){
std::cout << "Error: Failed to create a command queue!" << std::endl;
std::cout << "Test failed" << std::endl;
return EXIT_FAILURE;
}
//Allocate Buffer in Global Memory
cl_mem buffer_output = xcl_malloc(world, CL_MEM_WRITE_ONLY, vector_size_bytes);
cl_mem buffer_input = clCreateBuffer(world.context,
CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR,
vector_size_bytes, source_input.data(), NULL);
cl_event write_event;
// Using clEnqueueMigrateMemObjects() instead of clEnqueueWriteBuffer() to avoid
// deadlock in real hardware which can be noticed only for large dataset.
// Rootcause: design leads to a deadlock when host->DDR and
// output_stage->DDR causes a contention and deadlock. In small dataset, the
// data gets transferred from host-> DDR in 1 burst and hence no deadlock.
// Solution: Start output_stage when host->DDR data transfer is completed.
// clEnqueueMigrateMemObject() event is used for all three kernels to avoid deadlock.
//Copy input data to device global memory
OCL_CHECK(clEnqueueMigrateMemObjects(world.command_queue,1, &buffer_input,
0 /* flags, 0 means from host*/,0, NULL,&write_event));
//Wait
clFinish(world.command_queue);
int inc = INCR_VALUE;
int size = data_size;
//Set the Kernel Arguments
xcl_set_kernel_arg(krnl_input_stage,0,sizeof(cl_mem),&buffer_input);
xcl_set_kernel_arg(krnl_input_stage,1,sizeof(int),&size);
xcl_set_kernel_arg(krnl_adder_stage,0,sizeof(int),&inc);
xcl_set_kernel_arg(krnl_adder_stage,1,sizeof(int),&size);
xcl_set_kernel_arg(krnl_output_stage,0,sizeof(cl_mem),&buffer_output);
xcl_set_kernel_arg(krnl_output_stage,1,sizeof(int),&size);
//Launch the Kernel
OCL_CHECK(clEnqueueTask(world.command_queue,krnl_input_stage, 1, &write_event, NULL));
OCL_CHECK(clEnqueueTask(world.command_queue,krnl_adder_stage, 1, &write_event, NULL));
OCL_CHECK(clEnqueueTask(world.command_queue,krnl_output_stage,1, &write_event, NULL));
//wait for all kernels to finish their operations
clFinish(world.command_queue);
//Copy Result from Device Global Memory to Host Local Memory
xcl_memcpy_from_device(world, source_hw_results.data(), buffer_output,vector_size_bytes);
//Release Device Memories and Kernels
clReleaseMemObject(buffer_input);
clReleaseMemObject(buffer_output);
clReleaseKernel(krnl_input_stage);
clReleaseKernel(krnl_adder_stage);
clReleaseKernel(krnl_output_stage);
clReleaseProgram(program);
xcl_release_world(world);
//OPENCL HOST CODE AREA END
// Compare the results of the Device to the simulation
int match = 0;
for (size_t i = 0 ; i < data_size; i++){
if (source_hw_results[i] != source_sw_results[i]){
std::cout << "Error: Result mismatch" << std::endl;
std::cout << "i = " << i << " CPU result = " << source_sw_results[i]
<< " Device result = " << source_hw_results[i] << std::endl;
match = 1;
break;
}
}
std::cout << "TEST " << (match ? "FAILED" : "PASSED") << std::endl;
return (match ? EXIT_FAILURE : EXIT_SUCCESS);
}
| 41.090909 | 101 | 0.661114 | [
"vector"
] |
3a49539238c7a5a8af5cfbff2329a42a51787fc6 | 3,152 | cxx | C++ | Modules/Numerics/Statistics/test/itkDecisionRuleTest.cxx | eile/ITK | 2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1 | [
"Apache-2.0"
] | 3 | 2019-11-19T09:47:25.000Z | 2022-02-24T00:32:31.000Z | Modules/Numerics/Statistics/test/itkDecisionRuleTest.cxx | eile/ITK | 2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1 | [
"Apache-2.0"
] | 1 | 2019-03-18T14:19:49.000Z | 2020-01-11T13:54:33.000Z | Modules/Numerics/Statistics/test/itkDecisionRuleTest.cxx | eile/ITK | 2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1 | [
"Apache-2.0"
] | 1 | 2022-02-24T00:32:36.000Z | 2022-02-24T00:32:36.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkDecisionRule.h"
namespace itk {
namespace Statistics {
namespace DecisionRuleTest {
class MyDecisionRule : public DecisionRule
{
public:
/** Standard class typedef. */
typedef MyDecisionRule Self;
typedef DecisionRule Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Standard macros */
itkTypeMacro(MyDecisionRule, DecisionRule);
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Types for discriminant values and vectors. */
typedef Superclass::MembershipValueType MembershipValueType;
typedef Superclass::MembershipVectorType MembershipVectorType;
/** Types for class identifiers. */
typedef Superclass::ClassIdentifierType ClassIdentifierType;
/** Evaluate membership score */
virtual ClassIdentifierType Evaluate(const MembershipVectorType &scoreVector) const ITK_OVERRIDE
{
double max = scoreVector[0];
unsigned int maxIndex = 0;
unsigned int i;
for (i = 1; i < scoreVector.size(); i++)
{
if (scoreVector[i] > max)
{
max = scoreVector[i];
maxIndex = i;
}
}
return maxIndex;
}
};
}
}
}
int itkDecisionRuleTest(int, char* [] )
{
typedef itk::Statistics::DecisionRuleTest::MyDecisionRule DecisionRuleType;
typedef DecisionRuleType::MembershipVectorType MembershipVectorType;
DecisionRuleType::Pointer decisionRule = DecisionRuleType::New();
std::cout << decisionRule->GetNameOfClass() << std::endl;
std::cout << decisionRule->DecisionRuleType::Superclass::GetNameOfClass() << std::endl;
decisionRule->Print(std::cout);
MembershipVectorType membershipScoreVector;
double membershipScore1;
membershipScore1 = 0.1;
membershipScoreVector.push_back( membershipScore1 );
double membershipScore2;
membershipScore2 = 0.5;
membershipScoreVector.push_back( membershipScore2 );
double membershipScore3;
membershipScore3 = 1.9;
membershipScoreVector.push_back( membershipScore3 );
// the maximum score is the third component. The decision rule should
// return index ( 2)
if( decisionRule->Evaluate( membershipScoreVector ) != 2 )
{
std::cerr << "Decision rule computation is incorrect!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 29.735849 | 98 | 0.675444 | [
"object"
] |
3a49f6ca9c7f0b9455bc9d9555d703ff841483ed | 10,305 | cpp | C++ | control_7688/control.cpp | NTUEELightDance/2019-LightDance | 2e2689f868364e16972465abc22801aaeaf3d8ba | [
"MIT"
] | 2 | 2019-07-16T10:40:52.000Z | 2022-03-14T00:26:42.000Z | control_7688/control.cpp | NTUEELightDance/2019-LightDance | 2e2689f868364e16972465abc22801aaeaf3d8ba | [
"MIT"
] | null | null | null | control_7688/control.cpp | NTUEELightDance/2019-LightDance | 2e2689f868364e16972465abc22801aaeaf3d8ba | [
"MIT"
] | 2 | 2019-12-01T07:40:04.000Z | 2020-02-15T09:58:50.000Z |
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "mraa/common.hpp"
#include "mraa/gpio.hpp"
#include "mraa.hpp"
#ifdef USE_INTERNAL_PWM
#include "mraa/pwm.hpp"
#else
#include "PCA9685.h"
#endif
#include "common.h"
using namespace rapidjson;
using namespace std;
#define SPI_PORT 0
mraa::Spi spi(SPI_PORT);
Config conf;
bool use_local_file = false;
char buf[1024];
char sendbuf[1024];
unsigned int num_ws = 5;
unsigned int num_led[] = {88,96,60,36,36};
string json_str;
bool data_ok = false;
bool time_ok = false;
double TIME_BASE = 0;
#ifdef USE_INTERNAL_PWM
mraa::Pwm pwm_0(18);
mraa::Pwm pwm_1(19);
#else
PCA9685 pca(0, 0x40);
#endif
void init_spi(){
spi.mode( mraa::SPI_MODE0 );
spi.frequency(2000000);
}
vector < vector< vector<Color> > > anim;
double get_sys_time() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + (((double) tv.tv_usec) / 1000000);
}
vector<Seg> LD[NUM_PARTS];
int get_light(int part, double tm) {
int res = 0;
vector<Seg>& vec = LD[part];
int S = vec.size();
if(S == 0) return res;
int lb = 0, rb = S-1;
while(lb < rb)
{
int mb = (lb + rb + 1) >> 1;
if(vec[mb].start > tm)
rb = mb - 1;
else
lb = mb;
}
Seg& seg = vec[lb];
if(seg.start <= tm && tm <= seg.end)
{
if(seg.ltype == 1)
res = 4095;
else if(seg.ltype == 2)
res = 4095 * (tm - seg.start) / (seg.end - seg.start);
else if(seg.ltype == 3)
res = 4095 * (seg.end - tm) / (seg.end - seg.start);
}
return res;
}
int init_sock() {
int sock = 0;
struct sockaddr_in dest;
memset(&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
inet_pton(AF_INET, SERVER_ADDR, &dest.sin_addr);
dest.sin_port = htons(SERVER_PORT);
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock < 0) {
cerr << "Failed to create socket." << endl;
return -1;
}
if(connect(sock, (struct sockaddr*) &dest, sizeof(dest)) < 0) {
cerr << "Failed to connect to server." << endl;
return -1;
}
recv(sock, buf, 1024, 0);
if(buf[0] != 'N') {
cerr << "Failed to establish a connection." << endl;
close(sock);
return -1;
}
sprintf(sendbuf, "%d", conf.board_id);
send(sock, sendbuf, strlen(sendbuf), 0);
recv(sock, buf, 1024, 0);
if(buf[0] != 'O') {
cerr << "Board rejected by server!" << endl;
close(sock);
return -1;
}
return sock;
}
int main(int argc, char** argv) {
conf = read_config();
if(argc > 1) {
if(strcmp(argv[1], "--local") == 0) use_local_file = true;
}
#ifdef USE_INTERNAL_PWM
pwm_0.period_ms(2);
pwm_1.period_ms(2);
pwm_0.enable(true);
pwm_1.enable(true);
#endif
Document doc;
if(use_local_file) {
while(!data_ok) {
FILE *fp = fopen("data.json", "r");
if(fp < 0) {
cerr << "Cannot read local file!" << endl;
sleep(2);
continue;
}
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
doc.ParseStream(is);
fclose(fp);
cout << "Local file read OK" << endl;
data_ok = true;
}
} else {
while(!data_ok) {
int sock = init_sock();
if(sock < 0) {
cerr << "DATA Connection failed!" << endl;
sleep(2);
continue;
}
strcpy(sendbuf, "D");
send(sock, sendbuf, strlen(sendbuf), 0);
recv(sock, buf, 1024, 0);
int data_len = atoi(buf);
cout << "Data length: " << data_len << endl;
ssize_t bytesRead = 0;
json_str = "";
while (bytesRead < data_len) {
ssize_t rv = recv(sock, buf, 512, 0);
if(rv == 0) {
cerr << "Socket closed gracefully before enough data received" << endl;
break;
} else if(rv < 0) {
cerr << "Read error occurred before enough data received" << endl;
break;
}
bytesRead += rv;
buf[rv] = '\0';
json_str += string(buf);
}
if(bytesRead < data_len) {
cerr << "Transmission failed!" << endl;
close(sock);
sleep(2);
continue;
}
cout << "Transmission success!" << endl;
strcpy(sendbuf, "S");
send(sock, sendbuf, strlen(sendbuf), 0);
close(sock);
data_ok = true;
}
doc.Parse(json_str.c_str());
}
for(int i = 0; i < NUM_PARTS; i++) {
const Value& jpart = doc[i];
for(SizeType j = 0; j < jpart.Size(); ++j) {
const Value& jseg = jpart[j];
LD[i].push_back(Seg(jseg[0].GetDouble(), jseg[1].GetDouble(), jseg[2].GetInt()));
}
printf("Part %d : %d segments\n", i, LD[i].size());
}
init_spi();
Document doc2;
data_ok = false;
while(!data_ok){
FILE *fp = fopen("data_ws.json", "r");
if (fp<0){
cerr << "Cannot read local file!" << endl;
}
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
doc2.ParseStream(is);
fclose(fp);
cout << "data_ws.json read OK" << endl;
data_ok = true;
}
const Value& jfile = doc2;
for (SizeType i = 0;i < jfile.Size();i++){
const Value& jarray = jfile[i];
vector< vector<Color> > new_frame_list;
anim.push_back(new_frame_list);
for (SizeType j = 0 ; j < jarray.Size() ; j++){
vector<Color> new_frame;
anim[i].push_back(new_frame);
const Value& jframe = jarray[j];
for (SizeType k=0 ; k < jframe.Size() ; k++){
const Value& jseg = jframe[k];
anim[i][j].push_back(Color(jseg[0].GetInt(), jseg[1].GetInt(), jseg[2].GetInt() ));
}
}
}
cout << anim.size() << " LED arrays" << endl;
for (unsigned int i = 0;i < anim.size();i++){
cout << "Length of array[" << i << "]: " << anim[i].size() << endl;
}
while(!time_ok) {
int sock = init_sock();
if(sock < 0) {
cerr << "TIME Connection failed!" << endl;
sleep(2);
continue;
}
strcpy(sendbuf, "T");
send(sock, sendbuf, strlen(sendbuf), 0);
ssize_t rv = recv(sock, buf, 1024, 0);
if(buf[0] == 'X') {
cerr << "TIME Server not ready!" << endl;
sleep(2);
continue;
}
buf[rv] = '\0';
double ft1 = atof(buf);
double curtime = get_sys_time();
strcpy(sendbuf, "S");
send(sock, sendbuf, strlen(sendbuf), 0);
rv = recv(sock, buf, 1024, 0);
buf[rv] = '\0';
double ft2 = atof(buf);
send(sock, sendbuf, strlen(sendbuf), 0);
double ft = (ft1 + ft2) / 2;
TIME_BASE = curtime - ft;
double delay = ft2 - ft1;
if(delay > 0.2) {
cerr << "TIME Delay too large! (" << delay << ")" << endl;
sleep(1);
continue;
}
cout.precision(4);
cout << "Time calibration success!" << endl;
cout << "TIME_BASE: ";
printf("%10.4lf\n", TIME_BASE);
cout << "Delay : " << delay << endl;
time_ok = true;
}
int max_length = anim[0].size() - 23;
int limit_length = anim[0].size();
int last_frame = -1;
while(true) {
double tm = get_sys_time() - TIME_BASE;
for(int i = 0; i < NUM_PARTS; ++i) {
int light = get_light(i, tm);
#ifdef USE_INTERNAL_PWM
if(i == 0) pwm_0.write(((float) light) / 4095);
else if(i == 1) pwm_1.write(((float) light) / 4095);
#else
pca.setPWM(conf.pins[i], 0, light);
#endif
}
int current_frame = (int)(tm*10);
if(tm < 0 || current_frame >= limit_length){
for(unsigned int i=0;i<num_ws;i++){
spi.writeByte( (uint8_t)(63) ); // start byte
spi.writeByte( (uint8_t)(i) ); // i-th gif
for (unsigned int j=0;j<num_led[i];j++){
spi.writeByte( 0 );
spi.writeByte( 0 );
spi.writeByte( 0 );
}
}
}
else if(current_frame > last_frame){
if(current_frame >= max_length){
// change max light
for(unsigned int i=0;i<anim.size();i++){
spi.writeByte( (uint8_t)(62) ); // start byte
spi.writeByte( (uint8_t)(i) ); // i-th gif
for (unsigned int j=0;j<anim[i][current_frame].size();j++){
spi.writeByte( (uint8_t)anim[i][current_frame][j].r );
spi.writeByte( (uint8_t)anim[i][current_frame][j].g );
spi.writeByte( (uint8_t)anim[i][current_frame][j].b );
}
}
}
else{
// send ws signal
for(unsigned int i=0;i<anim.size();i++){
spi.writeByte( (uint8_t)(63) ); // start byte
spi.writeByte( (uint8_t)(i) ); // i-th gif
for (unsigned int j=0;j<anim[i][current_frame].size();j++){
spi.writeByte( (uint8_t)anim[i][current_frame][j].r );
spi.writeByte( (uint8_t)anim[i][current_frame][j].g );
spi.writeByte( (uint8_t)anim[i][current_frame][j].b );
}
}
}
last_frame = current_frame;
}
}
return 0;
}
| 28.946629 | 99 | 0.489277 | [
"vector"
] |
3a4cf7493b7c626254cde7a80df472ada059e5ae | 49,438 | cpp | C++ | src/controller.cpp | jonuts/newsbeuter | fb46f9f5267f0d23ec0d5d077d556893adc65b18 | [
"MIT"
] | 1 | 2015-11-05T02:01:07.000Z | 2015-11-05T02:01:07.000Z | src/controller.cpp | jonuts/newsbeuter | fb46f9f5267f0d23ec0d5d077d556893adc65b18 | [
"MIT"
] | null | null | null | src/controller.cpp | jonuts/newsbeuter | fb46f9f5267f0d23ec0d5d077d556893adc65b18 | [
"MIT"
] | null | null | null | #include <config.h>
#include <view.h>
#include <controller.h>
#include <configparser.h>
#include <configcontainer.h>
#include <exceptions.h>
#include <downloadthread.h>
#include <colormanager.h>
#include <logger.h>
#include <utils.h>
#include <stflpp.h>
#include <exception.h>
#include <formatstring.h>
#include <regexmanager.h>
#include <rss_parser.h>
#include <remote_api.h>
#include <google_api.h>
#include <ttrss_api.h>
#include <xlicense.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <cerrno>
#include <algorithm>
#include <functional>
#include <sys/time.h>
#include <ctime>
#include <cassert>
#include <signal.h>
#include <sys/utsname.h>
#include <langinfo.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <pwd.h>
#include <ncurses.h>
#include <libxml/xmlversion.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlsave.h>
#include <libxml/uri.h>
#include <curl/curl.h>
namespace newsbeuter {
#define LOCK_SUFFIX ".lock"
std::string lock_file;
int ctrl_c_hit = 0;
void ctrl_c_action(int sig) {
LOG(LOG_DEBUG,"caught signal %d",sig);
if (SIGINT == sig) {
ctrl_c_hit = 1;
} else {
stfl::reset();
utils::remove_fs_lock(lock_file);
::exit(EXIT_FAILURE);
}
}
void ignore_signal(int sig) {
LOG(LOG_WARN, "caught signal %d but ignored it", sig);
}
void omg_a_child_died(int /* sig */) {
pid_t pid;
int stat;
while ((pid = waitpid(-1,&stat,WNOHANG)) > 0) { }
::signal(SIGCHLD, omg_a_child_died); /* in case of unreliable signals */
}
controller::controller() : v(0), urlcfg(0), rsscache(0), url_file("urls"), cache_file("cache.db"), config_file("config"), queue_file("queue"), refresh_on_start(false), api(0), offline_mode(false) {
}
/**
* \brief Try to setup XDG style dirs.
*
* returns false, if that fails
*/
bool controller::setup_dirs_xdg(const char *env_home) {
const char *env_xdg_config;
const char *env_xdg_data;
std::string xdg_config_dir;
std::string xdg_data_dir;
env_xdg_config = ::getenv("XDG_CONFIG_HOME");
if (env_xdg_config) {
xdg_config_dir = env_xdg_config;
} else {
xdg_config_dir = env_home;
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(".config");
}
env_xdg_data = ::getenv("XDG_DATA_HOME");
if (env_xdg_data) {
xdg_data_dir = env_xdg_data;
} else {
xdg_data_dir = env_home;
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(".local");
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append("share");
}
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(NEWSBEUTER_SUBDIR_XDG);
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(NEWSBEUTER_SUBDIR_XDG);
if (access(xdg_config_dir.c_str(), R_OK | X_OK) != 0)
{
std::cout << utils::strprintf(_("XDG: configuration directory '%s' not accessible, using '%s' instead."), xdg_config_dir.c_str(), config_dir.c_str()) << std::endl;
return false;
}
if (access(xdg_data_dir.c_str(), R_OK | X_OK | W_OK) != 0)
{
std::cout << utils::strprintf(_("XDG: data directory '%s' not accessible, using '%s' instead."), xdg_data_dir.c_str(), config_dir.c_str()) << std::endl;
return false;
}
config_dir = xdg_config_dir;
/* in config */
url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file;
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
/* in data */
cache_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file;
lock_file = cache_file + LOCK_SUFFIX;
queue_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
searchfile = utils::strprintf("%s%shistory.search", xdg_data_dir.c_str(), NEWSBEUTER_PATH_SEP);
cmdlinefile = utils::strprintf("%s%shistory.cmdline", xdg_data_dir.c_str(), NEWSBEUTER_PATH_SEP);
return true;
}
void controller::setup_dirs() {
const char * env_home;
if (!(env_home = ::getenv("HOME"))) {
struct passwd * spw = ::getpwuid(::getuid());
if (spw) {
env_home = spw->pw_dir;
} else {
std::cout << _("Fatal error: couldn't determine home directory!") << std::endl;
std::cout << utils::strprintf(_("Please set the HOME environment variable or add a valid user for UID %u!"), ::getuid()) << std::endl;
::exit(EXIT_FAILURE);
}
}
config_dir = env_home;
config_dir.append(NEWSBEUTER_PATH_SEP);
config_dir.append(NEWSBEUTER_CONFIG_SUBDIR);
if (setup_dirs_xdg(env_home))
return;
mkdir(config_dir.c_str(),0700); // create configuration directory if it doesn't exist
url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file;
cache_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file;
lock_file = cache_file + LOCK_SUFFIX;
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
queue_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
searchfile = utils::strprintf("%s%shistory.search", config_dir.c_str(), NEWSBEUTER_PATH_SEP);
cmdlinefile = utils::strprintf("%s%shistory.cmdline", config_dir.c_str(), NEWSBEUTER_PATH_SEP);
}
controller::~controller() {
delete rsscache;
delete urlcfg;
delete api;
scope_mutex feedslock(&feeds_mutex);
for (std::vector<std::tr1::shared_ptr<rss_feed> >::iterator it=feeds.begin();it!=feeds.end();it++) {
scope_mutex lock(&((*it)->item_mutex));
(*it)->items().clear();
}
feeds.clear();
}
void controller::set_view(view * vv) {
v = vv;
}
void controller::run(int argc, char * argv[]) {
int c;
setup_dirs();
::signal(SIGINT, ctrl_c_action);
::signal(SIGPIPE, ignore_signal);
::signal(SIGHUP, ctrl_c_action);
::signal(SIGCHLD, omg_a_child_died);
bool do_import = false, do_export = false, cachefile_given_on_cmdline = false, do_vacuum = false;
bool real_offline_mode = false;
std::string importfile;
bool do_read_import = false, do_read_export = false;
std::string readinfofile;
unsigned int show_version = 0;
bool silent = false;
bool execute_cmds = false;
do {
if((c = ::getopt(argc,argv,"i:erhqu:c:C:d:l:vVoxXI:E:"))<0)
continue;
switch (c) {
case ':': /* fall-through */
case '?': /* missing option */
usage(argv[0]);
break;
case 'i':
if (do_export)
usage(argv[0]);
do_import = true;
silent = true;
importfile = optarg;
break;
case 'r':
refresh_on_start = true;
break;
case 'e':
if (do_import)
usage(argv[0]);
do_export = true;
silent = true;
break;
case 'h':
usage(argv[0]);
break;
case 'u':
url_file = optarg;
break;
case 'c':
cache_file = optarg;
lock_file = std::string(cache_file) + LOCK_SUFFIX;
cachefile_given_on_cmdline = true;
break;
case 'C':
config_file = optarg;
break;
case 'X':
do_vacuum = true;
break;
case 'v':
case 'V':
show_version++;
break;
case 'o':
offline_mode = true;
break;
case 'x':
execute_cmds = true;
silent = true;
break;
case 'q':
silent = true;
break;
case 'd': // this is an undocumented debug commandline option!
GetLogger().set_logfile(optarg);
break;
case 'l': // this is an undocumented debug commandline option!
{
loglevel level = static_cast<loglevel>(atoi(optarg));
if (level > LOG_NONE && level <= LOG_DEBUG)
GetLogger().set_loglevel(level);
}
break;
case 'I':
if (do_read_export)
usage(argv[0]);
do_read_import = true;
readinfofile = optarg;
break;
case 'E':
if (do_read_import)
usage(argv[0]);
do_read_export = true;
readinfofile = optarg;
break;
default:
std::cout << utils::strprintf(_("%s: unknown option - %c"), argv[0], static_cast<char>(c)) << std::endl;
usage(argv[0]);
break;
}
} while (c != -1);
if (show_version) {
version_information(argv[0], show_version);
}
if (do_import) {
LOG(LOG_INFO,"Importing OPML file from %s",importfile.c_str());
urlcfg = new file_urlreader(url_file);
urlcfg->reload();
import_opml(importfile.c_str());
return;
}
LOG(LOG_INFO, "nl_langinfo(CODESET): %s", nl_langinfo(CODESET));
if (!do_export) {
if (!silent)
std::cout << utils::strprintf(_("Starting %s %s..."), PROGRAM_NAME, PROGRAM_VERSION) << std::endl;
pid_t pid;
if (!utils::try_fs_lock(lock_file, pid)) {
if (pid > 0) {
LOG(LOG_ERROR,"an instance is already running: pid = %u",pid);
} else {
LOG(LOG_ERROR,"something went wrong with the lock: %s", strerror(errno));
}
if (!execute_cmds) {
std::cout << utils::strprintf(_("Error: an instance of %s is already running (PID: %u)"), PROGRAM_NAME, pid) << std::endl;
}
return;
}
}
if (!silent)
std::cout << _("Loading configuration...");
std::cout.flush();
cfg.register_commands(cfgparser);
colorman.register_commands(cfgparser);
keymap keys(KM_NEWSBEUTER);
cfgparser.register_handler("bind-key",&keys);
cfgparser.register_handler("unbind-key",&keys);
cfgparser.register_handler("macro", &keys);
cfgparser.register_handler("ignore-article",&ign);
cfgparser.register_handler("always-download",&ign);
cfgparser.register_handler("reset-unread-on-update",&ign);
cfgparser.register_handler("define-filter",&filters);
cfgparser.register_handler("highlight", &rxman);
cfgparser.register_handler("highlight-article", &rxman);
try {
cfgparser.parse("/etc/" PROGRAM_NAME "/config");
cfgparser.parse(config_file);
} catch (const configexception& ex) {
LOG(LOG_ERROR,"an exception occured while parsing the configuration file: %s",ex.what());
std::cout << ex.what() << std::endl;
utils::remove_fs_lock(lock_file);
return;
}
update_config();
if (!silent)
std::cout << _("done.") << std::endl;
// create cache object
std::string cachefilepath = cfg.get_configvalue("cache-file");
if (cachefilepath.length() > 0 && !cachefile_given_on_cmdline) {
cache_file = cachefilepath.c_str();
// ok, we got another cache file path via the configuration
// that means we need to remove the old lock file, assemble
// the new lock file's name, and then try to lock it.
utils::remove_fs_lock(lock_file);
lock_file = std::string(cache_file) + LOCK_SUFFIX;
pid_t pid;
if (!utils::try_fs_lock(lock_file, pid)) {
if (pid > 0) {
LOG(LOG_ERROR,"an instance is already running: pid = %u",pid);
} else {
LOG(LOG_ERROR,"something went wrong with the lock: %s", strerror(errno));
}
std::cout << utils::strprintf(_("Error: an instance of %s is already running (PID: %u)"), PROGRAM_NAME, pid) << std::endl;
return;
}
}
if (!silent) {
std::cout << _("Opening cache...");
std::cout.flush();
}
try {
rsscache = new cache(cache_file,&cfg);
} catch (const dbexception& e) {
std::cout << utils::strprintf(_("Error: opening the cache file `%s' failed: %s"), cache_file.c_str(), e.what()) << std::endl;
utils::remove_fs_lock(lock_file);
::exit(EXIT_FAILURE);
}
if (!silent) {
std::cout << _("done.") << std::endl;
}
std::string type = cfg.get_configvalue("urls-source");
if (type == "local") {
urlcfg = new file_urlreader(url_file);
} else if (type == "opml") {
urlcfg = new opml_urlreader(&cfg);
real_offline_mode = offline_mode;
} else if (type == "googlereader") {
api = new googlereader_api(&cfg);
urlcfg = new googlereader_urlreader(&cfg, url_file, api);
real_offline_mode = offline_mode;
} else if (type == "ttrss") {
api = new ttrss_api(&cfg);
urlcfg = new ttrss_urlreader(&cfg, url_file, api);
real_offline_mode = offline_mode;
} else {
LOG(LOG_ERROR,"unknown urls-source `%s'", urlcfg->get_source().c_str());
}
if (real_offline_mode) {
if (!do_export) {
std::cout << _("Loading URLs from local cache...");
std::cout.flush();
}
urlcfg->set_offline(true);
urlcfg->get_urls() = rsscache->get_feed_urls();
if (!do_export) {
std::cout << _("done.") << std::endl;
}
} else {
if (!do_export && !silent) {
std::cout << utils::strprintf(_("Loading URLs from %s..."), urlcfg->get_source().c_str());
std::cout.flush();
}
if (api) {
if (!api->authenticate()) {
std::cout << "Authentication failed." << std::endl;
utils::remove_fs_lock(lock_file);
return;
}
}
urlcfg->reload();
if (!do_export && !silent) {
std::cout << _("done.") << std::endl;
}
if (api && type == "googlereader") { // ugly hack!
std::vector<google_replay_pair> actions = rsscache->get_google_replay();
if (actions.size() > 0) {
std::cout << _("Updating Google Reader unread states...");
std::cout.flush();
std::vector<std::string> successful_guids = dynamic_cast<googlereader_api *>(api)->bulk_mark_articles_read(actions);
rsscache->delete_google_replay_by_guid(successful_guids);
std::cout << _("done.") << std::endl;
}
}
}
if (urlcfg->get_urls().size() == 0) {
LOG(LOG_ERROR,"no URLs configured.");
std::string msg;
if (type == "local") {
msg = utils::strprintf(_("Error: no URLs configured. Please fill the file %s with RSS feed URLs or import an OPML file."), url_file.c_str());
} else if (type == "opml") {
msg = utils::strprintf(_("It looks like the OPML feed you subscribed contains no feeds. Please fill it with feeds, and try again."));
} else if (type == "googlereader") {
msg = utils::strprintf(_("It looks like you haven't configured any feeds in your Google Reader account. Please do so, and try again."));
} else if (type == "ttrss") {
msg = utils::strprintf(_("It looks like you haven't configured any feeds in your Tiny Tiny RSS account. Please do so, and try again."));
} else {
assert(0); // shouldn't happen
}
std::cout << msg << std::endl << std::endl;
usage(argv[0]);
}
if (!do_export && !do_vacuum && !silent)
std::cout << _("Loading articles from cache...");
if (do_vacuum)
std::cout << _("Opening cache...");
std::cout.flush();
if (do_vacuum) {
std::cout << _("done.") << std::endl;
std::cout << _("Cleaning up cache thoroughly...");
std::cout.flush();
rsscache->do_vacuum();
std::cout << _("done.") << std::endl;
utils::remove_fs_lock(lock_file);
return;
}
unsigned int i=0;
for (std::vector<std::string>::const_iterator it=urlcfg->get_urls().begin(); it != urlcfg->get_urls().end(); ++it, ++i) {
std::tr1::shared_ptr<rss_feed> feed(new rss_feed(rsscache));
try {
feed->set_rssurl(*it);
feed->set_tags(urlcfg->get_tags(*it));
bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display");
rsscache->internalize_rssfeed(feed, ignore_disp ? &ign : NULL);
} catch(const dbexception& e) {
std::cout << _("Error while loading feeds from database: ") << e.what() << std::endl;
utils::remove_fs_lock(lock_file);
return;
} catch(const std::string& str) {
std::cout << utils::strprintf(_("Error while loading feed '%s': %s"), it->c_str(), str.c_str()) << std::endl;
utils::remove_fs_lock(lock_file);
return;
}
feed->set_order(i);
scope_mutex feedslock(&feeds_mutex);
feeds.push_back(feed);
}
sort_feeds();
std::vector<std::string> tags = urlcfg->get_alltags();
if (!do_export && !silent)
std::cout << _("done.") << std::endl;
// if configured, we fill all query feeds with some data; no need to sort it, it will be refilled when actually opening it.
if (cfg.get_configvalue_as_bool("prepopulate-query-feeds")) {
std::cout << _("Prepopulating query feeds...");
std::cout.flush();
scope_mutex feedslock(&feeds_mutex);
for (std::vector<std::tr1::shared_ptr<rss_feed> >::iterator it=feeds.begin();it!=feeds.end();it++) {
if ((*it)->rssurl().substr(0,6) == "query:") {
(*it)->update_items(get_all_feeds_unlocked());
}
}
std::cout << _("done.") << std::endl;
}
if (do_export) {
export_opml();
utils::remove_fs_lock(lock_file);
return;
}
if (do_read_import) {
LOG(LOG_INFO,"Importing read information file from %s",readinfofile.c_str());
std::cout << _("Importing list of read articles...");
std::cout.flush();
import_read_information(readinfofile);
std::cout << _("done.") << std::endl;
return;
}
if (do_read_export) {
LOG(LOG_INFO,"Exporting read information file to %s",readinfofile.c_str());
std::cout << _("Exporting list of read articles...");
std::cout.flush();
export_read_information(readinfofile);
std::cout << _("done.") << std::endl;
return;
}
if (execute_cmds) {
execute_commands(argv, optind);
utils::remove_fs_lock(lock_file);
return;
}
// if the user wants to refresh on startup via configuration file, then do so,
// but only if -r hasn't been supplied.
if (!refresh_on_start && cfg.get_configvalue_as_bool("refresh-on-startup")) {
refresh_on_start = true;
}
// hand over the important objects to the view
v->set_config_container(&cfg);
v->set_keymap(&keys);
v->set_tags(tags);
formaction::load_histories(searchfile, cmdlinefile);
// run the view
v->run();
unsigned int history_limit = cfg.get_configvalue_as_int("history-limit");
LOG(LOG_DEBUG, "controller::run: history-limit = %u", history_limit);
formaction::save_histories(searchfile, cmdlinefile, history_limit);
if (!silent) {
std::cout << _("Cleaning up cache...");
std::cout.flush();
}
try {
scope_mutex feedslock(&feeds_mutex);
rsscache->cleanup_cache(feeds);
if (!silent) {
std::cout << _("done.") << std::endl;
}
} catch (const dbexception& e) {
LOG(LOG_USERERROR, "Cleaning up cache failed: %s", e.what());
if (!silent) {
std::cout << _("failed: ") << e.what() << std::endl;
}
}
utils::remove_fs_lock(lock_file);
}
void controller::update_feedlist() {
scope_mutex feedslock(&feeds_mutex);
v->set_feedlist(feeds);
}
void controller::update_visible_feeds() {
scope_mutex feedslock(&feeds_mutex);
v->update_visible_feeds(feeds);
}
void controller::catchup_all() {
try {
rsscache->catchup_all();
} catch (const dbexception& e) {
v->show_error(utils::strprintf(_("Error: couldn't mark all feeds read: %s"), e.what()));
return;
}
scope_mutex feedslock(&feeds_mutex);
for (std::vector<std::tr1::shared_ptr<rss_feed> >::iterator it=feeds.begin();it!=feeds.end();++it) {
scope_mutex lock(&(*it)->item_mutex);
if ((*it)->items().size() > 0) {
if (api) {
api->mark_all_read((*it)->rssurl());
}
for (std::vector<std::tr1::shared_ptr<rss_item> >::iterator jt=(*it)->items().begin();jt!=(*it)->items().end();++jt) {
(*jt)->set_unread_nowrite(false);
}
}
}
}
void controller::mark_article_read(const std::string& guid, bool read) {
if (api) {
if (offline_mode) {
if (dynamic_cast<googlereader_api *>(api) != NULL) {
LOG(LOG_DEBUG, "controller::mark_article_read: recording %s", guid.c_str());
record_google_replay(guid, read);
} else {
LOG(LOG_DEBUG, "not on googlereader_api");
}
} else {
api->mark_article_read(guid, read);
}
}
}
void controller::record_google_replay(const std::string& guid, bool read) {
rsscache->record_google_replay(guid, read ? GOOGLE_MARK_READ : GOOGLE_MARK_UNREAD);
}
void controller::mark_all_read(unsigned int pos) {
if (pos < feeds.size()) {
scope_measure m("controller::mark_all_read");
scope_mutex feedslock(&feeds_mutex);
std::tr1::shared_ptr<rss_feed> feed = feeds[pos];
if (feed->rssurl().substr(0,6) == "query:") {
rsscache->catchup_all(feed);
} else {
rsscache->catchup_all(feed->rssurl());
if (api) {
api->mark_all_read(feed->rssurl());
}
}
m.stopover("after rsscache->catchup_all, before iteration over items");
scope_mutex lock(&feed->item_mutex);
std::vector<std::tr1::shared_ptr<rss_item> >& items = feed->items();
std::vector<std::tr1::shared_ptr<rss_item> >::iterator begin = items.begin(), end = items.end();
if (items.size() > 0) {
bool notify = items[0]->feedurl() != feed->rssurl();
LOG(LOG_DEBUG, "controller::mark_all_read: notify = %s", notify ? "yes" : "no");
for (std::vector<std::tr1::shared_ptr<rss_item> >::iterator it=begin;it!=end;++it) {
(*it)->set_unread_nowrite_notify(false, notify);
}
}
}
}
void controller::reload(unsigned int pos, unsigned int max, bool unattended) {
LOG(LOG_DEBUG, "controller::reload: pos = %u max = %u", pos, max);
if (pos < feeds.size()) {
std::tr1::shared_ptr<rss_feed> oldfeed = feeds[pos];
std::string errmsg;
if (!unattended)
v->set_status(utils::strprintf(_("%sLoading %s..."), prepare_message(pos+1, max).c_str(), utils::censor_url(oldfeed->rssurl()).c_str()));
bool ignore_dl = (cfg.get_configvalue("ignore-mode") == "download");
rss_parser parser(oldfeed->rssurl(), rsscache, &cfg, ignore_dl ? &ign : NULL, api);
LOG(LOG_DEBUG, "controller::reload: created parser");
try {
oldfeed->set_status(DURING_DOWNLOAD);
std::tr1::shared_ptr<rss_feed> newfeed = parser.parse();
if (newfeed->items().size() > 0) {
scope_mutex feedslock(&feeds_mutex);
save_feed(newfeed, pos);
enqueue_items(newfeed);
if (!unattended) {
v->set_feedlist(feeds);
}
} else {
LOG(LOG_DEBUG, "controller::reload: feed is empty");
}
oldfeed->set_status(SUCCESS);
v->set_status("");
} catch (const dbexception& e) {
errmsg = utils::strprintf(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()).c_str(), e.what());
} catch (const std::string& emsg) {
errmsg = utils::strprintf(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()).c_str(), emsg.c_str());
} catch (rsspp::exception& e) {
errmsg = utils::strprintf(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()).c_str(), e.what());
}
if (errmsg != "") {
oldfeed->set_status(DL_ERROR);
v->set_status(errmsg);
LOG(LOG_USERERROR, "%s", errmsg.c_str());
}
} else {
v->show_error(_("Error: invalid feed!"));
}
}
std::tr1::shared_ptr<rss_feed> controller::get_feed(unsigned int pos) {
scope_mutex feedslock(&feeds_mutex);
if (pos >= feeds.size()) {
throw std::out_of_range(_("invalid feed index (bug)"));
}
std::tr1::shared_ptr<rss_feed> feed = feeds[pos];
return feed;
}
void controller::reload_indexes(const std::vector<int>& indexes, bool unattended) {
scope_measure m1("controller::reload_indexes");
unsigned int unread_feeds, unread_articles;
compute_unread_numbers(unread_feeds, unread_articles);
unsigned long size;
{
scope_mutex feedslock(&feeds_mutex);
size = feeds.size();
}
for (std::vector<int>::const_iterator it=indexes.begin();it!=indexes.end();++it) {
this->reload(*it, size, unattended);
}
unsigned int unread_feeds2, unread_articles2;
compute_unread_numbers(unread_feeds2, unread_articles2);
bool notify_always = cfg.get_configvalue_as_bool("notify-always");
if (notify_always || unread_feeds2 != unread_feeds || unread_articles2 != unread_articles) {
fmtstr_formatter fmt;
fmt.register_fmt('f', utils::to_s(unread_feeds2));
fmt.register_fmt('n', utils::to_s(unread_articles2));
fmt.register_fmt('d', utils::to_s(unread_articles2 - unread_articles));
fmt.register_fmt('D', utils::to_s(unread_feeds2 - unread_feeds));
this->notify(fmt.do_format(cfg.get_configvalue("notify-format")));
}
if (!unattended)
v->set_status("");
}
void controller::reload_range(unsigned int start, unsigned int end, unsigned int size, bool unattended) {
for (unsigned int i=start;i<=end;i++) {
LOG(LOG_DEBUG, "controller::reload_range: reloading feed #%u", i);
this->reload(i, size, unattended);
}
}
void controller::reload_all(bool unattended) {
unsigned int unread_feeds, unread_articles;
compute_unread_numbers(unread_feeds, unread_articles);
unsigned int num_threads = cfg.get_configvalue_as_int("reload-threads");
time_t t1, t2, dt;
unsigned int size;
{
scope_mutex feedlock(&feeds_mutex);
for (std::vector<std::tr1::shared_ptr<rss_feed> >::iterator it=feeds.begin();it!=feeds.end();it++) {
(*it)->reset_status();
}
size = feeds.size();
}
if (num_threads < 1)
num_threads = 1;
if (num_threads > size) {
num_threads = size;
}
t1 = time(NULL);
LOG(LOG_DEBUG,"controller::reload_all: starting with reload all...");
if (num_threads <= 1) {
this->reload_range(0, size-1, size, unattended);
} else {
std::vector<std::pair<unsigned int, unsigned int> > partitions = utils::partition_indexes(0, size-1, num_threads);
std::vector<pthread_t> threads;
LOG(LOG_DEBUG, "controller::reload_all: starting reload threads...");
for (unsigned int i=0;i<num_threads-1;i++) {
reloadrangethread* t = new reloadrangethread(this, partitions[i].first, partitions[i].second, size, unattended);
threads.push_back(t->start());
}
LOG(LOG_DEBUG, "controller::reload_all: starting my own reload...");
this->reload_range(partitions[num_threads-1].first, partitions[num_threads-1].second, size, unattended);
LOG(LOG_DEBUG, "controller::reload_all: joining other threads...");
for (std::vector<pthread_t>::iterator it=threads.begin();it!=threads.end();it++) {
::pthread_join(*it, NULL);
}
}
sort_feeds();
update_feedlist();
t2 = time(NULL);
dt = t2 - t1;
LOG(LOG_INFO, "controller::reload_all: reload took %d seconds", dt);
unsigned int unread_feeds2, unread_articles2;
compute_unread_numbers(unread_feeds2, unread_articles2);
bool notify_always = cfg.get_configvalue_as_bool("notify-always");
if (notify_always || unread_feeds2 != unread_feeds || unread_articles2 != unread_articles) {
fmtstr_formatter fmt;
fmt.register_fmt('f', utils::to_s(unread_feeds2));
fmt.register_fmt('n', utils::to_s(unread_articles2));
fmt.register_fmt('d', utils::to_s(unread_articles2 - unread_articles));
fmt.register_fmt('D', utils::to_s(unread_feeds2 - unread_feeds));
this->notify(fmt.do_format(cfg.get_configvalue("notify-format")));
}
}
void controller::notify(const std::string& msg) {
if (cfg.get_configvalue_as_bool("notify-screen")) {
LOG(LOG_DEBUG, "controller:notify: notifying screen");
std::cout << "\033^" << msg << "\033\\";
std::cout.flush();
}
if (cfg.get_configvalue_as_bool("notify-xterm")) {
LOG(LOG_DEBUG, "controller:notify: notifying xterm");
std::cout << "\033]2;" << msg << "\033\\";
std::cout.flush();
}
if (cfg.get_configvalue_as_bool("notify-beep")) {
LOG(LOG_DEBUG, "controller:notify: notifying beep");
::beep();
}
if (cfg.get_configvalue("notify-program").length() > 0) {
std::string prog = cfg.get_configvalue("notify-program");
LOG(LOG_DEBUG, "controller:notify: notifying external program `%s'", prog.c_str());
utils::run_command(prog, msg);
}
}
void controller::compute_unread_numbers(unsigned int& unread_feeds, unsigned int& unread_articles) {
unread_feeds = 0;
unread_articles = 0;
for (std::vector<std::tr1::shared_ptr<rss_feed> >::iterator it=feeds.begin();it!=feeds.end();++it) {
unsigned int items = (*it)->unread_item_count();
if (items > 0) {
++unread_feeds;
unread_articles += items;
}
}
}
bool controller::trylock_reload_mutex() {
if (reload_mutex.trylock()) {
LOG(LOG_DEBUG, "controller::trylock_reload_mutex succeeded");
return true;
}
LOG(LOG_DEBUG, "controller::trylock_reload_mutex failed");
return false;
}
void controller::start_reload_all_thread(std::vector<int> * indexes) {
LOG(LOG_INFO,"starting reload all thread");
thread * dlt = new downloadthread(this, indexes);
dlt->start();
}
void controller::version_information(const char * argv0, unsigned int level) {
if (level<=1) {
std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION << " - " << PROGRAM_URL << std::endl;
std::cout << "Copyright (C) 2006-2010 Andreas Krennmair" << std::endl << std::endl;
std::cout << _("newsbeuter is free software and licensed under the MIT/X Consortium License.") << std::endl;
std::cout << utils::strprintf(_("Type `%s -vv' for more information."), argv0) << std::endl << std::endl;
struct utsname xuts;
uname(&xuts);
std::cout << "Compilation date/time: " << __DATE__ << " " << __TIME__ << std::endl;
std::cout << "System: " << xuts.sysname << " " << xuts.release << " (" << xuts.machine << ")" << std::endl;
#if defined(__GNUC__) && defined(__VERSION__)
std::cout << "Compiler: g++ " << __VERSION__ << std::endl;
#endif
std::cout << "ncurses: " << curses_version() << " (compiled with " << NCURSES_VERSION << ")" << std::endl;
std::cout << "libcurl: " << curl_version() << " (compiled with " << LIBCURL_VERSION << ")" << std::endl;
std::cout << "SQLite: " << sqlite3_libversion() << " (compiled with " << SQLITE_VERSION << ")" << std::endl;
std::cout << "libxml2: compiled with " << LIBXML_DOTTED_VERSION << std::endl << std::endl;
} else {
std::cout << LICENSE_str << std::endl;
}
::exit(EXIT_SUCCESS);
}
static unsigned int gentabs(const std::string& str) {
int tabcount = 2 - ((3 + utils::strwidth(str)) / 8);
if (tabcount <= 0) {
tabcount = 1;
}
return tabcount;
}
void controller::usage(char * argv0) {
std::cout << utils::strprintf(_("%s %s\nusage: %s [-i <file>|-e] [-u <urlfile>] [-c <cachefile>] [-x <command> ...] [-h]\n"),
PROGRAM_NAME, PROGRAM_VERSION, argv0);
struct {
char arg;
const char * params;
const char * desc;
} args[] = {
{ 'e', "", _("export OPML feed to stdout") },
{ 'r', "", _("refresh feeds on start") },
{ 'i', _("<file>"), _("import OPML file") },
{ 'u', _("<urlfile>"), _("read RSS feed URLs from <urlfile>") },
{ 'c', _("<cachefile>"), _("use <cachefile> as cache file") },
{ 'C', _("<configfile>"), _("read configuration from <configfile>") },
{ 'X', "", _("clean up cache thoroughly") },
{ 'x', _("<command>..."), _("execute list of commands") },
{ 'o', "", _("activate offline mode (only applies to Google Reader synchronization mode)") },
{ 'q', "", _("quiet startup") },
{ 'v', "", _("get version information") },
{ 'l', _("<loglevel>"), _("write a log with a certain loglevel (valid values: 1 to 6)") },
{ 'd', _("<logfile>"), _("use <logfile> as output log file") },
{ 'E', _("<file>"), _("export list of read articles to <file>") },
{ 'I', _("<file>"), _("import list of read articles from <file>") },
{ 'h', "", _("this help") },
{ '\0', NULL, NULL }
};
for (unsigned int i=0;args[i].arg != '\0';i++) {
unsigned int tabs = gentabs(args[i].params);
std::cout << "\t-" << args[i].arg << " " << args[i].params;
for (unsigned int j=0;j<tabs;j++) {
std::cout << "\t";
}
std::cout << args[i].desc << std::endl;
}
::exit(EXIT_FAILURE);
}
void controller::import_opml(const char * filename) {
xmlDoc * doc = xmlReadFile(filename, NULL, 0);
if (doc == NULL) {
std::cout << utils::strprintf(_("An error occured while parsing %s."), filename) << std::endl;
return;
}
xmlNode * root = xmlDocGetRootElement(doc);
for (xmlNode * node = root->children; node != NULL; node = node->next) {
if (strcmp((const char *)node->name, "body")==0) {
LOG(LOG_DEBUG, "import_opml: found body");
rec_find_rss_outlines(node->children, "");
urlcfg->write_config();
}
}
xmlFreeDoc(doc);
std::cout << utils::strprintf(_("Import of %s finished."), filename) << std::endl;
}
void controller::export_opml() {
xmlDocPtr root = xmlNewDoc((const xmlChar *)"1.0");
xmlNodePtr opml_node = xmlNewDocNode(root, NULL, (const xmlChar *)"opml", NULL);
xmlSetProp(opml_node, (const xmlChar *)"version", (const xmlChar *)"1.0");
xmlDocSetRootElement(root, opml_node);
xmlNodePtr head = xmlNewTextChild(opml_node, NULL, (const xmlChar *)"head", NULL);
xmlNewTextChild(head, NULL, (const xmlChar *)"title", (const xmlChar *)PROGRAM_NAME " - Exported Feeds");
xmlNodePtr body = xmlNewTextChild(opml_node, NULL, (const xmlChar *)"body", NULL);
for (std::vector<std::tr1::shared_ptr<rss_feed> >::iterator it=feeds.begin(); it != feeds.end(); ++it) {
if (!utils::is_special_url((*it)->rssurl())) {
std::string rssurl = (*it)->rssurl();
std::string link = (*it)->link();
std::string title = (*it)->title();
xmlNodePtr outline = xmlNewTextChild(body, NULL, (const xmlChar *)"outline", NULL);
xmlSetProp(outline, (const xmlChar *)"type", (const xmlChar *)"rss");
xmlSetProp(outline, (const xmlChar *)"xmlUrl", (const xmlChar *)rssurl.c_str());
xmlSetProp(outline, (const xmlChar *)"htmlUrl", (const xmlChar *)link.c_str());
xmlSetProp(outline, (const xmlChar *)"title", (const xmlChar *)title.c_str());
}
}
xmlSaveCtxtPtr savectx = xmlSaveToFd(1, NULL, 1);
xmlSaveDoc(savectx, root);
xmlSaveClose(savectx);
xmlFreeNode(opml_node);
}
void controller::rec_find_rss_outlines(xmlNode * node, std::string tag) {
while (node) {
std::string newtag = tag;
if (strcmp((const char *)node->name, "outline")==0) {
char * url = (char *)xmlGetProp(node, (const xmlChar *)"xmlUrl");
if (!url) {
url = (char *)xmlGetProp(node, (const xmlChar *)"url");
}
if (url) {
LOG(LOG_DEBUG,"OPML import: found RSS outline with url = %s",url);
std::string nurl = std::string(url);
// Liferea uses a pipe to signal feeds read from the output of
// a program in its OPMLs. Convert them to our syntax.
if (*url == '|') {
nurl = utils::strprintf("exec:%s", url+1);
LOG(LOG_DEBUG,"OPML import: liferea-style url %s converted to %s", url, nurl.c_str());
}
// Handle OPML filters.
char * filtercmd = (char *)xmlGetProp(node, (const xmlChar *)"filtercmd");
if (filtercmd) {
LOG(LOG_DEBUG,"OPML import: adding filter command %s to url %s", filtercmd, nurl.c_str());
nurl.insert(0, utils::strprintf("filter:%s:", filtercmd));
xmlFree(filtercmd);
}
xmlFree(url);
// Filters and scripts may have arguments, so, quote them when needed.
url = (char*) xmlStrdup((const xmlChar*)utils::quote_if_necessary(nurl).c_str());
assert(url);
bool found = false;
LOG(LOG_DEBUG, "OPML import: size = %u", urlcfg->get_urls().size());
if (urlcfg->get_urls().size() > 0) {
for (std::vector<std::string>::iterator it = urlcfg->get_urls().begin(); it != urlcfg->get_urls().end(); ++it) {
if (*it == url) {
found = true;
}
}
}
if (!found) {
LOG(LOG_DEBUG,"OPML import: added url = %s",url);
urlcfg->get_urls().push_back(std::string(url));
if (tag.length() > 0) {
LOG(LOG_DEBUG, "OPML import: appending tag %s to url %s", tag.c_str(), url);
urlcfg->get_tags(url).push_back(tag);
}
} else {
LOG(LOG_DEBUG,"OPML import: url = %s is already in list",url);
}
xmlFree(url);
} else {
char * text = (char *)xmlGetProp(node, (const xmlChar *)"text");
if (!text)
text = (char *)xmlGetProp(node, (const xmlChar *)"title");
if (text) {
if (newtag.length() > 0) {
newtag.append("/");
}
newtag.append(text);
xmlFree(text);
}
}
}
rec_find_rss_outlines(node->children, newtag);
node = node->next;
}
}
std::vector<std::tr1::shared_ptr<rss_item> > controller::search_for_items(const std::string& query, const std::string& feedurl) {
std::vector<std::tr1::shared_ptr<rss_item> > items = rsscache->search_for_items(query, feedurl);
LOG(LOG_DEBUG, "controller::search_for_items: setting feed pointers");
for (std::vector<std::tr1::shared_ptr<rss_item> >::iterator it=items.begin();it!=items.end();++it) {
(*it)->set_feedptr(get_feed_by_url((*it)->feedurl()));
}
return items;
}
std::tr1::shared_ptr<rss_feed> controller::get_feed_by_url(const std::string& feedurl) {
for (std::vector<std::tr1::shared_ptr<rss_feed> >::iterator it=feeds.begin();it!=feeds.end();++it) {
if (feedurl == (*it)->rssurl())
return *it;
}
return std::tr1::shared_ptr<rss_feed>();
}
bool controller::is_valid_podcast_type(const std::string& /* mimetype */) {
return true;
}
void controller::enqueue_url(const std::string& url, std::tr1::shared_ptr<rss_feed> feed) {
bool url_found = false;
std::fstream f;
f.open(queue_file.c_str(), std::fstream::in);
if (f.is_open()) {
do {
std::string line;
getline(f, line);
if (!f.eof() && line.length() > 0) {
std::vector<std::string> fields = utils::tokenize_quoted(line);
if (fields.size() > 0 && fields[0] == url) {
url_found = true;
break;
}
}
} while (!f.eof());
f.close();
}
if (!url_found) {
f.open(queue_file.c_str(), std::fstream::app | std::fstream::out);
std::string filename = generate_enqueue_filename(url, feed);
f << url << " " << stfl::quote(filename) << std::endl;
f.close();
}
}
void controller::reload_urls_file() {
urlcfg->reload();
std::vector<std::tr1::shared_ptr<rss_feed> > new_feeds;
unsigned int i = 0;
for (std::vector<std::string>::const_iterator it=urlcfg->get_urls().begin();it!=urlcfg->get_urls().end();++it,++i) {
bool found = false;
for (std::vector<std::tr1::shared_ptr<rss_feed> >::iterator jt=feeds.begin();jt!=feeds.end();++jt) {
if (*it == (*jt)->rssurl()) {
found = true;
(*jt)->set_tags(urlcfg->get_tags(*it));
(*jt)->set_order(i);
new_feeds.push_back(*jt);
break;
}
}
if (!found) {
std::tr1::shared_ptr<rss_feed> new_feed(new rss_feed(rsscache));
try {
new_feed->set_rssurl(*it);
} catch (const std::string& str) {
LOG(LOG_USERERROR, "ignored invalid RSS URL '%s'", it->c_str());
continue;
}
new_feed->set_tags(urlcfg->get_tags(*it));
new_feed->set_order(i);
try {
bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display");
rsscache->internalize_rssfeed(new_feed, ignore_disp ? &ign : NULL);
} catch(const dbexception& e) {
LOG(LOG_ERROR, "controller::reload_urls_file: caught exception: %s", e.what());
throw e;
}
new_feeds.push_back(new_feed);
}
}
{
scope_mutex feedslock(&feeds_mutex);
feeds = new_feeds;
}
sort_feeds();
update_feedlist();
}
void controller::edit_urls_file() {
const char * editor;
editor = getenv("VISUAL");
if (!editor)
editor = getenv("EDITOR");
if (!editor)
editor = "vi";
std::string cmdline = utils::strprintf("%s \"%s\"", editor, utils::replace_all(url_file,"\"","\\\"").c_str());
v->push_empty_formaction();
stfl::reset();
LOG(LOG_DEBUG, "controller::edit_urls_file: running `%s'", cmdline.c_str());
::system(cmdline.c_str());
v->pop_current_formaction();
reload_urls_file();
}
std::string controller::bookmark(const std::string& url, const std::string& title, const std::string& description) {
std::string bookmark_cmd = cfg.get_configvalue("bookmark-cmd");
bool is_interactive = cfg.get_configvalue_as_bool("bookmark-interactive");
if (bookmark_cmd.length() > 0) {
std::string cmdline = utils::strprintf("%s '%s' %s %s",
bookmark_cmd.c_str(), utils::replace_all(url,"'", "%27").c_str(),
stfl::quote(title).c_str(), stfl::quote(description).c_str());
LOG(LOG_DEBUG, "controller::bookmark: cmd = %s", cmdline.c_str());
if (is_interactive) {
v->push_empty_formaction();
stfl::reset();
::system(cmdline.c_str());
v->pop_current_formaction();
return "";
} else {
char * my_argv[4];
my_argv[0] = const_cast<char *>("/bin/sh");
my_argv[1] = const_cast<char *>("-c");
my_argv[2] = const_cast<char *>(cmdline.c_str());
my_argv[3] = NULL;
return utils::run_program(my_argv, "");
}
} else {
return _("bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly.");
}
}
void controller::execute_commands(char ** argv, unsigned int i) {
if (v->formaction_stack_size() > 0)
v->pop_current_formaction();
for (;argv[i];++i) {
LOG(LOG_DEBUG, "controller::execute_commands: executing `%s'", argv[i]);
std::string cmd(argv[i]);
if (cmd == "reload") {
reload_all(true);
} else if (cmd == "print-unread") {
std::cout << utils::strprintf(_("%u unread articles"), rsscache->get_unread_count()) << std::endl;
}
}
}
std::string controller::write_temporary_item(std::tr1::shared_ptr<rss_item> item) {
char filename[1024];
snprintf(filename, sizeof(filename), "/tmp/newsbeuter-article.XXXXXX");
int fd = mkstemp(filename);
if (fd != -1) {
write_item(item, filename);
close(fd);
return std::string(filename);
} else {
return "";
}
}
void controller::write_item(std::tr1::shared_ptr<rss_item> item, const std::string& filename) {
std::fstream f;
f.open(filename.c_str(),std::fstream::out);
if (!f.is_open())
throw exception(errno);
write_item(item, f);
}
void controller::write_item(std::tr1::shared_ptr<rss_item> item, std::ostream& ostr) {
std::vector<std::string> lines;
std::vector<linkpair> links; // not used
std::string title(_("Title: "));
title.append(item->title());
lines.push_back(title);
std::string author(_("Author: "));
author.append(item->author());
lines.push_back(author);
std::string date(_("Date: "));
date.append(item->pubDate());
lines.push_back(date);
std::string link(_("Link: "));
link.append(item->link());
lines.push_back(link);
if (item->enclosure_url() != "") {
std::string dlurl(_("Podcast Download URL: "));
dlurl.append(item->enclosure_url());
lines.push_back(dlurl);
}
lines.push_back(std::string(""));
unsigned int width = cfg.get_configvalue_as_int("text-width");
if (width == 0)
width = 80;
htmlrenderer rnd(width, true);
rnd.render(item->description(), lines, links, item->feedurl());
for (std::vector<std::string>::iterator it=lines.begin();it!=lines.end();++it) {
ostr << *it << std::endl;
}
}
void controller::mark_deleted(const std::string& guid, bool b) {
rsscache->mark_item_deleted(guid, b);
}
std::string controller::prepare_message(unsigned int pos, unsigned int max) {
if (max > 0) {
return utils::strprintf("(%u/%u) ", pos, max);
}
return "";
}
void controller::save_feed(std::tr1::shared_ptr<rss_feed> feed, unsigned int pos) {
if (!feed->is_empty()) {
LOG(LOG_DEBUG, "controller::reload: feed is nonempty, saving");
rsscache->externalize_rssfeed(feed, ign.matches_resetunread(feed->rssurl()));
LOG(LOG_DEBUG, "controller::reload: after externalize_rssfeed");
bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display");
rsscache->internalize_rssfeed(feed, ignore_disp ? &ign : NULL);
LOG(LOG_DEBUG, "controller::reload: after internalize_rssfeed");
feed->set_tags(urlcfg->get_tags(feed->rssurl()));
{
unsigned int order = feeds[pos]->get_order();
scope_mutex itemlock(&feeds[pos]->item_mutex);
feeds[pos]->items().clear();
feed->set_order(order);
}
feeds[pos] = feed;
v->notify_itemlist_change(feeds[pos]);
} else {
LOG(LOG_DEBUG, "controller::reload: feed is empty, not saving");
}
}
void controller::enqueue_items(std::tr1::shared_ptr<rss_feed> feed) {
if (!cfg.get_configvalue_as_bool("podcast-auto-enqueue"))
return;
scope_mutex lock(&feed->item_mutex);
for (std::vector<std::tr1::shared_ptr<rss_item> >::iterator it=feed->items().begin();it!=feed->items().end();++it) {
if (!(*it)->enqueued() && (*it)->enclosure_url().length() > 0) {
LOG(LOG_DEBUG, "controller::reload: enclosure_url = `%s' enclosure_type = `%s'", (*it)->enclosure_url().c_str(), (*it)->enclosure_type().c_str());
if (is_valid_podcast_type((*it)->enclosure_type()) && utils::is_http_url((*it)->enclosure_url())) {
LOG(LOG_INFO, "controller::reload: enqueuing `%s'", (*it)->enclosure_url().c_str());
enqueue_url((*it)->enclosure_url(), feed);
(*it)->set_enqueued(true);
rsscache->update_rssitem_unread_and_enqueued(*it, feed->rssurl());
}
}
}
}
std::string controller::generate_enqueue_filename(const std::string& url, std::tr1::shared_ptr<rss_feed> feed) {
std::string dlformat = cfg.get_configvalue("download-path");
if (dlformat[dlformat.length()-1] != NEWSBEUTER_PATH_SEP[0])
dlformat.append(NEWSBEUTER_PATH_SEP);
fmtstr_formatter fmt;
fmt.register_fmt('n', feed->title());
fmt.register_fmt('h', get_hostname_from_url(url));
std::string dlpath = fmt.do_format(dlformat);
char buf[2048];
snprintf(buf, sizeof(buf), "%s", url.c_str());
char * base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(NULL);
strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t));
dlpath.append(lbuf);
} else {
dlpath.append(base);
}
return dlpath;
}
std::string controller::get_hostname_from_url(const std::string& url) {
xmlURIPtr uri = xmlParseURI(url.c_str());
std::string hostname;
if (uri) {
hostname = uri->server;
xmlFreeURI(uri);
}
return hostname;
}
void controller::import_read_information(const std::string& readinfofile) {
std::vector<std::string> guids;
std::ifstream f(readinfofile.c_str());
std::string line;
getline(f,line);
if (!f.is_open()) {
return;
}
while (f.is_open() && !f.eof()) {
guids.push_back(line);
getline(f, line);
}
rsscache->mark_items_read_by_guid(guids);
}
void controller::export_read_information(const std::string& readinfofile) {
std::vector<std::string> guids = rsscache->get_read_item_guids();
std::fstream f;
f.open(readinfofile.c_str(), std::fstream::out);
if (f.is_open()) {
for (std::vector<std::string>::iterator it=guids.begin();it!=guids.end();it++) {
f << *it << std::endl;
}
}
}
struct sort_feeds_by_firsttag : public std::binary_function<std::tr1::shared_ptr<rss_feed>, std::tr1::shared_ptr<rss_feed>, bool> {
sort_feeds_by_firsttag() { }
bool operator()(std::tr1::shared_ptr<rss_feed> a, std::tr1::shared_ptr<rss_feed> b) {
if (a->get_firsttag().length() == 0 || b->get_firsttag().length() == 0) {
return a->get_firsttag().length() > b->get_firsttag().length();
}
return strcasecmp(a->get_firsttag().c_str(), b->get_firsttag().c_str()) < 0;
}
};
struct sort_feeds_by_title : public std::binary_function<std::tr1::shared_ptr<rss_feed>, std::tr1::shared_ptr<rss_feed>, bool> {
sort_feeds_by_title() { }
bool operator()(std::tr1::shared_ptr<rss_feed> a, std::tr1::shared_ptr<rss_feed> b) {
return strcasecmp(a->title().c_str(), b->title().c_str()) < 0;
}
};
struct sort_feeds_by_articles : public std::binary_function<std::tr1::shared_ptr<rss_feed>, std::tr1::shared_ptr<rss_feed>, bool> {
sort_feeds_by_articles() { }
bool operator()(std::tr1::shared_ptr<rss_feed> a, std::tr1::shared_ptr<rss_feed> b) {
return a->total_item_count() < b->total_item_count();
}
};
struct sort_feeds_by_unread_articles : public std::binary_function<std::tr1::shared_ptr<rss_feed>, std::tr1::shared_ptr<rss_feed>, bool> {
sort_feeds_by_unread_articles() { }
bool operator()(std::tr1::shared_ptr<rss_feed> a, std::tr1::shared_ptr<rss_feed> b) {
return a->unread_item_count() < b->unread_item_count();
}
};
struct sort_feeds_by_order : public std::binary_function<std::tr1::shared_ptr<rss_feed>, std::tr1::shared_ptr<rss_feed>, bool> {
sort_feeds_by_order() { }
bool operator()(std::tr1::shared_ptr<rss_feed> a, std::tr1::shared_ptr<rss_feed> b) {
return a->get_order() < b->get_order();
}
};
void controller::sort_feeds() {
scope_mutex feedslock(&feeds_mutex);
std::vector<std::string> sortmethod_info = utils::tokenize(cfg.get_configvalue("feed-sort-order"), "-");
std::string sortmethod = sortmethod_info[0];
std::string direction = "desc";
if (sortmethod_info.size() > 1)
direction = sortmethod_info[1];
if (sortmethod == "none") {
std::stable_sort(feeds.begin(), feeds.end(), sort_feeds_by_order());
} else if (sortmethod == "firsttag") {
std::stable_sort(feeds.begin(), feeds.end(), sort_feeds_by_firsttag());
} else if (sortmethod == "title") {
std::stable_sort(feeds.begin(), feeds.end(), sort_feeds_by_title());
} else if (sortmethod == "articlecount") {
std::stable_sort(feeds.begin(), feeds.end(), sort_feeds_by_articles());
} else if (sortmethod == "unreadarticlecount") {
std::stable_sort(feeds.begin(), feeds.end(), sort_feeds_by_unread_articles());
}
if (direction == "asc") {
std::reverse(feeds.begin(), feeds.end());
}
}
void controller::update_config() {
v->set_regexmanager(&rxman);
v->update_bindings();
if (colorman.colors_loaded()) {
v->set_colors(colorman.get_fgcolors(), colorman.get_bgcolors(), colorman.get_attributes());
v->apply_colors_to_all_formactions();
}
if (cfg.get_configvalue("error-log").length() > 0) {
GetLogger().set_errorlogfile(cfg.get_configvalue("error-log").c_str());
}
}
void controller::load_configfile(const std::string& filename) {
if (cfgparser.parse(filename, true)) {
update_config();
} else {
v->show_error(utils::strprintf(_("Error: couldn't open configuration file `%s'!"), filename.c_str()));
}
}
void controller::dump_config(const std::string& filename) {
std::vector<std::string> configlines;
cfg.dump_config(configlines);
if (v) {
v->get_keys()->dump_config(configlines);
}
ign.dump_config(configlines);
filters.dump_config(configlines);
colorman.dump_config(configlines);
rxman.dump_config(configlines);
std::fstream f;
f.open(filename.c_str(), std::fstream::out);
if (f.is_open()) {
for (std::vector<std::string>::iterator it=configlines.begin();it!=configlines.end();it++) {
f << *it << std::endl;
}
}
}
unsigned int controller::get_pos_of_next_unread(unsigned int pos) {
scope_mutex feedslock(&feeds_mutex);
for (pos++;pos < feeds.size();pos++) {
if (feeds[pos]->unread_item_count() > 0)
break;
}
return pos;
}
void controller::update_flags(std::tr1::shared_ptr<rss_item> item) {
if (api) {
api->update_article_flags(item->oldflags(), item->flags(), item->guid());
}
item->update_flags();
}
std::vector<std::tr1::shared_ptr<rss_feed> > controller::get_all_feeds() {
std::vector<std::tr1::shared_ptr<rss_feed> > tmpfeeds;
{
scope_mutex feedslock(&feeds_mutex);
tmpfeeds = feeds;
}
return tmpfeeds;
}
std::vector<std::tr1::shared_ptr<rss_feed> > controller::get_all_feeds_unlocked() {
return feeds;
}
}
| 31.449109 | 197 | 0.665278 | [
"render",
"object",
"vector"
] |
3a53c66ea10575a694c176629ad02550fae5b732 | 849 | cc | C++ | chrome/browser/vr/elements/invisible_hit_target.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 | chrome/browser/vr/elements/invisible_hit_target.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/vr/elements/invisible_hit_target.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 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 "chrome/browser/vr/elements/invisible_hit_target.h"
namespace vr {
InvisibleHitTarget::InvisibleHitTarget() {
set_hit_testable(true);
}
InvisibleHitTarget::~InvisibleHitTarget() = default;
void InvisibleHitTarget::Render(UiElementRenderer* renderer,
const CameraModel& model) const {}
void InvisibleHitTarget::OnHoverEnter(const gfx::PointF& position,
base::TimeTicks timestamp) {
UiElement::OnHoverEnter(position, timestamp);
hovered_ = true;
}
void InvisibleHitTarget::OnHoverLeave(base::TimeTicks timestamp) {
UiElement::OnHoverLeave(timestamp);
hovered_ = false;
}
} // namespace vr
| 29.275862 | 73 | 0.710247 | [
"render",
"model"
] |
3a54087b3c756e5bc3e955fe148b3de462bcc538 | 1,854 | cpp | C++ | _investigacion/contests/un_marzo/sum_of_consecutive_primes.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | 1 | 2016-02-11T21:28:22.000Z | 2016-02-11T21:28:22.000Z | _investigacion/contests/un_marzo/sum_of_consecutive_primes.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | _investigacion/contests/un_marzo/sum_of_consecutive_primes.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cassert>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <bitset>
#include <algorithm>
#include <numeric>
#include <complex>
#define D(x) cerr << #x << " = " << (x) << endl;
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define FOREACH(it,v) for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define ALL(v) (v).begin(), (v).end()
using namespace std;
typedef long long int64;
const int INF = (int)(1e9);
const int64 INFLL = (int64)(1e18);
const double EPS = 1e-13;
map<int,int> sum, sum_count;
long long sieve_size;
bitset<10010> bs;
vector<int> primes;
void sieve(long long upperbound) {
sieve_size = upperbound + 1;
bs.set();
bs[0] = bs[1] = true;
for(long long i = 2; i <= sieve_size; i++) if(bs[i]) {
for(long long j = i*i; j <= sieve_size; j += i) bs[j] = 0;
primes.push_back((int)i);
}
}
void precalc() {
int m = primes.size();
sum[primes[0]] = 2;
for(int i = 1; i < m; i++) {
sum[primes[i]] = primes[i] + sum[primes[i-1]];
}
for(int i = 0; i < m; i++) {
int curr_sum = sum[primes[i]];
sum_count[curr_sum]++;
for(int j = i-1; j >= 0; j--) {
int curr = curr_sum - sum[primes[j]];
if(curr > 10000) break;
sum_count[curr]++;
}
}
}
int main() {
#ifdef LOCAL
freopen("inputs/sum_primes.in", "r", stdin);
freopen("outputs/sum_primes.out", "w", stdout);
#else
ios_base::sync_with_stdio(false);
#endif
sieve(10000);
precalc();
int n;
while(cin >> n) {
if(n == 0) break;
int ans = (sum_count.count(n))? sum_count[n] : 0;
cout << ans << endl;
}
return 0;
}
| 19.935484 | 84 | 0.594391 | [
"vector"
] |
3a5596ef6ca0046caa3c9cc8228999eeee4db951 | 3,316 | cpp | C++ | Pets_solution/InterestingLearningStuff/src/main.cpp | kirixx/pets | c64379ab8b3bb14aa8c9fcb111c2abf2c08ff0a3 | [
"Apache-2.0"
] | null | null | null | Pets_solution/InterestingLearningStuff/src/main.cpp | kirixx/pets | c64379ab8b3bb14aa8c9fcb111c2abf2c08ff0a3 | [
"Apache-2.0"
] | null | null | null | Pets_solution/InterestingLearningStuff/src/main.cpp | kirixx/pets | c64379ab8b3bb14aa8c9fcb111c2abf2c08ff0a3 | [
"Apache-2.0"
] | null | null | null | #include "MayersRules/RuleN3.h"
#include "CompleteModernC++/Printer.h"
#include "CompleteModernC++/Deleter.h"
#include "CompleteModernC++/StringPractice.h"
#include <vector>
#include <future>
namespace TemplateTest
{
//the example when class and typename is not interchangeably
template <typename T>
struct wrapper
{
using value_type = T;
value_type value;
};
template <typename T>
struct foo
{
T wrapped_value;
//you need to return a wrapped value, class is not allowed here.
typename T::value_type get_wrapped_value() { return wrapped_value.value; }
};
//template of template. since c++17 class could be changed on typename.
template < template < typename, typename > /*here*/class Container, typename Type >
class Example
{
Container< Type, std::allocator < Type > > baz;
};
template<class T>
T Add(T x, T y)
{
T sum = x + y;
std::cout << __FUNCSIG__ << sum << '\n';
return sum;
}
template <class T>
T ArraySum(T* pArray, T size)
{
T retVal = 0;
for (T i = 0; i < size; ++i)
{
retVal += pArray[i];
}
std::cout << __FUNCSIG__ << retVal << '\n';
return retVal;
}
template <class T>
T Max(T* pArray, T size)
{
T retVal = size > 0 ? pArray[0] : 0;
for (T i = 0; i < size; ++i)
{
retVal = pArray[i] > retVal ? pArray[i] : retVal;
}
std::cout << __FUNCSIG__ << retVal << '\n';
return retVal;
}
//variadic
void Print() {
std::cout << std::endl;
}
//Template parameter pack
template<typename T, typename...Params>
//Function parameter pack
void Print(T&& a, Params&&... args) {
//std::cout << sizeof...(args) << std::endl;
//std::cout << sizeof...(Params) << std::endl;
std::cout << a;
if (sizeof...(args) != 0) {
std::cout << ",";
}
//We can forward a function parameter pack
Print(std::forward<Params>(args)...);
}
/*
1. Print(1, 2.5, 3, "4") ;
2. Print(2.5, 3, "4") ;
3. Print(3, "4") ;
4. Print("4") ;
5. Print() ;
*/
}
int main()
{
std::cout << "***WEAK PTR USE CASE***\n";
weakPtrUseCase();
std::cout << "\n***DELETERS FOR SMART POINTERS***\n";
Deleter::uniquePtrDeleterTest();
Deleter::sharedPtrDeleterTest();
std::cout << "***ALWAYS USE CONST WHEREVER IT POSSIBLE***\n";
mayersRule3();
std::cout << "***STRING CONVERSION AND CASE SENSITIVE FIND***\n";
std::string up = StringPractice::ConvertToCase(std::string("boom"), StringPractice::Case::TO_UPPER);
std::string low = StringPractice::ConvertToCase(std::string("BAM"), StringPractice::Case::TO_LOWER);
std::string src("RUN boom");
std::string patt("BOOM");
size_t pos = StringPractice::Find(src, patt);
TemplateTest::foo<TemplateTest::wrapper<int>> f{ {42} };
std::cout << f.get_wrapped_value() << '\n';
TemplateTest::Example<std::vector, int> a;
TemplateTest::Add(3, 5);
int ar[] = { 1,2,3,4 };
TemplateTest::ArraySum(ar, 4);
TemplateTest::Max(ar, 4);
TemplateTest::Print(0, 1, 2, 4.5, "BOOM");
return 0;
} | 25.121212 | 104 | 0.553679 | [
"vector"
] |
3a581d3e560618d0cf5cfe307f44e299c4c421b9 | 1,168 | cpp | C++ | Algorithms/comparisonsMergeSort.cpp | moyfdzz/University-Projects | 8d6ab689fd3fba43994494245e489b1c97544fbd | [
"MIT"
] | 4 | 2018-04-27T00:03:39.000Z | 2019-01-27T07:31:57.000Z | Algorithms/comparisonsMergeSort.cpp | moyfdzz/University-Projects | 8d6ab689fd3fba43994494245e489b1c97544fbd | [
"MIT"
] | 1 | 2018-04-08T18:55:36.000Z | 2018-11-01T02:30:11.000Z | Algorithms/comparisonsMergeSort.cpp | moyfdzz/University-Assignments | 8d6ab689fd3fba43994494245e489b1c97544fbd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int contComp=0;
//&function
void Une(vector<int> &arreglo, int inicio, int mitad, int fin){
int i = inicio, j = mitad + 1, k = 0;
vector<int> aux(fin - inicio + 1);
while (i <= mitad && j <= fin) {
contComp++;
if (arreglo[i] < arreglo[j]) {
aux[k] = arreglo[i++];
}
else {
aux[k] = arreglo[j++];
}
k++;
}
while (i <= mitad) {
aux[k++] = arreglo[i++];
}
while (j <= fin) {
aux[k++] = arreglo[j++];
}
for (int z = inicio; z <= fin; z++) {
arreglo[z] = aux[z - inicio];
}
}
void MergeSort(vector<int> &arreglo, int inicio, int fin){
int mitad;
if (inicio < fin) {
mitad = (inicio + fin) / 2;
MergeSort(arreglo, inicio, mitad);
MergeSort(arreglo, mitad + 1, fin);
Une(arreglo, inicio, mitad, fin);
}
}
int main(){
int n;
cin >> n;
vector<int> datos(n);
for (int i=0; i<n; i++){
cin>>datos[i];
}
MergeSort(datos, 0, n-1);
cout << contComp <<endl;
for (int i=0; i<n; i++){
cout<<datos[i]<< " ";
}
} | 18.539683 | 63 | 0.479452 | [
"vector"
] |
3a5cc0f917d0a7b930f01a05334c2bed5e4355ae | 1,517 | cpp | C++ | src/configParser/Parser.cpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | src/configParser/Parser.cpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | src/configParser/Parser.cpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | #include "configParser/Parser.hpp"
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace ConfigParser {
void Parser::registerModule(std::shared_ptr<ParsingModule> module) {
_modules.emplace(module->key(), std::move(module));
}
std::shared_ptr<ParsingModule> Parser::module(const std::string& key) {
auto it = _modules.find(key);
if (it != _modules.end()) {
return it->second->shareState();
}
return nullptr;
}
bool Parser::parse(const std::string& filePath) {
std::ifstream fileStream(filePath, std::ios::binary);
if (!fileStream.is_open()) {
std::cout << "failed to open " << filePath << std::endl;
return false;
}
std::string line;
// Init all modules.
for (auto& module : _modules) {
module.second->setUp();
}
for (size_t lineCount = 1; std::getline(fileStream, line); ++lineCount) {
std::stringstream tokenStream(line);
std::vector<std::string> tokens;
std::string token;
while (tokenStream >> token) {
tokens.push_back(std::move(token));
}
if (tokens.empty()) {
continue;
}
auto it = _modules.find(tokens[0]);
// Unknown keyword.
if (it == _modules.end()) {
std::cout << "Line " << lineCount << ": unknown keyword " << tokens[0] << std::endl;
return false;
}
// Invalid arguments.
if (it->second->parse(tokens, lineCount) == false) {
return false;
}
}
return true;
}
} /* namespace ConfigParser */
| 22.641791 | 90 | 0.629532 | [
"vector"
] |
3a60b1b79479daad8bf960de4e5ca3fa8be21f49 | 15,338 | cpp | C++ | Source/JavaScriptCore/testRegExp.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | Source/JavaScriptCore/testRegExp.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/JavaScriptCore/testRegExp.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2011, 2015 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "RegExp.h"
#include <wtf/CurrentTime.h>
#include "InitializeThreading.h"
#include "JSCInlines.h"
#include "JSGlobalObject.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wtf/text/StringBuilder.h>
#if !OS(WINDOWS)
#include <unistd.h>
#endif
#if HAVE(SYS_TIME_H)
#include <sys/time.h>
#endif
#if COMPILER(MSVC)
#include <crtdbg.h>
#include <mmsystem.h>
#include <windows.h>
#endif
const int MaxLineLength = 100 * 1024;
using namespace JSC;
using namespace WTF;
struct CommandLine {
CommandLine()
: interactive(false)
, verbose(false)
{
}
bool interactive;
bool verbose;
Vector<String> arguments;
Vector<String> files;
};
class StopWatch {
public:
void start();
void stop();
long getElapsedMS(); // call stop() first
private:
double m_startTime;
double m_stopTime;
};
void StopWatch::start()
{
m_startTime = monotonicallyIncreasingTime();
}
void StopWatch::stop()
{
m_stopTime = monotonicallyIncreasingTime();
}
long StopWatch::getElapsedMS()
{
return static_cast<long>((m_stopTime - m_startTime) * 1000);
}
struct RegExpTest {
RegExpTest()
: offset(0)
, result(0)
{
}
String subject;
int offset;
int result;
Vector<int, 32> expectVector;
};
class GlobalObject : public JSGlobalObject {
private:
GlobalObject(VM&, Structure*, const Vector<String>& arguments);
public:
typedef JSGlobalObject Base;
static GlobalObject* create(VM& vm, Structure* structure, const Vector<String>& arguments)
{
GlobalObject* globalObject = new (NotNull, allocateCell<GlobalObject>(vm.heap)) GlobalObject(vm, structure, arguments);
return globalObject;
}
DECLARE_INFO;
static const bool needsDestructor = false;
static Structure* createStructure(VM& vm, JSValue prototype)
{
return Structure::create(vm, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), info());
}
protected:
void finishCreation(VM& vm, const Vector<String>& arguments)
{
Base::finishCreation(vm);
UNUSED_PARAM(arguments);
}
};
const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(GlobalObject) };
GlobalObject::GlobalObject(VM& vm, Structure* structure, const Vector<String>& arguments)
: JSGlobalObject(vm, structure)
{
finishCreation(vm, arguments);
}
// Use SEH for Release builds only to get rid of the crash report dialog
// (luckily the same tests fail in Release and Debug builds so far). Need to
// be in a separate main function because the realMain function requires object
// unwinding.
#if COMPILER(MSVC) && !defined(_DEBUG)
#define TRY __try {
#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
#else
#define TRY
#define EXCEPT(x)
#endif
int realMain(int argc, char** argv);
int main(int argc, char** argv)
{
#if OS(WINDOWS)
// Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
// testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
// error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
::SetErrorMode(0);
#if defined(_DEBUG)
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
#endif
timeBeginPeriod(1);
#endif
// Initialize JSC before getting VM.
JSC::initializeThreading();
// We can't use destructors in the following code because it uses Windows
// Structured Exception Handling
int res = 0;
TRY
res = realMain(argc, argv);
EXCEPT(res = 3)
return res;
}
static bool testOneRegExp(VM& vm, RegExp* regexp, RegExpTest* regExpTest, bool verbose, unsigned int lineNumber)
{
bool result = true;
Vector<int> outVector;
outVector.resize(regExpTest->expectVector.size());
int matchResult = regexp->match(vm, regExpTest->subject, regExpTest->offset, outVector);
if (matchResult != regExpTest->result) {
result = false;
if (verbose)
printf("Line %d: results mismatch - expected %d got %d\n", lineNumber, regExpTest->result, matchResult);
} else if (matchResult != -1) {
if (outVector.size() != regExpTest->expectVector.size()) {
result = false;
if (verbose) {
#if OS(WINDOWS)
printf("Line %d: output vector size mismatch - expected %Iu got %Iu\n", lineNumber, regExpTest->expectVector.size(), outVector.size());
#else
printf("Line %d: output vector size mismatch - expected %zu got %zu\n", lineNumber, regExpTest->expectVector.size(), outVector.size());
#endif
}
} else if (outVector.size() % 2) {
result = false;
if (verbose) {
#if OS(WINDOWS)
printf("Line %d: output vector size is odd (%Iu), should be even\n", lineNumber, outVector.size());
#else
printf("Line %d: output vector size is odd (%zu), should be even\n", lineNumber, outVector.size());
#endif
}
} else {
// Check in pairs since the first value of the pair could be -1 in which case the second doesn't matter.
size_t pairCount = outVector.size() / 2;
for (size_t i = 0; i < pairCount; ++i) {
size_t startIndex = i*2;
if (outVector[startIndex] != regExpTest->expectVector[startIndex]) {
result = false;
if (verbose) {
#if OS(WINDOWS)
printf("Line %d: output vector mismatch at index %Iu - expected %d got %d\n", lineNumber, startIndex, regExpTest->expectVector[startIndex], outVector[startIndex]);
#else
printf("Line %d: output vector mismatch at index %zu - expected %d got %d\n", lineNumber, startIndex, regExpTest->expectVector[startIndex], outVector[startIndex]);
#endif
}
}
if ((i > 0) && (regExpTest->expectVector[startIndex] != -1) && (outVector[startIndex+1] != regExpTest->expectVector[startIndex+1])) {
result = false;
if (verbose) {
#if OS(WINDOWS)
printf("Line %d: output vector mismatch at index %Iu - expected %d got %d\n", lineNumber, startIndex + 1, regExpTest->expectVector[startIndex + 1], outVector[startIndex + 1]);
#else
printf("Line %d: output vector mismatch at index %zu - expected %d got %d\n", lineNumber, startIndex + 1, regExpTest->expectVector[startIndex + 1], outVector[startIndex + 1]);
#endif
}
}
}
}
}
return result;
}
static int scanString(char* buffer, int bufferLength, StringBuilder& builder, char termChar)
{
bool escape = false;
for (int i = 0; i < bufferLength; ++i) {
UChar c = buffer[i];
if (escape) {
switch (c) {
case '0':
c = '\0';
break;
case 'a':
c = '\a';
break;
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
case 'v':
c = '\v';
break;
case '\\':
c = '\\';
break;
case '?':
c = '\?';
break;
case 'u':
if ((i + 4) >= bufferLength)
return -1;
unsigned int charValue;
if (sscanf(buffer+i+1, "%04x", &charValue) != 1)
return -1;
c = static_cast<UChar>(charValue);
i += 4;
break;
}
builder.append(c);
escape = false;
} else {
if (c == termChar)
return i;
if (c == '\\')
escape = true;
else
builder.append(c);
}
}
return -1;
}
static RegExp* parseRegExpLine(VM& vm, char* line, int lineLength)
{
StringBuilder pattern;
if (line[0] != '/')
return 0;
int i = scanString(line + 1, lineLength - 1, pattern, '/') + 1;
if ((i >= lineLength) || (line[i] != '/'))
return 0;
++i;
RegExp* r = RegExp::create(vm, pattern.toString(), regExpFlags(line + i));
if (r->isValid())
return r;
return nullptr;
}
static RegExpTest* parseTestLine(char* line, int lineLength)
{
StringBuilder subjectString;
if ((line[0] != ' ') || (line[1] != '"'))
return 0;
int i = scanString(line + 2, lineLength - 2, subjectString, '"') + 2;
if ((i >= (lineLength - 2)) || (line[i] != '"') || (line[i+1] != ',') || (line[i+2] != ' '))
return 0;
i += 3;
int offset;
if (sscanf(line + i, "%d, ", &offset) != 1)
return 0;
while (line[i] && line[i] != ' ')
++i;
++i;
int matchResult;
if (sscanf(line + i, "%d, ", &matchResult) != 1)
return 0;
while (line[i] && line[i] != ' ')
++i;
++i;
if (line[i++] != '(')
return 0;
int start, end;
RegExpTest* result = new RegExpTest();
result->subject = subjectString.toString();
result->offset = offset;
result->result = matchResult;
while (line[i] && line[i] != ')') {
if (sscanf(line + i, "%d, %d", &start, &end) != 2) {
delete result;
return 0;
}
result->expectVector.append(start);
result->expectVector.append(end);
while (line[i] && (line[i] != ',') && (line[i] != ')'))
i++;
i++;
while (line[i] && (line[i] != ',') && (line[i] != ')'))
i++;
if (line[i] == ')')
break;
if (!line[i] || (line[i] != ',')) {
delete result;
return 0;
}
i++;
}
return result;
}
static bool runFromFiles(GlobalObject* globalObject, const Vector<String>& files, bool verbose)
{
String script;
String fileName;
Vector<char> scriptBuffer;
unsigned tests = 0;
unsigned failures = 0;
char* lineBuffer = new char[MaxLineLength + 1];
VM& vm = globalObject->vm();
bool success = true;
for (size_t i = 0; i < files.size(); i++) {
FILE* testCasesFile = fopen(files[i].utf8().data(), "rb");
if (!testCasesFile) {
printf("Unable to open test data file \"%s\"\n", files[i].utf8().data());
continue;
}
RegExp* regexp = 0;
size_t lineLength = 0;
char* linePtr = 0;
unsigned int lineNumber = 0;
while ((linePtr = fgets(&lineBuffer[0], MaxLineLength, testCasesFile))) {
lineLength = strlen(linePtr);
if (linePtr[lineLength - 1] == '\n') {
linePtr[lineLength - 1] = '\0';
--lineLength;
}
++lineNumber;
if (linePtr[0] == '#')
continue;
if (linePtr[0] == '/') {
regexp = parseRegExpLine(vm, linePtr, lineLength);
} else if (linePtr[0] == ' ') {
RegExpTest* regExpTest = parseTestLine(linePtr, lineLength);
if (regexp && regExpTest) {
++tests;
if (!testOneRegExp(vm, regexp, regExpTest, verbose, lineNumber)) {
failures++;
printf("Failure on line %u\n", lineNumber);
}
}
if (regExpTest)
delete regExpTest;
} else if (linePtr[0] == '-') {
tests++;
regexp = 0; // Reset the live regexp to avoid confusing other subsequent tests
bool successfullyParsed = parseRegExpLine(vm, linePtr + 1, lineLength - 1);
if (successfullyParsed) {
failures++;
fprintf(stderr, "Failure on line %u. '%s' is not a valid regexp\n", lineNumber, linePtr + 1);
}
}
}
fclose(testCasesFile);
}
if (failures)
printf("%u tests run, %u failures\n", tests, failures);
else
printf("%u tests passed\n", tests);
delete[] lineBuffer;
#if ENABLE(REGEXP_TRACING)
vm.dumpRegExpTrace();
#endif
return success;
}
#define RUNNING_FROM_XCODE 0
static NO_RETURN void printUsageStatement(bool help = false)
{
fprintf(stderr, "Usage: regexp_test [options] file\n");
fprintf(stderr, " -h|--help Prints this help message\n");
fprintf(stderr, " -v|--verbose Verbose output\n");
exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
}
static void parseArguments(int argc, char** argv, CommandLine& options)
{
int i = 1;
for (; i < argc; ++i) {
const char* arg = argv[i];
if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
printUsageStatement(true);
if (!strcmp(arg, "-v") || !strcmp(arg, "--verbose"))
options.verbose = true;
else
options.files.append(argv[i]);
}
for (; i < argc; ++i)
options.arguments.append(argv[i]);
}
int realMain(int argc, char** argv)
{
VM* vm = &VM::create(LargeHeap).leakRef();
JSLockHolder locker(vm);
CommandLine options;
parseArguments(argc, argv, options);
GlobalObject* globalObject = GlobalObject::create(*vm, GlobalObject::createStructure(*vm, jsNull()), options.arguments);
bool success = runFromFiles(globalObject, options.files, options.verbose);
return success ? 0 : 3;
}
#if OS(WINDOWS)
extern "C" __declspec(dllexport) int WINAPI dllLauncherEntryPoint(int argc, const char* argv[])
{
return main(argc, const_cast<char**>(argv));
}
#endif
| 28.615672 | 199 | 0.560438 | [
"object",
"vector"
] |
3a6667e0f62da304e8de9dc3dbc2cc51073fc682 | 10,057 | cpp | C++ | Overlevende Core/Base Code/ModuleFileSystem.cpp | Pletenica/OVERLEVENDE | e22715448165e045d940d4f9a71de1fe91e30ada | [
"MIT"
] | 2 | 2020-09-28T10:34:38.000Z | 2020-09-28T10:34:43.000Z | Overlevende Core/Base Code/ModuleFileSystem.cpp | Pletenica/Overlevende | e22715448165e045d940d4f9a71de1fe91e30ada | [
"MIT"
] | null | null | null | Overlevende Core/Base Code/ModuleFileSystem.cpp | Pletenica/Overlevende | e22715448165e045d940d4f9a71de1fe91e30ada | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Application.h"
#include "ModuleFileSystem.h"
#include "FBXManager.h"
#include "ModuleRenderer3D.h"
#include "ModuleBaseMotor.h"
#include "InspectorWindow.h"
#include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "Mesh.h"
//#include "PathNode.h"
#include "Resource.h"
#include "PhysFS/include/physfs.h"
#include <fstream>
#include <filesystem>
#include "Assimp/include/cfileio.h"
#include "Assimp/include/types.h"
#pragma comment( lib, "PhysFS/libx86/physfs.lib" )
ModuleFileSystem::ModuleFileSystem(Application* app, bool start_enabled) : Module(app, start_enabled)
{
// needs to be created before Init so other modules can use it
char* base_path = SDL_GetBasePath();
PHYSFS_init(nullptr);
SDL_free(base_path);
//Setting the working directory as the writing directory
if (PHYSFS_setWriteDir(".") == 0)
LOG("File System error while creating write dir: %s\n", PHYSFS_getLastError());
AddPath("."); //Adding ProjectFolder (working directory)
AddPath("Assets");
CreateLibraryDirectories();
}
// Destructor
ModuleFileSystem::~ModuleFileSystem()
{
PHYSFS_deinit();
}
// Called before render is available
bool ModuleFileSystem::Init()
{
LOG("Loading File System");
bool ret = true;
// Ask SDL for a write dir
char* write_path = SDL_GetPrefPath("Pletenica Studios", "Overlevende");
// Trun this on while in game mode
//if(PHYSFS_setWriteDir(write_path) == 0)
// LOG("File System error while creating write dir: %s\n", PHYSFS_getLastError());
SDL_free(write_path);
return ret;
}
// Called before quitting
bool ModuleFileSystem::CleanUp()
{
//LOG("Freeing File System subsystem");
return true;
}
void ModuleFileSystem::CreateLibraryDirectories()
{
CreateDir(LIBRARY_PATH);
//CreateDir(FOLDERS_PATH);
CreateDir(MESHES_PATH);
//CreateDir(TEXTURES_PATH);
CreateDir(MATERIALS_PATH);
//CreateDir(MODELS_PATH);
//CreateDir(ANIMATIONS_PATH);
//CreateDir(PARTICLES_PATH);
//CreateDir(SHADERS_PATH);
//CreateDir(SCENES_PATH);
}
// Add a new zip file or folder
bool ModuleFileSystem::AddPath(const char* path_or_zip)
{
bool ret = false;
if (PHYSFS_mount(path_or_zip, nullptr, 1) == 0)
{
LOG("File System error while adding a path or zip: %s\n", PHYSFS_getLastError());
}
else
ret = true;
return ret;
}
// Check if a file exists
bool ModuleFileSystem::Exists(const char* file) const
{
return PHYSFS_exists(file) != 0;
}
bool ModuleFileSystem::CreateDir(const char* dir)
{
if (IsDirectory(dir) == false)
{
PHYSFS_mkdir(dir);
return true;
}
return false;
}
// Check if a file is a directory
bool ModuleFileSystem::IsDirectory(const char* file) const
{
return PHYSFS_isDirectory(file) != 0;
}
const char * ModuleFileSystem::GetWriteDir() const
{
//TODO: erase first annoying dot (".")
return PHYSFS_getWriteDir();
}
void ModuleFileSystem::DiscoverFiles(const char* directory, std::vector<Resource> &file_list) const
{
char **rc = PHYSFS_enumerateFiles(directory);
char **i;
for (i = rc; *i != nullptr; i++)
{
std::string str = std::string(directory) + std::string("/") + std::string(*i);
if (IsDirectory(str.c_str()))
file_list.push_back(Resource((*i), true));
else
file_list.push_back(Resource((*i),false));
}
PHYSFS_freeList(rc);
}
void ModuleFileSystem::GetFilesRecursive(Resource* _resourceroot)
{
DiscoverFiles(_resourceroot->name.c_str(), _resourceroot->children);
if (_resourceroot->children.size() != 0) {
for (int i = 0; i < _resourceroot->children.size(); i++) {
if (_resourceroot->children[i].isDirectory == true) {
GetFilesRecursive(&_resourceroot->children[i]);
}
}
}
}
void ModuleFileSystem::GetRealDir(const char* path, std::string& output) const
{
output = PHYSFS_getBaseDir();
std::string baseDir = PHYSFS_getBaseDir();
std::string searchPath = *PHYSFS_getSearchPath();
std::string realDir = PHYSFS_getRealDir(path);
output.append(*PHYSFS_getSearchPath()).append("/");
output.append(PHYSFS_getRealDir(path)).append("/").append(path);
}
std::string ModuleFileSystem::GetPathRelativeToAssets(const char* originalPath) const
{
std::string ret;
GetRealDir(originalPath, ret);
return ret;
}
bool ModuleFileSystem::HasExtension(const char* path) const
{
std::string ext = "";
SplitFilePath(path, nullptr, nullptr, &ext);
return ext != "";
}
bool ModuleFileSystem::HasExtension(const char* path, std::string extension) const
{
std::string ext = "";
SplitFilePath(path, nullptr, nullptr, &ext);
return ext == extension;
}
bool ModuleFileSystem::HasExtension(const char* path, std::vector<std::string> extensions) const
{
std::string ext = "";
SplitFilePath(path, nullptr, nullptr, &ext);
if (ext == "")
return true;
for (uint i = 0; i < extensions.size(); i++)
{
if (extensions[i] == ext)
return true;
}
return false;
}
std::string ModuleFileSystem::NormalizePath(const char * full_path) const
{
std::string newPath(full_path);
for (int i = 0; i < newPath.size(); ++i)
{
if (newPath[i] == '\\')
newPath[i] = '/';
}
return newPath;
}
void ModuleFileSystem::SplitFilePath(const char * full_path, std::string * path, std::string * file, std::string * extension) const
{
if (full_path != nullptr)
{
std::string full(full_path);
size_t pos_separator = full.find_last_of("\\/");
size_t pos_dot = full.find_last_of(".");
if (path != nullptr)
{
if (pos_separator < full.length())
*path = full.substr(0, pos_separator + 1);
else
path->clear();
}
if (file != nullptr)
{
if (pos_separator < full.length())
*file = full.substr(pos_separator + 1, pos_dot - pos_separator - 1);
else
*file = full.substr(0, pos_dot);
}
if (extension != nullptr)
{
if (pos_dot < full.length())
*extension = full.substr(pos_dot + 1);
else
extension->clear();
}
}
}
int close_sdl_rwops(SDL_RWops *rw)
{
//Comented here
//RELEASE_ARRAY(rw->hidden.mem.base);
SDL_FreeRW(rw);
return 0;
}
unsigned int ModuleFileSystem::Save(const char* file, const void* buffer, unsigned int size, bool append) const
{
unsigned int ret = 0;
bool overwrite = PHYSFS_exists(file) != 0;
PHYSFS_file* fs_file = (append) ? PHYSFS_openAppend(file) : PHYSFS_openWrite(file);
if (fs_file != nullptr)
{
uint written = (uint)PHYSFS_write(fs_file, (const void*)buffer, 1, size);
if (written != size)
{
LOG("[error] File System error while writing to file %s: %s", file, PHYSFS_getLastError());
}
else
{
if (append == true) {
LOG("Added %u data to [%s%s]", size, GetWriteDir(), file);
}
else if (overwrite == true) {
LOG("File [%s%s] overwritten with %u bytes", GetWriteDir(), file, size);
}
else {
LOG("New file created [%s%s] of %u bytes", GetWriteDir(), file, size);
}
ret = written;
}
if (PHYSFS_close(fs_file) == 0)
LOG("[error] File System error while closing file %s: %s", file, PHYSFS_getLastError());
}
else
LOG("[error] File System error while opening file %s: %s", file, PHYSFS_getLastError());
return ret;
}
unsigned int ModuleFileSystem::Load(const char* path, const char* file, char** buffer) const
{
std::string full_path(path);
full_path += file;
return Load(full_path.c_str(), buffer);
}
// Read a whole file and put it in a new buffer
uint ModuleFileSystem::Load(const char* file, char** buffer) const
{
uint ret = 0;
PHYSFS_file* fs_file = PHYSFS_openRead(file);
if (fs_file != nullptr)
{
PHYSFS_sint32 size = (PHYSFS_sint32)PHYSFS_fileLength(fs_file);
if (size > 0)
{
*buffer = new char[size + 1];
uint readed = (uint)PHYSFS_read(fs_file, *buffer, 1, size);
if (readed != size)
{
LOG("File System error while reading from file %s: %s\n", file, PHYSFS_getLastError());
delete(buffer);
}
else
{
ret = readed;
//Adding end of file at the end of the buffer. Loading a shader file does not add this for some reason
(*buffer)[size] = '\0';
}
}
if (PHYSFS_close(fs_file) == 0)
LOG("File System error while closing file %s: %s\n", file, PHYSFS_getLastError());
}
else
LOG("File System error while opening file %s: %s\n", file, PHYSFS_getLastError());
return ret;
}
void ModuleFileSystem::LoadFileFromPath(const char* _path)
{
std::string path = _path;
path = NormalizePath(path.c_str());
ResourceType _type = ResourceType::R_NONE;
_type = GetResourceTypeFromPath(path);
char* buffer = nullptr;
std::string _p = path.substr(path.find_last_of("/")+1);
if (_type == ResourceType::R_MESH) {
std::string _localpath = "Assets/FBXs/" + _p;
int size = Load(_localpath.c_str(), &buffer);
if (buffer != nullptr) {
FBXLoader::ImportFBX(buffer, size, App->renderer3D->imgID, _p.c_str());
}
}
if (_type == ResourceType::R_TEXTURE) {
std::string _lpath = "Assets/Textures/" + _p;
std::string _texname = _p.substr(0, _p.find_first_of("."));
int size = Load(_lpath.c_str(), &buffer);
ComponentMesh* c_mesh = (ComponentMesh*)App->base_motor->inspector_window->_selectedGO->GetComponent(ComponentType::C_Mesh);
ComponentMaterial* c_mat = (ComponentMaterial*)App->base_motor->inspector_window->_selectedGO->GetComponent(ComponentType::C_Material);
if (c_mesh != nullptr && c_mat != nullptr) {
c_mesh->mesh->textureID = FBXLoader::LoadTexture(buffer, size, &c_mesh->mesh->textureWidth, &c_mesh->mesh->textureHeight, _texname);
c_mat->textureID = c_mesh->mesh->textureID;
c_mat->textureAssetsPath = _lpath;
}
}
delete[] buffer;
}
ResourceType ModuleFileSystem::GetResourceTypeFromPath(std::string _path)
{
ResourceType _type = ResourceType::R_NONE;
std::string extension = _path.substr(_path.find_last_of(".") + 1);
if (extension == "fbx" ||
extension == "FBX" ||
extension == "DAE" ||
extension == "dae" ||
extension == "obj" ||
extension == "OBJ") {
_type = ResourceType::R_MESH;
}
if (extension == "png" ||
extension == "PNG" ||
extension == "DDS" ||
extension == "dds" ||
extension == "jpeg" ||
extension == "JPEG" ||
extension == "tga" ||
extension == "TGA") {
_type = ResourceType::R_TEXTURE;
}
return _type;
} | 24.589242 | 137 | 0.685692 | [
"mesh",
"render",
"vector"
] |
3a69a48c31020befec6536f120771ff2686b1256 | 2,479 | hpp | C++ | source/NanairoCore/Material/Bxdf/ggx_dielectric_bsdf.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 30 | 2015-09-06T03:14:29.000Z | 2021-06-18T11:00:19.000Z | source/NanairoCore/Material/Bxdf/ggx_dielectric_bsdf.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 31 | 2016-01-14T14:50:34.000Z | 2018-06-25T13:21:48.000Z | source/NanairoCore/Material/Bxdf/ggx_dielectric_bsdf.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 6 | 2017-04-09T13:07:47.000Z | 2021-05-29T21:17:34.000Z | /*!
\file ggx_dielectric_bsdf.hpp
\author Sho Ikeda
Copyright (c) 2015-2018 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#ifndef NANAIRO_GGX_DIELECTRIC_BSDF_HPP
#define NANAIRO_GGX_DIELECTRIC_BSDF_HPP
// Standard C++ library
#include <tuple>
// Nanairo
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoCore/Geometry/vector.hpp"
#include "NanairoCore/Material/shader_model.hpp"
#include "NanairoCore/Sampling/sampled_direction.hpp"
#include "NanairoCore/Sampling/sampled_spectra.hpp"
namespace nanairo {
// Forward declaration
class IntersectionInfo;
class PathState;
class Sampler;
class WavelengthSamples;
//! \addtogroup Core
//! \{
/*!
\details
No detailed.
*/
class GgxDielectricBsdf : public GlossyShaderModel
{
public:
//! Create a GGX dielectric BSDF
GgxDielectricBsdf(const Float roughness_x,
const Float roughness_y,
const Float n) noexcept;
//! Evaluate the pdf
Float evalPdf(const Vector3* vin,
const Vector3* vout,
const WavelengthSamples& wavelengths,
const IntersectionInfo* info) const noexcept override;
//! Evaluate the radiance of the area sampling
SampledSpectra evalRadiance(
const Vector3* vin,
const Vector3* vout,
const WavelengthSamples& wavelengths,
const IntersectionInfo* info) const noexcept override;
//! Evaluate the radiance of the area sampling
std::tuple<SampledSpectra, Float> evalRadianceAndPdf(
const Vector3* vin,
const Vector3* vout,
const WavelengthSamples& wavelengths,
const IntersectionInfo* info) const noexcept override;
//! Check if the BSDF is reflective
bool isReflective() const noexcept override;
//! Check if the BSDF is transmissive
bool isTransmissive() const noexcept override;
//! Sample a reflection direction and evaluate a reflection weight
std::tuple<SampledDirection, SampledSpectra> sample(
const Vector3* vin,
const WavelengthSamples& wavelengths,
Sampler& sampler,
PathState& path_state,
const IntersectionInfo* info) const noexcept override;
//! Check if wavelength selection occured
bool wavelengthIsSelected() const noexcept override;
private:
const Float roughness_x_,
roughness_y_;
const Float n_;
};
//! \} Core
} // namespace nanairo
#endif // NANAIRO_GGX_DIELECTRIC_BSDF_HPP
| 26.37234 | 70 | 0.720855 | [
"geometry",
"vector"
] |
3a747f2bd6252cb15cf4b25474716e4dbbfb5ea0 | 4,184 | hpp | C++ | include/libphysica/Linear_Algebra.hpp | temken/libphysica | 0b0f3d4377cfd1ab0ec5a25a3753848d6e6ea657 | [
"MIT"
] | 1 | 2021-08-13T12:55:16.000Z | 2021-08-13T12:55:16.000Z | include/libphysica/Linear_Algebra.hpp | temken/libphysica | 0b0f3d4377cfd1ab0ec5a25a3753848d6e6ea657 | [
"MIT"
] | 22 | 2020-05-11T10:01:19.000Z | 2022-03-31T12:33:17.000Z | include/libphysica/Linear_Algebra.hpp | temken/libphysica | 0b0f3d4377cfd1ab0ec5a25a3753848d6e6ea657 | [
"MIT"
] | 1 | 2021-09-29T15:49:59.000Z | 2021-09-29T15:49:59.000Z | #ifndef __Linear_Algebra_hpp_
#define __Linear_Algebra_hpp_
#include <iostream>
#include <vector>
namespace libphysica
{
// 1. Vector class
class Vector
{
private:
std::vector<double> components;
unsigned int dimension;
public:
// Constructors
Vector();
explicit Vector(unsigned int dim);
Vector(unsigned int dim, double entry);
Vector(std::vector<double> entries);
Vector(const Vector& rhs);
// Size functions
unsigned int Size() const;
void Resize(unsigned int dim);
void Assign(unsigned int dim, double entry);
// Products
double Dot(const Vector& rhs) const;
Vector Cross(const Vector& rhs) const;
// Norm functions
double Norm() const;
void Normalize();
Vector Normalized() const;
// Overloading brackets
double& operator[](const unsigned int i);
const double& operator[](const unsigned int i) const;
// Overloading operators
Vector operator+(Vector v) const;
Vector operator-(Vector v) const;
double operator*(Vector v) const;
Vector operator*(double s) const;
Vector operator/(double s) const;
Vector operator=(Vector v);
Vector& operator+=(const Vector& v);
Vector& operator-=(const Vector& v);
};
Vector operator*(double s, const Vector& v);
std::ostream& operator<<(std::ostream& output, const Vector& v);
bool operator==(const Vector& v1, const Vector& v2);
// 2. Coordinate systems
extern Vector Spherical_Coordinates(double r, double theta, double phi);
// 3. Matrices
class Matrix
{
private:
std::vector<std::vector<double>> components;
unsigned int rows, columns;
public:
// Constructors
Matrix();
Matrix(unsigned int dim_rows, unsigned int dim_columns);
Matrix(unsigned int dim_rows, unsigned int dim_columns, double entry);
Matrix(std::vector<std::vector<double>> entries);
Matrix(const Matrix& rhs);
Matrix(std::vector<double> diagonal_entries);
Matrix(std::vector<std::vector<Matrix>> block_matrices);
// Functions
// Size and components
unsigned int Rows() const;
unsigned int Columns() const;
void Resize(int row, int col);
void Assign(int row, int col, double entry);
void Delete_Row(unsigned int row);
void Delete_Column(unsigned int column);
Vector Return_Row(unsigned int row) const;
Vector Return_Column(unsigned int column) const;
//Binary operations
Matrix Plus(const Matrix& M) const;
Matrix Minus(const Matrix& M) const;
Matrix Product(double s) const;
Matrix Product(const Matrix& M) const;
Vector Product(const Vector& v) const;
Matrix Division(double s) const;
//Matrix properties
bool Square() const;
bool Symmetric() const;
bool Antisymmetric() const;
bool Diagonal() const;
bool Invertible() const;
bool Orthogonal() const;
//Matrix operations
Matrix Transpose() const;
Matrix Inverse() const;
double Trace() const;
double Determinant() const;
Matrix Sub_Matrix(int row, int column) const;
std::vector<double> Eigen_Values() const; //TODO
std::vector<Vector> Eigen_Vectors() const; //TODO
// Overloading brackets
std::vector<double>& operator[](const unsigned int i);
const std::vector<double>& operator[](const unsigned int i) const;
// Overloading operators
Matrix operator+(Matrix v);
Matrix operator-(Matrix v);
Matrix operator*(const Matrix& M);
Vector operator*(const Vector& v_rhs);
Matrix operator*(double s);
Matrix operator/(double s);
Matrix operator=(Matrix v);
Matrix& operator+=(const Matrix& M);
Matrix& operator-=(const Matrix& M);
};
// Overloading operators (Non-members)
Matrix operator*(double s, const Matrix& M);
Vector operator*(const Vector& v_left, const Matrix& M);
std::ostream& operator<<(std::ostream& output, const Matrix& v);
bool operator==(const Matrix& v1, const Matrix& v2);
extern Matrix Identity_Matrix(unsigned int dim);
extern Matrix Rotation_Matrix(double alpha, int dim, Vector axis = Vector({0, 0, 1}));
extern Matrix Outer_Vector_Product(const Vector& lhs, const Vector& rhs);
// Eigen systems
extern std::pair<Matrix, Matrix> QR_Decomposition(const Matrix& M);
extern std::vector<double> Eigenvalues(const Matrix& M);
extern std::vector<Vector> Eigenvectors(Matrix& M);
extern std::pair<std::vector<double>, std::vector<Vector>> Eigensystem(Matrix& M);
} // namespace libphysica
#endif | 28.462585 | 86 | 0.737811 | [
"vector"
] |
3a7597a99525eddddd05c360d919dc2f93c3c33a | 488 | cpp | C++ | src/naive_detect/main.cpp | xquery/asteroid_detect | ac6bd30a16b3c89d844a3e52f8cbccc6b48c53d5 | [
"Apache-2.0"
] | 2 | 2017-07-07T00:26:48.000Z | 2021-06-28T11:01:36.000Z | src/naive_detect/main.cpp | xquery/sdss_asteroid_detect | ac6bd30a16b3c89d844a3e52f8cbccc6b48c53d5 | [
"Apache-2.0"
] | null | null | null | src/naive_detect/main.cpp | xquery/sdss_asteroid_detect | ac6bd30a16b3c89d844a3e52f8cbccc6b48c53d5 | [
"Apache-2.0"
] | null | null | null | #include "../detect.hpp"
using namespace ad;
using namespace std;
// simplified branch example using opencv pre processing and hough transform for detection
int main(int argc, char** argv ){
LOG_S(INFO) << "asteroid naive_detect | Copyright 2017 James Fuller jim.fuller@webcomposite.com | https://github.com/xquery/asteroid_detect";
CHECK_S(argc == 2) << "you must supply an image file ex. usage: naive_detect <Image_Path>";
naive_detect(argv[1]);
return EXIT_SUCCESS;
} | 40.666667 | 145 | 0.735656 | [
"transform"
] |
3a7606c787bdeca4c59c95fae574a6b393da57f8 | 3,521 | cpp | C++ | src/Heuristic_KM_1.cpp | phitsc/check-cpp-api | 590c481f89f1b36d1fc5027d8fc89f87f2d5e0ca | [
"MIT"
] | null | null | null | src/Heuristic_KM_1.cpp | phitsc/check-cpp-api | 590c481f89f1b36d1fc5027d8fc89f87f2d5e0ca | [
"MIT"
] | null | null | null | src/Heuristic_KM_1.cpp | phitsc/check-cpp-api | 590c481f89f1b36d1fc5027d8fc89f87f2d5e0ca | [
"MIT"
] | null | null | null | #include "Helpers.hpp"
#include "Heuristics.hpp"
#include "Options.hpp"
#include <clang/AST/Decl.h>
#include <clang/AST/DeclCXX.h>
#include <llvm/Support/Casting.h>
#include <boost/optional.hpp>
namespace
{
CheckResult checkFunctionNameLength(const clang::FunctionDecl& functionDecl, const Options& options)
{
const auto limit = options["km-1-1-limit"].as<int>();
const auto name = getFunctionName(functionDecl);
// ignore template parameter names
const auto pos = name.find('<');
const auto len = pos == std::string::npos ? name.length() : pos;
// ignore operators
if ((int)len > limit && name.find("operator ") == std::string::npos) {
auto methodDecl = clang::dyn_cast<clang::CXXMethodDecl>(&functionDecl);
// also ignore generated methods
if (!methodDecl || methodDecl->isUserProvided()) {
return {
loc(functionDecl),
"long function name",
"the name of function '" + name + "' is " + std::to_string(len) +
" characters long, which is more than " + std::to_string(limit) + " characters"
};
}
}
return {};
}
CheckResult checkParamCount(const clang::FunctionDecl& functionDecl, const Options& options)
{
const auto limit = options["km-1-2-limit"].as<int>();
if ((int)functionDecl.parameters().size() > limit) {
return {
loc(functionDecl),
"too many parameters",
"function '" + getFunctionName(functionDecl) + "' has " + std::to_string(functionDecl.parameters().size()) +
" parameters, which are more than " + std::to_string(limit) + " parameters"
};
} else {
return {};
}
}
CheckResult checkConsecutiveParams(const clang::FunctionDecl& functionDecl, const Options& options)
{
const auto limit = options["km-1-3-limit"].as<int>();
auto check = [limit](const auto& params) -> boost::optional<std::string> {
if ((int)params.size() > limit) {
return std::to_string(params.size()) + " consecutive parameters of type " + params.back()->getOriginalType().getAsString();
} else {
return {};
}
};
std::string msg;
std::vector<clang::ParmVarDecl*> params;
for (const auto param : functionDecl.parameters()) {
if (!params.empty()) {
if (params.back()->getOriginalType() != param->getOriginalType()) {
if (auto res = check(params)) {
append(msg, *res, " and ");
}
params.clear();
}
}
params.push_back(param);
}
if (auto res = check(params)) {
append(msg, *res, " and ");
}
if (!msg.empty()) {
msg += " (only " + std::to_string(limit) + " consecutive parameters of same type allowed)";
return {
loc(functionDecl),
"too many consecutive parameters of same type",
"function '" + getFunctionName(functionDecl) + "' has " + msg
};
} else {
return {};
}
}
} // ns
Heuristic createHeuristic_KM_1()
{
return Heuristic(
"KM-1", "The API should be easy to remember",
{
{ 1, "Prefer short function names", &checkFunctionNameLength },
{ 2, "Avoid functions with many parameters", &checkParamCount },
{ 3, "Avoid functions with many consecutive parameters of the same type", &checkConsecutiveParams }
}
);
}
| 28.168 | 135 | 0.572565 | [
"vector"
] |
b91b108be70f9fd0c51cd927c47beaf3d816b11b | 392 | hpp | C++ | inst/include/rastr.hpp | aviralg/rastr | 67ebb1671af12cc8199f755f88da100051e225d4 | [
"MIT"
] | 1 | 2021-11-14T21:23:09.000Z | 2021-11-14T21:23:09.000Z | inst/include/rastr.hpp | aviralg/rastr | 67ebb1671af12cc8199f755f88da100051e225d4 | [
"MIT"
] | 4 | 2020-08-04T17:26:25.000Z | 2020-08-06T21:28:33.000Z | inst/include/rastr.hpp | aviralg/rastr | 67ebb1671af12cc8199f755f88da100051e225d4 | [
"MIT"
] | 1 | 2021-11-12T23:21:43.000Z | 2021-11-12T23:21:43.000Z | #ifndef RASTR_RASTR_HPP
#define RASTR_RASTR_HPP
#include "RIncludes.hpp"
#include <memory>
#include <vector>
#include <string>
namespace rastr {
SEXP get_undefined_object();
bool is_undefined_object(SEXP object);
bool is_defined_object(SEXP object);
SEXP create_class(const std::vector<std::string>& class_names);
void initialize();
} // namespace rastr
#endif /* RASTR_RASTR_HPP */
| 16.333333 | 63 | 0.765306 | [
"object",
"vector"
] |
b91c4b417b8b79290b103da57571da9b66b7a6d8 | 4,275 | hxx | C++ | lonestar/experimental/meshsingularities/Productions/PointProduction.hxx | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | null | null | null | lonestar/experimental/meshsingularities/Productions/PointProduction.hxx | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | 7 | 2020-02-27T19:24:51.000Z | 2020-04-10T21:04:28.000Z | lonestar/experimental/meshsingularities/Productions/PointProduction.hxx | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | 2 | 2020-02-17T22:00:40.000Z | 2020-03-24T10:18:02.000Z | /*
* This file belongs to the Galois project, a C++ library for exploiting parallelism.
* The code is being released under the terms of the 3-Clause BSD License (a
* copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
/*
* PointProduction.hxx
*
* Created on: Sep 12, 2013
* Author: dgoik
*/
#ifndef POINTPRODUCTION_HXX_
#define POINTPRODUCTION_HXX_
#include "Production.h"
class PointProduction : public AbstractProduction {
private:
const int interfaceSize;
const int leafSize;
const int a1Size;
const int anSize;
const int offset;
const int a1Offset;
const int anOffset;
void generateGraph();
virtual void recursiveGraphGeneration(int low_range, int high_range,
GraphNode bsSrcNode,
GraphNode mergingDstNode,
Vertex* parent);
virtual GraphNode addNode(int incomingEdges, int outgoingEdges,
int leafNumber, EProduction production,
GraphNode src, GraphNode dst, Vertex* v,
EquationSystem* system);
std::vector<EquationSystem*>*
preprocess(std::vector<EquationSystem*>* input) const;
/* these methods may be useful in order to parallelize {pre,post}processing */
EquationSystem* preprocessA1(EquationSystem* input) const;
EquationSystem* preprocessA(EquationSystem* input) const;
EquationSystem* preprocessAN(EquationSystem* input) const;
void postprocessA1(Vertex* leaf, EquationSystem* inputData,
std::vector<double>* result, int num) const;
void postprocessA(Vertex* leaf, EquationSystem* inputData,
std::vector<double>* result, int num) const;
void postprocessAN(Vertex* leaf, EquationSystem* inputData,
std::vector<double>* result, int num) const;
// iterate over leafs and return them in correct order
std::vector<Vertex*>* collectLeafs(Vertex* p);
public:
PointProduction(std::vector<int>* productionParameters,
std::vector<EquationSystem*>* inputData)
: AbstractProduction(productionParameters, inputData),
interfaceSize((*productionParameters)[0]),
leafSize((*productionParameters)[1]),
a1Size((*productionParameters)[2]), anSize((*productionParameters)[3]),
offset((*productionParameters)[1] - 2 * (*productionParameters)[0]),
a1Offset((*productionParameters)[2] - (*productionParameters)[1]),
anOffset((*productionParameters)[3] - (*productionParameters)[1]) {
this->inputData = preprocess(inputData);
generateGraph();
};
/* pull data from leafs and return the solution of MES
this is sequential code*/
virtual std::vector<double>* getResult();
virtual void Execute(EProduction productionToExecute, Vertex* v,
EquationSystem* input);
virtual Vertex* getRootVertex();
virtual Graph* getGraph();
void A1(Vertex* v, EquationSystem* inData) const;
void A(Vertex* v, EquationSystem* inData) const;
void AN(Vertex* v, EquationSystem* inData) const;
void A2Node(Vertex* v) const;
void A2Root(Vertex* v) const;
void BS(Vertex* v) const;
int getInterfaceSize() const;
int getLeafSize() const;
int getA1Size() const;
int getANSize() const;
};
#endif /* POINTPRODUCTION_HXX_ */
| 39.220183 | 85 | 0.693099 | [
"vector"
] |
b91d269004f9c9c90f4c702f2ebdc912dbb8c34e | 22,907 | cpp | C++ | plugins/mmstd_datatools/src/ParticlesToDensity.cpp | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | plugins/mmstd_datatools/src/ParticlesToDensity.cpp | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | plugins/mmstd_datatools/src/ParticlesToDensity.cpp | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | /*
* ParticlesToDensity.h
*
* Copyright (C) 2018 by MegaMol team
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "ParticlesToDensity.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <fstream>
#include "mmcore/misc/VolumetricDataCall.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/IntParam.h"
#include "omp.h"
#include "vislib/sys/Log.h"
#define _USE_MATH_DEFINES
#include <chrono>
#include <functional>
#include <math.h>
#include "mmcore/param/FloatParam.h"
using namespace megamol;
using namespace megamol::stdplugin;
/*
* datatools::ParticlesToDensity::create
*/
bool datatools::ParticlesToDensity::create(void) { return true; }
/*
* datatools::ParticlesToDensity::release
*/
void datatools::ParticlesToDensity::release(void) {
delete[] this->metadata.MinValues;
delete[] this->metadata.MaxValues;
delete[] this->metadata.SliceDists[0];
delete[] this->metadata.SliceDists[1];
delete[] this->metadata.SliceDists[2];
}
/*
* datatools::ParticlesToDensity::ParticlesToDensity
*/
datatools::ParticlesToDensity::ParticlesToDensity(void)
: aggregatorSlot("aggregator", "algorithm for the aggregation")
, xResSlot("sizex", "The size of the volume in numbers of voxels")
, yResSlot("sizey", "The size of the volume in numbers of voxels")
, zResSlot("sizez", "The size of the volume in numbers of voxels")
, cyclXSlot("cyclX", "Considers cyclic boundary conditions in X direction")
, cyclYSlot("cyclY", "Considers cyclic boundary conditions in Y direction")
, cyclZSlot("cyclZ", "Considers cyclic boundary conditions in Z direction")
, normalizeSlot("normalize", "Normalize the output volume")
, sigmaSlot("sigma", "Sigma for Gauss in multiple of rad")
, surfaceSlot("forSurfaceReconstruction", "Set true if this volume is used for surface reconstruction")
//, datahash(std::numeric_limits<size_t>::max())
, datahash(0)
, time(std::numeric_limits<unsigned int>::max())
, outDataSlot("outData", "Provides a density volume for the particles")
, inDataSlot("inData", "takes the particle data") {
auto* ep = new core::param::EnumParam(0);
ep->SetTypePair(0, "PosToSingleCell_Volume");
ep->SetTypePair(1, "IColToSingleCell_Volume");
this->aggregatorSlot << ep;
this->MakeSlotAvailable(&this->aggregatorSlot);
/*this->outDataSlot.SetCallback(core::moldyn::VolumeDataCall::ClassName(),
core::moldyn::VolumeDataCall::FunctionName(core::moldyn::VolumeDataCall::CallForGetData),
&ParticlesToDensity::getDataCallback);
this->outDataSlot.SetCallback(core::moldyn::VolumeDataCall::ClassName(),
core::moldyn::VolumeDataCall::FunctionName(core::moldyn::VolumeDataCall::CallForGetExtent),
&ParticlesToDensity::getExtentCallback);
this->MakeSlotAvailable(&this->outDataSlot);*/
this->outDataSlot.SetCallback(core::misc::VolumetricDataCall::ClassName(),
core::misc::VolumetricDataCall::FunctionName(core::misc::VolumetricDataCall::IDX_GET_DATA),
&ParticlesToDensity::getDataCallback);
this->outDataSlot.SetCallback(core::misc::VolumetricDataCall::ClassName(),
core::misc::VolumetricDataCall::FunctionName(core::misc::VolumetricDataCall::IDX_GET_EXTENTS),
&ParticlesToDensity::getExtentCallback);
this->outDataSlot.SetCallback(core::misc::VolumetricDataCall::ClassName(),
core::misc::VolumetricDataCall::FunctionName(core::misc::VolumetricDataCall::IDX_GET_METADATA),
&ParticlesToDensity::getExtentCallback);
this->outDataSlot.SetCallback(core::misc::VolumetricDataCall::ClassName(),
core::misc::VolumetricDataCall::FunctionName(core::misc::VolumetricDataCall::IDX_START_ASYNC),
&ParticlesToDensity::dummyCallback);
this->outDataSlot.SetCallback(core::misc::VolumetricDataCall::ClassName(),
core::misc::VolumetricDataCall::FunctionName(core::misc::VolumetricDataCall::IDX_STOP_ASYNC),
&ParticlesToDensity::dummyCallback);
this->outDataSlot.SetCallback(core::misc::VolumetricDataCall::ClassName(),
core::misc::VolumetricDataCall::FunctionName(core::misc::VolumetricDataCall::IDX_TRY_GET_DATA),
&ParticlesToDensity::dummyCallback);
this->MakeSlotAvailable(&this->outDataSlot);
this->xResSlot << new core::param::IntParam(16);
this->MakeSlotAvailable(&this->xResSlot);
this->yResSlot << new core::param::IntParam(16);
this->MakeSlotAvailable(&this->yResSlot);
this->zResSlot << new core::param::IntParam(16);
this->MakeSlotAvailable(&this->zResSlot);
this->cyclXSlot.SetParameter(new core::param::BoolParam(true));
this->MakeSlotAvailable(&this->cyclXSlot);
this->cyclYSlot.SetParameter(new core::param::BoolParam(true));
this->MakeSlotAvailable(&this->cyclYSlot);
this->cyclZSlot.SetParameter(new core::param::BoolParam(true));
this->MakeSlotAvailable(&this->cyclZSlot);
this->normalizeSlot << new core::param::BoolParam(true);
this->MakeSlotAvailable(&this->normalizeSlot);
this->sigmaSlot << new core::param::FloatParam(
1.0f, std::numeric_limits<float>::min(), std::numeric_limits<float>::max());
this->MakeSlotAvailable(&this->sigmaSlot);
this->surfaceSlot << new core::param::BoolParam(false);
this->MakeSlotAvailable(&this->surfaceSlot);
this->inDataSlot.SetCompatibleCall<megamol::core::moldyn::MultiParticleDataCallDescription>();
this->MakeSlotAvailable(&this->inDataSlot);
}
/*
* datatools::ParticlesToDensity::~ParticlesToDensity
*/
datatools::ParticlesToDensity::~ParticlesToDensity(void) { this->Release(); }
bool datatools::ParticlesToDensity::getExtentCallback(megamol::core::Call& c) {
using megamol::core::moldyn::MultiParticleDataCall;
auto* out = dynamic_cast<core::misc::VolumetricDataCall*>(&c);
if (out == nullptr) return false;
auto* inMpdc = this->inDataSlot.CallAs<MultiParticleDataCall>();
if (inMpdc == nullptr) return false;
// if (!this->assertData(inMpdc, outDpdc)) return false;
inMpdc->SetFrameID(out->FrameID(), true);
if (!(*inMpdc)(1)) {
vislib::sys::Log::DefaultLog.WriteError(
"ParticlesToDensity: could not get current frame extents (%u)", time - 1);
return false;
}
out->AccessBoundingBoxes().SetObjectSpaceBBox(inMpdc->GetBoundingBoxes().ObjectSpaceBBox());
out->AccessBoundingBoxes().SetObjectSpaceClipBox(inMpdc->GetBoundingBoxes().ObjectSpaceClipBox());
out->SetFrameCount(inMpdc->FrameCount());
// TODO: what am I actually doing here
// inMpdc->SetUnlocker(nullptr, false);
// inMpdc->Unlock();
return true;
}
bool datatools::ParticlesToDensity::getDataCallback(megamol::core::Call& c) {
auto* inMpdc = this->inDataSlot.CallAs<core::moldyn::MultiParticleDataCall>();
if (inMpdc == nullptr) return false;
auto* outVol = dynamic_cast<core::misc::VolumetricDataCall*>(&c);
if (outVol == nullptr) return false;
inMpdc->SetFrameID(outVol->FrameID(), true);
if (!(*inMpdc)(1)) {
vislib::sys::Log::DefaultLog.WriteError("ParticlesToDensity: Unable to get extents.");
return false;
}
if (!(*inMpdc)(0)) {
vislib::sys::Log::DefaultLog.WriteError("ParticlesToDensity: Unable to get data.");
return false;
}
if (this->time != inMpdc->FrameID() || this->in_datahash != inMpdc->DataHash() || this->anythingDirty()) {
if (this->surfaceSlot.Param<core::param::BoolParam>()->Value()) modifyBBox(inMpdc);
if (!this->createVolumeCPU(inMpdc)) return false;
this->time = inMpdc->FrameID();
this->in_datahash = inMpdc->DataHash();
++this->datahash;
this->resetDirty();
}
// TODO set data
outVol->SetData(this->vol[0].data());
metadata.Components = 1;
metadata.GridType = core::misc::GridType_t::CARTESIAN;
metadata.Resolution[0] = static_cast<size_t>(this->xResSlot.Param<core::param::IntParam>()->Value());
metadata.Resolution[1] = static_cast<size_t>(this->yResSlot.Param<core::param::IntParam>()->Value());
metadata.Resolution[2] = static_cast<size_t>(this->zResSlot.Param<core::param::IntParam>()->Value());
metadata.ScalarType = core::misc::ScalarType_t::FLOATING_POINT;
metadata.ScalarLength = sizeof(float);
metadata.MinValues = new double[1];
metadata.MinValues[0] = this->minDens;
metadata.MaxValues = new double[1];
metadata.MaxValues[0] = this->maxDens;
auto bbox = inMpdc->AccessBoundingBoxes().ObjectSpaceBBox();
metadata.Extents[0] = bbox.Width();
metadata.Extents[1] = bbox.Height();
metadata.Extents[2] = bbox.Depth();
metadata.NumberOfFrames = 1;
metadata.SliceDists[0] = new float[1];
metadata.SliceDists[0][0] = metadata.Extents[0] / static_cast<float>(metadata.Resolution[0] - 1);
metadata.SliceDists[1] = new float[1];
metadata.SliceDists[1][0] = metadata.Extents[1] / static_cast<float>(metadata.Resolution[1] - 1);
metadata.SliceDists[2] = new float[1];
metadata.SliceDists[2][0] = metadata.Extents[2] / static_cast<float>(metadata.Resolution[2] - 1);
metadata.Origin[0] = bbox.Left();
//-metadata.SliceDists[0][0] / 4.0f;
metadata.Origin[1] = bbox.Bottom();
//-metadata.SliceDists[1][0] / 4.0f;
metadata.Origin[2] = bbox.Back();
//-metadata.SliceDists[2][0] / 4.0f;
metadata.IsUniform[0] = true;
metadata.IsUniform[1] = true;
metadata.IsUniform[2] = true;
outVol->SetMetadata(&metadata);
outVol->SetDataHash(this->datahash);
/*outVol->SetVolumeDimension(this->xResSlot.Param<core::param::IntParam>()->Value(),
this->yResSlot.Param<core::param::IntParam>()->Value(), this->zResSlot.Param<core::param::IntParam>()->Value());
outVol->SetComponents(1);
outVol->SetMinimumDensity(0.0f);
outVol->SetMaximumDensity(this->maxDens);
outVol->SetVoxelMapPointer(this->vol[0].data());*/
// inMpdc->Unlock();
return true;
}
/*
* moldyn::DynDensityGradientEstimator::createVolumeCPU
*/
bool datatools::ParticlesToDensity::createVolumeCPU(class megamol::core::moldyn::MultiParticleDataCall* c2) {
vislib::sys::Log::DefaultLog.WriteInfo("ParticlesToDensity: starting volume creation");
const auto startTime = std::chrono::high_resolution_clock::now();
size_t totalParticles = 0;
auto const sx = this->xResSlot.Param<core::param::IntParam>()->Value();
auto const sy = this->yResSlot.Param<core::param::IntParam>()->Value();
auto const sz = this->zResSlot.Param<core::param::IntParam>()->Value();
vol.resize(omp_get_max_threads());
#pragma omp parallel for
for (int init = 0; init < omp_get_max_threads(); ++init) {
vol[init].resize(sx * sy * sz);
std::fill(vol[init].begin(), vol[init].end(), 0.0f);
}
// TODO: the whole code is wrong since we might not have the bounding box for the actual cyclic boundary conditions.
// TODO: what about near-zero or zero radii? This currently blows the whole thing up.
bool const cycl_x = this->cyclXSlot.Param<megamol::core::param::BoolParam>()->Value();
bool const cycl_y = this->cyclYSlot.Param<megamol::core::param::BoolParam>()->Value();
bool const cycl_z = this->cyclZSlot.Param<megamol::core::param::BoolParam>()->Value();
auto const minOSx = c2->AccessBoundingBoxes().ObjectSpaceBBox().Left();
auto const minOSy = c2->AccessBoundingBoxes().ObjectSpaceBBox().Bottom();
auto const minOSz = c2->AccessBoundingBoxes().ObjectSpaceBBox().Back();
auto const rangeOSx = c2->AccessBoundingBoxes().ObjectSpaceBBox().Width();
auto const rangeOSy = c2->AccessBoundingBoxes().ObjectSpaceBBox().Height();
auto const rangeOSz = c2->AccessBoundingBoxes().ObjectSpaceBBox().Depth();
auto const halfRangeOSx = c2->AccessBoundingBoxes().ObjectSpaceBBox().Width() * 0.5;
auto const halfRangeOSy = c2->AccessBoundingBoxes().ObjectSpaceBBox().Height() * 0.5;
auto const halfRangeOSz = c2->AccessBoundingBoxes().ObjectSpaceBBox().Depth() * 0.5;
float const sliceDistX = rangeOSx / static_cast<float>(sx - 1);
float const sliceDistY = rangeOSy / static_cast<float>(sy - 1);
float const sliceDistZ = rangeOSz / static_cast<float>(sz - 1);
float const maxCellSize = std::max(sliceDistX, std::max(sliceDistY, sliceDistZ));
for (unsigned int i = 0; i < c2->GetParticleListCount(); ++i) {
megamol::core::moldyn::MultiParticleDataCall::Particles& parts = c2->AccessParticles(i);
const float globRad = parts.GetGlobalRadius();
const bool useGlobRad =
(parts.GetVertexDataType() ==
megamol::core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZ) ||
(parts.GetVertexDataType() == megamol::core::moldyn::MultiParticleDataCall::Particles::VERTDATA_DOUBLE_XYZ);
if (parts.GetVertexDataType() == megamol::core::moldyn::MultiParticleDataCall::Particles::VERTDATA_NONE) {
continue;
}
totalParticles += parts.GetCount();
// https : // en.wikipedia.org/wiki/Radial_basis_function
auto gauss = [](float const dist, float const epsilon) -> float {
if (dist >= epsilon) return 0.0f;
return std::exp(-1.0f / (1.0f - std::pow((1.0f / epsilon) * dist, 2.0f)));
};
auto const& parStore = parts.GetParticleStore();
auto const& xAcc = parStore.GetXAcc();
auto const& yAcc = parStore.GetYAcc();
auto const& zAcc = parStore.GetZAcc();
auto const& rAcc = parStore.GetRAcc();
auto const& iAcc = parStore.GetCRAcc();
auto const sigma = this->sigmaSlot.Param<core::param::FloatParam>()->Value();
std::function<void(int, int, int, int, float, float)> volOp;
switch (this->aggregatorSlot.Param<core::param::EnumParam>()->Value()) {
case 1: {
volOp = [this, &gauss, iAcc, sx, sy, sigma](int const pidx, int const x, int const y, int const z,
float const dis, float const rad) -> void {
auto const val = iAcc->Get_f(pidx);
vol[omp_get_thread_num()][x + (y + z * sy) * sx] +=
gauss(dis, sigma * rad) * val;
};
} break;
default:
case 0: {
volOp = [this, &gauss, sx, sy, sigma](int const pidx, int const x, int const y, int const z, float const dis,
float const rad) -> void {
vol[omp_get_thread_num()][x + (y + z * sy) * sx] +=
gauss(dis, sigma * rad);
};
}
}
#if 0
# pragma omp parallel for collapse(4)
for (int z = 0; z < sz; ++z) {
for (int y = 0; y < sy; ++y) {
for (int x = 0; x < sx; ++x) {
for (int64_t j = 0; j < parts.GetCount(); ++j) {
auto const x_base = xAcc->Get_f(j);
auto const y_base = yAcc->Get_f(j);
auto const z_base = zAcc->Get_f(j);
auto rad = globRad;
if (!useGlobRad) rad = rAcc->Get_f(j);
float x_diff = static_cast<float>(x) * sliceDistX + minOSx;
x_diff = std::fabs(x_diff - x_base);
if (cycl_x && x_diff > halfRangeOSx) x_diff -= rangeOSx;
float y_diff = static_cast<float>(y) * sliceDistY + minOSy;
y_diff = std::fabs(y_diff - y_base);
if (cycl_y && y_diff > halfRangeOSy) y_diff -= rangeOSy;
float z_diff = static_cast<float>(z) * sliceDistZ + minOSz;
z_diff = std::fabs(z_diff - z_base);
if (cycl_z && z_diff > halfRangeOSz) z_diff -= rangeOSz;
float const dis = std::sqrt(x_diff * x_diff + y_diff * y_diff + z_diff * z_diff);
volOp(j, x, y, z, dis, rad);
}
}
}
}
#endif
#pragma omp parallel for
for (int64_t j = 0; j < parts.GetCount(); ++j) {
auto const x_base = xAcc->Get_f(j);
auto x = static_cast<int>((x_base - minOSx) / sliceDistX);
auto const y_base = yAcc->Get_f(j);
auto y = static_cast<int>((y_base - minOSy) / sliceDistY);
auto const z_base = zAcc->Get_f(j);
auto z = static_cast<int>((z_base - minOSz) / sliceDistZ);
auto rad = globRad;
if (!useGlobRad) rad = rAcc->Get_f(j);
int const filterSizeX = static_cast<int>(std::ceil(rad / sliceDistX));
int const filterSizeY = static_cast<int>(std::ceil(rad / sliceDistY));
int const filterSizeZ = static_cast<int>(std::ceil(rad / sliceDistZ));
for (int hz = z - filterSizeZ; hz <= z + filterSizeZ; ++hz) {
for (int hy = y - filterSizeY; hy <= y + filterSizeY; ++hy) {
for (int hx = x - filterSizeX; hx <= x + filterSizeX; ++hx) {
auto tmp_hx = hx;
auto tmp_hy = hy;
auto tmp_hz = hz;
if (cycl_x) {
tmp_hx = (hx + 2 * sx) % sx;
} else {
if (hx < 0 || hx > sx - 1) {
continue;
}
}
if (cycl_y) {
tmp_hy = (hy + 2 * sy) % sy;
} else {
if (hy < 0 || hy > sy - 1) {
continue;
}
}
if (cycl_z) {
tmp_hz = (hz + 2 * sz) % sz;
} else {
if (hz < 0 || hz > sz - 1) {
continue;
}
}
float x_diff = static_cast<float>(hx) * sliceDistX + minOSx;
x_diff = std::fabs(x_diff - x_base);
// if (x_diff > halfRangeOSx) x_diff -= rangeOSx;
float y_diff = static_cast<float>(hy) * sliceDistY + minOSy;
y_diff = std::fabs(y_diff - y_base);
// if (y_diff > halfRangeOSy) y_diff -= rangeOSy;
float z_diff = static_cast<float>(hz) * sliceDistZ + minOSz;
z_diff = std::fabs(z_diff - z_base);
// if (z_diff > halfRangeOSz) z_diff -= rangeOSz;
float const dis = std::sqrt(x_diff * x_diff + y_diff * y_diff + z_diff * z_diff);
volOp(j, tmp_hx, tmp_hy, tmp_hz, dis, rad);
}
}
}
}
}
for (int i = 1; i < omp_get_max_threads(); ++i) {
std::transform(vol[i].begin(), vol[i].end(), vol[0].begin(), vol[0].begin(), std::plus<>());
}
maxDens = *std::max_element(vol[0].begin(), vol[0].end());
minDens = *std::min_element(vol[0].begin(), vol[0].end());
vislib::sys::Log::DefaultLog.WriteInfo("ParticlesToDensity: Captured density %f -> %f", minDens, maxDens);
if (this->normalizeSlot.Param<core::param::BoolParam>()->Value()) {
auto const rcpValRange = 1.0f / (maxDens - minDens);
std::transform(
vol[0].begin(), vol[0].end(), vol[0].begin(), [this, rcpValRange](float const& a) { return (a - minDens) * rcpValRange; });
minDens = 0.0f;
maxDens = 1.0f;
}
//#define PTD_DEBUG_OUTPUT
#ifdef PTD_DEBUG_OUTPUT
std::ofstream raw_file{"bolla.raw", std::ios::binary};
raw_file.write(reinterpret_cast<char const*>(vol[0].data()), vol[0].size() * sizeof(float));
raw_file.close();
vislib::sys::Log::DefaultLog.WriteInfo("ParticlesToDensity: Debug file written\n");
#endif
// Cleanup
vol.resize(1);
const auto endTime = std::chrono::high_resolution_clock::now();
std::chrono::duration<float, std::milli> diffMillis = endTime - startTime;
vislib::sys::Log::DefaultLog.WriteInfo(
"ParticlesToDensity: creation of %u x %u x %u volume from %llu particles took %f ms.", sx, sy, sz,
totalParticles, diffMillis.count());
return true;
}
void datatools::ParticlesToDensity::modifyBBox(megamol::core::moldyn::MultiParticleDataCall* c2) {
auto sx = this->xResSlot.Param<core::param::IntParam>()->Value();
auto sy = this->yResSlot.Param<core::param::IntParam>()->Value();
auto sz = this->zResSlot.Param<core::param::IntParam>()->Value();
auto rangeOSx = c2->AccessBoundingBoxes().ObjectSpaceBBox().Width();
auto rangeOSy = c2->AccessBoundingBoxes().ObjectSpaceBBox().Height();
auto rangeOSz = c2->AccessBoundingBoxes().ObjectSpaceBBox().Depth();
float general_box_scaling = 1.1;
// extend deph
auto spacing = (rangeOSz * general_box_scaling) /sz;
auto newDepth = (rangeOSz * general_box_scaling) + 2 * spacing;
spacing = newDepth / sz;
// ensure cubic voxels
auto newWidth = (rangeOSx * general_box_scaling) + 2*spacing;
int resolutionX = newWidth/spacing;
auto rest = newWidth / spacing - static_cast<float>(resolutionX);
newWidth += (1-rest)*spacing;
resolutionX += 1;
this->xResSlot.Param<core::param::IntParam>()->SetValue(resolutionX);
auto newHeight = (rangeOSy * general_box_scaling) + 2 * spacing;
int resolutionY = newHeight / spacing;
rest = newHeight / spacing - static_cast<float>(resolutionY);
newHeight += (1 - rest) * spacing;
resolutionY += 1;
this->yResSlot.Param<core::param::IntParam>()->SetValue(resolutionY);
auto minOSx = c2->AccessBoundingBoxes().ObjectSpaceBBox().Left();
auto minOSy = c2->AccessBoundingBoxes().ObjectSpaceBBox().Bottom();
auto minOSz = c2->AccessBoundingBoxes().ObjectSpaceBBox().Back();
auto maxOSx = c2->AccessBoundingBoxes().ObjectSpaceBBox().Right();
auto maxOSy = c2->AccessBoundingBoxes().ObjectSpaceBBox().Top();
auto maxOSz = c2->AccessBoundingBoxes().ObjectSpaceBBox().Front();
auto newLeft = minOSx - (newWidth - rangeOSx) / 2;
auto newBottom = minOSy - (newHeight - rangeOSy) / 2;
auto newBack = minOSz - (newDepth - rangeOSz) / 2;
auto newRight = maxOSx + (newWidth - rangeOSx) / 2;
auto newTop = maxOSy + (newHeight - rangeOSy) / 2;
auto newFront = maxOSz + (newDepth - rangeOSz) / 2;
c2->AccessBoundingBoxes().SetObjectSpaceBBox(newLeft, newBottom, newBack, newRight, newTop, newFront);
c2->AccessBoundingBoxes().SetObjectSpaceClipBox(newLeft, newBottom, newBack, newRight, newTop, newFront);
}
bool datatools::ParticlesToDensity::dummyCallback(megamol::core::Call& c) { return true; }
| 44.653021 | 135 | 0.623085 | [
"transform"
] |
b9211546694795cb22dea13116043e75afde128c | 1,705 | cc | C++ | 0_leetcode/33_search-in-rotated-sorted-array/search.cc | amdfansheng/alogrithm | b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d | [
"MIT"
] | null | null | null | 0_leetcode/33_search-in-rotated-sorted-array/search.cc | amdfansheng/alogrithm | b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d | [
"MIT"
] | null | null | null | 0_leetcode/33_search-in-rotated-sorted-array/search.cc | amdfansheng/alogrithm | b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d | [
"MIT"
] | null | null | null | #include <vector>
#include <cstdio>
#include <cstdlib>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target)
{
int size = nums.size() - 1;
if (size == -1) return -1;
int left = 0, right = size;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[left] <= nums[mid]) { // 前有序
int ret = bsearch(nums, left, mid, target);
if (ret != -1) return ret;
left = mid + 1;
} else { // 后有序
int ret = bsearch(nums, mid, right, target);
if (ret != -1) return ret;
right = mid - 1;
}
}
return -1;
}
int bsearch(const vector<int> &nums, int left, int right, int target)
{
while (left <= right) {
int mid = left + (right - left) / 2;
printf("left: %d, mid: %d, right: %d, nums[mid]: %d\n", left, mid, right, nums[mid]);
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
void dump(const vector<int> &nums)
{
for (auto &&v : nums) {
printf("%d, ", v);
}
printf("\n");
}
};
int main(int argc, char *argv[])
{
if (argc < 2) return -1;
Solution s;
//vector<int> nums = {4, 5, 6, 7, 0, 1, 2};
vector<int> nums = {3, 1};
s.dump(nums);
int target = atoi(argv[1]);
int ret = s.search(nums, target);
printf("target: %d, index: %d\n", target, ret);
}
| 24.710145 | 97 | 0.43871 | [
"vector"
] |
b92117257545a302c4a80976b08ee99baba070d1 | 18,734 | cpp | C++ | avs/vis_avs/r_text.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 18 | 2020-07-30T11:55:23.000Z | 2022-02-25T02:39:15.000Z | avs/vis_avs/r_text.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 34 | 2021-01-13T02:02:12.000Z | 2022-03-23T12:09:55.000Z | avs/vis_avs/r_text.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 3 | 2021-03-18T12:53:58.000Z | 2021-10-02T20:24:41.000Z | /*
LICENSE
-------
Copyright 2005 Nullsoft, 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 Nullsoft 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 "c_text.h"
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#include <math.h>
#include "../util.h"
#include "r_defs.h"
#include "avs_eelif.h"
#ifndef LASER
// Reinit bitmap buffer since size changed
void C_THISCLASS::reinit(int w, int h)
{
// Free anything if needed
if (lw || lh)
{
SelectObject (hBitmapDC, hOldBitmap);
if (hOldFont) SelectObject(hBitmapDC, hOldFont);
DeleteDC (hBitmapDC);
ReleaseDC (NULL, hDesktopDC);
if (myBuffer) free(myBuffer);
}
// Alloc buffers, select objects, init structures
myBuffer = (int *)malloc(w*h*4);
hDesktopDC = GetDC (NULL);
hRetBitmap = CreateCompatibleBitmap (hDesktopDC, w, h);
hBitmapDC = CreateCompatibleDC (hDesktopDC);
hOldBitmap = (HBITMAP) SelectObject (hBitmapDC, hRetBitmap);
SetTextColor(hBitmapDC, ((color & 0xFF0000) >> 16) | (color & 0xFF00) | (color&0xFF)<<16);
SetBkMode(hBitmapDC, TRANSPARENT);
SetBkColor(hBitmapDC, 0);
if (myFont)
hOldFont = (HFONT) SelectObject(hBitmapDC, myFont);
else
hOldFont = NULL;
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = h;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biSizeImage = 0;
bi.bmiHeader.biXPelsPerMeter = 0;
bi.bmiHeader.biYPelsPerMeter = 0;
bi.bmiHeader.biClrUsed = 0;
bi.bmiHeader.biClrImportant = 0;
}
C_THISCLASS::~C_THISCLASS()
{
// Free up everything
if (lw || lh)
{
SelectObject (hBitmapDC, hOldBitmap);
if (hOldFont) SelectObject(hBitmapDC, hOldFont);
DeleteDC (hBitmapDC);
ReleaseDC (NULL, hDesktopDC);
if (myBuffer) free(myBuffer);
}
if (text) free(text);
if (myFont)
DeleteObject(myFont);
}
// configuration read/write
C_THISCLASS::C_THISCLASS() // set up default configuration
{
// Init all
randomword=0;
shadow=0;
old_valign=0;
old_halign=0;
old_outline=-1;
old_curword=-1;
old_clipcolor=-1;
oldshadow=-1;
*oldtxt=0;
old_blend1=0;
old_blend2=0;
old_blend3=0;
_xshift=0;
_yshift=0;
forceredraw=0;
myBuffer = NULL;
curword=0;
forceshift=0;
forceBeat=0;
forcealign=1;
xshift=0;
yshift=0;
outlinecolor = 0;
outline=0;
outline=0;
color = 0xFFFFFF;
enabled = 1;
blend = 0;
blendavg = 0;
onbeat = 0;
insertBlank = 0;
randomPos = 0;
halign = DT_CENTER;
valign = DT_VCENTER;
onbeatSpeed=15;
normSpeed=15;
myFont = NULL;
memset(&cf, 0, sizeof(CHOOSEFONT));
cf.lStructSize = sizeof(CHOOSEFONT);
cf.lpLogFont = &lf;
cf.Flags = CF_EFFECTS|CF_SCREENFONTS |CF_FORCEFONTEXIST|CF_INITTOLOGFONTSTRUCT;
cf.rgbColors = color;
memset(&lf, 0, sizeof(LOGFONT));
text = NULL;
lw=lh=0;
updating=false;
nb=0;
outlinesize=1;
oddeven=0;
nf=0;
shiftinit=1;
}
#define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24))
void C_THISCLASS::load_config(unsigned char *data, int len) // read configuration of max length "len" from data.
{
int pos=0;
int size=0;
updating=true;
forceredraw=1;
if (len-pos >= 4) { enabled=GET_INT(); pos+=4; }
if (len-pos >= 4) { color=GET_INT(); pos+=4; }
if (len-pos >= 4) { blend=GET_INT(); pos+=4; }
if (len-pos >= 4) { blendavg=GET_INT(); pos+=4; }
if (len-pos >= 4) { onbeat=GET_INT(); pos+=4; }
if (len-pos >= 4) { insertBlank=GET_INT(); pos+=4; }
if (len-pos >= 4) { randomPos=GET_INT(); pos+=4; }
if (len-pos >= 4) { valign=GET_INT(); pos+=4; }
if (len-pos >= 4) { halign=GET_INT(); pos+=4; }
if (len-pos >= 4) { onbeatSpeed=GET_INT(); pos+=4; }
if (len-pos >= 4) { normSpeed=GET_INT(); pos+=4; }
if (len-pos >= ssizeof32(cf)) { memcpy(&cf, data+pos, sizeof(cf)); pos+=sizeof(cf);}
cf.lpLogFont = &lf;
if (len-pos >= ssizeof32(lf)) { memcpy(&lf, data+pos, sizeof(lf)); pos+=sizeof(lf);}
if (len-pos >= 4) { size=GET_INT(); pos+=4; }
if (size > 0 && len-pos >= size)
{
if (text) free(text);
text = (char *)malloc(size+1);
memcpy(text, data+pos, size);
pos+=size;
}
else
{
if (text) free(text);
text = NULL;
}
myFont = CreateFontIndirect(&lf);
if (len-pos >= 4) { outline=GET_INT(); pos+=4; }
if (len-pos >= 4) { outlinecolor=GET_INT(); pos+=4; }
if (len-pos >= 4) { xshift=GET_INT(); pos+=4; }
if (len-pos >= 4) { yshift=GET_INT(); pos+=4; }
if (len-pos >= 4) { outlinesize=GET_INT(); pos+=4; }
if (len-pos >= 4) { randomword=GET_INT(); pos+=4; }
if (len-pos >= 4) { shadow=GET_INT(); pos+=4; }
forcealign=1;
forceredraw=1;
forceshift=1;
shiftinit=1;
updating=false;
}
#define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255
extern HWND hwnd_WinampParent;
int C_THISCLASS::save_config(unsigned char *data) // write configuration to data, return length. config data should not exceed 64k.
{
int pos=0;
PUT_INT(enabled); pos+=4;
PUT_INT(color); pos+=4;
PUT_INT(blend); pos+=4;
PUT_INT(blendavg); pos+=4;
PUT_INT(onbeat); pos+=4;
PUT_INT(insertBlank); pos+=4;
PUT_INT(randomPos); pos+=4;
PUT_INT(valign); pos+=4;
PUT_INT(halign); pos+=4;
PUT_INT(onbeatSpeed); pos+=4;
PUT_INT(normSpeed); pos+=4;
memcpy(data+pos, &cf, sizeof(cf));
pos+=sizeof(cf);
memcpy(data+pos, &lf, sizeof(lf));
pos+=sizeof(lf);
if (text)
{
int l=strlen(text)+1;
PUT_INT(l); pos+=4;
memcpy(data+pos, text, strlen(text)+1);
pos+=strlen(text)+1;
}
else
{ PUT_INT(0); pos+=4;}
PUT_INT(outline); pos+=4;
PUT_INT(outlinecolor); pos+=4;
PUT_INT(xshift); pos+=4;
PUT_INT(yshift); pos+=4;
PUT_INT(outlinesize); pos+=4;
PUT_INT(randomword); pos+=4;
PUT_INT(shadow); pos+=4;
return pos;
}
// Parse text buffer for a specified word
void C_THISCLASS::getWord(int n, char *buf, int maxlen)
{
int w=0;
char *p=text;
char *d=buf;
*d=0;
if (!p) return;
while (w<n && *p)
{
if (*p==';')
w++;
p++;
}
maxlen--; // null terminator
while (*p && *p != ';' && maxlen>0)
{
char *endp;
if ((!strnicmp(p,"$(playpos",9) || !strnicmp(p,"$(playlen",9)) && (endp = strstr(p+9,")")))
{
char buf[128];
int islen=strnicmp(p,"$(playpos",9);
int add_dig=0;
if (p[9]=='.')
add_dig=atoi(p+10);
if (add_dig > 3) add_dig=3;
int pos=0;
extern HWND hwnd_WinampParent;
if (IsWindow(hwnd_WinampParent))
{
if (!SendMessageTimeout( hwnd_WinampParent, WM_USER,(WPARAM)!!islen,(LPARAM)105,SMTO_BLOCK,50,(LPDWORD)&pos))
pos=0;
}
if (islen) pos*=1000;
wsprintf(buf,"%d:%02d",pos/60000,(pos/1000)%60);
if (add_dig>0)
{
char fmt[16];
wsprintf(fmt,".%%%02dd",add_dig);
int div=1;
int x;
for (x = 0; x < 3-add_dig; x ++)
{
div*=10;
}
wsprintf(buf+strlen(buf),fmt,(pos%1000) / div);
}
int l=strlen(buf);
if (l > maxlen) l=maxlen;
memcpy(d,buf,l);
maxlen-=l;
d += l;
p=endp+1;
}
else if (!strnicmp(p,"$(title",7) && (endp = strstr(p+7,")")))
{
static char this_title[256];
static unsigned int ltg;
unsigned int now=GetTickCount();
if (!this_title[0] || now-ltg > 1000 || now < ltg)
{
ltg=now;
char *tpp;
if (IsWindow(hwnd_WinampParent))
{
DWORD id;
if (!SendMessageTimeout( hwnd_WinampParent,WM_GETTEXT,(WPARAM)sizeof(this_title),(LPARAM)this_title,SMTO_BLOCK,50,&id) || !id)
{
this_title[0]=0;
}
}
tpp = this_title+strlen(this_title);
while (tpp >= this_title)
{
char buf[9];
memcpy(buf,tpp,8);
buf[8]=0;
if (!lstrcmpi(buf,"- Winamp")) break;
tpp--;
}
if (tpp >= this_title) tpp--;
while (tpp >= this_title && *tpp == ' ') tpp--;
*++tpp=0;
}
int skipnum=1,max_fmtlen=0;
char *titleptr=this_title;
if (p[7] == ':')
{
char *ptr=p+8;
if (*ptr == 'n') { ptr++; skipnum=0; }
max_fmtlen=atoi(ptr);
}
// use: $(reg00), $(reg00:4.5), $(title), $(title:32), $(title:n32)
if (skipnum && *titleptr >= '0' && *titleptr <= '9')
{
while (*titleptr >= '0' && *titleptr <= '9') titleptr++;
if (*titleptr == '.')
{
titleptr++;
if (*titleptr == ' ')
{
titleptr++;
}
else titleptr=this_title;
}
else titleptr=this_title;
}
int n=strlen(titleptr);
if (n > maxlen)n=maxlen;
if (max_fmtlen >0 && max_fmtlen < n) n=max_fmtlen;
memcpy(d,titleptr,n);
maxlen-=n;
d+=n;
p=endp+1;
}
else if (!strnicmp(p,"$(reg",5) && p[5] >= '0' && p[5] <= '9' &&
p[6] >= '0' && p[6] <= '9' && (endp = strstr(p+7,")")))
{
char buf[128];
char fmt[32];
int wr=atoi(p+5);
if (wr <0)wr=0;
if (wr>99)wr=99;
p+=7;
char *fmtptr=fmt;
*fmtptr++='%';
if (*p == ':')
{
p++;
while (fmtptr-fmt < 16 && ((*p >= '0' && *p <= '9') || *p == '.'))
*fmtptr++=*p++;
}
*fmtptr++='f';
*fmtptr++=0;
int l=sprintf(buf,fmt,NSEEL_getglobalregs()[wr]);
if (l > maxlen) l=maxlen;
memcpy(d,buf,l);
maxlen-=l;
d += l;
p = endp+1;
}
else
{
*d++=*p++;
maxlen--;
}
}
*d=0;
}
// Returns number of words in buffer
static int getNWords(char *buf)
{
char *p=buf;
int n=0;
while (p && *p)
{
if (*p==';')
n++;
p++;
}
return n;
}
// render function
// render should return 0 if it only used framebuffer, or 1 if the new output data is in fbout. this is
// used when you want to do something that you'd otherwise need to make a copy of the framebuffer.
// w and h are the width and height of the screen, in pixels.
// isBeat is 1 if a beat has been detected.
// visdata is in the format of [spectrum:0,wave:1][channel][band].
int C_THISCLASS::render(char[2][2][576], int isBeat, int *framebuffer, int*, int w, int h)
{
int i,j;
int *p,*d;
int clipcolor;
char thisText[256];
if (updating) return 0;
if (!enabled) return 0;
if (isBeat&0x80000000) return 0;
if (forcealign)
{
forcealign=false;
_halign = halign;
_valign = valign;
}
if (shiftinit)
{
shiftinit=0;
_xshift = xshift;
_yshift = yshift;
}
// If not beat sensitive and time is up for this word
// OR if beat sensitive and this frame is a beat and time is up for last beat
if ((!onbeat && nf >= normSpeed) || (onbeat && isBeat && !nb))
{ // Then choose which word to show
if (!(insertBlank && !(oddeven % 2)))
{
if (randomword)
curword=rand()%(getNWords(text)+1);
else
{
curword++;
curword%=(getNWords(text)+1);
}
}
oddeven++;
oddeven%=2;
}
if (forceBeat)
{
isBeat = 1;
forceBeat=0;
}
// If beat sensitive and frame is a beat and last beat expired, start frame timer for this beat
if (onbeat && isBeat && !nb)
nb = onbeatSpeed;
// Get the word(s) to show
getWord(curword, thisText, 256);
if (insertBlank && !oddeven)
*thisText=0;
// Same test as above but takes care of nb init
if ((!onbeat && nf >= normSpeed) || (onbeat && isBeat && nb == onbeatSpeed))
{
nf=0;
if (randomPos && w && h) // Handle random position
{
SIZE size={0,0};
GetTextExtentPoint32(hBitmapDC, thisText, strlen(thisText), &size); // Don't write outside the screen
_halign = DT_LEFT;
if (size.cx < w)
_xshift = rand() % (int)(((float)(w-size.cx) / (float)w) * 100.0F);
_valign = DT_TOP;
if (size.cy < h)
_yshift = rand() % (int)(((float)(h-size.cy) / (float)h) * 100.0F);
forceshift=1;
}
else
{ // Reset position to what is specified
_halign = halign;
_valign = valign;
_xshift = xshift;
_yshift = yshift;
}
}
// Choose cliping color
if (color != 0 && outlinecolor != 0)
clipcolor = 0;
else
if (color != 0x000008 && outlinecolor != 0x000008)
clipcolor = 8;
else
if (color != 0x0000010 && outlinecolor != 0x0000010)
clipcolor = 10;
// If size changed or if we're forced to shift the buffer
if ((lw != w || lh != h) || forceshift)
{
if (lw != w || lh != h) // only if size changed then reinit buffer, not if its only a forcedshifting
reinit(w, h);
forceshift=0;
forceredraw=1; // do redraw!
// remember last state
lw = w;
lh = h;
// Compute buffer position
r.left = 0;
r.right = w;
r.top = 0;
r.bottom = h;
r.left += (int)((float)_xshift * (float)w / 100.0F);
r.right += (int)((float)_xshift * (float)w / 100.0F);
r.top += (int)((float)_yshift * (float)h / 100.0F);
r.bottom += (int)((float)_yshift * (float)h / 100.0F);
forceredraw=1;
}
// Check if we need to redraw the buffer
if (forceredraw ||
old_halign != _halign ||
old_valign != _valign ||
curword != old_curword ||
(*thisText && strcmp(thisText, oldtxt)) ||
old_clipcolor != clipcolor ||
(old_blend1 != (blend && !(onbeat && !nb))) ||
(old_blend2 != (blendavg && !(onbeat && !nb))) ||
(old_blend3 != (!(onbeat && !nb))) ||
old_outline != outline ||
oldshadow != shadow ||
_xshift != oldxshift ||
_yshift != oldyshift)
{
forceredraw=0;
old_halign = _halign;
old_valign = _valign;
old_curword = curword;
if (thisText) strcpy(oldtxt, thisText);
old_clipcolor = clipcolor;
old_blend1 = (blend && !(onbeat && !nb));
old_blend2 = (blendavg && !(onbeat && !nb));
old_blend3 = !(onbeat && !nb);
old_outline = outline;
oldshadow = shadow;
oldxshift = _xshift;
oldyshift = _yshift;
// Draw everything
p = myBuffer;
while (p < myBuffer+h*w) { *p = clipcolor; p++; }
SetDIBits(hBitmapDC, hRetBitmap, 0, h, (void *)myBuffer, &bi, DIB_RGB_COLORS);
if (*thisText)
{
if (outline)
{
SetTextColor(hBitmapDC, ((outlinecolor&0xFF0000) >> 16) | (outlinecolor& 0xFF00) | (outlinecolor&0xFF)<<16);
r.left-=outlinesize; r.right-=outlinesize; r.top-=outlinesize; r.bottom-=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.left+=outlinesize; r.right+=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.left+=outlinesize; r.right+=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.top+=outlinesize; r.bottom+=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.top+=outlinesize; r.bottom+=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.left-=outlinesize; r.right-=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.left-=outlinesize; r.right-=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.top-=outlinesize; r.bottom-=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.left+=outlinesize; r.right+=outlinesize;
SetTextColor(hBitmapDC, ((color&0xFF0000) >> 16) | (color& 0xFF00) | (color&0xFF)<<16);
}
else if (shadow)
{
SetTextColor(hBitmapDC, ((outlinecolor&0xFF0000) >> 16) | (outlinecolor& 0xFF00) | (outlinecolor&0xFF)<<16);
r.left+=outlinesize; r.right+=outlinesize; r.top+=outlinesize; r.bottom+=outlinesize;
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
r.left-=outlinesize; r.right-=outlinesize; r.top-=outlinesize; r.bottom-=outlinesize;
SetTextColor(hBitmapDC, ((color&0xFF0000) >> 16) | (color& 0xFF00) | (color&0xFF)<<16);
}
DrawText(hBitmapDC, thisText, strlen(thisText), &r, _valign | _halign | DT_NOCLIP | DT_SINGLELINE);
}
GetDIBits(hBitmapDC, hRetBitmap, 0, h, (void *)myBuffer, &bi, DIB_RGB_COLORS);
}
// Now render the bitmap text buffer over framebuffer, handle blending options.
// Separate blocks here so we don4t have to make w*h tests
p = myBuffer;
d = framebuffer+w*(h-1);
if (blend && !(onbeat && !nb))
for (i=0;i<h;i++)
{
for (j=0;j<w;j++)
{
if (*p != clipcolor) *d=BLEND(*p, *d);
d++;
p++;
}
d -= w*2;
}
else
if (blendavg && !(onbeat && !nb))
for (i=0;i<h;i++)
{
for (j=0;j<w;j++)
{
if (*p != clipcolor) *d=BLEND_AVG(*p, *d);
d++;
p++;
}
d -= w*2;
}
else
if (!(onbeat && !nb))
for (i=0;i<h;i++)
{
for (j=0;j<w;j++)
{
if (*p != clipcolor)
*d=*p;
d++;
p++;
}
d -= w*2;
}
// Advance frame counter
if (!onbeat) nf++;
// Decrease frametimer
if (onbeat && nb) nb--;
return 0;
}
C_RBASE *R_Text(char *desc) // creates a new effect object if desc is NULL, otherwise fills in desc with description
{
if (desc) { strcpy(desc,MOD_NAME); return NULL; }
return (C_RBASE *) new C_THISCLASS();
}
#else
C_RBASE *R_Text(char *desc) // creates a new effect object if desc is NULL, otherwise fills in desc with description
{ return NULL; }
#endif
| 27.55 | 137 | 0.609694 | [
"render",
"object"
] |
b9291e9a75819be057ef3b6674c25eacf814a4eb | 2,448 | cpp | C++ | Tools/DumpRenderTree/CyclicRedundancyCheck.cpp | VincentWei/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | Tools/DumpRenderTree/CyclicRedundancyCheck.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | null | null | null | Tools/DumpRenderTree/CyclicRedundancyCheck.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-17T06:02:42.000Z | 2018-09-19T10:08:38.000Z | /*
* Copyright (C) 2010, Robert Eisele <robert@xarg.org> 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 "CyclicRedundancyCheck.h"
#include <wtf/Vector.h>
static void makeCrcTable(unsigned long crcTable[256])
{
for (unsigned long i = 0; i < 256; i++) {
unsigned long c = i;
for (int k = 0; k < 8; k++) {
if (c & 1)
c = -306674912 ^ ((c >> 1) & 0x7fffffff);
else
c = c >> 1;
}
crcTable[i] = c;
}
}
unsigned long computeCrc(const Vector<unsigned char>& buffer)
{
static unsigned long crcTable[256];
static bool crcTableComputed = false;
if (!crcTableComputed) {
makeCrcTable(crcTable);
crcTableComputed = true;
}
unsigned long crc = 0xffffffffL;
for (size_t i = 0; i < buffer.size(); ++i)
crc = crcTable[(crc ^ buffer[i]) & 0xff] ^ ((crc >> 8) & 0x00ffffffL);
return crc ^ 0xffffffffL;
}
| 37.661538 | 78 | 0.688725 | [
"vector"
] |
b9360939976045cfb2d39ba4417d860c2ef6e36a | 6,350 | cpp | C++ | flashsim/dftl_ftl.cpp | praneethyerramothu/AOSPROJECT1 | 1792b1c484bc35e334093b9a5c2fb4d20b3f4452 | [
"BSD-4-Clause-UC"
] | 6 | 2015-05-31T15:28:30.000Z | 2022-02-10T04:39:18.000Z | flashsim/dftl_ftl.cpp | praneethyerramothu/AOSPROJECT1 | 1792b1c484bc35e334093b9a5c2fb4d20b3f4452 | [
"BSD-4-Clause-UC"
] | null | null | null | flashsim/dftl_ftl.cpp | praneethyerramothu/AOSPROJECT1 | 1792b1c484bc35e334093b9a5c2fb4d20b3f4452 | [
"BSD-4-Clause-UC"
] | 6 | 2015-03-23T02:49:28.000Z | 2018-10-30T06:44:40.000Z | /* Copyright 2011 Matias Bjørling */
/* dftp_ftl.cpp */
/* FlashSim is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version. */
/* FlashSim 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 FlashSim. If not, see <http://www.gnu.org/licenses/>. */
/****************************************************************************/
/* Implementation of the DFTL described in the paper
* "DFTL: A Flasg Translation Layer Employing Demand-based Selective Caching og Page-level Address Mappings"
*
* Global Mapping Table GMT
* Global Translation Directory GTD (Maintained in memory)
* Cached Mapping Table CMT (Uses LRU to pick victim)
*
* Dlpn/Dppn Data Logical/Physical Page Number
* Mlpn/Mppn Translation Logical/Physical Page Number
*/
#include <new>
#include <assert.h>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <queue>
#include <iostream>
#include "ssd.h"
using namespace ssd;
FtlImpl_Dftl::FtlImpl_Dftl(Controller &controller):
FtlImpl_DftlParent(controller)
{
uint ssdSize = NUMBER_OF_ADDRESSABLE_BLOCKS * BLOCK_SIZE;
printf("Total size to map: %uKB\n", ssdSize * PAGE_SIZE / 1024);
printf("Using DFTL.\n");
return;
}
FtlImpl_Dftl::~FtlImpl_Dftl(void)
{
return;
}
enum status FtlImpl_Dftl::read(Event &event)
{
uint dlpn = event.get_logical_address();
resolve_mapping(event, false);
MPage current = trans_map[dlpn];
if (current.ppn == -1)
{
event.set_address(Address(0, PAGE));
event.set_noop(true);
}
else
event.set_address(Address(current.ppn, PAGE));
controller.stats.numFTLRead++;
return controller.issue(event);
}
enum status FtlImpl_Dftl::write(Event &event)
{
uint dlpn = event.get_logical_address();
resolve_mapping(event, true);
// Important order. As get_free_data_page might change current.
long free_page = get_free_data_page(event);
MPage current = trans_map[dlpn];
Address a = Address(current.ppn, PAGE);
if (current.ppn != -1)
event.set_replace_address(a);
update_translation_map(current, free_page);
trans_map.replace(trans_map.begin()+dlpn, current);
Address b = Address(free_page, PAGE);
event.set_address(b);
controller.stats.numFTLWrite++;
return controller.issue(event);
}
enum status FtlImpl_Dftl::trim(Event &event)
{
uint dlpn = event.get_logical_address();
event.set_address(Address(0, PAGE));
MPage current = trans_map[dlpn];
if (current.ppn != -1)
{
Address address = Address(current.ppn, PAGE);
Block *block = controller.get_block_pointer(address);
block->invalidate_page(address.page);
evict_specific_page_from_cache(event, dlpn);
update_translation_map(current, -1);
trans_map.replace(trans_map.begin()+dlpn, current);
}
controller.stats.numFTLTrim++;
return controller.issue(event);
}
void FtlImpl_Dftl::cleanup_block(Event &event, Block *block)
{
std::map<long, long> invalidated_translation;
/*
* 1. Copy only valid pages in the victim block to the current data block
* 2. Invalidate old pages
* 3. mark their corresponding translation pages for update
*/
for (uint i=0;i<BLOCK_SIZE;i++)
{
assert(block->get_state(i) != EMPTY);
// When valid, two events are create, one for read and one for write. They are chained and the controller are
// called to execute them. The execution time is then added to the real event.
if (block->get_state(i) == VALID)
{
// Set up events.
Event readEvent = Event(READ, event.get_logical_address(), 1, event.get_start_time());
readEvent.set_address(Address(block->get_physical_address()+i, PAGE));
// Execute read event
if (controller.issue(readEvent) == FAILURE)
printf("Data block copy failed.");
// Get new address to write to and invalidate previous
Event writeEvent = Event(WRITE, event.get_logical_address(), 1, event.get_start_time()+readEvent.get_time_taken());
Address dataBlockAddress = Address(get_free_data_page(event, false), PAGE);
writeEvent.set_address(dataBlockAddress);
writeEvent.set_replace_address(Address(block->get_physical_address()+i, PAGE));
// Setup the write event to read from the right place.
writeEvent.set_payload((char*)page_data + (block->get_physical_address()+i) * PAGE_SIZE);
if (controller.issue(writeEvent) == FAILURE)
printf("Data block copy failed.");
event.incr_time_taken(writeEvent.get_time_taken() + readEvent.get_time_taken());
// Update GTD
long dataPpn = dataBlockAddress.get_linear_address();
// vpn -> Old ppn to new ppn
//printf("%li Moving %li to %li\n", reverse_trans_map[block->get_physical_address()+i], block->get_physical_address()+i, dataPpn);
invalidated_translation[reverse_trans_map[block->get_physical_address()+i]] = dataPpn;
// Statistics
controller.stats.numFTLRead++;
controller.stats.numFTLWrite++;
controller.stats.numWLRead++;
controller.stats.numWLWrite++;
controller.stats.numMemoryRead++; // Block->get_state(i) == VALID
controller.stats.numMemoryWrite =+ 3; // GTD Update (2) + translation invalidate (1)
}
}
/*
* Perform batch update on the marked translation pages
* 1. Update GDT and CMT if necessary.
* 2. Simulate translation page updates.
*/
std::map<long, bool> dirtied_translation_pages;
for (std::map<long, long>::const_iterator i = invalidated_translation.begin(); i!=invalidated_translation.end(); ++i)
{
long real_vpn = (*i).first;
long newppn = (*i).second;
// Update translation map ( it also updates the CMT, as it is stored inside the GDT )
MPage current = trans_map[real_vpn];
update_translation_map(current, newppn);
if (current.cached)
current.modified_ts = event.get_start_time();
else
{
current.modified_ts = event.get_start_time();
current.create_ts = event.get_start_time();
current.cached = true;
cmt++;
}
trans_map.replace(trans_map.begin()+real_vpn, current);
}
}
void FtlImpl_Dftl::print_ftl_statistics()
{
Block_manager::instance()->print_statistics();
}
| 28.603604 | 133 | 0.71937 | [
"vector"
] |
b9381264a72cea35cd45d6ce8c433da743a33346 | 8,698 | cpp | C++ | src/model/Table.cpp | rizwanniazigroupdocs/aspose-slides-cloud-cpp | f668947a72f717a955bc4579537e853b9e43eb45 | [
"MIT"
] | null | null | null | src/model/Table.cpp | rizwanniazigroupdocs/aspose-slides-cloud-cpp | f668947a72f717a955bc4579537e853b9e43eb45 | [
"MIT"
] | null | null | null | src/model/Table.cpp | rizwanniazigroupdocs/aspose-slides-cloud-cpp | f668947a72f717a955bc4579537e853b9e43eb45 | [
"MIT"
] | 1 | 2020-12-25T16:15:58.000Z | 2020-12-25T16:15:58.000Z | // --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose" file="ApiBase.cs">
// Copyright (c) 2020 Aspose.Slides for Cloud
// </copyright>
// <summary>
// 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.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#include "Table.h"
namespace asposeslidescloud {
namespace model {
Table::Table()
{
m_FirstColIsSet = false;
m_FirstRowIsSet = false;
m_HorizontalBandingIsSet = false;
m_LastColIsSet = false;
m_LastRowIsSet = false;
m_RightToLeftIsSet = false;
m_VerticalBandingIsSet = false;
}
Table::~Table()
{
}
utility::string_t Table::getStyle() const
{
return m_Style;
}
void Table::setStyle(utility::string_t value)
{
m_Style = value;
}
std::vector<std::shared_ptr<TableRow>> Table::getRows() const
{
return m_Rows;
}
void Table::setRows(std::vector<std::shared_ptr<TableRow>> value)
{
m_Rows = value;
}
std::vector<std::shared_ptr<TableColumn>> Table::getColumns() const
{
return m_Columns;
}
void Table::setColumns(std::vector<std::shared_ptr<TableColumn>> value)
{
m_Columns = value;
}
bool Table::getFirstCol() const
{
return m_FirstCol;
}
void Table::setFirstCol(bool value)
{
m_FirstCol = value;
m_FirstColIsSet = true;
}
bool Table::firstColIsSet() const
{
return m_FirstColIsSet;
}
void Table::unsetFirstCol()
{
m_FirstColIsSet = false;
}
bool Table::getFirstRow() const
{
return m_FirstRow;
}
void Table::setFirstRow(bool value)
{
m_FirstRow = value;
m_FirstRowIsSet = true;
}
bool Table::firstRowIsSet() const
{
return m_FirstRowIsSet;
}
void Table::unsetFirstRow()
{
m_FirstRowIsSet = false;
}
bool Table::getHorizontalBanding() const
{
return m_HorizontalBanding;
}
void Table::setHorizontalBanding(bool value)
{
m_HorizontalBanding = value;
m_HorizontalBandingIsSet = true;
}
bool Table::horizontalBandingIsSet() const
{
return m_HorizontalBandingIsSet;
}
void Table::unsetHorizontalBanding()
{
m_HorizontalBandingIsSet = false;
}
bool Table::getLastCol() const
{
return m_LastCol;
}
void Table::setLastCol(bool value)
{
m_LastCol = value;
m_LastColIsSet = true;
}
bool Table::lastColIsSet() const
{
return m_LastColIsSet;
}
void Table::unsetLastCol()
{
m_LastColIsSet = false;
}
bool Table::getLastRow() const
{
return m_LastRow;
}
void Table::setLastRow(bool value)
{
m_LastRow = value;
m_LastRowIsSet = true;
}
bool Table::lastRowIsSet() const
{
return m_LastRowIsSet;
}
void Table::unsetLastRow()
{
m_LastRowIsSet = false;
}
bool Table::getRightToLeft() const
{
return m_RightToLeft;
}
void Table::setRightToLeft(bool value)
{
m_RightToLeft = value;
m_RightToLeftIsSet = true;
}
bool Table::rightToLeftIsSet() const
{
return m_RightToLeftIsSet;
}
void Table::unsetRightToLeft()
{
m_RightToLeftIsSet = false;
}
bool Table::getVerticalBanding() const
{
return m_VerticalBanding;
}
void Table::setVerticalBanding(bool value)
{
m_VerticalBanding = value;
m_VerticalBandingIsSet = true;
}
bool Table::verticalBandingIsSet() const
{
return m_VerticalBandingIsSet;
}
void Table::unsetVerticalBanding()
{
m_VerticalBandingIsSet = false;
}
web::json::value Table::toJson() const
{
web::json::value val = this->ShapeBase::toJson();
if (!m_Style.empty())
{
val[utility::conversions::to_string_t("Style")] = ModelBase::toJson(m_Style);
}
{
std::vector<web::json::value> jsonArray;
for (auto& item : m_Rows)
{
jsonArray.push_back(ModelBase::toJson(item));
}
if (jsonArray.size() > 0)
{
val[utility::conversions::to_string_t("Rows")] = web::json::value::array(jsonArray);
}
}
{
std::vector<web::json::value> jsonArray;
for (auto& item : m_Columns)
{
jsonArray.push_back(ModelBase::toJson(item));
}
if (jsonArray.size() > 0)
{
val[utility::conversions::to_string_t("Columns")] = web::json::value::array(jsonArray);
}
}
if(m_FirstColIsSet)
{
val[utility::conversions::to_string_t("FirstCol")] = ModelBase::toJson(m_FirstCol);
}
if(m_FirstRowIsSet)
{
val[utility::conversions::to_string_t("FirstRow")] = ModelBase::toJson(m_FirstRow);
}
if(m_HorizontalBandingIsSet)
{
val[utility::conversions::to_string_t("HorizontalBanding")] = ModelBase::toJson(m_HorizontalBanding);
}
if(m_LastColIsSet)
{
val[utility::conversions::to_string_t("LastCol")] = ModelBase::toJson(m_LastCol);
}
if(m_LastRowIsSet)
{
val[utility::conversions::to_string_t("LastRow")] = ModelBase::toJson(m_LastRow);
}
if(m_RightToLeftIsSet)
{
val[utility::conversions::to_string_t("RightToLeft")] = ModelBase::toJson(m_RightToLeft);
}
if(m_VerticalBandingIsSet)
{
val[utility::conversions::to_string_t("VerticalBanding")] = ModelBase::toJson(m_VerticalBanding);
}
return val;
}
void Table::fromJson(web::json::value& val)
{
this->ShapeBase::fromJson(val);
web::json::value* jsonForStyle = ModelBase::getField(val, "Style");
if(jsonForStyle != nullptr && !jsonForStyle->is_null())
{
setStyle(ModelBase::stringFromJson(*jsonForStyle));
}
web::json::value* jsonForRows = ModelBase::getField(val, "Rows");
if(jsonForRows != nullptr && !jsonForRows->is_null())
{
{
m_Rows.clear();
std::vector<web::json::value> jsonArray;
for(auto& item : jsonForRows->as_array())
{
if(item.is_null())
{
m_Rows.push_back(std::shared_ptr<TableRow>(nullptr));
}
else
{
std::shared_ptr<TableRow> newItem(new TableRow());
newItem->fromJson(item);
m_Rows.push_back( newItem );
}
}
}
}
web::json::value* jsonForColumns = ModelBase::getField(val, "Columns");
if(jsonForColumns != nullptr && !jsonForColumns->is_null())
{
{
m_Columns.clear();
std::vector<web::json::value> jsonArray;
for(auto& item : jsonForColumns->as_array())
{
if(item.is_null())
{
m_Columns.push_back(std::shared_ptr<TableColumn>(nullptr));
}
else
{
std::shared_ptr<TableColumn> newItem(new TableColumn());
newItem->fromJson(item);
m_Columns.push_back( newItem );
}
}
}
}
web::json::value* jsonForFirstCol = ModelBase::getField(val, "FirstCol");
if(jsonForFirstCol != nullptr && !jsonForFirstCol->is_null())
{
setFirstCol(ModelBase::boolFromJson(*jsonForFirstCol));
}
web::json::value* jsonForFirstRow = ModelBase::getField(val, "FirstRow");
if(jsonForFirstRow != nullptr && !jsonForFirstRow->is_null())
{
setFirstRow(ModelBase::boolFromJson(*jsonForFirstRow));
}
web::json::value* jsonForHorizontalBanding = ModelBase::getField(val, "HorizontalBanding");
if(jsonForHorizontalBanding != nullptr && !jsonForHorizontalBanding->is_null())
{
setHorizontalBanding(ModelBase::boolFromJson(*jsonForHorizontalBanding));
}
web::json::value* jsonForLastCol = ModelBase::getField(val, "LastCol");
if(jsonForLastCol != nullptr && !jsonForLastCol->is_null())
{
setLastCol(ModelBase::boolFromJson(*jsonForLastCol));
}
web::json::value* jsonForLastRow = ModelBase::getField(val, "LastRow");
if(jsonForLastRow != nullptr && !jsonForLastRow->is_null())
{
setLastRow(ModelBase::boolFromJson(*jsonForLastRow));
}
web::json::value* jsonForRightToLeft = ModelBase::getField(val, "RightToLeft");
if(jsonForRightToLeft != nullptr && !jsonForRightToLeft->is_null())
{
setRightToLeft(ModelBase::boolFromJson(*jsonForRightToLeft));
}
web::json::value* jsonForVerticalBanding = ModelBase::getField(val, "VerticalBanding");
if(jsonForVerticalBanding != nullptr && !jsonForVerticalBanding->is_null())
{
setVerticalBanding(ModelBase::boolFromJson(*jsonForVerticalBanding));
}
}
}
}
| 23.010582 | 119 | 0.697172 | [
"vector",
"model"
] |
b947af7a64d1e14ce544c31ede5ddc69cfe8f1e4 | 5,660 | hpp | C++ | autocovariance/boost/accumulators/statistics/acvf_analysis.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | autocovariance/boost/accumulators/statistics/acvf_analysis.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | autocovariance/boost/accumulators/statistics/acvf_analysis.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// acvf_analysis.hpp //
// //
// Copyright 2008 Erwann Rogard. Distributed under the Boost //
// Software License, Version 1.0. (See accompanying file //
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //
///////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_ACCUMULATORS_STATISTICS_ACVF_ANALYSIS_HPP_ER_2008_04
#define BOOST_ACCUMULATORS_STATISTICS_ACVF_ANALYSIS_HPP_ER_2008_04
#include <iostream>
#include <algorithm>
#include <iterator>
#include <functional>
#include <stdexcept>
//#include <boost/assert.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/parameter/parameters.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/bind.hpp>
#include <boost/range.hpp>
#include <boost/ref.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/delay.hpp>
#include <boost/accumulators/statistics/acvf_moving_average.hpp>
#include <boost/accumulators/statistics/acvf.hpp>
#include <boost/accumulators/statistics/acf.hpp>
#include <boost/accumulators/statistics/percentage_effective_sample_size.hpp>
#include <boost/accumulators/statistics/standard_error_autocorrelated.hpp>
#include <boost/accumulators/statistics/standard_error_iid.hpp>
namespace boost{namespace accumulators{
namespace statistics{
template<
typename RealType,
typename I = default_delay_discriminator
>
class acvf_analysis{
typedef I discr_t;
public:
typedef RealType value_type;
private:
typedef boost::accumulators::accumulator_set<
value_type, boost::accumulators::stats<
boost::accumulators::tag::mean,
boost::accumulators::tag::acf<discr_t>,
boost::accumulators::tag::integrated_acvf<discr_t>,
boost::accumulators::tag::percentage_effective_sample_size<
discr_t>,
boost::accumulators::tag::standard_error_autocorrelated<discr_t>,
boost::accumulators::tag::standard_error_iid<discr_t>
>
> acc_type;
public://TODO define copy and assign
acvf_analysis(std::size_t max_lag)
:K(max_lag),
acc(boost::accumulators::tag::delay<discr_t>::cache_size=(K+1)){};
void operator()(value_type x){
return acc(x);
}
template<typename R>
void operator()(
const R& range,
std::size_t offset,
std::size_t stride){
// an iterator range?
typedef typename range_iterator<const R>::type const_iter_type;
typedef typename range_size<R>::type size_type;
const_iter_type i = boost::begin(range);
const_iter_type e = boost::end(range);
if(std::distance(i,e)>offset){
std::advance(i,offset);
//this has the effect of rounding to smallest
std::size_t d = (std::distance(i,e)-1)/stride;
d *= stride;
e = i; std::advance(e,d+1);
while(i<e){
acc(*i);
std::advance(i,stride);
}
// for_each(
// boost::begin(range),
// boost::end(range),
// boost::bind<void>(boost::ref(acc),_1)
// );
}else{
std::runtime_error("acvf_analysis");
}
}
std::size_t max_lag()const{ return K; }
value_type mean()const{ return accumulators::mean(acc); }
value_type standard_error_iid()const{
return accumulators::standard_error_iid<discr_t>(acc);
}
value_type standard_error_autocorrelated()const{
return accumulators
::standard_error_autocorrelated<discr_t>(acc);
}
value_type integrated_acvf()const{
return accumulators
::integrated_acvf<discr_t>(acc);
}
value_type percentage_effective_sample_size()const{
return accumulators
::percentage_effective_sample_size<discr_t>(acc);
}
void print(std::ostream& os)const
{
//using namespace boost::accumulators;
os << "count : " << accumulators::count(acc)
<< "\nacf : ";
copy(
begin(accumulators::acf<discr_t>(acc)),
end(accumulators::acf<discr_t>(acc)),
std::ostream_iterator<value_type>(os," ")
);
os << "\nintegrated_acvf : "
<< integrated_acvf()
<< "\ness% : "
<< percentage_effective_sample_size()
<< "\nmean : " << mean()
<< "\nstandard error : "
<< "\n assuming iid : "
<< standard_error_iid()
<< "\n assuming acf is zero after lag "
<< max_lag() << ": "
<< standard_error_autocorrelated() << std::endl;
};
private:
std::size_t K;
acc_type acc;
};
//TODO
// std::ostream& operator<<(std::ostream& os,const acvf_analysis& a){
// a.print(os);
// return os;
// };
}
}}
#endif
| 35.822785 | 79 | 0.549823 | [
"vector"
] |
b948fb4ed6042ed626efb372f1d6d628f8e1dffd | 616 | hpp | C++ | Iterator/Aggregate.hpp | Yescafe/pattern_demo | b87d8d588683773cd37efff0e9e12fc70b13f187 | [
"MIT"
] | 1 | 2020-07-11T04:36:14.000Z | 2020-07-11T04:36:14.000Z | Iterator/Aggregate.hpp | Yescafe/pattern_demo | b87d8d588683773cd37efff0e9e12fc70b13f187 | [
"MIT"
] | null | null | null | Iterator/Aggregate.hpp | Yescafe/pattern_demo | b87d8d588683773cd37efff0e9e12fc70b13f187 | [
"MIT"
] | null | null | null | #ifndef _AGGREGATE_HPP_
#define _AGGREGATE_HPP_
#include <cstddef>
class Iterator;
using Object = int;
class Interator;
class Aggregate {
public:
virtual ~Aggregate();
virtual Iterator* CreateIterator() = 0;
virtual Object GetItem(int idx) = 0;
virtual int GetSize() = 0;
protected:
Aggregate();
};
class ConcreteAggregate : public Aggregate {
public:
ConcreteAggregate();
~ConcreteAggregate();
Iterator* CreateIterator();
Object GetItem(int idx);
int GetSize();
private:
constexpr static std::size_t SIZE = 3u;
Object objs[SIZE];
};
#endif /* _AGGREGATE_HPP_ */
| 19.25 | 44 | 0.689935 | [
"object"
] |
b95a4e53179961ae20fb2bb47dc73edb8a4baf60 | 1,458 | cpp | C++ | BashuOJ-Code/2223.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/2223.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/2223.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#define ri register int
#define ll long long
using namespace std;
struct heap{
bool map[5][5];
int step;
};
bool S[5][5],T[5][5],H[65540];
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};
int tid;
inline int Hash(bool t[5][5])
{
int id=0,Base=1;
for(ri i=1;i<=4;i++)
for(ri j=1;j<=4;j++)
id+=t[i][j]*Base,Base<<=1;
return id;
}
void BFS()
{
queue<heap>q;
heap tmp;
for(ri i=1;i<=4;i++)
for(ri j=1;j<=4;j++)tmp.map[i][j]=S[i][j];
tmp.step=0;
q.push(tmp);
while(!q.empty())
{
heap now=q.front();q.pop();
if(Hash(now.map)==tid)
{
printf("%d\n",now.step);
break;
}
for(ri i=1;i<=4;i++)
for(ri j=1;j<=4;j++)
{
if(!now.map[i][j])continue;
for(ri k=0;k<4;k++)
{
int nx=i+dx[k],ny=j+dy[k];
if(nx>=1&&nx<=4&&ny>=1&&ny<=4&&!now.map[nx][ny])
{
heap next=now;
next.map[i][j]=0;
next.map[nx][ny]=1;
next.step++;
if(!H[Hash(next.map)])
q.push(next),H[Hash(next.map)]=1;
}
}
}
}
}
int main()
{
char ch;
for(ri i=1;i<=4;i++)
for(ri j=1;j<=4;j++)
{
while(ch=getchar())
if(ch=='0'||ch=='1')break;
S[i][j]=ch-'0';
}
H[Hash(S)]=1;
for(ri i=1;i<=4;i++)
for(ri j=1;j<=4;j++)
{
while(ch=getchar())
if(ch=='0'||ch=='1')break;
T[i][j]=ch-'0';
}
tid=Hash(T);
BFS();
return 0;
}
| 16.758621 | 53 | 0.516461 | [
"vector"
] |
b95a7a6e895451e0b1534846b6ae4461e2cbce48 | 33,772 | hpp | C++ | include/ax_list.hpp | axia-sw/axlib | ddf0857dfa597ab49ccfc6d578953ad2a0ffcf2a | [
"Unlicense"
] | 3 | 2017-07-06T22:17:27.000Z | 2020-11-25T00:06:25.000Z | include/ax_list.hpp | axia-sw/axlib | ddf0857dfa597ab49ccfc6d578953ad2a0ffcf2a | [
"Unlicense"
] | null | null | null | include/ax_list.hpp | axia-sw/axlib | ddf0857dfa597ab49ccfc6d578953ad2a0ffcf2a | [
"Unlicense"
] | null | null | null | /*
ax_list - public domain
last update: 2015-10-01 Aaron Miller
This library provides a typical linked list and an intrusively linked list.
INTERACTIONS
============
This library will use ax_platform definitions if they are available. To use
them include ax_platform.h before including this header.
This library will use ax_types if it has been included prior to this header.
LICENSE
=======
This software is in the public domain. Where that dedication is not
recognized, you are granted a perpetual, irrevocable license to copy
and modify this file as you see fit. There are no warranties of any
kind.
*/
#ifndef INCGUARD_AX_LIST_HPP_
#define INCGUARD_AX_LIST_HPP_
#ifndef AX_NO_PRAGMA_ONCE
# pragma once
#endif
#if !defined( AX_NO_INCLUDES ) && defined( __has_include )
# if __has_include( "ax_platform.h" )
# include "ax_platform.h"
# endif
# if __has_include( "ax_types.h" )
# include "ax_types.h"
# endif
#endif
#ifdef AX_TYPES_DEFINED
typedef ax_uptr_t axls_size_t;
#else
# include <stddef.h>
typedef size_t axls_size_t;
#endif
#ifndef axls_alloc
# include <stdlib.h>
# define axls_alloc(N_) (malloc((N_)))
# define axls_free(P_) (free((P_)))
#endif
#ifndef AXLS_CONSTEXPR_ENABLED
# if defined( AX_CXX_N2235 )
# if AX_CXX_N2235
# define AXLS_CONSTEXPR_ENABLED 1
# else
# define AXLS_CONSTEXPR_ENABLED 0
# endif
# elif defined( __has_feature )
# if __has_feature( cxx_constexpr )
# define AXLS_CONSTEXPR_ENABLED 1
# else
# define AXLS_CONSTEXPR_ENABLED 0
# endif
# elif defined( _MSC_VER ) && _MSC_VER >= 1900
# define AXLS_CONSTEXPR_ENABLED 1
# elif defined( __GNUC__ ) && ( __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 ) )
# define AXLS_CONSTEXPR_ENABLED 1
# elif defined( __clang__ ) && ( __clang__ > 3 || ( __clang__ == 3 && __clang_minor__ >= 1 ) )
# define AXLS_CONSTEXPR_ENABLED 1
# elif defined( __INTEL_COMPILER ) && __INTEL_COMPILER >= 1400
# define AXLS_CONSTEXPR_ENABLED 1
# else
# define AXLS_CONSTEXPR_ENABLED 0
# endif
#endif
#ifndef AXLS_CONSTEXPR
# if AXLS_CONSTEXPR_ENABLED
# define AXLS_CONSTEXPR constexpr
# else
# define AXLS_CONSTEXPR const
# endif
#endif
#ifndef AX_CONSTRUCT
# define AX_CONSTRUCT(X_)\
::new(reinterpret_cast<void*>(&(X_)),::ax::detail::SPlcmntNw())
namespace ax { namespace detail { struct SPlcmntNw {}; } }
inline void *operator new( axls_size_t, void *p, ax::detail::SPlcmntNw )
{
return p;
}
inline void operator delete( void *, void *, ax::detail::SPlcmntNw )
{
}
#endif
namespace ax
{
// Forward declarations
template< typename TElement >
class TIntrList;
template< typename TElement >
class TIntrLink;
namespace detail
{
template< typename TLink >
struct TListIter
{
typedef TLink LinkType;
typedef typename TLink::ElementType ElementType;
TLink *pLink;
inline TListIter(): pLink( NULL ) {}
inline TListIter( TLink &x ) : pLink( &x ) {}
inline TListIter( TLink *x ) : pLink( x ) {}
inline TListIter( const TLink &x ) : pLink( const_cast< TLink * >( &x ) ) {}
inline TListIter( const TLink *x ) : pLink( const_cast< TLink * >( x ) ) {}
inline TListIter( const TListIter &iter ) : pLink( iter.pLink ) {}
inline ~TListIter() {}
inline ElementType *get() { return pLink != NULL ? pLink->node() : NULL; }
inline const ElementType *get() const { return pLink != NULL ? pLink->node() : NULL; }
inline TListIter &operator=( const TListIter &iter ) { pLink = iter.pLink; return *this; }
inline bool operator!() const { return !pLink || !pLink->node(); }
inline bool operator==( const TListIter &iter ) const { return pLink == iter.pLink; }
inline bool operator!=( const TListIter &iter ) const { return pLink != iter.pLink; }
inline operator ElementType *( ) { return pLink->node(); }
inline operator const ElementType *( ) const { return pLink->node(); }
inline operator bool() const { return get() != NULL; }
inline ElementType &operator*() { return *pLink->node(); }
inline ElementType *operator->() { return pLink->node(); }
inline const ElementType &operator*() const { return *pLink->node(); }
inline const ElementType *operator->() const { return pLink->node(); }
inline TListIter &retreat() { pLink = pLink != NULL ? pLink->prevLink() : NULL; return *this; }
inline TListIter &advance() { pLink = pLink != NULL ? pLink->nextLink() : NULL; return *this; }
inline TListIter &operator--() { return retreat(); }
inline TListIter &operator++() { return advance(); }
inline TListIter operator--( int ) const { return TListIter( const_cast< TLink * >( pLink ) ).retreat(); }
inline TListIter operator++( int ) const { return TListIter( const_cast< TLink * >( pLink ) ).advance(); }
};
}
namespace policy
{
template< typename TElement >
struct ListIndexing
{
typedef axls_size_t SizeType;
};
template< typename TElement >
struct ListAllocator
{
typedef axls_size_t AllocSizeType;
inline void *allocate( AllocSizeType cBytes )
{
return axls_alloc( cBytes );
}
inline void deallocate( void *pBytes, AllocSizeType cBytes )
{
( ( void )cBytes );
axls_free( pBytes );
}
};
}
template< typename TElement >
struct ListPolicies
{
typedef TElement Type;
typedef policy::ListIndexing<Type> Indexing;
typedef policy::ListAllocator<Type> Allocator;
typedef typename Indexing::SizeType SizeType;
typedef typename Allocator::AllocSizeType AllocSizeType;
};
// A link within a list -- meant to be used as a member of whatever object owns it
template< typename TElement >
class TIntrLink
{
friend class TIntrList< TElement >;
public:
typedef TElement ElementType;
typedef TIntrList< TElement > ListType;
// Default constructor
TIntrLink();
// Construct with a given owner
TIntrLink( TElement *pNode );
// Construct with a given owner, added to the end of a list
TIntrLink( TElement *pNode, TIntrList< TElement > &list );
// Destructor -- unlinks from list
~TIntrLink();
// remove self from whatever list we're in
void unlink();
// Unlink from current list and insert before the given link
void insertBefore( TIntrLink &link );
// Unlink from current list and insert after the given link
void insertAfter( TIntrLink &link );
// Move this link to the front of the list it's within
void toFront();
// Move this link to the back of the list it's within
void toBack();
// Move this link to before the link immediately before this one
void toPrior();
// Move this link to after the link immediately after this one
void toNext();
// Retrieve the previous sibling link
inline TIntrLink *prevLink() { return m_pPrev; }
// Retrieve the previous sibling link [const]
inline const TIntrLink *prevLink() const { return m_pPrev; }
// Retrieve the next sibling link
inline TIntrLink *nextLink() { return m_pNext; }
// Retrieve the next sibling link [const]
inline const TIntrLink *nextLink() const { return m_pNext; }
// Retrieve the owner of the sibling link prior to this
inline TElement *prev() { return m_pPrev != NULL ? m_pPrev->m_pNode : NULL; }
// Retrieve the owner of the sibling link prior to this [const]
inline const TElement *prev() const { return m_pPrev != NULL ? m_pPrev->m_pNode : NULL; }
// Retrieve the owner of the sibling link after this
inline TElement *next() { return m_pNext != NULL ? m_pNext->m_pNode : NULL; }
// Retrieve the owner of the sibling link after this [const]
inline const TElement *next() const { return m_pNext != NULL ? m_pNext->m_pNode : NULL; }
// Set the owner of this link
inline void setNode( TElement *pNode ) { m_pNode = pNode; }
// Retrieve the owner of this link
inline TElement *node() { return m_pNode; }
// Retrieve the owner of this link [const]
inline const TElement *node() const { return m_pNode; }
// Retrieve the owner of this link
inline TElement &operator *() { return *m_pNode; }
// Retrieve the owner of this link [const]
inline const TElement &operator *() const { return *m_pNode; }
// Dereference the owner of this link
inline TElement *operator->() { return m_pNode; }
// Dereference the owner of this link [const]
inline const TElement *operator->() const { return m_pNode; }
// Retrieve the list this link is a part of
inline TIntrList< TElement > *list() { return m_pList; }
// Retrieve the list this link is a part of [const]
inline const TIntrList< TElement > *list() const { return m_pList; }
// Determine whether an owner is set
inline operator bool() const { return m_pNode != NULL; }
// Retrieve the owner of this link (through casting)
inline operator TElement *() { return m_pNode; }
// Retrieve the owner of this link (through casting)
inline operator const TElement *() const { return m_pNode; }
protected:
// Prior sibling link
TIntrLink< TElement > *m_pPrev;
// next sibling link
TIntrLink< TElement > *m_pNext;
// List this link resides within
TIntrList< TElement > *m_pList;
// Current owner node
TElement *m_pNode;
private:
#ifdef AX_DELETE_COPYFUNCS
AX_DELETE_COPYFUNCS( TIntrLink );
#endif
};
// A list of intrusive links -- does not do any allocations
template< typename TElement >
class TIntrList
{
public:
typedef TElement ElementType;
typedef TIntrLink< TElement > LinkType;
typedef detail::TListIter< TIntrLink< TElement > > Iterator;
typedef int( *FnComparator )( const TElement &, const TElement & );
static inline int operatorLessComparator_f( const TElement &a, const TElement &b )
{
return +( a < b );
}
// Default constructor
TIntrList();
// Destructor -- unlinks all items in the list
~TIntrList();
// Unlinks the given link from this list (debug mode checks that the link is in this list)
void unlink( TIntrLink< TElement > &link );
// Unlink all items in this list
void clear();
// Unlink all items in this list, deleting the owner nodes
void deleteAll();
// Determine whether this list has no links in it
bool isEmpty() const;
// Determine whether this list has any links in it
bool isUsed() const;
// Count how many links are in this list (this value is not cached)
axls_size_t num() const;
// Add a link to the front of this list after unlinking it from whatever list it was in before
void addHead( TIntrLink< TElement > &link );
// Add a link to the back of this list after unlinking it from whatever list it was in before
void addTail( TIntrLink< TElement > &link );
// Insert 'link' before 'before' (debug mode checks that 'before' is part of this list) after unlinking 'link' from whatever list it was in before
void insertBefore( TIntrLink< TElement > &link, TIntrLink< TElement > &before );
// Insert 'link' after 'after' (debug mode checks that 'after' is part of this list) after unlinking 'link' from whatever list it was in before
void insertAfter( TIntrLink< TElement > &link, TIntrLink< TElement > &after );
// Sort the items in this list with the given comparison function
void sort( FnComparator pfnCompare );
// Sort the items in this list with ElementType::operator<() comparison
inline void sort() { sort( &operatorLessComparator_f ); }
// Retrieve the link at the front of this list
inline TIntrLink< TElement > *headLink() { return m_pHead; }
// Retrieve the link at the front of this list [const]
inline const TIntrLink< TElement > *headLink() const { return m_pHead; }
// Retrieve the link at the back of this list
inline TIntrLink< TElement > *tailLink() { return m_pTail; }
// Retrieve the link at the back of this list [const]
inline const TIntrLink< TElement > *tailLink() const { return m_pTail; }
// Retrieve the owner of the link at the front of this list
inline TElement *head() { return m_pHead != NULL ? m_pHead->m_pNode : NULL; }
// Retrieve the owner of the link at the front of this list [const]
inline const TElement *head() const { return m_pHead != NULL ? m_pHead->m_pNode : NULL; }
// Retrieve the owner of the link at the back of this list
inline TElement *tail() { return m_pTail != NULL ? m_pTail->m_pNode : NULL; }
// Retrieve the owner of the link at the back of this list [const]
inline const TElement *tail() const { return m_pTail != NULL ? m_pTail->m_pNode : NULL; }
// Determine whether this list has any items in it
inline operator bool() const { return isUsed(); }
// Determine whether this list has no items in it
inline bool operator!() const { return isEmpty(); }
// C++ range-for begin()
inline Iterator begin() const { return Iterator( const_cast< TIntrLink< TElement > * >( m_pHead ) ); }
// C++ range-for end()
inline Iterator end() const { return Iterator(); }
private:
// Link to the front of the list
TIntrLink< TElement > *m_pHead;
// Link to the back of the list
TIntrLink< TElement > *m_pTail;
#ifdef AX_DELETE_COPYFUNCS
AX_DELETE_COPYFUNCS( TIntrList );
#endif
};
template< typename TElement, typename TAllocator = typename ListPolicies<TElement>::Allocator >
class TList: private TAllocator
{
public:
typedef ListPolicies<TElement> Policies;
typedef typename Policies::Type Type;
typedef typename Policies::SizeType SizeType;
typedef typename Policies::AllocSizeType AllocSizeType;
typedef typename TIntrList< Type >::FnComparator FnComparator;
typedef detail::TListIter< TIntrLink< Type > > Iterator;
typedef detail::TListIter< TIntrLink< Type > > ConstIterator;
TList();
TList( const TList &ls );
template< typename TOtherAllocator >
TList( const TList< TElement, TOtherAllocator > &ls );
template< SizeType tLen >
inline TList( const Type( &arr )[ tLen ] )
: m_list()
{
for( SizeType i = 0; i < tLen; ++i ) {
addTail( arr[ i ] );
}
}
TList( SizeType cItems, Type *pItems );
~TList();
inline TList &operator=( const TList &ls )
{
if( this == &ls ) {
return *this;
}
clear();
for( ConstIterator x = ls.begin(); x != ls.end(); ++x ) {
addTail( x );
}
return *this;
}
template< typename TOtherAllocator >
inline TList &operator=( const TList< Type, TOtherAllocator >&ls )
{
clear();
for( typename TList< Type, TOtherAllocator >::ConstIterator x = ls.begin(); x != ls.end(); ++x ) {
addTail( x );
}
return *this;
}
template< SizeType tLen >
inline TList &operator=( const Type( &arr )[ tLen ] )
{
clear();
for( SizeType i = 0; i < tLen; ++i ) {
addTail( arr[ i ] );
}
return *this;
}
void clear();
bool isEmpty() const;
bool isUsed() const;
SizeType num() const;
SizeType len() const;
AllocSizeType memSize() const;
// For C++ range-based for-loops
inline Iterator begin() { return Iterator( m_list.headLink() ); }
inline Iterator end() { return Iterator(); }
inline ConstIterator begin() const { return ConstIterator( m_list.headLink() ); }
inline ConstIterator end() const { return ConstIterator(); }
inline Iterator first() { return Iterator( m_list.headLink() ); }
inline Iterator last() { return Iterator( m_list.tailLink() ); }
inline ConstIterator first() const { return ConstIterator( m_list.headLink() ); }
inline ConstIterator last() const { return ConstIterator( m_list.tailLink() ); }
Iterator addHead();
Iterator addTail();
Iterator insertBefore( Iterator x );
Iterator insertAfter( Iterator x );
Iterator addHead( const Type &element );
Iterator addTail( const Type &element );
Iterator insertBefore( Iterator x, const Type &element );
Iterator insertAfter( Iterator x, const Type &element );
ConstIterator find_const( const Type &item ) const;
inline ConstIterator find( const Type &item ) const { return find_const( item ); }
inline Iterator find( const Type &item ) { return find_const( item ); }
Iterator remove( Iterator iter );
inline Iterator removeLast() { return remove( last() ); }
void sort( FnComparator pfnCompare );
void sort();
private:
typedef TIntrList< Type > IntrList;
typedef TIntrLink< Type > IntrLink;
IntrList m_list;
IntrLink *alloc_();
IntrLink *alloc_( const Type &x );
void dealloc_( IntrLink *ptr );
};
namespace detail
{
template< axls_size_t tElementSize, unsigned tNumElements, typename TOtherAllocator >
class TSmallListAllocator: private TOtherAllocator
{
public:
#ifdef AX_HAS_STATIC_ASSERT
# if AX_HAS_STATIC_ASSERT
static_assert( tNumElements > 0, "Too few elements for small list allocator" );
# endif
#endif
TSmallListAllocator()
: TOtherAllocator()
, m_pFreeObj( ( SMemoryObject * )0 )
{
SMemoryObject *pPrev = ( SMemoryObject * )0;
for( unsigned i = 0; i < tNumElements; ++i ) {
m_objects[ i ].data.pNext = pPrev;
pPrev = &m_objects[ i ];
}
m_pFreeObj = &m_objects[ tNumElements - 1 ];
}
~TSmallListAllocator()
{
}
void *allocate( axls_size_t n )
{
if( !n ) {
return ( void * )0;
}
if( n <= sizeof( SMemoryObject ) && m_pFreeObj != ( SMemoryObject * )0 ) {
SMemoryObject *const p = m_pFreeObj;
m_pFreeObj = m_pFreeObj->data.pNext;
return &p->data.bytes[ 0 ];
}
return TOtherAllocator::allocate( n );
}
void deallocate( void *p, axls_size_t n )
{
if( !p ) {
return;
}
if( n <= sizeof( SMemoryObject ) && isPointingToMemoryObject( p ) ) {
SMemoryObject *const pMemObj = reinterpret_cast< SMemoryObject * >( p );
pMemObj->data.pNext = m_pFreeObj;
m_pFreeObj = pMemObj;
return;
}
TOtherAllocator::deallocate( p, n );
}
private:
struct SMemoryObject
{
union
{
unsigned char bytes[ tElementSize ];
SMemoryObject *pNext;
} data;
};
SMemoryObject m_objects[ tNumElements ];
SMemoryObject *m_pFreeObj;
inline bool isPointingToMemoryObject( void *p ) const
{
return p >= &m_objects[0] && p <= &m_objects[ tNumElements ];
}
};
template< typename TElement, unsigned tNumElements, typename TOtherAllocator >
struct TSmallListAllocatorSelector
{
typedef TSmallListAllocator< sizeof( TElement ) + sizeof( TIntrLink< TElement > ), tNumElements, TOtherAllocator > Allocator;
};
template< typename TElement, unsigned tNumElements, typename TOtherAllocator >
struct TSmallListBase
{
typedef TList< TElement, typename TSmallListAllocatorSelector< TElement, tNumElements, TOtherAllocator >::Allocator > List;
};
}
template< typename TElement, unsigned tNumElements, typename TOtherAllocator = typename ListPolicies<TElement>::Allocator >
class TSmallList: public detail::TSmallListBase< TElement, tNumElements, TOtherAllocator >::List
{
public:
typedef typename detail::TSmallListBase< TElement, tNumElements, TOtherAllocator >::List ListBase;
typedef ListPolicies<TElement> Policies;
typedef typename Policies::Type Type;
typedef typename Policies::SizeType SizeType;
typedef typename Policies::AllocSizeType AllocSizeType;
typedef typename TIntrList< Type >::FnComparator FnComparator;
typedef detail::TListIter< TIntrLink< Type > > Iterator;
typedef detail::TListIter< TIntrLink< TElement > > ConstIterator;
TSmallList(): ListBase() {}
TSmallList( const TSmallList &ls ): ListBase( ls ) {}
template< typename TPassedAllocator >
TSmallList( const TList< TElement, TPassedAllocator > &ls ): ListBase( ls ) {}
template< SizeType tLen >
TSmallList( const Type( &arr )[ tLen ] ): ListBase( arr ) {}
TSmallList( SizeType cItems, Type *pItems ): ListBase( cItems, pItems ) {}
~TSmallList() {}
TSmallList &operator=( const ListBase &x )
{
ListBase::operator=( x );
return *this;
}
};
/*
===========================================================================
INTRUSIVE LINK
===========================================================================
*/
template< typename TElement >
TIntrLink< TElement >::TIntrLink()
: m_pPrev( NULL )
, m_pNext( NULL )
, m_pList( NULL )
, m_pNode( NULL )
{
}
template< typename TElement >
TIntrLink< TElement >::TIntrLink( TElement *pNode )
: m_pPrev( NULL )
, m_pNext( NULL )
, m_pList( NULL )
, m_pNode( pNode )
{
}
template< typename TElement >
TIntrLink< TElement >::TIntrLink( TElement *pNode, TIntrList< TElement > &list )
: m_pPrev( NULL )
, m_pNext( NULL )
, m_pList( NULL )
, m_pNode( pNode )
{
list.addTail( *this );
}
template< typename TElement >
TIntrLink< TElement >::~TIntrLink()
{
unlink();
}
template< typename TElement >
void TIntrLink< TElement >::unlink()
{
if( !m_pList ) {
return;
}
m_pList->unlink( *this );
}
template< typename TElement >
void TIntrLink< TElement >::insertBefore( TIntrLink &link )
{
if( !m_pList ) {
return;
}
m_pList->insertBefore( link, *this );
}
template< typename TElement >
void TIntrLink< TElement >::insertAfter( TIntrLink &link )
{
if( !m_pList ) {
return;
}
m_pList->insertAfter( link, *this );
}
template< typename TElement >
void TIntrLink< TElement >::toFront()
{
if( !m_pList ) {
return;
}
m_pList->addHead( *this );
}
template< typename TElement >
void TIntrLink< TElement >::toBack()
{
if( !m_pList ) {
return;
}
m_pList->addTail( *this );
}
template< typename TElement >
void TIntrLink< TElement >::toPrior()
{
if( !m_pList || !m_pPrev ) {
return;
}
m_pList->insertBefore( *this, *m_pPrev );
}
template< typename TElement >
void TIntrLink< TElement >::toNext()
{
if( !m_pList || !m_pNext ) {
return;
}
m_pList->insertAfter( *this, *m_pNext );
}
/*
===========================================================================
INTRUSIVE LIST
===========================================================================
*/
template< typename TElement >
TIntrList< TElement >::TIntrList()
: m_pHead( NULL )
, m_pTail( NULL )
{
}
template< typename TElement >
TIntrList< TElement >::~TIntrList()
{
clear();
}
template< typename TElement >
void TIntrList< TElement >::unlink( TIntrLink< TElement > &link )
{
if( link.m_pList != this ) {
return;
}
if( link.m_pPrev != NULL ) {
link.m_pPrev->m_pNext = link.m_pNext;
} else {
m_pHead = link.m_pNext;
}
if( link.m_pNext != NULL ) {
link.m_pNext->m_pPrev = link.m_pPrev;
} else {
m_pTail = link.m_pPrev;
}
link.m_pList = NULL;
link.m_pPrev = NULL;
link.m_pNext = NULL;
}
template< typename TElement >
void TIntrList< TElement >::clear()
{
while( m_pHead != NULL ) {
unlink( *m_pHead );
}
}
template< typename TElement >
void TIntrList< TElement >::deleteAll()
{
while( m_pHead != NULL ) {
TIntrLink< TElement > *link = m_pHead;
unlink( *link );
delete link->m_pNode;
}
}
template< typename TElement >
bool TIntrList< TElement >::isEmpty() const
{
return m_pHead == NULL;
}
template< typename TElement >
bool TIntrList< TElement >::isUsed() const
{
return m_pHead != NULL;
}
template< typename TElement >
axls_size_t TIntrList< TElement >::num() const
{
axls_size_t n = 0;
for( TIntrLink< TElement > *p = m_pHead; p != NULL; p = p->m_pNext ) {
++n;
}
return n;
}
template< typename TElement >
void TIntrList< TElement >::addHead( TIntrLink< TElement > &link )
{
if( &link == m_pHead ) {
return;
}
if( m_pHead != NULL ) {
insertBefore( link, *m_pHead );
return;
}
link.unlink();
m_pHead = &link;
m_pTail = &link;
link.m_pList = this;
}
template< typename TElement >
void TIntrList< TElement >::addTail( TIntrLink< TElement > &link )
{
if( &link == m_pTail ) {
return;
}
if( m_pTail != NULL ) {
insertAfter( link, *m_pTail );
return;
}
link.unlink();
m_pHead = &link;
m_pTail = &link;
link.m_pList = this;
}
template< typename TElement >
void TIntrList< TElement >::insertBefore( TIntrLink< TElement > &link, TIntrLink< TElement > &before )
{
link.unlink();
link.m_pPrev = before.m_pPrev;
if( before.m_pPrev != NULL ) {
before.m_pPrev->m_pNext = &link;
} else {
m_pHead = &link;
}
before.m_pPrev = &link;
link.m_pNext = &before;
link.m_pList = this;
}
template< typename TElement >
void TIntrList< TElement >::insertAfter( TIntrLink< TElement > &link, TIntrLink< TElement > &after )
{
link.unlink();
link.m_pNext = after.m_pNext;
if( after.m_pNext != NULL ) {
after.m_pNext->m_pPrev = &link;
} else {
m_pTail = &link;
}
after.m_pNext = &link;
link.m_pPrev = &after;
link.m_pList = this;
}
template< typename TElement >
void TIntrList< TElement >::sort( FnComparator pfnCompare )
{
TIntrLink< TElement > *pNode;
TIntrLink< TElement > *pTemp;
size_t cSwaps;
if( !pfnCompare ) {
return;
}
//
// TERRIBLE IMPLEMENTATION
// TODO: Use a better sorting algorithm
//
do {
cSwaps = 0;
for( pNode = m_pHead; pNode != NULL; pNode = pNode->m_pNext ) {
if( !pNode->m_pNode || !pNode->m_pNext || !pNode->m_pNext->m_pNode ) {
continue;
}
if( pfnCompare( *pNode->m_pNode, *pNode->m_pNext->m_pNode ) <= 0 ) {
continue;
}
pTemp = pNode->m_pNext;
pTemp->unlink();
pTemp->m_pList = this;
pTemp->m_pPrev = pNode != NULL ? pNode->m_pPrev : m_pTail;
pTemp->m_pNext = pNode;
if( pTemp->m_pPrev != NULL ) {
pTemp->m_pPrev->m_pNext = pTemp;
} else {
m_pHead = pTemp;
}
if( pNode != NULL ) {
pNode->m_pPrev = pTemp;
} else {
m_pTail = pTemp;
}
++cSwaps;
}
} while( cSwaps > 0 );
}
/*
===========================================================================
LIST
===========================================================================
*/
template< typename TElement, typename TAllocator >
TList< TElement, TAllocator >::TList()
: m_list()
{
}
template< typename TElement, typename TAllocator >
TList< TElement, TAllocator >::TList( const TList &ls )
: m_list()
{
for( Iterator x = ls.begin(); x != ls.end(); ++x ) {
addTail( *x );
}
}
template< typename TElement, typename TAllocator >
TList< TElement, TAllocator >::TList( SizeType cItems, Type *pItems )
: m_list()
{
if( !pItems ) {
return;
}
for( SizeType i = 0; i < cItems; ++i ) {
addTail( pItems[ i ] );
}
}
template< typename TElement, typename TAllocator >
TList< TElement, TAllocator >::~TList()
{
clear();
}
template< typename TElement, typename TAllocator >
void TList< TElement, TAllocator >::clear()
{
while( isUsed() ) {
remove( begin() );
}
}
template< typename TElement, typename TAllocator >
bool TList< TElement, TAllocator >::isEmpty() const
{
return m_list.isEmpty();
}
template< typename TElement, typename TAllocator >
bool TList< TElement, TAllocator >::isUsed() const
{
return m_list.isUsed();
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::SizeType TList< TElement, TAllocator >::num() const
{
return m_list.num();
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::SizeType TList< TElement, TAllocator >::len() const
{
return m_list.num();
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::AllocSizeType TList< TElement, TAllocator >::memSize() const
{
static AXLS_CONSTEXPR AllocSizeType kElementSize = sizeof( IntrLink ) + sizeof( Type );
return sizeof( *this ) + m_list.num()*kElementSize;
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::addHead()
{
IntrLink *const pItem = alloc_();
if( !pItem ) {
return end();
}
m_list.addHead( *pItem );
return Iterator( pItem );
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::addTail()
{
IntrLink *const pItem = alloc_();
if( !pItem ) {
return end();
}
m_list.addTail( *pItem );
return Iterator( pItem );
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::insertBefore( Iterator x )
{
if( !x ) {
return addTail();
}
IntrLink *const pItem = alloc_();
if( !pItem ) {
return end();
}
m_list.insertBefore( *pItem, *x.link );
return Iterator( pItem );
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::insertAfter( Iterator x )
{
if( !x ) {
return addTail();
}
IntrLink *const pItem = alloc_();
if( !pItem ) {
return end();
}
m_list.insertAfter( *pItem, *x.link );
return Iterator( pItem );
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::addHead( const Type &element )
{
IntrLink *const pItem = alloc_( element );
if( !pItem ) {
return end();
}
m_list.addHead( *pItem );
return Iterator( pItem );
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::addTail( const Type &element )
{
IntrLink *const pItem = alloc_( element );
if( !pItem ) {
return end();
}
m_list.addTail( *pItem );
return Iterator( pItem );
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::insertBefore( Iterator x, const Type &element )
{
if( !x ) {
return addTail( element );
}
IntrLink *const pItem = alloc_( element );
if( !pItem ) {
return end();
}
m_list.insertBefore( *pItem, *x.link );
return Iterator( pItem );
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::insertAfter( Iterator x, const Type &element )
{
if( !x ) {
return addTail( element );
}
IntrLink *const pItem = alloc_( element );
if( !pItem ) {
return end();
}
m_list.insertAfter( *pItem, *x.link );
return Iterator( pItem );
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::ConstIterator TList< TElement, TAllocator >::find_const( const Type &item ) const
{
const IntrLink *p;
for( p = m_list.headLink(); p != NULL; p = p->nextLink() ) {
if( *p->node() == item ) {
return ConstIterator( p );
}
}
return end();
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::Iterator TList< TElement, TAllocator >::remove( Iterator iter )
{
if( !iter ) {
return end();
}
Iterator next = Iterator( iter.pLink->nextLink() );
m_list.unlink( *iter.pLink );
dealloc_( iter.pLink );
return next;
}
template< typename TElement, typename TAllocator >
void TList< TElement, TAllocator >::sort( FnComparator pfnCompare )
{
m_list.sort( pfnCompare );
}
template< typename TElement, typename TAllocator >
void TList< TElement, TAllocator >::sort()
{
m_list.sort();
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::IntrLink *TList< TElement, TAllocator >::alloc_()
{
static AXLS_CONSTEXPR AllocSizeType kElementSize = sizeof( IntrLink ) + sizeof( Type );
char *const p = reinterpret_cast< char * >( TAllocator::allocate( kElementSize ) );
if( !p ) {
return NULL;
}
IntrLink *const a = ( IntrLink * )( p );
Type *const b = ( Type * )( p + sizeof( IntrLink ) );
AX_CONSTRUCT(*a) IntrLink( b );
AX_CONSTRUCT(*b) Type();
return a;
}
template< typename TElement, typename TAllocator >
typename TList< TElement, TAllocator >::IntrLink *TList< TElement, TAllocator >::alloc_( const Type &element )
{
static AXLS_CONSTEXPR AllocSizeType kElementSize = sizeof( IntrLink ) + sizeof( Type );
char *const p = reinterpret_cast< char * >( TAllocator::allocate( kElementSize ) );
if( !p ) {
return NULL;
}
IntrLink *const a = ( IntrLink * )( p );
Type *const b = ( Type * )( p + sizeof( IntrLink ) );
AX_CONSTRUCT(*a) IntrLink( b );
AX_CONSTRUCT(*b) Type( element );
return a;
}
template< typename TElement, typename TAllocator >
void TList< TElement, TAllocator >::dealloc_( IntrLink *ptr )
{
static AXLS_CONSTEXPR AllocSizeType kElementSize = sizeof( IntrLink ) + sizeof( Type );
if( !ptr ) {
return;
}
if( ptr->node() != NULL ) {
ptr->node()->~Type();
}
TAllocator::deallocate( reinterpret_cast< void * >( ptr ), kElementSize );
}
}
#endif
| 28.237458 | 149 | 0.638547 | [
"object"
] |
b95caab6958965c9ef337063c6811c60fc2b9a11 | 1,116 | hpp | C++ | Spades Game/Game/Net/GameServerManager.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 6 | 2017-01-04T22:40:50.000Z | 2019-11-24T15:37:46.000Z | Spades Game/Game/Net/GameServerManager.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 1 | 2016-09-18T19:10:01.000Z | 2017-08-04T23:53:38.000Z | Spades Game/Game/Net/GameServerManager.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 2 | 2015-11-21T16:42:18.000Z | 2019-04-21T20:41:39.000Z | #ifndef CGE_GAME_SERVER_MANAGER_HPP
#define CGE_GAME_SERVER_MANAGER_HPP
#include "Game/Net/ServerEntity.hpp"
#include <vector>
#include <map>
namespace cge
{
class GameServerManager
{
ServerEntitySetArray m_allocedEntities; // free ptrs
ServerEntitySetArray m_inactiveEntities;
ServerEntitySetArray m_activeEntities;
std::map<RakNet::RakNetGUID,ServerEntity*> m_entityMap;
void removeGuid(const RakNet::RakNetGUID& guid);
void assignGuid(const RakNet::RakNetGUID& guid,ServerEntity* entity);
public:
GameServerManager(void);
ServerEntity* createEntity(const RakNet::RakNetGUID& guid);
void destroyEntity(ServerEntity* entity);
void addToInactive(ServerEntity* entity);
void moveToInactive(ServerEntity* entity);
void moveToActive(ServerEntity* entity);
ServerEntitySetArray* getEntities(bool active);
ServerEntitySetArray* getAllocedEntities();
bool containsIP(const std::string& ip);
int getNumIPs(const std::string& ip);
ServerEntity* getEntity(const RakNet::RakNetGUID& guid);
bool guidExists(const RakNet::RakNetGUID& guid) const;
~GameServerManager(void);
};
}
#endif
| 32.823529 | 71 | 0.789427 | [
"vector"
] |
b95f083eb14d6343b67b92c7df9ff854b633e548 | 317 | cpp | C++ | 1_sort/InsertionSort.cpp | beyondan/algorithms | dedc9a58b28ecde4774a6f09ce7c1773219a716a | [
"MIT"
] | null | null | null | 1_sort/InsertionSort.cpp | beyondan/algorithms | dedc9a58b28ecde4774a6f09ce7c1773219a716a | [
"MIT"
] | null | null | null | 1_sort/InsertionSort.cpp | beyondan/algorithms | dedc9a58b28ecde4774a6f09ce7c1773219a716a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
void insertion_sort(vector<int> &a) {
int n = a.size();
for(int j=1; j<n; j++) {
int key = a[j];
int i = j-1;
while(i >= 0 && a[i] > key) {
a[i+1] = a[i];
--i;
}
a[i+1] = key;
}
}
| 17.611111 | 37 | 0.413249 | [
"vector"
] |
b961e6d0961d4bab70b58341cd156402dbcce289 | 6,340 | hpp | C++ | cmdstan/stan/src/stan/lang/grammars/program_grammar_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | 1 | 2019-07-05T01:40:40.000Z | 2019-07-05T01:40:40.000Z | cmdstan/stan/src/stan/lang/grammars/program_grammar_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/src/stan/lang/grammars/program_grammar_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | 1 | 2018-08-28T12:09:08.000Z | 2018-08-28T12:09:08.000Z | #ifndef STAN_LANG_GRAMMARS_PROGRAM_GRAMMAR_DEF_HPP
#define STAN_LANG_GRAMMARS_PROGRAM_GRAMMAR_DEF_HPP
#include <stan/io/program_reader.hpp>
#include <stan/lang/ast.hpp>
#include <stan/lang/grammars/program_grammar.hpp>
#include <stan/lang/grammars/semantic_actions.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/spirit/home/support/iterators/line_pos_iterator.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iomanip>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
// hack to pass pair into macro below to adapt; in namespace to hide
struct DUMMY_STRUCT {
typedef std::pair<std::vector<stan::lang::var_decl>,
std::vector<stan::lang::statement> > type;
};
BOOST_FUSION_ADAPT_STRUCT(stan::lang::program,
(std::vector<stan::lang::function_decl_def>,
function_decl_defs_)
(std::vector<stan::lang::var_decl>, data_decl_)
(DUMMY_STRUCT::type, derived_data_decl_)
(std::vector<stan::lang::var_decl>, parameter_decl_)
(DUMMY_STRUCT::type, derived_decl_)
(stan::lang::statement, statement_)
(DUMMY_STRUCT::type, generated_decl_) )
namespace stan {
namespace lang {
template <typename Iterator>
program_grammar<Iterator>::program_grammar(const std::string& model_name,
const io::program_reader& reader,
bool allow_undefined)
: program_grammar::base_type(program_r),
model_name_(model_name),
reader_(reader),
var_map_(),
error_msgs_(),
expression_g(var_map_, error_msgs_),
var_decls_g(var_map_, error_msgs_),
statement_g(var_map_, error_msgs_),
functions_g(var_map_, error_msgs_, allow_undefined) {
using boost::spirit::qi::eps;
using boost::spirit::qi::lit;
using boost::spirit::qi::on_error;
using boost::spirit::qi::rethrow;
using boost::spirit::qi::_1;
using boost::spirit::qi::_2;
using boost::spirit::qi::_3;
using boost::spirit::qi::labels::_a;
// add model_name to var_map with special origin
var_map_.add(model_name, base_var_decl(),
scope(model_name_origin, true));
program_r.name("program");
program_r
%= -functions_g
> -data_var_decls_r
> -derived_data_var_decls_r
> -param_var_decls_r
> eps[add_params_var_f(boost::phoenix::ref(var_map_))]
> -derived_var_decls_r
> -model_r
> eps[remove_params_var_f(boost::phoenix::ref(var_map_))]
> -generated_var_decls_r;
model_r.name("model declaration (or perhaps an earlier block)");
model_r
%= lit("model")
> eps[set_var_scope_local_f(_a, model_name_origin)]
> statement_g(_a, false);
end_var_decls_r.name(
"one of the following:\n"
" a variable declaration, beginning with type,\n"
" (int, real, vector, row_vector, matrix, unit_vector,\n"
" simplex, ordered, positive_ordered,\n"
" corr_matrix, cov_matrix,\n"
" cholesky_corr, cholesky_cov\n"
" or '}' to close variable declarations");
end_var_decls_r %= lit('}');
end_var_decls_statements_r.name(
"one of the following:\n"
" a variable declaration, beginning with type\n"
" (int, real, vector, row_vector, matrix, unit_vector,\n"
" simplex, ordered, positive_ordered,\n"
" corr_matrix, cov_matrix,\n"
" cholesky_corr, cholesky_cov\n"
" or a <statement>\n"
" or '}' to close variable declarations and definitions");
end_var_decls_statements_r %= lit('}');
end_var_definitions_r.name("expected another statement or '}'"
" to close declarations");
end_var_definitions_r %= lit('}');
data_var_decls_r.name("data variable declarations");
data_var_decls_r
%= (lit("data")
> lit('{'))
> eps[set_var_scope_f(_a, data_origin)]
> var_decls_g(true, _a)
> end_var_decls_r;
derived_data_var_decls_r.name("transformed data block");
derived_data_var_decls_r
%= ((lit("transformed")
>> lit("data"))
> lit('{'))
> eps[set_var_scope_f(_a, transformed_data_origin)]
> var_decls_g(true, _a)
> ((statement_g(_a, false)
> *statement_g(_a, false)
> end_var_definitions_r)
| (*statement_g(_a, false)
> end_var_decls_statements_r));
param_var_decls_r.name("parameter variable declarations");
param_var_decls_r
%= (lit("parameters")
> lit('{'))
> eps[set_var_scope_f(_a, parameter_origin)]
> var_decls_g(true, _a)
> end_var_decls_r;
derived_var_decls_r.name("derived variable declarations");
derived_var_decls_r
%= (lit("transformed")
> lit("parameters")
> lit('{'))
> eps[set_var_scope_f(_a, transformed_parameter_origin)]
> var_decls_g(true, _a)
> *statement_g(_a, false)
> end_var_decls_statements_r;
generated_var_decls_r.name("generated variable declarations");
generated_var_decls_r
%= (lit("generated")
> lit("quantities")
> lit('{'))
> eps[set_var_scope_f(_a, derived_origin)]
> var_decls_g(true, _a)
> *statement_g(_a, false)
> end_var_decls_statements_r;
on_error<rethrow>(program_r,
program_error_f(_1, _2, _3,
boost::phoenix::ref(var_map_),
boost::phoenix::ref(error_msgs_),
boost::phoenix::ref(reader_)));
}
}
}
#endif
| 37.964072 | 80 | 0.567823 | [
"vector",
"model"
] |
b963cc69cc94a4d04d1410299cc299e5865c49c8 | 619 | cpp | C++ | test/SelectManyTest.cpp | CyberTailor/boolinq | 5eb90673fad36125d8c7dd49b16f9b897972f3db | [
"MIT"
] | null | null | null | test/SelectManyTest.cpp | CyberTailor/boolinq | 5eb90673fad36125d8c7dd49b16f9b897972f3db | [
"MIT"
] | null | null | null | test/SelectManyTest.cpp | CyberTailor/boolinq | 5eb90673fad36125d8c7dd49b16f9b897972f3db | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include <gtest/gtest.h>
#include "CommonTests.h"
#include <boolinq/boolinq.h>
using namespace boolinq;
TEST(SelectMany, AxA)
{
int src[] = {1,2,3};
int ans[] = {1,2,2,3,3,3};
auto rng = from(src);
auto dst = rng.selectMany([](int a){return repeat(a, a);});
CheckRangeEqArray(dst, ans);
}
TEST(SelectMany, OneTwoThree)
{
int src[] = {1,2,3};
int ans[] = {1,2,3,2,4,6,3,6,9};
auto rng = from(src);
auto dst = rng.selectMany([&src](int a){
return from(src).select([a](int v){return a*v;});
});
CheckRangeEqArray(dst, ans);
} | 18.757576 | 63 | 0.588045 | [
"vector"
] |
b9653348e8c409d2df0485db75ccf82b124cfc35 | 726 | hpp | C++ | src/HetrickCV.hpp | nickfeisst/hetrickcv | 7829b24e7af248b563052b13d0c6408c28a6db5d | [
"CC0-1.0"
] | null | null | null | src/HetrickCV.hpp | nickfeisst/hetrickcv | 7829b24e7af248b563052b13d0c6408c28a6db5d | [
"CC0-1.0"
] | null | null | null | src/HetrickCV.hpp | nickfeisst/hetrickcv | 7829b24e7af248b563052b13d0c6408c28a6db5d | [
"CC0-1.0"
] | null | null | null | #pragma once
#include "HetrickUtilities.hpp"
using namespace rack;
extern Plugin *pluginInstance;
extern Model *modelTwoToFour;
extern Model *modelAnalogToDigital;
extern Model *modelASR;
extern Model *modelBitshift;
extern Model *modelBlankPanel;
extern Model *modelBoolean3;
extern Model *modelComparator;
extern Model *modelContrast;
extern Model *modelCrackle;
extern Model *modelDelta;
extern Model *modelDigitalToAnalog;
extern Model *modelDust;
extern Model *modelExponent;
extern Model *modelFlipFlop;
extern Model *modelFlipPan;
extern Model *modelGateJunction;
extern Model *modelLogicCombine;
extern Model *modelRandomGates;
extern Model *modelRotator;
extern Model *modelScanner;
extern Model *modelWaveshape; | 24.2 | 35 | 0.825069 | [
"model"
] |
b9658837aaecb06d476887d1a4b191b592685f98 | 14,743 | cpp | C++ | chromium/third_party/WebKit/Source/core/paint/ThemePainter.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/third_party/WebKit/Source/core/paint/ThemePainter.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/third_party/WebKit/Source/core/paint/ThemePainter.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | /**
* This file is part of the theme implementation for form controls in WebCore.
*
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Computer, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "core/paint/ThemePainter.h"
#include "core/InputTypeNames.h"
#include "core/frame/FrameView.h"
#include "core/html/HTMLDataListElement.h"
#include "core/html/HTMLDataListOptionsCollection.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLOptionElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/layout/LayoutMeter.h"
#include "core/layout/LayoutTheme.h"
#include "core/layout/LayoutView.h"
#include "core/paint/MediaControlsPainter.h"
#include "core/paint/PaintInfo.h"
#include "core/style/ComputedStyle.h"
#include "platform/graphics/GraphicsContextStateSaver.h"
#include "public/platform/Platform.h"
#include "public/platform/WebFallbackThemeEngine.h"
#include "public/platform/WebRect.h"
#if USE(NEW_THEME)
#include "platform/Theme.h"
#endif
// The methods in this file are shared by all themes on every platform.
namespace blink {
static WebFallbackThemeEngine::State getWebFallbackThemeState(const LayoutObject& o)
{
if (!LayoutTheme::isEnabled(o))
return WebFallbackThemeEngine::StateDisabled;
if (LayoutTheme::isPressed(o))
return WebFallbackThemeEngine::StatePressed;
if (LayoutTheme::isHovered(o))
return WebFallbackThemeEngine::StateHover;
return WebFallbackThemeEngine::StateNormal;
}
bool ThemePainter::paint(const LayoutObject& o, const PaintInfo& paintInfo, const IntRect&r)
{
ControlPart part = o.styleRef().appearance();
if (LayoutTheme::theme().shouldUseFallbackTheme(o.styleRef()))
return paintUsingFallbackTheme(o, paintInfo, r);
#if USE(NEW_THEME)
switch (part) {
case CheckboxPart:
case RadioPart:
case PushButtonPart:
case SquareButtonPart:
case ButtonPart:
case InnerSpinButtonPart:
platformTheme()->paint(part, LayoutTheme::controlStatesForLayoutObject(o), const_cast<GraphicsContext&>(paintInfo.context), r, o.styleRef().effectiveZoom(), o.view()->frameView());
return false;
default:
break;
}
#endif
// Call the appropriate paint method based off the appearance value.
switch (part) {
#if !USE(NEW_THEME)
case CheckboxPart:
return paintCheckbox(o, paintInfo, r);
case RadioPart:
return paintRadio(o, paintInfo, r);
case PushButtonPart:
case SquareButtonPart:
case ButtonPart:
return paintButton(o, paintInfo, r);
case InnerSpinButtonPart:
return paintInnerSpinButton(o, paintInfo, r);
#endif
case MenulistPart:
return paintMenuList(o, paintInfo, r);
case MeterPart:
case RelevancyLevelIndicatorPart:
case ContinuousCapacityLevelIndicatorPart:
case DiscreteCapacityLevelIndicatorPart:
case RatingLevelIndicatorPart:
return paintMeter(o, paintInfo, r);
case ProgressBarPart:
return paintProgressBar(o, paintInfo, r);
case SliderHorizontalPart:
case SliderVerticalPart:
return paintSliderTrack(o, paintInfo, r);
case SliderThumbHorizontalPart:
case SliderThumbVerticalPart:
return paintSliderThumb(o, paintInfo, r);
case MediaEnterFullscreenButtonPart:
case MediaExitFullscreenButtonPart:
return MediaControlsPainter::paintMediaFullscreenButton(o, paintInfo, r);
case MediaPlayButtonPart:
return MediaControlsPainter::paintMediaPlayButton(o, paintInfo, r);
case MediaOverlayPlayButtonPart:
return MediaControlsPainter::paintMediaOverlayPlayButton(o, paintInfo, r);
case MediaMuteButtonPart:
return MediaControlsPainter::paintMediaMuteButton(o, paintInfo, r);
case MediaToggleClosedCaptionsButtonPart:
return MediaControlsPainter::paintMediaToggleClosedCaptionsButton(o, paintInfo, r);
case MediaSliderPart:
return MediaControlsPainter::paintMediaSlider(o, paintInfo, r);
case MediaSliderThumbPart:
return MediaControlsPainter::paintMediaSliderThumb(o, paintInfo, r);
case MediaVolumeSliderContainerPart:
return true;
case MediaVolumeSliderPart:
return MediaControlsPainter::paintMediaVolumeSlider(o, paintInfo, r);
case MediaVolumeSliderThumbPart:
return MediaControlsPainter::paintMediaVolumeSliderThumb(o, paintInfo, r);
case MediaFullScreenVolumeSliderPart:
case MediaFullScreenVolumeSliderThumbPart:
case MediaTimeRemainingPart:
case MediaCurrentTimePart:
case MediaControlsBackgroundPart:
return true;
case MediaCastOffButtonPart:
case MediaOverlayCastOffButtonPart:
return MediaControlsPainter::paintMediaCastButton(o, paintInfo, r);
case MenulistButtonPart:
case TextFieldPart:
case TextAreaPart:
return true;
case SearchFieldPart:
return paintSearchField(o, paintInfo, r);
case SearchFieldCancelButtonPart:
return paintSearchFieldCancelButton(o, paintInfo, r);
case SearchFieldDecorationPart:
return paintSearchFieldDecoration(o, paintInfo, r);
case SearchFieldResultsDecorationPart:
return paintSearchFieldResultsDecoration(o, paintInfo, r);
default:
break;
}
return true; // We don't support the appearance, so let the normal background/border paint.
}
bool ThemePainter::paintBorderOnly(const LayoutObject& o, const PaintInfo& paintInfo, const IntRect&r)
{
// Call the appropriate paint method based off the appearance value.
switch (o.styleRef().appearance()) {
case TextFieldPart:
return paintTextField(o, paintInfo, r);
case TextAreaPart:
return paintTextArea(o, paintInfo, r);
case MenulistButtonPart:
case SearchFieldPart:
case ListboxPart:
return true;
case CheckboxPart:
case RadioPart:
case PushButtonPart:
case SquareButtonPart:
case ButtonPart:
case MenulistPart:
case MeterPart:
case RelevancyLevelIndicatorPart:
case ContinuousCapacityLevelIndicatorPart:
case DiscreteCapacityLevelIndicatorPart:
case RatingLevelIndicatorPart:
case ProgressBarPart:
case SliderHorizontalPart:
case SliderVerticalPart:
case SliderThumbHorizontalPart:
case SliderThumbVerticalPart:
case SearchFieldCancelButtonPart:
case SearchFieldDecorationPart:
case SearchFieldResultsDecorationPart:
default:
break;
}
return false;
}
bool ThemePainter::paintDecorations(const LayoutObject& o, const PaintInfo& paintInfo, const IntRect&r)
{
// Call the appropriate paint method based off the appearance value.
switch (o.styleRef().appearance()) {
case MenulistButtonPart:
return paintMenuListButton(o, paintInfo, r);
case TextFieldPart:
case TextAreaPart:
case CheckboxPart:
case RadioPart:
case PushButtonPart:
case SquareButtonPart:
case ButtonPart:
case MenulistPart:
case MeterPart:
case RelevancyLevelIndicatorPart:
case ContinuousCapacityLevelIndicatorPart:
case DiscreteCapacityLevelIndicatorPart:
case RatingLevelIndicatorPart:
case ProgressBarPart:
case SliderHorizontalPart:
case SliderVerticalPart:
case SliderThumbHorizontalPart:
case SliderThumbVerticalPart:
case SearchFieldPart:
case SearchFieldCancelButtonPart:
case SearchFieldDecorationPart:
case SearchFieldResultsDecorationPart:
default:
break;
}
return false;
}
bool ThemePainter::paintMeter(const LayoutObject&, const PaintInfo&, const IntRect&)
{
return true;
}
void ThemePainter::paintSliderTicks(const LayoutObject& o, const PaintInfo& paintInfo, const IntRect&rect)
{
Node* node = o.node();
if (!isHTMLInputElement(node))
return;
HTMLInputElement* input = toHTMLInputElement(node);
if (input->type() != InputTypeNames::range || !input->userAgentShadowRoot()->hasChildren())
return;
HTMLDataListElement* dataList = input->dataList();
if (!dataList)
return;
double min = input->minimum();
double max = input->maximum();
ControlPart part = o.styleRef().appearance();
// We don't support ticks on alternate sliders like MediaVolumeSliders.
if (part != SliderHorizontalPart && part != SliderVerticalPart)
return;
bool isHorizontal = part == SliderHorizontalPart;
IntSize thumbSize;
LayoutObject* thumbLayoutObject = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb())->layoutObject();
if (thumbLayoutObject) {
const ComputedStyle& thumbStyle = thumbLayoutObject->styleRef();
int thumbWidth = thumbStyle.width().intValue();
int thumbHeight = thumbStyle.height().intValue();
thumbSize.setWidth(isHorizontal ? thumbWidth : thumbHeight);
thumbSize.setHeight(isHorizontal ? thumbHeight : thumbWidth);
}
IntSize tickSize = LayoutTheme::theme().sliderTickSize();
float zoomFactor = o.styleRef().effectiveZoom();
FloatRect tickRect;
int tickRegionSideMargin = 0;
int tickRegionWidth = 0;
IntRect trackBounds;
LayoutObject* trackLayoutObject = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack())->layoutObject();
// We can ignoring transforms because transform is handled by the graphics context.
if (trackLayoutObject)
trackBounds = trackLayoutObject->absoluteBoundingBoxRectIgnoringTransforms();
IntRect sliderBounds = o.absoluteBoundingBoxRectIgnoringTransforms();
// Make position relative to the transformed ancestor element.
trackBounds.setX(trackBounds.x() - sliderBounds.x() + rect.x());
trackBounds.setY(trackBounds.y() - sliderBounds.y() + rect.y());
if (isHorizontal) {
tickRect.setWidth(floor(tickSize.width() * zoomFactor));
tickRect.setHeight(floor(tickSize.height() * zoomFactor));
tickRect.setY(floor(rect.y() + rect.height() / 2.0 + LayoutTheme::theme().sliderTickOffsetFromTrackCenter() * zoomFactor));
tickRegionSideMargin = trackBounds.x() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0;
tickRegionWidth = trackBounds.width() - thumbSize.width();
} else {
tickRect.setWidth(floor(tickSize.height() * zoomFactor));
tickRect.setHeight(floor(tickSize.width() * zoomFactor));
tickRect.setX(floor(rect.x() + rect.width() / 2.0 + LayoutTheme::theme().sliderTickOffsetFromTrackCenter() * zoomFactor));
tickRegionSideMargin = trackBounds.y() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0;
tickRegionWidth = trackBounds.height() - thumbSize.width();
}
RefPtrWillBeRawPtr<HTMLDataListOptionsCollection> options = dataList->options();
for (unsigned i = 0; HTMLOptionElement* optionElement = options->item(i); i++) {
String value = optionElement->value();
if (!input->isValidValue(value))
continue;
double parsedValue = parseToDoubleForNumberType(input->sanitizeValue(value));
double tickFraction = (parsedValue - min) / (max - min);
double tickRatio = isHorizontal && o.styleRef().isLeftToRightDirection() ? tickFraction : 1.0 - tickFraction;
double tickPosition = round(tickRegionSideMargin + tickRegionWidth * tickRatio);
if (isHorizontal)
tickRect.setX(tickPosition);
else
tickRect.setY(tickPosition);
paintInfo.context.fillRect(tickRect, o.resolveColor(CSSPropertyColor));
}
}
bool ThemePainter::paintUsingFallbackTheme(const LayoutObject& o, const PaintInfo& i, const IntRect&r)
{
ControlPart part = o.styleRef().appearance();
switch (part) {
case CheckboxPart:
return paintCheckboxUsingFallbackTheme(o, i, r);
case RadioPart:
return paintRadioUsingFallbackTheme(o, i, r);
default:
break;
}
return true;
}
bool ThemePainter::paintCheckboxUsingFallbackTheme(const LayoutObject& o, const PaintInfo& i, const IntRect&r)
{
WebFallbackThemeEngine::ExtraParams extraParams;
WebCanvas* canvas = i.context.canvas();
extraParams.button.checked = LayoutTheme::isChecked(o);
extraParams.button.indeterminate = LayoutTheme::isIndeterminate(o);
float zoomLevel = o.styleRef().effectiveZoom();
GraphicsContextStateSaver stateSaver(i.context);
IntRect unzoomedRect = r;
if (zoomLevel != 1) {
unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
i.context.translate(unzoomedRect.x(), unzoomedRect.y());
i.context.scale(zoomLevel, zoomLevel);
i.context.translate(-unzoomedRect.x(), -unzoomedRect.y());
}
Platform::current()->fallbackThemeEngine()->paint(canvas, WebFallbackThemeEngine::PartCheckbox, getWebFallbackThemeState(o), WebRect(unzoomedRect), &extraParams);
return false;
}
bool ThemePainter::paintRadioUsingFallbackTheme(const LayoutObject& o, const PaintInfo& i, const IntRect&r)
{
WebFallbackThemeEngine::ExtraParams extraParams;
WebCanvas* canvas = i.context.canvas();
extraParams.button.checked = LayoutTheme::isChecked(o);
extraParams.button.indeterminate = LayoutTheme::isIndeterminate(o);
float zoomLevel = o.styleRef().effectiveZoom();
GraphicsContextStateSaver stateSaver(i.context);
IntRect unzoomedRect = r;
if (zoomLevel != 1) {
unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
i.context.translate(unzoomedRect.x(), unzoomedRect.y());
i.context.scale(zoomLevel, zoomLevel);
i.context.translate(-unzoomedRect.x(), -unzoomedRect.y());
}
Platform::current()->fallbackThemeEngine()->paint(canvas, WebFallbackThemeEngine::PartRadio, getWebFallbackThemeState(o), WebRect(unzoomedRect), &extraParams);
return false;
}
} // namespace blink
| 38.899736 | 188 | 0.724208 | [
"transform"
] |
b967bad4cce111003d660cd514d010ed969a8c73 | 4,061 | cpp | C++ | Development/Editor/Core/ydbase/base/warcraft3/jass/func_value.cpp | shawwwn/YDWE | b83ffe041d9623409d9ffd951988e2b482d9cfc3 | [
"Apache-2.0"
] | 2 | 2016-05-30T11:42:33.000Z | 2017-10-31T11:53:42.000Z | Development/Editor/Core/ydbase/base/warcraft3/jass/func_value.cpp | shawwwn/YDWE | b83ffe041d9623409d9ffd951988e2b482d9cfc3 | [
"Apache-2.0"
] | null | null | null | Development/Editor/Core/ydbase/base/warcraft3/jass/func_value.cpp | shawwwn/YDWE | b83ffe041d9623409d9ffd951988e2b482d9cfc3 | [
"Apache-2.0"
] | null | null | null | #include <base/warcraft3/jass/func_value.h>
#include <base/warcraft3/war3_searcher.h>
#include <base/warcraft3/hashtable.h>
#include <base/warcraft3/jass.h>
#include <map>
#include <string>
namespace base { namespace warcraft3 { namespace jass {
namespace detail {
#pragma pack(push)
#pragma pack(1)
struct asm_opcode_5
{
uint8_t opcode;
uint32_t value;
};
// push offset aRR ; "(R)R" 68 3C D9 95 6F
// mov edx, offset aDeg2rad ; "Deg2Rad" BA 34 D9 95 6F
// mov ecx, offset sub_6F3B3510 B9 10 35 3B 6F
// call sub_6F455C20 E8 A7 10 08 00
struct asm_register_native_function
{
private:
asm_opcode_5 Push;
asm_opcode_5 MovEdx;
asm_opcode_5 MovEcx;
asm_opcode_5 Call;
public:
bool verify() const
{
return ((Push.opcode == 0x68)
&& (MovEdx.opcode == 0xBA)
&& (MovEcx.opcode == 0xB9)
&& (Call.opcode == 0xE8));
}
const char* get_param() const
{
return (const char*)(Push.value);
}
const char* get_name() const
{
return (const char*)(MovEdx.value);
}
uintptr_t get_address() const
{
return (uintptr_t)(MovEcx.value);
}
};
#pragma pack(pop)
func_mapping initialize_mapping_from_register()
{
func_mapping m;
uintptr_t ptr_Deg2Rad = get_war3_searcher().search_string("Deg2Rad");
if (ptr_Deg2Rad)
{
for (asm_register_native_function* ptr = (asm_register_native_function*)(ptr_Deg2Rad - 6); ptr->verify(); ++ptr)
{
m.insert(std::make_pair(ptr->get_name(), func_value(ptr->get_param(), ptr->get_address())));
}
}
return std::move(m);
}
}
func_value::func_value()
: return_(TYPE_NONE)
, param_()
, address_(0)
{ }
func_value::func_value(const char* param, uintptr_t address)
: return_(TYPE_NONE)
, param_()
, address_(address)
{
if (!param || param[0] != '(')
{
return ;
}
const char* it = ++param;
bool is_end = false;
for (; *it; ++it)
{
if (*it == ')')
{
is_end = true;
}
else if (isupper(static_cast<unsigned char>(*it)))
{
if (is_end)
{
return_ = (variable_type)(*it);
break;
}
else
{
param_.push_back((variable_type)(*it));
}
}
}
}
func_value::func_value(func_value const& that, uintptr_t address)
: return_(that.return_)
, param_(that.param_)
, address_(address)
{ }
bool func_value::is_valid() const
{
return return_ != TYPE_NONE;
}
std::vector<variable_type> const& func_value::get_param() const
{
return param_;
}
variable_type const& func_value::get_return() const
{
return return_;
}
uintptr_t func_value::get_address() const
{
return address_;
}
uintptr_t func_value::call(uintptr_t param_list[]) const
{
return jass::call(address_, param_list, param_.size());
}
func_value const* jass_func(const char* proc_name)
{
static func_mapping m = detail::initialize_mapping_from_register();
if (!proc_name)
{
return nullptr;
}
auto it = m.find(proc_name);
if (it != m.end() && it->second.is_valid())
{
return &(it->second);
}
return nullptr;
}
func_mapping japi_function;
func_value const* japi_func(const char* proc_name)
{
if (!proc_name)
{
return nullptr;
}
auto it = japi_function.find(proc_name);
if (it != japi_function.end() && it->second.is_valid())
{
return &(it->second);
}
return nullptr;
}
bool japi_func_add(const char* proc_name, uintptr_t new_proc)
{
func_value const* nf = jass_func(proc_name);
if (!nf)
{
return false;
}
return japi_function.insert(std::make_pair(proc_name, func_value(*nf, new_proc))).second;
}
bool japi_func_add(const char* proc_name, uintptr_t new_proc, const char* param)
{
return japi_function.insert(std::make_pair(proc_name, func_value(param, new_proc))).second;
}
bool japi_func_remove(const char* proc_name)
{
auto it = japi_function.find(proc_name);
if (it != japi_function.end())
{
japi_function.erase(it);
return true;
}
return false;
}
}}}
| 19.430622 | 116 | 0.639498 | [
"vector"
] |
b96e41452a442037f60836fa699e11d43ba21e03 | 3,606 | cpp | C++ | base/base_tests/rolling_hash_test.cpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 1 | 2019-01-11T05:02:05.000Z | 2019-01-11T05:02:05.000Z | base/base_tests/rolling_hash_test.cpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 13 | 2015-09-28T13:59:23.000Z | 2015-10-08T20:12:45.000Z | base/base_tests/rolling_hash_test.cpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 1 | 2019-08-09T21:21:09.000Z | 2019-08-09T21:21:09.000Z | #include "testing/benchmark.hpp"
#include "testing/testing.hpp"
#include "base/rolling_hash.hpp"
#include "base/base.hpp"
#include "base/logging.hpp"
#include "base/macros.hpp"
namespace
{
template <class RollingHasherT> void SmokeTest1RollingHasher()
{
typedef typename RollingHasherT::hash_type hash_type;
RollingHasherT hash;
hash_type const h0 = hash.Init("a", 1);
TEST_EQUAL(h0, hash.Scroll('a', 'a'), (sizeof(hash_type)));
}
template <class RollingHasherT> void SmokeTest2RollingHasher()
{
typedef typename RollingHasherT::hash_type hash_type;
RollingHasherT hash;
hash_type const hAB = hash.Init("ab", 2);
hash_type const hBA = hash.Scroll('a', 'a');
hash_type const hAB1 = hash.Scroll('b', 'b');
TEST_EQUAL(hAB, hAB1, (sizeof(hash_type)));
hash_type const hBA1 = hash.Scroll('a', 'a');
TEST_EQUAL(hBA, hBA1, (sizeof(hash_type)));
}
template <class RollingHasherT> void TestRollingHasher()
{
SmokeTest1RollingHasher<RollingHasherT>();
SmokeTest2RollingHasher<RollingHasherT>();
// 01234567890123
char const s [] = "abcdefghaabcde";
size_t const len = ARRAY_SIZE(s) - 1;
for (uint32_t size = 1; size <= 6; ++size)
{
typedef typename RollingHasherT::hash_type hash_type;
RollingHasherT hash;
vector<hash_type> hashes;
hashes.push_back(hash.Init(static_cast<char const *>(s), size));
for (uint32_t i = size; i < len; ++i)
hashes.push_back(hash.Scroll(s[i - size], s[i]));
TEST_EQUAL(hashes.size(), len - size + 1, (size, len, sizeof(hash_type)));
switch (size)
{
case 6:
{
// Test that there are no collisions.
sort(hashes.begin(), hashes.end());
TEST(hashes.end() == unique(hashes.begin(), hashes.end()), (size, hashes));
}
break;
case 1:
{
TEST_EQUAL(hashes[0], hashes[8], (size, len, sizeof(hash_type)));
TEST_EQUAL(hashes[0], hashes[9], (size, len, sizeof(hash_type)));
TEST_EQUAL(hashes[1], hashes[10], (size, len, sizeof(hash_type)));
TEST_EQUAL(hashes[2], hashes[11], (size, len, sizeof(hash_type)));
TEST_EQUAL(hashes[3], hashes[12], (size, len, sizeof(hash_type)));
TEST_EQUAL(hashes[4], hashes[13], (size, len, sizeof(hash_type)));
}
break;
default:
{
for (unsigned int i = 0; i < 6 - size; ++i)
TEST_EQUAL(hashes[i], hashes[i + 9], (i, size, len, sizeof(hash_type)));
sort(hashes.begin(), hashes.end());
TEST((hashes.end() - (6 - size)) == unique(hashes.begin(), hashes.end()), (size, hashes));
}
}
}
}
}
UNIT_TEST(RabinKarpRollingHasher32)
{
TestRollingHasher<RabinKarpRollingHasher32>();
}
UNIT_TEST(RabinKarpRollingHasher64)
{
TestRollingHasher<RabinKarpRollingHasher64>();
}
UNIT_TEST(RollingHasher32)
{
TestRollingHasher<RollingHasher32>();
}
UNIT_TEST(RollingHasher64)
{
TestRollingHasher<RollingHasher64>();
}
#ifndef DEBUG
BENCHMARK_TEST(RollingHasher32)
{
RollingHasher32 hash;
hash.Init("abcdefghijklmnopq", 17);
BENCHMARK_N_TIMES(IF_DEBUG_ELSE(500000, 20000000), 0.2)
{
FORCE_USE_VALUE(hash.Scroll(static_cast<uint32_t>('a') + benchmark.Iteration(),
static_cast<uint32_t>('r') + benchmark.Iteration()));
}
}
BENCHMARK_TEST(RollingHasher64)
{
RollingHasher64 hash;
hash.Init("abcdefghijklmnopq", 17);
BENCHMARK_N_TIMES(IF_DEBUG_ELSE(500000, 10000000), 0.3)
{
FORCE_USE_VALUE(hash.Scroll(static_cast<uint64_t>('a') + benchmark.Iteration(),
static_cast<uint64_t>('r') + benchmark.Iteration()));
}
}
#endif
| 29.080645 | 98 | 0.655574 | [
"vector"
] |
b97b347c00b4548acea3a13f1830e4f6f853640d | 16,248 | hxx | C++ | main/ucbhelper/inc/ucbhelper/interceptedinteraction.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/ucbhelper/inc/ucbhelper/interceptedinteraction.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/ucbhelper/inc/ucbhelper/interceptedinteraction.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
#ifndef _UCBHELPER_INTERCEPTEDINTERACTION_HXX_
#define _UCBHELPER_INTERCEPTEDINTERACTION_HXX_
//_______________________________________________
// includes
#include <vector>
#ifndef __COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP__
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef __COM_SUN_STAR_TASK_XINTERACTIONREQUEST_HPP__
#include <com/sun/star/task/XInteractionRequest.hpp>
#endif
#include <cppuhelper/implbase1.hxx>
#include "ucbhelper/ucbhelperdllapi.h"
//_______________________________________________
// namespace
namespace ucbhelper{
//_______________________________________________
// definitions
/** @short it wraps any other interaction handler and intercept
its handle() requests.
@descr This class can be used as:
- instance if special interactions must be suppressed
only
- or as base class if interactions must be modified.
*/
class UCBHELPER_DLLPUBLIC InterceptedInteraction : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionHandler >
{
//-------------------------------------------
// types
public:
struct InterceptedRequest
{
//-----------------------------------
/** @short marks an Handle as invalid.
*/
static const sal_Int32 INVALID_HANDLE = -1;
//-----------------------------------
/** @short contains the interaction request, which should be intercepted. */
::com::sun::star::uno::Any Request;
//-----------------------------------
/** @short specify the fix continuation, which must be selected, if the
interaction could be intercepted successfully.
*/
::com::sun::star::uno::Type Continuation;
//-----------------------------------
/** @short specify, if both interactions must have the same type
or can be derived from.
@descr Interaction base on exceptions - and exceptions are real types.
So they can be checked in its type. These parameter "MatchExact"
influence the type-check in the following way:
TRUE => the exception will be intercepted only
if it supports exactly the same type ...
or
FALSE => derived exceptions will be intercepted too.
@attention This parameter does not influence the check of the continuation
type! The continuation must be matched exactly everytimes ...
*/
sal_Bool MatchExact;
//-----------------------------------
/** @short its an unique identifier, which must be managed by the outside code.
@descr If there is a derived class, which overwrites the InterceptedInteraction::intercepted()
method, it will be called with a reference to an InterceptedRequest struct.
Then it can use the handle to react without checking the request type again.
*/
sal_Int32 Handle;
//-----------------------------------
/** @short default ctor.
@descr Such constructed object can't be used really.
Might it will crash if its used!
Dont forget to initialize all(!) members ...
*/
InterceptedRequest()
{
MatchExact = sal_False;
Handle = INVALID_HANDLE;
}
//-----------------------------------
/** @short initialize this instance.
@param nHandle
used to identify every intercepted request
@param aRequest
must contain an exception object, which can be checked
in its uno-type against the later handled interaction.
@param aContinuation
must contain a continuation object, which is used
in its uno-type to locate the same continuation
inside the list of possible ones.
@param bMatchExact
influence the type check of the interception request.
Its not used to check the continuation!
*/
InterceptedRequest( sal_Int32 nHandle ,
const ::com::sun::star::uno::Any& aRequest ,
const ::com::sun::star::uno::Type& aContinuation,
sal_Bool bMatchExact )
{
Handle = nHandle;
Request = aRequest;
Continuation = aContinuation;
MatchExact = bMatchExact;
}
};
//---------------------------------------
/** @short represent the different states, which can occur
as result of an interception.
@see impl_interceptRequest()
*/
enum EInterceptionState
{
/** none of the specified interceptions match the incoming request */
E_NOT_INTERCEPTED,
/** the request could be intercepted - but the specified continuation could not be located.
That's normally an error of the programmer. May be the interaction request does not use
the right set of continuations ... or the interception list contains the wrong continuation. */
E_NO_CONTINUATION_FOUND,
/** the request could be intercepted and the specified continuation could be selected successfully. */
E_INTERCEPTED
};
//-------------------------------------------
// member
protected:
//---------------------------------------
/** @short reference to the intercepted interaction handler.
@descr NULL is allowed for this member!
All interaction will be aborted then ...
expecting th handle() was overwritten by
a derived class.
*/
::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler > m_xInterceptedHandler;
//---------------------------------------
/** @short these list contains the requests, which should be intercepted.
*/
::std::vector< InterceptedRequest > m_lInterceptions;
//-------------------------------------------
// native interface
public:
//---------------------------------------
/** @short initialize a new instance with default values.
*/
InterceptedInteraction();
//---------------------------------------
/** @short initialize a new instance with real values.
@param xInterceptedHandler
the outside interaction handler, which should
be intercepted here.
@param lInterceptions
the list of intercepted requests.
*/
InterceptedInteraction(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& xInterceptedHandler,
const ::std::vector< InterceptedRequest >& lInterceptions );
//---------------------------------------
/** @short initialize a new instance with the interaction handler,
which should be intercepted.
@attention If such interaction handler isn't set here,
all incoming requests will be aborted ...
if the right continuation is available!
@param xInterceptedHandler
the outside interaction handler, which should
be intercepted here.
*/
void setInterceptedHandler(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& xInterceptedHandler);
//---------------------------------------
/** @short set a new list of intercepted interactions.
@attention If the interface method handle() will be overwritten by
a derived class, the functionality behind these static list
can't be used.
@param lInterceptions
the list of intercepted requests.
*/
void setInterceptions(const ::std::vector< InterceptedRequest >& lInterceptions);
//---------------------------------------
/** @short extract a requested continuation from te list of available ones.
@param lContinuations
the list of available continuations.
@param aType
is used to locate the right continuation,
by checking its interface type.
@return A valid reference to the continuation, if it could be located ...
or an empty reference otherwise.
*/
static ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > extractContinuation(
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& lContinuations,
const ::com::sun::star::uno::Type& aType );
//-------------------------------------------
// useable for derived classes
protected:
//---------------------------------------
/** @short can be overwritten by a derived class to handle interceptions
outside.
@descr This base implementation checks, if the request could be intercepted
successfully. Then this method intercepted() is called.
The default implementation returns "NOT_INTERCEPTED" everytimes.
So the method impl_interceptRequest() uses the right continuation automatically.
If this method was overwritten and something different "NO_INTERCEPTED"
is returned, the method impl_interceptRequest() will return immediately with
the result, which is returned by this intercepted() method.
Then the continuations must be selected inside the intercepted() call!
@param rRequest
it points to the intercepted request (means the item of the
set interception list). e.g. its "Handle" member can be used
to identify it and react very easy, without the need to check the
type of the exception ...
@param xOrgRequest
points to the original interaction, which was intercepted.
It provides access to the exception and the list of possible
continuations.
@return The result of this operation.
Note: If E_NOT_INTERCEPTED is returned the default handling of the base class
will be used automatically for this request!
*/
virtual EInterceptionState intercepted(const InterceptedRequest& rRequest ,
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xOrgRequest);
//-------------------------------------------
// uno interface
public:
//---------------------------------------
/** @short implements the default handling of this class ....
or can be overwritten by any derived class.
@descr If no further class is derived from this one
-> the default implementation is used. Then the
internal list of requests is used to handle different
interactions automatically.
(see impl_interceptRequest())
If this method was overwritten by a derived implementation
-> the new implementation has to do everything by itself.
Of course it can access all members/helpers and work with it.
But the default implementation isn't used automatically then.
@param xRequest
the interaction request, which should be intercepted.
*/
virtual void SAL_CALL handle(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest)
throw(::com::sun::star::uno::RuntimeException);
//-------------------------------------------
// helper
private:
//---------------------------------------
/** @short implements the default handling:
- intercept or forward to internal handler.
*/
UCBHELPER_DLLPRIVATE void impl_handleDefault(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest);
//---------------------------------------
/** @short implements the interception of requests.
@descr The incoming request will be analyzed, if it match
any request of the m_lIntercepions list.
If an interception could be found, its continuation will be
searched and selected.
The method return the state of that operation.
But it doesn't call the intercepted and here set
interaction handler. That has to be done in the outside method.
@param xRequest
the interaction request, which should be intercepted.
@return A identifier, which inidicates if the request was intercepted,
the continuation was found and selected ... or not.
*/
UCBHELPER_DLLPRIVATE EInterceptionState impl_interceptRequest(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest);
};
} // namespace ucbhelper
#endif // _UCBHELPER_INTERCEPTEDINTERACTION_HXX_
| 46.689655 | 167 | 0.507755 | [
"object",
"vector"
] |
b9810b06acec72d640b5262b12a0e8819b295c0b | 32,039 | cpp | C++ | cpp/react-native-lua.cpp | swittk/react-native-lua | dfe26ecec49466deb2a3fde78eca673d40875d90 | [
"MIT"
] | null | null | null | cpp/react-native-lua.cpp | swittk/react-native-lua | dfe26ecec49466deb2a3fde78eca673d40875d90 | [
"MIT"
] | null | null | null | cpp/react-native-lua.cpp | swittk/react-native-lua | dfe26ecec49466deb2a3fde78eca673d40875d90 | [
"MIT"
] | null | null | null | #include "react-native-lua.h"
extern "C" {
#include "lua_src/lua.h"
#include "lua_src/lauxlib.h"
#include "lua_src/lualib.h"
#include <sys/time.h>
#include "skrnlua_multithread_define.h"
}
#include <jsi/jsi.h>
#include "CPPNumericStringHashCompare.h"
#include <sstream>
#include <thread>
#include <ReactCommon/CallInvoker.h>
#include "skrnluaezcppstringoperations.h"
#ifdef __ANDROID__
#include <android/log.h>
#define printf(...) __android_log_print(ANDROID_LOG_DEBUG, "TAG", __VA_ARGS__);
#endif
#define EZ_JSI_HOST_FN_TEMPLATE(numArgs, capture) jsi::Function::createFromHostFunction\
(runtime, name, numArgs,\
[&](facebook::jsi::Runtime &runtime,\
const facebook::jsi::Value &thisValue,\
const facebook::jsi::Value *arguments,\
size_t count) -> jsi::Value \
{capture}) \
#define EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE(capture) EZ_JSI_HOST_FN_TEMPLATE(1, { \
if(count < 1) return jsi::Value::undefined(); \
capture \
})
void clearMTHelperForLuaState(lua_State *L);
SKRNNativeLua::SKRNLuaMTHelper *mtHelperForLuaState(lua_State *L);
void SKRNLuaMultitheadUserStateOpen(lua_State *L);
void SKRNLuaMultitheadUserStateClose(lua_State *L);
void SKRNLuaMultitheadLuaLock(lua_State *L);
void SKRNLuaMultitheadLuaUnlock(lua_State *L);
namespace SKRNNativeLua {
using namespace facebook;
static long long getLuaStateStartExecutionTime(lua_State *L);
static long long currentMillisecondsSinceEpoch();
static int skrn_lua_sleep (lua_State *L) {
double ms = luaL_checknumber(L, 1);
//check and fetch the arguments
std::this_thread::sleep_for(std::chrono::milliseconds((int)ms));
//return number of results
return 0;
}
//std::shared_ptr<facebook::react::CallInvoker> shared_callinvoker;
void install(facebook::jsi::Runtime &jsiRuntime, std::shared_ptr<facebook::react::CallInvoker> invoker) {
using namespace jsi;
// std::shared_ptr<facebook::react::CallInvoker> shared_callinvoker;
// This is stupid using a global variable, but just adding this to try prevent android from crashing.
// shared_callinvoker = invoker;
auto newInterpreterFunction =
jsi::Function::createFromHostFunction(
jsiRuntime,
PropNameID::forAscii(jsiRuntime, "SKRNNativeLuaNewInterpreter"),
0,
// [&, invoker](Runtime &runtime, const Value &thisValue, const Value *arguments,
[&, invoker](jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments,
size_t count) -> jsi::Value
{
if(invoker == nullptr) {
printf("nullptr sad life");
return jsi::Value::undefined();
}
jsi::Object object = jsi::Object::createFromHostObject(runtime, std::make_shared<SKRNLuaInterpreter>(invoker));
return object;
});
jsiRuntime.global().setProperty(jsiRuntime, "SKRNNativeLuaNewInterpreter",
std::move(newInterpreterFunction));
}
//void install(facebook::jsi::Runtime &jsiRuntime, std::shared_ptr<facebook::react::CallInvoker> invoker);
void cleanup(facebook::jsi::Runtime &jsiRuntime) {
// shared_callinvoker = nullptr;
// shared_callinvoker = null
}
int multiply(float a, float b) {
return a * b;
}
// Inspired by answer to https://stackoverflow.com/a/4514193/4469172
int SKRNLuaInterpreter::staticLuaPrintHandler(lua_State *L) {
SKRNLuaInterpreter *me = (SKRNLuaInterpreter *)lua_touserdata(L, lua_upvalueindex(1));
int nargs = lua_gettop(L);
std::stringstream outStr;
for (int i=1; i <= nargs; i++) {
// Mimicking what luaB_print does; add a \t if it's idx > 1
if(i > 1) {
outStr << "\t";
}
if (lua_isstring(L, i)) {
/* Pop the next arg using lua_tostring(L, i) and do your print */
const char *str = lua_tostring(L, i);
outStr << str;
}
else {
// Mimicking what luaB_print does; convert to string and just print
size_t strSize = 0;
const char *s = lua_tolstring(L, i, &strSize);
outStr << std::string(s, strSize);
}
}
me->luaPrintHandler(outStr.str());
return 0;
}
void SKRNLuaInterpreter::luaPrintHandler(std::string str) {
printOutputMutex.lock();
printOutput.push_back(str);
if(printOutput.size() > maxPrintOutputCount) {
printOutput.pop_front();
}
printOutputMutex.unlock();
}
// Endless loop prevention hook
// Inspired by https://stackoverflow.com/a/7083653/4469172
static void luaState_debug_hook(lua_State* L, lua_Debug *ar)
{
SKRNLuaMTHelper *helper = mtHelperForLuaState(L);
SKRNLuaInterpreter *instance = (SKRNLuaInterpreter *)helper->conveniencePointers[0];
if(instance->shouldTerminate
||
currentMillisecondsSinceEpoch() - getLuaStateStartExecutionTime(L) > instance->executionLimitMilliseconds)
{
printf("attempting longjump due to crash");
longjmp(instance->place, 1);
}
}
void SKRNLuaInterpreter::createState() {
_state = luaL_newstate();
luaL_openlibs(_state);
SKRNLuaMTHelper *helper = mtHelperForLuaState(_state);
helper->conveniencePointers[0] = (void *)this;
// SKRNLuaInterpreter *instance = (SKRNLuaInterpreter *)helper->conveniencePointers[0];
// Register class method in Lua https://stackoverflow.com/a/21326241/4469172
lua_pushlightuserdata(_state, this);
lua_pushcclosure(_state, &SKRNLuaInterpreter::staticLuaPrintHandler, 1);
lua_setglobal(_state, "print");
lua_pushcfunction(_state, skrn_lua_sleep);
lua_setglobal(_state, "sleep");
// Add a watcher hook to prevent infinite loops
// Inspired by https://stackoverflow.com/a/7083653/4469172
lua_sethook(_state, luaState_debug_hook, LUA_MASKCOUNT, 100);
}
void SKRNLuaInterpreter::closeStateIfNeeded() {
callInvoker = nullptr;
printf("\nclosing state(deallocating)");
if(_state != NULL) {
printf("\ndoing lua_close");
lua_sethook(_state, NULL, 0, 100);
lua_close(_state);
_state = NULL;
printf("\ndone lua_close");
}
printf("\ndone all deallocating");
}
static long long currentMillisecondsSinceEpoch() {
// struct timeval tv;
// gettimeofday(&tv, NULL);
// long long millis = (long long)(tv.tv_sec) * 1000 + (long long)(tv.tv_usec) / 1000;
// return millis;
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
static void setLuaStateStartExecutionTime(lua_State *L) {
lua_pushinteger(L, currentMillisecondsSinceEpoch());
lua_setglobal(L, "___skrn_start_execution_time");
}
static long long getLuaStateStartExecutionTime(lua_State *L) {
lua_getglobal(L, "___skrn_start_execution_time");
long long sinceStart = lua_tointeger(L, -1);
lua_pop(L, 1);
return sinceStart;
}
/**
* Loads and runs the given string. It is defined as the following macro:
* (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)).
* @returns result code, LUA_OK if ok. (returns 0 if there are no errors or 1 in case of errors)
*/
int SKRNLuaInterpreter::doString(std::string str) {
if(!valid) return 0;
setLuaStateStartExecutionTime(_state);
int ret = 0;
if (setjmp(place) == 0) {
ret = luaL_dostring(_state, str.c_str());
}
else {
// Setjmp Fails. Prevent execution from happening since the lua state is now unstable.
printf("doString jumped due to failure of execution");
valid = false;
ret = 999;
}
return ret;
}
int SKRNLuaInterpreter::doFile(std::string str) {
if(!valid) return 0;
setLuaStateStartExecutionTime(_state);
// Nice string prefix checking using stl (https://stackoverflow.com/a/40441240/4469172)
if (str.rfind("file:///", 0) == 0) { // pos=0 limits the search to the prefix
str = str.substr(7); // Slice out beginning "file://"
}
int ret = 0;
if (setjmp(place) == 0) {
ret = luaL_dofile(_state, str.c_str());
}
else {
// Setjmp Fails. Prevent execution from happening since the lua state is now unstable.
printf("doFile jumped due to failure of execution");
valid = false;
ret = 999;
}
return ret;
}
std::string SKRNLuaInterpreter::getLatestError() {
return lua_tostring(_state, -1);
}
jsi::Value SKRNLuaInterpreter::get(jsi::Runtime &runtime, const jsi::PropNameID &name) {
std::string methodName = name.utf8(runtime);
long long methodSwitch = string_hash(methodName.c_str());
switch(methodSwitch) {
case "printCount"_sh: {
printOutputMutex.lock();
int size = (int)printOutput.size();
printOutputMutex.unlock();
return jsi::Value(size);
} break;
case "getPrint"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
printOutputMutex.lock();
int size = (int)printOutput.size();
printOutputMutex.unlock();
int numElems;
if(count < 1) {
numElems = size;
}
else {
numElems = (int)arguments[0].asNumber();
if(numElems > size) {
numElems = size;
}
}
// jsi::Array ret = jsi::Array(runtime, numElems);
printOutputMutex.lock();
std::vector<std::string> printElems;
for(int i = 0; i < numElems; i++) {
printElems.push_back(std::move(printOutput[0]));
printOutput.pop_front();
}
printOutputMutex.unlock();
std::string retStr = StringEZJoin(printElems, "\n");
jsi::String ret = jsi::String::createFromUtf8(runtime, retStr);
return std::move(ret);
});
} break;
case "dostringasync"_sh: {
std::shared_ptr<react::CallInvoker> invoker = callInvoker;
if(callInvoker == nullptr) {
throw jsi::JSError(runtime, "callinvoker is null");
}
if(!valid) {
throw jsi::JSError(runtime, "Runtime is no longer valid");
}
if(executing) {
throw jsi::JSError(runtime, "Runtime is executing");
}
return jsi::Function::createFromHostFunction
(runtime,name, 1, [&, invoker](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, size_t count) -> jsi::Value {
if(count < 2) {
return jsi::Value::undefined();
}
// callInvoker->invokeAsync([&]{
// arguments[1].getObject(runtime).asFunction(runtime).call(runtime, 555);
// });
executing = true;
std::string todostring = arguments[0].getString(runtime).utf8(runtime);
std::shared_ptr<jsi::Object> userCallbackRef =
std::make_shared<jsi::Object>(arguments[1].getObject(runtime));
std::shared_ptr<react::CallInvoker> myInvoker = callInvoker;
std::thread runThread = std::thread([&, this, userCallbackRef, myInvoker, todostring]() {
int ret = doString(todostring);
printf("ret is %d", ret);
executing = false;
if(myInvoker == nullptr) return;
printf("has invoker, about to invoke it");
// Currently Android crashes right here. It also crashes whenever callInvoker->invokeAsync() is called, even during the module initialization (::install() method). Any help with debugging this would be extremely welcome.
myInvoker->invokeAsync([&, userCallbackRef, ret]{
if(userCallbackRef == nullptr) {
return;
}
printf("calling userCallbackRef since it is not null");
userCallbackRef->asFunction(runtime).call(runtime, jsi::Value(ret));
});
});
runThread.detach();
return jsi::Value::undefined();
});
} break;
case "dofileasync"_sh: {
std::shared_ptr<react::CallInvoker> invoker = callInvoker;
if(callInvoker == nullptr) {
throw jsi::JSError(runtime, "callinvoker is null");
}
if(!valid) {
throw jsi::JSError(runtime, "Runtime is no longer valid");
}
if(executing) {
throw jsi::JSError(runtime, "Runtime is executing");
}
return jsi::Function::createFromHostFunction
(runtime,name, 1, [&, invoker](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, size_t count) -> jsi::Value {
if(count < 2) {
return jsi::Value::undefined();
}
executing = true;
std::string todostring = arguments[0].getString(runtime).utf8(runtime);
std::shared_ptr<jsi::Object> userCallbackRef =
std::make_shared<jsi::Object>(arguments[1].getObject(runtime));
std::shared_ptr<react::CallInvoker> myInvoker = callInvoker;
std::thread runThread = std::thread([&, userCallbackRef, todostring]() {
int ret = doFile(todostring);
executing = false;
if(myInvoker == nullptr) return;
myInvoker->invokeAsync([&, userCallbackRef, ret]{
printf("ret is %d", ret);
if(userCallbackRef == nullptr) {
return;
}
userCallbackRef->asFunction(runtime).call(runtime, jsi::Value(ret));
});
});
runThread.detach();
return jsi::Value::undefined();
});
} break;
// These methods listed from https://www.lua.org/manual/5.4/manual.html#lua_pop
case "pop"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1,{
if(count < 1) return jsi::Value::undefined();
lua_pop(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "pushboolean"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
lua_pushboolean(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
// lua_pushcclosure
// lua_pushcfunction
// lua_pushfstring
case "pushglobaltable"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(0, {
lua_pushglobaltable(_state);
return jsi::Value::undefined();
});
} break;
case "pushinteger"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1,{
if(count < 1) return jsi::Value::undefined();
lua_pushinteger(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "pushnil"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(0,{
lua_pushnil(_state);
return jsi::Value::undefined();
});
} break;
case "pushnumber"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(0,{
if(count < 1) return jsi::Value::undefined();
lua_pushnumber(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "pushstring"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1,{
if(count < 1) return jsi::Value::undefined();
lua_pushstring(_state, arguments[0].asString(runtime).utf8(runtime).c_str());
return jsi::Value::undefined();
});
} break;
case "pushthread"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1,{
return jsi::Value(lua_pushthread(_state));
});
} break;
case "pushvalue"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1,{
if(count < 1) return jsi::Value::undefined();
lua_pushvalue(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "rawequal"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(2,{
if(count < 2) return jsi::Value::undefined();
return jsi::Value(lua_rawequal(_state, arguments[0].asNumber(), arguments[1].asNumber()));
});
} break;
case "rawget"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1,{
if(count < 1) return jsi::Value::undefined();
return jsi::Value(lua_rawget(_state, arguments[0].asNumber()));
});
} break;
case "rawgeti"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(2,{
if(count < 2) return jsi::Value::undefined();
return jsi::Value(lua_rawgeti(_state, arguments[0].asNumber(), arguments[1].asNumber()));
});
} break;
//rawgetp
case "rawlen"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
return jsi::Value((double)lua_rawlen(_state, arguments[0].asNumber()));
});
} break;
case "rawset"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
lua_rawset(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "rawseti"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(2,{
if(count < 2) return jsi::Value::undefined();
lua_rawseti(_state, arguments[0].asNumber(), arguments[1].asNumber());
return jsi::Value::undefined();
});
} break;
// lua_rawsetp
// skip to lua_remove
case "remove"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
lua_remove(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "insert"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
lua_insert(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "replace"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
lua_replace(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "resetthread"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(0,{
lua_resetthread(_state);
return jsi::Value::undefined();
});
} break;
case "resume"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(2,{
if(count < 2) return jsi::Value::undefined();
long ptrVal = arguments[0].asNumber();
int nargs = arguments[1].asNumber();
int nresults = 0;
int result = lua_resume(_state, (lua_State *)ptrVal, nargs, &nresults);
jsi::Object ret = jsi::Object(runtime);
ret.setProperty(runtime, "result", result);
ret.setProperty(runtime, "nresults", nresults);
return ret;
});
} break;
case "rotate"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(2,{
if(count < 2) return jsi::Value::undefined();
lua_rotate(_state, arguments[0].asNumber(), arguments[1].asNumber());
return jsi::Value::undefined();
});
} break;
//lua_setallocf
case "setfield"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(2,{
if(count < 2) return jsi::Value::undefined();
lua_setfield(_state, arguments[0].asNumber(), arguments[1].asString(runtime).utf8(runtime).c_str());
return jsi::Value::undefined();
});
} break;
case "setglobal"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
lua_setglobal(_state, arguments[1].asString(runtime).utf8(runtime).c_str());
return jsi::Value::undefined();
});
}break;
case "seti"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(2,{
if(count < 2) return jsi::Value::undefined();
lua_seti(_state, arguments[0].asNumber(), arguments[1].asNumber());
return jsi::Value::undefined();
});
} break;
case "setiuservalue"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(2,{
if(count < 2) return jsi::Value::undefined();
return jsi::Value(lua_setiuservalue(_state, arguments[0].asNumber(), arguments[1].asNumber()));
});
} break;
case "setmetatable"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
return jsi::Value(lua_setmetatable(_state, arguments[0].asNumber()));
});
} break;
case "settable"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
lua_settable(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "settop"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
lua_settop(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "gettop"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(0, {
return jsi::Value(lua_gettop(_state));
});
} break;
//lua_setwarnf
case "status"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(0,{
return jsi::Value(lua_status(_state));
});
} break;
case "stringtonumber"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
size_t ret = lua_stringtonumber(_state, arguments[0].asString(runtime).utf8(runtime).c_str());
return jsi::Value((int)(ret));
});
} break;
case "gettable"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1,{
if(count < 1) return jsi::Value::undefined();
return jsi::Value(lua_gettable(_state, arguments[0].asNumber()));
});
} break;
case "dostring"_sh: {
if(!valid) {
throw jsi::JSError(runtime, "Runtime is no longer valid");
}
if(executing) {
throw jsi::JSError(runtime, "Runtime is executing");
}
return EZ_JSI_HOST_FN_TEMPLATE(1,{
if(count < 1) return jsi::Value::undefined();
std::string str = arguments[0].asString(runtime).utf8(runtime);
int retVal = doString(str);
executing = false;
if(retVal == 999) {
throw jsi::JSError(runtime, "Execution over limit");
}
return jsi::Value(retVal);
});
} break;
case "dofile"_sh: {
if(!valid) {
throw jsi::JSError(runtime, "Runtime is no longer valid");
}
if(executing) {
throw jsi::JSError(runtime, "Runtime is executing");
}
return EZ_JSI_HOST_FN_TEMPLATE(1,{
if(count < 1) return jsi::Value::undefined();
std::string str = arguments[0].asString(runtime).utf8(runtime);
int retVal = doFile(str);
executing = false;
if(retVal == 999) {
throw jsi::JSError(runtime, "Execution over limit");
}
return jsi::Value(retVal);
});
} break;
case "getglobal"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
std::string str = arguments[0].asString(runtime).utf8(runtime);
lua_getglobal(_state, str.c_str());
return jsi::Value::undefined();
});
} break;
case "getLatestError"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(0, {
return jsi::String::createFromUtf8(runtime, getLatestError());
});
} break;
case "var_asnumber"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
std::string str = arguments[0].asString(runtime).utf8(runtime);
lua_getglobal(_state, str.c_str());
if(lua_isnumber(_state, -1)) {
// lua_Number num = lua_tonumberx(_state, -1, NULL);
lua_Number num = lua_tonumber(_state, -1);
return jsi::Value(num);
}
return jsi::Value(0);
});
} break;
case "toboolean"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
return jsi::Value(lua_toboolean(_state, arguments[0].asNumber()));
});
} break;
// tocfunction
case "toclose"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
lua_toclose(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
case "tointeger"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
return jsi::Value((int)lua_tointeger(_state, arguments[0].asNumber()));
});
} break;
case "tonumber"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
return jsi::Value(lua_tonumber(_state, arguments[0].asNumber()));
});
} break;
case "tostring"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
lua_tostring(_state, arguments[0].asNumber());
return jsi::Value::undefined();
});
} break;
// case "topointer"_sh: {
//
// } break;
case "tothread"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
lua_State *thread = lua_tothread(_state, arguments[0].asNumber());
return jsi::Value((double)(long)(thread));
});
} break;
case "type"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
int idx = count < 1 ? -1 : arguments[0].asNumber();
return jsi::Value(lua_type(_state, idx));
});
} break;
case "typename"_sh: {
return EZ_JSI_HOST_FN_TEMPLATE(1, {
if(count < 1) return jsi::Value::undefined();
return jsi::String::createFromUtf8(runtime, lua_typename(_state, arguments[0].asNumber()));
});
} break;
// skip to lua_yield
case "yield"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
return jsi::Value(lua_yield(_state, arguments[0].asNumber()));
});
} break;
case "valid"_sh: {
return jsi::Value(valid);
} break;
case "executionLimit"_sh: {
return jsi::Value((double)executionLimitMilliseconds);
} break;
case "setExecutionLimit"_sh: {
return EZ_LUA_MANDATORY_SINGLE_ARGUMENT_TEMPLATE({
executionLimitMilliseconds = arguments[0].asNumber();
if(executionLimitMilliseconds < 0) {
executionLimitMilliseconds = 10000;
}
return jsi::Value::undefined();
});
} break;
// case "size"_sh: {
// return ObjectFromSKRNSize(runtime, size());
// } break;
}
return jsi::Value::undefined();
}
static std::vector<std::string> nativeLuaInterpreterKeys = {
"pop",
"pushboolean",
"pushglobaltable",
"pushinteger",
"pushnil",
"pushnumber",
"pushstring",
"pushthread",
"pushvalue",
"rawequal",
"rawget",
"rawgeti",
"rawlen",
"rawset",
"rawseti",
"remove",
"insert",
"replace",
"resetthread",
"resume",
"rotate",
"setfield",
"setglobal",
"seti",
"setiuservalue",
"setmetatable",
"settable",
"settop",
"gettop",
"status",
"stringtonumber",
"gettable",
"dostring",
"dofile",
"getglobal",
"getLatestError",
"var_asnumber",
"toboolean",
"toclose",
"tointeger",
"tonumber",
"tostring",
"topointer",
"tothread",
"type",
"typename",
"yield",
"valid"
};
std::vector<jsi::PropNameID> SKRNLuaInterpreter::getPropertyNames(jsi::Runtime& rt) {
std::vector<jsi::PropNameID> ret;
for(std::string key : nativeLuaInterpreterKeys) {
ret.push_back(jsi::PropNameID::forUtf8(rt, key));
}
return ret;
}
}
#define LUAMTHELPERKEY "__SKRNMTHelper"
void SKRNLuaMultitheadUserStateOpen(lua_State *L) {
// Lua EXTRADATA http://lua-users.org/lists/lua-l/2013-09/msg00005.html
// But it's no longer the same in Lua 5.4 apparently;
// We how have helpful macros like lua_getextraspace !
void **extraSpace = (void **)lua_getextraspace(L);
SKRNNativeLua::SKRNLuaMTHelper *helper = new SKRNNativeLua::SKRNLuaMTHelper();
// ((char *)(L) - LUA_EXTRASPACE);
*extraSpace = (void *)helper;
}
void SKRNLuaMultitheadUserStateClose(lua_State *L) {
printf("userstateclose");
clearMTHelperForLuaState(L);
}
void SKRNLuaMultitheadLuaLock(lua_State *L) {
SKRNNativeLua::SKRNLuaMTHelper *helper = mtHelperForLuaState(L);
helper->mutex.lock();
}
void SKRNLuaMultitheadLuaUnlock(lua_State *L) {
SKRNNativeLua::SKRNLuaMTHelper *helper = mtHelperForLuaState(L);
helper->mutex.unlock();
}
SKRNNativeLua::SKRNLuaMTHelper *mtHelperForLuaState(lua_State *L) {
void **extraspacePointer = (void **)lua_getextraspace(L);
SKRNNativeLua::SKRNLuaMTHelper *helper = (SKRNNativeLua::SKRNLuaMTHelper *)(*extraspacePointer);
return helper;
}
void clearMTHelperForLuaState(lua_State *L) {
void **extraspacePointer = (void **)lua_getextraspace(L);
if(*extraspacePointer != NULL) {
printf("nonnulextraspace");
SKRNNativeLua::SKRNLuaMTHelper *helper = (SKRNNativeLua::SKRNLuaMTHelper *)(*extraspacePointer);
delete helper;
printf("deleted helper");
*extraspacePointer = NULL;
}
}
| 39.359951 | 240 | 0.553045 | [
"object",
"vector"
] |
b9823a72d13248daf77c034f1ebe6c3857fc3750 | 4,905 | cpp | C++ | shared/sentry/external/libunwindstack-ndk/DexFiles.cpp | Eeems-Org/oxide | d3bfa47e60bf311feb7768234dfe95a15adeb9da | [
"MIT"
] | 18 | 2022-01-11T17:24:50.000Z | 2022-03-30T04:35:25.000Z | shared/sentry/external/libunwindstack-ndk/DexFiles.cpp | Eeems-Org/oxide | d3bfa47e60bf311feb7768234dfe95a15adeb9da | [
"MIT"
] | 21 | 2022-01-07T19:20:04.000Z | 2022-03-24T14:32:28.000Z | shared/sentry/external/libunwindstack-ndk/DexFiles.cpp | Eeems-Org/oxide | d3bfa47e60bf311feb7768234dfe95a15adeb9da | [
"MIT"
] | 2 | 2022-01-15T16:45:34.000Z | 2022-03-01T22:37:48.000Z | /*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 <stdint.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <memory>
#include <unwindstack/DexFiles.h>
#include <unwindstack/MapInfo.h>
#include <unwindstack/Maps.h>
#include <unwindstack/Memory.h>
#if defined(DEXFILE_SUPPORT)
#include "DexFile.h"
#endif
namespace unwindstack {
#if !defined(DEXFILE_SUPPORT)
// Empty class definition.
class DexFile {
public:
DexFile() = default;
virtual ~DexFile() = default;
};
#endif
struct DEXFileEntry32 {
uint32_t next;
uint32_t prev;
uint32_t dex_file;
};
struct DEXFileEntry64 {
uint64_t next;
uint64_t prev;
uint64_t dex_file;
};
DexFiles::DexFiles(std::shared_ptr<Memory>& memory) : Global(memory) {}
DexFiles::DexFiles(std::shared_ptr<Memory>& memory, std::vector<std::string>& search_libs)
: Global(memory, search_libs) {}
DexFiles::~DexFiles() {}
void DexFiles::ProcessArch() {
switch (arch()) {
case ARCH_ARM:
case ARCH_X86:
read_entry_ptr_func_ = &DexFiles::ReadEntryPtr32;
read_entry_func_ = &DexFiles::ReadEntry32;
break;
case ARCH_ARM64:
case ARCH_X86_64:
read_entry_ptr_func_ = &DexFiles::ReadEntryPtr64;
read_entry_func_ = &DexFiles::ReadEntry64;
break;
case ARCH_UNKNOWN:
abort();
}
}
uint64_t DexFiles::ReadEntryPtr32(uint64_t addr) {
uint32_t entry;
const uint32_t field_offset = 12; // offset of first_entry_ in the descriptor struct.
if (!memory_->ReadFully(addr + field_offset, &entry, sizeof(entry))) {
return 0;
}
return entry;
}
uint64_t DexFiles::ReadEntryPtr64(uint64_t addr) {
uint64_t entry;
const uint32_t field_offset = 16; // offset of first_entry_ in the descriptor struct.
if (!memory_->ReadFully(addr + field_offset, &entry, sizeof(entry))) {
return 0;
}
return entry;
}
bool DexFiles::ReadEntry32() {
DEXFileEntry32 entry;
if (!memory_->ReadFully(entry_addr_, &entry, sizeof(entry)) || entry.dex_file == 0) {
entry_addr_ = 0;
return false;
}
addrs_.push_back(entry.dex_file);
entry_addr_ = entry.next;
return true;
}
bool DexFiles::ReadEntry64() {
DEXFileEntry64 entry;
if (!memory_->ReadFully(entry_addr_, &entry, sizeof(entry)) || entry.dex_file == 0) {
entry_addr_ = 0;
return false;
}
addrs_.push_back(entry.dex_file);
entry_addr_ = entry.next;
return true;
}
bool DexFiles::ReadVariableData(uint64_t ptr_offset) {
entry_addr_ = (this->*read_entry_ptr_func_)(ptr_offset);
return entry_addr_ != 0;
}
void DexFiles::Init(Maps* maps) {
if (initialized_) {
return;
}
initialized_ = true;
entry_addr_ = 0;
FindAndReadVariable(maps, "__dex_debug_descriptor");
}
#if defined(DEXFILE_SUPPORT)
DexFile* DexFiles::GetDexFile(uint64_t dex_file_offset, MapInfo* info) {
// Lock while processing the data.
DexFile* dex_file;
auto entry = files_.find(dex_file_offset);
if (entry == files_.end()) {
std::unique_ptr<DexFile> new_dex_file = DexFile::Create(dex_file_offset, memory_.get(), info);
dex_file = new_dex_file.get();
files_[dex_file_offset] = std::move(new_dex_file);
} else {
dex_file = entry->second.get();
}
return dex_file;
}
#else
DexFile* DexFiles::GetDexFile(uint64_t, MapInfo*) {
return nullptr;
}
#endif
bool DexFiles::GetAddr(size_t index, uint64_t* addr) {
if (index < addrs_.size()) {
*addr = addrs_[index];
return true;
}
if (entry_addr_ != 0 && (this->*read_entry_func_)()) {
*addr = addrs_.back();
return true;
}
return false;
}
#if defined(DEXFILE_SUPPORT)
void DexFiles::GetMethodInformation(Maps* maps, MapInfo* info, uint64_t dex_pc,
std::string* method_name, uint64_t* method_offset) {
std::lock_guard<std::mutex> guard(lock_);
if (!initialized_) {
Init(maps);
}
size_t index = 0;
uint64_t addr;
while (GetAddr(index++, &addr)) {
if (addr < info->start || addr >= info->end) {
continue;
}
DexFile* dex_file = GetDexFile(addr, info);
if (dex_file != nullptr &&
dex_file->GetMethodInformation(dex_pc - addr, method_name, method_offset)) {
break;
}
}
}
#else
void DexFiles::GetMethodInformation(Maps*, MapInfo*, uint64_t, std::string*, uint64_t*) {}
#endif
} // namespace unwindstack
| 24.648241 | 98 | 0.688685 | [
"vector"
] |
b984422126e6530b4e329eefd97cdf9aedb45d2b | 11,548 | cpp | C++ | src/tests/class_tests/openms/source/FastLowessSmoothing_test.cpp | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 348 | 2015-01-17T16:50:12.000Z | 2022-03-30T22:55:39.000Z | src/tests/class_tests/openms/source/FastLowessSmoothing_test.cpp | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 4,259 | 2015-01-01T14:07:54.000Z | 2022-03-31T16:49:14.000Z | src/tests/class_tests/openms/source/FastLowessSmoothing_test.cpp | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 266 | 2015-01-24T14:56:14.000Z | 2022-03-30T12:32:35.000Z | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2021.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Erhan Kenar, Holger Franken $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FILTERING/SMOOTHING/FastLowessSmoothing.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
///////////////////////////
using namespace OpenMS;
using namespace std;
double targetFunction(double x)
{
return 10 + 20*x + 40*x*x;
}
START_TEST(FastLowessSmoothing, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION([FastLowessSmoothing_Original tests]void smoothData(const DoubleVector&, const DoubleVector&, DoubleVector&))
{
/*
* These are the original tests described in the FORTRAN code. We should be able to reproduce those.
*
* X values:
* 1 2 3 4 5 (10)6 8 10 12 14 50
*
* Y values:
* 18 2 15 6 10 4 16 11 7 3 14 17 20 12 9 13 1 8 5 19
*
*
* YS values with F = .25, NSTEPS = 0, DELTA = 0.0
* 13.659 11.145 8.701 9.722 10.000 (10)11.300 13.000 6.440 5.596
* 5.456 18.998
*
* YS values with F = .25, NSTEPS = 0 , DELTA = 3.0
* 13.659 12.347 11.034 9.722 10.511 (10)11.300 13.000 6.440 5.596
* 5.456 18.998
*
* YS values with F = .25, NSTEPS = 2, DELTA = 0.0
* 14.811 12.115 8.984 9.676 10.000 (10)11.346 13.000 6.734 5.744
* 5.415 18.998
*/
double xval[] = {1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 50 };
double yval[] = { 18, 2, 15, 6, 10, 4, 16, 11, 7, 3, 14, 17, 20, 12, 9, 13, 1, 8, 5, 19};
double ys_1[] = { 13.659, 11.145, 8.701, 9.722, 10.000, 11.300, 11.300,
11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 13.000,
6.440, 5.596, 5.456, 18.998};
double ys_2[] = {13.659, 12.347, 11.034, 9.722, 10.511, 11.300, 11.300,
11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 13.000,
6.440, 5.596, 5.456, 18.998};
double ys_3[] = { 14.811, 12.115, 8.984, 9.676, 10.000, 11.346, 11.346,
11.346, 11.346, 11.346, 11.346, 11.346, 11.346, 11.346, 11.346, 13.000,
6.734, 5.744, 5.415, 18.998};
// the original test has limited numerical accuracy
TOLERANCE_RELATIVE(1e-4);
TOLERANCE_ABSOLUTE(1e-3);
{
std::vector< double > v_xval;
std::vector< double > v_yval;
for (size_t i = 0; i < 20; i++)
{
v_xval.push_back(xval[i]);
v_yval.push_back(yval[i]);
}
// YS values with F = .25, NSTEPS = 0, DELTA = 0.0
{
std::vector< double > out(20), tmp1(20), tmp2(20);
FastLowessSmoothing::lowess(v_xval, v_yval, 0.25, 0, 0.0, out);
for (size_t i = 0; i < 20; i++)
{
TEST_REAL_SIMILAR(out[i], ys_1[i]);
}
}
// YS values with F = .25, NSTEPS = 0 , DELTA = 3.0
{
std::vector< double > out(20), tmp1(20), tmp2(20);
FastLowessSmoothing::lowess(v_xval, v_yval, 0.25, 0, 3.0, out);
for (size_t i = 0; i < 20; i++)
{
TEST_REAL_SIMILAR(out[i], ys_2[i]);
}
}
// YS values with F = .25, NSTEPS = 2, DELTA = 0.0
{
std::vector< double > out(20), tmp1(20), tmp2(20);
FastLowessSmoothing::lowess(v_xval, v_yval, 0.25, 2, 0.0, out);
for (size_t i = 0; i < 20; i++)
{
TEST_REAL_SIMILAR(out[i], ys_3[i]);
}
}
}
}
END_SECTION
START_SECTION([FastLowessSmoothing_cars]void smoothData(const DoubleVector&, const DoubleVector&, DoubleVector&))
{
/*
In R
require(graphics)
plot(cars, main = "lowess(cars)")
lines(lowess(cars), col = 2)
lines(lowess(cars, f = .2), col = 3)
legend(5, 120, c(paste("f = ", c("2/3", ".2"))), lty = 1, col = 2:3)
The data below is what we expect from the R function when running the cars example.
*/
TOLERANCE_RELATIVE(4e-7);
int speed[] = {4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 16, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, 22, 23, 24, 24, 24, 24, 25};
int dist[] = { 2, 10, 4, 22, 16, 10, 18, 26, 34, 17, 28, 14, 20, 24, 28, 26, 34, 34, 46, 26, 36, 60, 80, 20, 26, 54, 32, 40, 32, 40, 50, 42, 56, 76, 84, 36, 46, 68, 32, 48, 52, 56, 64, 66, 54, 70, 92, 93, 120, 85};
double expected_1[] = {4.965459, 4.965459, 13.124495, 13.124495, 15.858633, 18.579691, 21.280313, 21.280313, 21.280313, 24.129277, 24.129277, 27.119549, 27.119549, 27.119549, 27.119549, 30.027276, 30.027276, 30.027276, 30.027276, 32.962506, 32.962506, 32.962506, 32.962506, 36.757728, 36.757728, 36.757728, 40.435075, 40.435075, 43.463492, 43.463492, 43.463492, 46.885479, 46.885479, 46.885479, 46.885479, 50.793152, 50.793152, 50.793152, 56.491224, 56.491224, 56.491224, 56.491224, 56.491224, 67.585824, 73.079695, 78.643164, 78.643164, 78.643164, 78.643164, 84.328698};
double expected_2[] = {6.030408, 6.030408, 12.678893, 12.678893, 15.383796, 18.668847, 22.227571, 22.227571, 22.227571, 23.306483, 23.306483, 21.525372, 21.525372, 21.525372, 21.525372, 34.882735, 34.882735, 34.882735, 34.882735, 47.059947, 47.059947, 47.059947, 47.059947, 37.937118, 37.937118, 37.937118, 36.805260, 36.805260, 46.267862, 46.267862, 46.267862, 65.399825, 65.399825, 65.399825, 65.399825, 48.982482, 48.982482, 48.982482, 51.001919, 51.001919, 51.001919, 51.001919, 51.001919, 66.000000, 71.873554, 82.353574, 82.353574, 82.353574, 82.353574, 92.725141};
std::vector<double> x, y, y_noisy, out;
for (Size i = 0; i < 50; i++)
{
x.push_back(speed[i]);
y.push_back(dist[i]);
}
FastLowessSmoothing::lowess(x, y, out);
for (Size i = 0; i < out.size(); ++i)
{
TEST_REAL_SIMILAR(out[i], expected_1[i]);
}
out.clear();
double delta = 0.01 * (x[ x.size()-1 ] - x[0]); // x is sorted
FastLowessSmoothing::lowess(x, y, 0.2, 3, delta, out);
for (Size i = 0; i < out.size(); ++i)
{
TEST_REAL_SIMILAR(out[i], expected_2[i]);
}
// numerical identity with the C++ function
TOLERANCE_RELATIVE(4e-7);
TOLERANCE_ABSOLUTE(1e-4);
double expected_3[] = {4.96545927718688, 4.96545927718688, 13.1244950396665, 13.1244950396665, 15.8586333820983, 18.5796905142177, 21.2803125785285, 21.2803125785285, 21.2803125785285, 24.1292771489265, 24.1292771489265, 27.1195485506035, 27.1195485506035, 27.1195485506035, 27.1195485506035, 30.027276331154, 30.027276331154, 30.027276331154, 30.027276331154, 32.9625061361576, 32.9625061361576, 32.9625061361576, 32.9625061361576, 36.7577283416497, 36.7577283416497, 36.7577283416497, 40.4350745619887, 40.4350745619887, 43.4634917818176, 43.4634917818176, 43.4634917818176, 46.885478946024, 46.885478946024, 46.885478946024, 46.885478946024, 50.7931517254206, 50.7931517254206, 50.7931517254206, 56.4912240928772, 56.4912240928772, 56.4912240928772, 56.4912240928772, 56.4912240928772, 67.5858242314312, 73.0796952693701, 78.6431635544, 78.6431635544, 78.6431635544, 78.6431635544, 84.3286980968344};
double expected_4[] = {6.03040788454055, 6.03040788454055, 12.6788932684282, 12.6788932684282, 15.3837960614806, 18.6688467170581, 22.2275706232724, 22.2275706232724, 22.2275706232724, 23.3064828196959, 23.3064828196959, 21.52537248518, 21.52537248518, 21.52537248518, 21.52537248518, 34.8827348652577, 34.8827348652577, 34.8827348652577, 34.8827348652577, 47.0599472320042, 47.0599472320042, 47.0599472320042, 47.0599472320042, 37.9371179560115, 37.9371179560115, 37.9371179560115, 36.8052597644327, 36.8052597644327, 46.2678618410954, 46.2678618410954, 46.2678618410954, 65.3998245907766, 65.3998245907766, 65.3998245907766, 65.3998245907766, 48.9824817807382, 48.9824817807382, 48.9824817807382, 51.0019185064708, 51.0019185064708, 51.0019185064708, 51.0019185064708, 51.0019185064708, 65.9999999999999, 71.8735541744287, 82.3535742388261, 82.3535742388261, 82.3535742388261, 82.3535742388261, 92.7251407107177};
out.clear();
FastLowessSmoothing::lowess(x, y, out);
for (Size i = 0; i < out.size(); ++i)
{
TEST_REAL_SIMILAR(out[i], expected_3[i]);
}
out.clear();
FastLowessSmoothing::lowess(x, y, 0.2, 3, delta, out);
for (Size i = 0; i < out.size(); ++i)
{
TEST_REAL_SIMILAR(out[i], expected_4[i]);
}
}
END_SECTION
// trying to fit a quadratic function -> wont work so well, obviously
TOLERANCE_RELATIVE(1.06);
START_SECTION([FastLowessSmoothing]void smoothData(const DoubleVector&, const DoubleVector&, DoubleVector&))
{
std::vector<double> x, y, y_noisy, out, expect;
//exact data -> sample many points
for (Size i = 1; i <= 10000; ++i)
{
x.push_back(i/500.0);
y.push_back(targetFunction(i/500.0));
expect.push_back(targetFunction(i/500.0));
}
//noisy data
// make some noise
boost::random::mt19937 rnd_gen_;
for (Size i = 0; i < y.size(); ++i)
{
boost::normal_distribution<float> udist (y.at(i), 0.05);
y_noisy.push_back( udist(rnd_gen_) );
}
FastLowessSmoothing::lowess(x, y, 0.02, 3, 0.2, out);
for (Size i = 0; i < out.size(); ++i)
{
TEST_REAL_SIMILAR(out[i], expect[i]);
}
out.clear();
FastLowessSmoothing::lowess(x, y_noisy, 0.02, 3, 0.2, out);
for (Size i = 0; i < out.size(); ++i)
{
TEST_REAL_SIMILAR(out[i], expect[i]);
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| 45.464567 | 917 | 0.620887 | [
"vector"
] |
b98627f2fdeb5eb93055f43702af278c8638d510 | 590 | cpp | C++ | Codeforces/615A.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | Codeforces/615A.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | Codeforces/615A.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main(){
int a, b, cnt = 0, ans = 1 ;
vector<int>vec;
cin >> a >> b;
for ( int i = 0 ; i < a ; i++ ){
int x;
cin >> x;
for ( int j = 0 ; j < x ; j++){
int y;
cin >> y ;
vec.push_back(y);
cnt ++;
}
}
sort (vec.begin(), vec.end());
for ( int i = 0 ;i < cnt ; i++ ){
if ( vec[i] == ans)
ans ++ ;
if ( (ans - 1) == b){
cout << "YES";
return 0;
}
}
cout << "NO";
}
| 17.352941 | 39 | 0.328814 | [
"vector"
] |
b9866feaf8071a3d0801a69cf71dc7d8ad4515d9 | 43,650 | cpp | C++ | boost_1_57_0/libs/geometry/test/algorithms/disjoint_coverage.cpp | MisterTea/HyperNEAT | 516fef725621991ee709eb9b4afe40e0ce82640d | [
"BSD-3-Clause"
] | 85 | 2015-02-08T20:36:17.000Z | 2021-11-14T20:38:31.000Z | libs/boost/libs/geometry/test/algorithms/disjoint_coverage.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/boost/libs/geometry/test/algorithms/disjoint_coverage.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 27 | 2015-01-28T16:33:30.000Z | 2021-08-12T05:04:39.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2014, Oracle and/or its affiliates.
// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
#ifndef BOOST_TEST_MODULE
#define BOOST_TEST_MODULE test_disjoint_coverage
#endif
// unit test to test disjoint for all geometry combinations
#include <iostream>
#include <boost/test/included/unit_test.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/multi/core/tags.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/io/wkt/read.hpp>
#include <boost/geometry/io/wkt/write.hpp>
#include <boost/geometry/multi/io/wkt/read.hpp>
#include <boost/geometry/multi/io/wkt/write.hpp>
#include <boost/geometry/io/dsv/write.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/segment.hpp>
#include <boost/geometry/geometries/linestring.hpp>
#include <boost/geometry/geometries/ring.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/multi/geometries/multi_point.hpp>
#include <boost/geometry/multi/geometries/multi_linestring.hpp>
#include <boost/geometry/multi/geometries/multi_polygon.hpp>
#include <boost/geometry/algorithms/disjoint.hpp>
#include "from_wkt.hpp"
#ifdef HAVE_TTMATH
#include <boost/geometry/extensions/contrib/ttmath_stub.hpp>
#endif
namespace bg = ::boost::geometry;
//============================================================================
template <typename Geometry, typename Tag = typename bg::tag<Geometry>::type>
struct pretty_print_geometry
{
static inline std::ostream& apply(Geometry const& geometry)
{
std::cout << bg::wkt(geometry);
return std::cout;
}
};
template <typename Segment>
struct pretty_print_geometry<Segment, bg::segment_tag>
{
static inline std::ostream& apply(Segment const& segment)
{
std::cout << "SEGMENT" << bg::dsv(segment);
return std::cout;
}
};
template <typename Ring>
struct pretty_print_geometry<Ring, bg::ring_tag>
{
static inline std::ostream& apply(Ring const& ring)
{
std::cout << "RING" << bg::dsv(ring);
return std::cout;
}
};
template <typename Box>
struct pretty_print_geometry<Box, bg::box_tag>
{
static inline std::ostream& apply(Box const& box)
{
std::cout << "BOX" << bg::dsv(box);
return std::cout;
}
};
//============================================================================
struct test_disjoint
{
template <typename Geometry1, typename Geometry2>
static inline void apply(Geometry1 const& geometry1,
Geometry2 const& geometry2,
bool expected_result)
{
bool result = bg::disjoint(geometry1, geometry2);
BOOST_CHECK( result == expected_result );
result = bg::disjoint(geometry2, geometry1);
BOOST_CHECK( result == expected_result );
#ifdef BOOST_GEOMETRY_TEST_DEBUG
std::cout << "G1 - G2: ";
pretty_print_geometry<Geometry1>::apply(geometry1) << " - ";
pretty_print_geometry<Geometry2>::apply(geometry2) << std::endl;
std::cout << std::boolalpha;
std::cout << "expected/computed result: "
<< expected_result << " / " << result << std::endl;
std::cout << std::endl;
std::cout << std::noboolalpha;
#endif
}
};
//============================================================================
// pointlike-pointlike geometries
template <typename P>
inline void test_point_point()
{
typedef test_disjoint tester;
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<P>("POINT(0 0)"),
false);
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<P>("POINT(1 1)"),
true);
}
template <typename P>
inline void test_point_multipoint()
{
typedef bg::model::multi_point<P> MP;
typedef test_disjoint tester;
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<MP>("MULTIPOINT(0 0,1 1)"),
false);
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<MP>("MULTIPOINT(1 1,2 2)"),
true);
}
template <typename P>
inline void test_multipoint_multipoint()
{
typedef bg::model::multi_point<P> MP;
typedef test_disjoint tester;
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,1 0)"),
from_wkt<MP>("MULTIPOINT(0 0,1 1)"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,1 0)"),
from_wkt<MP>("MULTIPOINT(1 1,2 2)"),
true);
}
//============================================================================
// pointlike-linear geometries
template <typename P>
inline void test_point_segment()
{
typedef test_disjoint tester;
typedef bg::model::segment<P> S;
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<S>("SEGMENT(0 0,2 0)"),
false);
tester::apply(from_wkt<P>("POINT(1 0)"),
from_wkt<S>("SEGMENT(0 0,2 0)"),
false);
tester::apply(from_wkt<P>("POINT(1 1)"),
from_wkt<S>("SEGMENT(0 0,2 0)"),
true);
}
template <typename P>
inline void test_point_linestring()
{
typedef bg::model::linestring<P> L;
typedef test_disjoint tester;
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
false);
tester::apply(from_wkt<P>("POINT(1 1)"),
from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
false);
tester::apply(from_wkt<P>("POINT(3 3)"),
from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
false);
tester::apply(from_wkt<P>("POINT(1 0)"),
from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
true);
}
template <typename P>
inline void test_point_multilinestring()
{
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef test_disjoint tester;
tester::apply(from_wkt<P>("POINT(0 1)"),
from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
true);
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
false);
tester::apply(from_wkt<P>("POINT(1 1)"),
from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
false);
tester::apply(from_wkt<P>("POINT(1 0)"),
from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
false);
}
template <typename P>
inline void test_multipoint_segment()
{
typedef test_disjoint tester;
typedef bg::model::multi_point<P> MP;
typedef bg::model::segment<P> S;
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,1 1)"),
from_wkt<S>("SEGMENT(0 0,2 0)"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 0,1 1)"),
from_wkt<S>("SEGMENT(0 0,2 0)"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 1,2 2)"),
from_wkt<S>("SEGMENT(0 0,2 0)"),
true);
}
template <typename P>
inline void test_multipoint_linestring()
{
typedef bg::model::multi_point<P> MP;
typedef bg::model::linestring<P> L;
typedef test_disjoint tester;
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,1 0)"),
from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 0,1 1)"),
from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 0,3 3)"),
from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 0,2 0)"),
from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
true);
}
template <typename P>
inline void test_multipoint_multilinestring()
{
typedef bg::model::multi_point<P> MP;
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef test_disjoint tester;
tester::apply(from_wkt<MP>("MULTIPOINT(0 1,0 2)"),
from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
true);
tester::apply(from_wkt<MP>("POINT(0 0,1 0)"),
from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
false);
tester::apply(from_wkt<MP>("POINT(0 1,1 1)"),
from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
false);
tester::apply(from_wkt<MP>("POINT(0 1,1 0)"),
from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
false);
}
//============================================================================
// pointlike-areal geometries
template <typename P>
inline void test_point_box()
{
typedef test_disjoint tester;
typedef bg::model::box<P> B;
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<B>("BOX(0 0,1 1)"),
false);
tester::apply(from_wkt<P>("POINT(2 2)"),
from_wkt<B>("BOX(0 0,1 0)"),
true);
}
template <typename P>
inline void test_point_ring()
{
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<R>("POLYGON((0 0,1 0,0 1))"),
false);
tester::apply(from_wkt<P>("POINT(1 1)"),
from_wkt<R>("POLYGON((0 0,1 0,0 1))"),
true);
}
template <typename P>
inline void test_point_polygon()
{
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<PL>("POLYGON((0 0,1 0,0 1))"),
false);
tester::apply(from_wkt<P>("POINT(1 1)"),
from_wkt<PL>("POLYGON((0 0,1 0,0 1))"),
true);
}
template <typename P>
inline void test_point_multipolygon()
{
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<P>("POINT(0 0)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,1 0,0 1)),((2 0,3 0,2 1)))"),
false);
tester::apply(from_wkt<P>("POINT(1 1)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,1 0,0 1)),((2 0,3 0,2 1)))"),
true);
}
template <typename P>
inline void test_multipoint_box()
{
typedef test_disjoint tester;
typedef bg::model::multi_point<P> MP;
typedef bg::model::box<P> B;
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,1 1)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 1,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(3 3,4 4)"),
from_wkt<B>("BOX(0 0,2 2)"),
true);
}
template <typename P>
inline void test_multipoint_ring()
{
typedef bg::model::multi_point<P> MP;
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,1 0)"),
from_wkt<R>("POLYGON((0 0,1 0,0 1))"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 0,1 1)"),
from_wkt<R>("POLYGON((0 0,1 0,0 1))"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 1,2 2)"),
from_wkt<R>("POLYGON((0 0,1 0,0 1))"),
true);
}
template <typename P>
inline void test_multipoint_polygon()
{
typedef bg::model::multi_point<P> MP;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,1 0)"),
from_wkt<PL>("POLYGON(((0 0,1 0,0 1)))"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,2 0)"),
from_wkt<PL>("POLYGON(((0 0,1 0,0 1)))"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 1,2 0)"),
from_wkt<PL>("POLYGON(((0 0,1 0,0 1)))"),
true);
tester::apply(from_wkt<MP>("MULTIPOINT(1 1,2 3)"),
from_wkt<PL>("POLYGON(((0 0,1 0,0 1)))"),
true);
}
template <typename P>
inline void test_multipoint_multipolygon()
{
typedef bg::model::multi_point<P> MP;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,2 0)"),
from_wkt<MPL>("MULTIPOLYGON((0 0,1 0,0 1)),(2 0,3 0,2 1))"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(0 0,1 0)"),
from_wkt<MPL>("MULTIPOLYGON((0 0,1 0,0 1)),(2 0,3 0,2 1))"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 1,2 0)"),
from_wkt<MPL>("MULTIPOLYGON((0 0,1 0,0 1)),(2 0,3 0,2 1))"),
false);
tester::apply(from_wkt<MP>("MULTIPOINT(1 1,2 3)"),
from_wkt<MPL>("MULTIPOLYGON((0 0,1 0,0 1)),(2 0,3 0,2 1))"),
true);
}
//============================================================================
// linear-linear geometries
template <typename P>
inline void test_segment_segment()
{
typedef bg::model::segment<P> S;
typedef test_disjoint tester;
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<S>("SEGMENT(0 0,0 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<S>("SEGMENT(2 0,3 0)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<S>("SEGMENT(1 0,3 0)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<S>("SEGMENT(1 0,1 1)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<S>("SEGMENT(1 1,2 2)"),
true);
}
template <typename P>
inline void test_linestring_segment()
{
typedef bg::model::segment<P> S;
typedef bg::model::linestring<P> L;
typedef test_disjoint tester;
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<L>("LINESTRING(0 0,0 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<L>("LINESTRING(2 0,3 0)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<L>("LINESTRING(1 0,3 0)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<L>("LINESTRING(1 0,1 1)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<L>("LINESTRING(1 1,2 2)"),
true);
}
template <typename P>
inline void test_multilinestring_segment()
{
typedef bg::model::segment<P> S;
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef test_disjoint tester;
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((0 0,0 2))"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((2 0,3 0))"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((1 0,3 0))"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((1 0,1 1))"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((1 1,2 2))"),
true);
}
template <typename P>
inline void test_linestring_linestring()
{
typedef bg::model::linestring<P> L;
typedef test_disjoint tester;
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<L>("LINESTRING(0 0,0 2)"),
false);
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<L>("LINESTRING(2 0,3 0)"),
false);
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<L>("LINESTRING(1 0,3 0)"),
false);
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<L>("LINESTRING(1 0,1 1)"),
false);
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<L>("LINESTRING(1 1,2 2)"),
true);
}
template <typename P>
inline void test_linestring_multilinestring()
{
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef test_disjoint tester;
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((0 0,0 2))"),
false);
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((2 0,3 0))"),
false);
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((1 0,3 0))"),
false);
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((1 0,1 1))"),
false);
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<ML>("MULTILINESTRING((1 1,2 2))"),
true);
}
template <typename P>
inline void test_multilinestring_multilinestring()
{
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef test_disjoint tester;
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<ML>("MULTILINESTRING((0 0,0 2))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<ML>("MULTILINESTRING((2 0,3 0))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<ML>("MULTILINESTRING((1 0,3 0))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<ML>("MULTILINESTRING((1 0,1 1))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<ML>("MULTILINESTRING((1 1,2 2))"),
true);
}
//============================================================================
// linear-areal geometries
template <typename P>
inline void test_segment_box()
{
typedef bg::model::segment<P> S;
typedef bg::model::box<P> B;
typedef test_disjoint tester;
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(1 1,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(2 2,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(4 4,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
true);
tester::apply(from_wkt<S>("SEGMENT(0 4,4 4)"),
from_wkt<B>("BOX(0 0,2 2)"),
true);
tester::apply(from_wkt<S>("SEGMENT(4 0,4 4)"),
from_wkt<B>("BOX(0 0,2 2)"),
true);
tester::apply(from_wkt<S>("SEGMENT(0 -2,0 -1)"),
from_wkt<B>("BOX(0 0,1 1)"),
true);
tester::apply(from_wkt<S>("SEGMENT(-2 -2,-2 -1)"),
from_wkt<B>("BOX(0 0,1 1)"),
true);
tester::apply(from_wkt<S>("SEGMENT(-2 -2,-2 -2)"),
from_wkt<B>("BOX(0 0,1 1)"),
true);
tester::apply(from_wkt<S>("SEGMENT(-2 0,-2 0)"),
from_wkt<B>("BOX(0 0,1 1)"),
true);
tester::apply(from_wkt<S>("SEGMENT(0 -2,0 -2)"),
from_wkt<B>("BOX(0 0,1 1)"),
true);
tester::apply(from_wkt<S>("SEGMENT(-2 0,-1 0)"),
from_wkt<B>("BOX(0 0,1 1)"),
true);
// segment degenerates to a point
tester::apply(from_wkt<S>("SEGMENT(0 0,0 0)"),
from_wkt<B>("BOX(0 0,1 1)"),
false);
tester::apply(from_wkt<S>("SEGMENT(1 1,1 1)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(2 2,2 2)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(2 0,2 0)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(0 2,0 2)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<S>("SEGMENT(2 2,2 2)"),
from_wkt<B>("BOX(0 0,1 1)"),
true);
}
template <typename P>
inline void test_segment_ring()
{
typedef bg::model::segment<P> S;
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<S>("SEGMENT(1 0,3 3)"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<S>("SEGMENT(1 1,3 3)"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<S>("SEGMENT(2 2,3 3)"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
true);
}
template <typename P>
inline void test_segment_polygon()
{
typedef bg::model::segment<P> S;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<S>("SEGMENT(1 0,3 3)"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<S>("SEGMENT(1 1,3 3)"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<S>("SEGMENT(2 2,3 3)"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
true);
}
template <typename P>
inline void test_segment_multipolygon()
{
typedef bg::model::segment<P> S;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<S>("SEGMENT(0 0,2 0)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<S>("SEGMENT(1 0,3 3)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<S>("SEGMENT(1 1,3 3)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<S>("SEGMENT(2 2,3 3)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
true);
}
template <typename P>
inline void test_linestring_box()
{
typedef bg::model::linestring<P> L;
typedef bg::model::box<P> B;
typedef test_disjoint tester;
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<L>("LINESTRING(1 1,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<L>("LINESTRING(2 2,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<L>("LINESTRING(4 4,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
true);
}
template <typename P>
inline void test_linestring_ring()
{
typedef bg::model::linestring<P> L;
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<L>("LINESTRING(1 0,3 3)"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<L>("LINESTRING(1 1,3 3)"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<L>("LINESTRING(2 2,3 3)"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
true);
}
template <typename P>
inline void test_linestring_polygon()
{
typedef bg::model::linestring<P> L;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<L>("LINESTRING(1 0,3 3)"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<L>("LINESTRING(1 1,3 3)"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<L>("LINESTRING(2 2,3 3)"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
true);
}
template <typename P>
inline void test_linestring_multipolygon()
{
typedef bg::model::linestring<P> L;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<L>("LINESTRING(0 0,2 0)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<L>("LINESTRING(1 0,3 3)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<L>("LINESTRING(1 1,3 3)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<L>("LINESTRING(2 2,3 3)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
true);
}
template <typename P>
inline void test_multilinestring_box()
{
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef bg::model::box<P> B;
typedef test_disjoint tester;
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((1 1,3 3))"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((2 2,3 3))"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((4 4,3 3))"),
from_wkt<B>("BOX(0 0,2 2)"),
true);
}
template <typename P>
inline void test_multilinestring_ring()
{
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((1 0,3 3))"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((1 1,3 3))"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((2 2,3 3))"),
from_wkt<R>("POLYGON((0 0,2 0,0 2))"),
true);
}
template <typename P>
inline void test_multilinestring_polygon()
{
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((1 0,3 3))"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((1 1,3 3))"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((2 2,3 3))"),
from_wkt<PL>("POLYGON((0 0,2 0,0 2))"),
true);
}
template <typename P>
inline void test_multilinestring_multipolygon()
{
typedef bg::model::linestring<P> L;
typedef bg::model::multi_linestring<L> ML;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<ML>("MULTILINESTRING((0 0,2 0))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((1 0,3 3))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((1 1,3 3))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
false);
tester::apply(from_wkt<ML>("MULTILINESTRING((2 2,3 3))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,0 2)))"),
true);
}
//============================================================================
// areal-areal geometries
template <typename P>
inline void test_box_box()
{
typedef bg::model::box<P> B;
typedef test_disjoint tester;
tester::apply(from_wkt<B>("BOX(2 2,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<B>("BOX(1 1,3 3)"),
from_wkt<B>("BOX(0 0,2 2)"),
false);
tester::apply(from_wkt<B>("BOX(3 3,4 4)"),
from_wkt<B>("BOX(0 0,2 2)"),
true);
}
template <typename P>
inline void test_ring_box()
{
typedef bg::model::box<P> B;
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<B>("BOX(2 2,3 3)"),
from_wkt<R>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<B>("BOX(1 1,3 3)"),
from_wkt<R>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<B>("BOX(3 3,4 4)"),
from_wkt<R>("POLYGON((0 0,2 0,2 2,0 2))"),
true);
}
template <typename P>
inline void test_polygon_box()
{
typedef bg::model::box<P> B;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<B>("BOX(2 2,3 3)"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<B>("BOX(1 1,3 3)"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<B>("BOX(3 3,4 4)"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
true);
}
template <typename P>
inline void test_multipolygon_box()
{
typedef bg::model::box<P> B;
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<B>("BOX(2 2,3 3)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
false);
tester::apply(from_wkt<B>("BOX(1 1,3 3)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
false);
tester::apply(from_wkt<B>("BOX(3 3,4 4)"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
true);
}
template <typename P>
inline void test_ring_ring()
{
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<R>("POLYGON((2 2,2 3,3 3,3 2))"),
from_wkt<R>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<R>("POLYGON((1 1,1 3,3 3,3 1))"),
from_wkt<R>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<R>("POLYGON((3 3,3 4,4 4,4 3))"),
from_wkt<R>("POLYGON((0 0,2 0,2 2,0 2))"),
true);
}
template <typename P>
inline void test_polygon_ring()
{
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<R>("POLYGON((2 2,2 3,3 3,3 2))"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<R>("POLYGON((1 1,1 3,3 3,3 1))"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<R>("POLYGON((3 3,3 4,4 4,4 3))"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
true);
}
template <typename P>
inline void test_multipolygon_ring()
{
typedef bg::model::ring<P, false, false> R; // ccw, open
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<R>("POLYGON((2 2,2 3,3 3,3 2))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
false);
tester::apply(from_wkt<R>("POLYGON((1 1,1 3,3 3,3 1))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
false);
tester::apply(from_wkt<R>("POLYGON((3 3,3 4,4 4,4 3))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
true);
}
template <typename P>
inline void test_polygon_polygon()
{
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef test_disjoint tester;
tester::apply(from_wkt<PL>("POLYGON((2 2,2 3,3 3,3 2))"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<PL>("POLYGON((1 1,1 3,3 3,3 1))"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
false);
tester::apply(from_wkt<PL>("POLYGON((3 3,3 4,4 4,4 3))"),
from_wkt<PL>("POLYGON((0 0,2 0,2 2,0 2))"),
true);
tester::apply(from_wkt<PL>("POLYGON((0 0,9 0,9 9,0 9))"),
from_wkt<PL>("POLYGON((3 3,6 3,6 6,3 6))"),
false);
// polygon with a hole which entirely contains the other polygon
tester::apply(from_wkt<PL>("POLYGON((0 0,9 0,9 9,0 9),(2 2,2 7,7 7,7 2))"),
from_wkt<PL>("POLYGON((3 3,6 3,6 6,3 6))"),
true);
// polygon with a hole, but the inner ring intersects the other polygon
tester::apply(from_wkt<PL>("POLYGON((0 0,9 0,9 9,0 9),(3 2,3 7,7 7,7 2))"),
from_wkt<PL>("POLYGON((2 3,6 3,6 6,2 6))"),
false);
// polygon with a hole, but the other polygon is entirely contained
// between the inner and outer rings.
tester::apply(from_wkt<PL>("POLYGON((0 0,9 0,9 9,0 9),(6 2,6 7,7 7,7 2))"),
from_wkt<PL>("POLYGON((3 3,5 3,5 6,3 6))"),
false);
// polygon with a hole and the outer ring of the other polygon lies
// between the inner and outer, but without touching either.
tester::apply(from_wkt<PL>("POLYGON((0 0,9 0,9 9,0 9),(3 3,3 6,6 6,6 3))"),
from_wkt<PL>("POLYGON((2 2,7 2,7 7,2 7))"),
false);
}
template <typename P>
inline void test_polygon_multipolygon()
{
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<PL>("POLYGON((2 2,2 3,3 3,3 2))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
false);
tester::apply(from_wkt<PL>("POLYGON((1 1,1 3,3 3,3 1))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
false);
tester::apply(from_wkt<PL>("POLYGON((3 3,3 4,4 4,4 3))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
true);
}
template <typename P>
inline void test_multipolygon_multipolygon()
{
typedef bg::model::polygon<P, false, false> PL; // ccw, open
typedef bg::model::multi_polygon<PL> MPL;
typedef test_disjoint tester;
tester::apply(from_wkt<MPL>("MULTIPOLYGON(((2 2,2 3,3 3,3 2)))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
false);
tester::apply(from_wkt<MPL>("MULTIPOLYGON(((1 1,1 3,3 3,3 1)))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
false);
tester::apply(from_wkt<MPL>("MULTIPOLYGON(((3 3,3 4,4 4,4 3)))"),
from_wkt<MPL>("MULTIPOLYGON(((0 0,2 0,2 2,0 2)))"),
true);
}
//============================================================================
template <typename CoordinateType>
inline void test_pointlike_pointlike()
{
typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;
test_point_point<point_type>();
// not implemented yet
// test_point_multipoint<point_type>();
// test_multipoint_multipoint<point_type>();
}
template <typename CoordinateType>
inline void test_pointlike_linear()
{
typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;
test_point_linestring<point_type>();
test_point_multilinestring<point_type>();
test_point_segment<point_type>();
// not implemented yet
// test_multipoint_linestring<point_type>();
// test_multipoint_multilinestring<point_type>();
// test_multipoint_segment<point_type>();
}
template <typename CoordinateType>
inline void test_pointlike_areal()
{
typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;
test_point_polygon<point_type>();
test_point_multipolygon<point_type>();
test_point_ring<point_type>();
test_point_box<point_type>();
// not implemented yet
// test_multipoint_polygon<point_type>();
// test_multipoint_multipolygon<point_type>();
// test_multipoint_ring<point_type>();
// test_multipoint_box<point_type>();
}
template <typename CoordinateType>
inline void test_linear_linear()
{
typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;
test_linestring_linestring<point_type>();
test_linestring_multilinestring<point_type>();
test_linestring_segment<point_type>();
test_multilinestring_multilinestring<point_type>();
test_multilinestring_segment<point_type>();
test_segment_segment<point_type>();
}
template <typename CoordinateType>
inline void test_linear_areal()
{
typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;
test_segment_polygon<point_type>();
test_segment_multipolygon<point_type>();
test_segment_ring<point_type>();
test_segment_box<point_type>();
test_linestring_polygon<point_type>();
test_linestring_multipolygon<point_type>();
test_linestring_ring<point_type>();
test_linestring_box<point_type>();
test_multilinestring_polygon<point_type>();
test_multilinestring_multipolygon<point_type>();
test_multilinestring_ring<point_type>();
test_multilinestring_box<point_type>();
}
template <typename CoordinateType>
inline void test_areal_areal()
{
typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;
test_polygon_polygon<point_type>();
test_polygon_multipolygon<point_type>();
test_polygon_ring<point_type>();
test_polygon_box<point_type>();
test_multipolygon_multipolygon<point_type>();
test_multipolygon_ring<point_type>();
test_multipolygon_box<point_type>();
test_ring_ring<point_type>();
test_ring_box<point_type>();
test_box_box<point_type>();
}
//============================================================================
BOOST_AUTO_TEST_CASE( test_pointlike_pointlike_all )
{
test_pointlike_pointlike<double>();
test_pointlike_pointlike<int>();
#ifdef HAVE_TTMATH
test_pointlike_pointlike<ttmath_big>();
#endif
}
BOOST_AUTO_TEST_CASE( test_pointlike_linear_all )
{
test_pointlike_linear<double>();
test_pointlike_linear<int>();
#ifdef HAVE_TTMATH
test_pointlike_linear<ttmath_big>();
#endif
}
BOOST_AUTO_TEST_CASE( test_pointlike_areal_all )
{
test_pointlike_areal<double>();
test_pointlike_areal<int>();
#ifdef HAVE_TTMATH
test_pointlike_areal<ttmath_big>();
#endif
}
BOOST_AUTO_TEST_CASE( test_linear_linear_all )
{
test_linear_linear<double>();
test_linear_linear<int>();
#ifdef HAVE_TTMATH
test_linear_linear<ttmath_big>();
#endif
}
BOOST_AUTO_TEST_CASE( test_linear_areal_all )
{
test_linear_areal<double>();
test_linear_areal<int>();
#ifdef HAVE_TTMATH
test_linear_areal<ttmath_big>();
#endif
}
BOOST_AUTO_TEST_CASE( test_areal_areal_all )
{
test_areal_areal<double>();
test_areal_areal<int>();
#ifdef HAVE_TTMATH
test_areal_areal<ttmath_big>();
#endif
}
| 31.023454 | 82 | 0.523597 | [
"geometry",
"model"
] |
b9869044096c2478db4d5c263679ddaa8a89e928 | 21,193 | cpp | C++ | ccmain/ltrresultiterator.cpp | ma7euus/tesseract-ocr | 22d6462c5b8a26cae2f90cc6d20d16b57c6b6ef8 | [
"Apache-2.0"
] | null | null | null | ccmain/ltrresultiterator.cpp | ma7euus/tesseract-ocr | 22d6462c5b8a26cae2f90cc6d20d16b57c6b6ef8 | [
"Apache-2.0"
] | null | null | null | ccmain/ltrresultiterator.cpp | ma7euus/tesseract-ocr | 22d6462c5b8a26cae2f90cc6d20d16b57c6b6ef8 | [
"Apache-2.0"
] | null | null | null | ///////////////////////////////////////////////////////////////////////
// File: ltrresultiterator.cpp
// Description: Iterator for tesseract results in strict left-to-right
// order that avoids using tesseract internal data structures.
// Author: Ray Smith
// Created: Fri Feb 26 14:32:09 PST 2010
//
// (C) Copyright 2010, Google 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 "ltrresultiterator.h"
#include "allheaders.h"
#include "pageres.h"
#include "strngs.h"
#include "tesseractclass.h"
namespace tesseract {
LTRResultIterator::LTRResultIterator(PAGE_RES* page_res, Tesseract* tesseract,
int scale, int scaled_yres,
int rect_left, int rect_top,
int rect_width, int rect_height)
: PageIterator(page_res, tesseract, scale, scaled_yres,
rect_left, rect_top, rect_width, rect_height),
line_separator_("\n"),
paragraph_separator_("\n") {
}
LTRResultIterator::~LTRResultIterator() {
}
// Returns the null terminated UTF-8 encoded text string for the current
// object at the given level. Use delete [] to free after use.
char* LTRResultIterator::GetUTF8Text_APP(PageIteratorLevel level, const char* id_user, const char* id_img, int* word_count) const {
if (it_->word() == NULL) return NULL; // Already at the end!
STRING text;
PAGE_RES_IT res_it(*it_);
WERD_CHOICE* best_choice = res_it.word()->best_choice;
ASSERT_HOST(best_choice != NULL);
if (level == RIL_SYMBOL) {
text = res_it.word()->BestUTF8(blob_index_, false);
} else if (level == RIL_WORD) {
text = best_choice->unichar_string();
} else {
bool eol = false; // end of line?
bool eop = false; // end of paragraph?
do { // for each paragraph in a block
do { // for each text line in a paragraph
do { // for each word in a text line
STRING word_info_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
best_choice = res_it.word()->best_choice;
// IMPLEMENTACAO APP ==========================================
TBOX box = res_it.word()->word->bounding_box();
int left, top, right, bottom;
const int pix_height = pixGetHeight(res_it.word()->tesseract->pix_binary());
const int pix_width = pixGetWidth(res_it.word()->tesseract->pix_binary());
left = ClipToRange(static_cast<int>(box.left()), 0, pix_width);
top = ClipToRange(pix_height - box.top(), 0, pix_height);
right = ClipToRange(static_cast<int>(box.right()), left, pix_width);
bottom = ClipToRange(pix_height - box.bottom(), top, pix_height);
Box* bbox = boxCreate(left, top, right - left, bottom - top);
Pix* pix = pixClipRectangle(res_it.word()->tesseract->pix_binary(), bbox, NULL);
char buf[256];
char buf_i[256];
char word_certainty[256];
//tprintf("%s : %d\n",best_choice->unichar_string().string(), pix->data);
//tprintf("%d\n", *word_count);
snprintf(buf_i, sizeof(buf_i), "%07d", *word_count);
snprintf(buf, sizeof(buf), "%s%s/%s.jpg", id_user, id_img, buf_i);
pixWrite(buf, pix, IFF_JFIF_JPEG);
pixDestroy(&pix);
boxDestroy(&bbox);
//tprintf("%s\n", buf);
// ===========================================================
snprintf(word_certainty, sizeof(word_certainty), "%f", best_choice->certainty());
word_info_xml += "<word_info>\n <text><![CDATA[";
word_info_xml += best_choice->unichar_string().string();
word_info_xml += "]]></text>\n<word_certainty>";
word_info_xml += word_certainty;
word_info_xml += "</word_certainty>\n<img_id>";
word_info_xml += buf_i;
word_info_xml += "</img_id>\n</word_info>";
*word_count = *word_count + 1;
ASSERT_HOST(best_choice != NULL);
//text += best_choice->unichar_string();
text += buf_i;
text += " ";
res_it.forward();
eol = res_it.row() != res_it.prev_row();
char outfile[256] = "";
snprintf(outfile, sizeof(outfile), "%s%s/%s.xml", id_user, id_img, buf_i);
FILE* fout = fopen(outfile, "wb");
if (fout == NULL) {
fprintf(stderr, "Cannot create output file %s\n", outfile);
exit(1);
}
fwrite(word_info_xml.string(), 1, word_info_xml.length(), fout);
fclose(fout);
} while (!eol);
text.truncate_at(text.length() - 1);
text += line_separator_;
eop = res_it.block() != res_it.prev_block() ||
res_it.row()->row->para() != res_it.prev_row()->row->para();
} while (level != RIL_TEXTLINE && !eop);
if (eop) text += paragraph_separator_;
} while (level == RIL_BLOCK && res_it.block() == res_it.prev_block());
}
int length = text.length() + 1;
char* result = new char[length];
strncpy(result, text.string(), length);
return result;
}
char* LTRResultIterator::GetUTF8Text(PageIteratorLevel level) const {
if (it_->word() == NULL) return NULL; // Already at the end!
STRING text;
PAGE_RES_IT res_it(*it_);
WERD_CHOICE* best_choice = res_it.word()->best_choice;
ASSERT_HOST(best_choice != NULL);
if (level == RIL_SYMBOL) {
text = res_it.word()->BestUTF8(blob_index_, false);
} else if (level == RIL_WORD) {
text = best_choice->unichar_string();
} else {
bool eol = false; // end of line?
bool eop = false; // end of paragraph?
int i = 0;
do { // for each paragraph in a block
do { // for each text line in a paragraph
do { // for each word in a text line
best_choice = res_it.word()->best_choice;
ASSERT_HOST(best_choice != NULL);
text += best_choice->unichar_string();
text += " ";
res_it.forward();
eol = res_it.row() != res_it.prev_row();
i++;
} while (!eol);
text.truncate_at(text.length() - 1);
text += line_separator_;
eop = res_it.block() != res_it.prev_block() ||
res_it.row()->row->para() != res_it.prev_row()->row->para();
} while (level != RIL_TEXTLINE && !eop);
if (eop) text += paragraph_separator_;
} while (level == RIL_BLOCK && res_it.block() == res_it.prev_block());
}
int length = text.length() + 1;
char* result = new char[length];
strncpy(result, text.string(), length);
return result;
}
// Set the string inserted at the end of each text line. "\n" by default.
void LTRResultIterator::SetLineSeparator(const char *new_line) {
line_separator_ = new_line;
}
// Set the string inserted at the end of each paragraph. "\n" by default.
void LTRResultIterator::SetParagraphSeparator(const char *new_para) {
paragraph_separator_ = new_para;
}
// Returns the mean confidence of the current object at the given level.
// The number should be interpreted as a percent probability. (0.0f-100.0f)
float LTRResultIterator::Confidence(PageIteratorLevel level) const {
if (it_->word() == NULL) return 0.0f; // Already at the end!
float mean_certainty = 0.0f;
int certainty_count = 0;
PAGE_RES_IT res_it(*it_);
WERD_CHOICE* best_choice = res_it.word()->best_choice;
ASSERT_HOST(best_choice != NULL);
switch (level) {
case RIL_BLOCK:
do {
best_choice = res_it.word()->best_choice;
ASSERT_HOST(best_choice != NULL);
mean_certainty += best_choice->certainty();
++certainty_count;
res_it.forward();
} while (res_it.block() == res_it.prev_block());
break;
case RIL_PARA:
do {
best_choice = res_it.word()->best_choice;
ASSERT_HOST(best_choice != NULL);
mean_certainty += best_choice->certainty();
++certainty_count;
res_it.forward();
} while (res_it.block() == res_it.prev_block() &&
res_it.row()->row->para() == res_it.prev_row()->row->para());
break;
case RIL_TEXTLINE:
do {
best_choice = res_it.word()->best_choice;
ASSERT_HOST(best_choice != NULL);
mean_certainty += best_choice->certainty();
++certainty_count;
res_it.forward();
} while (res_it.row() == res_it.prev_row());
break;
case RIL_WORD:
mean_certainty += best_choice->certainty();
++certainty_count;
break;
case RIL_SYMBOL:
BLOB_CHOICE_LIST_CLIST* choices = best_choice->blob_choices();
if (choices != NULL) {
BLOB_CHOICE_LIST_C_IT blob_choices_it(choices);
for (int blob = 0; blob < blob_index_; ++blob)
blob_choices_it.forward();
BLOB_CHOICE_IT choice_it(blob_choices_it.data());
for (choice_it.mark_cycle_pt();
!choice_it.cycled_list();
choice_it.forward()) {
if (choice_it.data()->unichar_id() ==
best_choice->unichar_id(blob_index_))
break;
}
mean_certainty += choice_it.data()->certainty();
} else {
mean_certainty += best_choice->certainty();
}
++certainty_count;
}
if (certainty_count > 0) {
mean_certainty /= certainty_count;
float confidence = 100 + 5 * mean_certainty;
if (confidence < 0.0f) confidence = 0.0f;
if (confidence > 100.0f) confidence = 100.0f;
return confidence;
}
return 0.0f;
}
// Returns the font attributes of the current word. If iterating at a higher
// level object than words, eg textlines, then this will return the
// attributes of the first word in that textline.
// The actual return value is a string representing a font name. It points
// to an internal table and SHOULD NOT BE DELETED. Lifespan is the same as
// the iterator itself, ie rendered invalid by various members of
// TessBaseAPI, including Init, SetImage, End or deleting the TessBaseAPI.
// Pointsize is returned in printers points (1/72 inch.)
const char* LTRResultIterator::WordFontAttributes(bool* is_bold,
bool* is_italic,
bool* is_underlined,
bool* is_monospace,
bool* is_serif,
bool* is_smallcaps,
int* pointsize,
int* font_id) const {
if (it_->word() == NULL) return NULL; // Already at the end!
if (it_->word()->fontinfo == NULL) {
*font_id = -1;
return NULL; // No font information.
}
const FontInfo& font_info = *it_->word()->fontinfo;
*font_id = font_info.universal_id;
*is_bold = font_info.is_bold();
*is_italic = font_info.is_italic();
*is_underlined = false; // TODO(rays) fix this!
*is_monospace = font_info.is_fixed_pitch();
*is_serif = font_info.is_serif();
*is_smallcaps = it_->word()->small_caps;
float row_height = it_->row()->row->x_height() +
it_->row()->row->ascenders() - it_->row()->row->descenders();
// Convert from pixels to printers points.
*pointsize = scaled_yres_ > 0
? static_cast<int> (row_height * kPointsPerInch / scaled_yres_ + 0.5)
: 0;
return font_info.name;
}
// Returns the name of the language used to recognize this word.
const char* LTRResultIterator::WordRecognitionLanguage() const {
if (it_->word() == NULL || it_->word()->tesseract == NULL) return NULL;
return it_->word()->tesseract->lang.string();
}
// Return the overall directionality of this word.
StrongScriptDirection LTRResultIterator::WordDirection() const {
if (it_->word() == NULL) return DIR_NEUTRAL;
bool has_rtl = it_->word()->AnyRtlCharsInWord();
bool has_ltr = it_->word()->AnyLtrCharsInWord();
if (has_rtl && !has_ltr)
return DIR_RIGHT_TO_LEFT;
if (has_ltr && !has_rtl)
return DIR_LEFT_TO_RIGHT;
if (!has_ltr && !has_rtl)
return DIR_NEUTRAL;
return DIR_MIX;
}
// Returns true if the current word was found in a dictionary.
bool LTRResultIterator::WordIsFromDictionary() const {
if (it_->word() == NULL) return false; // Already at the end!
int permuter = it_->word()->best_choice->permuter();
return permuter == SYSTEM_DAWG_PERM || permuter == FREQ_DAWG_PERM ||
permuter == USER_DAWG_PERM;
}
// Returns true if the current word is numeric.
bool LTRResultIterator::WordIsNumeric() const {
if (it_->word() == NULL) return false; // Already at the end!
int permuter = it_->word()->best_choice->permuter();
return permuter == NUMBER_PERM;
}
// Returns true if the word contains blamer information.
bool LTRResultIterator::HasBlamerInfo() const {
return (it_->word() != NULL && it_->word()->blamer_bundle != NULL &&
(it_->word()->blamer_bundle->debug.length() > 0 ||
it_->word()->blamer_bundle->misadaption_debug.length() > 0));
}
// Returns the pointer to ParamsTrainingBundle stored in the BlamerBundle
// of the current word.
void *LTRResultIterator::GetParamsTrainingBundle() const {
return (it_->word() != NULL && it_->word()->blamer_bundle != NULL) ?
&(it_->word()->blamer_bundle->params_training_bundle) : NULL;
}
// Returns the pointer to the string with blamer information for this word.
// Assumes that the word's blamer_bundle is not NULL.
const char *LTRResultIterator::GetBlamerDebug() const {
return it_->word()->blamer_bundle->debug.string();
}
// Returns the pointer to the string with misadaption information for this word.
// Assumes that the word's blamer_bundle is not NULL.
const char *LTRResultIterator::GetBlamerMisadaptionDebug() const {
return it_->word()->blamer_bundle->misadaption_debug.string();
}
// Returns the null terminated UTF-8 encoded truth string for the current word.
// Use delete [] to free after use.
char* LTRResultIterator::WordTruthUTF8Text() const {
if (it_->word() == NULL) return NULL; // Already at the end!
if (it_->word()->blamer_bundle == NULL ||
it_->word()->blamer_bundle->incorrect_result_reason == IRR_NO_TRUTH) {
return NULL; // no truth information for this word
}
const GenericVector<STRING> &truth_vec =
it_->word()->blamer_bundle->truth_text;
STRING truth_text;
for (int i = 0; i < truth_vec.size(); ++i) truth_text += truth_vec[i];
int length = truth_text.length() + 1;
char* result = new char[length];
strncpy(result, truth_text.string(), length);
return result;
}
// Returns a pointer to serialized choice lattice.
// Fills lattice_size with the number of bytes in lattice data.
const char *LTRResultIterator::WordLattice(int *lattice_size) const {
if (it_->word() == NULL) return NULL; // Already at the end!
if (it_->word()->blamer_bundle == NULL) return NULL;
*lattice_size = it_->word()->blamer_bundle->lattice_size;
return it_->word()->blamer_bundle->lattice_data;
}
// Returns true if the current symbol is a superscript.
// If iterating at a higher level object than symbols, eg words, then
// this will return the attributes of the first symbol in that word.
bool LTRResultIterator::SymbolIsSuperscript() const {
if (cblob_it_ == NULL && it_->word() != NULL)
return it_->word()->box_word->BlobPosition(blob_index_) == SP_SUPERSCRIPT;
return false;
}
// Returns true if the current symbol is a subscript.
// If iterating at a higher level object than symbols, eg words, then
// this will return the attributes of the first symbol in that word.
bool LTRResultIterator::SymbolIsSubscript() const {
if (cblob_it_ == NULL && it_->word() != NULL)
return it_->word()->box_word->BlobPosition(blob_index_) == SP_SUBSCRIPT;
return false;
}
// Returns true if the current symbol is a dropcap.
// If iterating at a higher level object than symbols, eg words, then
// this will return the attributes of the first symbol in that word.
bool LTRResultIterator::SymbolIsDropcap() const {
if (cblob_it_ == NULL && it_->word() != NULL)
return it_->word()->box_word->BlobPosition(blob_index_) == SP_DROPCAP;
return false;
}
ChoiceIterator::ChoiceIterator(const LTRResultIterator& result_it) {
ASSERT_HOST(result_it.it_->word() != NULL);
word_res_ = result_it.it_->word();
PAGE_RES_IT res_it(*result_it.it_);
WERD_CHOICE* best_choice = word_res_->best_choice;
BLOB_CHOICE_LIST_CLIST* choices = best_choice->blob_choices();
if (choices != NULL) {
BLOB_CHOICE_LIST_C_IT blob_choices_it(choices);
for (int blob = 0; blob < result_it.blob_index_; ++blob)
blob_choices_it.forward();
choice_it_ = new BLOB_CHOICE_IT(blob_choices_it.data());
choice_it_->mark_cycle_pt();
} else {
choice_it_ = NULL;
}
}
ChoiceIterator::~ChoiceIterator() {
delete choice_it_;
}
// Moves to the next choice for the symbol and returns false if there
// are none left.
bool ChoiceIterator::Next() {
if (choice_it_ == NULL)
return false;
choice_it_->forward();
return !choice_it_->cycled_list();
}
// Returns the null terminated UTF-8 encoded text string for the current
// choice. Use delete [] to free after use.
const char* ChoiceIterator::GetUTF8Text() const {
if (choice_it_ == NULL)
return NULL;
UNICHAR_ID id = choice_it_->data()->unichar_id();
return word_res_->uch_set->id_to_unichar_ext(id);
}
// Returns the confidence of the current choice.
// The number should be interpreted as a percent probability. (0.0f-100.0f)
float ChoiceIterator::Confidence() const {
if (choice_it_ == NULL)
return 0.0f;
float confidence = 100 + 5 * choice_it_->data()->certainty();
if (confidence < 0.0f) confidence = 0.0f;
if (confidence > 100.0f) confidence = 100.0f;
return confidence;
}
}
// namespace tesseract.
| 43.96888 | 135 | 0.550606 | [
"object"
] |
b98a59bd62a84469ff5ee94557cb2d53f41f42d0 | 2,327 | cpp | C++ | src/mc/MinecraftRegion.cpp | pufmat/PirateMap | 8f97ad791cf07fd085642c3dedb0bb317a33a8e6 | [
"Apache-2.0"
] | null | null | null | src/mc/MinecraftRegion.cpp | pufmat/PirateMap | 8f97ad791cf07fd085642c3dedb0bb317a33a8e6 | [
"Apache-2.0"
] | null | null | null | src/mc/MinecraftRegion.cpp | pufmat/PirateMap | 8f97ad791cf07fd085642c3dedb0bb317a33a8e6 | [
"Apache-2.0"
] | null | null | null | #include "MinecraftRegion.h"
#include "BufferedReader.h"
#include "nbt/NBTTag.h"
#include <algorithm>
#include <stdexcept>
#include <zlib.h>
#include <iostream>
static const int BUFFER_SIZE = 2048;
MinecraftRegion::MinecraftRegion(const std::string& path){
stream.open(path);
}
void MinecraftRegion::getChunks(std::function<void(const std::unique_ptr<NBTTag>&)> callback){
std::vector<uint_least32_t> locations;
byte buffer[BUFFER_SIZE];
for(int i = 0; i < 32 * 32; ++i){
stream.read(reinterpret_cast<char*>(buffer), 4);
uint_least32_t location = (static_cast<uint_least32_t>(buffer[0]) << 16) | (static_cast<uint_least32_t>(buffer[1]) << 8) | static_cast<uint_least32_t>(buffer[2]);
char size = buffer[3];
if(size > 0){
locations.push_back(location * 4096);
}
}
//ignore timestamps
stream.ignore(4096);
std::sort(locations.begin(), locations.end(), std::less<uint_least32_t>());
uint_least32_t read = 2 * 4096;
for(uint_least32_t location : locations){
//jump to location
stream.ignore(location - read);
read = location;
stream.read(reinterpret_cast<char*>(buffer), 5);
uint_least32_t compressedSize = (static_cast<uint_least32_t>(buffer[0]) << 24) | (static_cast<uint_least32_t>(buffer[1]) << 16) | (static_cast<uint_least32_t>(buffer[2]) << 8) | static_cast<uint_least32_t>(buffer[3]);
compressedSize -= 1;
byte compressionType = buffer[4];
if(compressionType != 2){
throw std::runtime_error("Unknown compression type!");
}else{
std::unique_ptr<byte[]> compressedBuffer(new byte[compressedSize]);
stream.read(reinterpret_cast<char*>(compressedBuffer.get()), compressedSize);
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL;
infstream.avail_in = compressedSize;
infstream.next_in = compressedBuffer.get();
inflateInit(&infstream);
BufferedReader br([&infstream, &br, &buffer](){
infstream.avail_out = BUFFER_SIZE;
infstream.next_out = buffer;
if(inflate(&infstream, Z_NO_FLUSH) != Z_OK){
//throw std::runtime_error("Decompression error!");
}
br.setBuffer(buffer, BUFFER_SIZE - infstream.avail_out);
});
callback(NBTTag::parse(br));
inflateEnd(&infstream);
}
read += 4 + 1 + compressedSize;
}
}
MinecraftRegion::~MinecraftRegion(){
}
| 25.571429 | 219 | 0.702621 | [
"vector"
] |
b98beb3e62df5f6311372a91250dad53277d389a | 11,014 | cpp | C++ | Engine/Source/Editor/MeshPaint/Private/IMeshPainter.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Editor/MeshPaint/Private/IMeshPainter.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Editor/MeshPaint/Private/IMeshPainter.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "IMeshPainter.h"
#include "Editor.h"
#include "IMeshPaintGeometryAdapter.h"
#include "MeshPaintSettings.h"
#include "MeshPainterCommands.h"
#include "MeshPaintHelpers.h"
#include "ScopedTransaction.h"
#include "VREditorMode.h"
#include "IVREditorModule.h"
#include "ViewportWorldInteraction.h"
#include "ViewportInteractableInterface.h"
#include "ViewportInteractor.h"
#include "VREditorInteractor.h"
#include "EditorWorldExtension.h"
#include "Framework/Commands/UICommandList.h"
#include "Components/MeshComponent.h"
#include "Components/PrimitiveComponent.h"
IMeshPainter::IMeshPainter()
: CurrentViewportInteractor(nullptr), bArePainting(false), TimeSinceStartedPainting(0.0f), Time(0.0f), WidgetLineThickness(1.0f), VertexPointSize(3.5f), VertexPointColor(FLinearColor::White), HoverVertexPointColor(0.3f, 1.0f, 0.3f), PaintTransaction(nullptr)
{
FMeshPainterCommands::Register();
}
IMeshPainter::~IMeshPainter()
{
}
void IMeshPainter::RenderInteractors(const FSceneView* View, FViewport* Viewport, FPrimitiveDrawInterface* PDI, bool bRenderVertices, ESceneDepthPriorityGroup DepthGroup/* = SDPG_World*/)
{
TArray<MeshPaintHelpers::FPaintRay> PaintRays;
MeshPaintHelpers::RetrieveViewportPaintRays(View, Viewport, PDI, PaintRays);
// Apply paint pressure and start painting (or if not currently painting, draw a preview of where paint will be applied)
for (const MeshPaintHelpers::FPaintRay& PaintRay : PaintRays)
{
const UVREditorInteractor* VRInteractor = Cast<UVREditorInteractor>(PaintRay.ViewportInteractor);
EMeshPaintAction RayPaintAction = VRInteractor ? (VRInteractor->IsModifierPressed() ? EMeshPaintAction::Erase : EMeshPaintAction::Paint)
: (Viewport->KeyState(EKeys::LeftControl) || Viewport->KeyState(EKeys::RightControl)) ? EMeshPaintAction::Erase : EMeshPaintAction::Paint;
RenderInteractorWidget(PaintRay.CameraLocation, PaintRay.RayStart, PaintRay.RayDirection, PDI, RayPaintAction, bRenderVertices, DepthGroup);
}
}
void IMeshPainter::Tick(FEditorViewportClient* ViewportClient, float DeltaTime)
{
if (bArePainting)
{
TimeSinceStartedPainting += DeltaTime;
}
if (ViewportClient->IsPerspective())
{
// Make sure perspective viewports are still set to real-time
MeshPaintHelpers::SetRealtimeViewport(true);
// Set viewport show flags
MeshPaintHelpers::SetViewportColorMode(GetBrushSettings()->ColorViewMode, ViewportClient);
}
Time += DeltaTime;
}
void IMeshPainter::RegisterCommands(TSharedRef<FUICommandList> CommandList)
{
const FMeshPainterCommands& Commands = FMeshPainterCommands::Get();
// Lambda used to alter the paint brush size
auto BrushLambda = [this](float Multiplier)
{
const float BrushChangeValue = 0.05f;
float BrushRadius = GetBrushSettings()->GetBrushRadius();
BrushRadius *= (1.f + (BrushChangeValue * Multiplier));
GetBrushSettings()->SetBrushRadius(BrushRadius);
};
CommandList->MapAction(Commands.IncreaseBrushSize, FExecuteAction::CreateLambda(BrushLambda, 1.0f), FCanExecuteAction(), EUIActionRepeatMode::RepeatEnabled);
CommandList->MapAction(Commands.DecreaseBrushSize, FExecuteAction::CreateLambda(BrushLambda, -1.0f), FCanExecuteAction(), EUIActionRepeatMode::RepeatEnabled);
}
void IMeshPainter::UnregisterCommands(TSharedRef<FUICommandList> CommandList)
{
const FMeshPainterCommands& Commands = FMeshPainterCommands::Get();
for (const TSharedPtr<const FUICommandInfo> Action : Commands.Commands)
{
CommandList->UnmapAction(Action);
}
}
bool IMeshPainter::Paint(FViewport* Viewport, const FVector& InCameraOrigin, const FVector& InRayOrigin, const FVector& InRayDirection)
{
// Determine paint action according to whether or not shift is held down
const EMeshPaintAction PaintAction = (Viewport->KeyState(EKeys::LeftShift) || Viewport->KeyState(EKeys::RightShift)) ? EMeshPaintAction::Erase : EMeshPaintAction::Paint;
const float PaintStrength = Viewport->IsPenActive() ? Viewport->GetTabletPressure() : 1.f;
// Handle internal painting functionality
return PaintInternal(InCameraOrigin, InRayOrigin, InRayDirection, PaintAction, PaintStrength);
}
bool IMeshPainter::PaintVR(FViewport* Viewport, const FVector& InCameraOrigin, const FVector& InRayOrigin, const FVector& InRayDirection, UVREditorInteractor* VRInteractor)
{
bool bPaintApplied = false;
// When painting using VR, allow the modifier button to activate Erase mode
if (VRInteractor)
{
// Determine custom paint strength from trigger
const float StrengthScale = VRInteractor->GetSelectAndMoveTriggerValue();
EMeshPaintAction PaintAction;
const bool bIsModifierPressed = VRInteractor->IsModifierPressed();
// Determine paint action according to whether or not modifier button is pressed
PaintAction = bIsModifierPressed ? EMeshPaintAction::Erase : EMeshPaintAction::Paint;
// Handle internal painting functionality
bPaintApplied = PaintInternal(InCameraOrigin, InRayOrigin, InRayDirection, PaintAction, StrengthScale);
if (bPaintApplied)
{
CurrentViewportInteractor = VRInteractor;
}
}
return bPaintApplied;
}
bool IMeshPainter::InputKey(FEditorViewportClient* InViewportClient, FViewport* InViewport, FKey InKey, EInputEvent InEvent)
{
bool bHandled = false;
// Lambda used to alter the paint brush size
auto BrushLambda = [this](float Multiplier)
{
const float BrushChangeValue = 0.05f;
float BrushRadius = GetBrushSettings()->GetBrushRadius();
BrushRadius *= (1.f + (BrushChangeValue * Multiplier));
GetBrushSettings()->SetBrushRadius(BrushRadius);
};
if (InKey == EKeys::LeftBracket)
{
BrushLambda(-1.0f);
bHandled = true;
}
else if (InKey == EKeys::RightBracket)
{
BrushLambda(1.0f);
bHandled = true;
}
return bHandled;
}
void IMeshPainter::FinishPainting()
{
if (bArePainting)
{
bArePainting = false;
EndTransaction();
}
CurrentViewportInteractor = nullptr;
}
void IMeshPainter::RenderInteractorWidget(const FVector& InCameraOrigin, const FVector& InRayOrigin, const FVector& InRayDirection, FPrimitiveDrawInterface* PDI, EMeshPaintAction PaintAction, bool bRenderVertices, ESceneDepthPriorityGroup DepthGroup /*= SDPG_World*/)
{
const UPaintBrushSettings* BrushSettings = GetBrushSettings();
const float BrushRadius = BrushSettings->GetBrushRadius();
const FHitResult& HitResult = GetHitResult(InRayOrigin, InRayDirection);
const float DrawThickness = WidgetLineThickness;
const float DrawIntensity = 1.0f;
if (HitResult.Component != nullptr)
{
// Brush properties
const float BrushFalloffAmount = BrushSettings->BrushFalloffAmount;
// Display settings
const float VisualBiasDistance = 0.15f;
const float NormalLineSize(BrushRadius * 0.35f); // Make the normal line length a function of brush size
const FLinearColor NormalLineColor(0.3f, 1.0f, 0.3f);
const FLinearColor BrushCueColor = (bArePainting ? FLinearColor(1.0f, 1.0f, 0.3f) : FLinearColor(0.3f, 1.0f, 0.3f));
const FLinearColor InnerBrushCueColor = (bArePainting ? FLinearColor(0.5f, 0.5f, 0.1f) : FLinearColor(0.1f, 0.5f, 0.1f));
FVector BrushXAxis, BrushYAxis;
HitResult.Normal.FindBestAxisVectors(BrushXAxis, BrushYAxis);
const FVector BrushVisualPosition = HitResult.Location + HitResult.Normal * VisualBiasDistance;
if (PDI != NULL)
{
// Draw brush circle
const int32 NumCircleSides = 128;
DrawCircle(PDI, BrushVisualPosition, BrushXAxis, BrushYAxis, BrushCueColor, BrushRadius, NumCircleSides, DepthGroup, DrawThickness);
// Also draw the inner brush radius
const float InnerBrushRadius = (BrushRadius * BrushFalloffAmount);
DrawCircle(PDI, BrushVisualPosition, BrushXAxis, BrushYAxis, InnerBrushCueColor, InnerBrushRadius, NumCircleSides, DepthGroup, DrawThickness);
// If we just started painting then also draw a little brush effect
if (bArePainting)
{
const float EffectDuration = 0.2f;
const double CurTime = FPlatformTime::Seconds();
if (TimeSinceStartedPainting <= EffectDuration)
{
// Invert the effect if we're currently erasing
float EffectAlpha = TimeSinceStartedPainting / EffectDuration;
if (PaintAction == EMeshPaintAction::Erase)
{
EffectAlpha = 1.0f - EffectAlpha;
}
const FLinearColor EffectColor(0.1f + EffectAlpha * 0.4f, 0.1f + EffectAlpha * 0.4f, 0.1f + EffectAlpha * 0.4f);
const float EffectRadius = BrushRadius * EffectAlpha * EffectAlpha; // Squared curve here (looks more interesting)
DrawCircle(PDI, BrushVisualPosition, BrushXAxis, BrushYAxis, EffectColor, EffectRadius, NumCircleSides, DepthGroup);
}
}
// Draw trace surface normal
const FVector NormalLineEnd(BrushVisualPosition + HitResult.Normal * NormalLineSize);
PDI->DrawLine(BrushVisualPosition, NormalLineEnd, NormalLineColor, DepthGroup, DrawThickness);
TSharedPtr<IMeshPaintGeometryAdapter> MeshAdapter = GetMeshAdapterForComponent(Cast<UMeshComponent>(HitResult.Component.Get()));
if (MeshAdapter->IsValid() && bRenderVertices && MeshAdapter->SupportsVertexPaint())
{
const FMatrix ComponentToWorldMatrix = MeshAdapter->GetComponentToWorldMatrix();
const FVector ComponentSpaceCameraPosition(ComponentToWorldMatrix.InverseTransformPosition(InCameraOrigin));
const FVector ComponentSpaceBrushPosition(ComponentToWorldMatrix.InverseTransformPosition(HitResult.Location));
// @todo MeshPaint: Input vector doesn't work well with non-uniform scale
const float ComponentSpaceBrushRadius = ComponentToWorldMatrix.InverseTransformVector(FVector(BrushRadius, 0.0f, 0.0f)).Size();
const float ComponentSpaceSquaredBrushRadius = ComponentSpaceBrushRadius * ComponentSpaceBrushRadius;
const TArray<FVector>& InRangeVertices = MeshAdapter->SphereIntersectVertices(ComponentSpaceSquaredBrushRadius, ComponentSpaceBrushPosition, ComponentSpaceCameraPosition, GetBrushSettings()->bOnlyFrontFacingTriangles);
for (const FVector& Vertex : InRangeVertices)
{
const FVector WorldPositionVertex = ComponentToWorldMatrix.TransformPosition(Vertex);
if (( HitResult.Location - WorldPositionVertex).Size() <= BrushRadius)
{
const FVector VertexVisualPosition = WorldPositionVertex + HitResult.Normal * VisualBiasDistance;
PDI->DrawPoint(VertexVisualPosition, HoverVertexPointColor, VertexPointSize * 2.0f, DepthGroup);
}
}
}
}
}
}
void IMeshPainter::BeginTransaction(const FText Description)
{
// In paint mode we only allow the BeginTransaction to be called with the EndTransaction pair. We should never be
// in a state where a second transaction was started before the first was ended.
checkf(PaintTransaction == NULL, TEXT("Cannot create Transaction while another one is still active"));
if (PaintTransaction == NULL)
{
PaintTransaction = new FScopedTransaction(Description);
}
}
void IMeshPainter::EndTransaction()
{
checkf(PaintTransaction != NULL, TEXT("Cannot end Transaction since there isn't one Active"));
delete PaintTransaction;
PaintTransaction = NULL;
}
| 40.19708 | 267 | 0.777102 | [
"vector"
] |
b9921307eccc1c1a8889b104426f36fb950e24e0 | 9,536 | cpp | C++ | src/kdl_interface.cpp | dscho15/dynamics_wrapper | ac7b214e31d1392ffdced581bc98d021897b19bc | [
"MIT"
] | null | null | null | src/kdl_interface.cpp | dscho15/dynamics_wrapper | ac7b214e31d1392ffdced581bc98d021897b19bc | [
"MIT"
] | null | null | null | src/kdl_interface.cpp | dscho15/dynamics_wrapper | ac7b214e31d1392ffdced581bc98d021897b19bc | [
"MIT"
] | null | null | null | #include <dynamics_wrapper/kdl_interface.hpp>
#include <ros/ros.h>
#include <kdl/chainfksolverpos_recursive.hpp>
namespace dynamics_wrapper{
kdl_interface::kdl_interface()
{}
std_msgs::Bool
kdl_interface::initialize(const std_msgs::String & link_start, const std_msgs::String & link_end)
{
std_msgs::Bool msg;
msg.data = 0; _init = false;
if (_tree = std::make_shared<KDL::Tree>(); !kdl_parser::treeFromParam("robot_description", *_tree.get()))
{
ROS_ERROR("Failed to construct kdl tree.");
return msg;
}
if(_chain = std::make_shared<KDL::Chain>(); !_tree->getChain(link_start.data, link_end.data, *_chain.get()))
{
ROS_ERROR_STREAM("Failed to parse the chain from " << link_start.data << " to " << link_end.data);
return msg;
}
if(_fk_solver = std::make_shared<KDL::ChainFkSolverPos_recursive>(*_chain.get()); _fk_solver == nullptr)
{
ROS_ERROR("Failed to create the fk_solver in KDL.");
return msg;
}
if(_jac_solver = std::make_shared<KDL::ChainJntToJacSolver>(*_chain.get()); _jac_solver == nullptr)
{
ROS_ERROR("Failed to create the jac_solver in KDL.");
return msg;
}
if(_dyn_solver = std::make_shared<KDL::ChainDynParam>(*_chain.get(), KDL::Vector(0, 0, -9.82)); _dyn_solver == nullptr)
{
ROS_ERROR("Failed to create the dynamics solver in KDL");
return msg;
}
_joints = _chain->getNrOfJoints();
msg.data = 1; _init = true;
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::pose_euler(std_msgs::Float64MultiArray q_)
{
// Msg
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
// Load data into KDL framework
if(q_.data.size() != _joints) return msg;
// Resize to 6 [ x y z | alpha beta gamma ]
msg.data.resize(6);
// KDL Jnt_array, Frame
KDL::JntArray q(_joints);
KDL::Frame x;
q.data = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(q_.data.data(), q_.data.size());
// Determine the Cartesian coords
_fk_solver->JntToCart(q, x);
// Get Translational part
msg.data[0] = x.p.data[0]; msg.data[1] = x.p.data[1]; msg.data[2] = x.p.data[2];
// Get EulerZYX
x.M.GetEulerZYX(msg.data[3], msg.data[4], msg.data[5]);
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::pose_error_euler(std_msgs::Float64MultiArray q_e_, std_msgs::Float64MultiArray q_d_)
{
// Msg
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
// Updata
auto msg_d = pose_euler(q_d_);
auto msg_e = pose_euler(q_e_);
// Resize
msg.data.resize(6);
for (int i = 0; i < msg.data.size(); i++)
msg.data[i] = msg_d.data[i] - msg_e.data[i];
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::pose_quaternion(std_msgs::Float64MultiArray q_)
{
// Msg
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
if(q_.data.size() != _joints) return msg;
// KDL Jnt_array, Frame
KDL::JntArray q(_joints);
KDL::Frame x;
// Fill JntArray
q.data = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(q_.data.data(), q_.data.size());
// Compute [4 x 4] homogenous transformatrion matrix
_fk_solver->JntToCart(q, x);
// Extract [3 x 3] rotation matrix
Eigen::Matrix3d R = Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>(x.M.data);
// Extract Quaternion
Eigen::Quaterniond quat(R);
msg.data.resize(7);
msg.data[0] = x.p.data[0];
msg.data[1] = x.p.data[1];
msg.data[2] = x.p.data[2];
msg.data[3] = quat.x();
msg.data[4] = quat.y();
msg.data[5] = quat.z();
msg.data[6] = quat.w();
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::pose_error_quaternion(std_msgs::Float64MultiArray q_e_, std_msgs::Float64MultiArray q_d_)
{
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
if(q_e_.data.size() != q_d_.data.size() and q_e_.data.size() != _joints) return msg;
auto pose_e = pose_quaternion(q_e_);
auto pose_d = pose_quaternion(q_d_);
Eigen::Quaterniond q_e(pose_e.data[6], pose_e.data[3], pose_e.data[4], pose_e.data[5]);
Eigen::Quaterniond q_d(pose_d.data[6], pose_d.data[3], pose_d.data[4], pose_d.data[5]);
Eigen::Quaterniond q = q_d * q_e.inverse();
msg.data.resize(6);
msg.data[0] = pose_d.data[0] - pose_e.data[0];
msg.data[1] = pose_d.data[1] - pose_e.data[1];
msg.data[2] = pose_d.data[2] - pose_e.data[2];
msg.data[3] = q.x();
msg.data[4] = q.y();
msg.data[5] = q.z();
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::jac_geometric(std_msgs::Float64MultiArray q_)
{
// Msg
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
// Load data into KDL framework
if(q_.data.size() != _joints) return msg;
// KDL Jnt_array, Frame
KDL::JntArray q(_joints);
KDL::Jacobian jac(_joints);
KDL::Frame x;
q.data = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(q_.data.data(), q_.data.size());
// Compute jacobian
_jac_solver->JntToJac(q, jac);
// Transform from eigen to std_msgs
tf::matrixEigenToMsg(jac.data, msg);
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::jac_analytic(std_msgs::Float64MultiArray q_)
{
// Msg
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
// Load data into KDL framework
if(q_.data.size() != _joints) return msg;
// Defines
KDL::Jacobian jac(_joints);
KDL::JntArray q(_joints);
KDL::Frame x;
q.data = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(q_.data.data(), q_.data.size());
// Forward kinematic solver
_fk_solver->JntToCart(q, x);
// Get the angles to compute the transformation
double alpha, beta, gamma;
x.M.GetEulerZYX(alpha, beta, gamma);
// Transformation for ZYX angles
Eigen::Matrix3d B;
B << 0, -std::sin(alpha), std::cos(beta)*std::cos(alpha),
0, std::cos(alpha), std::cos(beta)*std::sin(alpha),
1, 0, -std::sin(beta);
// Put it into the transformation matrix
Eigen::Matrix<double, 6, 6> T = Eigen::MatrixXd::Identity(6, 6);
T.bottomRightCorner(3, 3) << B;
// Invert the transformation
T = T.inverse();
// Determine jacobian
_jac_solver->JntToJac(q, jac);
// Do Jacobian
Eigen::Matrix<double, 6, -1> T_jac = T * jac.data;
// Transfrom message
tf::matrixEigenToMsg(T_jac, msg);
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::gravity(std_msgs::Float64MultiArray q_)
{
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
// Load data into KDL framework
if(q_.data.size() != _joints) return msg;
// Variables
KDL::JntArray q(_joints);
KDL::JntArray g(_joints);
// Parse joint values
q.data = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(q_.data.data(), q_.data.size());
// Gravity determination
_dyn_solver->JntToGravity(q, g);
msg.data = std::vector<double>(&g.data[0], g.data.data()+g.data.size());
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::coriolis(std_msgs::Float64MultiArray q_, std_msgs::Float64MultiArray qd_)
{
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
// Load data into KDL framework
if(q_.data.size() != _joints and q_.data.size() == qd_.data.size()) return msg;
// Variables
KDL::JntArray q(_joints), qd(_joints), c(_joints);
// Parse joint values
q.data = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(q_.data.data(), q_.data.size());
qd.data = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(qd_.data.data(), qd_.data.size());
// Coriolis determination
_dyn_solver->JntToCoriolis(q, qd, c);
msg.data = std::vector<double>(&c.data[0], c.data.data()+c.data.size());
return msg;
}
std_msgs::Float64MultiArray
kdl_interface::inertia_matrix(std_msgs::Float64MultiArray q_)
{
std_msgs::Float64MultiArray msg;
if(_init == false) return msg;
// Load data into KDL framework
if(q_.data.size() != _joints) return msg;
// Variables
KDL::JntArray q(_joints);
KDL::JntSpaceInertiaMatrix m(_joints);
// Parse joint values
q.data = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(q_.data.data(), q_.data.size());
// Mass Matrix
_dyn_solver->JntToMass(q, m);
// Parse back to message
msg.data = std::vector<double>(&m.data(0, 0), m.data.data()+m.data.size());
return msg;
}
}
| 29.341538 | 127 | 0.575084 | [
"vector",
"transform"
] |
b998f97a356f4e5c29cd7c067f57e24b0606d62f | 37,708 | cpp | C++ | ssd/Flash_Block_Manager_Base.cpp | Singularity0817/HybridSim | 2610d4cfc2132a42210e4f9fcc125e2afb580a1d | [
"MIT"
] | null | null | null | ssd/Flash_Block_Manager_Base.cpp | Singularity0817/HybridSim | 2610d4cfc2132a42210e4f9fcc125e2afb580a1d | [
"MIT"
] | null | null | null | ssd/Flash_Block_Manager_Base.cpp | Singularity0817/HybridSim | 2610d4cfc2132a42210e4f9fcc125e2afb580a1d | [
"MIT"
] | 2 | 2020-10-27T02:05:42.000Z | 2021-04-07T14:11:31.000Z | #include "Flash_Block_Manager.h"
namespace SSD_Components
{
unsigned int Block_Pool_Slot_Type::Page_vector_size = 0;
Flash_Block_Manager_Base::Flash_Block_Manager_Base(GC_and_WL_Unit_Base* gc_and_wl_unit, unsigned int max_allowed_block_erase_count, unsigned int total_concurrent_streams_no,
unsigned int channel_count, unsigned int chip_no_per_channel, unsigned int die_no_per_chip, unsigned int plane_no_per_die,
unsigned int block_no_per_plane, unsigned int page_no_per_block)
: gc_and_wl_unit(gc_and_wl_unit), max_allowed_block_erase_count(max_allowed_block_erase_count), total_concurrent_streams_no(total_concurrent_streams_no),
channel_count(channel_count), chip_no_per_channel(chip_no_per_channel), die_no_per_chip(die_no_per_chip), plane_no_per_die(plane_no_per_die),
block_no_per_plane(block_no_per_plane), pages_no_per_block(page_no_per_block)
{
plane_manager = new PlaneBookKeepingType***[channel_count];
for (unsigned int channelID = 0; channelID < channel_count; channelID++)
{
plane_manager[channelID] = new PlaneBookKeepingType**[chip_no_per_channel];
for (unsigned int chipID = 0; chipID < chip_no_per_channel; chipID++)
{
plane_manager[channelID][chipID] = new PlaneBookKeepingType*[die_no_per_chip];
for (unsigned int dieID = 0; dieID < die_no_per_chip; dieID++)
{
plane_manager[channelID][chipID][dieID] = new PlaneBookKeepingType[plane_no_per_die];
for (unsigned int planeID = 0; planeID < plane_no_per_die; planeID++)//Initialize plane book keeping data structure
{
plane_manager[channelID][chipID][dieID][planeID].Total_pages_count = block_no_per_plane * pages_no_per_block;
plane_manager[channelID][chipID][dieID][planeID].Free_pages_count = block_no_per_plane * pages_no_per_block;
plane_manager[channelID][chipID][dieID][planeID].Valid_pages_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Invalid_pages_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Ongoing_erase_operations.clear();
plane_manager[channelID][chipID][dieID][planeID].Ongoing_slc_erase_operations.clear();
plane_manager[channelID][chipID][dieID][planeID].Blocks = new Block_Pool_Slot_Type[block_no_per_plane];
for (unsigned int blockID = 0; blockID < block_no_per_plane; blockID++)//Initialize block pool for plane
{
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].BlockID = blockID;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Current_page_write_index = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Current_status = Block_Service_Status::IDLE;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Erase_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Holds_mapping_data = false;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Has_ongoing_gc_wl = false;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Erase_transaction = NULL;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Ongoing_user_program_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Ongoing_user_read_count = 0;
Block_Pool_Slot_Type::Page_vector_size = pages_no_per_block / (sizeof(uint64_t) * 8) + (pages_no_per_block % (sizeof(uint64_t) * 8) == 0 ? 0 : 1);
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_bitmap = new uint64_t[Block_Pool_Slot_Type::Page_vector_size];
for (unsigned int i = 0; i < Block_Pool_Slot_Type::Page_vector_size; i++)
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_bitmap[i] = All_VALID_PAGE;
plane_manager[channelID][chipID][dieID][planeID].Add_to_free_block_pool(&plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID], false);
}
plane_manager[channelID][chipID][dieID][planeID].Data_wf = new Block_Pool_Slot_Type*[total_concurrent_streams_no];
plane_manager[channelID][chipID][dieID][planeID].Translation_wf = new Block_Pool_Slot_Type*[total_concurrent_streams_no];
plane_manager[channelID][chipID][dieID][planeID].GC_wf = new Block_Pool_Slot_Type*[total_concurrent_streams_no];
for (unsigned int stream_cntr = 0; stream_cntr < total_concurrent_streams_no; stream_cntr++)
{
plane_manager[channelID][chipID][dieID][planeID].Data_wf[stream_cntr] = plane_manager[channelID][chipID][dieID][planeID].Get_a_free_block(stream_cntr, false);
plane_manager[channelID][chipID][dieID][planeID].Translation_wf[stream_cntr] = plane_manager[channelID][chipID][dieID][planeID].Get_a_free_block(stream_cntr, true);
plane_manager[channelID][chipID][dieID][planeID].GC_wf[stream_cntr] = plane_manager[channelID][chipID][dieID][planeID].Get_a_free_block(stream_cntr, false);
}
}
}
}
}
}
Flash_Block_Manager_Base::Flash_Block_Manager_Base(GC_and_WL_Unit_Base* gc_and_wl_unit, unsigned int max_allowed_block_erase_count, unsigned int total_concurrent_streams_no,
unsigned int channel_count, unsigned int chip_no_per_channel, unsigned int die_no_per_chip, unsigned int plane_no_per_die,
unsigned int block_no_per_plane, unsigned int page_no_per_block, unsigned int slc_block_no_per_plane, unsigned int page_no_per_slc_block)
: gc_and_wl_unit(gc_and_wl_unit), max_allowed_block_erase_count(max_allowed_block_erase_count), total_concurrent_streams_no(total_concurrent_streams_no),
channel_count(channel_count), chip_no_per_channel(chip_no_per_channel), die_no_per_chip(die_no_per_chip), plane_no_per_die(plane_no_per_die),
block_no_per_plane(block_no_per_plane), pages_no_per_block(page_no_per_block), slc_block_no_per_plane(slc_block_no_per_plane), page_no_per_slc_block(page_no_per_slc_block)
{
tlc_block_no_per_plane = block_no_per_plane - slc_block_no_per_plane;
std::cout << "Initializing Flash_Block_Manager that supports SLC-TLC combined SSD " << slc_block_no_per_plane << ":" << tlc_block_no_per_plane << std::endl;
page_no_per_tlc_block = page_no_per_block;
plane_manager = new PlaneBookKeepingType***[channel_count];
Max_data_migration_trigger_one_time = 10;
for (unsigned int channelID = 0; channelID < channel_count; channelID++)
{
plane_manager[channelID] = new PlaneBookKeepingType**[chip_no_per_channel];
for (unsigned int chipID = 0; chipID < chip_no_per_channel; chipID++)
{
plane_manager[channelID][chipID] = new PlaneBookKeepingType*[die_no_per_chip];
for (unsigned int dieID = 0; dieID < die_no_per_chip; dieID++)
{
plane_manager[channelID][chipID][dieID] = new PlaneBookKeepingType[plane_no_per_die];
for (unsigned int planeID = 0; planeID < plane_no_per_die; planeID++)//Initialize plane book keeping data structure
{
//*ZWH* in an SLC-TLC combined SSD, SLC blocks and TLC blocks are managed seperately!
//SLC block records
plane_manager[channelID][chipID][dieID][planeID].Total_slc_pages_count = slc_block_no_per_plane * page_no_per_slc_block;
plane_manager[channelID][chipID][dieID][planeID].Free_slc_pages_count = slc_block_no_per_plane * page_no_per_slc_block;
plane_manager[channelID][chipID][dieID][planeID].Valid_slc_pages_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Invalid_slc_pages_count = 0;
//TLC block records
plane_manager[channelID][chipID][dieID][planeID].Total_tlc_pages_count = tlc_block_no_per_plane * page_no_per_tlc_block;
plane_manager[channelID][chipID][dieID][planeID].Free_tlc_pages_count = tlc_block_no_per_plane * page_no_per_tlc_block;
plane_manager[channelID][chipID][dieID][planeID].Valid_tlc_pages_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Invalid_tlc_pages_count = 0;
//Total block records
plane_manager[channelID][chipID][dieID][planeID].Total_pages_count = slc_block_no_per_plane * page_no_per_slc_block + tlc_block_no_per_plane * page_no_per_tlc_block;
plane_manager[channelID][chipID][dieID][planeID].Free_pages_count = slc_block_no_per_plane * page_no_per_slc_block + tlc_block_no_per_plane * page_no_per_tlc_block;
plane_manager[channelID][chipID][dieID][planeID].Valid_pages_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Invalid_pages_count = 0;
plane_manager[channelID][chipID][dieID][planeID].On_going_slc_transaction_num = 0;
plane_manager[channelID][chipID][dieID][planeID].On_going_tlc_transaction_num = 0;
plane_manager[channelID][chipID][dieID][planeID].Triggered_data_migration = 0;
plane_manager[channelID][chipID][dieID][planeID].Completed_data_migration = 0;
plane_manager[channelID][chipID][dieID][planeID].Doing_data_migration = false;
plane_manager[channelID][chipID][dieID][planeID].Data_migration_should_be_terminated = false;
plane_manager[channelID][chipID][dieID][planeID].Doing_garbage_collection = false;
plane_manager[channelID][chipID][dieID][planeID].Triggered_garbage_collection = 0;
plane_manager[channelID][chipID][dieID][planeID].Completed_garbage_collection = 0;
/*
plane_manager[channelID][chipID][dieID][planeID].Total_pages_count = block_no_per_plane * pages_no_per_block;
plane_manager[channelID][chipID][dieID][planeID].Free_pages_count = block_no_per_plane * pages_no_per_block;
plane_manager[channelID][chipID][dieID][planeID].Valid_pages_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Invalid_pages_count = 0;
*/
plane_manager[channelID][chipID][dieID][planeID].Ongoing_erase_operations.clear();
plane_manager[channelID][chipID][dieID][planeID].Ongoing_slc_erase_operations.clear();
plane_manager[channelID][chipID][dieID][planeID].Blocks = new Block_Pool_Slot_Type[block_no_per_plane];
//*ZWH* initialize SLC blocks first
for (unsigned int blockID = 0; blockID < slc_block_no_per_plane; blockID++)//Initialize block pool for plane
{
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].BlockID = blockID;
//*ZWH*
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Flash_type = Flash_Technology_Type::SLC;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Pages_count = page_no_per_slc_block;
//*ZWH*
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Current_page_write_index = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Current_status = Block_Service_Status::IDLE;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Erase_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Holds_mapping_data = false;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Has_ongoing_gc_wl = false;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Erase_transaction = NULL;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Ongoing_user_program_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Ongoing_user_read_count = 0;
Block_Pool_Slot_Type::Page_vector_size = pages_no_per_block / (sizeof(uint64_t) * 8) + (pages_no_per_block % (sizeof(uint64_t) * 8) == 0 ? 0 : 1);
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_bitmap = new uint64_t[Block_Pool_Slot_Type::Page_vector_size];
for (unsigned int i = 0; i < Block_Pool_Slot_Type::Page_vector_size; i++)
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_bitmap[i] = All_VALID_PAGE;
plane_manager[channelID][chipID][dieID][planeID].Add_to_free_slc_block_pool(&plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID], false);
}
//*ZWH* then initialize TLC blocks
for (unsigned int blockID = slc_block_no_per_plane; blockID < block_no_per_plane; blockID++)//Initialize block pool for plane
{
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].BlockID = blockID;
//*ZWH*
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Flash_type = Flash_Technology_Type::TLC;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Pages_count = page_no_per_tlc_block;
//*ZWH*
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Current_page_write_index = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Current_status = Block_Service_Status::IDLE;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Erase_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Holds_mapping_data = false;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Has_ongoing_gc_wl = false;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Erase_transaction = NULL;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Ongoing_user_program_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Ongoing_user_read_count = 0;
Block_Pool_Slot_Type::Page_vector_size = pages_no_per_block / (sizeof(uint64_t) * 8) + (pages_no_per_block % (sizeof(uint64_t) * 8) == 0 ? 0 : 1);
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_bitmap = new uint64_t[Block_Pool_Slot_Type::Page_vector_size];
for (unsigned int i = 0; i < Block_Pool_Slot_Type::Page_vector_size; i++)
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_bitmap[i] = All_VALID_PAGE;
plane_manager[channelID][chipID][dieID][planeID].Add_to_free_tlc_block_pool(&plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID], false);
}
/*
for (unsigned int blockID = 0; blockID < block_no_per_plane; blockID++)//Initialize block pool for plane
{
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].BlockID = blockID;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Current_page_write_index = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Current_status = Block_Service_Status::IDLE;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Erase_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Holds_mapping_data = false;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Has_ongoing_gc_wl = false;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Erase_transaction = NULL;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Ongoing_user_program_count = 0;
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Ongoing_user_read_count = 0;
Block_Pool_Slot_Type::Page_vector_size = pages_no_per_block / (sizeof(uint64_t) * 8) + (pages_no_per_block % (sizeof(uint64_t) * 8) == 0 ? 0 : 1);
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_bitmap = new uint64_t[Block_Pool_Slot_Type::Page_vector_size];
for (unsigned int i = 0; i < Block_Pool_Slot_Type::Page_vector_size; i++)
plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID].Invalid_page_bitmap[i] = All_VALID_PAGE;
plane_manager[channelID][chipID][dieID][planeID].Add_to_free_block_pool(&plane_manager[channelID][chipID][dieID][planeID].Blocks[blockID], false);
}
*/
plane_manager[channelID][chipID][dieID][planeID].Data_wf = new Block_Pool_Slot_Type*[total_concurrent_streams_no];
plane_manager[channelID][chipID][dieID][planeID].Translation_wf = new Block_Pool_Slot_Type*[total_concurrent_streams_no];
plane_manager[channelID][chipID][dieID][planeID].GC_wf = new Block_Pool_Slot_Type*[total_concurrent_streams_no];
//*ZWH*
plane_manager[channelID][chipID][dieID][planeID].Data_slc_wf = new Block_Pool_Slot_Type*[total_concurrent_streams_no];
plane_manager[channelID][chipID][dieID][planeID].Data_tlc_wf = new Block_Pool_Slot_Type*[total_concurrent_streams_no];
//*ZWH*
for (unsigned int stream_cntr = 0; stream_cntr < total_concurrent_streams_no; stream_cntr++)
{
//plane_manager[channelID][chipID][dieID][planeID].Data_wf[stream_cntr] = plane_manager[channelID][chipID][dieID][planeID].Get_a_free_block(stream_cntr, false);
//std::cout << "Allocating blocks in " << channelID << ":"<< chipID << ":"<< dieID << ":"<< planeID << " for stream " << stream_cntr << std::endl;
plane_manager[channelID][chipID][dieID][planeID].Translation_wf[stream_cntr] = plane_manager[channelID][chipID][dieID][planeID].Get_a_free_tlc_block(stream_cntr, true);
plane_manager[channelID][chipID][dieID][planeID].Data_slc_wf[stream_cntr] = plane_manager[channelID][chipID][dieID][planeID].Get_a_free_slc_block(stream_cntr, false);
plane_manager[channelID][chipID][dieID][planeID].Data_tlc_wf[stream_cntr] = plane_manager[channelID][chipID][dieID][planeID].Get_a_free_tlc_block(stream_cntr, false);
plane_manager[channelID][chipID][dieID][planeID].GC_wf[stream_cntr] = plane_manager[channelID][chipID][dieID][planeID].Get_a_free_tlc_block(stream_cntr, false);
}
}
}
}
}
}
Flash_Block_Manager_Base::~Flash_Block_Manager_Base()
{
for (unsigned int channel_id = 0; channel_id < channel_count; channel_id++)
{
for (unsigned int chip_id = 0; chip_id < chip_no_per_channel; chip_id++)
{
for (unsigned int die_id = 0; die_id < die_no_per_chip; die_id++)
{
for (unsigned int plane_id = 0; plane_id < plane_no_per_die; plane_id++)
{
for (unsigned int blockID = 0; blockID < block_no_per_plane; blockID++)
delete[] plane_manager[channel_id][chip_id][die_id][plane_id].Blocks[blockID].Invalid_page_bitmap;
delete[] plane_manager[channel_id][chip_id][die_id][plane_id].Blocks;
delete[] plane_manager[channel_id][chip_id][die_id][plane_id].GC_wf;
delete[] plane_manager[channel_id][chip_id][die_id][plane_id].Data_wf;
delete[] plane_manager[channel_id][chip_id][die_id][plane_id].Translation_wf;
}
delete[] plane_manager[channel_id][chip_id][die_id];
}
delete[] plane_manager[channel_id][chip_id];
}
delete[] plane_manager[channel_id];
}
delete[] plane_manager;
}
void Flash_Block_Manager_Base::Set_GC_and_WL_Unit(GC_and_WL_Unit_Base* gcwl) { this->gc_and_wl_unit = gcwl; }
void Block_Pool_Slot_Type::Erase()
{
if (Invalid_page_count != Pages_count)
{
std::cout << "Erasing a block with VALID Page!!!" << std::endl;
std::cin.get();
}
Current_page_write_index = 0;
Invalid_page_count = 0;
Erase_count++;
for (unsigned int i = 0; i < Block_Pool_Slot_Type::Page_vector_size; i++)
Invalid_page_bitmap[i] = All_VALID_PAGE;
Stream_id = NO_STREAM;
Holds_mapping_data = false;
Erase_transaction = NULL;
}
bool Block_Pool_Slot_Type::Check_Block_Metadata()
{
if (Flash_type == Flash_Technology_Type::SLC)
{
if (Pages_count > 128)
{
std::cout << "INVALID METADATA in block pool : Wrong flash type" << std::endl;
std::cin.get();
return false;
}
}
if (Current_page_write_index > Pages_count)
{
std::cout << "INVALID METADATA in block pool : write index is larger than pages count" << std::endl;
std::cin.get();
return false;
}
unsigned int invalid_page_check = 0;
for (unsigned int i = 0; i < Page_vector_size; i++)
{
uint64_t vector = Invalid_page_bitmap[i];
for (unsigned int j = 0; j < 64; j++)
{
if (vector % 2 == 1)
invalid_page_check++;
vector = vector / 2;
}
}
if (invalid_page_check != Invalid_page_count)
{
std::cout << "INVALID METADATA in block pool : invalid page number wrong " << invalid_page_check << " : " << Invalid_page_count << std::endl;
std::cin.get();
return false;
}
}
Block_Pool_Slot_Type* PlaneBookKeepingType::Get_a_free_block(stream_id_type stream_id, bool for_mapping_data)
{
Block_Pool_Slot_Type* new_block = NULL;
new_block = (*Free_block_pool.begin()).second;//Assign a new write frontier block
if (Free_block_pool.size() == 0)
PRINT_ERROR("Requesting a free block from an empty pool!")
Free_block_pool.erase(Free_block_pool.begin());
new_block->Stream_id = stream_id;
new_block->Holds_mapping_data = for_mapping_data;
Block_usage_history.push(new_block->BlockID);
return new_block;
}
Block_Pool_Slot_Type* PlaneBookKeepingType::Get_a_free_slc_block(stream_id_type stream_id, bool for_mapping_data)
{
//std::cout << "...Getting a free Slc block...." << Get_free_slc_block_pool_size() << std::endl;
Block_Pool_Slot_Type* new_block = NULL;
if (Get_free_slc_block_pool_size() == 0)
{
//PRINT_ERROR("Requesting a free SLC block from an empty pool!")
return new_block;
}
new_block = Free_slc_block_pool.front();//Assign a new write frontier block
/*
if (Free_slc_block_pool.size() == 0)
{
PRINT_ERROR("Requesting a free SLC block from an empty pool!")
return NULL;
}
*/
//std::cout << "...New block is found " << new_block->BlockID << " " << new_block->Pages_count << ":" << new_block->Current_page_write_index << std::endl;
/*
std::multimap<unsigned int, Block_Pool_Slot_Type*> new_Free_slc_block_pool;
for (auto it = Free_slc_block_pool.begin(); it != Free_slc_block_pool.end(); it++)
{
if (it == Free_slc_block_pool.begin())
continue;
else
{
new_Free_slc_block_pool.insert(*it);
}
}
std::cout << "...block_pool is copied." << std::endl;
Free_slc_block_pool.clear();
std::cout << "...the old pool is cleared" << std::endl;
Free_slc_block_pool = new_Free_slc_block_pool;
*/
Free_slc_block_pool.pop();
if (Free_slc_block_pool.front() == new_block)
{
std::cout << "......WRONGWRONGWRONG......" << std::endl;
}
//Free_slc_block_pool.erase(Free_slc_block_pool.begin());
//std::cout << "...block is activated and erased from the pool... ";
//std::cout << Free_slc_block_pool.size() << std::endl;
new_block->Stream_id = stream_id;
new_block->Holds_mapping_data = for_mapping_data;
//std::cout << "...Pushing the block to usage_history..." << std::endl;
Slc_Block_usage_history.push(new_block->BlockID);
if (new_block->Flash_type != Flash_Technology_Type::SLC)
{
std::cout << "Get a wrong type of flash block! SLC->TLC" << std::endl;
std::cin.get();
}
return new_block;
}
Block_Pool_Slot_Type* PlaneBookKeepingType::Get_a_free_tlc_block(stream_id_type stream_id, bool for_mapping_data)
{
//std::cout << "...ready to get a free Tlc block...." << Free_tlc_block_pool.size() << std::endl;
Block_Pool_Slot_Type* new_block = NULL;
if (Free_tlc_block_pool.size() == 0)
{
PRINT_ERROR("Requesting a free TLC block from an empty pool!")
return NULL;
}
//std::cout << "...get the front block from the pool...." << Free_tlc_block_pool.size() << std::endl;
new_block = Free_tlc_block_pool.front();//Assign a new write frontier block
//std::cout << "...poping the front block of the pool...." << Free_tlc_block_pool.size() << std::endl;
Free_tlc_block_pool.pop();
//Free_tlc_block_pool.erase(Free_tlc_block_pool.begin());
//std::cout << "...initializing data...." << Free_tlc_block_pool.size() << std::endl;
//std::cout << "...checking flash type...." << std::endl;
if (new_block->Flash_type != Flash_Technology_Type::TLC)
{
std::cout << "Get a wrong type of flash block! TLC->SLC" << std::endl;
std::cin.get();
}
new_block->Stream_id = stream_id;
//std::cout << "...stream id set...." << std::endl;
new_block->Holds_mapping_data = for_mapping_data;
//std::cout << "...mapping data flag set...." << std::endl;
Tlc_Block_usage_history.push(new_block->BlockID);
//std::cout << "...history updated...." << std::endl;
return new_block;
}
void PlaneBookKeepingType::Check_bookkeeping_correctness(const NVM::FlashMemory::Physical_Page_Address& plane_address)
{
if (Total_pages_count != Free_pages_count + Valid_pages_count + Invalid_pages_count)
PRINT_ERROR("Inconsistent status in the plane bookkeeping record!")
if (Total_slc_pages_count != Free_slc_pages_count + Valid_slc_pages_count + Invalid_slc_pages_count)
PRINT_ERROR("Inconsistent status in the plane bookkeeping record SLC pages!" << Free_slc_pages_count << ":" << Valid_slc_pages_count << ":" << Invalid_slc_pages_count)
if (Total_tlc_pages_count != Free_tlc_pages_count + Valid_tlc_pages_count + Invalid_tlc_pages_count)
PRINT_ERROR("Inconsistent status in the plane bookkeeping record TLC pages!")
if (Free_pages_count == 0)
PRINT_ERROR("Plane " << "@" << plane_address.ChannelID << "@" << plane_address.ChipID << "@" << plane_address.DieID << "@" << plane_address.PlaneID << " pool size: " << Get_free_block_pool_size() << " ran out of free pages! Bad resource management! It is not safe to continue simulation!");
}
unsigned int PlaneBookKeepingType::Get_free_block_pool_size()
{
return (unsigned int)Free_block_pool.size();
}
unsigned int PlaneBookKeepingType::Get_free_slc_block_pool_size()
{
return (unsigned int)Free_slc_block_pool.size();
}
unsigned int PlaneBookKeepingType::Get_free_tlc_block_pool_size()
{
return (unsigned int)Free_tlc_block_pool.size();
}
unsigned int PlaneBookKeepingType::Get_free_slc_page_number()
{
return (unsigned int)Free_slc_pages_count;
}
void PlaneBookKeepingType::Add_to_free_block_pool(Block_Pool_Slot_Type* block, bool consider_dynamic_wl)
{
if (consider_dynamic_wl)
{
std::pair<unsigned int, Block_Pool_Slot_Type*> entry(block->Erase_count, block);
Free_block_pool.insert(entry);
}
else
{
std::pair<unsigned int, Block_Pool_Slot_Type*> entry(0, block);
Free_block_pool.insert(entry);
}
}
void PlaneBookKeepingType::Add_to_free_slc_block_pool(Block_Pool_Slot_Type* block, bool consider_dynamic_wl)
{
//*ZWH*
//wear leveling is not considerred now
Free_slc_block_pool.push(block);
/*
if (consider_dynamic_wl)
{
std::pair<unsigned int, Block_Pool_Slot_Type*> entry(block->Erase_count, block);
Free_slc_block_pool.insert(entry);
}
else
{
std::pair<unsigned int, Block_Pool_Slot_Type*> entry(0, block);
Free_slc_block_pool.insert(entry);
}
*/
}
void PlaneBookKeepingType::Add_to_free_tlc_block_pool(Block_Pool_Slot_Type* block, bool consider_dynamic_wl)
{
Free_tlc_block_pool.push(block);
/*
if (consider_dynamic_wl)
{
std::pair<unsigned int, Block_Pool_Slot_Type*> entry(block->Erase_count, block);
Free_tlc_block_pool.insert(entry);
}
else
{
std::pair<unsigned int, Block_Pool_Slot_Type*> entry(0, block);
Free_tlc_block_pool.insert(entry);
}
*/
}
unsigned int Flash_Block_Manager_Base::Get_min_max_erase_difference(const NVM::FlashMemory::Physical_Page_Address& plane_address)
{
unsigned int min_erased_block = 0;
unsigned int max_erased_block = 0;
PlaneBookKeepingType *plane_record = &plane_manager[plane_address.ChannelID][plane_address.ChipID][plane_address.DieID][plane_address.PlaneID];
for (unsigned int i = 1; i < block_no_per_plane; i++)
{
if (plane_record->Blocks[i].Erase_count > plane_record->Blocks[i].Erase_count)
max_erased_block = i;
if (plane_record->Blocks[i].Erase_count < plane_record->Blocks[i].Erase_count)
min_erased_block = i;
}
return max_erased_block - min_erased_block;
}
flash_block_ID_type Flash_Block_Manager_Base::Get_coldest_block_id(const NVM::FlashMemory::Physical_Page_Address& plane_address)
{
unsigned int min_erased_block = 0;
PlaneBookKeepingType *plane_record = &plane_manager[plane_address.ChannelID][plane_address.ChipID][plane_address.DieID][plane_address.PlaneID];
for (unsigned int i = 1; i < block_no_per_plane; i++)
{
if (plane_record->Blocks[i].Erase_count < plane_record->Blocks[min_erased_block].Erase_count)
min_erased_block = i;
}
return min_erased_block;
}
flash_block_ID_type Flash_Block_Manager_Base::Get_coldest_slc_block_id(const NVM::FlashMemory::Physical_Page_Address& plane_address)
{
unsigned int min_erased_block = 65536000;
PlaneBookKeepingType *plane_record = &plane_manager[plane_address.ChannelID][plane_address.ChipID][plane_address.DieID][plane_address.PlaneID];
for (unsigned int i = 0; i < slc_block_no_per_plane; i++)
{
if (plane_record->Blocks[i].Current_page_write_index < plane_record->Blocks[i].Pages_count)
continue;
else if (min_erased_block == 65536000)
min_erased_block = i;
else if (plane_record->Blocks[i].Erase_count < plane_record->Blocks[min_erased_block].Erase_count)
min_erased_block = i;
}
if (min_erased_block == 65536000)
{
std::cout << "Can't FIND A COLDEST SLC BLOCK." << std::endl;
std::cin.get();
}
return (unsigned int)min_erased_block;
}
flash_block_ID_type Flash_Block_Manager_Base::Get_coldest_tlc_block_id(const NVM::FlashMemory::Physical_Page_Address& plane_address)
{
unsigned int min_erased_block = 65536000;
PlaneBookKeepingType *plane_record = &plane_manager[plane_address.ChannelID][plane_address.ChipID][plane_address.DieID][plane_address.PlaneID];
for (unsigned int i = slc_block_no_per_plane + 1; i < block_no_per_plane; i++)
{
if (plane_record->Blocks[i].Current_page_write_index < plane_record->Blocks[i].Pages_count)
continue;
else if (min_erased_block == 65536000)
min_erased_block = i;
else if (plane_record->Blocks[i].Erase_count < plane_record->Blocks[min_erased_block].Erase_count)
min_erased_block = i;
}
if (min_erased_block == 65536000)
{
std::cout << "Can't FIND A COLDEST TLC BLOCK." << std::endl;
std::cin.get();
}
return min_erased_block;
}
PlaneBookKeepingType* Flash_Block_Manager_Base::Get_plane_bookkeeping_entry(const NVM::FlashMemory::Physical_Page_Address& plane_address)
{
return &(plane_manager[plane_address.ChannelID][plane_address.ChipID][plane_address.DieID][plane_address.PlaneID]);
}
bool Flash_Block_Manager_Base::Block_has_ongoing_gc_wl(const NVM::FlashMemory::Physical_Page_Address& block_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[block_address.ChannelID][block_address.ChipID][block_address.DieID][block_address.PlaneID];
return plane_record->Blocks[block_address.BlockID].Has_ongoing_gc_wl;
}
bool Flash_Block_Manager_Base::Can_execute_gc_wl(const NVM::FlashMemory::Physical_Page_Address& block_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[block_address.ChannelID][block_address.ChipID][block_address.DieID][block_address.PlaneID];
return (plane_record->Blocks[block_address.BlockID].Ongoing_user_program_count + plane_record->Blocks[block_address.BlockID].Ongoing_user_read_count == 0);
}
void Flash_Block_Manager_Base::GC_WL_started(const NVM::FlashMemory::Physical_Page_Address& block_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[block_address.ChannelID][block_address.ChipID][block_address.DieID][block_address.PlaneID];
plane_record->Blocks[block_address.BlockID].Has_ongoing_gc_wl = true;
}
void Flash_Block_Manager_Base::program_transaction_issued(const NVM::FlashMemory::Physical_Page_Address& page_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[page_address.ChannelID][page_address.ChipID][page_address.DieID][page_address.PlaneID];
plane_record->Blocks[page_address.BlockID].Ongoing_user_program_count++;
if(plane_record->Blocks[page_address.BlockID].Flash_type == Flash_Technology_Type::SLC)
plane_record->On_going_slc_transaction_num++;
else if(plane_record->Blocks[page_address.BlockID].Flash_type == Flash_Technology_Type::TLC)
{
plane_record->On_going_tlc_transaction_num++;
//std::cout << "Recieved a TLC write??? " << plane_record->On_going_tlc_transaction_num << std::endl;
//std::cin.get();
}
else
{
std::cout << "Something wrong in calculating the number of program transactions 0" << std::endl;
}
}
void Flash_Block_Manager_Base::Read_transaction_issued(const NVM::FlashMemory::Physical_Page_Address& page_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[page_address.ChannelID][page_address.ChipID][page_address.DieID][page_address.PlaneID];
plane_record->Blocks[page_address.BlockID].Ongoing_user_read_count++;
plane_record->Ongoing_user_read_count_plane++;
}
void Flash_Block_Manager_Base::Program_transaction_serviced(const NVM::FlashMemory::Physical_Page_Address& page_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[page_address.ChannelID][page_address.ChipID][page_address.DieID][page_address.PlaneID];
plane_record->Blocks[page_address.BlockID].Ongoing_user_program_count--;
if(plane_record->Blocks[page_address.BlockID].Flash_type == Flash_Technology_Type::SLC)
plane_record->On_going_slc_transaction_num--;
else if(plane_record->Blocks[page_address.BlockID].Flash_type == Flash_Technology_Type::TLC)
plane_record->On_going_tlc_transaction_num--;
else
{
std::cout << "Something wrong in calculating the number of program transactions 1" << std::endl;
}
if(plane_record->On_going_slc_transaction_num < 0 || plane_record->On_going_tlc_transaction_num < 0)
std::cout << "Something wrong in calculating the number of program transactions 2" << std::endl;
}
void Flash_Block_Manager_Base::Read_transaction_serviced(const NVM::FlashMemory::Physical_Page_Address& page_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[page_address.ChannelID][page_address.ChipID][page_address.DieID][page_address.PlaneID];
plane_record->Blocks[page_address.BlockID].Ongoing_user_read_count--;
plane_record->Ongoing_user_read_count_plane--;
}
bool Flash_Block_Manager_Base::Is_having_ongoing_program(const NVM::FlashMemory::Physical_Page_Address& block_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[block_address.ChannelID][block_address.ChipID][block_address.DieID][block_address.PlaneID];
return plane_record->Blocks[block_address.BlockID].Ongoing_user_program_count > 0;
}
void Flash_Block_Manager_Base::GC_WL_finished(const NVM::FlashMemory::Physical_Page_Address& block_address)
{
PlaneBookKeepingType *plane_record = &plane_manager[block_address.ChannelID][block_address.ChipID][block_address.DieID][block_address.PlaneID];
plane_record->Blocks[block_address.BlockID].Has_ongoing_gc_wl = false;
if (plane_record->Blocks[block_address.BlockID].Flash_type == Flash_Technology_Type::SLC)
{
//std::cout << "plane " << block_address.ChannelID << ":" << block_address.ChipID << ":" << block_address.DieID << ":" << block_address.PlaneID << " finish collecting a block." << std::endl;
plane_record->Completed_data_migration++;
if (plane_record->Completed_data_migration == plane_record->Triggered_data_migration)
{
if (plane_record->Data_migration_should_be_terminated == true || plane_record->Triggered_data_migration == Max_data_migration_trigger_one_time)
{
//std::cout << block_address.ChannelID << ":" << block_address.ChipID << ":" << block_address.DieID << ":" << block_address.PlaneID << " finish doing data migration" << plane_record->Triggered_data_migration << ":" << plane_record->Completed_data_migration << std::endl;
plane_record->Triggered_data_migration = 0;
plane_record->Completed_data_migration = 0;
plane_record->Doing_data_migration = false;
plane_record->Data_migration_should_be_terminated = false;
gc_and_wl_unit->Decrease_plane_num_doing_data_migration();
}
else
{
gc_and_wl_unit->Check_data_migration_required(plane_record->Get_free_slc_block_pool_size(), block_address);
}
}
else if (plane_record->Triggered_data_migration == Max_data_migration_trigger_one_time)
{
plane_record->Data_migration_should_be_terminated = true;
}
else if (plane_record->Data_migration_should_be_terminated == false)
{
//gc_and_wl_unit->Check_data_migration_required(plane_record->Get_free_slc_block_pool_size(), block_address);
}
}
else
{
plane_record->Completed_garbage_collection++;
if (plane_record->Completed_garbage_collection == plane_record->Triggered_garbage_collection)
{
plane_record->Triggered_garbage_collection = 0;
plane_record->Completed_garbage_collection = 0;
plane_record->Doing_garbage_collection = false;
}
gc_and_wl_unit->Check_tlc_gc_required(plane_record->Get_free_tlc_block_pool_size(), block_address);
}
}
bool Flash_Block_Manager_Base::Is_page_valid(Block_Pool_Slot_Type* block, flash_page_ID_type page_id)
{
if ((block->Invalid_page_bitmap[page_id / 64] & (((uint64_t)1) << page_id)) == 0)
return true;
return false;
}
bool Flash_Block_Manager_Base::Is_data_migration_needed()
{
for (flash_channel_ID_type chann_id = 0; chann_id < channel_count; chann_id++)
{
for (flash_chip_ID_type chip_id = 0; chip_id < chip_no_per_channel; chip_id++)
{
for (flash_die_ID_type die_id = 0; die_id < die_no_per_chip; die_id++)
{
for (flash_plane_ID_type plane_id = 0; plane_id < plane_no_per_die; plane_id++)
{
PlaneBookKeepingType* pbke = &plane_manager[chann_id][chip_id][die_id][plane_id];
if (pbke->Get_free_slc_block_pool_size() < slc_block_no_per_plane * 0.8)
return true;
}
}
}
}
return false;
}
} | 53.945637 | 293 | 0.752334 | [
"vector"
] |
b99b989409d74c1d6eacf06be8e73c0135fa2766 | 4,836 | hpp | C++ | libraries/chain/include/fiberchain/chain/global_property_object.hpp | FiberChain/FiberChain | f4640dfa71cdc57c56d9e299b4f369750dc760ec | [
"MIT"
] | null | null | null | libraries/chain/include/fiberchain/chain/global_property_object.hpp | FiberChain/FiberChain | f4640dfa71cdc57c56d9e299b4f369750dc760ec | [
"MIT"
] | null | null | null | libraries/chain/include/fiberchain/chain/global_property_object.hpp | FiberChain/FiberChain | f4640dfa71cdc57c56d9e299b4f369750dc760ec | [
"MIT"
] | null | null | null | #pragma once
#include <fc/uint128.hpp>
#include <fiberchain/chain/fiberchain_object_types.hpp>
#include <fiberchain/protocol/asset.hpp>
namespace fiberchain { namespace chain {
using fiberchain::protocol::asset;
using fiberchain::protocol::price;
/**
* @class dynamic_global_property_object
* @brief Maintains global state information
* @ingroup object
* @ingroup implementation
*
* This is an implementation detail. The values here are calculated during normal chain operations and reflect the
* current values of global blockchain properties.
*/
class dynamic_global_property_object : public object< dynamic_global_property_object_type, dynamic_global_property_object>
{
public:
template< typename Constructor, typename Allocator >
dynamic_global_property_object( Constructor&& c, allocator< Allocator > a )
{
c( *this );
}
dynamic_global_property_object(){}
id_type id;
uint32_t head_block_number = 0;
block_id_type head_block_id;
time_point_sec time;
account_name_type current_bobserver;
asset printed_supply = asset( FIBERCHAIN_INIT_SUPPLY, PIA_SYMBOL );
asset virtual_supply = asset( 0, PIA_SYMBOL ); /// total supply after converting snac to pia
asset current_supply = asset( 0, PIA_SYMBOL ); /// total pia supply
asset current_snac_supply = asset( 0, SNAC_SYMBOL ); /// total snac supply
asset total_exchange_request_pia = asset( 0, PIA_SYMBOL ); /// total balance in reward fund
asset total_exchange_request_snac = asset( 0, SNAC_SYMBOL ); /// total balance in reward fund
price snac_exchange_rate = price( asset( 10000, SNAC_SYMBOL ), asset( 100000000, PIA_SYMBOL ) );
/**
* Maximum block size is decided by the set of active bobservers which change every round.
* Each bobserver posts what they think the maximum size should be as part of their bobserver
* properties, the median size is chosen to be the maximum block size for the round.
*
* @note the minimum value for maximum_block_size is defined by the protocol to prevent the
* network from getting stuck by bobservers attempting to set this too low.
*/
uint32_t maximum_block_size = 0;
/**
* The current absolute slot number. Equal to the total
* number of slots since genesis. Also equal to the total
* number of missed slots plus head_block_number.
*/
uint64_t current_aslot = 0;
/**
* used to compute bobserver participation.
*/
fc::uint128_t recent_slots_filled;
uint8_t participation_count = 0; ///< Divide by 128 to compute participation percentage
/**
* dapp transaction fee
* */
asset dapp_transaction_fee = FIBERCHAIN_DAPP_TRANSACTION_FEE;
uint32_t last_irreversible_block_num = 0;
uint32_t current_bproducer_count = 0;
time_point_sec last_update_bproducer_time;
/**
* last time that aggregate voting for dapp
* */
time_point_sec last_dapp_voting_aggregation_time;
};
typedef multi_index_container<
dynamic_global_property_object,
indexed_by<
ordered_unique< tag< by_id >,
member< dynamic_global_property_object, dynamic_global_property_object::id_type, &dynamic_global_property_object::id > >
>,
allocator< dynamic_global_property_object >
> dynamic_global_property_index;
} } // fiberchain::chain
FC_REFLECT( fiberchain::chain::dynamic_global_property_object,
(id)
(head_block_number)
(head_block_id)
(time)
(current_bobserver)
(printed_supply)
(virtual_supply)
(current_supply)
(current_snac_supply)
(total_exchange_request_pia)
(total_exchange_request_snac)
(snac_exchange_rate)
(maximum_block_size)
(current_aslot)
(recent_slots_filled)
(participation_count)
(dapp_transaction_fee)
(last_irreversible_block_num)
(current_bproducer_count)
(last_update_bproducer_time)
(last_dapp_voting_aggregation_time)
)
CHAINBASE_SET_INDEX_TYPE( fiberchain::chain::dynamic_global_property_object, fiberchain::chain::dynamic_global_property_index )
| 39.639344 | 132 | 0.621795 | [
"object"
] |
b9a32f714bc53b89710dbcdc962f2976179652bb | 6,033 | hpp | C++ | statistics/chisq.hpp | liweitianux/opt_utilities | 17363d2b870c88db108984a9a59d79c12d677e93 | [
"MIT"
] | null | null | null | statistics/chisq.hpp | liweitianux/opt_utilities | 17363d2b870c88db108984a9a59d79c12d677e93 | [
"MIT"
] | null | null | null | statistics/chisq.hpp | liweitianux/opt_utilities | 17363d2b870c88db108984a9a59d79c12d677e93 | [
"MIT"
] | 1 | 2020-03-05T16:14:44.000Z | 2020-03-05T16:14:44.000Z | /**
\file chisq.hpp
\brief chi-square statistic
\author Junhua Gu
*/
#ifndef CHI_SQ_HPP
#define CHI_SQ_HPP
#define OPT_HEADER
#include <core/fitter.hpp>
#include <iostream>
#include <vector>
#include <misc/optvec.hpp>
#include <cmath>
using std::cerr;using std::endl;
namespace opt_utilities
{
/**
\brief chi-square statistic
\tparam Ty the return type of model
\tparam Tx the type of the self-var
\tparam Tp the type of model parameter
\tparam Ts the type of the statistic
\tparam Tstr the type of the string used
*/
template<typename Ty,typename Tx,typename Tp,typename Ts,typename Tstr>
class chisq
:public statistic<Ty,Tx,Tp,Ts,Tstr>
{
private:
bool verb;
int n;
statistic<Ty,Tx,Tp,Ts,Tstr>* do_clone()const
{
// return const_cast<statistic<Ty,Tx,Tp>*>(this);
return new chisq<Ty,Tx,Tp,Ts,Tstr>(*this);
}
const char* do_get_type_name()const
{
return "chi^2 statistic";
}
public:
void verbose(bool v)
{
verb=v;
}
public:
chisq()
:verb(false)
{}
Ts do_eval(const Tp& p)
{
Ts result(0);
for(int i=(this->get_data_set()).size()-1;i>=0;--i)
{
Ty chi=(this->get_data_set().get_data(i).get_y()-this->eval_model(this->get_data_set().get_data(i).get_x(),p))/this->get_data_set().get_data(i).get_y_upper_err();
result+=chi*chi;
}
if(verb)
{
n++;
if(n%10==0)
{
cerr<<result<<"\t";
for(size_t i=0;i<get_size(p);++i)
{
cerr<<get_element(p,i)<<",";
}
cerr<<endl;
}
}
return result;
}
};
#if 1
template<>
class chisq<double,double,std::vector<double>,double,std::string>
:public statistic<double,double,std::vector<double> ,double,std::string>
{
public:
typedef double Ty;
typedef double Tx;
typedef std::vector<double> Tp;
typedef double Ts;
typedef std::string Tstr;
private:
bool verb;
int n;
statistic<Ty,Tx,Tp,Ts,Tstr>* do_clone()const
{
// return const_cast<statistic<Ty,Tx,Tp>*>(this);
return new chisq<Ty,Tx,Tp,Ts,Tstr>(*this);
}
const char* do_get_type_name()const
{
return "chi^2 statistics (specialized for double)";
}
public:
void verbose(bool v)
{
verb=v;
}
public:
chisq()
:verb(false)
{}
Ty do_eval(const Tp& p)
{
Ty result(0);
for(int i=(this->get_data_set()).size()-1;i>=0;--i)
{
#ifdef HAVE_X_ERROR
Tx x1=this->get_data_set().get_data(i).get_x()-this->get_data_set().get_data(i).get_x_lower_err();
Tx x2=this->get_data_set().get_data(i).get_x()+this->get_data_set().get_data(i).get_x_upper_err();
Tx x=this->get_data_set().get_data(i).get_x();
Ty errx1=(this->eval_model(x1,p)-this->eval_model(x,p));
Ty errx2=(this->eval_model(x2,p)-this->eval_model(x,p));
//Ty errx=0;
#else
Ty errx1=0;
Ty errx2=0;
#endif
Ty y_model=this->eval_model(this->get_data_set().get_data(i).get_x(),p);
Ty y_obs=this->get_data_set().get_data(i).get_y();
Ty y_err;
Ty errx=0;
if(errx1<errx2)
{
if(y_obs<y_model)
{
errx=errx1>0?errx1:-errx1;
}
else
{
errx=errx2>0?errx2:-errx2;
}
}
else
{
if(y_obs<y_model)
{
errx=errx2>0?errx2:-errx2;
}
else
{
errx=errx1>0?errx1:-errx1;
}
}
if(y_model>y_obs)
{
y_err=this->get_data_set().get_data(i).get_y_upper_err();
}
else
{
y_err=this->get_data_set().get_data(i).get_y_lower_err();
}
Ty chi=(y_obs-y_model)/std::sqrt(y_err*y_err+errx*errx);
// Ty chi=(this->get_data_set().get_data(i).get_y()-this->eval_model(this->get_data_set().get_data(i).get_x(),p));
// cerr<<chi<<"\n";
result+=chi*chi;
//std::cerr<<chi<<std::endl;
//cerr<<this->eval_model(this->get_data_set()[i].x,p)<<endl;
//cerr<<this->get_data_set()[i].y_upper_err<<endl;
// cerr<<this->get_data_set()[i].x<<"\t"<<this->get_data_set()[i].y<<"\t"<<this->eval_model(this->get_data_set()[i].x,p)<<endl;
}
if(verb)
{
n++;
if(n%10==0)
{
cerr<<result<<"\t";
for(int i=0;i<(int)get_size(p);++i)
{
cerr<<get_element(p,i)<<",";
}
cerr<<endl;
}
}
return result;
}
};
#endif
template<typename T,typename Ts,typename Tstr>
class chisq<optvec<T>,optvec<T>,optvec<T>,Ts,Tstr>
:public statistic<optvec<T>,optvec<T>,optvec<T>,Ts,Tstr>
{
private:
bool verb;
int n;
typedef optvec<T> Tx;
typedef optvec<T> Ty;
typedef optvec<T> Tp;
statistic<Ty,Tx,Tp,Ts,Tstr>* do_clone()const
{
// return const_cast<statistic<Ty,Tx,Tp>*>(this);
return new chisq<Ty,Tx,Tp,Ts,Tstr>(*this);
}
const char* do_get_type_name()const
{
return "chi^2 statistic";
}
public:
void verbose(bool v)
{
verb=v;
}
public:
chisq()
:verb(false)
{}
Ts do_eval(const Tp& p)
{
Ts result(0);
for(int i=(this->get_data_set()).size()-1;i>=0;--i)
{
Ty chi(this->get_data_set().get_data(0).get_y().size());
for(int j=0;j<chi.size();++j)
{
Ty model_y(this->eval_model(this->get_data_set().get_data(i).get_x(),p));
if(model_y[j]>this->get_data_set().get_data(i).get_y()[j])
{
chi[j]=(this->get_data_set().get_data(i).get_y()[j]-model_y[j])/this->get_data_set().get_data(i).get_y_upper_err()[j];
}
else
{
chi[j]=(this->get_data_set().get_data(i).get_y()[j]-model_y[j])/this->get_data_set().get_data(i).get_y_lower_err()[j];
}
}
result+=sum(chi*chi);
}
return result;
}
};
}
#endif
//EOF
| 21.623656 | 166 | 0.552959 | [
"vector",
"model"
] |
b9a65f378f2476dd35a7e751176eb8468af8c741 | 10,924 | cxx | C++ | model_server/gala/dis_gala/monitorBatch.cxx | kit-transue/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | 2 | 2015-11-24T03:31:12.000Z | 2015-11-24T16:01:57.000Z | model_server/gala/dis_gala/monitorBatch.cxx | radtek/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | null | null | null | model_server/gala/dis_gala/monitorBatch.cxx | radtek/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | 1 | 2019-05-19T02:26:08.000Z | 2019-05-19T02:26:08.000Z | /*************************************************************************
* Copyright (c) 2015, Synopsys, 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 *
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
*************************************************************************/
#include "cLibraryFunctions.h"
#include "machdep.h"
#include <vport.h>
#include vtimerHEADER
#include veventHEADER
#include "gString.h"
#include "gcontrolObjects.h"
#include "gapl_menu.h"
#include "progressBar.h"
#include "monitorBatch.h"
int spawn_redirected( const char *pszCommand, const char *pszOutFile );
void process_terminate( int nPid );
int process_is_active( int nPid );
monitorBatch* monitorBatch::m_CurrInst = NULL;
//initialization routine
void monitorBatch::commonInit(int nCmds, char **Cmds, char**Cmts, Tcl_Interp *interp,
const char *cmd_when_done, const char *results_text_item,
const char *log_file )
{
m_CurrCommand = -1;
m_CurrPid = -1;
m_ProgressBar=NULL;
m_Interp = interp;
m_CmdWhenDone = (const vchar *)cmd_when_done;
for( int i = 0,n = 0; n<nCmds && i<MAX_CMDS_NUMBER; i ++, n++ )
{
//special 'hack' for -proj pass
int fParsed = 0;
if( Cmds[n] )
{
char *pProj = strstr( Cmds[n], "-proj " );
if( pProj )
{
//////////////////////////////////////////////////////////////////////////////////////////////////
// The following code attempts to parse a line of the following form:
// pset_server -blah -blah -blah -proj /proj1 /proj2 -blah blah blah
// by breaking it up into a prefix, a project list, and a suffix. Be careful not to add empty projects...
//////////////////////////////////////////////////////////////////////////////////////////////////
fParsed = 1;
pProj[5] = '\0';
char *pNextOpt = strstr( pProj + 6, " -" );
if( pNextOpt )
*pNextOpt = '\0';
static const char *seps = " ,;\t";
char *proj = strtok( pProj + 6, seps );
int fFirstFlag = 1;
while( proj && i<MAX_CMDS_NUMBER )
{
m_Commands[i] = (vchar *)Cmds[n];
m_Commands[i] += " ";
m_Commands[i] += proj;
if( pNextOpt )
{
m_Commands[i] += " ";
m_Commands[i] += (pNextOpt + 1);
}
if( fFirstFlag )
m_Comments[i] = (vchar *)Cmts[n];
else
m_Comments[i] = (const vchar *)"";
proj = strtok( NULL, seps );
//this is necessary to prevent a null project.
if (proj)
i++;
fFirstFlag = 0;
}
if( fFirstFlag )//if project list contained 0 items
fParsed = 0;
}
}
if( !fParsed )
{
m_Comments[i] = (vchar *)Cmts[n];
m_Commands[i] = (vchar *)Cmds[n];
}
}
m_NumCommands = i;
if( m_Interp && results_text_item&&*results_text_item )
m_TextItem = gdTextItem::CastDown((vdialogItem *)dis_findItem( m_Interp, (vchar*)results_text_item));
else
m_TextItem = NULL;
m_fIsTmpFile = 1;
//BEWARE-- StartNextCommand expects a valid filename. If you pass an illegal/invalid filename, an
// invalid monitorbatch object will be created and it will do nothing.
// sooner or later I'll fix it properly...(GRB)
//
if( log_file && OSapi_strlen (log_file) )
{
m_fIsTmpFile = 0;
m_LogFile = (const vchar *)log_file;
//truncate old log file
OSapi_unlink( log_file );
}
if( m_fIsTmpFile )
{
char *tmp_nam = OSapi_tempnam( ".", "dis" );
if( tmp_nam )
{
m_LogFile = (const vchar *)OSPATH(tmp_nam);
OSapi_free( tmp_nam );
}
else
m_LogFile = (const vchar *)"dis_tmp.tmp";
}
m_Timer = new vtimer();
if( m_Timer )
{
m_Timer->SetPeriod( 3, 0 ); //3 secs
m_Timer->SetRecurrent();
m_Timer->SetObserveTimerProc( BatchTimerObserveProc );
}
}
monitorBatch::monitorBatch( int nCmds, char **Cmds, char **Cmts, Tcl_Interp *interp,
const char *cmd_when_done, const char *results_text_item,
const char *log_file )
{
commonInit( nCmds, Cmds, Cmts, interp, cmd_when_done, results_text_item, log_file);
m_ProgressBar=NULL;
StartNextCommand();
if( m_TextItem )
m_TextItem->ShowFile( (vchar *)m_LogFile.str(), 1 );
if (m_Timer)
m_Timer->Start();
}
monitorBatch::monitorBatch( int nCmds, char **Cmds, char **Cmts, Tcl_Interp *interp,
const char *cmd_when_done, const char *results_text_item,
const char *log_file, char * pszStatusMessages )
{
commonInit(nCmds,Cmds, Cmts, interp, cmd_when_done, results_text_item, log_file);
//this should be the only ifdef in here.
#ifdef _WIN32
//////////////////////////////////////////////////////////////////////////////////////////////////
// Because of the -proj hack in commonInit, the the project pass is split into multiple invocations
// of pset_server. Consquently, we initialize the progress bar with the known number of invocations,
// not the number of invocations suggested by the caller
// commonInit must have run before this function.
//////////////////////////////////////////////////////////////////////////////////////////////////
m_ProgressBar = new progressBar(m_NumCommands, pszStatusMessages);
#else
m_ProgressBar=NULL;
#endif
StartNextCommand();
if( m_TextItem )
m_TextItem->ShowFile( (vchar *)m_LogFile.str(), 1 );
if (m_Timer)
m_Timer->Start();
}
static int handleDestroy(vevent *theEvent)
{
vtimer *pTimer = (vtimer *)theEvent->GetClientData();
if( pTimer )
delete pTimer;
return 1;
}
monitorBatch::~monitorBatch()
{
if( m_Timer )
{
if( m_Timer->IsActive() )
m_Timer->Stop();
//delayed vtimer deletion
vevent *event = veventCreateClient();
veventSetPriority(event, veventPRIORITY_MIN);
veventSetTarget(event, handleDestroy);
veventSetClientData(event, m_Timer);
_veventPostLater(event);
//delete m_Timer;
}
if (m_ProgressBar)
{
delete m_ProgressBar;
m_ProgressBar=NULL;
}
if( m_fIsTmpFile && m_LogFile.not_null() )
OSapi_unlink( (const char *)m_LogFile.str() );
}
//Static method
int monitorBatch::Create( int nCmds, char **Cmds, char **Cmts, Tcl_Interp *interp,
const char *cmd_when_done, const char *results_text_item,
const char *log_file )
{
int nRet = 0;
if( m_CurrInst )
delete m_CurrInst;
m_CurrInst = new monitorBatch( nCmds, Cmds, Cmts, interp, cmd_when_done,
results_text_item, log_file );
if( m_CurrInst )
nRet = 1;
return nRet;
}
int monitorBatch::Create( int nCmds, char **Cmds, char **Cmts, Tcl_Interp *interp,
const char *cmd_when_done, const char *results_text_item,
const char *log_file, char * pszStatusMessages )
{ int nRet = 0;
if( m_CurrInst )
delete m_CurrInst;
m_CurrInst = new monitorBatch( nCmds, Cmds, Cmts, interp, cmd_when_done,
results_text_item, log_file, pszStatusMessages );
if( m_CurrInst )
nRet = 1;
return nRet;
}
//Static method
int monitorBatch::IsActive()
{
return ( m_CurrInst!=NULL );
}
int monitorBatch::Done()
{
int nRet = 0;
if( m_TextItem )
m_TextItem->StopUpdating();
if (m_ProgressBar)
m_ProgressBar->StopProgressBar();
if ( m_Interp && m_CmdWhenDone.not_null() )
nRet = (Tcl_Eval( m_Interp, (char *)m_CmdWhenDone.str() ) == TCL_OK );
vwindow::Beep();
return nRet;
}
int monitorBatch::Cancel()
{
int nRet = 0;
if( m_CurrInst )
{
int nPid = m_CurrInst->m_CurrPid;
if( nPid != -1 )
process_terminate( nPid );
nRet = m_CurrInst->Done();
delete m_CurrInst;
m_CurrInst = NULL;
}
return nRet;
}
int monitorBatch::StartNextCommand()
{
m_CurrCommand++;
m_CurrPid = -1;
if( m_CurrCommand < m_NumCommands )
{
//write comment first
if( m_Comments[m_CurrCommand].not_null() )
{
#ifndef _WIN32
char *mode = "a+";
#else
char *mode = "a+t";
#endif
FILE *out_f = OSapi_fopen( (const char *)m_LogFile.str(), mode );
if( out_f )
{
fprintf( out_f, "\n%s\n", (const char *)m_Comments[m_CurrCommand].str() );
fflush( out_f );
OSapi_fclose( out_f );
}
}
if( m_Commands[m_CurrCommand].not_null() )
m_CurrPid = spawn_redirected( (const char *)m_Commands[m_CurrCommand].str(),
(const char *)m_LogFile.str() );
//update the progressbar
if (m_ProgressBar)
m_ProgressBar->ShowNextCommand();
}
return m_CurrPid;
}
void monitorBatch::BatchTimerObserveProc( vtimer * )
{
int nPid = m_CurrInst->m_CurrPid;
if (m_CurrInst->m_ProgressBar&&m_CurrInst->m_ProgressBar->QueryProgressBar()>0)
{
Cancel();
return;
}
if( !process_is_active( nPid ) )
{
if( m_CurrInst->m_CurrCommand < m_CurrInst->m_NumCommands - 1 )
m_CurrInst->StartNextCommand();
else
{
m_CurrInst->Done();
delete m_CurrInst;
m_CurrInst = NULL;
}
}
}
| 31.30086 | 111 | 0.575522 | [
"object"
] |
b9aa7dad9f4ff5ace3a0717e7fbc4b36b6559201 | 21,171 | cpp | C++ | rtc_stack/erizo/LibNiceConnection.cpp | anjisuan783/media_lib | c09c7d48f495a803df79e39cf837bbcb1320ceb8 | [
"MIT"
] | 9 | 2022-01-07T03:10:45.000Z | 2022-03-31T03:29:02.000Z | rtc_stack/erizo/LibNiceConnection.cpp | anjisuan783/mia | c09c7d48f495a803df79e39cf837bbcb1320ceb8 | [
"MIT"
] | 16 | 2021-12-17T08:32:57.000Z | 2022-03-10T06:16:14.000Z | rtc_stack/erizo/LibNiceConnection.cpp | anjisuan783/media_lib | c09c7d48f495a803df79e39cf837bbcb1320ceb8 | [
"MIT"
] | 1 | 2022-02-21T15:47:21.000Z | 2022-02-21T15:47:21.000Z | /*
* LibNiceConnection.cpp
*/
#include <nice/nice.h>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <mutex>
#include <iostream>
#include "rtc_base/object_pool.h"
#include "erizo/LibNiceConnection.h"
#include "erizo/SdpInfo.h"
#include "utils/Clock.h"
#define USER_PACKET_POOL
using namespace wa;
namespace erizo {
DEFINE_LOGGER(LibNiceConnection, "LibNiceConnection")
void cb_nice_recv(NiceAgent *, guint stream_id, guint component_id,
guint len, gchar* buf, gpointer user_data) {
if (user_data == NULL || len == 0) {
return;
}
LibNiceConnection* nicecon = reinterpret_cast<LibNiceConnection*>(user_data);
nicecon->onData(component_id, reinterpret_cast<char*> (buf), static_cast<unsigned int> (len));
}
void cb_new_candidate(NiceAgent *,
NiceCandidate *candidate,
gpointer user_data) {
LibNiceConnection *conn = reinterpret_cast<LibNiceConnection*>(user_data);
conn->gotCandidate(candidate);
}
void cb_candidate_gathering_done(NiceAgent *, guint stream_id, gpointer user_data) {
LibNiceConnection *conn = reinterpret_cast<LibNiceConnection*>(user_data);
conn->gatheringDone(stream_id);
}
void cb_component_state_changed(NiceAgent *, guint stream_id,
guint component_id, guint state, gpointer user_data) {
LibNiceConnection *conn = reinterpret_cast<LibNiceConnection*>(user_data);
if (state == NICE_COMPONENT_STATE_DISCONNECTED) {
} else if (state == NICE_COMPONENT_STATE_GATHERING) {
} else if (state == NICE_COMPONENT_STATE_CONNECTING) {
} else if (state == NICE_COMPONENT_STATE_CONNECTED) {
} else if (state == NICE_COMPONENT_STATE_READY) {
conn->updateComponentState(component_id, IceState::READY);
} else if (state == NICE_COMPONENT_STATE_LAST) {
} else if (state == NICE_COMPONENT_STATE_FAILED) {
conn->updateComponentState(component_id, IceState::FAILED);
}
}
void cb_new_selected_pair(NiceAgent *agent,
guint stream_id,
guint component_id,
NiceCandidate *lcandidate,
NiceCandidate *rcandidate,
gpointer user_data) {
LibNiceConnection *conn = reinterpret_cast<LibNiceConnection*>(user_data);
conn->updateComponentState(component_id, IceState::READY);
}
void cb_first_binding_request(NiceAgent *agent,
guint stream_id,
gpointer user_data){
//std::cout << "cb_first_binding_request" << "stream id:" << stream_id << std::endl;
}
void cb_new_remote_candidate(NiceAgent *,
NiceCandidate *candidate,
gpointer user_data){
assert(candidate);
LibNiceConnection *conn = reinterpret_cast<LibNiceConnection*>(user_data);
conn->onRemoteNewCandidate(candidate);
}
LibNiceConnection::LibNiceConnection(std::unique_ptr<LibNiceInterface> libnice,
const IceConfig& ice_config,
wa::IOWorker* worker)
: IceConnection{ice_config},
lib_nice_{std::move(libnice)},
agent_{NULL},
context_{NULL},
loop_{NULL},
candsDelivered_{0},
receivedLastCandidate_{false} {
#if !GLIB_CHECK_VERSION(2, 35, 0)
g_type_init();
#endif
context_ = worker->getMainContext();
loop_ = worker->getMainLoop();
}
LibNiceConnection::~LibNiceConnection() {
this->close();
}
void LibNiceConnection::close() {
if (checkIceState() == IceState::FINISHED) {
return;
}
updateIceState(IceState::FINISHED);
ELOG_DEBUG("%s message:closing", toLog());
{
std::lock_guard<std::mutex> guard(close_mutex_);
listener_.reset();
if (agent_ != NULL) {
g_object_unref(agent_);
agent_ = NULL;
}
}
ELOG_DEBUG("%s message: closed, this: %p", toLog(), this);
}
static std::mutex s_memory_pool_lock_;
static webrtc::ObjectPoolT<DataPacket> s_memory_pool_{102400};
DataPacket* DataPacketMaker(int _comp,
const char *_data,
int _length,
packetType _type,
uint64_t _received_time_ms) {
DataPacket* pkt = nullptr;
{
std::lock_guard<std::mutex> guard(s_memory_pool_lock_);
pkt = s_memory_pool_.New();
}
pkt->Init(_comp, _data, _length, _type, _received_time_ms);
return pkt;
}
void DataPacketDeleter(DataPacket* pkt) {
std::lock_guard<std::mutex> guard(s_memory_pool_lock_);
s_memory_pool_.Delete(pkt);
}
void LibNiceConnection::onData(unsigned int component_id, char* buf, int len) {
if (checkIceState() == IceState::READY) {
if (auto listener = getIceListener().lock()) {
#ifdef USER_PACKET_POOL
std::shared_ptr<DataPacket> packet(
DataPacketMaker(component_id, buf, len, VIDEO_PACKET, 0),
DataPacketDeleter);
#else
auto packet = std::make_shared<DataPacket>(
component_id, buf, len, VIDEO_PACKET, 0);
#endif
listener->onPacketReceived(std::move(packet));
}
}
}
int LibNiceConnection::sendData(unsigned int component_id, const void* buf, int len) {
int val = -1;
if (this->checkIceState() == IceState::READY) {
val = lib_nice_->NiceAgentSend(agent_, stream_id_,
component_id, len, reinterpret_cast<const gchar*>(buf));
}
if (val != len) {
ELOG_DEBUG("%s message: Sending less data than expected,"
" sent: %d, to_send: %d", toLog(), val, len);
}
return val;
}
void LibNiceConnection::start() {
std::lock_guard<std::mutex> guard(close_mutex_);
if (this->checkIceState() != INITIAL) {
return;
}
ELOG_TRACE("%s message: creating Nice Agent", toLog());
// Create a nice agent
agent_ = lib_nice_->NiceAgentNewFull(context_,
NICE_AGENT_OPTION_LITE_MODE|NICE_AGENT_OPTION_SUPPORT_RENOMINATION);
if (ice_config_.stun_server.compare("") != 0 && ice_config_.stun_port != 0) {
g_object_set(agent_, "stun-server", (gchar*)ice_config_.stun_server.c_str(), nullptr);
g_object_set(agent_, "stun-server-port", ice_config_.stun_port, nullptr);
ELOG_DEBUG("%s message: setting stun, stun_server: %s, stun_port: %d",
toLog(), ice_config_.stun_server.c_str(), ice_config_.stun_port);
}
gboolean controllingMode = {FALSE};
g_object_set(agent_, "controlling-mode", controllingMode, nullptr);
g_object_set(agent_, "max-connectivity-checks", 100, nullptr);
gboolean keep_alive = {TRUE};
g_object_set(agent_, "keepalive-conncheck", keep_alive, nullptr);
// Connect the signals
g_signal_connect(agent_, "candidate-gathering-done",
G_CALLBACK(cb_candidate_gathering_done), this);
g_signal_connect(agent_, "new-selected-pair-full",
G_CALLBACK(cb_new_selected_pair), this);
g_signal_connect(agent_, "component-state-changed",
G_CALLBACK(cb_component_state_changed), this);
g_signal_connect(agent_, "new-candidate-full",
G_CALLBACK(cb_new_candidate), this);
g_signal_connect(agent_, "initial-binding-request-received",
G_CALLBACK(cb_first_binding_request), this);
g_signal_connect(agent_, "new-remote-candidate-full",
G_CALLBACK(cb_new_remote_candidate), this);
// Create a new stream and start gathering candidates
ELOG_DEBUG("%s message: adding stream, iceComponents: %d", toLog(), ice_config_.ice_components);
stream_id_ = lib_nice_->NiceAgentAddStream(agent_, ice_config_.ice_components);
assert(stream_id_ != 0);
gchar *ufrag = NULL, *upass = NULL;
lib_nice_->NiceAgentGetLocalCredentials(agent_, stream_id_, &ufrag, &upass);
ufrag_ = std::string(ufrag);
g_free(ufrag);
upass_ = std::string(upass);
g_free(upass);
// Set our remote credentials. This must be done *after* we add a stream.
if (ice_config_.username.compare("") != 0 && ice_config_.password.compare("") != 0) {
ELOG_DEBUG("%s message: setting remote credentials in constructor, ufrag:%s, pass:%s",
toLog(), ice_config_.username.c_str(), ice_config_.password.c_str());
this->setRemoteCredentials(ice_config_.username, ice_config_.password);
}
// Set Port Range: If this doesn't work when linking the file libnice.sym has to be modified to include this call
if (ice_config_.min_port != 0 && ice_config_.max_port != 0) {
ELOG_DEBUG("%s message: setting port range, min_port: %d, max_port: %d",
toLog(), ice_config_.min_port, ice_config_.max_port);
lib_nice_->NiceAgentSetPortRange(agent_, stream_id_, (guint)ice_config_.ice_components,
(guint)ice_config_.min_port, (guint)ice_config_.max_port);
}
if (!ice_config_.network_interface.empty()) {
const char* public_ip = lib_nice_->NiceInterfacesGetIpForInterface(ice_config_.network_interface.c_str());
if (public_ip) {
lib_nice_->NiceAgentAddLocalAddress(agent_, public_ip);
}
}
if (ice_config_.ip_addresses.size() > 0) {
for (const auto& ipAddress : ice_config_.ip_addresses) {
lib_nice_->NiceAgentAddLocalAddress(agent_, ipAddress.c_str());
}
}
if (ice_config_.turn_server.compare("") != 0 && ice_config_.turn_port != 0) {
ELOG_DEBUG("%s message: configuring TURN, turn_server: %s , turn_port: %d, turn_username: %s, turn_pass: %s",
toLog(), ice_config_.turn_server.c_str(),
ice_config_.turn_port, ice_config_.turn_username.c_str(), ice_config_.turn_pass.c_str());
for (unsigned int i = 1; i <= ice_config_.ice_components ; i++) {
lib_nice_->NiceAgentSetRelayInfo(agent_,
stream_id_,
i,
ice_config_.turn_server.c_str(), // TURN Server IP
ice_config_.turn_port, // TURN Server PORT
ice_config_.turn_username.c_str(), // Username
ice_config_.turn_pass.c_str()); // Pass
}
}
if (agent_) {
for (unsigned int i = 1; i <= ice_config_.ice_components; i++) {
lib_nice_->NiceAgentAttachRecv(
agent_, stream_id_, i, context_, reinterpret_cast<void*>(cb_nice_recv), this);
}
}
ELOG_DEBUG("%s message: gathering, this: %p", toLog(), this);
lib_nice_->NiceAgentGatherCandidates(agent_, stream_id_);
}
void LibNiceConnection::mainLoop() {
// Start gathering candidates and fire event loop
ELOG_DEBUG("%s message: starting g_main_loop, this: %p", toLog(), this);
if (agent_ == NULL || loop_ == NULL) {
return;
}
ELOG_DEBUG("%s message: finished g_main_loop, this: %p", toLog(), this);
}
bool LibNiceConnection::setRemoteCandidates(const std::vector<CandidateInfo> &candidates, bool is_bundle) {
if (agent_ == NULL) {
this->close();
return false;
}
GSList* candList = NULL;
ELOG_DEBUG("%s message: setting remote candidates, candidateSize: %lu, mediaType: %d",
toLog(), candidates.size(), ice_config_.media_type);
for (unsigned int it = 0; it < candidates.size(); it++) {
NiceCandidateType nice_cand_type;
CandidateInfo cinfo = candidates[it];
// If bundle we will add the candidates regardless the mediaType
if (cinfo.componentId != 1 || (!is_bundle && cinfo.mediaType != ice_config_.media_type ))
continue;
if (strstr(cinfo.hostAddress.c_str(), ":") != NULL) // We ignore IPv6 candidates at this point
continue;
switch (cinfo.hostType) {
case HOST:
nice_cand_type = NICE_CANDIDATE_TYPE_HOST;
break;
case SRFLX:
nice_cand_type = NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE;
break;
case PRFLX:
nice_cand_type = NICE_CANDIDATE_TYPE_PEER_REFLEXIVE;
break;
case RELAY:
nice_cand_type = NICE_CANDIDATE_TYPE_RELAYED;
break;
default:
nice_cand_type = NICE_CANDIDATE_TYPE_HOST;
break;
}
if (cinfo.hostPort == 0) {
continue;
}
NiceCandidate* thecandidate = nice_candidate_new(nice_cand_type);
g_strlcpy(thecandidate->foundation, cinfo.foundation.c_str(), NICE_CANDIDATE_MAX_FOUNDATION);
thecandidate->username = strdup(cinfo.username.c_str());
thecandidate->password = strdup(cinfo.password.c_str());
thecandidate->stream_id = stream_id_;
thecandidate->component_id = cinfo.componentId;
thecandidate->priority = cinfo.priority;
thecandidate->transport = NICE_CANDIDATE_TRANSPORT_UDP;
nice_address_set_from_string(&thecandidate->addr, cinfo.hostAddress.c_str());
nice_address_set_port(&thecandidate->addr, cinfo.hostPort);
std::ostringstream host_info;
host_info << "hostType: " << cinfo.hostType
<< ", hostAddress: " << cinfo.hostAddress
<< ", hostPort: " << cinfo.hostPort;
if (cinfo.hostType == RELAY || cinfo.hostType == SRFLX) {
nice_address_set_from_string(&thecandidate->base_addr, cinfo.rAddress.c_str());
nice_address_set_port(&thecandidate->base_addr, cinfo.rPort);
ELOG_DEBUG("%s message: adding relay or srflx remote candidate, %s, rAddress: %s, rPort: %d",
toLog(), host_info.str().c_str(),
cinfo.rAddress.c_str(), cinfo.rPort);
} else {
ELOG_DEBUG("%s message: adding remote candidate, %s, priority: %d, componentId: %d, ufrag: %s, pass: %s",
toLog(), host_info.str().c_str(), cinfo.priority, cinfo.componentId, cinfo.username.c_str(),
cinfo.password.c_str());
}
candList = g_slist_prepend(candList, thecandidate);
}
// TODO(pedro): Set Component Id properly, now fixed at 1
lib_nice_->NiceAgentSetRemoteCandidates(agent_, stream_id_, 1, candList);
g_slist_free_full(candList, (GDestroyNotify)&nice_candidate_free);
return true;
}
void LibNiceConnection::gatheringDone(uint stream_id) {
ELOG_DEBUG("%s message: gathering done, stream_id: %u", toLog(), stream_id);
updateIceState(IceState::CANDIDATES_RECEIVED);
}
CandidateInfo LibNiceConnection::transformCandidate(NiceCandidate* cand, bool bLocal) {
char address[NICE_ADDRESS_STRING_LEN], baseAddress[NICE_ADDRESS_STRING_LEN];
nice_address_to_string(&cand->addr, address);
nice_address_to_string(&cand->base_addr, baseAddress);
CandidateInfo cand_info;
cand_info.isBundle = true;
cand_info.priority = cand->priority;
cand_info.componentId = cand->component_id;
cand_info.foundation = cand->foundation;
cand_info.hostAddress = std::string(address);
cand_info.hostPort = nice_address_get_port(&cand->addr);
cand_info.mediaType = ice_config_.media_type;
cand_info.netProtocol = "udp";
if (NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE == cand->transport) {
cand_info.netProtocol = "tcp";
}
cand_info.transProtocol = ice_config_.transport_name;
cand_info.username = bLocal ? getLocalUsername() : getRemoteUsername();
cand_info.password = bLocal ? getLocalPassword() : getRemotePassword();
/*
* NICE_CANDIDATE_TYPE_HOST,
* NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE,
* NICE_CANDIDATE_TYPE_PEER_REFLEXIVE,
* NICE_CANDIDATE_TYPE_RELAYED,
*/
switch (cand->type) {
case NICE_CANDIDATE_TYPE_HOST:
cand_info.hostType = HOST;
break;
case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
cand_info.hostType = SRFLX;
cand_info.rAddress = std::string(baseAddress);
cand_info.rPort = nice_address_get_port(&cand->base_addr);
break;
case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
cand_info.hostType = PRFLX;
break;
case NICE_CANDIDATE_TYPE_RELAYED:
cand_info.hostType = RELAY;
cand_info.rAddress = std::string(baseAddress);
cand_info.rPort = nice_address_get_port(&cand->base_addr);
break;
default:
break;
}
return cand_info;
}
void LibNiceConnection::gotCandidate(NiceCandidate* cand) {
CandidateInfo cand_info = transformCandidate(cand, true);
candsDelivered_++;
if ( strstr(cand_info.hostAddress.c_str(), ":") != NULL) { // We ignore IPv6 candidates at this point
return;
}
if (cand_info.hostPort == 0) {
return;
}
cand_info.username = ufrag_;
cand_info.password = upass_;
if (auto listener = this->getIceListener().lock()) {
listener->onCandidate(cand_info, this);
}
}
void LibNiceConnection::setRemoteCredentials(const std::string& username, const std::string& password) {
ELOG_DEBUG("%s message: setting remote credentials, ufrag: %s, pass: %s",
toLog(), username.c_str(), password.c_str());
ice_config_.username = username;
ice_config_.password = password;
lib_nice_->NiceAgentSetRemoteCredentials(agent_, stream_id_, username.c_str(), password.c_str());
}
void LibNiceConnection::updateComponentState(unsigned int component_id, IceState state) {
ELOG_TRACE("%s message: new ice component state, newState: %u, "
"transportName: %s, componentId %u, iceComponents: %u",
toLog(), state, ice_config_.transport_name.c_str(),
component_id, ice_config_.ice_components);
comp_state_list_[component_id] = state;
if (state == IceState::READY) {
for (unsigned int i = 1; i <= ice_config_.ice_components; i++) {
if (comp_state_list_[i] != IceState::READY) {
return;
}
}
} else if (state == IceState::FAILED) {
if (receivedLastCandidate_ || this->checkIceState() == IceState::READY) {
ELOG_WARN("%s message: component failed, ice_config_.transport_name: %s, componentId: %u",
toLog(), ice_config_.transport_name.c_str(), component_id);
for (unsigned int i = 1; i <= ice_config_.ice_components; i++) {
if (comp_state_list_[i] != IceState::FAILED) {
return;
}
}
} else {
ELOG_WARN("%s message: failed and not received all candidates, newComponentState:%u", toLog(), state);
return;
}
}
this->updateIceState(state);
}
std::string getHostTypeFromCandidate(NiceCandidate *candidate) {
switch (candidate->type) {
case NICE_CANDIDATE_TYPE_HOST: return "host";
case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE: return "serverReflexive";
case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE: return "peerReflexive";
case NICE_CANDIDATE_TYPE_RELAYED: return "relayed";
default: return "unknown";
}
}
CandidatePair LibNiceConnection::getSelectedPair() {
char ipaddr[NICE_ADDRESS_STRING_LEN];
CandidatePair selectedPair;
NiceCandidate* local, *remote;
lib_nice_->NiceAgentGetSelectedPair(agent_, stream_id_, 1, &local, &remote);
nice_address_to_string(&local->addr, ipaddr);
selectedPair.erizoCandidateIp = std::string(ipaddr);
selectedPair.erizoCandidatePort = nice_address_get_port(&local->addr);
selectedPair.erizoHostType = getHostTypeFromCandidate(local);
ELOG_DEBUG("%s message: selected pair, local_addr: %s, local_port: %d, local_type: %s",
toLog(), ipaddr, nice_address_get_port(&local->addr), selectedPair.erizoHostType.c_str());
nice_address_to_string(&remote->addr, ipaddr);
selectedPair.clientCandidateIp = std::string(ipaddr);
selectedPair.clientCandidatePort = nice_address_get_port(&remote->addr);
selectedPair.clientHostType = getHostTypeFromCandidate(local);
ELOG_INFO("%s message: selected pair, remote_addr: %s, remote_port: %d, remote_type: %s",
toLog(), ipaddr, nice_address_get_port(&remote->addr), selectedPair.clientHostType.c_str());
return selectedPair;
}
void LibNiceConnection::setReceivedLastCandidate(bool hasReceived) {
ELOG_DEBUG("%s message: setting hasReceivedLastCandidate, hasReceived: %u", toLog(), hasReceived);
this->receivedLastCandidate_ = hasReceived;
}
bool LibNiceConnection::removeRemoteCandidates() {
ELOG_DEBUG("remove remote candidates");
//nice_agent_remove_remote_candidates(agent_, stream_id_, 1, NULL);
return true;
}
void LibNiceConnection::onRemoteNewCandidate(NiceCandidate* candidate) {
ELOG_DEBUG("%s remote new candidate: join, this: %p", toLog(), this);
CandidateInfo can_info = transformCandidate(candidate, false);
std::vector<CandidateInfo> t{std::move(can_info)};
setRemoteCandidates(t, true);
}
LibNiceConnection* LibNiceConnection::create(
const IceConfig& ice_config, wa::IOWorker* worker) {
return new LibNiceConnection(std::make_unique<LibNiceInterfaceImpl>(), ice_config, worker);
}
void LibNiceConnection::libnice_log(const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data){
if (log_level == G_LOG_LEVEL_DEBUG) {
ELOG_DEBUG("[agent:%d-%s]msg:%s", user_data, log_domain, message);
} else if (log_level == G_LOG_LEVEL_ERROR || log_level == G_LOG_LEVEL_CRITICAL) {
ELOG_ERROR("[agent:%d-%s]msg:%s", user_data, log_domain, message);
} else if (log_level == G_LOG_LEVEL_INFO || log_level == G_LOG_LEVEL_MASK){
ELOG_INFO("[agent:%d-%s]msg:%s", user_data, log_domain, message);
} else if (log_level == G_LOG_LEVEL_WARNING ){
ELOG_WARN("[agent:%d-%s]msg:%s", user_data, log_domain, message);
}
}
} /* namespace erizo */
| 37.404594 | 117 | 0.680223 | [
"vector"
] |
b9adaa8cf69051716297c92a1af7a2fb0a23893f | 2,957 | cpp | C++ | EpicForceEngine/WxMagnumEditor/EditToolBarView.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | 1 | 2021-03-30T06:28:32.000Z | 2021-03-30T06:28:32.000Z | EpicForceEngine/WxMagnumEditor/EditToolBarView.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | EpicForceEngine/WxMagnumEditor/EditToolBarView.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | #include "EditToolBarView.h"
#include "ProjectView.h"
#include "Localization.h"
#include "BitmapCreater.h"
EditToolBarView::EditToolBarView(ProjectView *projectView_)
: wxAuiToolBar(projectView_, wxID_ANY,
wxPoint(0, 0), wxSize(960, 16),
wxAUI_TB_DEFAULT_STYLE /*| wxAUI_TB_OVERFLOW/* | wxAUI_TB_VERTICAL*/)
{
this->SetForegroundColour(wxColour( 0, 0, 0, 255));
this->SetBackgroundColour(wxColour(128, 128, 128, 255));
this->SetToolBitmapSize(wxSize(16,16));
this->AddTool(MenuCommand::MENU_EDIT_UNDO , Localization::getEditUndo() , wxArtProvider::GetBitmap(wxART_UNDO ), Localization::getEditUndo() );
this->AddTool(MenuCommand::MENU_EDIT_REDO , Localization::getEditRedo() , wxArtProvider::GetBitmap(wxART_REDO ), Localization::getEditRedo() );
this->AddSeparator();
this->AddTool(MenuCommand::MENU_EDIT_CUT , Localization::getEditCut() , wxArtProvider::GetBitmap(wxART_CUT ), Localization::getEditCut() );
this->AddTool(MenuCommand::MENU_EDIT_COPY , Localization::getEditCopy() , wxArtProvider::GetBitmap(wxART_COPY ), Localization::getEditCopy() );
this->AddTool(MenuCommand::MENU_EDIT_PASTE , Localization::getEditPaste() , wxArtProvider::GetBitmap(wxART_PASTE ), Localization::getEditPaste() );
this->AddSeparator();
this->AddTool(MenuCommand::MENU_EDIT_DELETE , Localization::getEditDelete() , wxArtProvider::GetBitmap(wxART_DELETE), Localization::getEditDelete() );
this->Realize();
enableUIEvent();
}
EditToolBarView::~EditToolBarView()
{
}
void EditToolBarView::diableUI(unsigned int flags)
{
}
void EditToolBarView::enableUI(unsigned int flags)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////
// View request update Model
////////////////////////////////////////////////////////////////////////////////////////////////
// Model request update View
void EditToolBarView::notify(int flags, ProjectModelBase &projectModel, const Vector<unsigned char> &buffer)
{
if(flags & ProjectModelBase::STATE_CHANGED)
{
if(projectModel.getCurrentState()=="DebugRun")
{
EnableTool(MenuCommand::MENU_EDIT_UNDO , false);
EnableTool(MenuCommand::MENU_EDIT_REDO , false);
EnableTool(MenuCommand::MENU_EDIT_CUT , false);
EnableTool(MenuCommand::MENU_EDIT_COPY , false);
EnableTool(MenuCommand::MENU_EDIT_PASTE , false);
EnableTool(MenuCommand::MENU_EDIT_DELETE, false);
Refresh();
}
else
{
EnableTool(MenuCommand::MENU_EDIT_UNDO , false); // , true);
EnableTool(MenuCommand::MENU_EDIT_REDO , false); // , true);
EnableTool(MenuCommand::MENU_EDIT_CUT , true);
EnableTool(MenuCommand::MENU_EDIT_COPY , true);
EnableTool(MenuCommand::MENU_EDIT_PASTE , true);
EnableTool(MenuCommand::MENU_EDIT_DELETE, true);
Refresh();
}
}
}
void EditToolBarView::disableUIEvent()
{
}
void EditToolBarView::enableUIEvent()
{
} | 37.910256 | 153 | 0.675347 | [
"vector",
"model"
] |
b9ade14a0b7d13772fb95e45dd41e02290fd7abb | 2,402 | hpp | C++ | src/project_build.hpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | src/project_build.hpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | src/project_build.hpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | #pragma once
#include "cmake.hpp"
#include "meson.hpp"
#include <boost/filesystem.hpp>
namespace Project {
class Build {
public:
virtual ~Build() {}
boost::filesystem::path project_path;
virtual boost::filesystem::path get_default_path();
virtual bool update_default(bool force = false) { return false; }
virtual boost::filesystem::path get_debug_path();
virtual bool update_debug(bool force = false) { return false; }
virtual std::string get_compile_command() { return std::string(); }
virtual boost::filesystem::path get_executable(const boost::filesystem::path &path) { return boost::filesystem::path(); }
/// Returns true if the project path reported by build system is correct
virtual bool is_valid() { return true; }
std::vector<std::string> get_exclude_folders();
static std::unique_ptr<Build> create(const boost::filesystem::path &path);
};
class CMakeBuild : public Build {
::CMake cmake;
public:
CMakeBuild(const boost::filesystem::path &path);
bool update_default(bool force = false) override;
bool update_debug(bool force = false) override;
std::string get_compile_command() override;
boost::filesystem::path get_executable(const boost::filesystem::path &path) override;
bool is_valid() override;
};
class MesonBuild : public Build {
Meson meson;
public:
MesonBuild(const boost::filesystem::path &path);
bool update_default(bool force = false) override;
bool update_debug(bool force = false) override;
std::string get_compile_command() override;
boost::filesystem::path get_executable(const boost::filesystem::path &path) override;
bool is_valid() override;
};
class CompileCommandsBuild : public Build {
public:
};
class CargoBuild : public Build {
public:
boost::filesystem::path get_default_path() override { return project_path / "target" / "debug"; }
bool update_default(bool force = false) override;
boost::filesystem::path get_debug_path() override { return get_default_path(); }
bool update_debug(bool force = false) override;
std::string get_compile_command() override;
boost::filesystem::path get_executable(const boost::filesystem::path &path) override;
};
class NpmBuild : public Build {
};
class PythonMain : public Build {
};
class GoBuild : public Build {
};
} // namespace Project
| 28.939759 | 125 | 0.703997 | [
"vector"
] |
b9b2967dd5f405345db5940ce33a9485b78bf5fc | 4,267 | cpp | C++ | src/ast/statements/controlblocks/Do_WhileBlock.cpp | totorigolo/caramel | 94c8a05c0a456be6b424d415cef19b7efdc3201b | [
"MIT"
] | null | null | null | src/ast/statements/controlblocks/Do_WhileBlock.cpp | totorigolo/caramel | 94c8a05c0a456be6b424d415cef19b7efdc3201b | [
"MIT"
] | null | null | null | src/ast/statements/controlblocks/Do_WhileBlock.cpp | totorigolo/caramel | 94c8a05c0a456be6b424d415cef19b7efdc3201b | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* 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 "Do_WhileBlock.h"
#include "../../../ir/BasicBlock.h"
#include "../../../ir/CFG.h"
#include "IfBlock.h"
#include "../../../ir/helpers/IROperatorHelper.h"
namespace caramel::ast {
Do_WhileBlock::Do_WhileBlock(
std::shared_ptr<caramel::ast::Expression> condition,
std::vector<std::shared_ptr<caramel::ast::Statement>> block,
antlr4::Token *token
) : ControlBlock(token, StatementType::DoWhileBlock),
mCondition{std::move(condition)},
mBlock{std::move(block)} {}
void Do_WhileBlock::acceptAstDotVisit() {
addNode(thisId(), "While");
visitChildrenAstDot();
}
void Do_WhileBlock::visitChildrenAstDot() {
addEdge(thisId(), mCondition->thisId(), "condition");
mCondition->acceptAstDotVisit();
addNode(thisId() + 1, "Block");
addEdge(thisId(), thisId() + 1);
for (const auto &blockStatement : mBlock) {
addEdge(thisId() + 1, blockStatement->thisId());
blockStatement->acceptAstDotVisit();
}
}
ir::GetBasicBlockReturn Do_WhileBlock::getBasicBlock(
ir::CFG *controlFlow
) {
ir::BasicBlock::Ptr bbDWcond = controlFlow->generateBasicBlock(ir::BasicBlock::getNextNumberName() + "_DWcond");
ir::BasicBlock::Ptr bbDWaction = controlFlow->generateBasicBlock(ir::BasicBlock::getNextNumberName() + "_DWaction");
ir::BasicBlock::Ptr bbDWend = controlFlow->generateBasicBlock(ir::BasicBlock::getNextNumberName() + "_DWend");
controlFlow->pushCurrentControlBlockEndBB(bbDWend);
bbDWaction->setExitWhenTrue(bbDWcond);
bbDWcond->setExitWhenTrue(bbDWaction);
bbDWcond->setExitWhenFalse(bbDWend);
// COND BB
if (mCondition->shouldReturnAnIR()) {
SAFE_ADD_INSTRUCTION(mCondition, bbDWcond); // bbDWcond->addInstruction(mCondition->getIR(bbDWcond));
} else if (mCondition->shouldReturnABasicBlock()) {
logger.warning() << "Untested BB in while block condition BB.";
auto[cond_begin, cond_end] = mCondition->getBasicBlock(controlFlow);
bbDWcond->setExitWhenTrue(cond_begin);
// bb has no when_false
cond_end->setExitWhenTrue(bbDWaction);
cond_end->setExitWhenFalse(bbDWend); //< ?? Check mElseBlock.empty() before
bbDWcond = cond_end->getNewWhenTrueBasicBlock("_DWcondafter");
}
// Action BB
for (auto const &statement : mBlock) {
if (statement->shouldReturnAnIR()) {
SAFE_ADD_INSTRUCTION(statement, bbDWaction); // bbDWaction->addInstruction(statement->getIR(bbDWaction));
} else if (statement->shouldReturnABasicBlock()) {
auto[then_begin, then_end] = statement->getBasicBlock(controlFlow);
then_end->setExitWhenTrue(bbDWaction->getNextWhenTrue());
// bbThen has no when_false
bbDWaction->setExitWhenTrue(then_begin);
// bbThen has no when_false
bbDWaction = then_end->getNewWhenTrueBasicBlock("_DWthenafter");
}
}
controlFlow->popCurrentControlBlockEndBB();
return {bbDWaction, bbDWend};
}
bool Do_WhileBlock::shouldReturnABasicBlock() const {
return true;
}
} // namespace caramel::ast
| 37.104348 | 120 | 0.701898 | [
"vector"
] |
b9b3ce394fad11ab8a7274af82a6eaedbb6275d6 | 811 | cpp | C++ | 1233.cpp | BYOUINZAKA/LeetCodeNotes | 48e1b4522c1f769eeec4944cfbd57abf1281d09a | [
"MIT"
] | null | null | null | 1233.cpp | BYOUINZAKA/LeetCodeNotes | 48e1b4522c1f769eeec4944cfbd57abf1281d09a | [
"MIT"
] | null | null | null | 1233.cpp | BYOUINZAKA/LeetCodeNotes | 48e1b4522c1f769eeec4944cfbd57abf1281d09a | [
"MIT"
] | null | null | null | /*
* @Author: Hata
* @Date: 2020-05-14 09:20:57
* @LastEditors: Hata
* @LastEditTime: 2020-05-14 09:49:51
* @FilePath: \LeetCode\1233.cpp
* @Description: https://leetcode-cn.com/problems/remove-sub-folders-from-the-filesystem/
*/
#include <bits/stdc++.h>
class Solution
{
public:
std::vector<std::string> removeSubfolders(std::vector<std::string> &folder)
{
std::vector<std::string> res;
std::sort(folder.begin(), folder.end());
for (auto it = folder.begin(); it != folder.end();)
{
res.push_back(*it);
it = std::find_if_not(it + 1, folder.end(), [&it](const auto &s) {
return s.substr(0, it->length()) == *it && (s[it->length()] == '/' || s.length() <= it->length());
});
}
return res;
}
}; | 30.037037 | 114 | 0.548705 | [
"vector"
] |
b9b3f29ca909573990218b0b45d5348028c78c80 | 3,924 | hh | C++ | gazebo/physics/bullet/BulletUniversalJoint.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 887 | 2020-04-18T08:43:06.000Z | 2022-03-31T11:58:50.000Z | gazebo/physics/bullet/BulletUniversalJoint.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 462 | 2020-04-21T21:59:19.000Z | 2022-03-31T23:23:21.000Z | gazebo/physics/bullet/BulletUniversalJoint.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 421 | 2020-04-21T09:13:03.000Z | 2022-03-30T02:22:01.000Z | /*
* Copyright (C) 2012 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _GAZEBO_BULLETUNIVERSALJOINT_HH_
#define _GAZEBO_BULLETUNIVERSALJOINT_HH_
#include <string>
#include "gazebo/physics/bullet/gzBtUniversalConstraint.hh"
#include "gazebo/physics/UniversalJoint.hh"
#include "gazebo/physics/bullet/BulletJoint.hh"
#include "gazebo/physics/bullet/BulletPhysics.hh"
#include "gazebo/util/system.hh"
class btUniversalConstraint;
namespace gazebo
{
namespace physics
{
/// \ingroup gazebo_physics
/// \addtogroup gazebo_physics_bullet Bullet Physics
/// \{
/// \brief A bullet universal joint class
class GZ_PHYSICS_VISIBLE BulletUniversalJoint
: public UniversalJoint<BulletJoint>
{
/// \brief Constructor
public: BulletUniversalJoint(btDynamicsWorld *world, BasePtr _parent);
/// \brief Destuctor
public: virtual ~BulletUniversalJoint();
// Documentation inherited.
public: virtual void Load(sdf::ElementPtr _sdf);
// Documentation inherited.
public: virtual void Init();
// Documentation inherited.
public: virtual ignition::math::Vector3d Anchor(
const unsigned int _index) const;
// Documentation inherited.
public: void SetAxis(const unsigned int _index,
const ignition::math::Vector3d &_axis);
// Documentation inherited.
public: virtual void SetVelocity(unsigned int _index, double _angle);
// Documentation inherited.
public: virtual double GetVelocity(unsigned int _index) const;
// Documentation inherited.
public: virtual void SetUpperLimit(const unsigned int _index,
const double _limit);
// Documentation inherited.
public: virtual void SetLowerLimit(const unsigned int _index,
const double _limit);
// Documentation inherited.
public: virtual double UpperLimit(const unsigned int _index) const;
// Documentation inherited.
public: virtual double LowerLimit(const unsigned int _index) const;
// Documentation inherited. \sa Joint::GlobalAxis
public: virtual ignition::math::Vector3d GlobalAxis(
const unsigned int _index) const;
// Documentation inherited.
public: virtual double PositionImpl(const unsigned int _index) const;
// Documentation inherited.
public: virtual bool SetParam(const std::string &_key,
unsigned int _index,
const boost::any &_value);
// Documentation inherited.
public: virtual double GetParam(const std::string &_key,
unsigned int _index);
// Documentation inherited. \sa void BulletJoint::SetForceImpl
protected: virtual void SetForceImpl(unsigned int _index, double _torque);
/// \brief Pointer to bullet universal constraint
private: gzBtUniversalConstraint *bulletUniversal;
/// \brief Offset angle used in PositionImpl, so that angles are reported
/// relative to the initial configuration.
private: double angleOffset[2];
/// \brief Initial value of joint axis, expressed as unit vector
/// in world frame.
private: ignition::math::Vector3d initialWorldAxis[2];
};
/// \}
}
}
#endif
| 34.121739 | 80 | 0.67737 | [
"vector"
] |
b9beeef8d4ecda92d47a1ba2f276ea24ed5f058c | 570 | cpp | C++ | rmsFunc.cpp | jdavidrcamacho/cppRandom | 2d19a0d4ab581c36c05f514d9c2abf7b84562fdf | [
"MIT"
] | null | null | null | rmsFunc.cpp | jdavidrcamacho/cppRandom | 2d19a0d4ab581c36c05f514d9c2abf7b84562fdf | [
"MIT"
] | null | null | null | rmsFunc.cpp | jdavidrcamacho/cppRandom | 2d19a0d4ab581c36c05f514d9c2abf7b84562fdf | [
"MIT"
] | null | null | null | //root mean squared error file;
#include <iostream>
#include <vector>
#include <cmath>
#include "rmsFunc.h"
using namespace std;
/* Root mean square error*/
float rms(std::vector<float> data, std::vector<float> func){
for (int n = 0; n < data.size(); n++){
data[n] = func[n] - data[n];
}
float m = mean(data);
for (int n = 0; n < data.size(); n++){
data[n] = (data[n] - m) * (data[n] - m);
}
m = 0;
for (int n = 0; n < data.size(); n++){
m += data[n];
}
answer = sqrt(m / data.size());
return answer;
} | 22.8 | 60 | 0.522807 | [
"vector"
] |
b9c0b0c4ee1957fce48641230cef6391bcc9180e | 2,362 | cc | C++ | tensorflow/compiler/xla/service/hlo_proto_util.cc | hsm207/tensorflow | 8ab4678ba216c3ec8fa32f417cb667b056689939 | [
"Apache-2.0"
] | 4 | 2021-06-15T17:26:07.000Z | 2021-11-17T10:58:08.000Z | tensorflow/compiler/xla/service/hlo_proto_util.cc | hsm207/tensorflow | 8ab4678ba216c3ec8fa32f417cb667b056689939 | [
"Apache-2.0"
] | 1 | 2018-09-17T19:30:27.000Z | 2018-09-17T19:30:27.000Z | tensorflow/compiler/xla/service/hlo_proto_util.cc | hsm207/tensorflow | 8ab4678ba216c3ec8fa32f417cb667b056689939 | [
"Apache-2.0"
] | 6 | 2018-12-20T01:35:20.000Z | 2020-07-10T17:29:57.000Z | /* Copyright 2017 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/compiler/xla/service/hlo_proto_util.h"
#include <string>
#include "tensorflow/compiler/xla/util.h"
namespace xla {
HloProto MakeHloProto(const HloModule& module,
const BufferAssignment& assignment) {
BufferAssignmentProto proto_assignment = assignment.ToProto();
HloProto proto = MakeHloProto(module);
proto.mutable_buffer_assignment()->Swap(&proto_assignment);
return proto;
}
HloProto MakeHloProto(const HloModule& module) {
HloModuleProto proto_module = module.ToProto();
HloProto proto;
proto.mutable_hlo_module()->Swap(&proto_module);
return proto;
}
StatusOr<std::vector<const Shape*>> EntryComputationParameterShapes(
const HloProto& hlo_proto) {
if (!hlo_proto.has_hlo_module()) {
return NotFound("HloProto missing HloModuleProto.");
}
if (!hlo_proto.hlo_module().has_program_shape()) {
return NotFound("HloProto missing program shape.");
}
std::vector<const Shape*> parameter_shapes;
const auto& program_shape = hlo_proto.hlo_module().program_shape();
for (const Shape& shape : program_shape.parameters()) {
parameter_shapes.push_back(&shape);
}
return parameter_shapes;
}
StatusOr<const Shape*> EntryComputationOutputShape(const HloProto& hlo_proto) {
if (!hlo_proto.has_hlo_module()) {
return NotFound("HloProto missing HloModuleProto.");
}
if (!hlo_proto.hlo_module().has_program_shape()) {
return NotFound("HloProto missing program shape.");
}
if (!hlo_proto.hlo_module().program_shape().has_result()) {
return NotFound("HloProto missing result in its program shape");
}
return &hlo_proto.hlo_module().program_shape().result();
}
} // namespace xla
| 33.267606 | 80 | 0.723116 | [
"shape",
"vector"
] |
b9c35ba9d4170baca93a537ccf11b368abef773e | 14,669 | cpp | C++ | LearnOpenGL/src/2.lighting/multiple_light.cpp | jisudong/LearnOpenGL | 105975a6a9b305a9cc7d9d9e567f868fc10e7186 | [
"MIT"
] | 1 | 2019-12-06T06:23:18.000Z | 2019-12-06T06:23:18.000Z | LearnOpenGL/src/2.lighting/multiple_light.cpp | jisudong/LearnOpenGL | 105975a6a9b305a9cc7d9d9e567f868fc10e7186 | [
"MIT"
] | null | null | null | LearnOpenGL/src/2.lighting/multiple_light.cpp | jisudong/LearnOpenGL | 105975a6a9b305a9cc7d9d9e567f868fc10e7186 | [
"MIT"
] | null | null | null | //
// multiple_light.cpp
// testgl
//
// Created by apple on 2019/5/30.
// Copyright © 2019 自动化. All rights reserved.
//
#include "multiple_light.hpp"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "shader.h"
#include "camera.h"
#include "stb_image.h"
void multiple_framebuffer_callback(GLFWwindow *window, int width, int height);
void multiple_input_process(GLFWwindow *window);
void multiple_mouse_callback(GLFWwindow *window, double xpos, double ypos);
void multiple_scroll_callback(GLFWwindow *window, double xoffset, double yoffset);
unsigned int multiple_loadTexture(char const *path);
const unsigned int MULTIPLE_SCR_WIDTH = 800;
const unsigned int MULTIPLE_SCR_HEIGHT = 600;
Camera multiple_camera(glm::vec3(0.0f, 0.0f, 3.0f));
float multiple_lastX = MULTIPLE_SCR_WIDTH / 2.0f;
float multiple_lastY = MULTIPLE_SCR_HEIGHT / 2.0f;
bool multiple_firstMouse = true;
float multiple_deltaTime = 0.0f;
float multiple_lastFrame = 0.0f;
glm::vec3 multiple_lightPos(0.8f, 0.4f, 1.5f);
int multiple() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
#endif
GLFWwindow *window = glfwCreateWindow(MULTIPLE_SCR_WIDTH, MULTIPLE_SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL) {
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, multiple_framebuffer_callback);
glfwSetCursorPosCallback(window, multiple_mouse_callback);
glfwSetScrollCallback(window, multiple_scroll_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
return -1;
}
glEnable(GL_DEPTH_TEST);
Shader lightingShader("./GLSL/2.lighting/6.1.multiple_light.vs", "./GLSL/2.lighting/6.1.multiple_light.fs");
Shader lampShader("./GLSL/2.lighting/6.1.lamp.vs", "./GLSL/2.lighting/6.1.lamp.fs");
float vertices[] = {
// positions // normals // texture coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
// positions all containers
glm::vec3 cubePositions[] = {
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3( 2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3( 1.3f, -2.0f, -2.5f),
glm::vec3( 1.5f, 2.0f, -2.5f),
glm::vec3( 1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
glm::vec3 pointLightPositions[] = {
glm::vec3( 0.7f, 0.2f, 2.0f),
glm::vec3( 2.3f, -3.3f, -4.0f),
glm::vec3(-4.0f, 2.0f, -12.0f),
glm::vec3( 0.0f, 0.0f, -3.0f)
};
unsigned int VBO, cubeVAO;
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(cubeVAO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
// second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube)
unsigned int lightVAO;
glGenVertexArrays(1, &lightVAO);
glBindVertexArray(lightVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// note that we update the lamp's position attribute's stride to reflect the updated buffer data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
lightingShader.use();
unsigned int diffuseMap = multiple_loadTexture("./resources/textures/container2.png");
unsigned int specularMap = multiple_loadTexture("./resources/textures/container2_specular.png");
while (!glfwWindowShouldClose(window)) {
float currentFrame = glfwGetTime();
multiple_deltaTime = currentFrame - multiple_lastFrame;
multiple_lastFrame = currentFrame;
multiple_input_process(window);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
lightingShader.use();
lightingShader.setVec3("viewPos", multiple_camera.Position);
lightingShader.setFloat("material.shininess", 32.0f);
// 平行光
lightingShader.setVec3("dirLight.direction", -0.2f, -1.0f, -0.3f);
lightingShader.setVec3("dirLight.ambient", 0.05f, 0.05f, 0.05f);
lightingShader.setVec3("dirLight.diffuse", glm::vec3(0.4f));
lightingShader.setVec3("dirLight.specular", 0.5f, 0.5f, 0.5f);
// 点光1
lightingShader.setVec3("pointLights[0].position", pointLightPositions[0]);
lightingShader.setVec3("pointLights[0].ambient", 0.05f, 0.05f, 0.05f);
lightingShader.setVec3("pointLights[0].diffuse", 0.8f, 0.8f, 0.8f);
lightingShader.setVec3("pointLights[0].ambient", 1.0f, 1.0f, 1.0f);
lightingShader.setFloat("pointLights[0].constant", 1.0f);
lightingShader.setFloat("pointLights[0].linear", 0.09f);
lightingShader.setFloat("pointLights[0].quadratic", 0.032f);
// 点光2
lightingShader.setVec3("pointLights[1].position", pointLightPositions[1]);
lightingShader.setVec3("pointLights[1].ambient", 0.05f, 0.05f, 0.05f);
lightingShader.setVec3("pointLights[1].diffuse", 0.8f, 0.8f, 0.8f);
lightingShader.setVec3("pointLights[1].ambient", 1.0f, 1.0f, 1.0f);
lightingShader.setFloat("pointLights[1].constant", 1.0f);
lightingShader.setFloat("pointLights[1].linear", 0.09f);
lightingShader.setFloat("pointLights[1].quadratic", 0.032f);
// 点光3
lightingShader.setVec3("pointLights[2].position", pointLightPositions[2]);
lightingShader.setVec3("pointLights[2].ambient", 0.05f, 0.05f, 0.05f);
lightingShader.setVec3("pointLights[2].diffuse", 0.8f, 0.8f, 0.8f);
lightingShader.setVec3("pointLights[2].ambient", 1.0f, 1.0f, 1.0f);
lightingShader.setFloat("pointLights[2].constant", 1.0f);
lightingShader.setFloat("pointLights[2].linear", 0.09f);
lightingShader.setFloat("pointLights[2].quadratic", 0.032f);
// 点光4
lightingShader.setVec3("pointLights[3].position", pointLightPositions[3]);
lightingShader.setVec3("pointLights[3].ambient", 0.05f, 0.05f, 0.05f);
lightingShader.setVec3("pointLights[3].diffuse", 0.8f, 0.8f, 0.8f);
lightingShader.setVec3("pointLights[3].ambient", 1.0f, 1.0f, 1.0f);
lightingShader.setFloat("pointLights[3].constant", 1.0f);
lightingShader.setFloat("pointLights[3].linear", 0.09f);
lightingShader.setFloat("pointLights[3].quadratic", 0.032f);
// 聚光
lightingShader.setVec3("spotLight.position", multiple_camera.Position);
lightingShader.setVec3("spotLight.direction", multiple_camera.Front);
lightingShader.setVec3("spotLight.ambient", 0.0f, 0.0f, 0.0f);
lightingShader.setVec3("spotLight.diffuse", 1.0f, 1.0f, 1.0f);
lightingShader.setVec3("spotLight.specular", 1.0f, 1.0f, 1.0f);
lightingShader.setFloat("spotLight.constant", 1.0f);
lightingShader.setFloat("spotLight.linear", 0.09f);
lightingShader.setFloat("spotLight.quadratic", 0.032f);
lightingShader.setFloat("spotLight.cutOff", glm::cos(glm::radians(12.5f)));
lightingShader.setFloat("spotLight.outerCutOff", glm::cos(glm::radians(15.0f)));
glm::mat4 projection = glm::perspective(glm::radians(multiple_camera.Zoom), (float)MULTIPLE_SCR_WIDTH/(float)MULTIPLE_SCR_HEIGHT, 0.1f, 100.0f);
glm::mat4 view = multiple_camera.getViewMatrix();
lightingShader.setMat4("projection", projection);
lightingShader.setMat4("view", view);
glm::mat4 model = glm::mat4(1.0f);
lightingShader.setMat4("model", model);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, diffuseMap);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, specularMap);
glBindVertexArray(cubeVAO);
for (unsigned int i = 0; i < 10; i++) {
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, cubePositions[i]);
float angle = 20.0f * i;
model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
lightingShader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
lampShader.use();
lampShader.setMat4("projection", projection);
lampShader.setMat4("view", view);
glBindVertexArray(lightVAO);
for (unsigned int i = 0; i < 4; i++) {
model = glm::mat4(1.0f);
model = glm::translate(model, pointLightPositions[i]);
model = glm::scale(model, glm::vec3(0.2f));
lampShader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &cubeVAO);
glDeleteVertexArrays(1, &lightVAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
void multiple_framebuffer_callback(GLFWwindow *window, int width, int height) {
glViewport(0, 0, width, height);
}
void multiple_input_process(GLFWwindow *window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
multiple_camera.processKeyboard(FORWARD, multiple_deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
multiple_camera.processKeyboard(BACKWARD, multiple_deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
multiple_camera.processKeyboard(LEFT, multiple_deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
multiple_camera.processKeyboard(RIGHT, multiple_deltaTime);
}
}
void multiple_mouse_callback(GLFWwindow *window, double xpos, double ypos) {
if (multiple_firstMouse) {
multiple_lastX = xpos;
multiple_lastY = ypos;
multiple_firstMouse = false;
}
float xoffset = xpos - multiple_lastX;
float yoffset = multiple_lastY - ypos;
multiple_lastX = xpos;
multiple_lastY = ypos;
multiple_camera.processMouseMovement(xoffset, yoffset);
}
void multiple_scroll_callback(GLFWwindow *window, double xoffset, double yoffset) {
multiple_camera.processMouseScroll(yoffset);
}
unsigned int multiple_loadTexture(char const *path) {
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data) {
GLenum format;
if (nrComponents == 1) {
format = GL_RED;
} else if (nrComponents == 3) {
format = GL_RGB;
} else if (nrComponents == 4) {
format = GL_RGBA;
}
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
} else {
std::cout << "Texture failed to load path" << path << std::endl;
}
stbi_image_free(data);
return textureID;
}
| 42.891813 | 152 | 0.611766 | [
"object",
"model",
"3d"
] |
844ef237e068b1ba6f8fee200ce77c9eb19cd1e3 | 195 | cpp | C++ | regression/esbmc-cpp/vector/vector5/main.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 143 | 2015-06-22T12:30:01.000Z | 2022-03-21T08:41:17.000Z | regression/esbmc-cpp/vector/vector5/main.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 542 | 2017-06-02T13:46:26.000Z | 2022-03-31T16:35:17.000Z | regression/esbmc-cpp/vector/vector5/main.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 81 | 2015-10-21T22:21:59.000Z | 2022-03-24T14:07:55.000Z | #include <cassert>
#include <vector>
using namespace std;
int main() {
vector<int> vectorOne(10,5);
vector<int> vectorTwo(vectorOne);
assert(vectorTwo.front() == 10);
return 0;
}
| 16.25 | 37 | 0.65641 | [
"vector"
] |
844f4be30f6164b26d85000894c44fb93e4e7242 | 3,794 | cpp | C++ | interface/src/audio/AudioToolBox.cpp | ey6es/hifi | 23f9c799dde439e4627eef45341fb0d53feff80b | [
"Apache-2.0"
] | null | null | null | interface/src/audio/AudioToolBox.cpp | ey6es/hifi | 23f9c799dde439e4627eef45341fb0d53feff80b | [
"Apache-2.0"
] | null | null | null | interface/src/audio/AudioToolBox.cpp | ey6es/hifi | 23f9c799dde439e4627eef45341fb0d53feff80b | [
"Apache-2.0"
] | null | null | null | //
// AudioToolBox.cpp
// interface/src/audio
//
// Created by Stephen Birarda on 2014-12-16.
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "InterfaceConfig.h"
#include <GLCanvas.h>
#include <PathUtils.h>
#include <GeometryCache.h>
#include "Audio.h"
#include "AudioToolBox.h"
// Mute icon configration
const int MUTE_ICON_SIZE = 24;
AudioToolBox::AudioToolBox() :
_iconPulseTimeReference(usecTimestampNow())
{
}
bool AudioToolBox::mousePressEvent(int x, int y) {
if (_iconBounds.contains(x, y)) {
DependencyManager::get<Audio>()->toggleMute();
return true;
}
return false;
}
void AudioToolBox::render(int x, int y, bool boxed) {
glEnable(GL_TEXTURE_2D);
auto glCanvas = DependencyManager::get<GLCanvas>();
if (_micTextureId == 0) {
_micTextureId = glCanvas->bindTexture(QImage(PathUtils::resourcesPath() + "images/mic.svg"));
}
if (_muteTextureId == 0) {
_muteTextureId = glCanvas->bindTexture(QImage(PathUtils::resourcesPath() + "images/mic-mute.svg"));
}
if (_boxTextureId == 0) {
_boxTextureId = glCanvas->bindTexture(QImage(PathUtils::resourcesPath() + "images/audio-box.svg"));
}
auto audioIO = DependencyManager::get<Audio>();
if (boxed) {
bool isClipping = ((audioIO->getTimeSinceLastClip() > 0.0f) && (audioIO->getTimeSinceLastClip() < 1.0f));
const int BOX_LEFT_PADDING = 5;
const int BOX_TOP_PADDING = 10;
const int BOX_WIDTH = 266;
const int BOX_HEIGHT = 44;
QRect boxBounds = QRect(x - BOX_LEFT_PADDING, y - BOX_TOP_PADDING, BOX_WIDTH, BOX_HEIGHT);
glBindTexture(GL_TEXTURE_2D, _boxTextureId);
if (isClipping) {
glColor3f(1.0f, 0.0f, 0.0f);
} else {
glColor3f(0.41f, 0.41f, 0.41f);
}
glm::vec2 topLeft(boxBounds.left(), boxBounds.top());
glm::vec2 bottomRight(boxBounds.right(), boxBounds.bottom());
glm::vec2 texCoordTopLeft(1,1);
glm::vec2 texCoordBottomRight(0,0);
DependencyManager::get<GeometryCache>()->renderQuad(topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight);
}
float iconColor = 1.0f;
_iconBounds = QRect(x, y, MUTE_ICON_SIZE, MUTE_ICON_SIZE);
if (!audioIO->isMuted()) {
glBindTexture(GL_TEXTURE_2D, _micTextureId);
iconColor = 1.0f;
} else {
glBindTexture(GL_TEXTURE_2D, _muteTextureId);
// Make muted icon pulsate
static const float PULSE_MIN = 0.4f;
static const float PULSE_MAX = 1.0f;
static const float PULSE_FREQUENCY = 1.0f; // in Hz
qint64 now = usecTimestampNow();
if (now - _iconPulseTimeReference > (qint64)USECS_PER_SECOND) {
// Prevents t from getting too big, which would diminish glm::cos precision
_iconPulseTimeReference = now - ((now - _iconPulseTimeReference) % USECS_PER_SECOND);
}
float t = (float)(now - _iconPulseTimeReference) / (float)USECS_PER_SECOND;
float pulseFactor = (glm::cos(t * PULSE_FREQUENCY * 2.0f * PI) + 1.0f) / 2.0f;
iconColor = PULSE_MIN + (PULSE_MAX - PULSE_MIN) * pulseFactor;
}
glColor3f(iconColor, iconColor, iconColor);
glm::vec2 topLeft(_iconBounds.left(), _iconBounds.top());
glm::vec2 bottomRight(_iconBounds.right(), _iconBounds.bottom());
glm::vec2 texCoordTopLeft(1,1);
glm::vec2 texCoordBottomRight(0,0);
DependencyManager::get<GeometryCache>()->renderQuad(topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight);
glDisable(GL_TEXTURE_2D);
} | 34.18018 | 120 | 0.648392 | [
"render"
] |
8450affb8a6cc2bab8f4c970f4cf6a9e47d53269 | 4,919 | cpp | C++ | engine/src/blazing_table/BlazingHostTable.cpp | Ethyling/blazingsql | 973e868e5f0a80189b69e56090ef2dc26ac90aa1 | [
"Apache-2.0"
] | 1,059 | 2019-08-05T13:14:42.000Z | 2019-11-28T21:03:23.000Z | engine/src/blazing_table/BlazingHostTable.cpp | ciusji/blazingsql | a35643d4c983334757eee96d5b9005b8b9fbd21b | [
"Apache-2.0"
] | 1,140 | 2019-11-30T00:36:17.000Z | 2022-03-31T22:51:51.000Z | engine/src/blazing_table/BlazingHostTable.cpp | ciusji/blazingsql | a35643d4c983334757eee96d5b9005b8b9fbd21b | [
"Apache-2.0"
] | 109 | 2019-12-13T08:31:43.000Z | 2022-03-31T06:01:26.000Z | #include "BlazingHostTable.h"
#include "bmr/BlazingMemoryResource.h"
#include "bmr/BufferProvider.h"
#include "rmm/cuda_stream_view.hpp"
#include "rmm/device_buffer.hpp"
#include "communication/CommunicationInterface/serializer.hpp"
using namespace fmt::literals;
namespace ral {
namespace frame {
BlazingHostTable::BlazingHostTable(const std::vector<ColumnTransport> &columns_offsets,
std::vector<ral::memory::blazing_chunked_column_info> && chunked_column_infos,
std::vector<std::unique_ptr<ral::memory::blazing_allocation_chunk>> && allocations)
: columns_offsets{columns_offsets}, chunked_column_infos{std::move(chunked_column_infos)}, allocations{std::move(allocations)} {
auto size = sizeInBytes();
blazing_host_memory_resource::getInstance().allocate(size); // this only increments the memory usage counter for the host memory. This does not actually allocate
}
BlazingHostTable::~BlazingHostTable() {
auto size = sizeInBytes();
blazing_host_memory_resource::getInstance().deallocate(size); // this only decrements the memory usage counter for the host memory. This does not actually allocate
for(auto i = 0; i < allocations.size(); i++){
auto pool = allocations[i]->allocation->pool;
pool->free_chunk(std::move(allocations[i]));
}
}
std::vector<cudf::data_type> BlazingHostTable::get_schema() const {
std::vector<cudf::data_type> data_types(this->num_columns());
std::transform(columns_offsets.begin(), columns_offsets.end(), data_types.begin(), [](auto &col) {
int32_t dtype = col.metadata.dtype;
return cudf::data_type{cudf::type_id(dtype)};
});
return data_types;
}
std::vector<std::string> BlazingHostTable::names() const {
std::vector<std::string> col_names(this->num_columns());
std::transform(columns_offsets.begin(), columns_offsets.end(), col_names.begin(),
[](auto &col) { return col.metadata.col_name; });
return col_names;
}
void BlazingHostTable::set_names(std::vector<std::string> names) {
for(size_t i = 0; i < names.size(); i++){
strcpy(columns_offsets[i].metadata.col_name, names[i].c_str());
}
}
cudf::size_type BlazingHostTable::num_rows() const {
return columns_offsets.empty() ? 0 : columns_offsets.front().metadata.size;
}
cudf::size_type BlazingHostTable::num_columns() const {
return columns_offsets.size();
}
std::size_t BlazingHostTable::sizeInBytes() {
std::size_t total_size = 0L;
for (auto &col : columns_offsets) {
total_size += col.size_in_bytes;
}
return total_size;
}
void BlazingHostTable::setPartitionId(const size_t &part_id) {
this->part_id = part_id;
}
size_t BlazingHostTable::get_part_id() {
return this->part_id;
}
const std::vector<ColumnTransport> &BlazingHostTable::get_columns_offsets() const {
return columns_offsets;
}
std::unique_ptr<BlazingTable> BlazingHostTable::get_gpu_table() const {
std::vector<rmm::device_buffer> gpu_raw_buffers(chunked_column_infos.size());
try{
int buffer_index = 0;
for(auto & chunked_column_info : chunked_column_infos){
gpu_raw_buffers[buffer_index].resize(chunked_column_info.use_size, rmm::cuda_stream_view{});
size_t position = 0;
for(size_t i = 0; i < chunked_column_info.chunk_index.size(); i++){
size_t chunk_index = chunked_column_info.chunk_index[i];
size_t offset = chunked_column_info.offset[i];
size_t chunk_size = chunked_column_info.size[i];
cudaMemcpyAsync((void *) (gpu_raw_buffers[buffer_index].data() + position), allocations[chunk_index]->data + offset, chunk_size, cudaMemcpyHostToDevice,0);
position += chunk_size;
}
buffer_index++;
}
cudaStreamSynchronize(0);
}catch(std::exception & e){
auto logger = spdlog::get("batch_logger");
if (logger){
logger->error("|||{info}|||||",
"info"_a="ERROR in BlazingHostTable::get_gpu_table(). What: {}"_format(e.what()));
}
throw;
}
return std::move(comm::deserialize_from_gpu_raw_buffers(columns_offsets,
gpu_raw_buffers));
}
std::vector<ral::memory::blazing_allocation_chunk> BlazingHostTable::get_raw_buffers() const {
std::vector<ral::memory::blazing_allocation_chunk> chunks;
for(auto & chunk : allocations){
ral::memory::blazing_allocation_chunk new_chunk;
new_chunk.size = chunk->size;
new_chunk.data = chunk->data;
new_chunk.allocation = nullptr;
chunks.push_back(new_chunk);
}
return chunks;
}
const std::vector<ral::memory::blazing_chunked_column_info> & BlazingHostTable::get_blazing_chunked_column_infos() const {
return this->chunked_column_infos;
}
} // namespace frame
} // namespace ral
| 37.265152 | 171 | 0.683472 | [
"vector",
"transform"
] |
8450b238619fcb900fe0749076932dac3e7bdde8 | 1,191 | hpp | C++ | source/LibFgBase/src/FgLighting.hpp | denim2x/FaceGenBaseLibrary | 52317cf96984a47d7f2d0c5471230d689404101c | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgLighting.hpp | denim2x/FaceGenBaseLibrary | 52317cf96984a47d7f2d0c5471230d689404101c | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgLighting.hpp | denim2x/FaceGenBaseLibrary | 52317cf96984a47d7f2d0c5471230d689404101c | [
"MIT"
] | null | null | null | //
// Copyright (c) 2019 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
#ifndef FGLIGHT_HPP
#define FGLIGHT_HPP
#include "FgStdLibs.hpp"
#include "FgMatrixC.hpp"
#include "FgMatrixV.hpp"
#include "FgImage.hpp"
namespace Fg {
struct FgLight
{
Vec3F colour {0.6f,0.6f,0.6f}; // RGB range [0,1]
Vec3F direction {0,0,1}; // Unit direction vector to light in OECS (all lights at infinity)
FG_SERIALIZE2(colour,direction);
FgLight() {}
FgLight(Vec3F c,Vec3F d) : colour(c), direction(d) {}
};
typedef Svec<FgLight> FgLights;
struct FgLighting
{
Vec3F ambient; // RGB range [0,1]
FgLights lights;
FG_SERIALIZE2(ambient,lights);
FgLighting() : ambient(0.4f) {lights.resize(1); }
FgLighting(Vec3F a) : ambient(a) {}
FgLighting(Vec3F a,FgLight l) : ambient(a), lights(fgSvec(l)) {}
FgLighting(Vec3F a,FgLights const & l) : ambient(a), lights(l) {}
ImgC4UC
createSpecularMap() const;
};
}
#endif
| 24.306122 | 108 | 0.628883 | [
"vector"
] |
8453fd5bfd2c2b209bc194777f5cf7404a40b2d1 | 7,753 | cpp | C++ | src/timeout.cpp | steamboatid/keydb | 7aa9296f1bd9773ce47c46ab3ac3800bf870f8fe | [
"BSD-3-Clause"
] | 4,587 | 2019-02-26T06:59:21.000Z | 2021-03-02T20:54:42.000Z | src/timeout.cpp | steamboatid/keydb | 7aa9296f1bd9773ce47c46ab3ac3800bf870f8fe | [
"BSD-3-Clause"
] | 269 | 2019-02-27T19:20:05.000Z | 2021-03-02T06:06:40.000Z | src/timeout.cpp | steamboatid/keydb | 7aa9296f1bd9773ce47c46ab3ac3800bf870f8fe | [
"BSD-3-Clause"
] | 297 | 2019-02-26T22:37:53.000Z | 2021-02-24T03:06:13.000Z | /* Copyright (c) 2009-2020, Salvatore Sanfilippo <antirez at gmail dot com>
* 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 Redis 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 "server.h"
#include "cluster.h"
#include <mutex>
/* ========================== Clients timeouts ============================= */
/* Check if this blocked client timedout (does nothing if the client is
* not blocked right now). If so send a reply, unblock it, and return 1.
* Otherwise 0 is returned and no operation is performed. */
int checkBlockedClientTimeout(client *c, mstime_t now) {
if (c->flags & CLIENT_BLOCKED &&
c->bpop.timeout != 0
&& c->bpop.timeout < now)
{
/* Handle blocking operation specific timeout. */
replyToBlockedClientTimedOut(c);
unblockClient(c);
return 1;
} else {
return 0;
}
}
/* Check for timeouts. Returns non-zero if the client was terminated.
* The function gets the current time in milliseconds as argument since
* it gets called multiple times in a loop, so calling gettimeofday() for
* each iteration would be costly without any actual gain. */
int clientsCronHandleTimeout(client *c, mstime_t now_ms) {
time_t now = now_ms/1000;
if (cserver.maxidletime &&
/* This handles the idle clients connection timeout if set. */
!(c->flags & CLIENT_SLAVE) && /* No timeout for slaves and monitors */
!(c->flags & CLIENT_MASTER) && /* No timeout for masters */
!(c->flags & CLIENT_BLOCKED) && /* No timeout for BLPOP */
!(c->flags & CLIENT_PUBSUB) && /* No timeout for Pub/Sub clients */
(now - c->lastinteraction > cserver.maxidletime))
{
serverLog(LL_VERBOSE,"Closing idle client");
freeClient(c);
return 1;
} else if (c->flags & CLIENT_BLOCKED) {
/* Cluster: handle unblock & redirect of clients blocked
* into keys no longer served by this server. */
if (g_pserver->cluster_enabled) {
if (clusterRedirectBlockedClientIfNeeded(c))
unblockClient(c);
}
}
return 0;
}
/* For blocked clients timeouts we populate a radix tree of 128 bit keys
* composed as such:
*
* [8 byte big endian expire time]+[8 byte client ID]
*
* We don't do any cleanup in the Radix tree: when we run the clients that
* reached the timeout already, if they are no longer existing or no longer
* blocked with such timeout, we just go forward.
*
* Every time a client blocks with a timeout, we add the client in
* the tree. In beforeSleep() we call clientsHandleTimeout() to run
* the tree and unblock the clients. */
#define CLIENT_ST_KEYLEN 16 /* 8 bytes mstime + 8 bytes client ID. */
/* Given client ID and timeout, write the resulting radix tree key in buf. */
void encodeTimeoutKey(unsigned char *buf, uint64_t timeout, client *c) {
timeout = htonu64(timeout);
memcpy(buf,&timeout,sizeof(timeout));
memcpy(buf+8,&c,sizeof(c));
if (sizeof(c) == 4) memset(buf+12,0,4); /* Zero padding for 32bit target. */
}
/* Given a key encoded with encodeTimeoutKey(), resolve the fields and write
* the timeout into *toptr and the client pointer into *cptr. */
void decodeTimeoutKey(unsigned char *buf, uint64_t *toptr, client **cptr) {
memcpy(toptr,buf,sizeof(*toptr));
*toptr = ntohu64(*toptr);
memcpy(cptr,buf+8,sizeof(*cptr));
}
/* Add the specified client id / timeout as a key in the radix tree we use
* to handle blocked clients timeouts. The client is not added to the list
* if its timeout is zero (block forever). */
void addClientToTimeoutTable(client *c) {
if (c->bpop.timeout == 0) return;
uint64_t timeout = c->bpop.timeout;
unsigned char buf[CLIENT_ST_KEYLEN];
encodeTimeoutKey(buf,timeout,c);
if (raxTryInsert(g_pserver->clients_timeout_table,buf,sizeof(buf),NULL,NULL))
c->flags |= CLIENT_IN_TO_TABLE;
}
/* Remove the client from the table when it is unblocked for reasons
* different than timing out. */
void removeClientFromTimeoutTable(client *c) {
if (!(c->flags & CLIENT_IN_TO_TABLE)) return;
c->flags &= ~CLIENT_IN_TO_TABLE;
uint64_t timeout = c->bpop.timeout;
unsigned char buf[CLIENT_ST_KEYLEN];
encodeTimeoutKey(buf,timeout,c);
raxRemove(g_pserver->clients_timeout_table,buf,sizeof(buf),NULL);
}
/* This function is called in beforeSleep() in order to unblock clients
* that are waiting in blocking operations with a timeout set. */
void handleBlockedClientsTimeout(void) {
if (raxSize(g_pserver->clients_timeout_table) == 0) return;
uint64_t now = mstime();
raxIterator ri;
raxStart(&ri,g_pserver->clients_timeout_table);
raxSeek(&ri,"^",NULL,0);
while(raxNext(&ri)) {
uint64_t timeout;
client *c;
decodeTimeoutKey(ri.key,&timeout,&c);
if (timeout >= now) break; /* All the timeouts are in the future. */
std::unique_lock<fastlock> lock(c->lock);
c->flags &= ~CLIENT_IN_TO_TABLE;
checkBlockedClientTimeout(c,now);
raxRemove(g_pserver->clients_timeout_table,ri.key,ri.key_len,NULL);
raxSeek(&ri,"^",NULL,0);
}
raxStop(&ri);
}
/* Get a timeout value from an object and store it into 'timeout'.
* The final timeout is always stored as milliseconds as a time where the
* timeout will expire, however the parsing is performed according to
* the 'unit' that can be seconds or milliseconds.
*
* Note that if the timeout is zero (usually from the point of view of
* commands API this means no timeout) the value stored into 'timeout'
* is zero. */
int getTimeoutFromObjectOrReply(client *c, robj *object, mstime_t *timeout, int unit) {
long long tval;
long double ftval;
if (unit == UNIT_SECONDS) {
if (getLongDoubleFromObjectOrReply(c,object,&ftval,
"timeout is not a float or out of range") != C_OK)
return C_ERR;
tval = (long long) (ftval * 1000.0);
} else {
if (getLongLongFromObjectOrReply(c,object,&tval,
"timeout is not an integer or out of range") != C_OK)
return C_ERR;
}
if (tval < 0) {
addReplyError(c,"timeout is negative");
return C_ERR;
}
if (tval > 0) {
tval += mstime();
}
*timeout = tval;
return C_OK;
}
| 40.170984 | 87 | 0.679221 | [
"object"
] |
84555c48e4524fe2720a32b8be7c0d927afcc7da | 1,072 | cpp | C++ | src/planner/Algo.cpp | nevermore3/nebula-graph | 6f24438289c2b20575bc6acdf607cd2a3648d30d | [
"Apache-2.0"
] | null | null | null | src/planner/Algo.cpp | nevermore3/nebula-graph | 6f24438289c2b20575bc6acdf607cd2a3648d30d | [
"Apache-2.0"
] | null | null | null | src/planner/Algo.cpp | nevermore3/nebula-graph | 6f24438289c2b20575bc6acdf607cd2a3648d30d | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "planner/Algo.h"
namespace nebula {
namespace graph {
Status CartesianProduct::addVar(std::string varName) {
auto checkName = [&varName](auto var) { return var->name == varName; };
if (std::find_if(inputVars_.begin(), inputVars_.end(), checkName) != inputVars_.end()) {
return Status::SemanticError("Duplicate Var: %s", varName.c_str());
}
auto* varPtr = qctx_->symTable()->getVar(varName);
DCHECK(varPtr != nullptr);
allColNames_.emplace_back(std::move(varPtr->colNames));
inputVars_.emplace_back(varPtr);
return Status::OK();
}
std::vector<std::string> CartesianProduct::inputVars() const {
std::vector<std::string> varNames;
varNames.reserve(inputVars_.size());
for (auto i : inputVars_) {
varNames.emplace_back(i->name);
}
return varNames;
}
} // namespace graph
} // namespace nebula
| 30.628571 | 92 | 0.679104 | [
"vector"
] |
84592903b2fefc7cb8d843adf44db13536b88014 | 847 | cpp | C++ | boboleetcode/Play-Leetcode-master/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2019-03-20T17:05:59.000Z | 2019-10-15T07:56:45.000Z | boboleetcode/Play-Leetcode-master/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/1013-Partition-Array-Into-Three-Parts-With-Equal-Sum/cpp-1013/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/
/// Author : liuyubobobo
/// Time : 2019-03-23
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
/// Linear Scan
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
bool canThreePartsEqualSum(vector<int>& A) {
int sum = accumulate(A.begin(), A.end(), 0);
if(sum % 3) return false;
int cur = 0, i = 0, j = A.size() - 1;
do{
cur += A[i ++];
}while(i < A.size() && cur != sum / 3);
if(i == A.size()) return false;
cur = 0;
do{
cur += A[j --];
}while(j >= 0 && cur != sum / 3);
if(j < 0) return false;
return i <= j;
}
};
int main() {
return 0;
} | 19.25 | 91 | 0.515939 | [
"vector"
] |
845e2524d0d40f27c5e47b068ea0ebb785118067 | 1,193 | cpp | C++ | Chapter11/barriers.cpp | markusbuchholz/Cpp-High-Performance-Second-Edition | 9d8ce97fae15a5f893a780fb3f8b187d11961a43 | [
"MIT"
] | 57 | 2020-07-09T22:54:31.000Z | 2022-03-31T14:18:41.000Z | Chapter11/barriers.cpp | markusbuchholz/Cpp-High-Performance-Second-Edition | 9d8ce97fae15a5f893a780fb3f8b187d11961a43 | [
"MIT"
] | 5 | 2021-04-02T17:25:31.000Z | 2021-07-30T09:38:42.000Z | Chapter11/barriers.cpp | PacktPublishing/Cpp-High-Performance-Second-Edition | 9d8ce97fae15a5f893a780fb3f8b187d11961a43 | [
"MIT"
] | 36 | 2019-12-25T19:30:47.000Z | 2022-03-16T16:41:02.000Z | #include <version>
#if defined(__cpp_lib_barrier)
#include <gtest/gtest.h>
#include <algorithm>
#include <array>
#include <barrier>
#include <iostream>
#include <numeric>
#include <random>
#include <thread>
#include <vector>
auto random_int(int min, int max) {
// One engine instance per thread
thread_local static auto engine =
std::default_random_engine{std::random_device{}()};
auto dist = std::uniform_int_distribution<>{min, max};
return dist(engine);
}
TEST(Barriers, ForkJoin) {
constexpr auto n = 5; // Number of dice
auto done = false;
auto dice = std::array<int, n>{};
auto threads = std::vector<std::thread>{};
auto n_turns = 0;
auto check_result = [&] { // Completion function
++n_turns;
auto is_six = [](auto i) { return i == 6; };
done = std::all_of(dice.begin(), dice.end(), is_six);
};
auto bar = std::barrier{n, check_result};
for (int i = 0; i < n; ++i) {
threads.emplace_back([&, i] {
while (!done) {
dice[i] = random_int(1, 6); // Roll dice
bar.arrive_and_wait(); // Join
}
});
}
for (auto&& t : threads) {
t.join();
}
std::cout << n_turns << '\n';
}
#endif // barrier | 22.942308 | 57 | 0.611065 | [
"vector"
] |
84615ec9a12609af3c571142917ca85237158279 | 45,673 | cpp | C++ | 3rdParty/DirectFB/src/gfx/generic/GenefxEngine.cpp | rohmer/LVGL_UI_Creator | 37a19be55e1de95d56717786a27506d8c78fd1ae | [
"MIT"
] | 33 | 2019-09-17T20:57:56.000Z | 2021-11-20T21:50:51.000Z | 3rdParty/DirectFB/src/gfx/generic/GenefxEngine.cpp | rohmer/LVGL_UI_Creator | 37a19be55e1de95d56717786a27506d8c78fd1ae | [
"MIT"
] | 4 | 2019-10-21T08:38:11.000Z | 2021-11-17T16:53:08.000Z | 3rdParty/DirectFB/src/gfx/generic/GenefxEngine.cpp | rohmer/LVGL_UI_Creator | 37a19be55e1de95d56717786a27506d8c78fd1ae | [
"MIT"
] | 16 | 2019-09-25T04:25:04.000Z | 2022-03-28T07:46:18.000Z | /*
(c) Copyright 2012-2013 DirectFB integrated media GmbH
(c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org)
(c) Copyright 2000-2004 Convergence (integrated media) GmbH
All rights reserved.
Written by Denis Oliver Kropp <dok@directfb.org>,
Andreas Shimokawa <andi@directfb.org>,
Marek Pikarski <mass@directfb.org>,
Sven Neumann <neo@directfb.org>,
Ville Syrjälä <syrjala@sci.fi> and
Claudio Ciccani <klan@users.sf.net>.
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 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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
//#define DIRECT_ENABLE_DEBUG
#include <config.h>
#include <directfb.h>
#include <direct/Types++.h>
extern "C" {
#include <direct/debug.h>
#include <direct/messages.h>
#include <core/core.h>
#include <core/palette.h>
#include <core/state.h>
#include <core/surface_allocation.h>
#include <core/surface_pool.h>
#include <gfx/clip.h>
#include <gfx/convert.h>
#include <gfx/generic/generic.h>
}
#include <core/Debug.h>
#include <core/PacketBuffer.h>
#include <core/Renderer.h>
#include <core/TaskThreadsQ.h>
#include <core/Util.h>
// FIXME: find better auto detection, runtime options or dynamic adjustment for the following values
#if defined(ARCH_X86) || defined(ARCH_X86_64)
#define DFB_GENEFX_COMMAND_BUFFER_BLOCK_SIZE 0x40000 // 256k
#define DFB_GENEFX_COMMAND_BUFFER_MAX_SIZE 0x130000 // 1216k
#define DFB_GENEFX_TASK_WEIGHT_MAX 300000000
#else
#define DFB_GENEFX_COMMAND_BUFFER_BLOCK_SIZE 0x8000 // 32k
#define DFB_GENEFX_COMMAND_BUFFER_MAX_SIZE 0x17800 // 94k
#define DFB_GENEFX_TASK_WEIGHT_MAX 1000000
#endif
D_DEBUG_DOMAIN( DirectFB_GenefxEngine, "DirectFB/Genefx/Engine", "DirectFB Genefx Engine" );
D_DEBUG_DOMAIN( DirectFB_GenefxTask, "DirectFB/Genefx/Task", "DirectFB Genefx Task" );
/*********************************************************************************************************************/
namespace DirectFB {
class GenefxEngine;
class GenefxTask : public DirectFB::SurfaceTask
{
public:
GenefxTask( GenefxEngine *engine,
const DFBRegion &clip,
unsigned int tile_count,
unsigned int tile_number )
:
SurfaceTask( CSAID_CPU ),
engine( engine ),
tile_clip( clip ),
commands( DFB_GENEFX_COMMAND_BUFFER_BLOCK_SIZE ),
weight( 0 ),
weight_shift_draw( 0 ),
weight_shift_blit( 0 ),
tile_count( tile_count ),
tile_number( tile_number ),
modified( SMF_NONE )
{
D_FLAGS_SET( flags, TASK_FLAG_NEED_SLAVE_PUSH );
}
virtual ~GenefxTask()
{
}
protected:
virtual DFBResult Setup();
virtual DFBResult Push();
virtual DFBResult Run();
virtual void Finalise();
public:
virtual void Describe( Direct::String &string ) const;
virtual const Direct::String &TypeName() const;
private:
friend class GenefxEngine;
GenefxEngine *engine;
DFBRegion tile_clip;
typedef enum {
TYPE_SET_DESTINATION,
TYPE_SET_CLIP,
TYPE_SET_SOURCE,
TYPE_SET_COLOR,
TYPE_SET_DRAWINGFLAGS,
TYPE_SET_BLITTINGFLAGS,
TYPE_SET_SRC_BLEND,
TYPE_SET_DST_BLEND,
TYPE_SET_SRC_COLORKEY,
TYPE_SET_DESTINATION_PALETTE,
TYPE_SET_SOURCE_PALETTE,
TYPE_FILL_RECTS,
TYPE_DRAW_LINES,
TYPE_BLIT,
TYPE_STRETCHBLIT,
TYPE_TEXTURE_TRIANGLES
} Type;
typedef Util::PacketBuffer<> Commands;
Commands commands;
DFBRegion clip;
unsigned int weight;
unsigned int weight_shift_draw;
unsigned int weight_shift_blit;
unsigned int tile_count;
unsigned int tile_number;
StateModificationFlags modified;
inline void addDrawingWeight( unsigned int w ) {
weight += 10 + (w << weight_shift_draw);
}
inline void addBlittingWeight( unsigned int w ) {
weight += 10 + (w << weight_shift_blit);
}
private:
static const Direct::String _Type;
};
void
GenefxTask::Describe( Direct::String &string ) const
{
SurfaceTask::Describe( string );
string.PrintF( " clip %4d,%4d-%4dx%4d", DFB_RECTANGLE_VALS_FROM_REGION(&clip) );
}
const Direct::String &
GenefxTask::TypeName() const
{
return _Type;
}
const Direct::String GenefxTask::_Type( "Genefx" );
class GenefxEngine : public DirectFB::Engine {
private:
friend class GenefxTask;
TaskThreadsQ threads;
public:
GenefxEngine( unsigned int cores = 1 )
:
threads( "Genefx", cores < 8 ? cores : 8 )
{
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( cores %d )\n", __FUNCTION__, cores );
D_ASSERT( cores > 0 );
caps.software = true;
caps.cores = cores < 8 ? cores : 8;
caps.clipping = (DFBAccelerationMask)(DFXL_FILLRECTANGLE |
DFXL_DRAWRECTANGLE |
DFXL_DRAWLINE |
DFXL_BLIT |
DFXL_STRETCHBLIT |
DFXL_TEXTRIANGLES);
caps.render_options = (DFBSurfaceRenderOptions)(DSRO_SMOOTH_DOWNSCALE | DSRO_SMOOTH_UPSCALE);
caps.max_operations = 300000;
desc.name = "Genefx";
}
/*
* Engine API
*/
virtual DFBResult bind ( Renderer::Setup *setup )
{
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %p )\n", __FUNCTION__, this );
for (unsigned int i=0; i<setup->tiles; i++) {
setup->tasks[i] = new GenefxTask( this, setup->clips[i], setup->tiles, i );
}
setup->tiles_render = 1;
return DFB_OK;
}
virtual DFBResult check ( Renderer::Setup *setup )
{
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %p )\n", __FUNCTION__, this );
// for (unsigned int i=0; i<setup->tiles; i++) {
GenefxTask *mytask = (GenefxTask *) setup->tasks[0];
if (mytask->weight >= DFB_GENEFX_TASK_WEIGHT_MAX ||
mytask->commands.GetLength() >= DFB_GENEFX_COMMAND_BUFFER_MAX_SIZE)
return DFB_LIMITEXCEEDED;
// }
return DFB_OK;
}
virtual DFBResult CheckState ( CardState *state,
DFBAccelerationMask accel )
{
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %p )\n", __FUNCTION__, this );
switch (accel) {
case DFXL_FILLRECTANGLE:
case DFXL_DRAWLINE:
case DFXL_BLIT:
case DFXL_STRETCHBLIT:
case DFXL_TEXTRIANGLES:
break;
default:
return DFB_UNSUPPORTED;
}
if (!gAcquireCheck( state, accel ))
return DFB_UNSUPPORTED;
return DFB_OK;
}
virtual DFBResult SetState ( DirectFB::SurfaceTask *task,
CardState *state,
StateModificationFlags modified,
DFBAccelerationMask accel )
{
GenefxTask *mytask = (GenefxTask *)task;
StateModificationFlags required = (StateModificationFlags)(SMF_TO | SMF_DESTINATION | SMF_CLIP | SMF_RENDER_OPTIONS);
StateModificationFlags emitting;
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %p )\n", __FUNCTION__, this );
if (state->render_options & DSRO_MATRIX)
required = (StateModificationFlags)(required | SMF_MATRIX);
if (DFB_DRAWING_FUNCTION( accel )) {
required = (StateModificationFlags)(required | SMF_DRAWING_FLAGS | SMF_COLOR);
if (state->drawingflags & DSDRAW_BLEND)
required = (StateModificationFlags)(required | SMF_SRC_BLEND | SMF_DST_BLEND);
if (state->drawingflags & DSDRAW_DST_COLORKEY)
required = (StateModificationFlags)(required | SMF_DST_COLORKEY);
}
else {
required = (StateModificationFlags)(required | SMF_BLITTING_FLAGS | SMF_FROM | SMF_SOURCE);
if (accel == DFXL_BLIT2)
required = (StateModificationFlags)(required | SMF_FROM | SMF_SOURCE2);
if (state->blittingflags & (DSBLIT_BLEND_COLORALPHA |
DSBLIT_COLORIZE |
DSBLIT_SRC_PREMULTCOLOR))
required = (StateModificationFlags)(required | SMF_COLOR);
if (state->blittingflags & (DSBLIT_BLEND_ALPHACHANNEL |
DSBLIT_BLEND_COLORALPHA))
required = (StateModificationFlags)(required | SMF_SRC_BLEND | SMF_DST_BLEND);
if (state->blittingflags & DSBLIT_SRC_COLORKEY)
required = (StateModificationFlags)(required | SMF_SRC_COLORKEY);
if (state->blittingflags & DSBLIT_DST_COLORKEY)
required = (StateModificationFlags)(required | SMF_DST_COLORKEY);
if (state->blittingflags & (DSBLIT_SRC_MASK_ALPHA | DSBLIT_SRC_MASK_COLOR))
required = (StateModificationFlags)(required | SMF_FROM | SMF_SOURCE_MASK | SMF_SOURCE_MASK_VALS);
if (state->blittingflags & DSBLIT_INDEX_TRANSLATION)
required = (StateModificationFlags)(required | SMF_INDEX_TRANSLATION);
if (state->blittingflags & DSBLIT_COLORKEY_PROTECT)
required = (StateModificationFlags)(required | SMF_COLORKEY);
if (state->blittingflags & DSBLIT_SRC_CONVOLUTION)
required = (StateModificationFlags)(required | SMF_SRC_CONVOLUTION);
}
D_FLAGS_SET( mytask->modified, modified );
emitting = (StateModificationFlags)(required & mytask->modified);
D_FLAGS_CLEAR( mytask->modified, emitting );
u32 max = 8 + 5 + 8 + 2 + 2 + 2 + 2 + 2 + 2;
if ((emitting & SMF_DESTINATION) && DFB_PIXELFORMAT_IS_INDEXED( state->destination->config.format ))
max += 2 + 2 * state->destination->palette->num_entries;
if ((emitting & SMF_SOURCE) && DFB_BLITTING_FUNCTION(accel) && DFB_PIXELFORMAT_IS_INDEXED( state->source->config.format ))
max += 2 + 2 * state->source->palette->num_entries;
// TODO: validate lazily as in CoreGraphicsStateClient
u32 *buf = (u32*) mytask->commands.GetBuffer( 4 * max );
if (!buf)
return DFB_NOSYSTEMMEMORY;
if (emitting & SMF_DESTINATION) {
D_DEBUG_AT( DirectFB_GenefxEngine, " -> destination %p (%d)\n", state->dst.addr, state->dst.pitch );
*buf++ = GenefxTask::TYPE_SET_DESTINATION;
*buf++ = (long long)(long)state->dst.addr >> 32;
*buf++ = (u32)(long)state->dst.addr;
*buf++ = state->dst.pitch;
*buf++ = state->destination->config.size.w; // FIXME: maybe should use allocation->config
*buf++ = state->destination->config.size.h;
*buf++ = state->destination->config.format;
*buf++ = state->destination->config.caps;
if (DFB_PIXELFORMAT_IS_INDEXED( state->destination->config.format )) {
*buf++ = GenefxTask::TYPE_SET_DESTINATION_PALETTE;
*buf++ = state->destination->palette->num_entries;
for (unsigned int i=0; i<state->destination->palette->num_entries; i++) {
*buf++ = *(u32*)&state->destination->palette->entries[i];
*buf++ = *(u32*)&state->destination->palette->entries_yuv[i];
}
}
}
if (emitting & SMF_CLIP) {
D_DEBUG_AT( DirectFB_GenefxEngine, " -> clip %d,%d-%dx%d\n", DFB_RECTANGLE_VALS_FROM_REGION(&state->clip) );
*buf++ = GenefxTask::TYPE_SET_CLIP;
*buf++ = state->clip.x1;
*buf++ = state->clip.y1;
*buf++ = state->clip.x2;
*buf++ = state->clip.y2;
mytask->clip = state->clip;
}
if (emitting & SMF_SOURCE && DFB_BLITTING_FUNCTION(accel)) {
D_DEBUG_AT( DirectFB_GenefxEngine, " -> source %p (%d)\n", state->src.addr, state->src.pitch );
*buf++ = GenefxTask::TYPE_SET_SOURCE;
*buf++ = (long long)(long)state->src.addr >> 32;
*buf++ = (u32)(long)state->src.addr;
*buf++ = state->src.pitch;
*buf++ = state->source->config.size.w;
*buf++ = state->source->config.size.h;
*buf++ = state->source->config.format;
*buf++ = state->source->config.caps;
if (DFB_PIXELFORMAT_IS_INDEXED( state->source->config.format )) {
*buf++ = GenefxTask::TYPE_SET_SOURCE_PALETTE;
*buf++ = state->source->palette->num_entries;
for (unsigned int i=0; i<state->source->palette->num_entries; i++) {
*buf++ = *(u32*)&state->source->palette->entries[i];
*buf++ = *(u32*)&state->source->palette->entries_yuv[i];
}
}
state->mod_hw = (StateModificationFlags)(state->mod_hw & ~SMF_SOURCE);
if (state->source->config.format != state->destination->config.format && state->source->config.format != DSPF_A8)
mytask->weight_shift_blit |= 4;
else
mytask->weight_shift_blit &= ~4;
}
if (emitting & SMF_COLOR) {
*buf++ = GenefxTask::TYPE_SET_COLOR;
*buf++ = PIXEL_ARGB( state->color.a, state->color.r, state->color.g, state->color.b );
}
if (emitting & SMF_DRAWING_FLAGS) {
*buf++ = GenefxTask::TYPE_SET_DRAWINGFLAGS;
*buf++ = state->drawingflags;
if (state->drawingflags) {
if (state->drawingflags & (DSDRAW_BLEND | DSDRAW_SRC_PREMULTIPLY | DSDRAW_DST_PREMULTIPLY | DSDRAW_DEMULTIPLY))
mytask->weight_shift_draw = 6;
else
mytask->weight_shift_draw = 3;
}
else
mytask->weight_shift_draw = 1;
}
if (emitting & SMF_BLITTING_FLAGS) {
*buf++ = GenefxTask::TYPE_SET_BLITTINGFLAGS;
*buf++ = state->blittingflags;
if (state->blittingflags) {
if (state->blittingflags & (DSBLIT_BLEND_ALPHACHANNEL | DSBLIT_BLEND_COLORALPHA | DSBLIT_COLORIZE | DSBLIT_SRC_PREMULTIPLY |
DSBLIT_DST_PREMULTIPLY | DSBLIT_DEMULTIPLY | DSBLIT_DEINTERLACE | DSBLIT_SRC_PREMULTCOLOR |
DSBLIT_SRC_COLORKEY_EXTENDED | DSBLIT_DST_COLORKEY_EXTENDED | DSBLIT_SRC_MASK_ALPHA |
DSBLIT_SRC_MASK_COLOR | DSBLIT_SRC_COLORMATRIX | DSBLIT_SRC_CONVOLUTION))
mytask->weight_shift_blit = 8 | (mytask->weight_shift_blit & 4);
else
mytask->weight_shift_blit = 2 | (mytask->weight_shift_blit & 4);
}
else
mytask->weight_shift_blit = 1 | (mytask->weight_shift_blit & 4);
}
if (emitting & SMF_SRC_BLEND) {
*buf++ = GenefxTask::TYPE_SET_SRC_BLEND;
*buf++ = state->src_blend;
}
if (emitting & SMF_DST_BLEND) {
*buf++ = GenefxTask::TYPE_SET_DST_BLEND;
*buf++ = state->dst_blend;
}
if (emitting & SMF_SRC_COLORKEY) {
*buf++ = GenefxTask::TYPE_SET_SRC_COLORKEY;
*buf++ = state->src_colorkey;
}
state->mod_hw = SMF_NONE;
state->set = (DFBAccelerationMask)(state->set | accel);
mytask->commands.PutBuffer( buf );
return DFB_OK;
}
virtual DFBResult FillRectangles( DirectFB::SurfaceTask *task,
const DFBRectangle *rects,
unsigned int &num_rects )
{
GenefxTask *mytask = (GenefxTask *)task;
u32 count = 0;
u32 *count_ptr;
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %d ) <- clip %d,%d-%dx%d\n", __FUNCTION__, num_rects,
DFB_RECTANGLE_VALS_FROM_REGION(&mytask->clip) );
u32 *buf = (u32*) mytask->commands.GetBuffer( 4 * (2 + num_rects * 4) );
if (!buf)
return DFB_NOSYSTEMMEMORY;
*buf++ = GenefxTask::TYPE_FILL_RECTS;
count_ptr = buf++;
for (unsigned int i=0; i<num_rects; i++) {
DFBRectangle rect = rects[i];
if (dfb_clip_rectangle( &mytask->clip, &rect )) {
*buf++ = rect.x;
*buf++ = rect.y;
*buf++ = rect.w;
*buf++ = rect.h;
count++;
mytask->addDrawingWeight( rect.w * rect.h );
}
}
*count_ptr = count;
mytask->commands.PutBuffer( buf );
return DFB_OK;
}
virtual DFBResult DrawRectangles( DirectFB::SurfaceTask *task,
const DFBRectangle *rects,
unsigned int &num_rects )
{
GenefxTask *mytask = (GenefxTask *)task;
u32 count = 0;
u32 *count_ptr;
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %d ) <- clip %d,%d-%dx%d\n", __FUNCTION__, num_rects,
DFB_RECTANGLE_VALS_FROM_REGION(&mytask->clip) );
u32 *buf = (u32*) mytask->commands.GetBuffer( 4 * (2 + num_rects * 4) );
if (!buf)
return DFB_NOSYSTEMMEMORY;
*buf++ = GenefxTask::TYPE_FILL_RECTS;
count_ptr = buf++;
for (unsigned int i=0; i<num_rects; i++) {
DFBRectangle rect = rects[i];
DFBRectangle rects[4];
int n = 0, num = 0;
dfb_build_clipped_rectangle_outlines( &rect, &mytask->clip, rects, &num );
for (; n<num; n++) {
*buf++ = rects[n].x;
*buf++ = rects[n].y;
*buf++ = rects[n].w;
*buf++ = rects[n].h;
count++;
mytask->addDrawingWeight( rects[n].w * 2 + rects[n].h * 2 );
}
}
*count_ptr = count;
mytask->commands.PutBuffer( buf );
return DFB_OK;
}
virtual DFBResult DrawLines( DirectFB::SurfaceTask *task,
const DFBRegion *lines,
unsigned int &num_lines )
{
GenefxTask *mytask = (GenefxTask *)task;
u32 count = 0;
u32 *count_ptr;
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %d ) <- clip %d,%d-%dx%d\n", __FUNCTION__, num_lines,
DFB_RECTANGLE_VALS_FROM_REGION(&mytask->clip) );
u32 *buf = (u32*) mytask->commands.GetBuffer( 4 * (2 + num_lines * 4) );
if (!buf)
return DFB_NOSYSTEMMEMORY;
*buf++ = GenefxTask::TYPE_DRAW_LINES;
count_ptr = buf++;
for (unsigned int i=0; i<num_lines; i++) {
DFBRegion line = lines[i];
if (dfb_clip_line( &mytask->clip, &line )) {
*buf++ = line.x1;
*buf++ = line.y1;
*buf++ = line.x2;
*buf++ = line.y2;
count++;
mytask->addDrawingWeight( (line.x2 - line.x1) + (line.y2 - line.y1) );
}
}
*count_ptr = count;
mytask->commands.PutBuffer( buf );
return DFB_OK;
}
virtual DFBResult Blit( DirectFB::SurfaceTask *task,
const DFBRectangle *rects,
const DFBPoint *points,
u32 &num )
{
GenefxTask *mytask = (GenefxTask *)task;
u32 count = 0;
u32 *count_ptr;
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %d ) <- clip %d,%d-%dx%d\n", __FUNCTION__, num,
DFB_RECTANGLE_VALS_FROM_REGION(&mytask->clip) );
u32 *buf = (u32*) mytask->commands.GetBuffer( 4 * (2 + num * 6) );
if (!buf)
return DFB_NOSYSTEMMEMORY;
*buf++ = GenefxTask::TYPE_BLIT;
count_ptr = buf++;
for (unsigned int i=0; i<num; i++) {
D_DEBUG_AT( DirectFB_GenefxTask, " -> %4d,%4d-%4dx%4d -> %4d,%4d\n",
rects[i].x, rects[i].y, rects[i].w, rects[i].h, points[i].x, points[i].y );
if (dfb_clip_blit_precheck( &mytask->clip, rects[i].w, rects[i].h, points[i].x, points[i].y )) {
DFBRectangle rect = rects[i];
DFBPoint point = points[i];
/* In multi tile mode clipping is done in GenefxTask::Run() anyways */
if (mytask->slaves == 0) {
dfb_clip_blit( &mytask->clip, &rect, &point.x, &point.y ); // FIXME: support rotation!
//dfb_clip_blit_flipped_rotated( &mytask->clip, &rect, &drect, blittingflags );
}
*buf++ = rect.x;
*buf++ = rect.y;
*buf++ = rect.w;
*buf++ = rect.h;
*buf++ = point.x;
*buf++ = point.y;
count++;
mytask->addBlittingWeight( rect.w * rect.h );
}
}
*count_ptr = count;
mytask->commands.PutBuffer( buf );
return DFB_OK;
}
virtual DFBResult StretchBlit( DirectFB::SurfaceTask *task,
const DFBRectangle *srects,
const DFBRectangle *drects,
u32 &num )
{
GenefxTask *mytask = (GenefxTask *)task;
u32 count = 0;
u32 *count_ptr;
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %d ) <- clip %d,%d-%dx%d\n", __FUNCTION__, num,
DFB_RECTANGLE_VALS_FROM_REGION(&mytask->clip) );
u32 *buf = (u32*) mytask->commands.GetBuffer( 4 * (2 + num * 8) );
if (!buf)
return DFB_NOSYSTEMMEMORY;
*buf++ = GenefxTask::TYPE_STRETCHBLIT;
count_ptr = buf++;
for (unsigned int i=0; i<num; i++) {
if (dfb_clip_blit_precheck( &mytask->clip, drects[i].w, drects[i].h, drects[i].x, drects[i].y )) {
*buf++ = srects[i].x;
*buf++ = srects[i].y;
*buf++ = srects[i].w;
*buf++ = srects[i].h;
*buf++ = drects[i].x;
*buf++ = drects[i].y;
*buf++ = drects[i].w;
*buf++ = drects[i].h;
count++;
mytask->addBlittingWeight( drects[i].w * drects[i].h * 2 );
}
}
*count_ptr = count;
mytask->commands.PutBuffer( buf );
return DFB_OK;
}
virtual DFBResult TextureTriangles( SurfaceTask *task,
const DFBVertex1616 *vertices,
unsigned int &num,
DFBTriangleFormation formation )
{
GenefxTask *mytask = (GenefxTask *)task;
D_DEBUG_AT( DirectFB_GenefxEngine, "GenefxEngine::%s( %d ) <- clip %d,%d-%dx%d\n", __FUNCTION__, num,
DFB_RECTANGLE_VALS_FROM_REGION(&mytask->clip) );
u32 *buf = (u32*) mytask->commands.GetBuffer( 4 * (3 + num * 4) );
if (!buf)
return DFB_NOSYSTEMMEMORY;
*buf++ = GenefxTask::TYPE_TEXTURE_TRIANGLES;
*buf++ = num;
*buf++ = formation;
for (unsigned int i=0; i<num; i++) {
*buf++ = vertices[i].x >> 16;
*buf++ = vertices[i].y >> 16;
*buf++ = vertices[i].s;
*buf++ = vertices[i].t;
}
mytask->addBlittingWeight( num * 10000 ); // FIXME: calculate weight better, maybe each diff to previous point
mytask->commands.PutBuffer( buf );
return DFB_OK;
}
};
DFBResult
GenefxTask::Setup()
{
D_DEBUG_AT( DirectFB_GenefxTask, "GenefxTask::%s( %p )\n", __FUNCTION__, this );
D_MAGIC_ASSERT( this, Task );
DFB_TASK_CHECK_STATE( this, TASK_FLUSHED, return DFB_BUG );
DFB_TASK_LOG( "Genefx::Setup()" );
const std::vector<SurfaceAllocationAccess> &accesses = master ? ((SurfaceTask*) master)->accesses : this->accesses;
D_ASSERT( accesses.size() > 0 );
D_ASSERT( accesses[0].flags & CSAF_WRITE );
D_MAGIC_ASSERT( accesses[0].allocation, CoreSurfaceAllocation );
D_ASSERT( qid == 0 );
qid = ((u64) accesses[0].allocation->object.id << 32) | tile_number;
return SurfaceTask::Setup();
}
DFBResult
GenefxTask::Push()
{
D_DEBUG_AT( DirectFB_GenefxTask, "GenefxTask::%s( %p )\n", __FUNCTION__, this );
D_MAGIC_ASSERT( this, Task );
DFB_TASK_CHECK_STATE( this, TASK_RUNNING, return DFB_BUG );
DFB_TASK_LOG( "Genefx::Push()" );
if (master) {
D_MAGIC_ASSERT( master, Task );
D_ASSERT( ((GenefxTask*) master)->qid != 0 );
D_ASSERT( qid == 0 );
qid = ((u64) ((SurfaceTask*) master)->accesses[0].allocation->object.id << 32) | tile_number;
}
engine->threads.Push( this );
return DFB_OK;
}
void
GenefxTask::Finalise()
{
D_DEBUG_AT( DirectFB_GenefxTask, "GenefxTask::%s( %p )\n", __FUNCTION__, this );
D_MAGIC_ASSERT( this, Task );
DFB_TASK_CHECK_STATE( this, TASK_FINISH, return );
DFB_TASK_LOG( "Genefx::Finalise()" );
engine->threads.Finalise( this );
SurfaceTask::Finalise();
}
DFBResult
GenefxTask::Run()
{
u32 ptr1;
u32 ptr2;
u32 color;
u32 num;
CoreSurface dest;
CorePalette dest_palette;
DFBColor dest_entries[256];
DFBColorYUV dest_entries_yuv[256];
CoreSurface source;
CorePalette source_palette;
DFBColor source_entries[256];
DFBColorYUV source_entries_yuv[256];
DFBTriangleFormation formation;
CardState state;
bool single_tile;
bool disable_rendering = false;
D_DEBUG_AT( DirectFB_GenefxTask, "GenefxTask::%s()\n", __FUNCTION__ );
dfb_state_init( &state, core_dfb );
state.destination = &dest;
state.source = &source;
dest.num_buffers = 1;
single_tile = (tile_count == 1);
D_ASSUME( this->commands.GetLength() > 0 || master != NULL );
const Commands &commands = this->commands.GetLength() ? this->commands : ((GenefxTask*) master)->commands;
/* Call SurfaceTask::CacheInvalidate() for cache invalidation, flush takes place at the end */
CacheInvalidate();
for (Commands::buffer_vector::const_iterator it = commands.buffers.begin(); it != commands.buffers.end(); ++it) {
const Util::HeapBuffer *packet_buffer = *it;
const u32 *buffer = (const u32*) packet_buffer->ptr;
size_t size = packet_buffer->length / 4;
D_DEBUG_AT( DirectFB_GenefxTask, " =-> buffer length %zu\n", size );
for (unsigned int i=0; i<size; i++) {
D_DEBUG_AT( DirectFB_GenefxTask, " -> [%d]\n", i );
switch (buffer[i]) {
case GenefxTask::TYPE_SET_DESTINATION:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_DESTINATION\n" );
ptr1 = buffer[++i];
ptr2 = buffer[++i];
state.dst.addr = (void*)(long)(((long long)ptr1 << 32) | ptr2);
D_DEBUG_AT( DirectFB_GenefxTask, " -> 0x%08x 0x%08x = %p\n", ptr1, ptr2, state.dst.addr );
state.dst.pitch = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> pitch %d\n", state.dst.pitch );
dest.config.size.w = buffer[++i];
dest.config.size.h = buffer[++i];
dest.config.format = (DFBSurfacePixelFormat) buffer[++i];
dest.config.caps = (DFBSurfaceCapabilities) buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> size %dx%d\n", dest.config.size.w, dest.config.size.h );
D_DEBUG_AT( DirectFB_GenefxTask, " -> format %s\n", dfb_pixelformat_name( dest.config.format ) );
D_DEBUG_AT( DirectFB_GenefxTask, " -> caps 0x%08x\n", dest.config.caps );
break;
case GenefxTask::TYPE_SET_CLIP:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_CLIP\n" );
state.clip.x1 = buffer[++i];
state.clip.y1 = buffer[++i];
state.clip.x2 = buffer[++i];
state.clip.y2 = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> " DFB_RECT_FORMAT "\n", DFB_RECTANGLE_VALS_FROM_REGION(&state.clip) );
if (!single_tile) {
if (dfb_region_region_intersect( &state.clip, &tile_clip )) {
disable_rendering = false;
D_DEBUG_AT( DirectFB_GenefxTask, " -> " DFB_RECT_FORMAT " (tile " DFB_RECT_FORMAT ")\n",
DFB_RECTANGLE_VALS_FROM_REGION(&state.clip), DFB_RECTANGLE_VALS_FROM_REGION(&tile_clip) );
}
else {
disable_rendering = true;
D_DEBUG_AT( DirectFB_GenefxTask, " -> NO OVERLAP WITH TILE (" DFB_RECT_FORMAT ")\n",
DFB_RECTANGLE_VALS_FROM_REGION(&tile_clip) );
}
}
break;
case GenefxTask::TYPE_SET_SOURCE:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_SOURCE\n" );
ptr1 = buffer[++i];
ptr2 = buffer[++i];
state.src.addr = (void*)(long)(((long long)ptr1 << 32) | ptr2);
D_DEBUG_AT( DirectFB_GenefxTask, " -> 0x%08x 0x%08x = %p\n", ptr1, ptr2, state.src.addr );
state.src.pitch = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> pitch %d\n", state.src.pitch );
source.config.size.w = buffer[++i];
source.config.size.h = buffer[++i];
source.config.format = (DFBSurfacePixelFormat) buffer[++i];
source.config.caps = (DFBSurfaceCapabilities) buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> size %dx%d\n", source.config.size.w, source.config.size.h );
D_DEBUG_AT( DirectFB_GenefxTask, " -> format %s\n", dfb_pixelformat_name( source.config.format ) );
D_DEBUG_AT( DirectFB_GenefxTask, " -> caps 0x%08x\n", source.config.caps );
break;
case GenefxTask::TYPE_SET_COLOR:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_COLOR\n" );
color = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> 0x%08x\n", color );
state.color.a = color >> 24;
state.color.r = color >> 16;
state.color.g = color >> 8;
state.color.b = color;
break;
case GenefxTask::TYPE_SET_DRAWINGFLAGS:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_DRAWINGFLAGS\n" );
state.drawingflags = (DFBSurfaceDrawingFlags) buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> 0x%08x\n", state.drawingflags );
break;
case GenefxTask::TYPE_SET_BLITTINGFLAGS:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_BLITTINGFLAGS\n" );
state.blittingflags = (DFBSurfaceBlittingFlags) buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> 0x%08x\n", state.blittingflags );
break;
case GenefxTask::TYPE_SET_SRC_BLEND:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_SRC_BLEND\n" );
state.src_blend = (DFBSurfaceBlendFunction) buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> 0x%08x\n", state.src_blend );
break;
case GenefxTask::TYPE_SET_DST_BLEND:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_DST_BLEND\n" );
state.dst_blend = (DFBSurfaceBlendFunction) buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> 0x%08x\n", state.dst_blend );
break;
case GenefxTask::TYPE_SET_SRC_COLORKEY:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_SRC_COLORKEY\n" );
state.src_colorkey = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> 0x%08x\n", state.src_colorkey );
break;
case GenefxTask::TYPE_SET_DESTINATION_PALETTE:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_DESTINATION_PALETTE\n" );
num = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> num %d\n", num );
D_ASSERT( num <= 256 );
for (u32 n=0; n<num; n++) {
dest_entries[n] = *(DFBColor*)&buffer[++i];
dest_entries_yuv[n] = *(DFBColorYUV*)&buffer[++i];
}
dest_palette.num_entries = num;
dest_palette.entries = dest_entries;
dest_palette.entries_yuv = dest_entries_yuv;
dest.palette = &dest_palette;
break;
case GenefxTask::TYPE_SET_SOURCE_PALETTE:
D_DEBUG_AT( DirectFB_GenefxTask, " -> SET_SOURCE_PALETTE\n" );
num = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> num %d\n", num );
D_ASSERT( num <= 256 );
for (u32 n=0; n<num; n++) {
source_entries[n] = *(DFBColor*)&buffer[++i];
source_entries_yuv[n] = *(DFBColorYUV*)&buffer[++i];
}
source_palette.num_entries = num;
source_palette.entries = source_entries;
source_palette.entries_yuv = source_entries_yuv;
source.palette = &source_palette;
break;
case GenefxTask::TYPE_FILL_RECTS:
D_DEBUG_AT( DirectFB_GenefxTask, " -> FILL_RECTS\n" );
num = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> num %d\n", num );
// TODO: run gAcquireSetup in Engine, requires lots of Genefx changes :(
if (!disable_rendering && gAcquireSetup( &state, DFXL_FILLRECTANGLE )) {
for (u32 n=0; n<num; n++) {
int x = buffer[++i];
int y = buffer[++i];
int w = buffer[++i];
int h = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> %4d,%4d-%4dx%4d\n", x, y, w, h );
DFBRectangle rect = {
x, y, w, h
};
if (single_tile || dfb_clip_rectangle( &state.clip, &rect ))
gFillRectangle( &state, &rect );
}
}
else
i += num * 4;
break;
case GenefxTask::TYPE_DRAW_LINES:
D_DEBUG_AT( DirectFB_GenefxTask, " -> DRAW_LINES\n" );
num = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> num %d\n", num );
// TODO: run gAcquireSetup in Engine, requires lots of Genefx changes :(
if (!disable_rendering && gAcquireSetup( &state, DFXL_DRAWLINE )) {
for (u32 n=0; n<num; n++) {
int x1 = buffer[++i];
int y1 = buffer[++i];
int x2 = buffer[++i];
int y2 = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> %4d,%4d-%4dx%4d\n", x1, y1, x2, y2 );
DFBRegion line = {
x1, y1, x2, y2
};
if (single_tile || dfb_clip_line( &state.clip, &line ))
gDrawLine( &state, &line );
}
}
else
i += num * 4;
break;
case GenefxTask::TYPE_BLIT:
D_DEBUG_AT( DirectFB_GenefxTask, " -> BLIT\n" );
num = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> num %d\n", num );
// TODO: run gAcquireSetup in Engine, requires lots of Genefx changes :(
if (!disable_rendering && gAcquireSetup( &state, DFXL_BLIT )) {
for (u32 n=0; n<num; n++) {
int x = buffer[++i];
int y = buffer[++i];
int w = buffer[++i];
int h = buffer[++i];
int dx = buffer[++i];
int dy = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> %4d,%4d-%4dx%4d -> %4d,%4d\n", x, y, w, h, dx, dy );
DFBRectangle rect = {
x, y, w, h
};
if (single_tile)
gBlit( &state, &rect, dx, dy );
else if (dfb_clip_blit_precheck( &state.clip, rect.w, rect.h, dx, dy )) {
dfb_clip_blit( &state.clip, &rect, &dx, &dy ); // FIXME: support rotation!
//dfb_clip_blit_flipped_rotated( &mytask->clip, &rect, &drect, blittingflags );
gBlit( &state, &rect, dx, dy );
}
}
}
else
i += num * 6;
break;
case GenefxTask::TYPE_STRETCHBLIT:
D_DEBUG_AT( DirectFB_GenefxTask, " -> STRETCHBLIT\n" );
num = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> num %d\n", num );
// TODO: run gAcquireSetup in Engine, requires lots of Genefx changes :(
if (!disable_rendering && gAcquireSetup( &state, DFXL_STRETCHBLIT )) {
for (u32 n=0; n<num; n++) {
DFBRectangle srect;
DFBRectangle drect;
srect.x = buffer[++i];
srect.y = buffer[++i];
srect.w = buffer[++i];
srect.h = buffer[++i];
drect.x = buffer[++i];
drect.y = buffer[++i];
drect.w = buffer[++i];
drect.h = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> %4d,%4d-%4dx%4d -> %4d,%4d-%4dx%4d\n",
srect.x, srect.y, srect.w, srect.h,
drect.x, drect.y, drect.w, drect.h );
gStretchBlit( &state, &srect, &drect );
}
}
else
i += num * 8;
break;
case GenefxTask::TYPE_TEXTURE_TRIANGLES:
D_DEBUG_AT( DirectFB_GenefxTask, " -> TEXTURE_TRIANGLES\n" );
num = buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> num %d\n", num );
formation = (DFBTriangleFormation) buffer[++i];
D_DEBUG_AT( DirectFB_GenefxTask, " -> formation %d\n", formation );
// TODO: run gAcquireSetup in Engine, requires lots of Genefx changes :(
if (!disable_rendering && gAcquireSetup( &state, DFXL_TEXTRIANGLES )) {
Util::TempArray<GenefxVertexAffine> v( num );
for (u32 n=0; n<num; n++) {
v.array[n].x = buffer[++i];
v.array[n].y = buffer[++i];
v.array[n].s = buffer[++i];
v.array[n].t = buffer[++i];
}
Genefx_TextureTrianglesAffine( &state, v.array, num, formation, &state.clip );
}
else
i += num * 4;
break;
default:
D_BUG( "unknown type %d", buffer[i] );
}
}
}
/* Call SurfaceTask::CacheFlush() for cache flushes */
CacheFlush();
state.destination = NULL;
state.source = NULL;
dfb_state_destroy( &state );
/* Return task to manager */
Done();
return DFB_OK;
}
extern "C" {
void
register_genefx()
{
Renderer::RegisterEngine( new GenefxEngine( dfb_config->software_cores ? : 1 ) );
}
}
}
| 37.652927 | 144 | 0.481313 | [
"object",
"vector"
] |
84655d74d9776c37bc0b5bea3b592dc31cafefbb | 374 | cpp | C++ | BinarySearch/find_range.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | BinarySearch/find_range.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | BinarySearch/find_range.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<int> searchRange(const vector<int> &A, int B) {
int i = lower_bound(A.begin(), A.end(), B) - A.begin();
int j = upper_bound(A.begin(), A.end(), B) - A.begin();
if(i > A.size() || A[i] != B) {
return vector<int> {-1, -1};
}
else {
return vector<int> {i, j - 1};
}
}
int main(void) {
} | 20.777778 | 59 | 0.526738 | [
"vector"
] |
8467741dcda2e9455068f4f8e873c36e063b519a | 17,402 | cpp | C++ | src/annotations/annotations.cpp | alyst/zorba | 6547fbaac38f26b89bee2e91818517d62de661d3 | [
"Apache-2.0"
] | null | null | null | src/annotations/annotations.cpp | alyst/zorba | 6547fbaac38f26b89bee2e91818517d62de661d3 | [
"Apache-2.0"
] | null | null | null | src/annotations/annotations.cpp | alyst/zorba | 6547fbaac38f26b89bee2e91818517d62de661d3 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
#include "annotations/annotations.h"
#include "store/api/item.h"
#include "store/api/item_factory.h"
#include "compiler/expression/expr.h"
#include "diagnostics/assert.h"
#include "diagnostics/util_macros.h"
#include "system/globalenv.h"
#include "zorbaserialization/serialize_template_types.h"
#include "zorbaserialization/serialize_zorba_types.h"
namespace zorba {
SERIALIZABLE_CLASS_VERSIONS(AnnotationInternal)
SERIALIZABLE_CLASS_VERSIONS(AnnotationList)
std::vector<store::Item_t>
AnnotationInternal::theAnnotId2NameMap;
ItemHandleHashMap<AnnotationInternal::AnnotationId>
AnnotationInternal::theAnnotName2IdMap(0, NULL, 64, false);
std::vector<AnnotationInternal::RuleBitSet>
AnnotationInternal::theConflictRuleSet;
std::vector<AnnotationInternal::AnnotationRequirement>
AnnotationInternal::theRequiredRuleSet;
/*******************************************************************************
Static method, called from GlobalEnvironment::init()
********************************************************************************/
void AnnotationInternal::createBuiltIn()
{
store::Item_t qname;
AnnotationId id;
theAnnotId2NameMap.resize(zann_end);
//
// W3C annotations
//
GENV_ITEMFACTORY->createQName(qname, static_context::XQUERY_NS, "", "public");
id = fn_public;
theAnnotId2NameMap[id] = qname;
theAnnotName2IdMap.insert(qname, id);
GENV_ITEMFACTORY->createQName(qname, static_context::XQUERY_NS, "", "private");
id = fn_private;
theAnnotId2NameMap[id] = qname;
theAnnotName2IdMap.insert(qname, id);
#define ZANN(a, b) \
GENV_ITEMFACTORY->createQName(qname, ZORBA_ANNOTATIONS_NS, "", #a); \
id = zann_##b; \
theAnnotId2NameMap[id] = qname; \
theAnnotName2IdMap.insert(qname, id);
//
// Zorba annotations - strictlydeterministic/deterministic/nondeterministic
//
ZANN(strictlydeterministic, strictlydeterministic);
ZANN(deterministic, deterministic);
ZANN(nondeterministic, nondeterministic);
//
// Zorba annotations - caching behaviour
//
ZANN(exclude-from-cache-key, exclude_from_cache_key);
ZANN(compare-with-deep-equal, compare_with_deep_equal);
//
// Zorba annotations - xquery scripting
//
ZANN(assignable, assignable);
ZANN(nonassignable, nonassignable);
ZANN(sequential, sequential);
ZANN(nonsequential, nonsequential);
//
// Zorba annotations - optimizer
//
ZANN(propagates-input-nodes, propagates_input_nodes);
ZANN(must-copy-input-nodes, must_copy_input_nodes);
//
// Zorba annotations - misc
//
ZANN(variadic, variadic);
ZANN(streamable, streamable);
ZANN(cache, cache);
//
// Zorba annotations - xqddf
//
ZANN(unique, unique);
ZANN(nonunique, nonunique);
ZANN(value-equality, value_equality);
ZANN(general-equality, general_equality);
ZANN(value-range, value_range);
ZANN(general-range, general_range);
ZANN(automatic, automatic);
ZANN(manual, manual);
ZANN(mutable, mutable);
ZANN(queue, queue);
ZANN(append-only, append_only);
ZANN(const, const);
ZANN(ordered, ordered);
ZANN(unordered, unordered);
ZANN(read-only-nodes, read_only_nodes);
ZANN(mutable-nodes, mutable_nodes);
#undef ZANN
#define ZANN(a) \
( uint64_t(1) << static_cast<uint64_t>(AnnotationInternal::a) )
// create a set of rules to detect conflicts between annotations
theConflictRuleSet.push_back(
ZANN(zann_unique) |
ZANN(zann_nonunique));
theConflictRuleSet.push_back(
ZANN(zann_value_equality) |
ZANN(zann_general_equality) |
ZANN(zann_value_range) |
ZANN(zann_general_range));
theConflictRuleSet.push_back(
ZANN(zann_automatic) |
ZANN(zann_manual));
theConflictRuleSet.push_back(
ZANN(zann_mutable) |
ZANN(zann_queue) |
ZANN(zann_append_only) |
ZANN(zann_const));
theConflictRuleSet.push_back(
ZANN(zann_ordered) |
ZANN(zann_unordered));
theConflictRuleSet.push_back(
ZANN(zann_assignable) |
ZANN(zann_nonassignable));
theConflictRuleSet.push_back(
ZANN(zann_strictlydeterministic) |
ZANN(zann_deterministic) |
ZANN(zann_nondeterministic));
theConflictRuleSet.push_back(
ZANN(zann_strictlydeterministic) |
ZANN(zann_cache));
theConflictRuleSet.push_back(
ZANN(zann_sequential) |
ZANN(zann_nonsequential));
theConflictRuleSet.push_back(
ZANN(fn_private) |
ZANN(fn_public));
theConflictRuleSet.push_back(
ZANN(zann_unordered) |
ZANN(zann_queue));
theConflictRuleSet.push_back(
ZANN(zann_unordered) |
ZANN(zann_append_only));
theConflictRuleSet.push_back(
ZANN(zann_queue) |
ZANN(zann_append_only));
theConflictRuleSet.push_back(
ZANN(zann_read_only_nodes) |
ZANN(zann_mutable_nodes));
// create a set of rules to detect missing requirements between annotations
theRequiredRuleSet.push_back(AnnotationRequirement(
zann_exclude_from_cache_key,
ZANN(zann_cache) | ZANN(zann_strictlydeterministic)
));
theRequiredRuleSet.push_back(AnnotationRequirement(
zann_compare_with_deep_equal,
ZANN(zann_cache) | ZANN(zann_strictlydeterministic)
));
#undef ZANN
}
/*******************************************************************************
Static method, called from GlobalEnvironment::destroy()
********************************************************************************/
void AnnotationInternal::destroyBuiltIn()
{
theAnnotId2NameMap.clear();
theAnnotName2IdMap.clear();
}
/*******************************************************************************
********************************************************************************/
AnnotationInternal::AnnotationId AnnotationInternal::lookup(
const store::Item_t& qname)
{
ItemHandleHashMap<AnnotationId>::iterator ite = theAnnotName2IdMap.find(qname);
if (ite == theAnnotName2IdMap.end())
return zann_end;
return (*ite).second;
}
/*******************************************************************************
********************************************************************************/
store::Item* AnnotationInternal::lookup(AnnotationInternal::AnnotationId id)
{
assert(id < zann_end);
assert(id < theAnnotId2NameMap.size());
return theAnnotId2NameMap[id].getp();
}
/*******************************************************************************
********************************************************************************/
AnnotationInternal::AnnotationInternal(const store::Item_t& qname)
:
theId(zann_end),
theQName(qname)
{
ItemHandleHashMap<AnnotationId>::iterator ite = theAnnotName2IdMap.find(qname);
if (ite != theAnnotName2IdMap.end())
theId = (*ite).second;
}
/*******************************************************************************
********************************************************************************/
AnnotationInternal::AnnotationInternal(
const store::Item_t& qname,
std::vector<store::Item_t>& literals)
:
theId(zann_end),
theQName(qname)
{
theLiterals.swap(literals);
ItemHandleHashMap<AnnotationId>::iterator ite = theAnnotName2IdMap.find(qname);
if (ite != theAnnotName2IdMap.end())
theId = (*ite).second;
}
/*******************************************************************************
********************************************************************************/
void AnnotationInternal::serialize(::zorba::serialization::Archiver& ar)
{
SERIALIZE_ENUM(AnnotationId, theId);
ar & theQName;
ar & theLiterals;
}
/*******************************************************************************
********************************************************************************/
const store::Item* AnnotationInternal::getQName() const
{
return theQName.getp();
}
/*******************************************************************************
********************************************************************************/
csize AnnotationInternal::getNumLiterals() const
{
return theLiterals.size();
}
/*******************************************************************************
********************************************************************************/
store::Item* AnnotationInternal::getLiteral(csize index) const
{
if (index < theLiterals.size())
return theLiterals[index].getp();
else
return NULL;
}
/*******************************************************************************
********************************************************************************/
AnnotationList::AnnotationList()
{
}
/*******************************************************************************
********************************************************************************/
AnnotationList::~AnnotationList()
{
for (Annotations::iterator ite = theAnnotationList.begin();
ite != theAnnotationList.end();
++ite)
{
delete *ite;
}
}
/*******************************************************************************
********************************************************************************/
void AnnotationList::serialize(::zorba::serialization::Archiver& ar)
{
ar & theAnnotationList;
}
/*******************************************************************************
********************************************************************************/
AnnotationInternal* AnnotationList::get(size_type index) const
{
if (index < theAnnotationList.size())
return theAnnotationList[index];
else
return NULL;
}
/*******************************************************************************
********************************************************************************/
AnnotationInternal* AnnotationList::get(AnnotationInternal::AnnotationId id) const
{
for (Annotations::const_iterator ite = theAnnotationList.begin();
ite != theAnnotationList.end();
++ite)
{
if ((*ite)->getId() == id)
return (*ite);
}
return NULL;
}
/*******************************************************************************
********************************************************************************/
bool AnnotationList::contains(AnnotationInternal::AnnotationId id) const
{
return (get(id) != NULL);
}
/*******************************************************************************
********************************************************************************/
void AnnotationList::push_back(
const store::Item_t& qname,
const std::vector<const_expr* >& literals)
{
std::vector<store::Item_t> lLiterals;
for (std::vector<const_expr* >::const_iterator it = literals.begin();
it != literals.end();
++it)
{
lLiterals.push_back((*it)->get_val());
}
theAnnotationList.push_back(new AnnotationInternal(qname, lLiterals));
}
/*******************************************************************************
Called from translator to detect duplicates and conflicting declarations
********************************************************************************/
void AnnotationList::checkDeclarations(
DeclarationKind declKind,
const QueryLoc& loc) const
{
// make sure we don't have more annotations then max 64 bit
assert(AnnotationInternal::zann_end < 64);
RuleBitSet lDeclaredAnnotations = checkDuplicateDeclarations(declKind, loc);
checkConflictingDeclarations(lDeclaredAnnotations, declKind, loc);
checkRequiredDeclarations(lDeclaredAnnotations, declKind, loc);
checkLiterals(declKind, loc);
}
AnnotationList::RuleBitSet AnnotationList::checkDuplicateDeclarations(
DeclarationKind declKind,
const QueryLoc& loc) const
{
RuleBitSet lCurrAnn;
// mark and detect duplicates
for (Annotations::const_iterator ite = theAnnotationList.begin();
ite != theAnnotationList.end();
++ite)
{
const store::Item* qname = (*ite)->getQName();
AnnotationId id = (*ite)->getId();
// detect duplicate annotations (if we "know" them)
if (id != AnnotationInternal::zann_end && lCurrAnn.test(id))
{
if (declKind == var_decl)
{
RAISE_ERROR(err::XQST0116, loc,
ERROR_PARAMS(ZED(XQST0116_Duplicate), qname->getStringValue()));
}
else
{
RAISE_ERROR(err::XQST0106, loc,
ERROR_PARAMS(ZED(XQST0106_Duplicate), qname->getStringValue()));
}
}
lCurrAnn.set(id);
}
return lCurrAnn;
}
void AnnotationList::checkConflictingDeclarations(
RuleBitSet currAnn,
DeclarationKind declKind,
const QueryLoc& loc) const
{
// check rules
std::vector<RuleBitSet>::const_iterator ite = AnnotationInternal::theConflictRuleSet.begin();
std::vector<RuleBitSet>::const_iterator end = AnnotationInternal::theConflictRuleSet.end();
for (; ite != end; ++ite)
{
const RuleBitSet& lCurrSet = *ite;
if ((currAnn & lCurrSet).count() > 1)
{
// build error string to return set of conflicting annotations
std::ostringstream lProblems;
for (csize i = 0, j = 0; i < AnnotationInternal::zann_end; ++i)
{
if (lCurrSet.test(i))
{
AnnotationId id = static_cast<AnnotationId>(i);
lProblems << AnnotationInternal::lookup(id)->getStringValue()
<< ((j == (currAnn & lCurrSet).count() - 1) ? "" : ", ");
++j;
}
}
if (declKind == var_decl)
{
RAISE_ERROR(err::XQST0116, loc,
ERROR_PARAMS(ZED(XQST0116_Conflicting), lProblems.str()));
}
else
{
RAISE_ERROR(err::XQST0106, loc,
ERROR_PARAMS(ZED(XQST0106_Conflicting), lProblems.str()));
}
}
}
}
void AnnotationList::checkRequiredDeclarations(
RuleBitSet declaredAnn,
DeclarationKind declKind,
const QueryLoc& loc) const
{
// check rules
std::vector<AnnotationRequirement>::const_iterator ite = AnnotationInternal::theRequiredRuleSet.begin();
std::vector<AnnotationRequirement>::const_iterator end = AnnotationInternal::theRequiredRuleSet.end();
for (; ite != end; ++ite)
{
const AnnotationId& lCurrAnn = ite->first;
const RuleBitSet& lCurrSet = ite->second;
if (declaredAnn.test(lCurrAnn) && (declaredAnn & lCurrSet).count() == 0)
{
// build error string to return set of required annotations
std::ostringstream lProblems;
for (csize i = 0, j = 0; i < AnnotationInternal::zann_end; ++i)
{
if (lCurrSet.test(i))
{
AnnotationId id = static_cast<AnnotationId>(i);
lProblems << AnnotationInternal::lookup(id)->getStringValue()
<< ((j == lCurrSet.count() - 1) ? "" : ", ");
++j;
}
}
if (declKind == var_decl)
{
RAISE_ERROR(err::XQST0116, loc,
ERROR_PARAMS(ZED(XQST0116_Requirement),
AnnotationInternal::lookup(lCurrAnn)->getStringValue(),
lProblems.str()));
}
else
{
RAISE_ERROR(err::XQST0106, loc,
ERROR_PARAMS(ZED(XQST0106_Requirement),
AnnotationInternal::lookup(lCurrAnn)->getStringValue(),
lProblems.str()));
}
}
}
}
void AnnotationList::checkLiterals(DeclarationKind k, const QueryLoc& loc) const
{
for (Annotations::const_iterator ite = theAnnotationList.begin();
ite != theAnnotationList.end();
++ite)
{
AnnotationInternal* lAnn = *ite;
switch (lAnn->getId())
{
case AnnotationInternal::zann_exclude_from_cache_key:
case AnnotationInternal::zann_compare_with_deep_equal:
//One or more integers
if (!lAnn->getNumLiterals())
{
RAISE_ERROR(zerr::ZXQP0062_INVALID_ANNOTATION_LITERALS_NUMBER, loc,
ERROR_PARAMS(
AnnotationInternal::lookup(lAnn->getId())->getStringValue(),
ZED(ZXQP0062_ONE_OR_MORE_LITERALS)));
}
for (csize i=0; i<lAnn->getNumLiterals(); ++i)
checkLiteralType(lAnn, lAnn->getLiteral(i), store::XS_INTEGER, loc);
break;
default:
break;
}
}
}
void AnnotationList::checkLiteralType(AnnotationInternal* ann, zorba::store::Item* literal,
zorba::store::SchemaTypeCode type, const QueryLoc& loc) const
{
if (literal->getTypeCode() != type)
{
std::ostringstream oss;
oss << type;
RAISE_ERROR(zerr::ZXQP0063_INVALID_ANNOTATION_LITERAL_TYPE, loc,
ERROR_PARAMS(
literal->getStringValue(),
literal->getType()->getLocalName(),
AnnotationInternal::lookup(ann->getId())->getStringValue(),
oss.str()));
}
}
} /* namespace zorba */
/* vim:set et sw=2 ts=2: */
| 28.481178 | 106 | 0.566257 | [
"vector"
] |
846ac6e0a755a55f9147c763de509748270c4a6d | 4,944 | cpp | C++ | src/backend/gporca/libgpopt/src/base/CDistributionSpecReplicated.cpp | deart2k/gpdb | df0144f8536c34a19e1c0158580e79a3906ace2e | [
"PostgreSQL",
"Apache-2.0"
] | 12 | 2018-10-02T09:44:51.000Z | 2022-02-21T07:24:08.000Z | src/backend/gporca/libgpopt/src/base/CDistributionSpecReplicated.cpp | deart2k/gpdb | df0144f8536c34a19e1c0158580e79a3906ace2e | [
"PostgreSQL",
"Apache-2.0"
] | 134 | 2018-08-09T09:51:53.000Z | 2022-03-29T03:17:27.000Z | src/backend/gporca/libgpopt/src/base/CDistributionSpecReplicated.cpp | deart2k/gpdb | df0144f8536c34a19e1c0158580e79a3906ace2e | [
"PostgreSQL",
"Apache-2.0"
] | 8 | 2018-05-21T16:20:39.000Z | 2021-11-01T07:05:39.000Z | // Greenplum Database
// Copyright (C) 2020 VMware Inc.
#include "gpopt/base/CDistributionSpecReplicated.h"
#include "gpopt/base/CDistributionSpecNonSingleton.h"
#include "gpopt/base/CDistributionSpecSingleton.h"
#include "gpopt/operators/CPhysicalMotionBroadcast.h"
using namespace gpopt;
// Check if this distribution spec satisfies the given one
// based on following satisfiability rules:
//
// pds = requested distribution
// this = derived distribution
//
// Table - Distribution satisfiability matrix:
// T - Satisfied
// F - Not satisfied; enforcer required
//
// Note that when checking for satisfiability for TaintedReplicated,
// we don't call the Match() function, since TaintedReplicated is a
// derived only property. Hence if FSatisfies is being called on
// TaintedReplicated, pds can never be TaintedReplicated.
// +-------------------------+------------------+-------------------+
// | | StrictReplicated | TaintedReplicated |
// +-------------------------+------------------+-------------------+
// | Matches | T | (default) F |
// | NonSingleton | FAllowReplicated | FAllowReplicated |
// | Replicated | T | T |
// | StrictReplicated | T | F |
// | singleton & master | F | F |
// | singleton & segment | T | T |
// | ANY | T | T |
// | others not Singleton | T |(default) F |
// +-------------------------+------------------+-------------------+
BOOL
CDistributionSpecReplicated::FSatisfies(const CDistributionSpec *pdss) const
{
GPOS_ASSERT(Edt() != CDistributionSpec::EdtReplicated);
if (Edt() == CDistributionSpec::EdtTaintedReplicated)
{
// TaintedReplicated::FSatisfies logic is similar to Replicated::FSatisifes
// except that Replicated can match and satisfy another Replicated Spec.
// However, Tainted will never satisfy another TaintedReplicated or
// Replicated.
switch (pdss->Edt())
{
default:
return false;
case CDistributionSpec::EdtAny:
// tainted replicated distribution satisfies an any required distribution spec
return true;
case CDistributionSpec::EdtReplicated:
// tainted replicated distribution satisfies a general replicated distribution spec
return true;
case CDistributionSpec::EdtNonSingleton:
// a tainted replicated distribution satisfies the non-singleton
// distribution, only if allowed by non-singleton distribution object
return CDistributionSpecNonSingleton::PdsConvert(pdss)
->FAllowReplicated();
case CDistributionSpec::EdtSingleton:
// a tainted replicated distribution satisfies singleton
// distributions that are not master-only
return CDistributionSpecSingleton::PdssConvert(pdss)->Est() ==
CDistributionSpecSingleton::EstSegment;
}
}
else if (Edt() == CDistributionSpec::EdtStrictReplicated)
{
if (Matches(pdss))
{
// exact match implies satisfaction
return true;
}
if (EdtNonSingleton == pdss->Edt())
{
// a replicated distribution satisfies the non-singleton
// distribution, only if allowed by non-singleton distribution object
return CDistributionSpecNonSingleton::PdsConvert(
const_cast<CDistributionSpec *>(pdss))
->FAllowReplicated();
}
// replicated distribution satisfies a general replicated distribution spec
if (EdtReplicated == pdss->Edt())
{
return true;
}
if (CDistributionSpec::EdtRandom == pdss->Edt() &&
(CDistributionSpecRandom::PdsConvert(pdss))->IsDuplicateSensitive())
{
return false;
}
// a replicated distribution satisfies any non-singleton one,
// as well as singleton distributions that are not master-only
return !(EdtSingleton == pdss->Edt() &&
(dynamic_cast<const CDistributionSpecSingleton *>(pdss))
->FOnMaster());
}
return false;
}
void
CDistributionSpecReplicated::AppendEnforcers(CMemoryPool *mp,
CExpressionHandle &, // exprhdl
CReqdPropPlan *
#ifdef GPOS_DEBUG
prpp
#endif // GPOS_DEBUG
,
CExpressionArray *pdrgpexpr,
CExpression *pexpr)
{
GPOS_ASSERT(NULL != mp);
GPOS_ASSERT(NULL != prpp);
GPOS_ASSERT(NULL != pdrgpexpr);
GPOS_ASSERT(NULL != pexpr);
GPOS_ASSERT(!GPOS_FTRACE(EopttraceDisableMotions));
GPOS_ASSERT(
this == prpp->Ped()->PdsRequired() &&
"required plan properties don't match enforced distribution spec");
GPOS_ASSERT(Edt() != CDistributionSpec::EdtTaintedReplicated);
if (GPOS_FTRACE(EopttraceDisableMotionBroadcast))
{
// broadcast Motion is disabled
return;
}
pexpr->AddRef();
CExpression *pexprMotion = GPOS_NEW(mp)
CExpression(mp, GPOS_NEW(mp) CPhysicalMotionBroadcast(mp), pexpr);
pdrgpexpr->Append(pexprMotion);
}
// EOF
| 34.333333 | 87 | 0.645833 | [
"object"
] |
846e3fe502bca727cae70b00c64128e92de93c48 | 40,999 | cpp | C++ | third_party/houdini/lib/gusd/meshWrapper.cpp | navefx/YuksUSD | 56c2e1def36ee07121f4ecb349c1626472b3c338 | [
"AML"
] | 6 | 2018-08-26T13:27:22.000Z | 2021-08-14T23:57:38.000Z | third_party/houdini/lib/gusd/meshWrapper.cpp | navefx/YuksUSD | 56c2e1def36ee07121f4ecb349c1626472b3c338 | [
"AML"
] | 1 | 2021-08-14T23:57:51.000Z | 2021-08-14T23:57:51.000Z | third_party/houdini/lib/gusd/meshWrapper.cpp | navefx/YuksUSD | 56c2e1def36ee07121f4ecb349c1626472b3c338 | [
"AML"
] | 4 | 2018-06-14T18:14:59.000Z | 2021-09-13T22:20:50.000Z | //
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "meshWrapper.h"
#include "context.h"
#include "UT_Gf.h"
#include "GU_USD.h"
#include "GT_VtArray.h"
#include "GT_VtStringArray.h"
#include "tokens.h"
#include "USD_XformCache.h"
#include <GT/GT_DAConstantValue.h>
#include <GT/GT_DANumeric.h>
#include <GT/GT_PrimPolygonMesh.h>
#include <GT/GT_PrimSubdivisionMesh.h>
#include <GT/GT_RefineParms.h>
#include <GT/GT_Refine.h>
#include <GT/GT_DAIndexedString.h>
#include <GT/GT_TransformArray.h>
#include <GT/GT_PrimInstance.h>
#include <GT/GT_DAIndirect.h>
#include <GT/GT_DASubArray.h>
#include <GT/GT_GEOPrimPacked.h>
#include <GT/GT_DAConstant.h>
#include <numeric>
PXR_NAMESPACE_OPEN_SCOPE
using std::cerr;
using std::endl;
using std::string;
using std::map;
#ifdef DEBUG
#define DBG(x) x
#else
#define DBG(x)
#endif
namespace {
void _reverseWindingOrder(GT_Int32Array* indices,
GT_DataArrayHandle faceCounts)
{
GT_DataArrayHandle buffer;
int* indicesData = indices->data();
const int32 *faceCountsData = faceCounts->getI32Array( buffer );
size_t base = 0;
for( size_t f = 0; f < faceCounts->entries(); ++f ) {
int32 numVerts = faceCountsData[f];
for( size_t p = 1, e = (numVerts + 1) / 2; p < e; ++p ) {
std::swap( indicesData[base+p], indicesData[base+numVerts-p] );
}
base+= numVerts;
}
}
void _validateAttrData(
const char* destName, // The Houdni name of the attribute
const char* srcName, // The USD name of the attribute
const char* primName,
GT_DataArrayHandle data,
const TfToken& interpolation,
int numFaces,
int numPoints,
int numVerticies,
GT_AttributeListHandle* vertexAttrs,
GT_AttributeListHandle* pointAttrs,
GT_AttributeListHandle* uniformAttrs,
GT_AttributeListHandle* detailAttrs );
} // anon namespace
GusdMeshWrapper::GusdMeshWrapper(
const GT_PrimitiveHandle& sourcePrim,
const UsdStagePtr& stage,
const SdfPath& path,
const GusdContext& ctxt,
bool isOverride )
: m_forceCreateNewGeo( false )
{
initUsdPrim( stage, path, isOverride );
initialize( ctxt, sourcePrim );
}
GusdMeshWrapper::GusdMeshWrapper(
const UsdGeomMesh& mesh,
UsdTimeCode time,
GusdPurposeSet purposes )
: GusdPrimWrapper( time, purposes )
, m_usdMesh( mesh )
, m_forceCreateNewGeo( false )
{
}
GusdMeshWrapper::GusdMeshWrapper( const GusdMeshWrapper &in )
: GusdPrimWrapper( in )
, m_usdMesh( in.m_usdMesh )
, m_forceCreateNewGeo( false )
{
}
GusdMeshWrapper::
~GusdMeshWrapper()
{
}
bool GusdMeshWrapper::
initUsdPrim(const UsdStagePtr& stage,
const SdfPath& path,
bool asOverride)
{
bool newPrim = true;
m_forceCreateNewGeo = false;
if( asOverride ) {
UsdPrim existing = stage->GetPrimAtPath( path );
if( existing ) {
newPrim = false;
m_usdMesh = UsdGeomMesh(stage->OverridePrim( path ));
}
else {
// When fracturing, we want to override the outside surfaces and create
// new inside surfaces in one export. So if we don't find an existing prim
// with the given path, create a new one.
m_usdMesh = UsdGeomMesh::Define( stage, path );
m_forceCreateNewGeo = true;
}
}
else {
m_usdMesh = UsdGeomMesh::Define( stage, path );
}
if( !m_usdMesh || !m_usdMesh.GetPrim().IsValid() ) {
TF_WARN( "Unable to create %s mesh '%s'.", newPrim ? "new" : "override", path.GetText() );
}
return bool( m_usdMesh );
}
GT_PrimitiveHandle GusdMeshWrapper::
defineForWrite(
const GT_PrimitiveHandle& sourcePrim,
const UsdStagePtr& stage,
const SdfPath& path,
const GusdContext& ctxt )
{
return new GusdMeshWrapper(
sourcePrim,
stage,
path,
ctxt,
ctxt.writeOverlay);
}
GT_PrimitiveHandle GusdMeshWrapper::
defineForRead( const UsdGeomImageable& sourcePrim,
UsdTimeCode time,
GusdPurposeSet purposes )
{
return new GusdMeshWrapper(
UsdGeomMesh( sourcePrim.GetPrim() ),
time,
purposes );
}
bool GusdMeshWrapper::
redefine( const UsdStagePtr& stage,
const SdfPath& path,
const GusdContext& ctxt,
const GT_PrimitiveHandle& sourcePrim )
{
initUsdPrim( stage, path, ctxt.writeOverlay );
clearCaches();
initialize( ctxt, sourcePrim );
return true;
}
void GusdMeshWrapper::
initialize( const GusdContext& ctxt,
const GT_PrimitiveHandle& sourcePrim )
{
// Set defaults from source prim if one was passed in
if((m_forceCreateNewGeo || !ctxt.writeOverlay || ctxt.overlayAll) &&
isValid() && sourcePrim) {
UsdAttribute usdAttr;
// Orientation
usdAttr = m_usdMesh.GetOrientationAttr();
if( usdAttr ) {
// Houdini uses left handed winding order for mesh vertices.
// USD can handle either right or left. If we are overlaying
// geo, we have to reverse the vertex order to match the original,
// otherwise just write the left handled verts directly.
TfToken orientation;
usdAttr.Get(&orientation, UsdTimeCode::Default());
if( orientation == UsdGeomTokens->rightHanded ) {
usdAttr.Set(UsdGeomTokens->leftHanded, UsdTimeCode::Default());
}
}
// SubdivisionScheme
TfToken subdScheme = UsdGeomTokens->none;
if(const GT_PrimSubdivisionMesh* mesh
= dynamic_cast<const GT_PrimSubdivisionMesh*>(sourcePrim.get())) {
if(GT_CATMULL_CLARK == mesh->scheme())
subdScheme = UsdGeomTokens->catmullClark;
else if(GT_LOOP == mesh->scheme())
subdScheme = UsdGeomTokens->loop;
}
setSubdivisionScheme(subdScheme);
}
}
bool
GusdMeshWrapper::refine(
GT_Refine& refiner,
const GT_RefineParms* parms) const
{
if(!isValid()) {
TF_WARN( "Invalid prim" );
return false;
}
bool refineForViewport = GT_GEOPrimPacked::useViewportLOD(parms);
DBG(cerr << "GusdMeshWrapper::refine, " << m_usdMesh.GetPrim().GetPath() << endl);
VtFloatArray vtFloatArray;
VtIntArray vtIntArray;
VtVec3fArray vtVec3Array;
// Houdini only supports left handed geometry. Right handed polys need to
// be reversed on import.
TfToken orientation;
bool reverseWindingOrder =
m_usdMesh.GetOrientationAttr().Get(&orientation, m_time)
&& orientation == UsdGeomTokens->rightHanded;
// vertex counts
UsdAttribute countsAttr = m_usdMesh.GetFaceVertexCountsAttr();
if(!countsAttr) {
TF_WARN( "Invalid vertex count attribute" );
return false;
}
VtIntArray usdCounts;
countsAttr.Get(&usdCounts, m_time);
if( usdCounts.size() < 1 ) {
return false;
}
GT_DataArrayHandle gtVertexCounts = new GusdGT_VtArray<int32>( usdCounts );
int numVerticiesExpected = std::accumulate( usdCounts.begin(), usdCounts.end(), 0 );
// vertex indices
UsdAttribute faceIndexAttr = m_usdMesh.GetFaceVertexIndicesAttr();
if(!faceIndexAttr) {
TF_WARN( "Invalid face vertex indicies attribute for %s.",
m_usdMesh.GetPrim().GetPath().GetText());
return false;
}
VtIntArray usdFaceIndex;
faceIndexAttr.Get(&usdFaceIndex, m_time);
if( usdFaceIndex.size() < numVerticiesExpected ) {
TF_WARN( "Invalid topology found for %s. "
"Expected at least %d verticies and only got %zd.",
m_usdMesh.GetPrim().GetPath().GetText(), numVerticiesExpected, usdFaceIndex.size() );
return false;
}
GT_DataArrayHandle gtIndicesHandle;
if( reverseWindingOrder ) {
// Make a copy and reorder
gtIndicesHandle = new GT_Int32Array(usdFaceIndex.cdata(),
usdFaceIndex.size(), 1);
_reverseWindingOrder(UTverify_cast<GT_Int32Array*>(gtIndicesHandle.get()),
gtVertexCounts);
}
else {
gtIndicesHandle = new GusdGT_VtArray<int32>( usdFaceIndex );
}
// point positions
UsdAttribute pointsAttr = m_usdMesh.GetPointsAttr();
if(!pointsAttr) {
TF_WARN( "Invalid point attribute" );
return false;
}
VtVec3fArray usdPoints;
pointsAttr.Get(&usdPoints, m_time);
int maxPointIndex = *std::max_element( usdFaceIndex.begin(), usdFaceIndex.end() ) + 1;
if( usdPoints.size() < maxPointIndex ) {
TF_WARN( "Invalid topology found for %s. "
"Expected at least %d points and only got %zd.",
m_usdMesh.GetPrim().GetPath().GetText(), maxPointIndex, usdPoints.size() );
return false;
}
auto gtPoints = new GusdGT_VtArray<GfVec3f>(usdPoints,GT_TYPE_POINT);
GT_AttributeListHandle gtPointAttrs = new GT_AttributeList( new GT_AttributeMap() );
GT_AttributeListHandle gtVertexAttrs = new GT_AttributeList( new GT_AttributeMap() );
GT_AttributeListHandle gtUniformAttrs = new GT_AttributeList( new GT_AttributeMap() );
GT_AttributeListHandle gtDetailAttrs = new GT_AttributeList( new GT_AttributeMap() );
gtPointAttrs = gtPointAttrs->addAttribute("P", gtPoints, true);
UsdAttribute normalsAttr = m_usdMesh.GetNormalsAttr();
if( normalsAttr && normalsAttr.HasAuthoredValueOpinion()) {
normalsAttr.Get(&vtVec3Array, m_time);
GT_DataArrayHandle gtNormals =
new GusdGT_VtArray<GfVec3f>(vtVec3Array, GT_TYPE_NORMAL);
TfToken interp;
if (!normalsAttr.GetMetadata(UsdGeomTokens->interpolation, &interp)) {
interp = UsdGeomTokens->varying;
}
if( gtNormals ) {
_validateAttrData(
"N",
normalsAttr.GetBaseName().GetText(),
m_usdMesh.GetPrim().GetPath().GetText(),
gtNormals,
interp,
usdCounts.size(),
usdPoints.size(),
usdFaceIndex.size(),
>VertexAttrs,
>PointAttrs,
>UniformAttrs,
>DetailAttrs );
}
}
if( !refineForViewport ) {
// point velocities
UsdAttribute velAttr = m_usdMesh.GetVelocitiesAttr();
if (velAttr && velAttr.HasAuthoredValueOpinion()) {
velAttr.Get(&vtVec3Array, m_time);
GT_DataArrayHandle gtVel =
new GusdGT_VtArray<GfVec3f>(vtVec3Array, GT_TYPE_VECTOR);
if( gtVel ) {
_validateAttrData(
"v",
velAttr.GetBaseName().GetText(),
m_usdMesh.GetPrim().GetPath().GetText(),
gtVel,
UsdGeomTokens->varying, // Point attribute
usdCounts.size(),
usdPoints.size(),
usdFaceIndex.size(),
>VertexAttrs,
>PointAttrs,
>UniformAttrs,
>DetailAttrs );
}
}
loadPrimvars( m_time, parms,
usdCounts.size(),
usdPoints.size(),
usdFaceIndex.size(),
m_usdMesh.GetPath().GetString(),
>VertexAttrs,
>PointAttrs,
>UniformAttrs,
>DetailAttrs );
if( gtVertexAttrs->entries() > 0 ) {
if( reverseWindingOrder ) {
// Construct an index array which will be used to lookup vertex
// attributes in the correct order.
GT_Int32Array* vertexIndirect
= new GT_Int32Array(gtIndicesHandle->entries(), 1);
GT_DataArrayHandle vertexIndirectHandle(vertexIndirect);
for(int i=0; i<gtIndicesHandle->entries(); ++i) {
vertexIndirect->set(i, i);
}
_reverseWindingOrder(vertexIndirect, gtVertexCounts );
gtVertexAttrs = gtVertexAttrs->createIndirect(vertexIndirect);
}
}
}
else {
// When refining for the viewport, the only attributes we care about is color
// and opacity. Prefer Cd / Alpha, but fallback to displayColor and displayOpacity.
// In order to be able to coalesce meshes in the GT_PrimCache, we need to use
// the same attribute owner for the attribute in all meshes. So promote
// to vertex.
UsdGeomPrimvar colorPrimvar = m_usdMesh.GetPrimvar(GusdTokens->Cd);
if( !colorPrimvar || !colorPrimvar.GetAttr().HasAuthoredValueOpinion() ) {
colorPrimvar = m_usdMesh.GetPrimvar(GusdTokens->displayColor);
}
if( colorPrimvar && colorPrimvar.GetAttr().HasAuthoredValueOpinion()) {
GT_DataArrayHandle gtData = convertPrimvarData( colorPrimvar, m_time );
if( gtData ) {
_validateAttrData(
"Cd",
colorPrimvar.GetBaseName().GetText(),
m_usdMesh.GetPrim().GetPath().GetText(),
gtData,
colorPrimvar.GetInterpolation(),
usdCounts.size(),
usdPoints.size(),
usdFaceIndex.size(),
>VertexAttrs,
>PointAttrs,
>UniformAttrs,
>DetailAttrs );
}
}
UsdGeomPrimvar alphaPrimvar = m_usdMesh.GetPrimvar(GusdTokens->Alpha);
if( !alphaPrimvar || !alphaPrimvar.GetAttr().HasAuthoredValueOpinion() ) {
alphaPrimvar = m_usdMesh.GetPrimvar(GusdTokens->displayOpacity);
}
if( alphaPrimvar && alphaPrimvar.GetAttr().HasAuthoredValueOpinion()) {
GT_DataArrayHandle gtData = convertPrimvarData( alphaPrimvar, m_time );
if( gtData ) {
_validateAttrData(
"Alpha",
alphaPrimvar.GetBaseName().GetText(),
m_usdMesh.GetPrim().GetPath().GetText(),
gtData,
alphaPrimvar.GetInterpolation(),
usdCounts.size(),
usdPoints.size(),
usdFaceIndex.size(),
>VertexAttrs,
>PointAttrs,
>UniformAttrs,
>DetailAttrs );
}
}
}
// build GT_Primitive
TfToken subdScheme;
m_usdMesh.GetSubdivisionSchemeAttr().Get(&subdScheme, m_time);
bool isSubdMesh = (UsdGeomTokens->none != subdScheme);
GT_PrimitiveHandle meshPrim;
if(isSubdMesh) {
GT_PrimSubdivisionMesh *subdPrim =
new GT_PrimSubdivisionMesh(gtVertexCounts,
gtIndicesHandle,
gtPointAttrs,
gtVertexAttrs,
gtUniformAttrs,
gtDetailAttrs);
meshPrim = subdPrim;
// See the houdini distribution's alembic importer for examples
// of how to use these tags:
// ./HoudiniAlembic/GABC/GABC_IObject.C
// inside HFS/houdini/public/Alembic/HoudiniAlembic.tgz
// Scheme
if (subdScheme == UsdGeomTokens->catmullClark) {
subdPrim->setScheme(GT_CATMULL_CLARK);
} else if (subdScheme == UsdGeomTokens->loop) {
subdPrim->setScheme(GT_LOOP);
} else {
// Other values, like bilinear, have no equivalent in houdini.
}
// Corners
UsdAttribute cornerIndicesAttr = m_usdMesh.GetCornerIndicesAttr();
UsdAttribute cornerSharpnessAttr = m_usdMesh.GetCornerSharpnessesAttr();
if (cornerIndicesAttr.IsValid() && cornerSharpnessAttr.IsValid()) {
cornerIndicesAttr.Get(&vtIntArray, m_time);
cornerSharpnessAttr.Get(&vtFloatArray, m_time);
if(!vtIntArray.empty() && !vtFloatArray.empty()) {
GT_DataArrayHandle cornerArrayHandle
= new GT_Int32Array(vtIntArray.data(), vtIntArray.size(), 1);
subdPrim->appendIntTag("corner", cornerArrayHandle);
GT_DataArrayHandle corenerWeightArrayHandle
= new GT_Real32Array(vtFloatArray.data(), vtFloatArray.size(), 1);
subdPrim->appendRealTag("corner", corenerWeightArrayHandle);
}
}
// Creases
UsdAttribute creaseIndicesAttr = m_usdMesh.GetCreaseIndicesAttr();
UsdAttribute creaseLengthsAttr = m_usdMesh.GetCreaseLengthsAttr();
UsdAttribute creaseSharpnessesAttr = m_usdMesh.GetCreaseSharpnessesAttr();
if (creaseIndicesAttr.IsValid() &&
creaseLengthsAttr.IsValid() &&
creaseSharpnessesAttr.IsValid() &&
creaseIndicesAttr.HasAuthoredValueOpinion()) {
// Extract vt arrays
VtIntArray vtCreaseIndices;
VtIntArray vtCreaseLengths;
VtFloatArray vtCreaseSharpnesses;
creaseIndicesAttr.Get(&vtCreaseIndices, m_time);
creaseLengthsAttr.Get(&vtCreaseLengths, m_time);
creaseSharpnessesAttr.Get(&vtCreaseSharpnesses, m_time);
// Unpack creases to vertex-pairs.
// Usd stores creases as N-length chains of vertices;
// Houdini expects separate creases per vertex pair.
std::vector<int> creaseIndices;
std::vector<float> creaseSharpness;
if (vtCreaseLengths.size() == vtCreaseSharpnesses.size()) {
// We have exactly 1 sharpness per crease.
size_t i=0;
for (size_t creaseNum=0; creaseNum < vtCreaseLengths.size();
++creaseNum) {
const float length = vtCreaseLengths[creaseNum];
const float sharp = vtCreaseSharpnesses[creaseNum];
for (size_t indexInCrease=0; indexInCrease < length-1;
++indexInCrease) {
creaseIndices.push_back( vtCreaseIndices[i] );
creaseIndices.push_back( vtCreaseIndices[i+1] );
creaseSharpness.push_back( sharp );
++i;
}
// Last index is only used once.
++i;
}
UT_ASSERT(i == vtCreaseIndices.size());
} else {
// We have N-1 sharpnesses for each crease that has N edges,
// i.e. the sharpness varies along each crease.
size_t i=0;
size_t sharpIndex=0;
for (size_t creaseNum=0; creaseNum < vtCreaseLengths.size();
++creaseNum) {
const float length = vtCreaseLengths[creaseNum];
for (size_t indexInCrease=0; indexInCrease < length-1;
++indexInCrease) {
creaseIndices.push_back( vtCreaseIndices[i] );
creaseIndices.push_back( vtCreaseIndices[i+1] );
const float sharp = vtCreaseSharpnesses[sharpIndex];
creaseSharpness.push_back(sharp);
++i;
++sharpIndex;
}
// Last index is only used once.
++i;
}
UT_ASSERT(i == vtCreaseIndices.size());
UT_ASSERT(sharpIndex == vtCreaseSharpnesses.size());
}
// Store tag.
GT_Int32Array *index =
new GT_Int32Array( &creaseIndices[0],
creaseIndices.size(), 1);
GT_Real32Array *weight =
new GT_Real32Array( &creaseSharpness[0],
creaseSharpness.size(), 1);
UT_ASSERT(index->entries() == weight->entries()*2);
subdPrim->appendIntTag("crease", GT_DataArrayHandle(index));
subdPrim->appendRealTag("crease", GT_DataArrayHandle(weight));
}
// Interpolation boundaries
UsdAttribute interpBoundaryAttr = m_usdMesh.GetInterpolateBoundaryAttr();
if(interpBoundaryAttr.IsValid()) {
TfToken val;
interpBoundaryAttr.Get(&val, m_time);
GT_DataArrayHandle interpBoundaryHandle = new GT_IntConstant(1, 1);
subdPrim->appendIntTag("interpolateboundary", interpBoundaryHandle);
}
//if (ival = sample.getFaceVaryingInterpolateBoundary())
//{
//GT_IntConstant *val = new GT_IntConstant(1, ival);
//gt->appendIntTag("facevaryinginterpolateboundary",
//GT_DataArrayHandle(val));
//}
//if (ival = sample.getFaceVaryingPropagateCorners())
//{
//GT_IntConstant *val = new GT_IntConstant(1, ival);
//gt->appendIntTag("facevaryingpropagatecorners",
//GT_DataArrayHandle(val));
//}
}
else {
meshPrim
= new GT_PrimPolygonMesh(gtVertexCounts,
gtIndicesHandle,
gtPointAttrs,
gtVertexAttrs,
gtUniformAttrs,
gtDetailAttrs);
}
meshPrim->setPrimitiveTransform( getPrimitiveTransform() );
refiner.addPrimitive( meshPrim );
return true;
}
namespace {
void
_validateAttrData(
const char* destName, // The Houdni name of the attribute
const char* srcName, // The USD name of the attribute
const char* primName,
GT_DataArrayHandle data,
const TfToken& interpolation,
int numFaces,
int numPoints,
int numVerticies,
GT_AttributeListHandle* vertexAttrs,
GT_AttributeListHandle* pointAttrs,
GT_AttributeListHandle* uniformAttrs,
GT_AttributeListHandle* detailAttrs )
{
if( interpolation == UsdGeomTokens->vertex ||
interpolation == UsdGeomTokens->varying ) {
if( data->entries() < numPoints ) {
TF_WARN( "Not enough values found for attribute: %s:%s",
primName, srcName );
}
else {
*pointAttrs = (*pointAttrs)->addAttribute( destName, data, true );
}
}
else if( interpolation == UsdGeomTokens->faceVarying ) {
if( data->entries() < numVerticies ) {
TF_WARN( "Not enough values found for attribute: %s:%s",
primName, srcName );
}
else {
*vertexAttrs = (*vertexAttrs)->addAttribute( destName, data, true );
}
}
else if( interpolation == UsdGeomTokens->uniform ) {
if( data->entries() < numFaces ) {
TF_WARN( "Not enough values found for attribute: %s:%s",
primName, srcName );
}
else {
*uniformAttrs = (*uniformAttrs)->addAttribute( destName, data, true );
}
}
else if( interpolation == UsdGeomTokens->constant ) {
if( data->entries() < 1 ) {
TF_WARN( "Not enough values found for attribute: %s:%s",
primName, srcName );
}
else {
*detailAttrs = (*detailAttrs)->addAttribute( destName, data, true );
}
}
}
}
//------------------------------------------------------------------------------
bool GusdMeshWrapper::
setSubdivisionScheme(const TfToken& scheme)
{
if(!m_usdMesh) {
return false;
}
UsdAttribute usdAttr = m_usdMesh.GetSubdivisionSchemeAttr();
if(!usdAttr) return false;
return usdAttr.Set(scheme, UsdTimeCode::Default());
}
TfToken GusdMeshWrapper::
getSubdivisionScheme() const
{
TfToken scheme;
if(m_usdMesh) {
m_usdMesh.GetSubdivisionSchemeAttr().Get(&scheme, UsdTimeCode::Default());
}
return scheme;
}
bool GusdMeshWrapper::
getUniqueID(int64& id) const
{
static const int s_id = GT_Primitive::createPrimitiveTypeId();
id = s_id;
return true;
}
const char* GusdMeshWrapper::
className() const
{
return "GusdMeshWrapper";
}
void GusdMeshWrapper::
enlargeBounds(UT_BoundingBox boxes[], int nsegments) const
{
// TODO
}
int GusdMeshWrapper::
getMotionSegments() const
{
// TODO
return 1;
}
int64 GusdMeshWrapper::
getMemoryUsage() const
{
cerr << "mesh wrapper, get memory usage" << endl;
return 0;
}
GT_PrimitiveHandle GusdMeshWrapper::
doSoftCopy() const
{
// TODO
return GT_PrimitiveHandle(new GusdMeshWrapper( *this ));
}
bool GusdMeshWrapper::isValid() const
{
return static_cast<bool>(m_usdMesh);
}
bool GusdMeshWrapper::
updateFromGTPrim(const GT_PrimitiveHandle& sourcePrim,
const UT_Matrix4D& houXform,
const GusdContext& ctxt,
GusdSimpleXformCache& xformCache )
{
if(!isValid()) {
TF_WARN( "Can't update USD mesh from GT prim '%s'", m_usdMesh.GetPrim().GetPath().GetText() );
return false;
}
const GT_PrimPolygonMesh* gtMesh
= dynamic_cast<const GT_PrimPolygonMesh*>(sourcePrim.get());
if(!gtMesh) {
TF_WARN( "source prim is not a mesh. '%s'", m_usdMesh.GetPrim().GetPath().GetText() );
return false;
}
bool writeOverlay = ctxt.writeOverlay && !m_forceCreateNewGeo;
// While I suppose we could write both points and transforms, it gets confusing,
// and I don't thik its necessary so lets not.
bool overlayTransforms = ctxt.overlayTransforms && !ctxt.overlayPoints;
UsdTimeCode geoTime = ctxt.time;
if( ctxt.writeStaticGeo ) {
geoTime = UsdTimeCode::Default();
}
bool reverseWindingOrder = false;
GT_DataArrayHandle vertexIndirect;
if( writeOverlay && (ctxt.overlayPrimvars || ctxt.overlayPoints) && !ctxt.overlayAll ) {
// If we are writing an overlay, we need to write geometry that matches
// the orientation of the underlying prim. All geometry in Houdini is left
// handed.
TfToken orientation;
m_usdMesh.GetOrientationAttr().Get(&orientation, geoTime);
if( orientation == UsdGeomTokens->rightHanded ) {
reverseWindingOrder = true;
// Build a LUT that will allow us to map the vertex list or
// primvars using a "indirect" data array.
GT_Size entries = gtMesh->getVertexList()->entries();
GT_Int32Array* indirect = new GT_Int32Array( entries, 1 );
for(int i=0; i<entries; ++i) {
indirect->set(i, i);
}
_reverseWindingOrder(indirect, gtMesh->getFaceCounts() );
vertexIndirect = indirect;
}
}
// houXform is a transform from world space to the space this prim's
// points are defined in. Compute this space relative to this prims's
// USD parent.
// Compute transform not including this prims transform.
GfMatrix4d xform = computeTransform(
m_usdMesh.GetPrim().GetParent(),
geoTime,
houXform,
xformCache );
// Compute transform including this prims transform.
GfMatrix4d loc_xform = computeTransform(
m_usdMesh.GetPrim(),
geoTime,
houXform,
xformCache );
// If we are writing points for an overlay but not writing transforms,
// then we have to transform the points into the proper space.
bool transformPoints =
writeOverlay && ctxt.overlayPoints &&
!GusdUT_Gf::Cast(loc_xform).isIdentity();
if( !writeOverlay && ctxt.purpose != UsdGeomTokens->default_ ) {
m_usdMesh.GetPurposeAttr().Set( ctxt.purpose );
}
// intrinsic attributes ----------------------------------------------------
GT_Owner attrOwner = GT_OWNER_INVALID;
GT_DataArrayHandle houAttr;
UsdAttribute usdAttr;
if( !writeOverlay || ctxt.overlayAll ||
ctxt.overlayPoints || overlayTransforms ) {
// extent
houAttr = GusdGT_Utils::getExtentsArray(sourcePrim);
usdAttr = m_usdMesh.GetExtentAttr();
if(houAttr && usdAttr && transformPoints ) {
houAttr = GusdGT_Utils::transformPoints( houAttr, loc_xform );
}
updateAttributeFromGTPrim( GT_OWNER_INVALID, "extents", houAttr, usdAttr, geoTime );
}
// transform ---------------------------------------------------------------
if( !writeOverlay || overlayTransforms ) {
updateTransformFromGTPrim( xform, geoTime,
ctxt.granularity == GusdContext::PER_FRAME );
}
updateVisibilityFromGTPrim(sourcePrim, geoTime,
(!ctxt.writeOverlay || ctxt.overlayAll) &&
ctxt.granularity == GusdContext::PER_FRAME );
// Points
if( !writeOverlay || ctxt.overlayAll || ctxt.overlayPoints ) {
// P
houAttr = sourcePrim->findAttribute("P", attrOwner, 0);
usdAttr = m_usdMesh.GetPointsAttr();
if( houAttr && usdAttr && transformPoints ) {
houAttr = GusdGT_Utils::transformPoints( houAttr, loc_xform );
}
updateAttributeFromGTPrim( attrOwner, "P",
houAttr, usdAttr, geoTime );
// N
houAttr = sourcePrim->findAttribute("N", attrOwner, 0);
if( houAttr && houAttr->getTupleSize() != 3 ) {
TF_WARN( "normals (N) attribute is not a 3 vector. Tuple size = %zd.",
houAttr->getTupleSize() );
}
usdAttr = m_usdMesh.GetNormalsAttr();
if( updateAttributeFromGTPrim( attrOwner, "N",
houAttr, usdAttr, geoTime ) ) {
if(GT_OWNER_VERTEX == attrOwner) {
m_usdMesh.SetNormalsInterpolation(UsdGeomTokens->faceVarying);
} else {
m_usdMesh.SetNormalsInterpolation(UsdGeomTokens->varying);
}
}
// v
houAttr = sourcePrim->findAttribute("v", attrOwner, 0);
if( houAttr && houAttr->getTupleSize() != 3 ) {
TF_WARN( "velocity (v) attribute is not a 3 vector. Tuple size = %zd.",
houAttr->getTupleSize() );
}
usdAttr = m_usdMesh.GetVelocitiesAttr();
updateAttributeFromGTPrim( attrOwner, "v",
houAttr, usdAttr, geoTime );
}
// Topology
if( !writeOverlay || ctxt.overlayAll ) {
UsdTimeCode topologyTime = ctxt.time;
if( ctxt.writeStaticTopology ) {
topologyTime = UsdTimeCode::Default();
}
// FaceVertexCounts
GT_DataArrayHandle houVertexCounts = gtMesh->getFaceCounts();
usdAttr = m_usdMesh.GetFaceVertexCountsAttr();
updateAttributeFromGTPrim( GT_OWNER_INVALID, "facevertexcounts",
houVertexCounts, usdAttr, topologyTime );
// FaceVertexIndices
GT_DataArrayHandle houVertexList = gtMesh->getVertexList();
if( reverseWindingOrder ) {
houVertexList = new GT_DAIndirect( vertexIndirect, houVertexList );
}
usdAttr = m_usdMesh.GetFaceVertexIndicesAttr();
updateAttributeFromGTPrim( GT_OWNER_INVALID, "facevertexindices",
houVertexList, usdAttr, topologyTime );
// Creases
if(const GT_PrimSubdivisionMesh* subdMesh
= dynamic_cast<const GT_PrimSubdivisionMesh*>(gtMesh)) {
if (const GT_PrimSubdivisionMesh::Tag *tag =
subdMesh->findTag("crease")) {
const GT_Int32Array *index =
dynamic_cast<GT_Int32Array*>(tag->intArray().get());
const GT_Real32Array *weight =
dynamic_cast<GT_Real32Array*>(tag->realArray().get());
if (index && weight) {
// We expect two index entries per weight
UT_ASSERT(index->entries() == weight->entries()*2);
// Convert to vt arrays
const int numCreases = weight->entries();
VtIntArray vtCreaseIndices;
VtIntArray vtCreaseLengths;
VtFloatArray vtCreaseSharpnesses;
vtCreaseIndices.resize(numCreases*2);
vtCreaseLengths.resize(numCreases);
vtCreaseSharpnesses.resize(numCreases);
for (size_t i=0; i < numCreases; ++i) {
vtCreaseIndices[i*2+0] = index->getValue<int>(i*2+0);
vtCreaseIndices[i*2+1] = index->getValue<int>(i*2+1);
vtCreaseSharpnesses[i] = weight->getValue<float>(i);
// We leave creases as vertex-pairs; we do
// not attempt to stitch them into longer runs.
vtCreaseLengths[i] = 2;
}
// Set usd attributes
UsdAttribute creaseIndicesAttr =
m_usdMesh.GetCreaseIndicesAttr();
UsdAttribute creaseLengthsAttr =
m_usdMesh.GetCreaseLengthsAttr();
UsdAttribute creaseSharpnessesAttr =
m_usdMesh.GetCreaseSharpnessesAttr();
creaseIndicesAttr.Set(vtCreaseIndices, m_time);
creaseLengthsAttr.Set(vtCreaseLengths, m_time);
creaseSharpnessesAttr.Set(vtCreaseSharpnesses, m_time);
}
}
}
}
// -------------------------------------------------------------------------
// primvars ----------------------------------------------------------------
if( !writeOverlay || ctxt.overlayAll || ctxt.overlayPrimvars ) {
UsdTimeCode primvarTime = ctxt.time;
if( ctxt.writeStaticPrimvars ) {
primvarTime = UsdTimeCode::Default();
}
GusdGT_AttrFilter filter = ctxt.attributeFilter;
filter.appendPattern(GT_OWNER_POINT, "^P ^N ^v");
filter.appendPattern(GT_OWNER_VERTEX, "^N ^creaseweight");
if( !ctxt.primPathAttribute.empty() ) {
filter.appendPattern(GT_OWNER_UNIFORM, "^" + ctxt.primPathAttribute );
}
if(const GT_AttributeListHandle pointAttrs = sourcePrim->getPointAttributes()) {
GusdGT_AttrFilter::OwnerArgs owners;
owners << GT_OWNER_POINT;
filter.setActiveOwners(owners);
updatePrimvarFromGTPrim( pointAttrs, filter, UsdGeomTokens->vertex, primvarTime );
}
if(GT_AttributeListHandle vertexAttrs = sourcePrim->getVertexAttributes()) {
GusdGT_AttrFilter::OwnerArgs owners;
owners << GT_OWNER_VERTEX;
filter.setActiveOwners(owners);
if( reverseWindingOrder ) {
// Use an index array (LUT) which will be used to lookup vertex
// attributes in the correct order.
vertexAttrs = vertexAttrs->createIndirect(vertexIndirect);
}
updatePrimvarFromGTPrim( vertexAttrs, filter, UsdGeomTokens->faceVarying, primvarTime );
}
if(const GT_AttributeListHandle primAttrs = sourcePrim->getUniformAttributes()) {
GusdGT_AttrFilter::OwnerArgs owners;
owners << GT_OWNER_UNIFORM;
filter.setActiveOwners(owners);
// When we import primvars from USD, both constant and uniform values get
// put into primitive attributes. At this point we don't really know
// which to write so we use the hueristic, if all the values in the array are
// identical, write the value as constant.
for( auto it = primAttrs->begin(); !it.atEnd(); ++it ) {
if(!filter.matches( it.getName() ))
continue;
GT_DataArrayHandle data = it.getData();
TfToken interpolation = UsdGeomTokens->uniform;
// cerr << "primitive primvar = " << it.getName() << ", "
// << data->className() << ", "
// << GTstorage( data->getStorage() ) << ", "
// << data->entries() << endl;
// cerr << "face count = " << gtMesh->getFaceCount() << endl;
if( GusdGT_Utils::isDataConstant( data ) ) {
interpolation = UsdGeomTokens->constant;
data = new GT_DASubArray( data, 0, 1 );
}
updatePrimvarFromGTPrim(
TfToken( it.getName() ),
GT_OWNER_UNIFORM,
interpolation,
primvarTime,
data );
}
}
if(const GT_AttributeListHandle constAttrs = sourcePrim->getDetailAttributes()) {
GusdGT_AttrFilter::OwnerArgs owners;
owners << GT_OWNER_CONSTANT;
filter.setActiveOwners(owners);
updatePrimvarFromGTPrim( constAttrs, filter, UsdGeomTokens->constant, primvarTime );
}
// If we have a "Cd" attribute, write it as both "Cd" and "displayColor".
// The USD guys promise me that this data will get "deduplicated" so there
// is not cost for doing this.
GT_Owner own;
if(GT_DataArrayHandle Cd = sourcePrim->findAttribute( "Cd", own, 0 )) {
TfToken interpolation = s_ownerToUsdInterp[own];
if ( own == GT_OWNER_PRIMITIVE ) {
if( GusdGT_Utils::isDataConstant( Cd ) ) {
interpolation = UsdGeomTokens->constant;
Cd = new GT_DASubArray( Cd, 0, 1 );
}
}
updatePrimvarFromGTPrim( GusdTokens->displayColor, GT_OWNER_UNIFORM,
interpolation, primvarTime, Cd );
}
// If we have a "Alpha" attribute, write it as both "Alpha" and "displayOpacity".
if(GT_DataArrayHandle Alpha = sourcePrim->findAttribute( "Alpha", own, 0 )) {
TfToken interpolation = s_ownerToUsdInterp[own];
if ( own == GT_OWNER_PRIMITIVE ) {
if( GusdGT_Utils::isDataConstant( Alpha ) ) {
interpolation = UsdGeomTokens->constant;
Alpha = new GT_DASubArray( Alpha, 0, 1 );
}
}
updatePrimvarFromGTPrim( GusdTokens->displayOpacity, GT_OWNER_UNIFORM,
interpolation, primvarTime, Alpha );
}
}
return GusdPrimWrapper::updateFromGTPrim(sourcePrim, houXform, ctxt, xformCache);
}
PXR_NAMESPACE_CLOSE_SCOPE
| 37.036134 | 102 | 0.56938 | [
"mesh",
"geometry",
"vector",
"transform"
] |
846e7557480cce08d7105bd60e237c818738e0ce | 8,304 | cc | C++ | L1Trigger/RPCTechnicalTrigger/src/RBCProcessRPCDigis.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | L1Trigger/RPCTechnicalTrigger/src/RBCProcessRPCDigis.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | L1Trigger/RPCTechnicalTrigger/src/RBCProcessRPCDigis.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | // Include files
// local
#include "L1Trigger/RPCTechnicalTrigger/interface/RBCProcessRPCDigis.h"
#include "L1Trigger/RPCTechnicalTrigger/interface/RBCLinkBoardGLSignal.h"
#include "DataFormats/Common/interface/Handle.h"
#include "GeometryConstants.h"
//-----------------------------------------------------------------------------
// Implementation file for class : RBCProcessRPCDigis
//
// 2009-04-15 : Andres Felipe Osorio Oliveros
//-----------------------------------------------------------------------------
using namespace rpctechnicaltrigger;
//=============================================================================
// Standard constructor, initializes variables
//=============================================================================
RBCProcessRPCDigis::RBCProcessRPCDigis( const edm::ESHandle<RPCGeometry> & rpcGeom,
const edm::Handle<RPCDigiCollection> & digiColl ) :
m_maxBxWindow{3},
m_debug{false}
{
m_ptr_rpcGeom = & rpcGeom;
m_ptr_digiColl = & digiColl;
m_lbin =std::make_unique<RBCLinkBoardGLSignal>( &m_data ) ;
configure();
}
void RBCProcessRPCDigis::configure()
{
for( auto wheel : s_wheelid)
m_digiCounters.emplace(wheel, wheel);
}
//=============================================================================
// Destructor
//=============================================================================
RBCProcessRPCDigis::~RBCProcessRPCDigis() {
}
//=============================================================================
int RBCProcessRPCDigis::next() {
//...clean up previous data contents
reset();
int ndigis(0);
for (auto const& detUnit : *(*m_ptr_digiColl) ) {
if ( m_debug ) std::cout << "looping over digis 1 ..." << std::endl;
auto digiItr = detUnit.second.first;
int bx = (*digiItr).bx();
if ( abs(bx) >= m_maxBxWindow ) {
if ( m_debug ) std::cout << "RBCProcessRPCDigis> found a bx bigger than max allowed: "
<< bx << std::endl;
continue;
}
const RPCDetId & id = detUnit.first;
const RPCRoll * roll = dynamic_cast<const RPCRoll* >( (*m_ptr_rpcGeom)->roll(id));
if((roll->isForward())) {
if( m_debug ) std::cout << "RBCProcessRPCDigis: roll is forward" << std::endl;
continue;
}
int wheel = roll->id().ring(); // -2,-1,0,+1,+2
int sector = roll->id().sector(); // 1 to 12
int layer = roll->id().layer(); // 1,2
int station = roll->id().station(); // 1-4
int blayer = getBarrelLayer( layer, station ); // 1 to 6
int rollid = id.roll();
int digipos = (station * 100) + (layer * 10) + rollid;
if ( (wheel == -1 || wheel == 0 || wheel == 1) && station == 2 && layer == 1 )
digipos = 30000 + digipos;
if ( (wheel == -2 || wheel == 2) && station == 2 && layer == 2 )
digipos = 30000 + digipos;
if ( (wheel == -1 || wheel == 0 || wheel == 1) && station == 2 && layer == 2 )
digipos = 20000 + digipos;
if ( (wheel == -2 || wheel == 2) && station == 2 && layer == 1 )
digipos = 20000 + digipos;
if ( m_debug ) std::cout << "Bx: " << bx << '\t'
<< "Wheel: " << wheel << '\t'
<< "Sector: " << sector << '\t'
<< "Station: " << station << '\t'
<< "Layer: " << layer << '\t'
<< "B-Layer: " << blayer << '\t'
<< "Roll id: " << rollid << '\t'
<< "Digi at: " << digipos << '\n';
//... Construct the RBCinput objects
auto itr = m_vecDataperBx.find( bx );
if ( itr == m_vecDataperBx.end() ) {
if ( m_debug ) std::cout << "Found a new Bx: " << bx << std::endl;
auto& wheelData = m_vecDataperBx[bx];
initialize(wheelData);
setDigiAt( sector, digipos, wheelData[ (wheel + 2) ] );
}
else{
setDigiAt( sector, digipos, (*itr).second[ (wheel + 2) ] );
}
auto wheelCounter = m_digiCounters.find( wheel );
if ( wheelCounter != m_digiCounters.end() )
(*wheelCounter).second.incrementSector( sector );
if ( m_debug ) std::cout << "looping over digis 2 ..." << std::endl;
++ndigis;
}
if ( m_debug ) std::cout << "size of data vectors: " << m_vecDataperBx.size() << std::endl;
builddata();
if ( m_debug ) {
std::cout << "after reset" << std::endl;
print_output();
}
if ( m_debug ) std::cout << "RBCProcessRPCDigis: DataSize: " << m_data.size()
<< " ndigis " << ndigis << std::endl;
for( auto& wheelCounter : m_digiCounters) {
wheelCounter.second.evalCounters();
if ( m_debug ) wheelCounter.second.printSummary();
}
if ( m_data.empty() ) return 0;
return 1;
}
void RBCProcessRPCDigis::reset()
{
m_vecDataperBx.clear();
}
void RBCProcessRPCDigis::initialize( std::vector<RPCData> & dataVec ) const
{
if ( m_debug ) std::cout << "initialize" << std::endl;
constexpr int maxWheels = 5;
constexpr int maxRbcBrds = 6;
dataVec.reserve(maxWheels);
for(int i=0; i < maxWheels; ++i) {
auto& block = dataVec.emplace_back();
block.m_wheel = s_wheelid[i];
for(int j=0; j < maxRbcBrds; ++j) {
block.m_sec1[j] = s_sec1id[j];
block.m_sec2[j] = s_sec2id[j];
block.m_orsignals[j].input_sec[0].reset();
block.m_orsignals[j].input_sec[1].reset();
block.m_orsignals[j].needmapping = false;
block.m_orsignals[j].hasData = false;
}
}
if ( m_debug ) std::cout << "initialize: completed" << std::endl;
}
void RBCProcessRPCDigis::builddata()
{
for(auto & vecData: m_vecDataperBx) {
int bx = vecData.first;
int bxsign(1);
if ( bx != 0 ) bxsign = ( bx / abs(bx) );
else bxsign = 1;
for(auto & item : vecData.second) {
for(int k=0; k < 6; ++k) {
int code = bxsign * ( 1000000*abs(bx)
+ 10000*item.wheelIdx()
+ 100 *item.m_sec1[k]
+ 1 *item.m_sec2[k] );
RBCInput * signal = & item.m_orsignals[k];
signal->needmapping = false;
if ( signal->hasData )
m_data.emplace( code , signal );
}
}
}
if ( m_debug and not m_vecDataperBx.empty() ) std::cout << "builddata: completed. size of data: " << m_data.size() << std::endl;
}
int RBCProcessRPCDigis::getBarrelLayer( const int & _layer, const int & _station )
{
//... Calculates the generic Barrel Layer (1 to 6)
int blayer(0);
if ( _station < 3 ) {
blayer = ( (_station-1) * 2 ) + _layer;
}
else {
blayer = _station + 2;
}
return blayer;
}
void RBCProcessRPCDigis::setDigiAt( int sector, int digipos, RPCData& block )
{
int pos = 0;
int isAoB = 0;
if ( m_debug ) std::cout << "setDigiAt" << std::endl;
auto itr = std::find( s_sec1id.begin(), s_sec1id.end(), sector );
if ( itr == s_sec1id.end()) {
itr = std::find( s_sec2id.begin(), s_sec2id.end(), sector );
isAoB = 1;
}
for ( pos = 0; pos < 6; ++pos ) {
if (block.m_sec1[pos] == sector || block.m_sec2[pos] == sector )
break;
}
if ( m_debug ) std::cout << block.m_orsignals[pos];
setInputBit( block.m_orsignals[pos].input_sec[ isAoB ] , digipos );
block.m_orsignals[pos].hasData = true;
if ( m_debug ) std::cout << block.m_orsignals[pos];
if ( m_debug ) std::cout << "setDigiAt completed" << std::endl;
}
void RBCProcessRPCDigis::setInputBit( std::bitset<15> & signals , int digipos )
{
int bitpos = s_layermap.at(digipos);
if( m_debug ) std::cout << "Bitpos: " << bitpos << std::endl;
signals.set( bitpos , true );
}
void RBCProcessRPCDigis::print_output()
{
std::cout << "RBCProcessRPCDigis> Output starts" << std::endl;
for( auto const& item: m_data) {
std::cout << item.first << '\t' << (* item.second ) << '\n';
}
std::cout << "RBCProcessRPCDigis> Output ends" << std::endl;
}
| 28.244898 | 130 | 0.508309 | [
"vector"
] |
84717369b37e8bf673248f017e8a03e504a53ad3 | 5,477 | cpp | C++ | lib/movegenerator/HeisenbergMoveGenerator.cpp | federico-terzi/osarracino | ae34855a1881282f35f556c4dde95d281ad0db0c | [
"MIT"
] | 11 | 2019-05-19T13:18:25.000Z | 2022-03-29T19:28:25.000Z | lib/movegenerator/HeisenbergMoveGenerator.cpp | federico-terzi/osarracino | ae34855a1881282f35f556c4dde95d281ad0db0c | [
"MIT"
] | null | null | null | lib/movegenerator/HeisenbergMoveGenerator.cpp | federico-terzi/osarracino | ae34855a1881282f35f556c4dde95d281ad0db0c | [
"MIT"
] | null | null | null | //
// Created by freddy on 27/04/19.
//
#include "util/BitUtils.h"
#include <algorithm>
#include "HeisenbergMoveGenerator.h"
const bool citadels[9][9] = {
{0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 0, 0, 0, 0, 0, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 0, 0, 0},
};
const uint16_t citadel_masks[9] = {
0b0000000'111000111,
0b0000000'111101111,
0b0000000'111111111,
0b0000000'111111111,
0b0000000'001111100,
0b0000000'111111111,
0b0000000'111111111,
0b0000000'111101111,
0b0000000'111000111,
};
HeisenbergMoveGenerator::HeisenbergMoveGenerator() {
// Initialize the col_to_positions cache, by precomputing all the possible
// configurations for a given column.
for (uint16_t col_config = 0; col_config < 512; col_config++) {
for (int col = 0; col < 9; col++) {
std::vector<Position> positions;
for (int row = 0; row < 9; row++) {
if (col_config & (1<<row)) {
positions.push_back({col, row});
}
}
col_to_positions[col_config][col] = std::move(positions);
}
}
// Initialize the horizontal moves cache.
for (uint16_t row_config = 0; row_config < 512; row_config++) {
for (int col = 0; col < 9; col++) {
for (int row = 0; row < 9; row++) {
std::vector<Move> current_moves;
int horizontal_high_moves = BitUtils::get_high_moves(row_config, col);
for (int i = (col+1); i <= (col + horizontal_high_moves); i++) {
current_moves.push_back({Position{col, row}, Position{i, row}});
}
int horizontal_low_moves = BitUtils::get_low_moves(row_config, col);
for (int i = (col-1); i >= (col- horizontal_low_moves); i--) {
current_moves.push_back({Position{col, row}, Position{i, row}});
}
row_to_horizontal_moves[row_config][col][row] = std::move(current_moves);
}
}
}
// Initialize the vertical moves cache.
for (uint16_t col_config = 0; col_config < 512; col_config++) {
for (int col = 0; col < 9; col++) {
for (int row = 0; row < 9; row++) {
std::vector<Move> current_moves;
int vertical_high_moves = BitUtils::get_high_moves(col_config, row);
for (int i = (row+1); i <= (row + vertical_high_moves); i++) {
current_moves.push_back({Position{col, row}, Position{col, i}});
}
int vertical_low_moves = BitUtils::get_low_moves(col_config, row);
for (int i = (row-1); i >= (row - vertical_low_moves); i--) {
current_moves.push_back({Position{col, row}, Position{col, i}});
}
col_to_vertical_moves[col_config][col][row] = std::move(current_moves);
}
}
}
}
std::vector<Move> HeisenbergMoveGenerator::generate(const Board &b) const {
std::vector<Move> current_moves;
if (b.is_white_win() || b.is_black_win()) {
return current_moves;
}
std::vector<Position> to_be_moved;
const uint16_t *target_col_vector = (b.is_white) ? b.white_cols : b.black_cols;
// Calculate the moves
for (int col = 0; col < 9; col++) {
const std::vector<Position> &positions {col_to_positions[target_col_vector[col]][col]};
to_be_moved.insert(to_be_moved.end(), positions.begin(), positions.end());
}
current_moves.reserve(30);
for (auto &pawn : to_be_moved) {
uint16_t target_col = b.obstacle_cols[pawn.col];
uint16_t target_row = b.obstacle_rows[pawn.row];
// Check if it's a black pawn inside a citadel
// to enable passing through the citadel itself
if (citadels[pawn.col][pawn.row]) {
target_col &= (citadel_masks[pawn.col] | b.white_cols[pawn.col] | b.black_cols[pawn.col]);
target_row &= (citadel_masks[pawn.row] | b.white_rows[pawn.row] | b.black_rows[pawn.row]);
}
auto &horizontal_moves {row_to_horizontal_moves[target_row][pawn.col][pawn.row]};
current_moves.insert(current_moves.end(), horizontal_moves.begin(), horizontal_moves.end());
auto &vertical_moves {col_to_vertical_moves[target_col][pawn.col][pawn.row]};
current_moves.insert(current_moves.end(), vertical_moves.begin(), vertical_moves.end());
}
if (!b.is_white) { // SORT BY KING DISTANCE
//BLACK
std::sort(current_moves.begin(), current_moves.end(), [&b](const auto &item1, const auto &item2) {
return abs(b.king_pos.col - item1.to.col) + abs(b.king_pos.row - item1.to.row) <
abs(b.king_pos.col - item2.to.col) + abs(b.king_pos.row - item2.to.row);
});
} else { // WHITE
std::sort(current_moves.begin(), current_moves.end(), [&b](const auto &item1, const auto &item2)-> bool {
return abs(b.king_pos.col - item1.from.col) + abs(b.king_pos.row - item1.from.row) <
abs(b.king_pos.col - item2.from.col) + abs(b.king_pos.row - item2.from.row);
});
}
return current_moves;
}
| 37.772414 | 113 | 0.564725 | [
"vector"
] |
8472e55cfb12aad11dbb4c1cca3de15746b0e0dc | 1,672 | cpp | C++ | c++/h5/format.cpp | hmenke/h5 | a21520150219f3c88d91908cea8e83535c608aa5 | [
"Apache-2.0"
] | null | null | null | c++/h5/format.cpp | hmenke/h5 | a21520150219f3c88d91908cea8e83535c608aa5 | [
"Apache-2.0"
] | 4 | 2021-02-05T16:44:54.000Z | 2021-11-30T08:15:35.000Z | c++/h5/format.cpp | hmenke/h5 | a21520150219f3c88d91908cea8e83535c608aa5 | [
"Apache-2.0"
] | 4 | 2020-05-01T21:04:50.000Z | 2021-07-01T17:52:02.000Z | // Copyright (c) 2019-2020 Simons Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0.txt
//
// 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 "./format.hpp"
#include "./stl/string.hpp"
#include <string>
namespace h5 {
void read_hdf5_format(object obj, std::string &s) {
h5_read_attribute(obj, "Format", s);
if (s == "") { // Backward compatibility
h5_read_attribute(obj, "TRIQS_HDF5_data_scheme", s);
}
}
std::string read_hdf5_format(group g) {
std::string s;
read_hdf5_format(g, s);
return s;
}
void read_hdf5_format_from_key(group g, std::string const &key, std::string &s) {
h5_read_attribute_from_key(g, key, "Format", s);
if (s == "") { // Backward compatibility
h5_read_attribute_from_key(g, key, "TRIQS_HDF5_data_scheme", s);
}
}
void assert_hdf5_format_as_string(group g, const char *tag_expected, bool ignore_if_absent) {
auto tag_file = read_hdf5_format(g);
if (ignore_if_absent and tag_file.empty()) return;
if (tag_file != tag_expected)
throw std::runtime_error("h5_read : mismatch of the Format tag in the h5 group : found " + tag_file + " while I expected " + tag_expected);
}
} // namespace h5
| 34.122449 | 145 | 0.699163 | [
"object"
] |
8472f7130d2314f32e037f0e64fdbb18af043aa3 | 4,191 | cpp | C++ | libs/cocos2d-x/extensions/CCArmature/physics/CCPhysicsWorld.cpp | mxenabled/androidpp | 5fd587157232d1d92bcc9402c0b9acfb5e65034b | [
"ICU",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 3 | 2016-03-25T14:11:57.000Z | 2021-08-24T19:46:11.000Z | libs/cocos2d-x/extensions/CCArmature/physics/CCPhysicsWorld.cpp | mxenabled/androidpp | 5fd587157232d1d92bcc9402c0b9acfb5e65034b | [
"ICU",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null | libs/cocos2d-x/extensions/CCArmature/physics/CCPhysicsWorld.cpp | mxenabled/androidpp | 5fd587157232d1d92bcc9402c0b9acfb5e65034b | [
"ICU",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 2 | 2018-01-18T04:38:16.000Z | 2019-05-29T02:20:44.000Z | /****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
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 "CCPhysicsWorld.h"
#include "../utils/CCArmatureDefine.h"
#include "Box2D/Box2D.h"
#include "../external_tool/GLES-Render.h"
NS_CC_EXT_BEGIN
class Contact
{
public:
b2Fixture *fixtureA;
b2Fixture *fixtureB;
};
class ContactListener : public b2ContactListener
{
//! Callbacks for derived classes.
virtual void BeginContact(b2Contact *contact)
{
if (contact)
{
Contact c;
c.fixtureA = contact->GetFixtureA();
c.fixtureB = contact->GetFixtureB();
contact_list.push_back(c);
}
B2_NOT_USED(contact);
}
virtual void EndContact(b2Contact *contact)
{
contact_list.clear();
B2_NOT_USED(contact);
}
virtual void PreSolve(b2Contact *contact, const b2Manifold *oldManifold)
{
B2_NOT_USED(contact);
B2_NOT_USED(oldManifold);
}
virtual void PostSolve(const b2Contact *contact, const b2ContactImpulse *impulse)
{
B2_NOT_USED(contact);
B2_NOT_USED(impulse);
}
public:
std::list<Contact> contact_list;
};
CCPhysicsWorld *CCPhysicsWorld::s_PhysicsWorld = NULL;
CCPhysicsWorld *CCPhysicsWorld::sharedPhysicsWorld()
{
if (s_PhysicsWorld == NULL)
{
s_PhysicsWorld = new CCPhysicsWorld();
s_PhysicsWorld->initNoGravityWorld();
}
return s_PhysicsWorld;
}
void CCPhysicsWorld::purgePhysicsWorld()
{
delete s_PhysicsWorld;
s_PhysicsWorld = NULL;
}
CCPhysicsWorld::CCPhysicsWorld()
: m_pNoGravityWorld(NULL)
, m_pDebugDraw(NULL)
{
}
CCPhysicsWorld::~CCPhysicsWorld()
{
CC_SAFE_DELETE(m_pDebugDraw);
CC_SAFE_DELETE(m_pNoGravityWorld);
CC_SAFE_DELETE(m_pContactListener);
}
void CCPhysicsWorld::initNoGravityWorld()
{
b2Vec2 noGravity(0, 0);
m_pNoGravityWorld = new b2World(noGravity);
m_pNoGravityWorld->SetAllowSleeping(true);
m_pContactListener = new ContactListener();
m_pNoGravityWorld->SetContactListener(m_pContactListener);
#if ENABLE_PHYSICS_DEBUG
m_pDebugDraw = new GLESDebugDraw( PT_RATIO );
m_pNoGravityWorld->SetDebugDraw(m_pDebugDraw);
uint32 flags = 0;
flags += b2Draw::e_shapeBit;
// flags += b2Draw::e_jointBit;
// flags += b2Draw::e_aabbBit;
// flags += b2Draw::e_pairBit;
// flags += b2Draw::e_centerOfMassBit;
m_pDebugDraw->SetFlags(flags);
#endif
}
b2World *CCPhysicsWorld::getNoGravityWorld()
{
return m_pNoGravityWorld;
}
void CCPhysicsWorld::update(float dt)
{
m_pNoGravityWorld->Step(dt, 0, 0);
for (std::list<Contact>::iterator it = m_pContactListener->contact_list.begin(); it != m_pContactListener->contact_list.end(); ++it)
{
Contact &contact = *it;
b2Body *b2a = contact.fixtureA->GetBody();
b2Body *b2b = contact.fixtureB->GetBody();
CCBone *ba = (CCBone *)b2a->GetUserData();
CCBone *bb = (CCBone *)b2b->GetUserData();
BoneColliderSignal.emit(ba, bb);
}
}
void CCPhysicsWorld::drawDebug()
{
m_pNoGravityWorld->DrawDebugData();
}
NS_CC_EXT_END
| 25.246988 | 136 | 0.698401 | [
"render"
] |
8473d2cf6cef8be65416c181c682a9942727bdb7 | 4,463 | hpp | C++ | ad_map_access/generated/include/ad/map/landmark/ENULandmark.hpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | 61 | 2019-12-19T20:57:24.000Z | 2022-03-29T15:20:51.000Z | ad_map_access/generated/include/ad/map/landmark/ENULandmark.hpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | 54 | 2020-04-05T05:32:47.000Z | 2022-03-15T18:42:33.000Z | ad_map_access/generated/include/ad/map/landmark/ENULandmark.hpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | 31 | 2019-12-20T07:37:39.000Z | 2022-03-16T13:06:16.000Z | /*
* ----------------- BEGIN LICENSE BLOCK ---------------------------------
*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
* ----------------- END LICENSE BLOCK -----------------------------------
*/
/**
* Generated file
* @file
*
* Generator Version : 11.0.0-1997
*/
#pragma once
#include <iostream>
#include <limits>
#include <memory>
#include <sstream>
#include "ad/map/landmark/LandmarkId.hpp"
#include "ad/map/landmark/LandmarkType.hpp"
#include "ad/map/landmark/TrafficLightType.hpp"
#include "ad/map/point/ENUHeading.hpp"
#include "ad/map/point/ENUPoint.hpp"
/*!
* @brief namespace ad
*/
namespace ad {
/*!
* @brief namespace map
*/
namespace map {
/*!
* @brief namespace landmark
*
* Handling of landmarks
*/
namespace landmark {
/*!
* \brief DataType ENULandmark
*
* Landmark description in ENU coordiante frame.
*/
struct ENULandmark
{
/*!
* \brief Smart pointer on ENULandmark
*/
typedef std::shared_ptr<ENULandmark> Ptr;
/*!
* \brief Smart pointer on constant ENULandmark
*/
typedef std::shared_ptr<ENULandmark const> ConstPtr;
/*!
* \brief standard constructor
*/
ENULandmark() = default;
/*!
* \brief standard destructor
*/
~ENULandmark() = default;
/*!
* \brief standard copy constructor
*/
ENULandmark(const ENULandmark &other) = default;
/*!
* \brief standard move constructor
*/
ENULandmark(ENULandmark &&other) = default;
/**
* \brief standard assignment operator
*
* \param[in] other Other ENULandmark
*
* \returns Reference to this ENULandmark.
*/
ENULandmark &operator=(const ENULandmark &other) = default;
/**
* \brief standard move operator
*
* \param[in] other Other ENULandmark
*
* \returns Reference to this ENULandmark.
*/
ENULandmark &operator=(ENULandmark &&other) = default;
/**
* \brief standard comparison operator
*
* \param[in] other Other ENULandmark
*
* \returns \c true if both ENULandmark are equal
*/
bool operator==(const ENULandmark &other) const
{
return (id == other.id) && (type == other.type) && (position == other.position) && (heading == other.heading)
&& (trafficLightType == other.trafficLightType);
}
/**
* \brief standard comparison operator
*
* \param[in] other Other ENULandmark.
*
* \returns \c true if both ENULandmark are different
*/
bool operator!=(const ENULandmark &other) const
{
return !operator==(other);
}
/*!
* Identifier of the landmark.
*/
::ad::map::landmark::LandmarkId id{0};
/*!
* Type of the landmark.
*/
::ad::map::landmark::LandmarkType type{::ad::map::landmark::LandmarkType::INVALID};
/*!
* Position of the landmark
*/
::ad::map::point::ENUPoint position;
/*!
* Landmark 2D orientation regardind Z axis (A.K.A. yaw/heading) [rad]Directional heading of the landmark.
*/
::ad::map::point::ENUHeading heading;
::ad::map::landmark::TrafficLightType trafficLightType{::ad::map::landmark::TrafficLightType::INVALID};
};
} // namespace landmark
} // namespace map
} // namespace ad
/*!
* \brief protect the definition of functions from duplicates by typedef usage within other data types
*/
#ifndef GEN_GUARD_AD_MAP_LANDMARK_ENULANDMARK
#define GEN_GUARD_AD_MAP_LANDMARK_ENULANDMARK
/*!
* @brief namespace ad
*/
namespace ad {
/*!
* @brief namespace map
*/
namespace map {
/*!
* @brief namespace landmark
*
* Handling of landmarks
*/
namespace landmark {
/**
* \brief standard ostream operator
*
* \param[in] os The output stream to write to
* \param[in] _value ENULandmark value
*
* \returns The stream object.
*
*/
inline std::ostream &operator<<(std::ostream &os, ENULandmark const &_value)
{
os << "ENULandmark(";
os << "id:";
os << _value.id;
os << ",";
os << "type:";
os << _value.type;
os << ",";
os << "position:";
os << _value.position;
os << ",";
os << "heading:";
os << _value.heading;
os << ",";
os << "trafficLightType:";
os << _value.trafficLightType;
os << ")";
return os;
}
} // namespace landmark
} // namespace map
} // namespace ad
namespace std {
/*!
* \brief overload of the std::to_string for ENULandmark
*/
inline std::string to_string(::ad::map::landmark::ENULandmark const &value)
{
stringstream sstream;
sstream << value;
return sstream.str();
}
} // namespace std
#endif // GEN_GUARD_AD_MAP_LANDMARK_ENULANDMARK
| 20.662037 | 113 | 0.63724 | [
"object"
] |
848145aa53fc85a365e995fc47cef3c61dab4481 | 302 | cpp | C++ | SGI-STL/SGI-STL Test/allocator_test/myAllocator/myAllocator.cpp | silence0201/C-Plus-Study | ad013f093f275620dee892033e5152083b10f2fc | [
"MIT"
] | null | null | null | SGI-STL/SGI-STL Test/allocator_test/myAllocator/myAllocator.cpp | silence0201/C-Plus-Study | ad013f093f275620dee892033e5152083b10f2fc | [
"MIT"
] | null | null | null | SGI-STL/SGI-STL Test/allocator_test/myAllocator/myAllocator.cpp | silence0201/C-Plus-Study | ad013f093f275620dee892033e5152083b10f2fc | [
"MIT"
] | null | null | null | #include "myAllocator.h"
#include <vector>
#include <iostream>
using namespace std;
// myAllocator test
int main()
{
int arr[5] = {0, 1, 2, 3, 4};
vector<int, myAllocator::allocator<int> > iv(arr, arr + 5);
for (size_t i = 0; i < iv.size(); i++) {
cout << iv[i] << ' ';
}
cout << endl;
}
| 15.1 | 60 | 0.572848 | [
"vector"
] |
8481ea5da5c07a4de209f4e0fecda53d15e6e789 | 31,531 | hpp | C++ | include/System/RuntimeTypeHandle.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/System/RuntimeTypeHandle.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/System/RuntimeTypeHandle.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"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"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.Runtime.Serialization.ISerializable
#include "System/Runtime/Serialization/ISerializable.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.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
namespace System {
// Forward declaring type: RuntimeType
class RuntimeType;
// Forward declaring type: Type
class Type;
}
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: TypeAttributes
struct TypeAttributes;
// Forward declaring type: RuntimeAssembly
class RuntimeAssembly;
// Forward declaring type: RuntimeModule
class RuntimeModule;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Size: 0x8
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: System.RuntimeTypeHandle
// [TokenAttribute] Offset: FFFFFFFF
// [ComVisibleAttribute] Offset: E14704
struct RuntimeTypeHandle/*, public System::ValueType, public System::Runtime::Serialization::ISerializable*/ {
public:
// private System.IntPtr value
// Size: 0x8
// Offset: 0x0
System::IntPtr value;
// Field size check
static_assert(sizeof(System::IntPtr) == 0x8);
// Creating value type constructor for type: RuntimeTypeHandle
constexpr RuntimeTypeHandle(System::IntPtr value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Creating interface conversion operator: operator System::Runtime::Serialization::ISerializable
operator System::Runtime::Serialization::ISerializable() noexcept {
return *reinterpret_cast<System::Runtime::Serialization::ISerializable*>(this);
}
// Creating conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept {
return value;
}
// Get instance field: private System.IntPtr value
System::IntPtr _get_value();
// Set instance field: private System.IntPtr value
void _set_value(System::IntPtr value);
// public System.IntPtr get_Value()
// Offset: 0xD76A60
System::IntPtr get_Value();
// System.Void .ctor(System.IntPtr val)
// Offset: 0xD76A34
// template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
// ABORTED: conflicts with another method. RuntimeTypeHandle(System::IntPtr val)
// System.Void .ctor(System.RuntimeType type)
// Offset: 0xD76A3C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
RuntimeTypeHandle(System::RuntimeType* type) {
static auto ___internal__logger = ::Logger::get().WithContext("System::RuntimeTypeHandle::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, type);
}
// private System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0xD76A58
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
RuntimeTypeHandle(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context) {
static auto ___internal__logger = ::Logger::get().WithContext("System::RuntimeTypeHandle::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(info), ::il2cpp_utils::ExtractType(context)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, info, context);
}
// public System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0xD76A68
void GetObjectData(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context);
// static System.Reflection.TypeAttributes GetAttributes(System.RuntimeType type)
// Offset: 0x138C560
static System::Reflection::TypeAttributes GetAttributes(System::RuntimeType* type);
// static private System.Int32 GetMetadataToken(System.RuntimeType type)
// Offset: 0x13921B4
static int GetMetadataToken(System::RuntimeType* type);
// static System.Int32 GetToken(System.RuntimeType type)
// Offset: 0x138F340
static int GetToken(System::RuntimeType* type);
// static private System.Type GetGenericTypeDefinition_impl(System.RuntimeType type)
// Offset: 0x13921B8
static System::Type* GetGenericTypeDefinition_impl(System::RuntimeType* type);
// static System.Type GetGenericTypeDefinition(System.RuntimeType type)
// Offset: 0x138DBB0
static System::Type* GetGenericTypeDefinition(System::RuntimeType* type);
// static System.Boolean HasElementType(System.RuntimeType type)
// Offset: 0x138C7D4
static bool HasElementType(System::RuntimeType* type);
// static System.Boolean HasInstantiation(System.RuntimeType type)
// Offset: 0x138DBB8
static bool HasInstantiation(System::RuntimeType* type);
// static System.Boolean IsArray(System.RuntimeType type)
// Offset: 0x138C960
static bool IsArray(System::RuntimeType* type);
// static System.Boolean IsByRef(System.RuntimeType type)
// Offset: 0x138C5FC
static bool IsByRef(System::RuntimeType* type);
// static System.Boolean IsComObject(System.RuntimeType type)
// Offset: 0x13921BC
static bool IsComObject(System::RuntimeType* type);
// static System.Boolean IsInstanceOfType(System.RuntimeType type, System.Object o)
// Offset: 0x138C208
static bool IsInstanceOfType(System::RuntimeType* type, ::Il2CppObject* o);
// static System.Boolean IsPointer(System.RuntimeType type)
// Offset: 0x138C60C
static bool IsPointer(System::RuntimeType* type);
// static System.Boolean IsPrimitive(System.RuntimeType type)
// Offset: 0x138C604
static bool IsPrimitive(System::RuntimeType* type);
// static System.Boolean HasReferences(System.RuntimeType type)
// Offset: 0x13921C0
static bool HasReferences(System::RuntimeType* type);
// static System.Boolean IsComObject(System.RuntimeType type, System.Boolean isGenericCOM)
// Offset: 0x138C614
static bool IsComObject(System::RuntimeType* type, bool isGenericCOM);
// static System.Boolean IsContextful(System.RuntimeType type)
// Offset: 0x138C568
static bool IsContextful(System::RuntimeType* type);
// static System.Boolean IsEquivalentTo(System.RuntimeType rtType1, System.RuntimeType rtType2)
// Offset: 0x138C544
static bool IsEquivalentTo(System::RuntimeType* rtType1, System::RuntimeType* rtType2);
// static System.Boolean IsSzArray(System.RuntimeType type)
// Offset: 0x138C90C
static bool IsSzArray(System::RuntimeType* type);
// static System.Boolean IsInterface(System.RuntimeType type)
// Offset: 0x13921C4
static bool IsInterface(System::RuntimeType* type);
// static System.Int32 GetArrayRank(System.RuntimeType type)
// Offset: 0x138CA10
static int GetArrayRank(System::RuntimeType* type);
// static System.Reflection.RuntimeAssembly GetAssembly(System.RuntimeType type)
// Offset: 0x138C1CC
static System::Reflection::RuntimeAssembly* GetAssembly(System::RuntimeType* type);
// static System.RuntimeType GetElementType(System.RuntimeType type)
// Offset: 0x138CA18
static System::RuntimeType* GetElementType(System::RuntimeType* type);
// static System.Reflection.RuntimeModule GetModule(System.RuntimeType type)
// Offset: 0x138C1C0
static System::Reflection::RuntimeModule* GetModule(System::RuntimeType* type);
// static System.Boolean IsGenericVariable(System.RuntimeType type)
// Offset: 0x138C550
static bool IsGenericVariable(System::RuntimeType* type);
// static System.RuntimeType GetBaseType(System.RuntimeType type)
// Offset: 0x138C554
static System::RuntimeType* GetBaseType(System::RuntimeType* type);
// static System.Boolean CanCastTo(System.RuntimeType type, System.RuntimeType target)
// Offset: 0x138C488
static bool CanCastTo(System::RuntimeType* type, System::RuntimeType* target);
// static private System.Boolean type_is_assignable_from(System.Type a, System.Type b)
// Offset: 0x13921E8
static bool type_is_assignable_from(System::Type* a, System::Type* b);
// static System.Boolean IsGenericTypeDefinition(System.RuntimeType type)
// Offset: 0x138DA4C
static bool IsGenericTypeDefinition(System::RuntimeType* type);
// static System.IntPtr GetGenericParameterInfo(System.RuntimeType type)
// Offset: 0x139161C
static System::IntPtr GetGenericParameterInfo(System::RuntimeType* type);
// public override System.Boolean Equals(System.Object obj)
// Offset: 0xD76A70
// Implemented from: System.ValueType
// Base method: System.Boolean ValueType::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0xD76A78
// Implemented from: System.ValueType
// Base method: System.Int32 ValueType::GetHashCode()
int GetHashCode();
}; // System.RuntimeTypeHandle
#pragma pack(pop)
static check_size<sizeof(RuntimeTypeHandle), 0 + sizeof(System::IntPtr)> __System_RuntimeTypeHandleSizeCheck;
static_assert(sizeof(RuntimeTypeHandle) == 0x8);
}
DEFINE_IL2CPP_ARG_TYPE(System::RuntimeTypeHandle, "System", "RuntimeTypeHandle");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::RuntimeTypeHandle::get_Value
// Il2CppName: get_Value
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IntPtr (System::RuntimeTypeHandle::*)()>(&System::RuntimeTypeHandle::get_Value)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "get_Value", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::RuntimeTypeHandle
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::RuntimeTypeHandle::RuntimeTypeHandle
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::RuntimeTypeHandle::RuntimeTypeHandle
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetObjectData
// Il2CppName: GetObjectData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::RuntimeTypeHandle::*)(System::Runtime::Serialization::SerializationInfo*, System::Runtime::Serialization::StreamingContext)>(&System::RuntimeTypeHandle::GetObjectData)> {
static const MethodInfo* get() {
static auto* info = &::il2cpp_utils::GetClassFromName("System.Runtime.Serialization", "SerializationInfo")->byval_arg;
static auto* context = &::il2cpp_utils::GetClassFromName("System.Runtime.Serialization", "StreamingContext")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetObjectData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{info, context});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetAttributes
// Il2CppName: GetAttributes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Reflection::TypeAttributes (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetAttributes)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetAttributes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetMetadataToken
// Il2CppName: GetMetadataToken
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetMetadataToken)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetMetadataToken", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetToken
// Il2CppName: GetToken
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetToken)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetToken", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetGenericTypeDefinition_impl
// Il2CppName: GetGenericTypeDefinition_impl
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Type* (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetGenericTypeDefinition_impl)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetGenericTypeDefinition_impl", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetGenericTypeDefinition
// Il2CppName: GetGenericTypeDefinition
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Type* (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetGenericTypeDefinition)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetGenericTypeDefinition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::HasElementType
// Il2CppName: HasElementType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::HasElementType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "HasElementType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::HasInstantiation
// Il2CppName: HasInstantiation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::HasInstantiation)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "HasInstantiation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsArray
// Il2CppName: IsArray
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsArray)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsArray", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsByRef
// Il2CppName: IsByRef
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsByRef)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsByRef", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsComObject
// Il2CppName: IsComObject
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsComObject)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsComObject", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsInstanceOfType
// Il2CppName: IsInstanceOfType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*, ::Il2CppObject*)>(&System::RuntimeTypeHandle::IsInstanceOfType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
static auto* o = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsInstanceOfType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, o});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsPointer
// Il2CppName: IsPointer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsPointer)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsPointer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsPrimitive
// Il2CppName: IsPrimitive
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsPrimitive)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsPrimitive", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::HasReferences
// Il2CppName: HasReferences
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::HasReferences)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "HasReferences", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsComObject
// Il2CppName: IsComObject
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*, bool)>(&System::RuntimeTypeHandle::IsComObject)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
static auto* isGenericCOM = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsComObject", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, isGenericCOM});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsContextful
// Il2CppName: IsContextful
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsContextful)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsContextful", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsEquivalentTo
// Il2CppName: IsEquivalentTo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*, System::RuntimeType*)>(&System::RuntimeTypeHandle::IsEquivalentTo)> {
static const MethodInfo* get() {
static auto* rtType1 = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
static auto* rtType2 = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsEquivalentTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{rtType1, rtType2});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsSzArray
// Il2CppName: IsSzArray
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsSzArray)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsSzArray", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsInterface
// Il2CppName: IsInterface
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsInterface)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsInterface", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetArrayRank
// Il2CppName: GetArrayRank
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetArrayRank)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetArrayRank", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetAssembly
// Il2CppName: GetAssembly
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Reflection::RuntimeAssembly* (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetAssembly)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetAssembly", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetElementType
// Il2CppName: GetElementType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::RuntimeType* (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetElementType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetElementType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetModule
// Il2CppName: GetModule
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Reflection::RuntimeModule* (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetModule)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetModule", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsGenericVariable
// Il2CppName: IsGenericVariable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsGenericVariable)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsGenericVariable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetBaseType
// Il2CppName: GetBaseType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::RuntimeType* (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetBaseType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetBaseType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::CanCastTo
// Il2CppName: CanCastTo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*, System::RuntimeType*)>(&System::RuntimeTypeHandle::CanCastTo)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
static auto* target = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "CanCastTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, target});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::type_is_assignable_from
// Il2CppName: type_is_assignable_from
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::Type*, System::Type*)>(&System::RuntimeTypeHandle::type_is_assignable_from)> {
static const MethodInfo* get() {
static auto* a = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* b = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "type_is_assignable_from", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{a, b});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::IsGenericTypeDefinition
// Il2CppName: IsGenericTypeDefinition
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::IsGenericTypeDefinition)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "IsGenericTypeDefinition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetGenericParameterInfo
// Il2CppName: GetGenericParameterInfo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IntPtr (*)(System::RuntimeType*)>(&System::RuntimeTypeHandle::GetGenericParameterInfo)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "RuntimeType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetGenericParameterInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::Equals
// Il2CppName: Equals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::RuntimeTypeHandle::*)(::Il2CppObject*)>(&System::RuntimeTypeHandle::Equals)> {
static const MethodInfo* get() {
static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj});
}
};
// Writing MetadataGetter for method: System::RuntimeTypeHandle::GetHashCode
// Il2CppName: GetHashCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::RuntimeTypeHandle::*)()>(&System::RuntimeTypeHandle::GetHashCode)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::RuntimeTypeHandle), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 60.753372 | 254 | 0.739685 | [
"object",
"vector"
] |
84883a1d300235711e001c474fec05d09bf1795a | 6,517 | cpp | C++ | src/common/string_util.cpp | maierfelix/bnsh-decoder | e02ccef69780831b38fe5b31710855d9ca6a5977 | [
"MIT"
] | 4 | 2020-11-11T05:36:24.000Z | 2021-12-25T05:22:09.000Z | src/common/string_util.cpp | maierfelix/bnsh-decoder | e02ccef69780831b38fe5b31710855d9ca6a5977 | [
"MIT"
] | 1 | 2021-01-24T00:22:38.000Z | 2021-01-24T00:22:38.000Z | src/common/string_util.cpp | maierfelix/bnsh-decoder | e02ccef69780831b38fe5b31710855d9ca6a5977 | [
"MIT"
] | 3 | 2021-02-24T12:01:13.000Z | 2021-12-14T01:37:53.000Z | // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <algorithm>
#include <cctype>
#include <codecvt>
#include <cstdlib>
#include <locale>
#include <sstream>
#include "common/common_paths.h"
#include "common/logging/log.h"
#include "common/string_util.h"
#ifdef _WIN32
#include <windows.h>
#endif
namespace Common {
/// Make a string lowercase
std::string ToLower(std::string str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) { return std::tolower(c); });
return str;
}
/// Make a string uppercase
std::string ToUpper(std::string str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) { return std::toupper(c); });
return str;
}
std::string StringFromBuffer(const std::vector<u8>& data) {
return std::string(data.begin(), std::find(data.begin(), data.end(), '\0'));
}
// Turns " hej " into "hej". Also handles tabs.
std::string StripSpaces(const std::string& str) {
const std::size_t s = str.find_first_not_of(" \t\r\n");
if (str.npos != s)
return str.substr(s, str.find_last_not_of(" \t\r\n") - s + 1);
else
return "";
}
// "\"hello\"" is turned to "hello"
// This one assumes that the string has already been space stripped in both
// ends, as done by StripSpaces above, for example.
std::string StripQuotes(const std::string& s) {
if (s.size() && '\"' == s[0] && '\"' == *s.rbegin())
return s.substr(1, s.size() - 2);
else
return s;
}
std::string StringFromBool(bool value) {
return value ? "True" : "False";
}
bool SplitPath(const std::string& full_path, std::string* _pPath, std::string* _pFilename,
std::string* _pExtension) {
if (full_path.empty())
return false;
std::size_t dir_end = full_path.find_last_of("/"
// windows needs the : included for something like just "C:" to be considered a directory
#ifdef _WIN32
"\\:"
#endif
);
if (std::string::npos == dir_end)
dir_end = 0;
else
dir_end += 1;
std::size_t fname_end = full_path.rfind('.');
if (fname_end < dir_end || std::string::npos == fname_end)
fname_end = full_path.size();
if (_pPath)
*_pPath = full_path.substr(0, dir_end);
if (_pFilename)
*_pFilename = full_path.substr(dir_end, fname_end - dir_end);
if (_pExtension)
*_pExtension = full_path.substr(fname_end);
return true;
}
void BuildCompleteFilename(std::string& _CompleteFilename, const std::string& _Path,
const std::string& _Filename) {
_CompleteFilename = _Path;
// check for seperator
if (DIR_SEP_CHR != *_CompleteFilename.rbegin())
_CompleteFilename += DIR_SEP_CHR;
// add the filename
_CompleteFilename += _Filename;
}
void SplitString(const std::string& str, const char delim, std::vector<std::string>& output) {
std::istringstream iss(str);
output.resize(1);
while (std::getline(iss, *output.rbegin(), delim)) {
output.emplace_back();
}
output.pop_back();
}
std::string TabsToSpaces(int tab_size, std::string in) {
std::size_t i = 0;
while ((i = in.find('\t')) != std::string::npos) {
in.replace(i, 1, tab_size, ' ');
}
return in;
}
std::string ReplaceAll(std::string result, const std::string& src, const std::string& dest) {
std::size_t pos = 0;
if (src == dest)
return result;
while ((pos = result.find(src, pos)) != std::string::npos) {
result.replace(pos, src.size(), dest);
pos += dest.length();
}
return result;
}
std::string UTF16ToUTF8(const std::u16string& input) {
#ifdef _MSC_VER
// Workaround for missing char16_t/char32_t instantiations in MSVC2017
std::wstring_convert<std::codecvt_utf8_utf16<__int16>, __int16> convert;
std::basic_string<__int16> tmp_buffer(input.cbegin(), input.cend());
return convert.to_bytes(tmp_buffer);
#else
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
return convert.to_bytes(input);
#endif
}
std::u16string UTF8ToUTF16(const std::string& input) {
#ifdef _MSC_VER
// Workaround for missing char16_t/char32_t instantiations in MSVC2017
std::wstring_convert<std::codecvt_utf8_utf16<__int16>, __int16> convert;
auto tmp_buffer = convert.from_bytes(input);
return std::u16string(tmp_buffer.cbegin(), tmp_buffer.cend());
#else
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
return convert.from_bytes(input);
#endif
}
#ifdef _WIN32
static std::wstring CPToUTF16(u32 code_page, const std::string& input) {
const auto size =
MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()), nullptr, 0);
if (size == 0) {
return L"";
}
std::wstring output(size, L'\0');
if (size != MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()),
&output[0], static_cast<int>(output.size()))) {
output.clear();
}
return output;
}
std::string UTF16ToUTF8(const std::wstring& input) {
const auto size = WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast<int>(input.size()),
nullptr, 0, nullptr, nullptr);
if (size == 0) {
return "";
}
std::string output(size, '\0');
if (size != WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast<int>(input.size()),
&output[0], static_cast<int>(output.size()), nullptr,
nullptr)) {
output.clear();
}
return output;
}
std::wstring UTF8ToUTF16W(const std::string& input) {
return CPToUTF16(CP_UTF8, input);
}
#endif
std::string StringFromFixedZeroTerminatedBuffer(const char* buffer, std::size_t max_len) {
std::size_t len = 0;
while (len < max_len && buffer[len] != '\0')
++len;
return std::string(buffer, len);
}
std::u16string UTF16StringFromFixedZeroTerminatedBuffer(std::u16string_view buffer,
std::size_t max_len) {
std::size_t len = 0;
while (len < max_len && buffer[len] != '\0')
++len;
return std::u16string(buffer.begin(), buffer.begin() + len);
}
} // namespace Common
| 28.709251 | 100 | 0.620071 | [
"vector",
"transform"
] |
848cfcabf29d0821f33fe9c28aaec396a7d856a1 | 662 | cpp | C++ | CodeForces/702/ProbB.cpp | shiva92/Contests | 720bb3699f774a6ea1f99e888e0cd784e63130c8 | [
"Apache-2.0"
] | null | null | null | CodeForces/702/ProbB.cpp | shiva92/Contests | 720bb3699f774a6ea1f99e888e0cd784e63130c8 | [
"Apache-2.0"
] | null | null | null | CodeForces/702/ProbB.cpp | shiva92/Contests | 720bb3699f774a6ea1f99e888e0cd784e63130c8 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
const int mod = 1e9 + 7;
const long long INF = 1e10;
using namespace std;
map<long long, int> mp;
vector<long long> powers;
void init() {
for (long long i = 2; (i << 1) < INF; i <<= 1) {
powers.push_back(i);
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("/Users/seeva92/Workspace/Contests/1.txt", "r", stdin);
freopen("/Users/seeva92/Workspace/Contests/2.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(0);
init();
int n, x; cin >> n;
long long total = 0;
for (int i = 0; i < n; i++) {
cin >> x;
for (auto j : powers) {
if (x < j)
total += mp[j - x];
}
mp[x]++;
}
cout << total << '\n';
}
| 18.914286 | 65 | 0.57855 | [
"vector"
] |
8492d04de45dc3012c477cfe2d9871ef685e575a | 6,924 | cc | C++ | common/find_runfiles.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | 2 | 2021-02-25T02:01:02.000Z | 2021-03-17T04:52:04.000Z | common/find_runfiles.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | null | null | null | common/find_runfiles.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | 1 | 2021-06-13T12:05:39.000Z | 2021-06-13T12:05:39.000Z | #include "drake/common/find_runfiles.h"
#include <cstdlib>
#include <memory>
#include <stdexcept>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include "fmt/format.h"
#include "tools/cpp/runfiles/runfiles.h"
#include "drake/common/drake_assert.h"
#include "drake/common/filesystem.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
using bazel::tools::cpp::runfiles::Runfiles;
namespace drake {
namespace {
// Replace `nullptr` with `"nullptr",` or else just return `arg` unchanged.
const char* nullable_to_string(const char* arg) {
return arg ? arg : "nullptr";
}
// Either a bazel_tools Runfiles object xor an error string.
struct RunfilesSingleton {
std::unique_ptr<Runfiles> runfiles;
std::string runfiles_dir;
std::string error;
};
// Create a bazel_tools Runfiles object xor an error string. This is memoized
// by GetSingletonRunfiles (i.e., this is only called once per process).
RunfilesSingleton Create() {
const char* mechanism{};
RunfilesSingleton result;
std::string bazel_error;
// Chose a mechanism based on environment variables.
if (std::getenv("TEST_SRCDIR")) {
// When running under bazel test, use the test heuristics.
mechanism = "TEST_SRCDIR";
result.runfiles.reset(Runfiles::CreateForTest(&bazel_error));
} else if ((std::getenv("RUNFILES_MANIFEST_FILE") != nullptr) ||
(std::getenv("RUNFILES_DIR") != nullptr)) {
// When running with some RUNFILES_* env already set, just use that.
mechanism = "RUNFILES_{MANIFEST_FILE,DIR}";
result.runfiles.reset(Runfiles::Create({}, &bazel_error));
} else {
// When running from the user's command line, use argv0.
mechanism = "argv0";
#ifdef __APPLE__
std::string argv0;
argv0.resize(4096);
uint32_t buf_size = argv0.size();
int error = _NSGetExecutablePath(&argv0.front(), &buf_size);
if (error) {
throw std::runtime_error("Error from _NSGetExecutablePath");
}
argv0 = argv0.c_str(); // Remove trailing nil bytes.
drake::log()->debug("_NSGetExecutablePath = {}", argv0);
#else
const std::string& argv0 = filesystem::read_symlink({
"/proc/self/exe"}).string();
drake::log()->debug("readlink(/proc/self/exe) = {}", argv0);
#endif
result.runfiles.reset(Runfiles::Create(argv0, &bazel_error));
}
drake::log()->debug("FindRunfile mechanism = {}", mechanism);
// If there were runfiles, identify the RUNFILES_DIR.
if (result.runfiles) {
for (const auto& key_value : result.runfiles->EnvVars()) {
if (key_value.first == "RUNFILES_DIR") {
// N.B. We must normalize the path; otherwise the path may include
// `parent/./path` if the binary was run using `./bazel-bin/target` vs
// `bazel-bin/target`.
// TODO(eric.cousineau): Show this in Drake itself. This behavior was
// encountered in Anzu issue 5653, in a Python binary.
result.runfiles_dir =
filesystem::path(key_value.second).lexically_normal().string();
break;
}
}
// If we didn't find it, something was very wrong.
if (result.runfiles_dir.empty()) {
bazel_error = "RUNFILES_DIR was not provided by the Runfiles object";
result.runfiles.reset();
} else if (!filesystem::is_directory({result.runfiles_dir})) {
bazel_error = fmt::format(
"RUNFILES_DIR '{}' does not exist", result.runfiles_dir);
result.runfiles.reset();
}
}
// Report any error.
if (!result.runfiles) {
result.runfiles_dir.clear();
result.error = fmt::format(
"{} (created using {} with TEST_SRCDIR={} and "
"RUNFILES_MANIFEST_FILE={} and RUNFILES_DIR={})",
bazel_error, mechanism,
nullable_to_string(std::getenv("TEST_SRCDIR")),
nullable_to_string(std::getenv("RUNFILES_MANIFEST_FILE")),
nullable_to_string(std::getenv("RUNFILES_DIR")));
drake::log()->debug("FindRunfile error: {}", result.error);
}
// Sanity check our return value.
if (result.runfiles.get() == nullptr) {
DRAKE_DEMAND(result.runfiles_dir.empty());
DRAKE_DEMAND(result.error.length() > 0);
} else {
DRAKE_DEMAND(result.runfiles_dir.length() > 0);
DRAKE_DEMAND(result.error.empty());
}
return result;
}
// Returns the RunfilesSingleton for the current process, latch-initializing it
// first if necessary.
const RunfilesSingleton& GetRunfilesSingleton() {
static const never_destroyed<RunfilesSingleton> result{Create()};
return result.access();
}
} // namespace
bool HasRunfiles() {
return GetRunfilesSingleton().runfiles.get() != nullptr;
}
RlocationOrError FindRunfile(const std::string& resource_path) {
const auto& singleton = GetRunfilesSingleton();
// Check for HasRunfiles.
RlocationOrError result;
if (!singleton.runfiles) {
DRAKE_DEMAND(!singleton.error.empty());
result.error = singleton.error;
return result;
}
// Check the user input.
if (resource_path.empty()) {
result.error = "Resource path must not be empty";
return result;
}
if (resource_path[0] == '/') {
result.error = fmt::format(
"Resource path '{}' must not be an absolute path", resource_path);
return result;
}
// Locate the file on the manifest and in the directory.
const std::string by_man = singleton.runfiles->Rlocation(resource_path);
const std::string by_dir = singleton.runfiles_dir + "/" + resource_path;
const bool by_man_ok = filesystem::is_regular_file({by_man});
const bool by_dir_ok = filesystem::is_regular_file({by_dir});
drake::log()->debug(
"FindRunfile found by-manifest '{}' ({}) and by-directory '{}' ({})",
by_man, by_man_ok ? "good" : "bad", by_dir, by_dir_ok ? "good" : "bad");
if (by_man_ok && by_dir_ok) {
// We must always return the directory-based result (not the manifest
// result) because the result itself may be a file that contains embedded
// relative pathnames. The manifest result might actually be in the source
// tree, not the runfiles directory, and in that case relative paths may
// not work (e.g., when the relative path refers to a genfile).
result.abspath = by_dir;
return result;
}
// Report an error.
const char* detail{};
if (!by_man_ok && !by_dir_ok) {
detail =
"but the file does not exist at that location "
"nor is it on the manifest";
} else if (!by_man_ok && by_dir_ok) {
detail =
"and the file exists at that location "
"but it is not on the manifest";
} else {
DRAKE_DEMAND(by_man_ok && !by_dir_ok);
detail =
"and it is on the manifest"
"but the file does not exist at that location";
}
result.error = fmt::format(
"Sought '{}' in runfiles directory '{}' {}; "
"perhaps a 'data = []' dependency is missing.",
resource_path, singleton.runfiles_dir, detail);
return result;
}
} // namespace drake
| 34.108374 | 79 | 0.669844 | [
"object"
] |
849b5720c5c7f7a6280b47a06cebe1e2e721552d | 928 | cpp | C++ | examples/example_1.cpp | ffwilliam1992/stdtensor | 8f15797fc571a5b7288af8c4153e4eafd9b37120 | [
"MIT"
] | null | null | null | examples/example_1.cpp | ffwilliam1992/stdtensor | 8f15797fc571a5b7288af8c4153e4eafd9b37120 | [
"MIT"
] | null | null | null | examples/example_1.cpp | ffwilliam1992/stdtensor | 8f15797fc571a5b7288af8c4153e4eafd9b37120 | [
"MIT"
] | null | null | null | #include <stdtensor>
using namespace ttl;
void example_1()
{
const int h = 3;
const int w = 4;
const int c = 5;
const int n = h * w * c;
tensor<int, 3> t(h, w, c);
{
int idx = 0;
for (const auto &t1 : t) {
for (const auto &t2 : t1) {
for (const auto &t3 : t2) {
t3 = idx++; //
}
}
}
}
{
tensor_ref<int, 3> r(t.data(), t.shape());
printf("%d\n", r.shape().offset(2, 3, 4));
scalar(r[2][3][4]) = 0;
}
{
tensor_view<int, 3> v(t.data(), t.shape());
int tot = 0;
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
for (int k = 0; k < c; ++k) { tot += scalar(v[i][j][k]); }
}
}
printf("%d, %d\n", n * (n + 1) / 2, tot);
}
}
int main()
{
example_1();
return 0;
}
| 19.744681 | 74 | 0.366379 | [
"shape"
] |
849f4e1f8f10d376bb055b9b4ef92406da47d26c | 5,459 | cpp | C++ | core/fpdfapi/page/cpdf_shadingpattern.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 16 | 2018-09-14T12:07:14.000Z | 2021-04-22T11:18:25.000Z | core/fpdfapi/page/cpdf_shadingpattern.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 1 | 2020-12-26T16:18:40.000Z | 2020-12-26T16:18:40.000Z | core/fpdfapi/page/cpdf_shadingpattern.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 6 | 2017-09-12T14:09:32.000Z | 2021-11-20T03:32:27.000Z | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fpdfapi/page/cpdf_shadingpattern.h"
#include <algorithm>
#include "core/fpdfapi/page/cpdf_docpagedata.h"
#include "core/fpdfapi/page/cpdf_function.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
#include "core/fpdfapi/parser/cpdf_object.h"
#include "core/fpdfapi/parser/cpdf_stream.h"
#include "core/fxcrt/fx_safe_types.h"
#include "third_party/base/check.h"
#include "third_party/base/notreached.h"
namespace {
ShadingType ToShadingType(int type) {
return (type > kInvalidShading && type < kMaxShading)
? static_cast<ShadingType>(type)
: kInvalidShading;
}
} // namespace
CPDF_ShadingPattern::CPDF_ShadingPattern(CPDF_Document* pDoc,
CPDF_Object* pPatternObj,
bool bShading,
const CFX_Matrix& parentMatrix)
: CPDF_Pattern(pDoc, pPatternObj, parentMatrix), m_bShading(bShading) {
DCHECK(document());
if (!bShading)
SetPatternToFormMatrix();
}
CPDF_ShadingPattern::~CPDF_ShadingPattern() = default;
CPDF_ShadingPattern* CPDF_ShadingPattern::AsShadingPattern() {
return this;
}
bool CPDF_ShadingPattern::Load() {
if (m_ShadingType != kInvalidShading)
return true;
const CPDF_Object* pShadingObj = GetShadingObject();
const CPDF_Dictionary* pShadingDict =
pShadingObj ? pShadingObj->GetDict() : nullptr;
if (!pShadingDict)
return false;
m_pFunctions.clear();
const CPDF_Object* pFunc = pShadingDict->GetDirectObjectFor("Function");
if (pFunc) {
if (const CPDF_Array* pArray = pFunc->AsArray()) {
m_pFunctions.resize(std::min<size_t>(pArray->size(), 4));
for (size_t i = 0; i < m_pFunctions.size(); ++i)
m_pFunctions[i] = CPDF_Function::Load(pArray->GetDirectObjectAt(i));
} else {
m_pFunctions.push_back(CPDF_Function::Load(pFunc));
}
}
const CPDF_Object* pCSObj = pShadingDict->GetDirectObjectFor("ColorSpace");
if (!pCSObj)
return false;
auto* pDocPageData = CPDF_DocPageData::FromDocument(document());
m_pCS = pDocPageData->GetColorSpace(pCSObj, nullptr);
// The color space is required and cannot be a Pattern space, according to the
// PDF 1.7 spec, page 305.
if (!m_pCS || m_pCS->GetFamily() == CPDF_ColorSpace::Family::kPattern)
return false;
m_ShadingType = ToShadingType(pShadingDict->GetIntegerFor("ShadingType"));
return Validate();
}
const CPDF_Object* CPDF_ShadingPattern::GetShadingObject() const {
return m_bShading ? pattern_obj()
: pattern_obj()->GetDict()->GetDirectObjectFor("Shading");
}
bool CPDF_ShadingPattern::Validate() const {
if (m_ShadingType == kInvalidShading)
return false;
// We expect to have a stream if our shading type is a mesh.
if (IsMeshShading() && !ToStream(GetShadingObject()))
return false;
// Validate color space
switch (m_ShadingType) {
case kFunctionBasedShading:
case kAxialShading:
case kRadialShading: {
if (m_pCS->GetFamily() == CPDF_ColorSpace::Family::kIndexed)
return false;
break;
}
case kFreeFormGouraudTriangleMeshShading:
case kLatticeFormGouraudTriangleMeshShading:
case kCoonsPatchMeshShading:
case kTensorProductPatchMeshShading: {
if (!m_pFunctions.empty() &&
m_pCS->GetFamily() == CPDF_ColorSpace::Family::kIndexed) {
return false;
}
break;
}
default: {
NOTREACHED();
return false;
}
}
uint32_t nNumColorSpaceComponents = m_pCS->CountComponents();
switch (m_ShadingType) {
case kFunctionBasedShading: {
// Either one 2-to-N function or N 2-to-1 functions.
return ValidateFunctions(1, 2, nNumColorSpaceComponents) ||
ValidateFunctions(nNumColorSpaceComponents, 2, 1);
}
case kAxialShading:
case kRadialShading: {
// Either one 1-to-N function or N 1-to-1 functions.
return ValidateFunctions(1, 1, nNumColorSpaceComponents) ||
ValidateFunctions(nNumColorSpaceComponents, 1, 1);
}
case kFreeFormGouraudTriangleMeshShading:
case kLatticeFormGouraudTriangleMeshShading:
case kCoonsPatchMeshShading:
case kTensorProductPatchMeshShading: {
// Either no function, one 1-to-N function, or N 1-to-1 functions.
return m_pFunctions.empty() ||
ValidateFunctions(1, 1, nNumColorSpaceComponents) ||
ValidateFunctions(nNumColorSpaceComponents, 1, 1);
}
default:
break;
}
NOTREACHED();
return false;
}
bool CPDF_ShadingPattern::ValidateFunctions(
uint32_t nExpectedNumFunctions,
uint32_t nExpectedNumInputs,
uint32_t nExpectedNumOutputs) const {
if (m_pFunctions.size() != nExpectedNumFunctions)
return false;
FX_SAFE_UINT32 nTotalOutputs = 0;
for (const auto& function : m_pFunctions) {
if (!function)
return false;
if (function->CountInputs() != nExpectedNumInputs ||
function->CountOutputs() != nExpectedNumOutputs) {
return false;
}
nTotalOutputs += function->CountOutputs();
}
return nTotalOutputs.IsValid();
}
| 31.373563 | 80 | 0.688771 | [
"mesh"
] |
84a2d3ebfbb9ea28a3df863599229d715fc6b7a0 | 14,982 | hpp | C++ | include/util/string.hpp | shift-left-test/stringutils | 1d4b022d4d910247b364a6699dd8f3d82cb9420b | [
"MIT"
] | null | null | null | include/util/string.hpp | shift-left-test/stringutils | 1d4b022d4d910247b364a6699dd8f3d82cb9420b | [
"MIT"
] | null | null | null | include/util/string.hpp | shift-left-test/stringutils | 1d4b022d4d910247b364a6699dd8f3d82cb9420b | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2019 LG Electronics, Inc.
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.
*/
#ifndef INCLUDE_UTIL_STRING_HPP_
#define INCLUDE_UTIL_STRING_HPP_
#include <cctype>
#include <cstddef>
#include <cwchar>
#include <algorithm>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
namespace util {
namespace string {
template <typename T>
inline bool startsWith(const std::basic_string<T> &haystack,
const std::basic_string<T> &needle) {
return (haystack.size() >= needle.size()) &&
std::equal(needle.begin(), needle.end(), haystack.begin());
}
template <typename T>
inline bool startsWith(const T *haystack, const std::basic_string<T> &needle) {
return startsWith(std::basic_string<T>(haystack), needle);
}
template <typename T>
inline bool startsWith(const std::basic_string<T> &haystack, const T *needle) {
return startsWith(haystack, std::basic_string<T>(needle));
}
template <typename T>
inline bool startsWith(const T *haystack, const T *needle) {
return startsWith(std::basic_string<T>(haystack),
std::basic_string<T>(needle));
}
template <typename T>
inline bool endsWith(const std::basic_string<T> &haystack,
const std::basic_string<T> &needle) {
return (haystack.size() >= needle.size()) &&
std::equal(needle.rbegin(), needle.rend(), haystack.rbegin());
}
template <typename T>
inline bool endsWith(const T *haystack, const std::basic_string<T> &needle) {
return endsWith(std::basic_string<T>(haystack), needle);
}
template <typename T>
inline bool endsWith(const std::basic_string<T> &haystack, const T *needle) {
return endsWith(haystack, std::basic_string<T>(needle));
}
template <typename T>
inline bool endsWith(const T *haystack, const T *needle) {
return endsWith(std::basic_string<T>(haystack),
std::basic_string<T>(needle));
}
template <typename T, class UnaryPredicate>
inline std::basic_string<T> transform(std::basic_string<T> s,
UnaryPredicate pred) {
std::transform(s.begin(), s.end(), s.begin(), pred);
return s;
}
template <typename T, class UnaryPredicate>
inline std::basic_string<T> transform(const T *s,
UnaryPredicate pred) {
return transform(std::basic_string<T>(s), pred);
}
template <typename T>
inline std::basic_string<T> uppercase(const std::basic_string<T> &s) {
return transform(s, ::toupper);
}
template <typename T>
inline std::basic_string<T> uppercase(const T *s) {
return uppercase(std::basic_string<T>(s));
}
template <typename T>
inline std::basic_string<T> lowercase(const std::basic_string<T> &s) {
return transform(s, ::tolower);
}
template <typename T>
inline std::basic_string<T> lowercase(const T *s) {
return lowercase(std::basic_string<T>(s));
}
template <typename T, typename UnaryPredicate>
inline std::basic_string<T> ltrim(const std::basic_string<T> &s,
UnaryPredicate pred) {
auto first = std::find_if_not(s.begin(), s.end(), pred);
auto last = s.end();
return std::basic_string<T>(first, last);
}
inline std::string ltrim(const std::string& s) {
return ltrim(s, [](unsigned char c) { return std::isspace(c); });
}
inline std::wstring ltrim(const std::wstring& s) {
return ltrim(s, [](wchar_t c) { return std::iswspace(c); });
}
inline std::string ltrim(const std::string& s, const char ch) {
return ltrim(s, [&](unsigned char c) { return ch == c; });
}
inline std::wstring ltrim(const std::wstring& s, const wchar_t ch) {
return ltrim(s, [&](wchar_t c) { return ch == c; });
}
template <typename T, typename UnaryPredicate>
inline std::basic_string<T> rtrim(const std::basic_string<T> &s,
UnaryPredicate pred) {
auto first = s.begin();
auto last = std::find_if_not(s.rbegin(), s.rend(), pred).base();
return std::basic_string<T>(first, last);
}
inline std::string rtrim(const std::string& s) {
return rtrim(s, [](unsigned char c) { return std::isspace(c); });
}
inline std::wstring rtrim(const std::wstring& s) {
return rtrim(s, [](wchar_t c) { return std::iswspace(c); });
}
inline std::string rtrim(const std::string& s, const char ch) {
return rtrim(s, [&](unsigned char c) { return ch == c; });
}
inline std::wstring rtrim(const std::wstring& s, const wchar_t ch) {
return rtrim(s, [&](wchar_t c) { return ch == c; });
}
template <typename T, typename UnaryPredicate>
inline std::basic_string<T> trim(const std::basic_string<T> &s,
UnaryPredicate pred) {
return ltrim(rtrim(s, pred), pred);
}
inline std::string trim(const std::string& s) {
return trim(s, [](unsigned char c) { return std::isspace(c); });
}
inline std::wstring trim(const std::wstring& s) {
return trim(s, [](wchar_t c) { return std::isspace(c); });
}
inline std::string trim(const std::string& s, const char ch) {
return trim(s, [&](unsigned char c) { return ch == c; });
}
inline std::wstring trim(const std::wstring& s, const wchar_t ch) {
return trim(s, [&](wchar_t c) { return ch == c; });
}
template <typename T>
inline bool contains(const std::basic_string<T> &haystack,
const std::basic_string<T> &needle) {
return haystack.find(needle) != std::string::npos;
}
template <typename T>
inline bool contains(const T *haystack, const std::basic_string<T> &needle) {
return contains(std::basic_string<T>(haystack), needle);
}
template <typename T>
inline bool contains(const std::basic_string<T> &haystack, const T *needle) {
return contains(haystack, std::basic_string<T>(needle));
}
template <typename T>
inline bool contains(const T *haystack, const T *needle) {
return contains(std::basic_string<T>(haystack), std::basic_string<T>(needle));
}
template <typename T>
inline std::basic_string<T> replace(std::basic_string<T> s,
const T from, const T to) {
std::replace(s.begin(), s.end(), from, to);
return s;
}
template <typename T>
inline std::basic_string<T> replace(const T *s, const T from, const T to) {
return replace(std::basic_string<T>(s), from, to);
}
template <typename T>
inline std::basic_string<T> replace(std::basic_string<T> s,
const std::basic_string<T> &from,
const std::basic_string<T> &to) {
if (from.empty()) {
return s;
}
std::size_t position = 0;
while ((position = s.find(from, position)) != std::string::npos) {
s.replace(position, from.length(), to);
position += to.length();
}
return s;
}
template <typename T>
inline std::basic_string<T> replace(const T *s,
const std::basic_string<T> &from,
const std::basic_string<T> &to) {
return replace(std::basic_string<T>(s), from, to);
}
template <typename T>
inline std::basic_string<T> replace(std::basic_string<T> s,
const T *from,
const std::basic_string<T> &to) {
return replace(s, std::basic_string<T>(from), to);
}
template <typename T>
inline std::basic_string<T> replace(std::basic_string<T> s,
const std::basic_string<T> &from,
const T *to) {
return replace(s, from, std::basic_string<T>(to));
}
template <typename T>
inline std::basic_string<T> replace(const T *s,
const T *from,
const std::basic_string<T> &to) {
return replace(std::basic_string<T>(s), std::basic_string<T>(from), to);
}
template <typename T>
inline std::basic_string<T> replace(const T *s,
const std::basic_string<T> &from,
const T *to) {
return replace(std::basic_string<T>(s), from, std::basic_string<T>(to));
}
template <typename T>
inline std::basic_string<T> replace(std::basic_string<T> s,
const T *from,
const T *to) {
return replace(s, std::basic_string<T>(from), std::basic_string<T>(to));
}
template <typename T>
inline std::basic_string<T> replace(const T *s,
const T *from,
const T *to) {
return replace(std::basic_string<T>(s),
std::basic_string<T>(from),
std::basic_string<T>(to));
}
template <typename T>
inline std::basic_string<T> reverse(const std::basic_string<T>& s) {
return std::basic_string<T>(s.rbegin(), s.rend());
}
template <typename T>
inline std::basic_string<T> reverse(const T* s) {
return reverse(std::basic_string<T>(s));
}
template <typename T>
inline std::basic_string<T> translate(std::basic_string<T> s,
const std::basic_string<T>& from,
const std::basic_string<T>& to) {
auto func = [&](const T ch) {
auto length = std::min(from.size(), to.size());
for (auto i = 0; i < length; i++) {
if (ch == from[i]) {
return to[i];
}
} return ch;
};
std::transform(s.begin(), s.end(), s.begin(), func);
return s;
}
template <typename T>
inline std::basic_string<T> translate(const std::basic_string<T>& s,
const std::basic_string<T>& from,
const T* to) {
return translate(s, from, std::basic_string<T>(to));
}
template <typename T>
inline std::basic_string<T> translate(const std::basic_string<T>& s,
const T* from,
const std::basic_string<T>& to) {
return translate(s, std::basic_string<T>(from), to);
}
template <typename T>
inline std::basic_string<T> translate(const T* s,
const std::basic_string<T>& from,
const std::basic_string<T>& to) {
return translate(std::basic_string<T>(s), from, to);
}
template <typename T>
inline std::basic_string<T> translate(const std::basic_string<T>& s,
const T* from,
const T* to) {
return translate(s, std::basic_string<T>(from), std::basic_string<T>(to));
}
template <typename T>
inline std::basic_string<T> translate(const T* s,
const std::basic_string<T>& from,
const T* to) {
return translate(std::basic_string<T>(s), from, std::basic_string<T>(to));
}
template <typename T>
inline std::basic_string<T> translate(const T* s,
const T* from,
const std::basic_string<T>& to) {
return translate(std::basic_string<T>(s), std::basic_string<T>(from), to);
}
template <typename T>
inline std::basic_string<T> translate(const T* s,
const T* from,
const T* to) {
return translate(std::basic_string<T>(s),
std::basic_string<T>(from),
std::basic_string<T>(to));
}
namespace internal {
template <typename T>
inline T to_const(const T& data) {
return data;
}
template <typename T>
inline const T* to_const(const T* data) {
return data;
}
template <typename T>
inline const T * to_const(const std::basic_string<T> &data) {
return data.c_str();
}
} // namespace internal
template <typename ... Args>
inline std::basic_string<char> format(const char *fmt, const Args& ... args) {
std::size_t size = std::snprintf(nullptr, 0, fmt,
internal::to_const(args) ...) + 1;
std::unique_ptr<char[]> buf(new char[size]);
std::snprintf(buf.get(), size, fmt, internal::to_const(args) ...);
return std::basic_string<char>(buf.get(), size - 1);
}
template <typename ... Args>
inline std::basic_string<char> format(const std::basic_string<char> &fmt,
const Args& ... args) {
return format(fmt.c_str(), args ...);
}
template <typename ... Args>
inline std::basic_string<wchar_t> format(const wchar_t *fmt,
const Args& ... args) {
// Used a fixed size buffer, since unable to predict the required size
wchar_t buf[65535] = {};
std::swprintf(buf, sizeof(buf), fmt, internal::to_const(args) ...);
return std::basic_string<wchar_t>(buf);
}
template <typename ... Args>
inline std::basic_string<wchar_t> format(const std::basic_string<wchar_t> &fmt,
const Args& ... args) {
return format(fmt.c_str(), args ...);
}
template <typename T>
inline std::vector<std::basic_string<T>> split(const std::basic_string<T> &s,
const T delim = ' ') {
std::vector<std::basic_string<T>> tokens;
std::basic_istringstream<T> ss;
ss.str(s);
std::basic_string<T> token;
while (std::getline(ss, token, delim)) {
tokens.emplace_back(token);
}
return tokens;
}
template <typename T>
inline std::vector<std::basic_string<T>> split(const T *s,
const T delim = ' ') {
return split(std::basic_string<T>(s), delim);
}
template <typename T>
inline std::basic_string<T>
join(const std::vector<std::basic_string<T>> &tokens,
const std::basic_string<T> &delim) {
std::basic_string<T> s;
for (auto it = tokens.begin(); it != tokens.end(); it++) {
s.append(*it);
if (it != std::prev(tokens.end())) {
s.append(delim);
}
}
return s;
}
template <typename T>
inline std::basic_string<T>
join(const std::vector<std::basic_string<T>> &tokens, const T *delim) {
return join(tokens, std::basic_string<T>(delim));
}
} // namespace string
} // namespace util
#endif // INCLUDE_UTIL_STRING_HPP_
| 32.640523 | 80 | 0.611133 | [
"vector",
"transform"
] |
84a39d6a87bfbe92f06f2477e5a9d1edcc7c105a | 18,648 | hpp | C++ | src/mpt/io_read/filereader.hpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 335 | 2017-02-25T16:39:27.000Z | 2022-03-29T17:45:42.000Z | src/mpt/io_read/filereader.hpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 7 | 2018-02-05T18:22:38.000Z | 2022-02-15T19:35:24.000Z | src/mpt/io_read/filereader.hpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 69 | 2017-04-10T00:48:09.000Z | 2022-03-20T10:24:45.000Z | /* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */
#ifndef MPT_IO_READ_FILEREADER_HPP
#define MPT_IO_READ_FILEREADER_HPP
#include "mpt/base/alloc.hpp"
#include "mpt/base/bit.hpp"
#include "mpt/base/integer.hpp"
#include "mpt/base/memory.hpp"
#include "mpt/base/namespace.hpp"
#include "mpt/base/span.hpp"
#include "mpt/base/utility.hpp"
#include "mpt/io/base.hpp"
#include "mpt/endian/floatingpoint.hpp"
#include "mpt/endian/integer.hpp"
#include "mpt/string/utility.hpp"
#include <algorithm>
#include <array>
#include <limits>
#include <string>
#include <vector>
#include <cassert>
#include <cstddef>
#include <cstring>
namespace mpt {
inline namespace MPT_INLINE_NS {
namespace IO {
namespace FileReader {
// Read a "T" object from the stream.
// If not enough bytes can be read, false is returned.
// If successful, the file cursor is advanced by the size of "T".
template <typename T, typename TFileCursor>
bool Read(TFileCursor & f, T & target) {
// cppcheck false-positive
// cppcheck-suppress uninitvar
mpt::byte_span dst = mpt::as_raw_memory(target);
if (dst.size() != f.GetRaw(dst).size()) {
return false;
}
f.Skip(dst.size());
return true;
}
// Read an array of binary-safe T values.
// If successful, the file cursor is advanced by the size of the array.
// Otherwise, the target is zeroed.
template <typename T, std::size_t destSize, typename TFileCursor>
bool ReadArray(TFileCursor & f, T (&destArray)[destSize]) {
static_assert(mpt::is_binary_safe<T>::value);
if (!f.CanRead(sizeof(destArray))) {
mpt::reset(destArray);
return false;
}
f.ReadRaw(mpt::as_raw_memory(destArray));
return true;
}
// Read an array of binary-safe T values.
// If successful, the file cursor is advanced by the size of the array.
// Otherwise, the target is zeroed.
template <typename T, std::size_t destSize, typename TFileCursor>
bool ReadArray(TFileCursor & f, std::array<T, destSize> & destArray) {
static_assert(mpt::is_binary_safe<T>::value);
if (!f.CanRead(sizeof(destArray))) {
destArray.fill(T{});
return false;
}
f.ReadRaw(mpt::as_raw_memory(destArray));
return true;
}
// Read destSize elements of binary-safe type T into a vector.
// If successful, the file cursor is advanced by the size of the vector.
// Otherwise, the vector is resized to destSize, but possibly existing contents are not cleared.
template <typename T, typename TFileCursor>
bool ReadVector(TFileCursor & f, std::vector<T> & destVector, size_t destSize) {
static_assert(mpt::is_binary_safe<T>::value);
destVector.resize(destSize);
if (!f.CanRead(sizeof(T) * destSize)) {
return false;
}
f.ReadRaw(mpt::as_raw_memory(destVector));
return true;
}
template <typename T, std::size_t destSize, typename TFileCursor>
std::array<T, destSize> ReadArray(TFileCursor & f) {
std::array<T, destSize> destArray;
ReadArray(f, destArray);
return destArray;
}
// Read some kind of integer in little-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename T, typename TFileCursor>
T ReadIntLE(TFileCursor & f) {
static_assert(std::numeric_limits<T>::is_integer == true, "Target type is a not an integer");
typename mpt::make_le<T>::type target;
if (!FileReader::Read(f, target)) {
return 0;
}
return target;
}
// Read some kind of integer in big-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename T, typename TFileCursor>
T ReadIntBE(TFileCursor & f) {
static_assert(std::numeric_limits<T>::is_integer == true, "Target type is a not an integer");
typename mpt::make_be<T>::type target;
if (!FileReader::Read(f, target)) {
return 0;
}
return target;
}
// Read a integer in little-endian format which has some of its higher bytes not stored in file.
// If successful, the file cursor is advanced by the given size.
template <typename T, typename TFileCursor>
T ReadTruncatedIntLE(TFileCursor & f, typename TFileCursor::pos_type size) {
static_assert(std::numeric_limits<T>::is_integer == true, "Target type is a not an integer");
assert(sizeof(T) >= size);
if (size == 0) {
return 0;
}
if (!f.CanRead(size)) {
return 0;
}
uint8 buf[sizeof(T)];
bool negative = false;
for (std::size_t i = 0; i < sizeof(T); ++i) {
uint8 byte = 0;
if (i < size) {
FileReader::Read(f, byte);
negative = std::numeric_limits<T>::is_signed && ((byte & 0x80) != 0x00);
} else {
// sign or zero extend
byte = negative ? 0xff : 0x00;
}
buf[i] = byte;
}
return mpt::bit_cast<typename mpt::make_le<T>::type>(buf);
}
// Read a supplied-size little endian integer to a fixed size variable.
// The data is properly sign-extended when fewer bytes are stored.
// If more bytes are stored, higher order bytes are silently ignored.
// If successful, the file cursor is advanced by the given size.
template <typename T, typename TFileCursor>
T ReadSizedIntLE(TFileCursor & f, typename TFileCursor::pos_type size) {
static_assert(std::numeric_limits<T>::is_integer == true, "Target type is a not an integer");
if (size == 0) {
return 0;
}
if (!f.CanRead(size)) {
return 0;
}
if (size < sizeof(T)) {
return FileReader::ReadTruncatedIntLE<T>(f, size);
}
T retval = FileReader::ReadIntLE<T>(f);
f.Skip(size - sizeof(T));
return retval;
}
// Read unsigned 32-Bit integer in little-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
uint32 ReadUint32LE(TFileCursor & f) {
return FileReader::ReadIntLE<uint32>(f);
}
// Read unsigned 32-Bit integer in big-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
uint32 ReadUint32BE(TFileCursor & f) {
return FileReader::ReadIntBE<uint32>(f);
}
// Read signed 32-Bit integer in little-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
int32 ReadInt32LE(TFileCursor & f) {
return FileReader::ReadIntLE<int32>(f);
}
// Read signed 32-Bit integer in big-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
int32 ReadInt32BE(TFileCursor & f) {
return FileReader::ReadIntBE<int32>(f);
}
// Read unsigned 24-Bit integer in little-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
uint32 ReadUint24LE(TFileCursor & f) {
const auto arr = FileReader::ReadArray<uint8, 3>(f);
return arr[0] | (arr[1] << 8) | (arr[2] << 16);
}
// Read unsigned 24-Bit integer in big-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
uint32 ReadUint24BE(TFileCursor & f) {
const auto arr = FileReader::ReadArray<uint8, 3>(f);
return (arr[0] << 16) | (arr[1] << 8) | arr[2];
}
// Read unsigned 16-Bit integer in little-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
uint16 ReadUint16LE(TFileCursor & f) {
return FileReader::ReadIntLE<uint16>(f);
}
// Read unsigned 16-Bit integer in big-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
uint16 ReadUint16BE(TFileCursor & f) {
return FileReader::ReadIntBE<uint16>(f);
}
// Read signed 16-Bit integer in little-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
int16 ReadInt16LE(TFileCursor & f) {
return FileReader::ReadIntLE<int16>(f);
}
// Read signed 16-Bit integer in big-endian format.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
int16 ReadInt16BE(TFileCursor & f) {
return FileReader::ReadIntBE<int16>(f);
}
// Read a single 8bit character.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
char ReadChar(TFileCursor & f) {
char target;
if (!FileReader::Read(f, target)) {
return 0;
}
return target;
}
// Read unsigned 8-Bit integer.
// If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
uint8 ReadUint8(TFileCursor & f) {
uint8 target;
if (!FileReader::Read(f, target)) {
return 0;
}
return target;
}
// Read signed 8-Bit integer. If successful, the file cursor is advanced by the size of the integer.
template <typename TFileCursor>
int8 ReadInt8(TFileCursor & f) {
int8 target;
if (!FileReader::Read(f, target)) {
return 0;
}
return target;
}
// Read 32-Bit float in little-endian format.
// If successful, the file cursor is advanced by the size of the float.
template <typename TFileCursor>
float ReadFloatLE(TFileCursor & f) {
IEEE754binary32LE target;
if (!FileReader::Read(f, target)) {
return 0.0f;
}
return target;
}
// Read 32-Bit float in big-endian format.
// If successful, the file cursor is advanced by the size of the float.
template <typename TFileCursor>
float ReadFloatBE(TFileCursor & f) {
IEEE754binary32BE target;
if (!FileReader::Read(f, target)) {
return 0.0f;
}
return target;
}
// Read 64-Bit float in little-endian format.
// If successful, the file cursor is advanced by the size of the float.
template <typename TFileCursor>
double ReadDoubleLE(TFileCursor & f) {
IEEE754binary64LE target;
if (!FileReader::Read(f, target)) {
return 0.0;
}
return target;
}
// Read 64-Bit float in big-endian format.
// If successful, the file cursor is advanced by the size of the float.
template <typename TFileCursor>
double ReadDoubleBE(TFileCursor & f) {
IEEE754binary64BE target;
if (!FileReader::Read(f, target)) {
return 0.0;
}
return target;
}
// Read a struct.
// If successful, the file cursor is advanced by the size of the struct. Otherwise, the target is zeroed.
template <typename T, typename TFileCursor>
bool ReadStruct(TFileCursor & f, T & target) {
static_assert(mpt::is_binary_safe<T>::value);
if (!FileReader::Read(f, target)) {
mpt::reset(target);
return false;
}
return true;
}
// Allow to read a struct partially (if there's less memory available than the struct's size, fill it up with zeros).
// The file cursor is advanced by "partialSize" bytes.
template <typename T, typename TFileCursor>
typename TFileCursor::pos_type ReadStructPartial(TFileCursor & f, T & target, typename TFileCursor::pos_type partialSize = sizeof(T)) {
static_assert(mpt::is_binary_safe<T>::value);
typename TFileCursor::pos_type copyBytes = std::min(partialSize, sizeof(T));
if (!f.CanRead(copyBytes)) {
copyBytes = f.BytesLeft();
}
f.GetRaw(mpt::span(mpt::as_raw_memory(target).data(), copyBytes));
std::memset(mpt::as_raw_memory(target).data() + copyBytes, 0, sizeof(target) - copyBytes);
f.Skip(partialSize);
return copyBytes;
}
// Read a null-terminated string into a std::string
template <typename TFileCursor>
bool ReadNullString(TFileCursor & f, std::string & dest, const typename TFileCursor::pos_type maxLength = std::numeric_limits<typename TFileCursor::pos_type>::max()) {
dest.clear();
if (!f.CanRead(1)) {
return false;
}
char buffer[mpt::IO::BUFFERSIZE_MINUSCULE];
typename TFileCursor::pos_type avail = 0;
while ((avail = std::min(f.GetRaw(mpt::as_span(buffer)).size(), maxLength - dest.length())) != 0) {
auto end = std::find(buffer, buffer + avail, '\0');
dest.insert(dest.end(), buffer, end);
f.Skip(end - buffer);
if (end < buffer + avail) {
// Found null char
f.Skip(1);
break;
}
}
return dest.length() != 0;
}
// Read a string up to the next line terminator into a std::string
template <typename TFileCursor>
bool ReadLine(TFileCursor & f, std::string & dest, const typename TFileCursor::pos_type maxLength = std::numeric_limits<typename TFileCursor::pos_type>::max()) {
dest.clear();
if (!f.CanRead(1)) {
return false;
}
char buffer[mpt::IO::BUFFERSIZE_MINUSCULE];
char c = '\0';
typename TFileCursor::pos_type avail = 0;
while ((avail = std::min(f.GetRaw(mpt::as_span(buffer)).size(), maxLength - dest.length())) != 0) {
auto end = std::find_if(buffer, buffer + avail, mpt::is_any_line_ending<char>);
dest.insert(dest.end(), buffer, end);
f.Skip(end - buffer);
if (end < buffer + avail) {
// Found line ending
f.Skip(1);
// Handle CRLF line ending
if (*end == '\r') {
if (FileReader::Read(f, c) && c != '\n') {
f.SkipBack(1);
}
}
break;
}
}
return true;
}
// Compare a magic string with the current stream position.
// Returns true if they are identical and advances the file cursor by the the length of the "magic" string.
// Returns false if the string could not be found. The file cursor is not advanced in this case.
template <size_t N, typename TFileCursor>
bool ReadMagic(TFileCursor & f, const char (&magic)[N]) {
assert(magic[N - 1] == '\0');
for (std::size_t i = 0; i < N - 1; ++i) {
assert(magic[i] != '\0');
}
constexpr typename TFileCursor::pos_type magicLength = N - 1;
std::byte buffer[magicLength] = {};
if (f.GetRaw(mpt::span(buffer, magicLength)).size() != magicLength) {
return false;
}
if (std::memcmp(buffer, magic, magicLength)) {
return false;
}
f.Skip(magicLength);
return true;
}
// Read variable-length unsigned integer (as found in MIDI files).
// If successful, the file cursor is advanced by the size of the integer and true is returned.
// False is returned if not enough bytes were left to finish reading of the integer or if an overflow happened (source doesn't fit into target integer).
// In case of an overflow, the target is also set to the maximum value supported by its data type.
template <typename T, typename TFileCursor>
bool ReadVarInt(TFileCursor & f, T & target) {
static_assert(std::numeric_limits<T>::is_integer == true && std::numeric_limits<T>::is_signed == false, "Target type is not an unsigned integer");
if (f.NoBytesLeft()) {
target = 0;
return false;
}
std::byte bytes[16]; // More than enough for any valid VarInt
typename TFileCursor::pos_type avail = f.GetRaw(mpt::as_span(bytes)).size();
typename TFileCursor::pos_type readPos = 1;
uint8 b = mpt::byte_cast<uint8>(bytes[0]);
target = (b & 0x7F);
std::size_t writtenBits = static_cast<std::size_t>(mpt::bit_width(target)); // Bits used in the most significant byte
while (readPos < avail && (b & 0x80) != 0) {
b = mpt::byte_cast<uint8>(bytes[readPos++]);
target <<= 7;
target |= (b & 0x7F);
writtenBits += 7;
if (readPos == avail) {
f.Skip(readPos);
avail = f.GetRaw(mpt::as_span(bytes)).size();
readPos = 0;
}
}
f.Skip(readPos);
if (writtenBits > sizeof(target) * 8u) {
// Overflow
target = std::numeric_limits<T>::max();
return false;
} else if ((b & 0x80) != 0) {
// Reached EOF
return false;
}
return true;
}
template <typename Tid, typename Tsize>
struct ChunkHeader {
using id_type = Tid;
using size_type = Tsize;
friend constexpr bool declare_binary_safe(const ChunkHeader &) noexcept {
return true;
}
id_type id{};
size_type size{};
id_type GetID() const {
return id;
}
size_type GetLength() const {
return size;
}
};
template <typename TChunkHeader, typename TFileCursor>
struct Chunk {
TChunkHeader header;
TFileCursor data;
TChunkHeader GetHeader() const {
return header;
}
TFileCursor GetData() const {
return data;
}
};
template <typename TChunkHeader, typename TFileCursor>
struct ChunkList {
using id_type = decltype(TChunkHeader().GetID());
using size_type = decltype(TChunkHeader().GetLength());
std::vector<Chunk<TChunkHeader, TFileCursor>> chunks;
// Check if the list contains a given chunk.
bool ChunkExists(id_type id) const {
return std::find_if(chunks.begin(), chunks.end(), [id](const Chunk<TChunkHeader, TFileCursor> & chunk) { return chunk.GetHeader().GetID() == id; }) != chunks.end();
}
// Retrieve the first chunk with a given ID.
TFileCursor GetChunk(id_type id) const {
auto chunk = std::find_if(chunks.begin(), chunks.end(), [id](const Chunk<TChunkHeader, TFileCursor> & chunk) { return chunk.GetHeader().GetID() == id; });
if (chunk == chunks.end()) {
return TFileCursor();
}
return chunk->GetData();
}
// Retrieve all chunks with a given ID.
std::vector<TFileCursor> GetAllChunks(id_type id) const {
std::vector<TFileCursor> result;
for (const auto & chunk : chunks) {
if (chunk.GetHeader().GetID() == id) {
result.push_back(chunk.GetData());
}
}
return result;
}
};
// Read a single "TChunkHeader" chunk.
// T is required to have the methods GetID() and GetLength().
// GetLength() must return the chunk size in bytes, and GetID() the chunk ID.
template <typename TChunkHeader, typename TFileCursor>
Chunk<TChunkHeader, TFileCursor> ReadNextChunk(TFileCursor & f, typename TFileCursor::pos_type alignment) {
Chunk<TChunkHeader, TFileCursor> result;
if (!FileReader::Read(f, result.header)) {
return Chunk<TChunkHeader, TFileCursor>();
}
typename TFileCursor::pos_type dataSize = result.header.GetLength();
result.data = f.ReadChunk(dataSize);
if (alignment > 1) {
if ((dataSize % alignment) != 0) {
f.Skip(alignment - (dataSize % alignment));
}
}
return result;
}
// Read a series of "TChunkHeader" chunks until the end of file is reached.
// T is required to have the methods GetID() and GetLength().
// GetLength() must return the chunk size in bytes, and GetID() the chunk ID.
template <typename TChunkHeader, typename TFileCursor>
ChunkList<TChunkHeader, TFileCursor> ReadChunks(TFileCursor & f, typename TFileCursor::pos_type alignment) {
ChunkList<TChunkHeader, TFileCursor> result;
while (f.CanRead(sizeof(TChunkHeader))) {
result.chunks.push_back(FileReader::ReadNextChunk<TChunkHeader, TFileCursor>(f, alignment));
}
return result;
}
// Read a series of "TChunkHeader" chunks until a given chunk ID is found.
// T is required to have the methods GetID() and GetLength().
// GetLength() must return the chunk size in bytes, and GetID() the chunk ID.
template <typename TChunkHeader, typename TFileCursor>
ChunkList<TChunkHeader, TFileCursor> ReadChunksUntil(TFileCursor & f, typename TFileCursor::pos_type alignment, decltype(TChunkHeader().GetID()) lastID) {
ChunkList<TChunkHeader, TFileCursor> result;
while (f.CanRead(sizeof(TChunkHeader))) {
result.chunks.push_back(FileReader::ReadNextChunk<TChunkHeader, TFileCursor>(f, alignment));
if (result.chunks.back().GetHeader().GetID() == lastID) {
break;
}
}
return result;
}
} // namespace FileReader
} // namespace IO
} // namespace MPT_INLINE_NS
} // namespace mpt
#endif // MPT_IO_READ_FILEREADER_HPP
| 31.341176 | 167 | 0.713964 | [
"object",
"vector"
] |
84a5441c0211d4dd0490aa4ac807dfc2ff94b5da | 5,531 | cpp | C++ | src/33u/Flash.cpp | TheImagingSource/tcam-firmware-update | a8feb157e73e36bf898bf4d6a025fef839df9584 | [
"Apache-2.0"
] | null | null | null | src/33u/Flash.cpp | TheImagingSource/tcam-firmware-update | a8feb157e73e36bf898bf4d6a025fef839df9584 | [
"Apache-2.0"
] | null | null | null | src/33u/Flash.cpp | TheImagingSource/tcam-firmware-update | a8feb157e73e36bf898bf4d6a025fef839df9584 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 The Imaging Source Europe GmbH
*
* 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 "Flash.h"
#include "Crc32.h"
#include "MemoryMap.h"
#include "ReportProgress.h"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <thread>
namespace lib33u
{
namespace device_interface
{
namespace
{
const uint32_t FLASH_UNLOCK_CODE = 0xCD56631A;
const uint64_t MEM_ADDRESS_DATA = MemoryMap::CAMERA_FLASH + 0x00000000;
const uint64_t MEM_ADDRESS_LOCK = MemoryMap::CAMERA_FLASH + 0x00800000;
const uint64_t MEM_ADDRESS_ERASE = MemoryMap::CAMERA_FLASH + 0x00800004;
const uint64_t MEM_ADDRESS_CRC32_START = MemoryMap::CAMERA_FLASH + 0x00800008;
const uint64_t MEM_ADDRESS_CRC32_LENGTH = MemoryMap::CAMERA_FLASH + 0x0080000C;
const uint64_t MEM_ADDRESS_CRC32_RESULT = MemoryMap::CAMERA_FLASH + 0x00800010;
const uint64_t MEM_ADDRESS_REBOOT = MemoryMap::CAMERA_FLASH + 0x00800020;
const uint32_t MAX_CRC_BLOCK_SIZE = 0x10000;
} // namespace
void Flash::unlock()
{
gencp_.write_u32(MEM_ADDRESS_LOCK, FLASH_UNLOCK_CODE);
}
void Flash::lock()
{
gencp_.write_u32(MEM_ADDRESS_LOCK, 0);
}
uint32_t Flash::block_crc32(uint32_t address, uint32_t length) const
{
if (length > MAX_CRC_BLOCK_SIZE)
{
throw std::invalid_argument("length for crc check has to be smaller than 64K");
}
gencp_.write_u32(MEM_ADDRESS_CRC32_START, address);
gencp_.write_u32(MEM_ADDRESS_CRC32_LENGTH, length);
return gencp_.read_u32(MEM_ADDRESS_CRC32_RESULT);
}
void Flash::block_write(uint32_t address, const uint8_t* data, uint16_t length)
{
if (length > gencp_.max_write_mem())
{
throw std::invalid_argument("length has to be <= gencp_.max_write_mem()");
}
gencp_.write_mem(MEM_ADDRESS_DATA + address, data, length);
}
void Flash::write_verify(uint32_t address,
const uint8_t* data,
uint32_t length,
util::progress::IReportProgress& progress)
{
if (length % 4)
{
throw std::invalid_argument("length must be divisible by 4");
}
unlock();
uint32_t bytes_remaining = length;
uint32_t offset = 0;
uint32_t step_size = gencp_.max_write_mem();
auto upload_progress = util::progress::MapItemProgress(progress, length);
upload_progress.report_step_format("Upload %d bytes", length);
while (bytes_remaining > 0)
{
uint16_t chunk_size = static_cast<uint16_t>(std::min(bytes_remaining, step_size));
block_write(address + offset, data + offset, chunk_size);
auto crc_flash = block_crc32(address + offset, chunk_size);
auto crc_buffer = util::crc32::calc(0, data + offset, chunk_size);
if (crc_flash != crc_buffer)
{
throw std::runtime_error("CRC error");
}
offset += chunk_size;
bytes_remaining -= chunk_size;
upload_progress.report_items(chunk_size, "KiB/s", 1024);
}
lock();
}
void Flash::erase_page(uint32_t address)
{
try
{
gencp_.write_u32(MEM_ADDRESS_ERASE, address);
}
catch (std::exception const& e)
{
// If this exception occurs, we might have run into a timeout because of a slow flash chip
// Since we cannot fix the firmware for this (this is a firmware upgrade in progress),
// we need to fix this issue in the updater
// Ignore this error and give the camera some time
//using namespace std::chrono_literals;
std::chrono::milliseconds ms { 1000 };
std::this_thread::sleep_for(ms);
}
}
void Flash::erase(uint32_t address, uint32_t length)
{
unlock();
uint32_t bytes_remaining = length;
uint32_t offset = 0;
uint32_t step_size = FLASH_PAGE_SIZE;
while (bytes_remaining > 0)
{
uint32_t chunk_size = std::min(bytes_remaining, step_size);
erase_page(address + offset);
offset += chunk_size;
bytes_remaining -= chunk_size;
}
lock();
}
void Flash::erase_write_verify(uint32_t address,
const uint8_t* data,
uint32_t length,
util::progress::IReportProgress& progress)
{
erase(address, length);
write_verify(address, data, length, progress);
}
std::vector<uint8_t> Flash::read(uint32_t address, uint32_t length) const
{
if (length % 4)
{
throw std::invalid_argument("length must be divisible by 4");
}
std::vector<uint8_t> result(length);
uint32_t bytes_remaining = length;
uint32_t offset = 0;
uint32_t step_size = gencp_.max_read_mem();
while (bytes_remaining > 0)
{
uint16_t chunk_size = static_cast<uint16_t>(std::min(bytes_remaining, step_size));
gencp_.read_mem(MEM_ADDRESS_DATA + address + offset, result.data() + offset, chunk_size);
offset += chunk_size;
bytes_remaining -= chunk_size;
}
return result;
}
} /* namespace device_interface */
} /* namespace lib33u */
| 28.219388 | 98 | 0.678178 | [
"vector"
] |
84a60b178937f243295dc5b40a260e29fcd05ffb | 1,439 | hpp | C++ | src/resample/resampler.hpp | mfkiwl/ugsdr | 7ce479c17ecbf00cf06b5e17bb00fb3d2d45d5d3 | [
"MIT"
] | null | null | null | src/resample/resampler.hpp | mfkiwl/ugsdr | 7ce479c17ecbf00cf06b5e17bb00fb3d2d45d5d3 | [
"MIT"
] | null | null | null | src/resample/resampler.hpp | mfkiwl/ugsdr | 7ce479c17ecbf00cf06b5e17bb00fb3d2d45d5d3 | [
"MIT"
] | null | null | null | #pragma once
#include "../common.hpp"
#include <cmath>
#include <vector>
#include "decimator.hpp"
#include "upsampler.hpp"
namespace ugsdr {
template <typename ResamplerImpl>
class Resampler {
protected:
public:
template <Container T>
static void Transform(T& src_dst, std::size_t new_sampling_rate, std::size_t old_sampling_rate) {
ResamplerImpl::Process(src_dst, new_sampling_rate, old_sampling_rate);
}
template <Container T>
static auto Transform(const T& src_dst, std::size_t new_sampling_rate, std::size_t old_sampling_rate) {
auto dst = src_dst;
ResamplerImpl::Process(dst, new_sampling_rate, old_sampling_rate);
return dst;
}
};
class SequentialResampler : public Resampler<SequentialResampler> {
protected:
friend class Resampler<SequentialResampler>;
template <typename T>
static auto Process(const std::vector<T>& src_dst, std::size_t new_sampling_rate, std::size_t old_sampling_rate) {
auto dst = src_dst;
Process(dst, new_sampling_rate, old_sampling_rate);
return dst;
}
template <typename T>
static void Process(std::vector<T>& src_dst, std::size_t new_sampling_rate, std::size_t old_sampling_rate) {
auto lcm = std::lcm(new_sampling_rate, old_sampling_rate);
auto new_samples = lcm * src_dst.size() / old_sampling_rate;
SequentialUpsampler::Transform(src_dst, new_samples);
Accumulator::Transform(src_dst, lcm / new_sampling_rate);
}
public:
};
}
| 28.215686 | 116 | 0.748436 | [
"vector",
"transform"
] |
84ab86c06a3fff99ad149805b17ced370fbbe1e1 | 3,584 | hpp | C++ | third_party/osmium/io/detail/zlib.hpp | cypox/devacus-backend | ba3d2ca8d72843560c4ff754780482dfe8a67c6b | [
"BSD-2-Clause"
] | 1 | 2015-03-16T12:49:12.000Z | 2015-03-16T12:49:12.000Z | third_party/osmium/io/detail/zlib.hpp | antoinegiret/osrm-backend | ebe34da5428c2bfdb2b227392248011c757822e5 | [
"BSD-2-Clause"
] | 1 | 2015-02-25T18:27:19.000Z | 2015-02-25T18:27:19.000Z | third_party/osmium/io/detail/zlib.hpp | antoinegiret/osrm-backend | ebe34da5428c2bfdb2b227392248011c757822e5 | [
"BSD-2-Clause"
] | null | null | null | #ifndef OSMIUM_IO_DETAIL_ZLIB_HPP
#define OSMIUM_IO_DETAIL_ZLIB_HPP
/*
This file is part of Osmium (http://osmcode.org/libosmium).
Copyright 2013,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_LINK_WITH_LIBS_ZLIB -lz
#include <memory>
#include <stdexcept>
#include <string>
#include <zlib.h>
namespace osmium {
namespace io {
namespace detail {
/**
* Compress data using zlib.
*
* @param input Data to compress.
* @returns Compressed data.
*/
inline std::string zlib_compress(const std::string& input) {
unsigned long output_size = ::compressBound(input.size());
std::string output(output_size, '\0');
if (::compress(reinterpret_cast<unsigned char*>(const_cast<char *>(output.data())),
&output_size,
reinterpret_cast<const unsigned char*>(input.data()),
input.size()) != Z_OK) {
throw std::runtime_error("failed to compress data");
}
output.resize(output_size);
return output;
}
/**
* Uncompress data using zlib.
*
* @param input Compressed input data.
* @param raw_size Size of uncompressed data.
* @returns Uncompressed data.
*/
inline std::unique_ptr<std::string> zlib_uncompress(const std::string& input, unsigned long raw_size) {
auto output = std::unique_ptr<std::string>(new std::string(raw_size, '\0'));
if (::uncompress(reinterpret_cast<unsigned char*>(const_cast<char *>(output->data())),
&raw_size,
reinterpret_cast<const unsigned char*>(input.data()),
input.size()) != Z_OK) {
throw std::runtime_error("failed to uncompress data");
}
return output;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_ZLIB_HPP
| 35.84 | 115 | 0.631138 | [
"object"
] |
84ba55ae3e02b583bcff90e53de4fa6f2f5a6296 | 1,394 | cc | C++ | content/browser/appcache/appcache_backend_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/appcache/appcache_backend_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/appcache/appcache_backend_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2011 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 "content/browser/appcache/appcache_backend_impl.h"
#include <memory>
#include <tuple>
#include <utility>
#include <vector>
#include "content/browser/appcache/appcache.h"
#include "content/browser/appcache/appcache_group.h"
#include "content/browser/appcache/appcache_service_impl.h"
#include "content/public/browser/browser_thread.h"
#include "third_party/blink/public/mojom/appcache/appcache.mojom.h"
namespace content {
AppCacheBackendImpl::AppCacheBackendImpl(AppCacheServiceImpl* service,
int process_id,
int routing_id)
: service_(service), process_id_(process_id), routing_id_(routing_id) {
DCHECK(service);
}
AppCacheBackendImpl::~AppCacheBackendImpl() = default;
void AppCacheBackendImpl::RegisterHost(
mojo::PendingReceiver<blink::mojom::AppCacheHost> host_receiver,
mojo::PendingRemote<blink::mojom::AppCacheFrontend> frontend_remote,
const base::UnguessableToken& host_id) {
service_->RegisterHost(std::move(host_receiver), std::move(frontend_remote),
host_id, routing_id_, process_id_,
mojo::GetBadMessageCallback());
}
} // namespace content
| 35.74359 | 78 | 0.711621 | [
"vector"
] |
84c36e649ad32faf61e2922b6b2db7b27c3ba8a5 | 33,256 | cpp | C++ | B2G/gecko/gfx/2d/DrawTargetCG.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/gfx/2d/DrawTargetCG.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/gfx/2d/DrawTargetCG.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* 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 "DrawTargetCG.h"
#include "SourceSurfaceCG.h"
#include "Rect.h"
#include "ScaledFontMac.h"
#include "Tools.h"
#include <vector>
#include "QuartzSupport.h"
//CG_EXTERN void CGContextSetCompositeOperation (CGContextRef, PrivateCGCompositeMode);
// A private API that Cairo has been using for a long time
CG_EXTERN void CGContextSetCTM(CGContextRef, CGAffineTransform);
namespace mozilla {
namespace gfx {
static CGRect RectToCGRect(Rect r)
{
return CGRectMake(r.x, r.y, r.width, r.height);
}
static CGRect IntRectToCGRect(IntRect r)
{
return CGRectMake(r.x, r.y, r.width, r.height);
}
CGBlendMode ToBlendMode(CompositionOp op)
{
CGBlendMode mode;
switch (op) {
case OP_OVER:
mode = kCGBlendModeNormal;
break;
case OP_ADD:
mode = kCGBlendModePlusLighter;
break;
case OP_ATOP:
mode = kCGBlendModeSourceAtop;
break;
case OP_OUT:
mode = kCGBlendModeSourceOut;
break;
case OP_IN:
mode = kCGBlendModeSourceIn;
break;
case OP_SOURCE:
mode = kCGBlendModeCopy;
break;
case OP_DEST_IN:
mode = kCGBlendModeDestinationIn;
break;
case OP_DEST_OUT:
mode = kCGBlendModeDestinationOut;
break;
case OP_DEST_OVER:
mode = kCGBlendModeDestinationOver;
break;
case OP_DEST_ATOP:
mode = kCGBlendModeDestinationAtop;
break;
case OP_XOR:
mode = kCGBlendModeXOR;
break;
/*
case OP_CLEAR:
mode = kCGBlendModeClear;
break;*/
default:
mode = kCGBlendModeNormal;
}
return mode;
}
DrawTargetCG::DrawTargetCG() : mSnapshot(nullptr)
{
}
DrawTargetCG::~DrawTargetCG()
{
MarkChanged();
// We need to conditionally release these because Init can fail without initializing these.
if (mColorSpace)
CGColorSpaceRelease(mColorSpace);
if (mCg)
CGContextRelease(mCg);
free(mData);
}
BackendType
DrawTargetCG::GetType() const
{
// It may be worth spliting Bitmap and IOSurface DrawTarget
// into seperate classes.
if (GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE) {
return BACKEND_COREGRAPHICS_ACCELERATED;
} else {
return BACKEND_COREGRAPHICS;
}
}
TemporaryRef<SourceSurface>
DrawTargetCG::Snapshot()
{
if (!mSnapshot) {
if (GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE) {
return new SourceSurfaceCGIOSurfaceContext(this);
} else {
mSnapshot = new SourceSurfaceCGBitmapContext(this);
}
}
return mSnapshot;
}
TemporaryRef<DrawTarget>
DrawTargetCG::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
{
// XXX: in thebes we use CGLayers to do this kind of thing. It probably makes sense
// to add that in somehow, but at a higher level
RefPtr<DrawTargetCG> newTarget = new DrawTargetCG();
if (newTarget->Init(GetType(), aSize, aFormat)) {
return newTarget;
} else {
return nullptr;
}
}
TemporaryRef<SourceSurface>
DrawTargetCG::CreateSourceSurfaceFromData(unsigned char *aData,
const IntSize &aSize,
int32_t aStride,
SurfaceFormat aFormat) const
{
RefPtr<SourceSurfaceCG> newSurf = new SourceSurfaceCG();
if (!newSurf->InitFromData(aData, aSize, aStride, aFormat)) {
return nullptr;
}
return newSurf;
}
static CGImageRef
GetImageFromSourceSurface(SourceSurface *aSurface)
{
if (aSurface->GetType() == SURFACE_COREGRAPHICS_IMAGE)
return static_cast<SourceSurfaceCG*>(aSurface)->GetImage();
else if (aSurface->GetType() == SURFACE_COREGRAPHICS_CGCONTEXT)
return static_cast<SourceSurfaceCGContext*>(aSurface)->GetImage();
else if (aSurface->GetType() == SURFACE_DATA)
return static_cast<DataSourceSurfaceCG*>(aSurface)->GetImage();
abort();
}
TemporaryRef<SourceSurface>
DrawTargetCG::OptimizeSourceSurface(SourceSurface *aSurface) const
{
return nullptr;
}
class UnboundnessFixer
{
CGRect mClipBounds;
CGLayerRef mLayer;
CGContextRef mCg;
public:
UnboundnessFixer() : mCg(nullptr) {}
CGContextRef Check(CGContextRef baseCg, CompositionOp blend)
{
if (!IsOperatorBoundByMask(blend)) {
mClipBounds = CGContextGetClipBoundingBox(baseCg);
// TransparencyLayers aren't blended using the blend mode so
// we are forced to use CGLayers
//XXX: The size here is in default user space units, of the layer relative to the graphics context.
// is the clip bounds still correct if, for example, we have a scale applied to the context?
mLayer = CGLayerCreateWithContext(baseCg, mClipBounds.size, nullptr);
//XXX: if the size is 0x0 we get a nullptr CGContext back from GetContext
mCg = CGLayerGetContext(mLayer);
// CGContext's default to have the origin at the bottom left
// so flip it to the top left and adjust for the origin
// of the layer
CGContextTranslateCTM(mCg, -mClipBounds.origin.x, mClipBounds.origin.y + mClipBounds.size.height);
CGContextScaleCTM(mCg, 1, -1);
return mCg;
} else {
return baseCg;
}
}
void Fix(CGContextRef baseCg)
{
if (mCg) {
CGContextTranslateCTM(baseCg, 0, mClipBounds.size.height);
CGContextScaleCTM(baseCg, 1, -1);
mClipBounds.origin.y *= -1;
CGContextDrawLayerAtPoint(baseCg, mClipBounds.origin, mLayer);
CGContextRelease(mCg);
}
}
};
void
DrawTargetCG::DrawSurface(SourceSurface *aSurface,
const Rect &aDest,
const Rect &aSource,
const DrawSurfaceOptions &aSurfOptions,
const DrawOptions &aDrawOptions)
{
MarkChanged();
CGImageRef image;
CGImageRef subimage = nullptr;
CGContextSaveGState(mCg);
CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
UnboundnessFixer fixer;
CGContextRef cg = fixer.Check(mCg, aDrawOptions.mCompositionOp);
CGContextSetAlpha(cg, aDrawOptions.mAlpha);
CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform));
image = GetImageFromSourceSurface(aSurface);
/* we have two options here:
* - create a subimage -- this is slower
* - fancy things with clip and different dest rects */
{
subimage = CGImageCreateWithImageInRect(image, RectToCGRect(aSource));
image = subimage;
}
CGContextScaleCTM(cg, 1, -1);
CGRect flippedRect = CGRectMake(aDest.x, -(aDest.y + aDest.height),
aDest.width, aDest.height);
//XXX: we should implement this for patterns too
if (aSurfOptions.mFilter == FILTER_POINT)
CGContextSetInterpolationQuality(cg, kCGInterpolationNone);
CGContextDrawImage(cg, flippedRect, image);
fixer.Fix(mCg);
CGContextRestoreGState(mCg);
CGImageRelease(subimage);
}
static CGColorRef ColorToCGColor(CGColorSpaceRef aColorSpace, const Color& aColor)
{
CGFloat components[4] = {aColor.r, aColor.g, aColor.b, aColor.a};
return CGColorCreate(aColorSpace, components);
}
class GradientStopsCG : public GradientStops
{
public:
//XXX: The skia backend uses a vector and passes in aNumStops. It should do better
GradientStopsCG(GradientStop* aStops, uint32_t aNumStops, ExtendMode aExtendMode)
{
//XXX: do the stops need to be in any particular order?
// what should we do about the color space here? we certainly shouldn't be
// recreating it all the time
std::vector<CGFloat> colors;
std::vector<CGFloat> offsets;
colors.reserve(aNumStops*4);
offsets.reserve(aNumStops);
for (uint32_t i = 0; i < aNumStops; i++) {
colors.push_back(aStops[i].color.r);
colors.push_back(aStops[i].color.g);
colors.push_back(aStops[i].color.b);
colors.push_back(aStops[i].color.a);
offsets.push_back(aStops[i].offset);
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
mGradient = CGGradientCreateWithColorComponents(colorSpace,
&colors.front(),
&offsets.front(),
aNumStops);
CGColorSpaceRelease(colorSpace);
}
virtual ~GradientStopsCG() {
CGGradientRelease(mGradient);
}
// Will always report BACKEND_COREGRAPHICS, but it is compatible
// with BACKEND_COREGRAPHICS_ACCELERATED
BackendType GetBackendType() const { return BACKEND_COREGRAPHICS; }
CGGradientRef mGradient;
};
TemporaryRef<GradientStops>
DrawTargetCG::CreateGradientStops(GradientStop *aStops, uint32_t aNumStops,
ExtendMode aExtendMode) const
{
return new GradientStopsCG(aStops, aNumStops, aExtendMode);
}
static void
DrawGradient(CGContextRef cg, const Pattern &aPattern)
{
if (aPattern.GetType() == PATTERN_LINEAR_GRADIENT) {
const LinearGradientPattern& pat = static_cast<const LinearGradientPattern&>(aPattern);
GradientStopsCG *stops = static_cast<GradientStopsCG*>(pat.mStops.get());
// XXX: we should take the m out of the properties of LinearGradientPatterns
CGPoint startPoint = { pat.mBegin.x, pat.mBegin.y };
CGPoint endPoint = { pat.mEnd.x, pat.mEnd.y };
// Canvas spec states that we should avoid drawing degenerate gradients (XXX: should this be in common code?)
//if (startPoint.x == endPoint.x && startPoint.y == endPoint.y)
// return;
CGContextDrawLinearGradient(cg, stops->mGradient, startPoint, endPoint,
kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
} else if (aPattern.GetType() == PATTERN_RADIAL_GRADIENT) {
const RadialGradientPattern& pat = static_cast<const RadialGradientPattern&>(aPattern);
GradientStopsCG *stops = static_cast<GradientStopsCG*>(pat.mStops.get());
// XXX: we should take the m out of the properties of RadialGradientPatterns
CGPoint startCenter = { pat.mCenter1.x, pat.mCenter1.y };
CGFloat startRadius = pat.mRadius1;
CGPoint endCenter = { pat.mCenter2.x, pat.mCenter2.y };
CGFloat endRadius = pat.mRadius2;
//XXX: are there degenerate radial gradients that we should avoid drawing?
CGContextDrawRadialGradient(cg, stops->mGradient, startCenter, startRadius, endCenter, endRadius,
kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
} else {
assert(0);
}
}
static void
drawPattern(void *info, CGContextRef context)
{
CGImageRef image = static_cast<CGImageRef>(info);
CGRect rect = {{0, 0},
{static_cast<CGFloat>(CGImageGetWidth(image)),
static_cast<CGFloat>(CGImageGetHeight(image))}};
CGContextDrawImage(context, rect, image);
}
static void
releaseInfo(void *info)
{
CGImageRef image = static_cast<CGImageRef>(info);
CGImageRelease(image);
}
CGPatternCallbacks patternCallbacks = {
0,
drawPattern,
releaseInfo
};
static bool
isGradient(const Pattern &aPattern)
{
return aPattern.GetType() == PATTERN_LINEAR_GRADIENT || aPattern.GetType() == PATTERN_RADIAL_GRADIENT;
}
/* CoreGraphics patterns ignore the userspace transform so
* we need to multiply it in */
static CGPatternRef
CreateCGPattern(const Pattern &aPattern, CGAffineTransform aUserSpace)
{
const SurfacePattern& pat = static_cast<const SurfacePattern&>(aPattern);
// XXX: is .get correct here?
CGImageRef image = GetImageFromSourceSurface(pat.mSurface.get());
CGFloat xStep, yStep;
switch (pat.mExtendMode) {
case EXTEND_CLAMP:
// The 1 << 22 comes from Webkit see Pattern::createPlatformPattern() in PatternCG.cpp for more info
xStep = static_cast<CGFloat>(1 << 22);
yStep = static_cast<CGFloat>(1 << 22);
break;
case EXTEND_REFLECT:
assert(0);
case EXTEND_REPEAT:
xStep = static_cast<CGFloat>(CGImageGetWidth(image));
yStep = static_cast<CGFloat>(CGImageGetHeight(image));
// webkit uses wkCGPatternCreateWithImageAndTransform a wrapper around CGPatternCreateWithImage2
// this is done to avoid pixel-cracking along pattern boundaries
// (see https://bugs.webkit.org/show_bug.cgi?id=53055)
// typedef enum {
// wkPatternTilingNoDistortion,
// wkPatternTilingConstantSpacingMinimalDistortion,
// wkPatternTilingConstantSpacing
// } wkPatternTiling;
// extern CGPatternRef (*wkCGPatternCreateWithImageAndTransform)(CGImageRef, CGAffineTransform, int);
}
//XXX: We should be using CGContextDrawTiledImage when we can. Even though it
// creates a pattern, it seems to go down a faster path than using a delegate
// like we do below
CGRect bounds = {
{0, 0,},
{static_cast<CGFloat>(CGImageGetWidth(image)), static_cast<CGFloat>(CGImageGetHeight(image))}
};
CGAffineTransform transform = CGAffineTransformConcat(CGAffineTransformMakeScale(1, -1), aUserSpace);
transform = CGAffineTransformTranslate(transform, 0, -static_cast<float>(CGImageGetHeight(image)));
return CGPatternCreate(CGImageRetain(image), bounds, transform, xStep, yStep, kCGPatternTilingConstantSpacing,
true, &patternCallbacks);
}
static void
SetFillFromPattern(CGContextRef cg, CGColorSpaceRef aColorSpace, const Pattern &aPattern)
{
assert(!isGradient(aPattern));
if (aPattern.GetType() == PATTERN_COLOR) {
const Color& color = static_cast<const ColorPattern&>(aPattern).mColor;
//XXX: we should cache colors
CGColorRef cgcolor = ColorToCGColor(aColorSpace, color);
CGContextSetFillColorWithColor(cg, cgcolor);
CGColorRelease(cgcolor);
} else if (aPattern.GetType() == PATTERN_SURFACE) {
CGColorSpaceRef patternSpace;
patternSpace = CGColorSpaceCreatePattern (nullptr);
CGContextSetFillColorSpace(cg, patternSpace);
CGColorSpaceRelease(patternSpace);
CGPatternRef pattern = CreateCGPattern(aPattern, CGContextGetCTM(cg));
CGFloat alpha = 1.;
CGContextSetFillPattern(cg, pattern, &alpha);
CGPatternRelease(pattern);
}
}
static void
SetStrokeFromPattern(CGContextRef cg, CGColorSpaceRef aColorSpace, const Pattern &aPattern)
{
assert(!isGradient(aPattern));
if (aPattern.GetType() == PATTERN_COLOR) {
const Color& color = static_cast<const ColorPattern&>(aPattern).mColor;
//XXX: we should cache colors
CGColorRef cgcolor = ColorToCGColor(aColorSpace, color);
CGContextSetStrokeColorWithColor(cg, cgcolor);
CGColorRelease(cgcolor);
} else if (aPattern.GetType() == PATTERN_SURFACE) {
CGColorSpaceRef patternSpace;
patternSpace = CGColorSpaceCreatePattern (nullptr);
CGContextSetStrokeColorSpace(cg, patternSpace);
CGColorSpaceRelease(patternSpace);
CGPatternRef pattern = CreateCGPattern(aPattern, CGContextGetCTM(cg));
CGFloat alpha = 1.;
CGContextSetStrokePattern(cg, pattern, &alpha);
CGPatternRelease(pattern);
}
}
void
DrawTargetCG::FillRect(const Rect &aRect,
const Pattern &aPattern,
const DrawOptions &aDrawOptions)
{
MarkChanged();
CGContextSaveGState(mCg);
UnboundnessFixer fixer;
CGContextRef cg = fixer.Check(mCg, aDrawOptions.mCompositionOp);
CGContextSetAlpha(mCg, aDrawOptions.mAlpha);
CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform));
if (isGradient(aPattern)) {
CGContextClipToRect(cg, RectToCGRect(aRect));
DrawGradient(cg, aPattern);
} else {
SetFillFromPattern(cg, mColorSpace, aPattern);
CGContextFillRect(cg, RectToCGRect(aRect));
}
fixer.Fix(mCg);
CGContextRestoreGState(mCg);
}
void
DrawTargetCG::StrokeLine(const Point &p1, const Point &p2, const Pattern &aPattern, const StrokeOptions &aStrokeOptions, const DrawOptions &aDrawOptions)
{
MarkChanged();
CGContextSaveGState(mCg);
UnboundnessFixer fixer;
CGContextRef cg = fixer.Check(mCg, aDrawOptions.mCompositionOp);
CGContextSetAlpha(mCg, aDrawOptions.mAlpha);
CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform));
CGContextBeginPath(cg);
CGContextMoveToPoint(cg, p1.x, p1.y);
CGContextAddLineToPoint(cg, p2.x, p2.y);
SetStrokeOptions(cg, aStrokeOptions);
if (isGradient(aPattern)) {
CGContextReplacePathWithStrokedPath(cg);
//XXX: should we use EO clip here?
CGContextClip(cg);
DrawGradient(cg, aPattern);
} else {
SetStrokeFromPattern(cg, mColorSpace, aPattern);
CGContextStrokePath(cg);
}
fixer.Fix(mCg);
CGContextRestoreGState(mCg);
}
void
DrawTargetCG::StrokeRect(const Rect &aRect,
const Pattern &aPattern,
const StrokeOptions &aStrokeOptions,
const DrawOptions &aDrawOptions)
{
MarkChanged();
CGContextSaveGState(mCg);
UnboundnessFixer fixer;
CGContextRef cg = fixer.Check(mCg, aDrawOptions.mCompositionOp);
CGContextSetAlpha(mCg, aDrawOptions.mAlpha);
CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform));
// we don't need to set all of the stroke state because
// it doesn't apply when stroking rects
switch (aStrokeOptions.mLineJoin)
{
case JOIN_BEVEL:
CGContextSetLineJoin(cg, kCGLineJoinBevel);
break;
case JOIN_ROUND:
CGContextSetLineJoin(cg, kCGLineJoinRound);
break;
case JOIN_MITER:
case JOIN_MITER_OR_BEVEL:
CGContextSetLineJoin(cg, kCGLineJoinMiter);
break;
}
CGContextSetLineWidth(cg, aStrokeOptions.mLineWidth);
if (isGradient(aPattern)) {
// There's no CGContextClipStrokeRect so we do it by hand
CGContextBeginPath(cg);
CGContextAddRect(cg, RectToCGRect(aRect));
CGContextReplacePathWithStrokedPath(cg);
//XXX: should we use EO clip here?
CGContextClip(cg);
DrawGradient(cg, aPattern);
} else {
SetStrokeFromPattern(cg, mColorSpace, aPattern);
CGContextStrokeRect(cg, RectToCGRect(aRect));
}
fixer.Fix(mCg);
CGContextRestoreGState(mCg);
}
void
DrawTargetCG::ClearRect(const Rect &aRect)
{
MarkChanged();
CGContextSaveGState(mCg);
CGContextConcatCTM(mCg, GfxMatrixToCGAffineTransform(mTransform));
CGContextClearRect(mCg, RectToCGRect(aRect));
CGContextRestoreGState(mCg);
}
void
DrawTargetCG::Stroke(const Path *aPath, const Pattern &aPattern, const StrokeOptions &aStrokeOptions, const DrawOptions &aDrawOptions)
{
MarkChanged();
CGContextSaveGState(mCg);
UnboundnessFixer fixer;
CGContextRef cg = fixer.Check(mCg, aDrawOptions.mCompositionOp);
CGContextSetAlpha(mCg, aDrawOptions.mAlpha);
CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform));
CGContextBeginPath(cg);
assert(aPath->GetBackendType() == BACKEND_COREGRAPHICS);
const PathCG *cgPath = static_cast<const PathCG*>(aPath);
CGContextAddPath(cg, cgPath->GetPath());
SetStrokeOptions(cg, aStrokeOptions);
if (isGradient(aPattern)) {
CGContextReplacePathWithStrokedPath(cg);
//XXX: should we use EO clip here?
CGContextClip(cg);
DrawGradient(cg, aPattern);
} else {
CGContextBeginPath(cg);
// XXX: we could put fill mode into the path fill rule if we wanted
const PathCG *cgPath = static_cast<const PathCG*>(aPath);
CGContextAddPath(cg, cgPath->GetPath());
SetStrokeFromPattern(cg, mColorSpace, aPattern);
CGContextStrokePath(cg);
}
fixer.Fix(mCg);
CGContextRestoreGState(mCg);
}
void
DrawTargetCG::Fill(const Path *aPath, const Pattern &aPattern, const DrawOptions &aDrawOptions)
{
MarkChanged();
assert(aPath->GetBackendType() == BACKEND_COREGRAPHICS);
CGContextSaveGState(mCg);
CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
UnboundnessFixer fixer;
CGContextRef cg = fixer.Check(mCg, aDrawOptions.mCompositionOp);
CGContextSetAlpha(cg, aDrawOptions.mAlpha);
CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform));
CGContextBeginPath(cg);
// XXX: we could put fill mode into the path fill rule if we wanted
const PathCG *cgPath = static_cast<const PathCG*>(aPath);
if (isGradient(aPattern)) {
// setup a clip to draw the gradient through
if (CGPathIsEmpty(cgPath->GetPath())) {
// Adding an empty path will cause us not to clip
// so clip everything explicitly
CGContextClipToRect(mCg, CGRectZero);
} else {
CGContextAddPath(cg, cgPath->GetPath());
if (cgPath->GetFillRule() == FILL_EVEN_ODD)
CGContextEOClip(mCg);
else
CGContextClip(mCg);
}
DrawGradient(cg, aPattern);
} else {
CGContextAddPath(cg, cgPath->GetPath());
SetFillFromPattern(cg, mColorSpace, aPattern);
if (cgPath->GetFillRule() == FILL_EVEN_ODD)
CGContextEOFillPath(cg);
else
CGContextFillPath(cg);
}
fixer.Fix(mCg);
CGContextRestoreGState(mCg);
}
void
DrawTargetCG::FillGlyphs(ScaledFont *aFont, const GlyphBuffer &aBuffer, const Pattern &aPattern, const DrawOptions &aDrawOptions,
const GlyphRenderingOptions*)
{
MarkChanged();
assert(aBuffer.mNumGlyphs);
CGContextSaveGState(mCg);
CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
UnboundnessFixer fixer;
CGContextRef cg = fixer.Check(mCg, aDrawOptions.mCompositionOp);
CGContextSetAlpha(cg, aDrawOptions.mAlpha);
CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform));
ScaledFontMac* cgFont = static_cast<ScaledFontMac*>(aFont);
CGContextSetFont(cg, cgFont->mFont);
CGContextSetFontSize(cg, cgFont->mSize);
//XXX: we should use a stack vector here when we have a class like that
std::vector<CGGlyph> glyphs;
std::vector<CGPoint> positions;
glyphs.resize(aBuffer.mNumGlyphs);
positions.resize(aBuffer.mNumGlyphs);
// Handle the flip
CGAffineTransform matrix = CGAffineTransformMakeScale(1, -1);
CGContextConcatCTM(cg, matrix);
// CGContextSetTextMatrix works differently with kCGTextClip && kCGTextFill
// It seems that it transforms the positions with TextFill and not with TextClip
// Therefore we'll avoid it. See also:
// http://cgit.freedesktop.org/cairo/commit/?id=9c0d761bfcdd28d52c83d74f46dd3c709ae0fa69
for (unsigned int i = 0; i < aBuffer.mNumGlyphs; i++) {
glyphs[i] = aBuffer.mGlyphs[i].mIndex;
// XXX: CGPointMake might not be inlined
positions[i] = CGPointMake(aBuffer.mGlyphs[i].mPosition.x,
-aBuffer.mGlyphs[i].mPosition.y);
}
//XXX: CGContextShowGlyphsAtPositions is 10.5+ for older versions use CGContextShowGlyphsWithAdvances
if (isGradient(aPattern)) {
CGContextSetTextDrawingMode(cg, kCGTextClip);
CGContextShowGlyphsAtPositions(cg, &glyphs.front(), &positions.front(), aBuffer.mNumGlyphs);
DrawGradient(cg, aPattern);
} else {
//XXX: with CoreGraphics we can stroke text directly instead of going
// through GetPath. It would be nice to add support for using that
CGContextSetTextDrawingMode(cg, kCGTextFill);
SetFillFromPattern(cg, mColorSpace, aPattern);
CGContextShowGlyphsAtPositions(cg, &glyphs.front(), &positions.front(), aBuffer.mNumGlyphs);
}
fixer.Fix(mCg);
CGContextRestoreGState(cg);
}
extern "C" {
void
CGContextResetClip(CGContextRef);
};
void
DrawTargetCG::CopySurface(SourceSurface *aSurface,
const IntRect& aSourceRect,
const IntPoint &aDestination)
{
MarkChanged();
CGImageRef image;
CGImageRef subimage = nullptr;
if (aSurface->GetType() == SURFACE_COREGRAPHICS_IMAGE) {
image = GetImageFromSourceSurface(aSurface);
/* we have two options here:
* - create a subimage -- this is slower
* - fancy things with clip and different dest rects */
{
subimage = CGImageCreateWithImageInRect(image, IntRectToCGRect(aSourceRect));
image = subimage;
}
// XXX: it might be more efficient for us to do the copy directly if we have access to the bits
CGContextSaveGState(mCg);
// CopySurface ignores the clip, so we need to use private API to temporarily reset it
CGContextResetClip(mCg);
CGContextSetBlendMode(mCg, kCGBlendModeCopy);
CGContextScaleCTM(mCg, 1, -1);
CGRect flippedRect = CGRectMake(aDestination.x, -(aDestination.y + aSourceRect.height),
aSourceRect.width, aSourceRect.height);
CGContextDrawImage(mCg, flippedRect, image);
CGContextRestoreGState(mCg);
CGImageRelease(subimage);
}
}
void
DrawTargetCG::DrawSurfaceWithShadow(SourceSurface *aSurface, const Point &aDest, const Color &aColor, const Point &aOffset, Float aSigma, CompositionOp aOperator)
{
MarkChanged();
CGImageRef image;
image = GetImageFromSourceSurface(aSurface);
IntSize size = aSurface->GetSize();
CGContextSaveGState(mCg);
//XXX do we need to do the fixup here?
CGContextSetBlendMode(mCg, ToBlendMode(aOperator));
CGContextScaleCTM(mCg, 1, -1);
CGRect flippedRect = CGRectMake(aDest.x, -(aDest.y + size.height),
size.width, size.height);
CGColorRef color = ColorToCGColor(mColorSpace, aColor);
CGSize offset = {aOffset.x, -aOffset.y};
// CoreGraphics needs twice sigma as it's amount of blur
CGContextSetShadowWithColor(mCg, offset, 2*aSigma, color);
CGColorRelease(color);
CGContextDrawImage(mCg, flippedRect, image);
CGContextRestoreGState(mCg);
}
bool
DrawTargetCG::Init(BackendType aType,
unsigned char* aData,
const IntSize &aSize,
int32_t aStride,
SurfaceFormat aFormat)
{
// XXX: we should come up with some consistent semantics for dealing
// with zero area drawtargets
if (aSize.width <= 0 || aSize.height <= 0 ||
// 32767 is the maximum size supported by cairo
// we clamp to that to make it easier to interoperate
aSize.width > 32767 || aSize.height > 32767) {
mColorSpace = nullptr;
mCg = nullptr;
mData = nullptr;
return false;
}
//XXX: handle SurfaceFormat
//XXX: we'd be better off reusing the Colorspace across draw targets
mColorSpace = CGColorSpaceCreateDeviceRGB();
if (aData == nullptr && aType != BACKEND_COREGRAPHICS_ACCELERATED) {
// XXX: Currently, Init implicitly clears, that can often be a waste of time
mData = calloc(aSize.height * aStride, 1);
aData = static_cast<unsigned char*>(mData);
} else {
// mData == nullptr means DrawTargetCG doesn't own the image data and will not
// delete it in the destructor
mData = nullptr;
}
mSize = aSize;
if (aType == BACKEND_COREGRAPHICS_ACCELERATED) {
RefPtr<MacIOSurface> ioSurface = MacIOSurface::CreateIOSurface(aSize.width, aSize.height);
mCg = ioSurface->CreateIOSurfaceContext();
// If we don't have the symbol for 'CreateIOSurfaceContext' mCg will be null
// and we will fallback to software below
mData = nullptr;
}
if (!mCg || aType == BACKEND_COREGRAPHICS) {
int bitsPerComponent = 8;
CGBitmapInfo bitinfo;
bitinfo = kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst;
// XXX: what should we do if this fails?
mCg = CGBitmapContextCreate (aData,
mSize.width,
mSize.height,
bitsPerComponent,
aStride,
mColorSpace,
bitinfo);
}
assert(mCg);
// CGContext's default to have the origin at the bottom left
// so flip it to the top left
CGContextTranslateCTM(mCg, 0, mSize.height);
CGContextScaleCTM(mCg, 1, -1);
// See Bug 722164 for performance details
// Medium or higher quality lead to expensive interpolation
// for canvas we want to use low quality interpolation
// to have competitive performance with other canvas
// implementation.
// XXX: Create input parameter to control interpolation and
// use the default for content.
CGContextSetInterpolationQuality(mCg, kCGInterpolationLow);
// XXX: set correct format
mFormat = FORMAT_B8G8R8A8;
if (aType == BACKEND_COREGRAPHICS_ACCELERATED) {
// The bitmap backend uses callac to clear, we can't do that without
// reading back the surface. This should trigger something equivilent
// to glClear.
ClearRect(Rect(0, 0, mSize.width, mSize.height));
}
return true;
}
void
DrawTargetCG::Flush()
{
CGContextFlush(mCg);
}
bool
DrawTargetCG::Init(CGContextRef cgContext, const IntSize &aSize)
{
// XXX: we should come up with some consistent semantics for dealing
// with zero area drawtargets
if (aSize.width == 0 || aSize.height == 0) {
mColorSpace = nullptr;
mCg = nullptr;
mData = nullptr;
return false;
}
//XXX: handle SurfaceFormat
//XXX: we'd be better off reusing the Colorspace across draw targets
mColorSpace = CGColorSpaceCreateDeviceRGB();
mSize = aSize;
mCg = cgContext;
mData = nullptr;
assert(mCg);
// CGContext's default to have the origin at the bottom left
// so flip it to the top left
CGContextTranslateCTM(mCg, 0, mSize.height);
CGContextScaleCTM(mCg, 1, -1);
//XXX: set correct format
mFormat = FORMAT_B8G8R8A8;
return true;
}
bool
DrawTargetCG::Init(BackendType aType, const IntSize &aSize, SurfaceFormat &aFormat)
{
int stride = aSize.width*4;
// Calling Init with aData == nullptr will allocate.
return Init(aType, nullptr, aSize, stride, aFormat);
}
TemporaryRef<PathBuilder>
DrawTargetCG::CreatePathBuilder(FillRule aFillRule) const
{
RefPtr<PathBuilderCG> pb = new PathBuilderCG(aFillRule);
return pb;
}
void*
DrawTargetCG::GetNativeSurface(NativeSurfaceType aType)
{
if (aType == NATIVE_SURFACE_CGCONTEXT && GetContextType(mCg) == CG_CONTEXT_TYPE_BITMAP ||
aType == NATIVE_SURFACE_CGCONTEXT_ACCELERATED && GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE) {
return mCg;
} else {
return nullptr;
}
}
void
DrawTargetCG::Mask(const Pattern &aSource,
const Pattern &aMask,
const DrawOptions &aDrawOptions)
{
MarkChanged();
CGContextSaveGState(mCg);
if (isGradient(aMask)) {
assert(0);
} else {
if (aMask.GetType() == PATTERN_COLOR) {
DrawOptions drawOptions(aDrawOptions);
const Color& color = static_cast<const ColorPattern&>(aMask).mColor;
drawOptions.mAlpha *= color.a;
assert(0);
// XXX: we need to get a rect that when transformed covers the entire surface
//Rect
//FillRect(rect, aSource, drawOptions);
} else if (aMask.GetType() == PATTERN_SURFACE) {
const SurfacePattern& pat = static_cast<const SurfacePattern&>(aMask);
CGImageRef mask = GetImageFromSourceSurface(pat.mSurface.get());
Rect rect(0,0, CGImageGetWidth(mask), CGImageGetHeight(mask));
// XXX: probably we need to do some flipping of the image or something
CGContextClipToMask(mCg, RectToCGRect(rect), mask);
FillRect(rect, aSource, aDrawOptions);
}
}
CGContextRestoreGState(mCg);
}
void
DrawTargetCG::PushClipRect(const Rect &aRect)
{
CGContextSaveGState(mCg);
/* We go through a bit of trouble to temporarilly set the transform
* while we add the path */
CGAffineTransform previousTransform = CGContextGetCTM(mCg);
CGContextConcatCTM(mCg, GfxMatrixToCGAffineTransform(mTransform));
CGContextClipToRect(mCg, RectToCGRect(aRect));
CGContextSetCTM(mCg, previousTransform);
}
void
DrawTargetCG::PushClip(const Path *aPath)
{
CGContextSaveGState(mCg);
CGContextBeginPath(mCg);
assert(aPath->GetBackendType() == BACKEND_COREGRAPHICS);
const PathCG *cgPath = static_cast<const PathCG*>(aPath);
// Weirdly, CoreGraphics clips empty paths as all shown
// but emtpy rects as all clipped. We detect this situation and
// workaround it appropriately
if (CGPathIsEmpty(cgPath->GetPath())) {
// XXX: should we return here?
CGContextClipToRect(mCg, CGRectZero);
}
/* We go through a bit of trouble to temporarilly set the transform
* while we add the path. XXX: this could be improved if we keep
* the CTM as resident state on the DrawTarget. */
CGContextSaveGState(mCg);
CGContextConcatCTM(mCg, GfxMatrixToCGAffineTransform(mTransform));
CGContextAddPath(mCg, cgPath->GetPath());
CGContextRestoreGState(mCg);
if (cgPath->GetFillRule() == FILL_EVEN_ODD)
CGContextEOClip(mCg);
else
CGContextClip(mCg);
}
void
DrawTargetCG::PopClip()
{
CGContextRestoreGState(mCg);
}
void
DrawTargetCG::MarkChanged()
{
if (mSnapshot) {
if (mSnapshot->refCount() > 1) {
// We only need to worry about snapshots that someone else knows about
mSnapshot->DrawTargetWillChange();
}
mSnapshot = nullptr;
}
}
}
}
| 30.878366 | 162 | 0.701618 | [
"vector",
"transform"
] |
84c586257c935402c8abeb6553182c2ed0c08618 | 33,547 | cpp | C++ | Slimfish/Marching Cubes/ChunkManager.cpp | ThatBeanBag/Slimfish | 7b0f821bccf2cae7d67f8a822f078def7a2d354d | [
"Apache-2.0"
] | null | null | null | Slimfish/Marching Cubes/ChunkManager.cpp | ThatBeanBag/Slimfish | 7b0f821bccf2cae7d67f8a822f078def7a2d354d | [
"Apache-2.0"
] | null | null | null | Slimfish/Marching Cubes/ChunkManager.cpp | ThatBeanBag/Slimfish | 7b0f821bccf2cae7d67f8a822f078def7a2d354d | [
"Apache-2.0"
] | null | null | null | //
// Bachelor of Software Engineering
// Media Design School
// Auckland
// New Zealand
//
// (c) 2005 - 2015 Media Design School
//
// File Name : ChunkManager.cpp
// Description : CChunkManager implementation file.
// Author : Hayden Asplet.
// Mail : hayden.asplet@mediadesignschool.com
//
// PCH
#include "MarchingCubesStd.h"
// Library Includes
// This Include
#include "ChunkManager.h"
// Local Includes
#include <Math\SlimAxisAlignedBoundingBox.h>
#include <Graphics\SlimRenderer.h>
#include "Tables.h"
int SmartDivision(int x, int y)
{
if (x < 0) {
return -static_cast<int>((-x + y - 1) / static_cast<float>(y));
}
return static_cast<int>(x / static_cast<float>(y));
}
int SmartModulus(int x, int y)
{
if (x < 0) {
int n = static_cast<int>(-x / static_cast<float>(y));
x += y * (n + 3);
}
return x % y;
}
int RoundUp(float x)
{
return static_cast<int>(std::ceilf(x));
}
std::string ToString(const CVector3& position)
{
std::ostringstream ss;
ss << position.GetX() << " " << position.GetY() << " " << position.GetZ();
return ss.str();
}
const std::array<int, CChunkManager::s_NUM_LOD> CChunkManager::s_CHUNK_SIZES = { 5, 10, 20 };
const std::array<float, CChunkManager::s_NUM_LOD> CChunkManager::s_LOD_DISTANCE_BIASES = { 1.0f, 0.7f, 0.5f };
CChunkManager::CChunkManager()
:m_FreeBufferIDs(s_NUM_BUFFERS),
m_VoxelDim(33),
m_VoxelMargins(4),
m_WireFrame(false),
m_RenderPoints(false),
m_AmboEnabled(true),
m_EnableShadows(true)
{
for (size_t i = 0; i < m_FreeBufferIDs.size(); ++i) {
m_FreeBufferIDs[i] = i;
}
}
CChunkManager::~CChunkManager()
{
}
bool CChunkManager::Initialise()
{
// Build vertex declarations.
m_QuadVertexDeclaration.AddElement("POSITION", CInputElement::FORMAT_FLOAT3);
m_QuadVertexDeclaration.AddElement("TEXCOORD", CInputElement::FORMAT_FLOAT2);
m_DummyCornersVertexDeclaration.AddElement("POSITION", CInputElement::FORMAT_FLOAT2);
m_DummyCornersVertexDeclaration.AddElement("POSITION", CInputElement::FORMAT_FLOAT2);
m_NonEmptyCellListVertexDeclaration.AddElement("TEX", CInputElement::FORMAT_UINT);
m_VertexListVertexDeclaration.AddElement("TEX", CInputElement::FORMAT_UINT);
m_ChunkVertexDeclaration.AddElement("POSITION", CInputElement::FORMAT_FLOAT4);
m_ChunkVertexDeclaration.AddElement("NORMAL", CInputElement::FORMAT_FLOAT3);
// Create geometry.
BuildQuad();
BuildDummyCorners();
BuildStreamOutputBuffers();
CreateRenderTextures();
// Create render passes.
CreateBuildDensitiesPass();
SLIM_INFO() << "Finished BuildDensitiesPass.";
CreateListNonEmptyCellsPass();
SLIM_INFO() << "Finished ListNonEmptyCellsPass.";
CreateListVerticesPass();
SLIM_INFO() << "Finished ListVerticesPass.";
CreateSplatVertexIDsPass();
SLIM_INFO() << "Finished SplatVertexIDsPass.";
CreateGenerateVerticesPass();
SLIM_INFO() << "Finished GenerateVerticesPass.";
CreateGenerateIndicesPass();
SLIM_INFO() << "Finished GenerateIndicesPass.";
CreateDrawDepthPass();
SLIM_INFO() << "Finished DrawDepthPass.";
CreateDrawChunkPass();
SLIM_INFO() << "Finished DrawChunkPass.";
// Setup shader parameters.
// Set the tables on the generate indices geometry shader.
auto pTableBuffer = m_GenerateIndicesPass.GetGeometryShader()->GetShaderParams("CBTables");
pTableBuffer->SetConstant("gEdgeStart", Tables::g_EDGE_START[0], Tables::GetSize(Tables::g_EDGE_START));
pTableBuffer->SetConstant("gEdgeAxis", Tables::g_EDGE_AXIS[0], Tables::GetSize(Tables::g_EDGE_AXIS));
pTableBuffer->SetConstant("gTriTable", Tables::g_TRI_TABLE[0], Tables::GetSize(Tables::g_TRI_TABLE));
m_GenerateIndicesPass.GetGeometryShader()->UpdateShaderParams("CBTables", pTableBuffer);
// Set the tables on the generate vertices vertex shader.
pTableBuffer = m_GenerateVerticesPass.GetVertexShader()->GetShaderParams("CBTables");
pTableBuffer->SetConstant("gEdgeStart", Tables::g_EDGE_START[0], Tables::GetSize(Tables::g_EDGE_START));
pTableBuffer->SetConstant("gEdgeEnd", Tables::g_EDGE_END[0], Tables::GetSize(Tables::g_EDGE_END));
m_GenerateVerticesPass.GetVertexShader()->UpdateShaderParams("CBTables", pTableBuffer);
pTableBuffer = m_GenerateVerticesPass.GetVertexShader()->GetShaderParams("CBAmbientOcclusion");
pTableBuffer->SetConstant("gAmboDistance", Tables::g_AMBO_DISTANCE[0], Tables::GetSize(Tables::g_AMBO_DISTANCE));
pTableBuffer->SetConstant("gOcclusion", Tables::g_AMBO_OCCLUSION[0], Tables::GetSize(Tables::g_AMBO_OCCLUSION));
pTableBuffer->SetConstant("gRayDirections", Tables::g_AMBO_RAY_DIRECTIONS[0], Tables::GetSize(Tables::g_AMBO_RAY_DIRECTIONS));
m_GenerateVerticesPass.GetVertexShader()->UpdateShaderParams("CBAmbientOcclusion", pTableBuffer);
m_pLodParams = m_BuildDensitiesPass.GetVertexShader()->GetShaderParams("CBLod");
m_BuildDensitiesPass.GetVertexShader()->GetShaderParams("CBLod");
m_BuildDensitiesPass.GetPixelShader()->GetShaderParams("CBLod");
m_ListNonEmptyCellsPass.GetVertexShader()->GetShaderParams("CBLod");
m_SplatVertexIDsPass.GetVertexShader()->GetShaderParams("CBLod");
m_GenerateVerticesPass.GetVertexShader()->GetShaderParams("CBLod");
m_GenerateIndicesPass.GetGeometryShader()->GetShaderParams("CBLod");
m_pChunkParams = m_BuildDensitiesPass.GetVertexShader()->GetShaderParams("CBChunk");
m_BuildDensitiesPass.GetVertexShader()->GetShaderParams("CBChunk");
m_GenerateVerticesPass.GetVertexShader()->GetShaderParams("CBChunk");
// Set the lod parameters of the chunk.
m_pLodParams->SetConstant("gVoxelDim", static_cast<float>(m_VoxelDim));
m_pLodParams->SetConstant("gVoxelDimMinusOne", static_cast<float>(m_VoxelDim - 1));
m_pLodParams->SetConstant("gWVoxelSize", static_cast<float>(s_CHUNK_SIZES[0]) / static_cast<float>(m_VoxelDim - 1));
m_pLodParams->SetConstant("gWChunkSize", static_cast<float>(s_CHUNK_SIZES[0]));
m_pLodParams->SetConstant("gInvVoxelDim", 1.0f / static_cast<float>(m_VoxelDim));
m_pLodParams->SetConstant("gInvVoxelDimMinusOne", 1 / static_cast<float>(m_VoxelDim - 1));
m_pLodParams->SetConstant("gMargin", static_cast<float>(m_VoxelMargins));
m_pLodParams->SetConstant("gVoxelDimPlusMargins", static_cast<float>(m_VoxelDim + m_VoxelMargins));
m_pLodParams->SetConstant("gVoxelDimPlusMarginsMinusOne", static_cast<float>(m_VoxelDim + m_VoxelMargins - 1));
m_pLodParams->SetConstant("gInvVoxelDimPlusMargins", 1.0f / static_cast<float>(m_VoxelDim + m_VoxelMargins));
m_pLodParams->SetConstant("gInvVoxelDimPlusMarginsMinusOne", 1.0f / static_cast<float>(m_VoxelDim + m_VoxelMargins - 1));
// Update all the CBLod buffers for shaders that use it.
m_BuildDensitiesPass.GetVertexShader()->UpdateShaderParams("CBLod", m_pLodParams);
m_BuildDensitiesPass.GetPixelShader()->UpdateShaderParams("CBLod", m_pLodParams);
m_ListNonEmptyCellsPass.GetVertexShader()->UpdateShaderParams("CBLod", m_pLodParams);
m_SplatVertexIDsPass.GetVertexShader()->UpdateShaderParams("CBLod", m_pLodParams);
m_GenerateVerticesPass.GetVertexShader()->UpdateShaderParams("CBLod", m_pLodParams);
m_GenerateIndicesPass.GetGeometryShader()->UpdateShaderParams("CBLod", m_pLodParams);
m_pWVPParams = m_DrawChunkPass.GetVertexShader()->GetShaderParams("CBPerFrame");
m_pLightingParams = m_DrawChunkPass.GetPixelShader()->GetShaderParams("CBLighting");
if (m_AmboEnabled) {
m_pLightingParams->SetConstant("gAmbientOcclusionInfluence", 1.0f);
}
else {
m_pLightingParams->SetConstant("gAmbientOcclusionInfluence", 0.0f);
}
return true;
}
void CChunkManager::Update(const CCamera& camera)
{
// Only need to update visible chunks if the camera has moved or rotated.
if (camera.GetRotation() != m_CameraRotation || camera.GetPosition() != m_CameraPosition) {
m_CameraRotation = camera.GetRotation();
m_CameraPosition = camera.GetPosition();
auto cameraDirection = m_CameraRotation.GetDirection();
// Invalidate the visibility of all chunks as we prepare to update the visibilities.
m_VisibleChunkList.clear();
for (int lod = 0; lod < 1; ++lod) {
int chunkSize = s_CHUNK_SIZES[lod];
// Get the centre of the array of chunks for this lod that we are interested in.
// This is so that the centre of the chunks is in front of the camera and not behind
// where they wouldn't be seen.
auto chunkCentre = m_CameraPosition + (cameraDirection * static_cast<float>(chunkSize * s_NUM_CHUNKS_PER_DIM) * 0.5f);
CVector3 chunkCentreInt(
static_cast<float>(SmartDivision(RoundUp(chunkCentre.GetX()), chunkSize)),
static_cast<float>(SmartDivision(RoundUp(chunkCentre.GetY()), chunkSize)),
static_cast<float>(SmartDivision(RoundUp(chunkCentre.GetZ()), chunkSize))
);
int ib = SmartDivision(static_cast<int>(chunkCentreInt.GetX() - s_NUM_CHUNKS_PER_DIM / 2.0f), s_NUM_CHUNKS_PER_DIM) * s_NUM_CHUNKS_PER_DIM;
int jb = SmartDivision(static_cast<int>(chunkCentreInt.GetY() - s_NUM_CHUNKS_PER_DIM / 2.0f), s_NUM_CHUNKS_PER_DIM) * s_NUM_CHUNKS_PER_DIM;
int kb = SmartDivision(static_cast<int>(chunkCentreInt.GetZ() - s_NUM_CHUNKS_PER_DIM / 2.0f), s_NUM_CHUNKS_PER_DIM) * s_NUM_CHUNKS_PER_DIM;
// Loop through all the chunks in the 3D array for this lod.
for (int i = 0; i < s_NUM_CHUNKS_PER_DIM; ++i) {
for (int j = 0; j < s_NUM_CHUNKS_PER_DIM; ++j) {
for (int k = 0; k < s_NUM_CHUNKS_PER_DIM; ++k) {
CVector3 chunkPosition = GetChunkPosition(i, j, k, chunkCentreInt, chunkSize, ib, jb, kb);
CVector3 chunkPositionMin = chunkPosition - chunkSize * 0.5f;
CVector3 chunkPositionCentre = chunkPosition + chunkSize * 0.5f;
CVector3 chunkPositionMax = chunkPosition + chunkSize * 1.5f;
// Check to see if the chunk is in the view frustum.
//bool isInView = true;
bool isInView = camera.IsInView(CAxisAlignedBoundingBox(chunkPositionMin, chunkPositionMax));
auto& chunkInfo = m_Chunks[lod][i][j][k];
if (!isInView || chunkInfo.position != chunkPosition) {
ClearChunk(chunkInfo);
}
if (!isInView) {
chunkInfo.distanceFromCameraSqr = std::numeric_limits<float>::max();
}
else {
CVector3 toChunk = chunkPositionCentre - m_CameraPosition;
chunkInfo.position = chunkPosition;
chunkInfo.distanceFromCameraSqr = toChunk.GetLengthSquared() * s_LOD_DISTANCE_BIASES[lod];
chunkInfo.isVisible = true;
chunkInfo.lod = lod;
m_VisibleChunkList.push_back(&chunkInfo);
}
}
}
}
}
// Sort the chunks in terms of distance from camera.
auto lessDistanceFromCamera = [](const TChunkInfo* plhs, const TChunkInfo* prhs) {
return plhs->distanceFromCameraSqr < prhs->distanceFromCameraSqr;
};
std::sort(m_VisibleChunkList.begin(), m_VisibleChunkList.end(), lessDistanceFromCamera);
}
BuildChunks();
}
void CChunkManager::BuildChunks()
{
// Build chunks.
int numChunks = m_VisibleChunkList.size();
int numWorkThisFrame = 0;
int lowestPriorityChunk = numChunks - 1;
for (int i = 0; i < numChunks && numWorkThisFrame < s_MAX_WORK_PER_FRAME - s_WORK_FOR_EMPTY_CHUNK; ++i) {
auto pChunkInfo = m_VisibleChunkList[i];
if (!pChunkInfo || pChunkInfo->bufferID >= 0 || pChunkInfo->hasPolys == false) {
// This chunk already has an id or has no polys, so no need to build it.
continue;
}
int bufferID = -1;
if (!m_FreeBufferIDs.empty()) {
bufferID = m_FreeBufferIDs.back();
m_FreeBufferIDs.pop_back();
}
else {
// Out of buffers.
// Try find a far away chunk and steal for the higher priority chunk.
while (lowestPriorityChunk > i) {
auto pLowestPriorityChunkInfo = m_VisibleChunkList[lowestPriorityChunk];
lowestPriorityChunk--;
if (pLowestPriorityChunkInfo->bufferID >= 0) {
bufferID = pLowestPriorityChunkInfo->bufferID;
pLowestPriorityChunkInfo->bufferID = -1;
break;
}
}
if (bufferID == -1) {
// Failed to get a buffer to generate chunk to.
// Clip off the rest of chunks as they aren't built for drawing.
m_VisibleChunkList.resize(i);
// Stop building chunks.
break;
}
}
pChunkInfo->bufferID = bufferID;
if (!BuildChunk(*pChunkInfo)) {
ClearChunk(*pChunkInfo);
pChunkInfo->hasPolys = false;
numWorkThisFrame += s_WORK_FOR_EMPTY_CHUNK;
}
else {
pChunkInfo->hasPolys = true;
numWorkThisFrame += s_WORK_FOR_NONEMPTY_CHUNK;
}
}
/*auto isNull = [](const TChunkInfo* pChunkInfo) {
return pChunkInfo == nullptr;
};
auto iter = std::remove_if(m_VisibleChunkList.begin(), m_VisibleChunkList.end(), isNull);
if (iter != m_VisibleChunkList.end()) {
m_VisibleChunkList.erase(iter);
}*/
}
void CChunkManager::ToggleAmbientOcclusionEnabled()
{
m_AmboEnabled = !m_AmboEnabled;
if (m_AmboEnabled) {
m_pLightingParams->SetConstant("gAmbientOcclusionInfluence", 1.0f);
}
else {
m_pLightingParams->SetConstant("gAmbientOcclusionInfluence", 0.0f);
}
}
void CChunkManager::ToggleWireFrame()
{
m_WireFrame = !m_WireFrame;
if (m_WireFrame) {
m_DrawChunkPass.SetFillMode(EFillMode::WIREFRAME);
}
else {
m_DrawChunkPass.SetFillMode(EFillMode::SOLID);
}
}
void CChunkManager::ToggleRenderPoints()
{
m_RenderPoints = !m_RenderPoints;
}
void CChunkManager::ToggleShadows()
{
m_EnableShadows = !m_EnableShadows;
}
void CChunkManager::DrawShadowMap(const CCamera& lightCamera)
{
// Update parameters.
m_pDrawDepthParams->SetConstant("gWorldViewProjectionMatrix", lightCamera.GetViewProjMatrix());
m_pDrawDepthParams->SetConstant("gZFar", lightCamera.GetFarClipDistance());
m_DrawDepthRenderPass.GetVertexShader()->UpdateShaderParams("CBPerFrame", m_pDrawDepthParams);
auto pRenderer = g_pApp->GetRenderer();
pRenderer->SetRenderPass(&m_DrawDepthRenderPass);
for (auto& chunk : m_VisibleChunkList) {
if (chunk) {
auto bufferID = chunk->bufferID;
if (bufferID >= 0) {
// Draw the mesh.
auto& pVertexBuffer = m_ChunkBuffers[bufferID].pVertexBuffer;
auto& pIndexBuffer = m_ChunkBuffers[bufferID].pIndexBuffer;
auto numIndices = m_ChunkBuffers[bufferID].numIndices;
pRenderer->VRender(m_ChunkVertexDeclaration, EPrimitiveType::TRIANGLELIST, pVertexBuffer, pIndexBuffer, numIndices);
}
}
}
}
void CChunkManager::DrawChunks(const CCamera& camera, const CCamera& lightCamera, const CLight& light)
{
auto pRenderer = g_pApp->GetRenderer();
if (m_EnableShadows) {
DrawShadowMap(lightCamera);
}
else {
// Clear the shadow map with in a really inefficient way.
pRenderer->SetRenderPass(&m_DrawDepthRenderPass);
}
// Update parameters.
m_pLightingParams->SetConstant("gLight.type", light.GetType());
m_pLightingParams->SetConstant("gLight.diffuse", light.GetDiffuse());
m_pLightingParams->SetConstant("gLight.specular", light.GetSpecular());
m_pLightingParams->SetConstant("gLight.direction", light.GetRotation().GetDirection());
m_pLightingParams->SetConstant("gLight.range", light.GetRange());
m_pLightingParams->SetConstant("gLight.attenuation", light.GetAttenuation());
m_pLightingParams->SetConstant("gFogStart", 60.0f);
m_pLightingParams->SetConstant("gFogRange", 5.0f);
m_pLightingParams->SetConstant("gFogColour", CColourValue(0.36862f, 0.36862f, 0.43137f));
m_pLightingParams->SetConstant("gAmbientLight", CColourValue(0.5f, 0.5f, 0.5f));
m_pLightingParams->SetConstant("gEyePosition", camera.GetPosition());
m_DrawChunkPass.GetPixelShader()->UpdateShaderParams("CBLighting", m_pLightingParams);
m_pWVPParams->SetConstant("gViewProjectionMatrix", camera.GetViewProjMatrix());
m_pWVPParams->SetConstant("gLightViewProjectionMatrix", lightCamera.GetViewProjMatrix());
m_DrawChunkPass.GetVertexShader()->UpdateShaderParams("CBPerFrame", m_pWVPParams);
pRenderer->SetRenderPass(&m_DrawChunkPass);
for (auto& chunk : m_VisibleChunkList) {
if (!chunk) {
continue;
}
auto bufferID = chunk->bufferID;
if (bufferID >= 0) {
// Not doing this at the moment as we are not using the different lods.
//// Set the lod parameters of the chunk.
//m_pLodParams->SetConstant("gWVoxelSize", static_cast<float>(s_CHUNK_SIZES[chunk->lod]) / static_cast<float>(m_VoxelDim - 1));
//m_pLodParams->SetConstant("gWChunkSize", static_cast<float>(s_CHUNK_SIZES[chunk->lod]));
//
//// Update all the CBLod buffers for shaders that use it.
//m_BuildDensitiesPass.GetVertexShader()->UpdateShaderParams("CBLod", m_pLodParams);
//m_BuildDensitiesPass.GetPixelShader()->UpdateShaderParams("CBLod", m_pLodParams);
//m_ListNonEmptyCellsPass.GetVertexShader()->UpdateShaderParams("CBLod", m_pLodParams);
//m_SplatVertexIDsPass.GetVertexShader()->UpdateShaderParams("CBLod", m_pLodParams);
//m_GenerateVerticesPass.GetVertexShader()->UpdateShaderParams("CBLod", m_pLodParams);
//m_GenerateIndicesPass.GetGeometryShader()->UpdateShaderParams("CBLod", m_pLodParams);
// Draw the mesh.
auto& pVertexBuffer = m_ChunkBuffers[bufferID].pVertexBuffer;
auto& pIndexBuffer = m_ChunkBuffers[bufferID].pIndexBuffer;
auto numIndices = m_ChunkBuffers[bufferID].numIndices;
if (!m_RenderPoints) {
pRenderer->VRender(m_ChunkVertexDeclaration, EPrimitiveType::TRIANGLELIST, pVertexBuffer, pIndexBuffer, numIndices);
}
else {
pRenderer->VRender(m_ChunkVertexDeclaration, EPrimitiveType::POINTLIST, pVertexBuffer, pIndexBuffer, numIndices);
}
}
}
}
std::shared_ptr<ATexture> CChunkManager::GetShadowMap()
{
return m_pShadowMapRenderTarget->GetTexture();
}
void CChunkManager::ClearChunk(TChunkInfo& chunkInfo)
{
if (chunkInfo.bufferID >= 0) {
m_FreeBufferIDs.push_back(chunkInfo.bufferID);
}
chunkInfo.bufferID = -1;
chunkInfo.hasPolys = true; // This chunk may or may not have polys.
}
bool CChunkManager::BuildChunk(TChunkInfo& chunkInfo)
{
auto pRenderer = g_pApp->GetRenderer();
// Update shader parameters
m_pChunkParams->SetConstant("gWChunkPosition", chunkInfo.position);
// Update CBChunk for the shaders that use it.
m_BuildDensitiesPass.GetVertexShader()->UpdateShaderParams("CBChunk", m_pChunkParams);
m_BuildDensitiesPass.GetPixelShader()->UpdateShaderParams("CBChunk", m_pChunkParams);
m_GenerateVerticesPass.GetVertexShader()->UpdateShaderParams("CBChunk", m_pChunkParams);
m_ListNonEmptyCellsPass.GetVertexShader()->UpdateShaderParams("CBChunk", m_pChunkParams);
// Set the stream output buffers.
auto& pVertexBuffer = m_ChunkBuffers[chunkInfo.bufferID].pVertexBuffer;
auto& pIndexBuffer = m_ChunkBuffers[chunkInfo.bufferID].pIndexBuffer;
m_GenerateVerticesPass.ClearStreamOutputTargets();
m_GenerateIndicesPass.ClearStreamOutputTargets();
m_GenerateVerticesPass.AddStreamOutputTarget(pVertexBuffer);
m_GenerateIndicesPass.AddStreamOutputTarget(pIndexBuffer);
// Create the density volume.
pRenderer->SetRenderPass(&m_BuildDensitiesPass);
// Render multiple times, one for each slice of the volume texture.
pRenderer->VRender(m_QuadVertexDeclaration, EPrimitiveType::TRIANGLESTRIP, m_pQuadVertices, m_pQuadIndices, 0, m_VoxelDim + m_VoxelMargins);
pRenderer->VBeginStreamOutQuery();
// List non empty cells.
pRenderer->SetRenderPass(&m_ListNonEmptyCellsPass);
pRenderer->VRender(m_DummyCornersVertexDeclaration, EPrimitiveType::POINTLIST, m_pDummyCornersVertices, nullptr, 0, m_VoxelDim);
auto numCells = pRenderer->VEndStreamOutQuery();
// Early out if there's no polygons for this chunk to produce.
if (numCells <= 0) {
ClearChunk(chunkInfo);
return false;
}
// List vertices.
pRenderer->VBeginStreamOutQuery();
pRenderer->SetRenderPass(&m_ListVerticesPass);
pRenderer->VRender(m_NonEmptyCellListVertexDeclaration, EPrimitiveType::POINTLIST, m_pNonEmptyCellListVertices, nullptr, numCells);
auto numVerts = pRenderer->VEndStreamOutQuery();
// Splat vertex IDs.
pRenderer->SetRenderPass(&m_SplatVertexIDsPass);
pRenderer->VRender(m_VertexListVertexDeclaration, EPrimitiveType::POINTLIST, m_pVertexListVertices, nullptr, numVerts);
// Generate vertices
pRenderer->SetRenderPass(&m_GenerateVerticesPass);
pRenderer->VRender(m_VertexListVertexDeclaration, EPrimitiveType::POINTLIST, m_pVertexListVertices, nullptr, numVerts);
// Generate indices.
pRenderer->VBeginStreamOutQuery();
pRenderer->SetRenderPass(&m_GenerateIndicesPass);
pRenderer->VRender(m_NonEmptyCellListVertexDeclaration, EPrimitiveType::POINTLIST, m_pNonEmptyCellListVertices, nullptr, numCells);
m_ChunkBuffers[chunkInfo.bufferID].numIndices = pRenderer->VEndStreamOutQuery() * 3;
return true;
}
void CChunkManager::BuildQuad()
{
std::vector<TQuadVertex> vertices = {
TQuadVertex{ CVector3(-1.0f, 1.0f, 0.5f), CVector2(0, 1) },
TQuadVertex{ CVector3(-1.0f, -1.0f, 0.5f), CVector2(0, 0) },
TQuadVertex{ CVector3(1.0f, 1.0f, 0.5f), CVector2(1, 1) },
TQuadVertex{ CVector3(1.0f, -1.0f, 0.5f), CVector2(1, 0) }
};
std::vector<int> indices = { 0, 2, 1, 3 };
m_pQuadVertices = g_pApp->GetRenderer()->CreateVertexBuffer(vertices);
m_pQuadIndices = g_pApp->GetRenderer()->CreateIndexBuffer(indices);
}
void CChunkManager::BuildDummyCorners()
{
std::vector<CVector2> writeUVs;
std::vector<CVector2> readUVs;
std::vector<TDummyCornerVertex> dummyCorners(m_VoxelDim * m_VoxelDim);
for (auto i = 0U; i < m_VoxelDim; ++i) {
for (auto j = 0U; j < m_VoxelDim; ++j) {
dummyCorners[j + i * m_VoxelDim].writeUV = {
i / static_cast<float>(m_VoxelDim - 1),
j / static_cast<float>(m_VoxelDim - 1)
};
dummyCorners[j + i * m_VoxelDim].readUV = {
(m_VoxelMargins + i) / static_cast<float>(m_VoxelDim + m_VoxelMargins - 1),
(m_VoxelMargins + j) / static_cast<float>(m_VoxelDim + m_VoxelMargins - 1)
};
}
}
/*AddPointsSwizzled(writeUVs,
0,
m_VoxelDim - 1,
0,
m_VoxelDim - 1,
m_VoxelDim,
m_VoxelDim);
AddPointsSwizzled(readUVs,
m_VoxelMargins,
m_VoxelDim + m_VoxelMargins - 1,
m_VoxelMargins,
m_VoxelDim + m_VoxelMargins - 1,
m_VoxelDim + m_VoxelMargins,
m_VoxelDim + m_VoxelMargins);
for (size_t i = 0; i < dummyCorners.size(); ++i) {
dummyCorners[i].writeUV = writeUVs[i];
dummyCorners[i].readUV = readUVs[i];
}*/
m_pDummyCornersVertices = g_pApp->GetRenderer()->CreateVertexBuffer(dummyCorners);
}
void CChunkManager::BuildStreamOutputBuffers()
{
m_pNonEmptyCellListVertices = g_pApp->GetRenderer()->VCreateVertexBuffer(
64000, sizeof(int), nullptr, EGpuBufferUsage::STATIC, true);
m_pVertexListVertices = g_pApp->GetRenderer()->VCreateVertexBuffer(
64000, sizeof(int), nullptr, EGpuBufferUsage::STATIC, true);
for (auto& buffer : m_ChunkBuffers) {
buffer.pVertexBuffer = g_pApp->GetRenderer()->VCreateVertexBuffer(
m_VoxelDim * 300, sizeof(TChunkVertex), nullptr, EGpuBufferUsage::STATIC, true);
buffer.pIndexBuffer = g_pApp->GetRenderer()->VCreateIndexBuffer(
m_VoxelDim * 300 * 6, AIndexGpuBuffer::INDEX_TYPE_32, nullptr, EGpuBufferUsage::STATIC, true);
}
}
void CChunkManager::CreateRenderTextures()
{
auto pDensityTexture = g_pApp->GetRenderer()->VCreateTexture("DensityTexture");
pDensityTexture->SetWidth(m_VoxelDim + m_VoxelMargins);
pDensityTexture->SetHeight(m_VoxelDim + m_VoxelMargins);
pDensityTexture->SetDepth(m_VoxelDim + m_VoxelMargins);
pDensityTexture->SetTextureType(ETextureType::TYPE_3D);
pDensityTexture->SetUsage(ETextureUsage::RENDER_TARGET);
pDensityTexture->SetPixelFormat(ETexturePixelFormat::FLOAT_32_R);
pDensityTexture->VLoad();
m_pDensityRenderTarget = g_pApp->GetRenderer()->VCreateRenderTexture(pDensityTexture);
auto pVertexIDsTexture = g_pApp->GetRenderer()->VCreateTexture("VertexIDsTextures");
pVertexIDsTexture->SetWidth(m_VoxelDim * 3);
pVertexIDsTexture->SetHeight(m_VoxelDim);
pVertexIDsTexture->SetDepth(m_VoxelDim);
pVertexIDsTexture->SetTextureType(ETextureType::TYPE_3D);
pVertexIDsTexture->SetUsage(ETextureUsage::RENDER_TARGET);
pVertexIDsTexture->SetPixelFormat(ETexturePixelFormat::UINT_32_R);
pVertexIDsTexture->VLoad();
m_pVertexIDRenderTarget = g_pApp->GetRenderer()->VCreateRenderTexture(pVertexIDsTexture);
// Create the shadow map render target.
m_pShadowMapRenderTarget = g_pApp->GetRenderer()->VCreateRenderTexture(
"ShadowMap", s_SHADOW_MAP_WIDTH, s_SHADOW_MAP_HEIGHT);
m_pShadowMapRenderTarget->SetBackgroundColour(CColourValue::s_WHITE);
}
void CChunkManager::CreateBuildDensitiesPass()
{
// Set shaders.
m_BuildDensitiesPass.SetVertexShader(g_pApp->GetRenderer()->VCreateShaderProgram("Density_VS.hlsl", EShaderProgramType::VERTEX, "main", "vs_4_0"));
m_BuildDensitiesPass.SetPixelShader(g_pApp->GetRenderer()->VCreateShaderProgram("Density_PS.hlsl", EShaderProgramType::PIXEL, "main", "ps_4_0"));
m_BuildDensitiesPass.SetGeometryShader(g_pApp->GetRenderer()->VCreateShaderProgram("Density_GS.hlsl", EShaderProgramType::GEOMETRY, "main", "gs_4_0"));
std::vector<CColourValue> randomData(s_NOISE_VOLUME_DIM * s_NOISE_VOLUME_DIM * s_NOISE_VOLUME_DIM);
auto randomize = [](std::vector<CColourValue>& randomData) {
for (auto& val : randomData) {
val = { Math::Random(), Math::Random(), Math::Random(), Math::Random() };
}
};
// Build the noise volumes.
for (auto& pNoiseVolume : m_NoiseVolumes) {
randomize(randomData);
pNoiseVolume = g_pApp->GetRenderer()->VCreateTexture("NoiseVolume0");
pNoiseVolume->SetPixelFormat(ETexturePixelFormat::FLOAT_32_RGBA);
pNoiseVolume->SetTextureType(ETextureType::TYPE_3D);
pNoiseVolume->SetDimensions(s_NOISE_VOLUME_DIM, s_NOISE_VOLUME_DIM, s_NOISE_VOLUME_DIM);
pNoiseVolume->LoadRaw(randomData);
m_BuildDensitiesPass.AddTextureLayer(pNoiseVolume)->SetTextureFilter(ETextureFilterTypeBroad::TRILINEAR);
}
m_BuildDensitiesPass.AddRenderTarget(m_pDensityRenderTarget.get());
}
void CChunkManager::CreateListNonEmptyCellsPass()
{
// Set shaders.
m_ListNonEmptyCellsPass.SetVertexShader(g_pApp->GetRenderer()->VCreateShaderProgram("ListNonEmptyCells_VS.hlsl", EShaderProgramType::VERTEX, "main", "vs_4_0"));
m_ListNonEmptyCellsPass.SetGeometryShader(g_pApp->GetRenderer()->VCreateShaderProgram("ListNonEmptyCells_GS.hlsl", EShaderProgramType::GEOMETRY, "main", "gs_4_0"));
// Add texture layers.
auto pDensityTextureLayer = m_ListNonEmptyCellsPass.AddTextureLayer();
pDensityTextureLayer->SetTexture(m_pDensityRenderTarget->GetTexture());
pDensityTextureLayer->SetTextureFilter(ETextureFilterType::POINT);
pDensityTextureLayer->SetTextureAddressModes(ETextureAddressMode::CLAMP);
// Set stream output targets.
m_ListNonEmptyCellsPass.AddStreamOutputTarget(m_pNonEmptyCellListVertices);
// Set states.
m_ListNonEmptyCellsPass.SetCullingMode(ECullingMode::NONE);
// Disable depth checks and writes for stream output only.
m_ListNonEmptyCellsPass.SetDepthWriteEnabled(false);
m_ListNonEmptyCellsPass.SetDepthCheckEnabled(false);
m_ListNonEmptyCellsPass.SetColourWritesEnabled(false);
}
void CChunkManager::CreateListVerticesPass()
{
// Set shaders.
m_ListVerticesPass.SetVertexShader(g_pApp->GetRenderer()->VCreateShaderProgram("ListVertices_VS.hlsl", EShaderProgramType::VERTEX, "main", "vs_4_0"));
m_ListVerticesPass.SetGeometryShader(g_pApp->GetRenderer()->VCreateShaderProgram("ListVertices_GS.hlsl", EShaderProgramType::GEOMETRY, "main", "gs_4_0"));
// Add texture layers.
// No texture layers to add.
// Set stream output targets.
m_ListVerticesPass.AddStreamOutputTarget(m_pVertexListVertices);
// Set states.
m_ListVerticesPass.SetCullingMode(ECullingMode::NONE);
// Disable depth checks and writes for stream output only.
m_ListVerticesPass.SetDepthWriteEnabled(false);
m_ListVerticesPass.SetDepthCheckEnabled(false);
m_ListVerticesPass.SetColourWritesEnabled(false);
}
void CChunkManager::CreateSplatVertexIDsPass()
{
// Set shaders.
m_SplatVertexIDsPass.SetVertexShader(g_pApp->GetRenderer()->VCreateShaderProgram("SplatVertexIDs_VS.hlsl", EShaderProgramType::VERTEX, "main", "vs_4_0"));
m_SplatVertexIDsPass.SetGeometryShader(g_pApp->GetRenderer()->VCreateShaderProgram("SplatVertexIDs_GS.hlsl", EShaderProgramType::GEOMETRY, "main", "gs_4_0"));
m_SplatVertexIDsPass.SetPixelShader(g_pApp->GetRenderer()->VCreateShaderProgram("SplatVertexIDs_PS.hlsl", EShaderProgramType::PIXEL, "main", "ps_4_0"));
// Set the render target.
m_SplatVertexIDsPass.AddRenderTarget(m_pVertexIDRenderTarget.get());
// Add texture layers.
// No texture layers to add.
// Set stream output targets.
// This pass renders to a volume instead of streaming out.
// Set states.
m_SplatVertexIDsPass.SetCullingMode(ECullingMode::NONE);
// Disable depth checks and writes for 3D Volume.
m_SplatVertexIDsPass.SetDepthWriteEnabled(false);
m_SplatVertexIDsPass.SetDepthCheckEnabled(false);
}
void CChunkManager::CreateGenerateVerticesPass()
{
// Set shaders.
m_GenerateVerticesPass.SetVertexShader(g_pApp->GetRenderer()->VCreateShaderProgram("GenerateVertices_VS.hlsl", EShaderProgramType::VERTEX, "main", "vs_4_0"));
m_GenerateVerticesPass.SetGeometryShader(g_pApp->GetRenderer()->VCreateShaderProgram("GenerateVertices_GS.hlsl", EShaderProgramType::GEOMETRY, "main", "gs_4_0"));
// Add texture layers.
auto pDensityTextureLayer = m_GenerateVerticesPass.AddTextureLayer();
pDensityTextureLayer->SetTexture(m_pDensityRenderTarget->GetTexture());
pDensityTextureLayer->SetTextureFilter(ETextureFilterType::POINT);
pDensityTextureLayer->SetTextureAddressModes(ETextureAddressMode::CLAMP);
for (auto pNoiseVolume : m_NoiseVolumes) {
m_GenerateVerticesPass.AddTextureLayer(pNoiseVolume)->SetTextureFilter(ETextureFilterType::LINEAR);
}
// Set stream output targets.
// This will be done later as each chunk has vertices that are generated.
// Set states.
m_GenerateVerticesPass.SetCullingMode(ECullingMode::NONE);
// Disable depth checks and writes for stream output only.
m_GenerateVerticesPass.SetDepthWriteEnabled(false);
m_GenerateVerticesPass.SetDepthCheckEnabled(false);
m_GenerateVerticesPass.SetColourWritesEnabled(false);
}
void CChunkManager::CreateGenerateIndicesPass()
{
// Set shaders.
m_GenerateIndicesPass.SetVertexShader(g_pApp->GetRenderer()->VCreateShaderProgram("GenerateIndices_VS.hlsl", EShaderProgramType::VERTEX, "main", "vs_4_0"));
m_GenerateIndicesPass.SetGeometryShader(g_pApp->GetRenderer()->VCreateShaderProgram("GenerateIndices_GS.hlsl", EShaderProgramType::GEOMETRY, "main", "gs_4_0"));
// Add texture layers.
auto pDensityTextureLayer = m_GenerateIndicesPass.AddTextureLayer();
pDensityTextureLayer->SetTexture(m_pVertexIDRenderTarget->GetTexture());
pDensityTextureLayer->SetTextureFilter(ETextureFilterType::POINT);
pDensityTextureLayer->SetTextureAddressModes(ETextureAddressMode::CLAMP);
// Set stream output targets.
// This will be done later as each chunk has indices that are generated.
// Set states.
m_GenerateIndicesPass.SetCullingMode(ECullingMode::NONE);
// Disable depth checks and writes for stream output only.
m_GenerateIndicesPass.SetDepthWriteEnabled(false);
m_GenerateIndicesPass.SetDepthCheckEnabled(false);
m_GenerateIndicesPass.SetColourWritesEnabled(false);
}
void CChunkManager::CreateDrawDepthPass()
{
// Set shaders.
m_DrawDepthRenderPass.SetVertexShader(g_pApp->GetRenderer()->VCreateShaderProgram("DepthOnly_VS.hlsl", EShaderProgramType::VERTEX, "main", "vs_4_0"));
m_DrawDepthRenderPass.SetGeometryShader(g_pApp->GetRenderer()->VCreateShaderProgram("DepthOnly_PS.hlsl", EShaderProgramType::PIXEL, "main", "ps_4_0"));
// Add texture layers.
m_pDrawDepthParams = m_DrawDepthRenderPass.GetVertexShader()->GetShaderParams("CBPerFrame");
// Set stream output targets.
// Set states.
m_DrawDepthRenderPass.AddRenderTarget(m_pShadowMapRenderTarget.get());
}
void CChunkManager::CreateDrawChunkPass()
{
// Set shaders.
m_DrawChunkPass.SetVertexShader(g_pApp->GetRenderer()->VCreateShaderProgram("DrawChunk_VS.hlsl", EShaderProgramType::VERTEX, "main", "vs_4_0"));
m_DrawChunkPass.SetPixelShader(g_pApp->GetRenderer()->VCreateShaderProgram("DrawChunk_PS.hlsl", EShaderProgramType::PIXEL, "main", "ps_4_0"));
// Add texture layers.
auto pShadowMapLayer = m_DrawChunkPass.AddTextureLayer(m_pShadowMapRenderTarget->GetTexture());
pShadowMapLayer->SetTextureFilter(ETextureFilterType::POINT);
pShadowMapLayer->SetTextureAddressModes(ETextureAddressMode::BORDER);
pShadowMapLayer->SetTextureBorderColour(CColourValue::s_WHITE);
m_DrawChunkPass.AddTextureLayer("Textures/GrassDiffuse.png");
m_DrawChunkPass.AddTextureLayer("Textures/StoneDiffuse.png");
m_DrawChunkPass.AddTextureLayer("Textures/StoneDiffuse.png");
m_DrawChunkPass.AddTextureLayer("Textures/GrassNormal.png");
m_DrawChunkPass.AddTextureLayer("Textures/StoneNormal.png");
m_DrawChunkPass.AddTextureLayer("Textures/StoneNormal.png");
// Set stream output targets.
// This the final pass it only uses output from previous passes.
// Set states.
// No states to set, defaults are fine.
}
CVector3 CChunkManager::GetChunkPosition(int i, int j, int k, const CVector3& centreChunkPosition, int chunkSize, int ib, int jb, int kb)
{
static const float s_HalfNumChunkPerDim = s_NUM_CHUNKS_PER_DIM / 2.0f;
int i1 = i + ib;
int j1 = j + jb;
int k1 = k + kb;
if (i < SmartModulus(static_cast<int>(centreChunkPosition.GetX() - s_HalfNumChunkPerDim), s_NUM_CHUNKS_PER_DIM)) {
i1 += s_NUM_CHUNKS_PER_DIM;
}
if (j < SmartModulus(static_cast<int>(centreChunkPosition.GetY() - s_HalfNumChunkPerDim), s_NUM_CHUNKS_PER_DIM)) {
j1 += s_NUM_CHUNKS_PER_DIM;
}
if (k < SmartModulus(static_cast<int>(centreChunkPosition.GetZ() - s_HalfNumChunkPerDim), s_NUM_CHUNKS_PER_DIM)) {
k1 += s_NUM_CHUNKS_PER_DIM;
}
assert(SmartModulus(i1, s_NUM_CHUNKS_PER_DIM) == i);
assert(SmartModulus(j1, s_NUM_CHUNKS_PER_DIM) == j);
assert(SmartModulus(k1, s_NUM_CHUNKS_PER_DIM) == k);
return CVector3(
static_cast<float>(i1 * chunkSize),
static_cast<float>(j1 * chunkSize),
static_cast<float>(k1 * chunkSize));
}
| 39.513545 | 165 | 0.768534 | [
"mesh",
"geometry",
"render",
"vector",
"3d",
"solid"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.