hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dba88550b5a913aafa78706f1d035fa13c634cc4 | 8,051 | cpp | C++ | src/qt/outmessagelistpage.cpp | gtacoin-dev/gtacoin | f66f063b47ba973856c200074db1b95abf5ab794 | [
"MIT"
] | null | null | null | src/qt/outmessagelistpage.cpp | gtacoin-dev/gtacoin | f66f063b47ba973856c200074db1b95abf5ab794 | [
"MIT"
] | null | null | null | src/qt/outmessagelistpage.cpp | gtacoin-dev/gtacoin | f66f063b47ba973856c200074db1b95abf5ab794 | [
"MIT"
] | null | null | null | #include "outmessagelistpage.h"
#include "ui_messagelistpage.h"
#include "guiutil.h"
#include "messagetablemodel.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "newmessagedialog.h"
#include "platformstyle.h"
#include "messageinfodialog.h"
#include "csvmodelwriter.h"
#include "ui_interface.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QKeyEvent>
#include <QSettings>
#include <QMenu>
using namespace std;
OutMessageListPage::OutMessageListPage(const PlatformStyle *platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::MessageListPage),
model(0),
optionsModel(0)
{
ui->setupUi(this);
QString theme = GUIUtil::getThemeName();
if (!platformStyle->getImagesOnButtons())
{
ui->exportButton->setIcon(QIcon());
ui->newMessage->setIcon(QIcon());
ui->detailButton->setIcon(QIcon());
ui->copyMessage->setIcon(QIcon());
ui->refreshButton->setIcon(QIcon());
}
else
{
ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/export"));
ui->newMessage->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/add"));
ui->detailButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/details"));
ui->copyMessage->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/editcopy"));
ui->refreshButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/refresh"));
}
ui->labelExplanation->setText(tr("These are Gtacoin messages you have sent."));
// Context menu actions
QAction *copyGuidAction = new QAction(ui->copyMessage->text(), this);
QAction *copySubjectAction = new QAction(tr("Copy Subject"), this);
QAction *copyMessageAction = new QAction(tr("Copy Msg"), this);
QAction *newMessageAction = new QAction(tr("New Msg"), this);
QAction *detailsAction = new QAction(tr("Details"), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyGuidAction);
contextMenu->addAction(copySubjectAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(detailsAction);
contextMenu->addSeparator();
contextMenu->addAction(newMessageAction);
// Connect signals for context menu actions
connect(copyGuidAction, SIGNAL(triggered()), this, SLOT(on_copyGuid_clicked()));
connect(copySubjectAction, SIGNAL(triggered()), this, SLOT(on_copySubject_clicked()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(on_copyMessage_clicked()));
connect(newMessageAction, SIGNAL(triggered()), this, SLOT(on_newMessage_clicked()));
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_detailButton_clicked()));
connect(detailsAction, SIGNAL(triggered()), this, SLOT(on_detailButton_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
}
void OutMessageListPage::on_detailButton_clicked()
{
if(!ui->tableView->selectionModel())
return;
QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
MessageInfoDialog dlg;
QModelIndex origIndex = proxyModel->mapToSource(selection.at(0));
dlg.setModel(walletModel, model);
dlg.loadRow(origIndex.row());
dlg.exec();
}
}
void OutMessageListPage::on_newMessage_clicked()
{
NewMessageDialog dlg(NewMessageDialog::NewMessage);
dlg.setModel(walletModel, model);
dlg.exec();
}
OutMessageListPage::~OutMessageListPage()
{
delete ui;
}
void OutMessageListPage::showEvent ( QShowEvent * event )
{
if(!walletModel) return;
}
void OutMessageListPage::setModel(WalletModel* walletModel, MessageTableModel *model)
{
this->model = model;
this->walletModel = walletModel;
if(!model) return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterRole(MessageTableModel::TypeRole);
ui->tableView->setModel(proxyModel);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
// Set column widths
ui->tableView->setColumnWidth(0, 75); //guid
ui->tableView->setColumnWidth(1, 75); //time
ui->tableView->setColumnWidth(2, 100); //from
ui->tableView->setColumnWidth(3, 100); //to
ui->tableView->setColumnWidth(4, 300); //subject
ui->tableView->setColumnWidth(5, 300); //message
ui->tableView->horizontalHeader()->setStretchLastSection(true);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created outmessage
connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewMessage(QModelIndex,int,int)));
selectionChanged();
}
void OutMessageListPage::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void OutMessageListPage::on_refreshButton_clicked()
{
if(!model)
return;
model->refreshMessageTable();
}
void OutMessageListPage::on_copyMessage_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageTableModel::Message);
}
void OutMessageListPage::on_copyGuid_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageTableModel::GUID);
}
void OutMessageListPage::on_copySubject_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageTableModel::Subject);
}
void OutMessageListPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
ui->copyMessage->setEnabled(true);
ui->detailButton->setEnabled(true);
}
else
{
ui->copyMessage->setEnabled(false);
ui->detailButton->setEnabled(false);
}
}
void OutMessageListPage::keyPressEvent(QKeyEvent * event)
{
if( event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter )
{
on_newMessage_clicked();
event->accept();
}
else
QDialog::keyPressEvent( event );
}
void OutMessageListPage::on_exportButton_clicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Message Data"), QString(),
tr("Comma separated file (*.csv)"), NULL);
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn(tr("GUID"), MessageTableModel::GUID, Qt::EditRole);
writer.addColumn(tr("Time"), MessageTableModel::Time, Qt::EditRole);
writer.addColumn(tr("From"), MessageTableModel::From, Qt::EditRole);
writer.addColumn(tr("To"), MessageTableModel::To, Qt::EditRole);
writer.addColumn(tr("Subject"), MessageTableModel::Subject, Qt::EditRole);
writer.addColumn(tr("Message"), MessageTableModel::Message, Qt::EditRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file: ") + filename,
QMessageBox::Abort, QMessageBox::Abort);
}
}
void OutMessageListPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid()) {
contextMenu->exec(QCursor::pos());
}
}
void OutMessageListPage::selectNewMessage(const QModelIndex &parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, MessageTableModel::GUID, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newMessageToSelect))
{
// Select row of newly created outmessage, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newMessageToSelect.clear();
}
}
| 32.595142 | 113 | 0.708732 | gtacoin-dev |
dbab1ffd5252e094a29808633d5cf15a2e0a2f5d | 1,450 | cpp | C++ | lib/src/DriverTimerLocal.cpp | RobertDamerius/GenericTarget | 6b26793c2d580797ac8104ca5368987cbb570ef8 | [
"MIT"
] | 1 | 2021-02-02T09:01:24.000Z | 2021-02-02T09:01:24.000Z | lib/src/DriverTimerLocal.cpp | RobertDamerius/GenericTarget | 6b26793c2d580797ac8104ca5368987cbb570ef8 | [
"MIT"
] | null | null | null | lib/src/DriverTimerLocal.cpp | RobertDamerius/GenericTarget | 6b26793c2d580797ac8104ca5368987cbb570ef8 | [
"MIT"
] | 2 | 2021-02-02T09:01:45.000Z | 2021-10-02T13:08:16.000Z | #include "DriverTimerLocal.h"
#include "HostImplementation.h"
#ifdef GENERIC_TARGET_IMPLEMENTATION
#include <GenericTarget.hpp>
#include <TargetTime.hpp>
#endif
void CreateDriverTimerLocal(void){
#ifndef GENERIC_TARGET_IMPLEMENTATION
#ifdef HOST_IMPLEMENTATION
HostImplementation::CreateDriverTimerLocal();
#endif
#endif
}
void DeleteDriverTimerLocal(void){
#ifndef GENERIC_TARGET_IMPLEMENTATION
#ifdef HOST_IMPLEMENTATION
HostImplementation::DeleteDriverTimerLocal();
#endif
#endif
}
void OutputDriverTimerLocal(int32_t* nanoseconds, int32_t* second, int32_t* minute, int32_t* hour, int32_t* mday, int32_t* mon, int32_t* year, int32_t* wday, int32_t* yday, int32_t* isdst){
#ifdef GENERIC_TARGET_IMPLEMENTATION
TargetTime t = GenericTarget::GetTargetTime();
*nanoseconds = t.local.nanoseconds;
*second = t.local.second;
*minute = t.local.minute;
*hour = t.local.hour;
*mday = t.local.mday;
*mon = t.local.mon;
*year = t.local.year;
*wday = t.local.wday;
*yday = t.local.yday;
*isdst = t.local.isdst;
#else
#ifdef HOST_IMPLEMENTATION
HostImplementation::OutputDriverTimerLocal(nanoseconds, second, minute, hour, mday, mon, year, wday, yday, isdst);
#else
*nanoseconds = 0;
*second = 0;
*minute = 0;
*hour = 0;
*mday = 1;
*mon = 0;
*year = 0;
*wday = 1;
*yday = 0;
*isdst = -1;
#endif
#endif
}
| 25.892857 | 189 | 0.678621 | RobertDamerius |
dbab996704340fbf821569adb51777c56f6a9c60 | 291 | hpp | C++ | src/PhongMaterial.hpp | lozog/CS488-raytracer | e566f8e2ca112088900b0320b7f3e2d5b2b370dd | [
"MIT"
] | null | null | null | src/PhongMaterial.hpp | lozog/CS488-raytracer | e566f8e2ca112088900b0320b7f3e2d5b2b370dd | [
"MIT"
] | null | null | null | src/PhongMaterial.hpp | lozog/CS488-raytracer | e566f8e2ca112088900b0320b7f3e2d5b2b370dd | [
"MIT"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
#include "Material.hpp"
class PhongMaterial : public Material {
public:
PhongMaterial(const glm::vec3& kd, const glm::vec3& ks, double shininess);
virtual ~PhongMaterial();
// private:
glm::vec3 m_kd;
glm::vec3 m_ks;
double m_shininess;
};
| 16.166667 | 76 | 0.701031 | lozog |
dbb0b606c652ee73670756441ba63cc120555c8e | 34,309 | cpp | C++ | tests/TestLogMemoryUtilities.cpp | Nuovations/LogUtilities | 8a367c33757dcf5a7df9ad5abbdc833e6cc21437 | [
"Apache-2.0"
] | 1 | 2021-03-02T20:55:22.000Z | 2021-03-02T20:55:22.000Z | tests/TestLogMemoryUtilities.cpp | Nuovations/LogUtilities | 8a367c33757dcf5a7df9ad5abbdc833e6cc21437 | [
"Apache-2.0"
] | null | null | null | tests/TestLogMemoryUtilities.cpp | Nuovations/LogUtilities | 8a367c33757dcf5a7df9ad5abbdc833e6cc21437 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Nuovation System Designs, LLC
* 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.
*/
/**
* @file
* This file implements a unit test for Log::Utilities::Memory
*/
#include <LogUtilities/LogFilterAlways.hpp>
#include <LogUtilities/LogFormatterPlain.hpp>
#include <LogUtilities/LogGlobals.hpp>
#include <LogUtilities/LogIndenterNone.hpp>
#include <LogUtilities/LogLogger.hpp>
#include <LogUtilities/LogMemoryUtilities.hpp>
#include <LogUtilities/LogWriterDescriptor.hpp>
#include <ostream>
#include <regex>
#include <string>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <cppunit/TestAssert.h>
#include <cppunit/extensions/HelperMacros.h>
#include "TestLogUtilitiesBasis.hpp"
using namespace Nuovations;
using namespace std;
class TestMemoryLines
{
public:
TestMemoryLines(const char * inMemoryLines);
~TestMemoryLines(void) = default;
bool operator ==(const TestMemoryLines & inMemoryLines) const;
size_t size(void) const;
const std::string & operator ()(void) const;
std::string & operator ()(void);
std::ostream & operator <<(const TestMemoryLines & inMemoryLines) const;
private:
class MemoryLine
{
public:
MemoryLine(void);
bool operator ==(const MemoryLine & inMemoryLine) const;
bool operator !=(const MemoryLine & inMemoryLine) const;
MemoryLine & operator =(const MemoryLine & inMemoryLine);
MemoryLine operator ++(int inDummy);
public:
size_t mAddressPosition;
size_t mDataPosition;
size_t mNewlinePosition;
private:
friend class TestMemoryLines;
MemoryLine(const TestMemoryLines & inMemoryLines);
MemoryLine(const TestMemoryLines & inMemoryLines,
const size_t & inAddressPosition,
const size_t & inDataPosition,
const size_t & inNewlinePosition);
const TestMemoryLines * mTestMemoryLines;
};
MemoryLine begin(void) const;
MemoryLine end(void) const;
bool CompareAddress(const MemoryLine & inOurLine,
const TestMemoryLines & inTheirLines,
const MemoryLine & inTheirLine) const;
bool CompareData(const MemoryLine & inOurLine,
const TestMemoryLines & inTheirLines,
const MemoryLine & inTheirLine) const;
private:
std::string mMemoryLines;
};
class TestLogMemoryUtilities :
public TestLogUtilitiesBasis
{
CPPUNIT_TEST_SUITE(TestLogMemoryUtilities);
CPPUNIT_TEST(TestWithExplicitLoggerWithInvalidWidth);
CPPUNIT_TEST(TestWithExplicitLoggerWithDefaultIndentAndLevel);
CPPUNIT_TEST(TestWithExplicitLoggerWithDefaultIndentWithLevel);
CPPUNIT_TEST(TestWithExplicitLoggerWithIndentAndLevel);
CPPUNIT_TEST(TestWithImplicitLoggerWithInvalidWidth);
CPPUNIT_TEST(TestWithImplicitLoggerWithDefaultIndentAndLevel);
CPPUNIT_TEST(TestWithImplicitLoggerWithDefaultIndentWithLevel);
CPPUNIT_TEST(TestWithImplicitLoggerWithIndentAndLevel);
CPPUNIT_TEST_SUITE_END();
public:
void TestWithExplicitLoggerWithInvalidWidth(void);
void TestWithExplicitLoggerWithDefaultIndentAndLevel(void);
void TestWithExplicitLoggerWithDefaultIndentWithLevel(void);
void TestWithExplicitLoggerWithIndentAndLevel(void);
void TestWithImplicitLoggerWithInvalidWidth(void);
void TestWithImplicitLoggerWithDefaultIndentAndLevel(void);
void TestWithImplicitLoggerWithDefaultIndentWithLevel(void);
void TestWithImplicitLoggerWithIndentAndLevel(void);
private:
int CreateTemporaryFile(char * aPathBuffer);
void CheckResults(const char * aPathBuffer, const TestMemoryLines & aExpected);
static constexpr uint8_t kUint8x8s[8] =
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07
};
static constexpr uint8_t kUint32x8s[32] =
{
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
};
static constexpr uint16_t kUint16s[16] =
{
0x3000, 0x3001, 0x3002, 0x3003,
0x3004, 0x3005, 0x3006, 0x3007,
0x3008, 0x3009, 0x300a, 0x300b,
0x300c, 0x300d, 0x300e, 0x300f
};
static constexpr uint32_t kUint32s[8] =
{
0x40000000, 0x40000001, 0x40000002, 0x40000003,
0x40000004, 0x40000005, 0x40000006, 0x40000007,
};
static constexpr uint64_t kUint64s[8] =
{
0x5000000000000000, 0x5000000000000001,
0x5000000000000002, 0x5000000000000003,
0x5000000000000004, 0x5000000000000005,
0x5000000000000006, 0x5000000000000007
};
static constexpr size_t kOffsets[2] = { 0, 3 };
static const TestMemoryLines kExpectedMemoryLines;
};
constexpr uint8_t TestLogMemoryUtilities ::kUint8x8s[];
constexpr uint8_t TestLogMemoryUtilities ::kUint32x8s[];
constexpr uint16_t TestLogMemoryUtilities ::kUint16s[];
constexpr uint32_t TestLogMemoryUtilities ::kUint32s[];
constexpr uint64_t TestLogMemoryUtilities ::kUint64s[];
constexpr size_t TestLogMemoryUtilities ::kOffsets[];
const TestMemoryLines TestLogMemoryUtilities ::kExpectedMemoryLines =
"<address>: 00 01 02 03 04 05 06 07 '................'\n"
"<address>: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f '................'\n"
"<address>: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f ' !\"#$%&'()*+,-./'\n"
"<address>: 00 30 01 30 02 30 03 30 04 30 05 30 06 30 07 30 '.0.0.0.0.0.0.0.0'\n"
"<address>: 00 00 00 40 01 00 00 40 '...@...@........'\n"
"<address>: 00 00 00 00 00 00 00 50 '.......P........'\n"
"<address>: 00 01 02 03 04 05 06 07 '................'\n"
"<address>: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f '................'\n"
"<address>: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f ' !\"#$%&'()*+,-./'\n"
"<address>: 3000 3001 3002 3003 3004 3005 3006 3007 '.0.0.0.0.0.0.0.0'\n"
"<address>: 3008 3009 300a 300b 300c 300d 300e 300f '.0.0.0.0.0.0.0.0'\n"
"<address>: 40000000 40000001 40000002 40000003 '...@...@...@...@'\n"
"<address>: 40000004 40000005 40000006 40000007 '...@...@...@...@'\n"
"<address>: 5000000000000000 5000000000000001 '.......P.......P'\n"
"<address>: 5000000000000002 5000000000000003 '.......P.......P'\n"
"<address>: 5000000000000004 5000000000000005 '.......P.......P'\n"
"<address>: 5000000000000006 5000000000000007 '.......P.......P'\n"
"<address>: 03 04 05 06 07 '................'\n"
"<address>: 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 '............. !\"'\n"
"<address>: 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f '#$%&'()*+,-./...'\n"
"<address>: 03 30 04 30 05 30 06 30 07 30 08 30 09 '.0.0.0.0.0.0....'\n"
"<address>: 03 00 00 40 04 '...@............'\n"
"<address>: 03 00 00 00 00 '................'\n"
"<address>: 03 04 05 06 07 '................'\n"
"<address>: 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 '............. !\"'\n"
"<address>: 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f '#$%&'()*+,-./...'\n"
"<address>: 3003 3004 3005 3006 3007 3008 3009 300a '.0.0.0.0.0.0.0.0'\n"
"<address>: 300b 300c 300d 300e 300f '.0.0.0.0.0......'\n"
"<address>: 40000003 40000004 40000005 40000006 '...@...@...@...@'\n"
"<address>: 40000007 '...@............'\n"
"<address>: 5000000000000003 5000000000000004 '.......P.......P'\n"
"<address>: 5000000000000005 5000000000000006 '.......P.......P'\n"
"<address>: 5000000000000007 '.......P........'\n";
TestMemoryLines :: TestMemoryLines(const char * inMemoryLines) :
mMemoryLines(inMemoryLines)
{
return;
}
TestMemoryLines :: MemoryLine :: MemoryLine(void) :
mAddressPosition(0),
mDataPosition(0),
mNewlinePosition(0),
mTestMemoryLines(nullptr)
{
return;
}
TestMemoryLines :: MemoryLine :: MemoryLine(const TestMemoryLines & inTestMemoryLines) :
mAddressPosition(0),
mDataPosition(0),
mNewlinePosition(0),
mTestMemoryLines(&inTestMemoryLines)
{
return;
}
TestMemoryLines :: MemoryLine :: MemoryLine(const TestMemoryLines & inTestMemoryLines,
const size_t & inAddressPosition,
const size_t & inDataPosition,
const size_t & inNewlinePosition) :
mAddressPosition(inAddressPosition),
mDataPosition(inDataPosition),
mNewlinePosition(inNewlinePosition),
mTestMemoryLines(&inTestMemoryLines)
{
return;
}
bool
TestMemoryLines :: MemoryLine ::operator ==(const MemoryLine & inMemoryLine) const
{
bool lRetval;
lRetval = ((mAddressPosition == inMemoryLine.mAddressPosition) &&
(mDataPosition == inMemoryLine.mDataPosition ) &&
(mNewlinePosition == inMemoryLine.mNewlinePosition) &&
(mTestMemoryLines == inMemoryLine.mTestMemoryLines));
return (lRetval);
}
bool
TestMemoryLines :: MemoryLine :: operator !=(const MemoryLine & inMemoryLine) const
{
return (!(*this == inMemoryLine));
}
TestMemoryLines::MemoryLine &
TestMemoryLines :: MemoryLine :: operator =(const MemoryLine & inMemoryLine)
{
mAddressPosition = inMemoryLine.mAddressPosition;
mDataPosition = inMemoryLine.mDataPosition;
mNewlinePosition = inMemoryLine.mNewlinePosition;
mTestMemoryLines = inMemoryLine.mTestMemoryLines;
return (*this);
}
TestMemoryLines::MemoryLine
TestMemoryLines :: MemoryLine :: operator ++(int inDummy)
{
static const char kColon = ':';
static const char kNewline = '\n';
const MemoryLine lCurrentLine = *this;
const size_t lNextAddressPosition = mNewlinePosition + 1;
(void)inDummy;
// When this has incremented past the last line, ALL of the data
// members should be set to string::npos. The find method covers
// that for data and newline. We have to manually handle it for
// the address.
mAddressPosition = ((lNextAddressPosition >= mTestMemoryLines->size()) ? string::npos : lNextAddressPosition);
mDataPosition = mTestMemoryLines->mMemoryLines.find(kColon, mAddressPosition);
mNewlinePosition = mTestMemoryLines->mMemoryLines.find(kNewline, mAddressPosition);
return (lCurrentLine);
}
TestMemoryLines::MemoryLine
TestMemoryLines :: begin(void) const
{
static const char kColon = ':';
static const char kNewline = '\n';
MemoryLine lMemoryLine(*this);
lMemoryLine.mAddressPosition = 0;
lMemoryLine.mDataPosition = mMemoryLines.find(kColon, lMemoryLine.mAddressPosition);
lMemoryLine.mNewlinePosition = mMemoryLines.find(kNewline, lMemoryLine.mAddressPosition);
// If we found no data and no newline, then the lines are either
// malformed or we are at the end. Regardless, return the end
// iterator. Otherwise, return the start iterator.
if ((lMemoryLine.mDataPosition == string::npos) &&
(lMemoryLine.mNewlinePosition == string::npos)) {
return (end());
} else {
return (lMemoryLine);
}
}
TestMemoryLines::MemoryLine
TestMemoryLines :: end(void) const
{
const MemoryLine kLastMemoryLine(*this,
string::npos,
string::npos,
string::npos);
return (kLastMemoryLine);
}
bool
TestMemoryLines :: CompareAddress(const MemoryLine & inOurLine,
const TestMemoryLines & inTheirLines,
const MemoryLine & inTheirLine) const
{
const auto ourAddressIteratorBegin = mMemoryLines.cbegin() + static_cast<string::difference_type>(inOurLine.mAddressPosition);
const auto ourAddressIteratorEnd = mMemoryLines.cbegin() + static_cast<string::difference_type>(inOurLine.mDataPosition);
const auto theirAddressIteratorBegin = inTheirLines.mMemoryLines.cbegin() + static_cast<string::difference_type>(inTheirLine.mAddressPosition);
const auto theirAddressIteratorEnd = inTheirLines.mMemoryLines.cbegin() + static_cast<string::difference_type>(inTheirLine.mDataPosition);
const regex lRegex("(<address>|0x[[:xdigit:]]{4,16})");
bool lRetval = true;
if (!regex_match(ourAddressIteratorBegin, ourAddressIteratorEnd, lRegex) ||
!regex_match(theirAddressIteratorBegin, theirAddressIteratorEnd, lRegex)) {
lRetval = false;
}
return (lRetval);
}
bool
TestMemoryLines :: CompareData(const MemoryLine & inOurLine,
const TestMemoryLines & inTheirLines,
const MemoryLine & inTheirLine) const
{
const size_t ourDataLength = inOurLine.mNewlinePosition - inOurLine.mDataPosition;
const size_t theirDataLength = inTheirLine.mNewlinePosition - inTheirLine.mDataPosition;
int lCompare;
lCompare = mMemoryLines.compare(inOurLine.mDataPosition,
ourDataLength,
inTheirLines.mMemoryLines,
inTheirLine.mDataPosition,
theirDataLength);
return (lCompare == 0);
}
bool
TestMemoryLines :: operator ==(const TestMemoryLines & inTheirLines) const
{
MemoryLine lOurLine;
MemoryLine lTheirLine;
bool lRetval = true;
// Walk through each line, ours and theirs, comparing the address
// portion for equivalence and comparing the data portion for
// equality.
lOurLine = begin();
lTheirLine = inTheirLines.begin();
while (lRetval) {
const bool lOurEnd = (lOurLine == end());
const bool lTheirEnd = (lTheirLine == inTheirLines.end());
// If we are at our end but not theirs or vice versa, then we
// have a line number mismatch and the lines, collectively are
// not equivalent.
if ((lOurEnd && !lTheirEnd) || (!lOurEnd && lTheirEnd)) {
lRetval = false;
break;
}
if (lOurEnd && lTheirEnd) {
break;
}
// Check the address and the data portion
lRetval = (CompareAddress(lOurLine, inTheirLines, lTheirLine) &&
CompareData(lOurLine, inTheirLines, lTheirLine));
// Get our and their next line
lOurLine++;
lTheirLine++;
}
return (lRetval);
}
size_t
TestMemoryLines :: size(void) const
{
return (mMemoryLines.size());
}
const std::string &
TestMemoryLines :: operator ()(void) const
{
return (mMemoryLines);
}
std::string &
TestMemoryLines :: operator ()(void)
{
return (mMemoryLines);
}
static std::ostream &
operator <<(std::ostream & inStream, const TestMemoryLines & inMemoryLines)
{
const std::string & lString = (const std::string &)(inMemoryLines);
inStream << lString;
return (inStream);
}
namespace Detail
{
template <typename T, size_t N>
constexpr size_t
elementsof(const T (&)[N])
{
return (N);
}
}; // namespace Detail
CPPUNIT_TEST_SUITE_REGISTRATION(TestLogMemoryUtilities);
void
TestLogMemoryUtilities :: TestWithExplicitLoggerWithInvalidWidth(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Logger lLogger(lAlwaysFilter,
lNoneIndenter,
lPlainFormatter,
lDescriptorWriter);
for (auto lOffset : kOffsets) {
static constexpr unsigned int kWidth = 3;
// Default indent and level
Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, kWidth);
Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, kWidth);
Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, kWidth);
Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, kWidth);
Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, kWidth);
}
}
close(lDescriptor);
CheckResults(lPathBuffer, "");
}
void
TestLogMemoryUtilities :: TestWithExplicitLoggerWithDefaultIndentAndLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Logger lLogger(lAlwaysFilter,
lNoneIndenter,
lPlainFormatter,
lDescriptorWriter);
for (auto lOffset : kOffsets) {
// Default indent, level, and width
Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// Default indent and level
Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithExplicitLoggerWithDefaultIndentWithLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
const Log::Level kLevel = 0;
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Logger lLogger(lAlwaysFilter,
lNoneIndenter,
lPlainFormatter,
lDescriptorWriter);
for (auto lOffset : kOffsets) {
// Default indent with level and default width
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// Default indent with level
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithExplicitLoggerWithIndentAndLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
const Log::Indent kIndent = 0;
const Log::Level kLevel = 0;
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Logger lLogger(lAlwaysFilter,
lNoneIndenter,
lPlainFormatter,
lDescriptorWriter);
for (auto lOffset : kOffsets) {
// With indent and level and default width
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// With indent and level
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithImplicitLoggerWithInvalidWidth(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Debug().SetFilter(lAlwaysFilter);
Log::Debug().SetIndenter(lNoneIndenter);
Log::Debug().SetFormatter(lPlainFormatter);
Log::Debug().SetWriter(lDescriptorWriter);
for (auto lOffset : kOffsets) {
static constexpr unsigned int kWidth = 3;
// Default indent and level
Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, kWidth);
Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, kWidth);
Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, kWidth);
Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, kWidth);
Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, kWidth);
}
}
close(lDescriptor);
CheckResults(lPathBuffer, "");
}
void
TestLogMemoryUtilities :: TestWithImplicitLoggerWithDefaultIndentAndLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Debug().SetFilter(lAlwaysFilter);
Log::Debug().SetIndenter(lNoneIndenter);
Log::Debug().SetFormatter(lPlainFormatter);
Log::Debug().SetWriter(lDescriptorWriter);
for (auto lOffset : kOffsets) {
// Default indent, level, and width
Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// Default indent and level
Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithImplicitLoggerWithDefaultIndentWithLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
const Log::Level kLevel = 0;
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Debug().SetFilter(lAlwaysFilter);
Log::Debug().SetIndenter(lNoneIndenter);
Log::Debug().SetFormatter(lPlainFormatter);
Log::Debug().SetWriter(lDescriptorWriter);
for (auto lOffset : kOffsets) {
// Default indent with level and default width
Log::Utilities::Memory::Write(kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// Default indent with level
Log::Utilities::Memory::Write(kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithImplicitLoggerWithIndentAndLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
const Log::Indent kIndent = 0;
const Log::Level kLevel = 0;
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Debug().SetFilter(lAlwaysFilter);
Log::Debug().SetIndenter(lNoneIndenter);
Log::Debug().SetFormatter(lPlainFormatter);
Log::Debug().SetWriter(lDescriptorWriter);
for (auto lOffset : kOffsets) {
// With indent and level and default width
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// With indent and level
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
int
TestLogMemoryUtilities :: CreateTemporaryFile(char * aPathBuffer)
{
static const char * const kTestName = "memory-utilities";
int lStatus;
lStatus = CreateTemporaryFileFromName(kTestName, aPathBuffer);
return (lStatus);
}
void
TestLogMemoryUtilities :: CheckResults(const char * aPathBuffer,
const TestMemoryLines & aExpected)
{
struct stat lStat;
int lStatus;
int lDescriptor;
char * lBuffer;
ssize_t lResidual;
lStatus = stat(aPathBuffer, &lStat);
CPPUNIT_ASSERT(lStatus == 0);
lDescriptor = open(aPathBuffer, O_RDONLY);
CPPUNIT_ASSERT(lDescriptor > 0);
lBuffer = new char[static_cast<size_t>(lStat.st_size) + 1];
CPPUNIT_ASSERT(lBuffer != NULL);
lResidual = read(lDescriptor, &lBuffer[0], static_cast<size_t>(lStat.st_size));
CPPUNIT_ASSERT_EQUAL(lStat.st_size, static_cast<off_t>(lResidual));
close(lDescriptor);
lBuffer[static_cast<size_t>(lStat.st_size)] = '\0';
CPPUNIT_ASSERT_EQUAL(aExpected, TestMemoryLines(lBuffer));
delete [] lBuffer;
lStatus = unlink(aPathBuffer);
CPPUNIT_ASSERT(lStatus == 0);
}
| 40.602367 | 162 | 0.635518 | Nuovations |
dbb0e1820c9150119aba27b89136bdfbc0b93966 | 20,078 | cpp | C++ | drape/texture_manager.cpp | Kazing/organicmaps | 687a6e21c7bda306558fe177608835f35d1b5d14 | [
"Apache-2.0"
] | null | null | null | drape/texture_manager.cpp | Kazing/organicmaps | 687a6e21c7bda306558fe177608835f35d1b5d14 | [
"Apache-2.0"
] | null | null | null | drape/texture_manager.cpp | Kazing/organicmaps | 687a6e21c7bda306558fe177608835f35d1b5d14 | [
"Apache-2.0"
] | null | null | null | #include "drape/texture_manager.hpp"
#include "drape/gl_functions.hpp"
#include "drape/font_texture.hpp"
#include "drape/symbols_texture.hpp"
#include "drape/static_texture.hpp"
#include "drape/stipple_pen_resource.hpp"
#include "drape/support_manager.hpp"
#include "drape/texture_of_colors.hpp"
#include "drape/tm_read_resources.hpp"
#include "drape/utils/glyph_usage_tracker.hpp"
#include "base/file_name_utils.hpp"
#include "base/stl_helpers.hpp"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace dp
{
namespace
{
uint32_t const kMaxTextureSize = 1024;
uint32_t const kStippleTextureWidth = 512; /// @todo Should be equal with kMaxStipplePenLength?
uint32_t const kMinStippleTextureHeight = 64;
uint32_t const kMinColorTextureSize = 32;
uint32_t const kGlyphsTextureSize = 1024;
size_t const kInvalidGlyphGroup = std::numeric_limits<size_t>::max();
// Reserved for elements like RuleDrawer or other LineShapes.
uint32_t const kReservedPatterns = 10;
size_t const kReservedColors = 20;
float const kGlyphAreaMultiplier = 1.2f;
float const kGlyphAreaCoverage = 0.9f;
std::string const kSymbolTextures[] = { "symbols" };
uint32_t const kDefaultSymbolsIndex = 0;
void MultilineTextToUniString(TextureManager::TMultilineText const & text, strings::UniString & outString)
{
size_t cnt = 0;
for (strings::UniString const & str : text)
cnt += str.size();
outString.clear();
outString.reserve(cnt);
for (strings::UniString const & str : text)
outString.append(str.begin(), str.end());
}
template <typename ToDo>
void ParseColorsList(std::string const & colorsFile, ToDo toDo)
{
ReaderStreamBuf buffer(GetPlatform().GetReader(colorsFile));
std::istream is(&buffer);
while (is.good())
{
uint32_t color;
is >> color;
toDo(dp::Extract(color));
}
}
m2::PointU StipplePenTextureSize(size_t patternsCount, uint32_t maxTextureSize)
{
uint32_t const sz = base::NextPowOf2(static_cast<uint32_t>(patternsCount) + kReservedPatterns);
// No problem if assert will fire here. Just pen texture will be 2x bigger :)
//ASSERT_LESS_OR_EQUAL(sz, kMinStippleTextureHeight, (patternsCount));
uint32_t const stippleTextureHeight = std::min(maxTextureSize, std::max(sz, kMinStippleTextureHeight));
return m2::PointU(kStippleTextureWidth, stippleTextureHeight);
}
m2::PointU ColorTextureSize(size_t colorsCount, uint32_t maxTextureSize)
{
uint32_t const sz = static_cast<uint32_t>(floor(sqrt(colorsCount + kReservedColors)));
// No problem if assert will fire here. Just color texture will be 2x bigger :)
ASSERT_LESS_OR_EQUAL(sz, kMinColorTextureSize, (colorsCount));
uint32_t colorTextureSize = std::max(base::NextPowOf2(sz), kMinColorTextureSize);
colorTextureSize *= ColorTexture::GetColorSizeInPixels();
colorTextureSize = std::min(maxTextureSize, colorTextureSize);
return m2::PointU(colorTextureSize, colorTextureSize);
}
} // namespace
TextureManager::TextureManager(ref_ptr<GlyphGenerator> glyphGenerator)
: m_maxTextureSize(0)
, m_maxGlypsCount(0)
, m_glyphGenerator(glyphGenerator)
{
m_nothingToUpload.test_and_set();
}
TextureManager::BaseRegion::BaseRegion()
: m_info(nullptr)
, m_texture(nullptr)
{}
bool TextureManager::BaseRegion::IsValid() const
{
return m_info != nullptr && m_texture != nullptr;
}
void TextureManager::BaseRegion::SetResourceInfo(ref_ptr<Texture::ResourceInfo> info)
{
m_info = info;
}
void TextureManager::BaseRegion::SetTexture(ref_ptr<Texture> texture)
{
m_texture = texture;
}
m2::PointF TextureManager::BaseRegion::GetPixelSize() const
{
if (!IsValid())
return m2::PointF(0.0f, 0.0f);
m2::RectF const & texRect = m_info->GetTexRect();
return m2::PointF(texRect.SizeX() * m_texture->GetWidth(),
texRect.SizeY() * m_texture->GetHeight());
}
float TextureManager::BaseRegion::GetPixelHeight() const
{
if (!IsValid())
return 0.0f;
return m_info->GetTexRect().SizeY() * m_texture->GetHeight();
}
m2::RectF const & TextureManager::BaseRegion::GetTexRect() const
{
if (!IsValid())
{
static m2::RectF nilRect(0.0f, 0.0f, 0.0f, 0.0f);
return nilRect;
}
return m_info->GetTexRect();
}
float TextureManager::GlyphRegion::GetOffsetX() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ());
return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_xOffset;
}
float TextureManager::GlyphRegion::GetOffsetY() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ());
return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_yOffset;
}
float TextureManager::GlyphRegion::GetAdvanceX() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ());
return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_xAdvance;
}
float TextureManager::GlyphRegion::GetAdvanceY() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ());
return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_yAdvance;
}
m2::PointU TextureManager::StippleRegion::GetMaskPixelSize() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::StipplePen, ());
return ref_ptr<StipplePenResourceInfo>(m_info)->GetMaskPixelSize();
}
//uint32_t TextureManager::StippleRegion::GetPatternPixelLength() const
//{
// ASSERT(m_info->GetType() == Texture::ResourceType::StipplePen, ());
// return ref_ptr<StipplePenResourceInfo>(m_info)->GetPatternPixelLength();
//}
void TextureManager::Release()
{
m_hybridGlyphGroups.clear();
m_symbolTextures.clear();
m_stipplePenTexture.reset();
m_colorTexture.reset();
m_trafficArrowTexture.reset();
m_hatchingTexture.reset();
m_smaaAreaTexture.reset();
m_smaaSearchTexture.reset();
m_glyphTextures.clear();
m_glyphManager.reset();
m_glyphGenerator->FinishGeneration();
m_isInitialized = false;
m_nothingToUpload.test_and_set();
}
bool TextureManager::UpdateDynamicTextures(ref_ptr<dp::GraphicsContext> context)
{
if (!HasAsyncRoutines() && m_nothingToUpload.test_and_set())
{
auto const apiVersion = context->GetApiVersion();
if (apiVersion == dp::ApiVersion::OpenGLES2 || apiVersion == dp::ApiVersion::OpenGLES3)
{
// For some reasons OpenGL can not update textures immediately.
// Here we use some timeout to prevent rendering frozening.
double const kUploadTimeoutInSeconds = 2.0;
return m_uploadTimer.ElapsedSeconds() < kUploadTimeoutInSeconds;
}
if (apiVersion == dp::ApiVersion::Metal || apiVersion == dp::ApiVersion::Vulkan)
return false;
CHECK(false, ("Unsupported API version."));
}
CHECK(m_isInitialized, ());
m_uploadTimer.Reset();
CHECK(m_colorTexture != nullptr, ());
m_colorTexture->UpdateState(context);
CHECK(m_stipplePenTexture != nullptr, ());
m_stipplePenTexture->UpdateState(context);
UpdateGlyphTextures(context);
CHECK(m_textureAllocator != nullptr, ());
m_textureAllocator->Flush();
return true;
}
void TextureManager::UpdateGlyphTextures(ref_ptr<dp::GraphicsContext> context)
{
std::lock_guard<std::mutex> lock(m_glyphTexturesMutex);
for (auto & texture : m_glyphTextures)
texture->UpdateState(context);
}
bool TextureManager::HasAsyncRoutines() const
{
CHECK(m_glyphGenerator != nullptr, ());
return !m_glyphGenerator->IsSuspended();
}
ref_ptr<Texture> TextureManager::AllocateGlyphTexture()
{
std::lock_guard<std::mutex> lock(m_glyphTexturesMutex);
m2::PointU size(kGlyphsTextureSize, kGlyphsTextureSize);
m_glyphTextures.push_back(make_unique_dp<FontTexture>(size, make_ref(m_glyphManager),
m_glyphGenerator,
make_ref(m_textureAllocator)));
return make_ref(m_glyphTextures.back());
}
void TextureManager::GetRegionBase(ref_ptr<Texture> tex, TextureManager::BaseRegion & region,
Texture::Key const & key)
{
bool isNew = false;
region.SetResourceInfo(tex != nullptr ? tex->FindResource(key, isNew) : nullptr);
region.SetTexture(tex);
ASSERT(region.IsValid(), ());
if (isNew)
m_nothingToUpload.clear();
}
void TextureManager::GetGlyphsRegions(ref_ptr<FontTexture> tex, strings::UniString const & text,
int fixedHeight, TGlyphsBuffer & regions)
{
ASSERT(tex != nullptr, ());
std::vector<GlyphKey> keys;
keys.reserve(text.size());
for (auto const & c : text)
keys.emplace_back(GlyphKey(c, fixedHeight));
bool hasNew = false;
auto resourcesInfo = tex->FindResources(keys, hasNew);
ASSERT_EQUAL(text.size(), resourcesInfo.size(), ());
regions.reserve(resourcesInfo.size());
for (auto const & info : resourcesInfo)
{
GlyphRegion reg;
reg.SetResourceInfo(info);
reg.SetTexture(tex);
ASSERT(reg.IsValid(), ());
regions.push_back(std::move(reg));
}
if (hasNew)
m_nothingToUpload.clear();
}
uint32_t TextureManager::GetNumberOfUnfoundCharacters(strings::UniString const & text, int fixedHeight,
HybridGlyphGroup const & group) const
{
uint32_t cnt = 0;
for (auto const & c : text)
{
if (group.m_glyphs.find(std::make_pair(c, fixedHeight)) == group.m_glyphs.end())
cnt++;
}
return cnt;
}
void TextureManager::MarkCharactersUsage(strings::UniString const & text, int fixedHeight,
HybridGlyphGroup & group)
{
for (auto const & c : text)
group.m_glyphs.emplace(std::make_pair(c, fixedHeight));
}
size_t TextureManager::FindHybridGlyphsGroup(strings::UniString const & text, int fixedHeight)
{
if (m_hybridGlyphGroups.empty())
{
m_hybridGlyphGroups.push_back(HybridGlyphGroup());
return 0;
}
HybridGlyphGroup & group = m_hybridGlyphGroups.back();
bool hasEnoughSpace = true;
if (group.m_texture != nullptr)
hasEnoughSpace = group.m_texture->HasEnoughSpace(static_cast<uint32_t>(text.size()));
// If we have got the only hybrid texture (in most cases it is)
// we can omit checking of glyphs usage.
if (hasEnoughSpace)
{
size_t const glyphsCount = group.m_glyphs.size() + text.size();
if (m_hybridGlyphGroups.size() == 1 && glyphsCount < m_maxGlypsCount)
return 0;
}
// Looking for a hybrid texture which contains text entirely.
for (size_t i = 0; i < m_hybridGlyphGroups.size() - 1; i++)
{
if (GetNumberOfUnfoundCharacters(text, fixedHeight, m_hybridGlyphGroups[i]) == 0)
return i;
}
// Check if we can contain text in the last hybrid texture.
uint32_t const unfoundChars = GetNumberOfUnfoundCharacters(text, fixedHeight, group);
uint32_t const newCharsCount = static_cast<uint32_t>(group.m_glyphs.size()) + unfoundChars;
if (newCharsCount >= m_maxGlypsCount || !group.m_texture->HasEnoughSpace(unfoundChars))
m_hybridGlyphGroups.push_back(HybridGlyphGroup());
return m_hybridGlyphGroups.size() - 1;
}
size_t TextureManager::FindHybridGlyphsGroup(TMultilineText const & text, int fixedHeight)
{
strings::UniString combinedString;
MultilineTextToUniString(text, combinedString);
return FindHybridGlyphsGroup(combinedString, fixedHeight);
}
void TextureManager::Init(ref_ptr<dp::GraphicsContext> context, Params const & params)
{
CHECK(!m_isInitialized, ());
m_resPostfix = params.m_resPostfix;
m_textureAllocator = CreateAllocator(context);
m_maxTextureSize = std::min(kMaxTextureSize, dp::SupportManager::Instance().GetMaxTextureSize());
auto const apiVersion = context->GetApiVersion();
if (apiVersion == dp::ApiVersion::OpenGLES2 || apiVersion == dp::ApiVersion::OpenGLES3)
GLFunctions::glPixelStore(gl_const::GLUnpackAlignment, 1);
// Initialize symbols.
for (auto const & texName : kSymbolTextures)
{
m_symbolTextures.push_back(make_unique_dp<SymbolsTexture>(context, m_resPostfix, texName,
make_ref(m_textureAllocator)));
}
// Initialize static textures.
m_trafficArrowTexture = make_unique_dp<StaticTexture>(context, "traffic-arrow", m_resPostfix,
dp::TextureFormat::RGBA8, make_ref(m_textureAllocator));
m_hatchingTexture = make_unique_dp<StaticTexture>(context, "area-hatching", m_resPostfix,
dp::TextureFormat::RGBA8, make_ref(m_textureAllocator));
// SMAA is not supported on OpenGL ES2.
if (apiVersion != dp::ApiVersion::OpenGLES2)
{
m_smaaAreaTexture = make_unique_dp<StaticTexture>(context, "smaa-area", StaticTexture::kDefaultResource,
dp::TextureFormat::RedGreen, make_ref(m_textureAllocator));
m_smaaSearchTexture = make_unique_dp<StaticTexture>(context, "smaa-search", StaticTexture::kDefaultResource,
dp::TextureFormat::Alpha, make_ref(m_textureAllocator));
}
// Initialize patterns (reserved ./data/patterns.txt lines count).
std::set<PenPatternT> patterns;
double const visualScale = params.m_visualScale;
uint32_t rowsCount = 0;
impl::ParsePatternsList(params.m_patterns, [&](buffer_vector<double, 8> const & pattern)
{
PenPatternT toAdd;
for (double d : pattern)
toAdd.push_back(impl::PatternFloat2Pixel(d * visualScale));
if (!patterns.insert(toAdd).second)
return;
if (IsTrianglePattern(toAdd))
{
rowsCount = rowsCount + toAdd[2] + toAdd[3];
}
else
{
ASSERT_EQUAL(toAdd.size(), 2, ());
++rowsCount;
}
});
m_stipplePenTexture = make_unique_dp<StipplePenTexture>(StipplePenTextureSize(rowsCount, m_maxTextureSize),
make_ref(m_textureAllocator));
LOG(LDEBUG, ("Patterns texture size =", m_stipplePenTexture->GetWidth(), m_stipplePenTexture->GetHeight()));
ref_ptr<StipplePenTexture> stipplePenTex = make_ref(m_stipplePenTexture);
for (auto const & p : patterns)
stipplePenTex->ReservePattern(p);
// Initialize colors (reserved ./data/colors.txt lines count).
std::vector<dp::Color> colors;
colors.reserve(512);
ParseColorsList(params.m_colors, [&colors](dp::Color const & color)
{
colors.push_back(color);
});
m_colorTexture = make_unique_dp<ColorTexture>(ColorTextureSize(colors.size(), m_maxTextureSize),
make_ref(m_textureAllocator));
LOG(LDEBUG, ("Colors texture size =", m_colorTexture->GetWidth(), m_colorTexture->GetHeight()));
ref_ptr<ColorTexture> colorTex = make_ref(m_colorTexture);
for (auto const & c : colors)
colorTex->ReserveColor(c);
// Initialize glyphs.
m_glyphManager = make_unique_dp<GlyphManager>(params.m_glyphMngParams);
uint32_t const textureSquare = kGlyphsTextureSize * kGlyphsTextureSize;
uint32_t const baseGlyphHeight =
static_cast<uint32_t>(params.m_glyphMngParams.m_baseGlyphHeight * kGlyphAreaMultiplier);
uint32_t const averageGlyphSquare = baseGlyphHeight * baseGlyphHeight;
m_maxGlypsCount = static_cast<uint32_t>(ceil(kGlyphAreaCoverage * textureSquare / averageGlyphSquare));
m_isInitialized = true;
m_nothingToUpload.clear();
}
void TextureManager::OnSwitchMapStyle(ref_ptr<dp::GraphicsContext> context)
{
CHECK(m_isInitialized, ());
// Here we need invalidate only textures which can be changed in map style switch.
// Now we update only symbol textures, if we need update other textures they must be added here.
// For Vulkan we use m_texturesToCleanup to defer textures destroying.
for (size_t i = 0; i < m_symbolTextures.size(); ++i)
{
ASSERT(m_symbolTextures[i] != nullptr, ());
ASSERT(dynamic_cast<SymbolsTexture *>(m_symbolTextures[i].get()) != nullptr, ());
ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]);
if (context->GetApiVersion() != dp::ApiVersion::Vulkan)
symbolsTexture->Invalidate(context, m_resPostfix, make_ref(m_textureAllocator));
else
symbolsTexture->Invalidate(context, m_resPostfix, make_ref(m_textureAllocator), m_texturesToCleanup);
}
}
void TextureManager::GetTexturesToCleanup(std::vector<drape_ptr<HWTexture>> & textures)
{
CHECK(m_isInitialized, ());
std::swap(textures, m_texturesToCleanup);
}
void TextureManager::GetSymbolRegion(std::string const & symbolName, SymbolRegion & region)
{
CHECK(m_isInitialized, ());
for (size_t i = 0; i < m_symbolTextures.size(); ++i)
{
ASSERT(m_symbolTextures[i] != nullptr, ());
ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]);
if (symbolsTexture->IsSymbolContained(symbolName))
{
GetRegionBase(symbolsTexture, region, SymbolsTexture::SymbolKey(symbolName));
region.SetTextureIndex(static_cast<uint32_t>(i));
return;
}
}
LOG(LWARNING, ("Detected using of unknown symbol ", symbolName));
}
bool TextureManager::HasSymbolRegion(std::string const & symbolName) const
{
CHECK(m_isInitialized, ());
for (size_t i = 0; i < m_symbolTextures.size(); ++i)
{
ASSERT(m_symbolTextures[i] != nullptr, ());
ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]);
if (symbolsTexture->IsSymbolContained(symbolName))
return true;
}
return false;
}
void TextureManager::GetStippleRegion(PenPatternT const & pen, StippleRegion & region)
{
CHECK(m_isInitialized, ());
GetRegionBase(make_ref(m_stipplePenTexture), region, StipplePenKey(pen));
}
void TextureManager::GetColorRegion(Color const & color, ColorRegion & region)
{
CHECK(m_isInitialized, ());
GetRegionBase(make_ref(m_colorTexture), region, ColorKey(color));
}
void TextureManager::GetGlyphRegions(TMultilineText const & text, int fixedHeight,
TMultilineGlyphsBuffer & buffers)
{
std::lock_guard<std::mutex> lock(m_calcGlyphsMutex);
CalcGlyphRegions<TMultilineText, TMultilineGlyphsBuffer>(text, fixedHeight, buffers);
}
void TextureManager::GetGlyphRegions(strings::UniString const & text, int fixedHeight,
TGlyphsBuffer & regions)
{
std::lock_guard<std::mutex> lock(m_calcGlyphsMutex);
CalcGlyphRegions<strings::UniString, TGlyphsBuffer>(text, fixedHeight, regions);
}
uint32_t TextureManager::GetAbsentGlyphsCount(ref_ptr<Texture> texture,
strings::UniString const & text,
int fixedHeight) const
{
if (texture == nullptr)
return 0;
ASSERT(dynamic_cast<FontTexture *>(texture.get()) != nullptr, ());
return static_cast<FontTexture *>(texture.get())->GetAbsentGlyphsCount(text, fixedHeight);
}
uint32_t TextureManager::GetAbsentGlyphsCount(ref_ptr<Texture> texture, TMultilineText const & text,
int fixedHeight) const
{
if (texture == nullptr)
return 0;
uint32_t count = 0;
for (size_t i = 0; i < text.size(); ++i)
count += GetAbsentGlyphsCount(texture, text[i], fixedHeight);
return count;
}
bool TextureManager::AreGlyphsReady(strings::UniString const & str, int fixedHeight) const
{
CHECK(m_isInitialized, ());
return m_glyphManager->AreGlyphsReady(str, fixedHeight);
}
ref_ptr<Texture> TextureManager::GetSymbolsTexture() const
{
CHECK(m_isInitialized, ());
ASSERT(!m_symbolTextures.empty(), ());
return make_ref(m_symbolTextures[kDefaultSymbolsIndex]);
}
ref_ptr<Texture> TextureManager::GetTrafficArrowTexture() const
{
CHECK(m_isInitialized, ());
return make_ref(m_trafficArrowTexture);
}
ref_ptr<Texture> TextureManager::GetHatchingTexture() const
{
CHECK(m_isInitialized, ());
return make_ref(m_hatchingTexture);
}
ref_ptr<Texture> TextureManager::GetSMAAAreaTexture() const
{
CHECK(m_isInitialized, ());
return make_ref(m_smaaAreaTexture);
}
ref_ptr<Texture> TextureManager::GetSMAASearchTexture() const
{
CHECK(m_isInitialized, ());
return make_ref(m_smaaSearchTexture);
}
constexpr size_t TextureManager::GetInvalidGlyphGroup()
{
return kInvalidGlyphGroup;
}
} // namespace dp
| 32.436187 | 113 | 0.707839 | Kazing |
dbb248fe16302798afd7c52255e7ff9b70068f87 | 1,971 | cpp | C++ | tests/fingerprint/fingerprint_tests.cpp | lighthouse-os/hardware_libhardware | c6fa046a69d9b1adf474cf5de58318b677801e49 | [
"Apache-2.0"
] | 9 | 2017-11-10T15:54:02.000Z | 2021-04-15T20:57:29.000Z | libhardware/tests/fingerprint/fingerprint_tests.cpp | Keneral/ahardware | 9a8a025f7c9471444c9e271bbe7f48182741d710 | [
"Unlicense"
] | null | null | null | libhardware/tests/fingerprint/fingerprint_tests.cpp | Keneral/ahardware | 9a8a025f7c9471444c9e271bbe7f48182741d710 | [
"Unlicense"
] | 7 | 2018-01-08T02:53:32.000Z | 2020-10-15T13:01:46.000Z | /*
* Copyright (C) 2014 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 <gtest/gtest.h>
#include "fingerprint_test_fixtures.h"
namespace tests {
TEST_F(FingerprintDevice, isThereEnroll) {
ASSERT_TRUE(NULL != fp_device()->enroll)
<< "enroll() function is not implemented";
}
TEST_F(FingerprintDevice, isTherePreEnroll) {
ASSERT_TRUE(NULL != fp_device()->pre_enroll)
<< "pre_enroll() function is not implemented";
}
TEST_F(FingerprintDevice, isThereGetAuthenticatorId) {
ASSERT_TRUE(NULL != fp_device()->get_authenticator_id)
<< "get_authenticator_id() function is not implemented";
}
TEST_F(FingerprintDevice, isThereCancel) {
ASSERT_TRUE(NULL != fp_device()->cancel)
<< "cancel() function is not implemented";
}
TEST_F(FingerprintDevice, isThereRemove) {
ASSERT_TRUE(NULL != fp_device()->remove)
<< "remove() function is not implemented";
}
TEST_F(FingerprintDevice, isThereAuthenticate) {
ASSERT_TRUE(NULL != fp_device()->authenticate)
<< "authenticate() function is not implemented";
}
TEST_F(FingerprintDevice, isThereSetActiveGroup) {
ASSERT_TRUE(NULL != fp_device()->set_active_group)
<< "set_active_group() function is not implemented";
}
TEST_F(FingerprintDevice, isThereSetNotify) {
ASSERT_TRUE(NULL != fp_device()->set_notify)
<< "set_notify() function is not implemented";
}
} // namespace tests
| 31.285714 | 75 | 0.716388 | lighthouse-os |
dbb483ea8fde9dc6114fe4803970c61c10d66a28 | 3,539 | hpp | C++ | include/mbgl/text/types.hpp | free1978/mapbox-gl-native | 2a50fccd24e762d0de5a53bac358e5ddfea8d213 | [
"BSD-2-Clause"
] | 2 | 2017-02-28T22:41:54.000Z | 2020-02-13T20:54:55.000Z | include/mbgl/text/types.hpp | free1978/mapbox-gl-native | 2a50fccd24e762d0de5a53bac358e5ddfea8d213 | [
"BSD-2-Clause"
] | null | null | null | include/mbgl/text/types.hpp | free1978/mapbox-gl-native | 2a50fccd24e762d0de5a53bac358e5ddfea8d213 | [
"BSD-2-Clause"
] | null | null | null | #ifndef MBGL_TEXT_TYPES
#define MBGL_TEXT_TYPES
#include <mbgl/util/vec.hpp>
#include <mbgl/util/rect.hpp>
#include <array>
#include <vector>
#include <boost/optional.hpp>
namespace mbgl {
typedef vec2<float> CollisionPoint;
typedef vec2<float> CollisionAnchor;
typedef std::array<float, 2> PlacementRange;
typedef float CollisionAngle;
typedef std::vector<CollisionAngle> CollisionAngles;
typedef std::array<CollisionAngle, 2> CollisionRange;
typedef std::vector<CollisionRange> CollisionList;
typedef std::array<CollisionPoint, 4> CollisionCorners;
struct CollisionRect {
CollisionPoint tl;
CollisionPoint br;
inline explicit CollisionRect() {}
inline explicit CollisionRect(CollisionPoint::Type ax,
CollisionPoint::Type ay,
CollisionPoint::Type bx,
CollisionPoint::Type by)
: tl(ax, ay), br(bx, by) {}
inline explicit CollisionRect(const CollisionPoint &tl,
const CollisionPoint &br)
: tl(tl), br(br) {}
};
// These are the glyph boxes that we want to have placed.
struct GlyphBox {
explicit GlyphBox() {}
explicit GlyphBox(const CollisionRect &box,
const CollisionAnchor &anchor,
float minScale,
float maxScale,
float padding)
: box(box), anchor(anchor), minScale(minScale), maxScale(maxScale), padding(padding) {}
explicit GlyphBox(const CollisionRect &box,
float minScale,
float padding)
: box(box), minScale(minScale), padding(padding) {}
CollisionRect box;
CollisionAnchor anchor;
float minScale = 0.0f;
float maxScale = std::numeric_limits<float>::infinity();
float padding = 0.0f;
boost::optional<CollisionRect> hBox;
};
typedef std::vector<GlyphBox> GlyphBoxes;
// TODO: Transform the vec2<float>s to vec2<int16_t> to save bytes
struct PlacedGlyph {
explicit PlacedGlyph(const vec2<float> &tl, const vec2<float> &tr,
const vec2<float> &bl, const vec2<float> &br,
const Rect<uint16_t> &tex, float angle, const vec2<float> &anchor,
float minScale, float maxScale)
: tl(tl),
tr(tr),
bl(bl),
br(br),
tex(tex),
angle(angle),
anchor(anchor),
minScale(minScale),
maxScale(maxScale) {}
vec2<float> tl, tr, bl, br;
Rect<uint16_t> tex;
float angle;
vec2<float> anchor;
float minScale, maxScale;
};
typedef std::vector<PlacedGlyph> PlacedGlyphs;
// These are the placed boxes contained in the rtree.
struct PlacementBox {
CollisionAnchor anchor;
CollisionRect box;
boost::optional<CollisionRect> hBox;
PlacementRange placementRange = {{0.0f, 0.0f}};
float placementScale = 0.0f;
float maxScale = std::numeric_limits<float>::infinity();
float padding = 0.0f;
};
struct PlacementProperty {
explicit PlacementProperty() {}
explicit PlacementProperty(float zoom, const PlacementRange &rotationRange)
: zoom(zoom), rotationRange(rotationRange) {}
inline operator bool() const {
return !std::isnan(zoom) && zoom != std::numeric_limits<float>::infinity() &&
rotationRange[0] != rotationRange[1];
}
float zoom = std::numeric_limits<float>::infinity();
PlacementRange rotationRange = {{0.0f, 0.0f}};
};
}
#endif
| 30.773913 | 95 | 0.626731 | free1978 |
dbb543019697b06a8f366a7ce4db4d983912d996 | 1,550 | cpp | C++ | Tutorial2/main.cpp | asm128/gpftw | 984eec9a0cb6047000dda98c03696592406154a8 | [
"MIT"
] | 1 | 2017-06-19T22:19:30.000Z | 2017-06-19T22:19:30.000Z | Tutorial2/main.cpp | asm128/gpftw | 984eec9a0cb6047000dda98c03696592406154a8 | [
"MIT"
] | 4 | 2017-06-16T23:25:37.000Z | 2017-07-01T01:33:25.000Z | Tutorial2/main.cpp | asm128/gpftw | 984eec9a0cb6047000dda98c03696592406154a8 | [
"MIT"
] | null | null | null | // Tip: Hold Left ALT + SHIFT while tapping or holding the arrow keys in order to select multiple columns and write on them at once.
// Also useful for copy & paste operations in which you need to copy a bunch of variable or function names and you can't afford the time of copying them one by one.
//
#include <stdio.h> // for printf()
#include <windows.h> // for interacting with Windows with GetAsyncKeyState()
// Define some functions to use from main(). These functions will contain our game code.
void setup () { printf("- setup() called.\n" ); }
void update () { printf("- update() called.\n" ); }
void draw () { printf("- draw() called.\n" ); }
int main () {
setup(); // Call setup()
int frameCounter = 0; // declare and initialize a variable of (int)eger type for keeping track of the number of frame since execution began.
while( true ) { // Execute code between braces while the condition inside () evaluates to true.
printf("Current frame number: %i\n", frameCounter); // Print the frame count.
update (); // Update frame.
draw (); // Render frame.
if(GetAsyncKeyState(VK_ESCAPE)) // Check for escape key pressed and execute code between braces if the condition between () evaluates to "true".
{
break; // Exit while() loop.
}
Sleep(50); // Wait 50 milliseconds then continue executing
frameCounter = frameCounter + 1; // increase our frame counter by 1
}
return 0; // Exit from the function returning an (int)eger.
}
| 51.666667 | 165 | 0.66 | asm128 |
dbb6b7c9b79e37132c4742471b20dd37a9310a52 | 7,343 | hpp | C++ | include/System/Linq/Expressions/Interpreter/NewArrayInstruction.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Linq/Expressions/Interpreter/NewArrayInstruction.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Linq/Expressions/Interpreter/NewArrayInstruction.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Linq.Expressions.Interpreter.Instruction
#include "System/Linq/Expressions/Interpreter/Instruction.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Forward declaring namespace: System::Linq::Expressions::Interpreter
namespace System::Linq::Expressions::Interpreter {
// Forward declaring type: InterpretedFrame
class InterpretedFrame;
}
// Completed forward declares
// Type namespace: System.Linq.Expressions.Interpreter
namespace System::Linq::Expressions::Interpreter {
// Forward declaring type: NewArrayInstruction
class NewArrayInstruction;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Linq::Expressions::Interpreter::NewArrayInstruction);
DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Expressions::Interpreter::NewArrayInstruction*, "System.Linq.Expressions.Interpreter", "NewArrayInstruction");
// Type namespace: System.Linq.Expressions.Interpreter
namespace System::Linq::Expressions::Interpreter {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: System.Linq.Expressions.Interpreter.NewArrayInstruction
// [TokenAttribute] Offset: FFFFFFFF
class NewArrayInstruction : public ::System::Linq::Expressions::Interpreter::Instruction {
public:
public:
// private readonly System.Type _elementType
// Size: 0x8
// Offset: 0x10
::System::Type* elementType;
// Field size check
static_assert(sizeof(::System::Type*) == 0x8);
public:
// Creating conversion operator: operator ::System::Type*
constexpr operator ::System::Type*() const noexcept {
return elementType;
}
// Get instance field reference: private readonly System.Type _elementType
[[deprecated("Use field access instead!")]] ::System::Type*& dyn__elementType();
// System.Void .ctor(System.Type elementType)
// Offset: 0xE941CC
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static NewArrayInstruction* New_ctor(::System::Type* elementType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NewArrayInstruction::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<NewArrayInstruction*, creationType>(elementType)));
}
// public override System.Int32 get_ConsumedStack()
// Offset: 0xE941F8
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.Int32 Instruction::get_ConsumedStack()
int get_ConsumedStack();
// public override System.Int32 get_ProducedStack()
// Offset: 0xE94200
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.Int32 Instruction::get_ProducedStack()
int get_ProducedStack();
// public override System.String get_InstructionName()
// Offset: 0xE94208
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.String Instruction::get_InstructionName()
::StringW get_InstructionName();
// public override System.Int32 Run(System.Linq.Expressions.Interpreter.InterpretedFrame frame)
// Offset: 0xE9424C
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.Int32 Instruction::Run(System.Linq.Expressions.Interpreter.InterpretedFrame frame)
int Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame);
}; // System.Linq.Expressions.Interpreter.NewArrayInstruction
#pragma pack(pop)
static check_size<sizeof(NewArrayInstruction), 16 + sizeof(::System::Type*)> __System_Linq_Expressions_Interpreter_NewArrayInstructionSizeCheck;
static_assert(sizeof(NewArrayInstruction) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ConsumedStack
// Il2CppName: get_ConsumedStack
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ConsumedStack)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_ConsumedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ProducedStack
// Il2CppName: get_ProducedStack
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ProducedStack)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_ProducedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_InstructionName
// Il2CppName: get_InstructionName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_InstructionName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_InstructionName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::Run
// Il2CppName: Run
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)(::System::Linq::Expressions::Interpreter::InterpretedFrame*)>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::Run)> {
static const MethodInfo* get() {
static auto* frame = &::il2cpp_utils::GetClassFromName("System.Linq.Expressions.Interpreter", "InterpretedFrame")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "Run", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{frame});
}
};
| 57.367188 | 269 | 0.759226 | v0idp |
dbb8b3d3a659d35a5e24a26da9e4bc0b452ee38f | 417 | hpp | C++ | src/SettingsDialog.hpp | asamy/vendace | ed949d6c7546f3a70582a0354c68a17f26aef6cd | [
"MIT"
] | 1 | 2020-05-02T06:47:48.000Z | 2020-05-02T06:47:48.000Z | src/SettingsDialog.hpp | asamy/vendace | ed949d6c7546f3a70582a0354c68a17f26aef6cd | [
"MIT"
] | null | null | null | src/SettingsDialog.hpp | asamy/vendace | ed949d6c7546f3a70582a0354c68a17f26aef6cd | [
"MIT"
] | null | null | null | #ifndef SETTINGS_DIALOG_HPP
#define SETTINGS_DIALOG_HPP
#include <QDialog>
#include "Settings.hpp"
#include "ui_settings.h"
class SettingsDialog : public QDialog {
Q_OBJECT
public:
SettingsDialog(QWidget *parent);
protected slots:
void editorPathChanged(QString);
void browseEditorPath();
private:
Ui::SettingsDialog mUi;
Settings mSettings;
};
#endif
| 15.444444 | 40 | 0.681055 | asamy |
dbbef1d6a5f29ac9f34d29d7a967cdc71a42b1a7 | 934 | hpp | C++ | includes.hpp | ph-moura/Spending-Control | a87836db644e35ded695c7736b11b608ba95e8a8 | [
"MIT"
] | null | null | null | includes.hpp | ph-moura/Spending-Control | a87836db644e35ded695c7736b11b608ba95e8a8 | [
"MIT"
] | null | null | null | includes.hpp | ph-moura/Spending-Control | a87836db644e35ded695c7736b11b608ba95e8a8 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <QAbstractBarSeries>
#include <QApplication>
#include <QBoxLayout>
#include <QClipboard>
#include <QComboBox>
#include <QDateEdit>
#include <QDateTimeEdit>
#include <QDebug>
#include <QFileInfo>
#include <QFormLayout>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
#include <QLineEdit>
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QObject>
#include <QProgressBar>
#include <QPushButton>
#include <QResource>
#include <QSlider>
#include <QString>
#include <QStringList>
#include <QTableWidget>
#include <QtCharts>
#include <QtCore>
#include <QTextEdit>
#include <QTextStream>
#include <QtGui>
#include <QTimeEdit>
#include <QtWidgets/QToolBar>
#include <QVBoxLayout>
#include <QWidget>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#pragma once
| 19.87234 | 29 | 0.75803 | ph-moura |
dbbf1c1c89d206b291bb86f06297c077d52ff671 | 4,812 | cpp | C++ | src/libclang/friend_parser.cpp | stevencpp/cppast | ab7a9b6627cc9ccc34ed30473957741ed0be00d7 | [
"MIT"
] | null | null | null | src/libclang/friend_parser.cpp | stevencpp/cppast | ab7a9b6627cc9ccc34ed30473957741ed0be00d7 | [
"MIT"
] | null | null | null | src/libclang/friend_parser.cpp | stevencpp/cppast | ab7a9b6627cc9ccc34ed30473957741ed0be00d7 | [
"MIT"
] | null | null | null | // Copyright (C) 2017-2018 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#include <cppast/cpp_friend.hpp>
#include <cppast/cpp_template.hpp>
#include <cppast/cpp_template_parameter.hpp>
#include "libclang_visitor.hpp"
#include "parse_functions.hpp"
using namespace cppast;
std::unique_ptr<cpp_entity> detail::parse_cpp_friend(const detail::parse_context& context,
const CXCursor& cur)
{
DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_FriendDecl, detail::assert_handler{});
std::string comment;
std::unique_ptr<cpp_entity> entity;
std::unique_ptr<cpp_type> type;
std::string namespace_str;
type_safe::optional<cpp_template_instantiation_type::builder> inst_builder;
detail::visit_children(cur, [&](const CXCursor& child) {
auto kind = clang_getCursorKind(child);
if (kind == CXCursor_TypeRef)
{
auto referenced = clang_getCursorReferenced(child);
if (inst_builder)
{
namespace_str.clear();
inst_builder.value().add_argument(
detail::parse_type(context, referenced, clang_getCursorType(referenced)));
}
else if (clang_getCursorKind(referenced) == CXCursor_TemplateTypeParameter)
// parse template parameter type
type = cpp_template_parameter_type::build(
cpp_template_type_parameter_ref(detail::get_entity_id(referenced),
detail::get_cursor_name(child).c_str()));
else if (!namespace_str.empty())
{
// parse as user defined type
// we can't use the other branch here,
// as then the class name would be wrong
auto name = detail::get_cursor_name(referenced);
type = cpp_user_defined_type::build(
cpp_type_ref(detail::get_entity_id(referenced),
namespace_str + "::" + name.c_str()));
}
else
{
// for some reason libclang gives a type ref here
// we actually need a class decl cursor, so parse the referenced one
// this might be a definition, so give friend information to the parser
entity = parse_entity(context, nullptr, referenced, cur);
comment = type_safe::copy(entity->comment()).value_or("");
}
}
else if (kind == CXCursor_NamespaceRef)
namespace_str += detail::get_cursor_name(child).c_str();
else if (kind == CXCursor_TemplateRef)
{
if (!namespace_str.empty())
namespace_str += "::";
auto templ = cpp_template_ref(detail::get_entity_id(clang_getCursorReferenced(child)),
namespace_str + detail::get_cursor_name(child).c_str());
namespace_str.clear();
if (!inst_builder)
inst_builder = cpp_template_instantiation_type::builder(std::move(templ));
else
inst_builder.value().add_argument(std::move(templ));
}
else if (clang_isDeclaration(kind))
{
entity = parse_entity(context, nullptr, child, cur);
if (entity)
{
// steal comment
comment = type_safe::copy(entity->comment()).value_or("");
entity->set_comment(type_safe::nullopt);
}
}
else if (inst_builder && clang_isExpression(kind))
{
namespace_str.clear();
inst_builder.value().add_argument(detail::parse_expression(context, child));
}
});
std::unique_ptr<cpp_entity> result;
if (entity)
result = cpp_friend::build(std::move(entity));
else if (type)
result = cpp_friend::build(std::move(type));
else if (inst_builder)
result = cpp_friend::build(inst_builder.value().finish());
else
DEBUG_UNREACHABLE(detail::parse_error_handler{}, cur,
"unknown child entity of friend declaration");
if (!comment.empty())
// set comment of entity...
result->set_comment(std::move(comment));
// ... but override if this finds a different comment
// due to clang_getCursorReferenced(), this may happen
context.comments.match(*result, cur);
return result;
}
| 44.146789 | 98 | 0.564838 | stevencpp |
dbc0643feecb461fe688b90149e7b4f4689c8283 | 1,375 | cpp | C++ | JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Manager/Input/Input.cpp | Jaraffe-github/Old_Engines | 0586d383af99cfcf076b18dace49e779a55b88e8 | [
"BSD-3-Clause"
] | null | null | null | JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Manager/Input/Input.cpp | Jaraffe-github/Old_Engines | 0586d383af99cfcf076b18dace49e779a55b88e8 | [
"BSD-3-Clause"
] | null | null | null | JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Manager/Input/Input.cpp | Jaraffe-github/Old_Engines | 0586d383af99cfcf076b18dace49e779a55b88e8 | [
"BSD-3-Clause"
] | null | null | null | #include "stdafx.h"
#include "Input.h"
JF::JFCInput::JFCInput()
{
memset(m_bKeyCodeArray, 0, sizeof(m_bKeyCodeArray));
memset(m_bKeyCodeArrayUp, 0, sizeof(m_bKeyCodeArrayUp));
m_vMousePos = { 0, 0, 0 };
m_vClickPos = { 0, 0, 0 };
}
JF::JFCInput::~JFCInput()
{
}
void JF::JFCInput::OnKeyDown(WPARAM wParam)
{
m_bKeyCodeArray[wParam] = true;
m_bKeyCodeArrayUp[wParam] = false;
}
void JF::JFCInput::OnKeyUp(WPARAM wParam)
{
m_bKeyCodeArray[wParam] = false;
m_bKeyCodeArrayUp[wParam] = true;
}
void JF::JFCInput::OnMouseMove(LPARAM lParam)
{
m_vMousePos.x = LOWORD(lParam);
m_vMousePos.y = HIWORD(lParam);
}
void JF::JFCInput::OnMouseClick(LPARAM lParam)
{
m_vClickPos.x = LOWORD(lParam);
m_vClickPos.y = HIWORD(lParam);
}
bool JF::JFCInput::GetKey(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
bool JF::JFCInput::GetKeyDown(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
bool JF::JFCInput::GetKeyUP(WPARAM wParam)
{
bool ret = m_bKeyCodeArrayUp[wParam];
m_bKeyCodeArrayUp[wParam] = false;
return ret;
}
bool JF::JFCInput::GetMouseButton(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
bool JF::JFCInput::GetMouseButtonDown(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
bool JF::JFCInput::GetMouseButtonUp(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
XMFLOAT3 JF::JFCInput::GetMousePosition() const
{
return m_vMousePos;
} | 18.333333 | 57 | 0.736 | Jaraffe-github |
dbc6d19e3ee35fe7a472a8e29bf60303513845ae | 1,528 | hpp | C++ | example/cust_paper/std_mem_usage/traits/framework/mem_usage.hpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 105 | 2015-01-24T13:26:41.000Z | 2022-02-18T15:36:53.000Z | example/cust_paper/std_mem_usage/traits/framework/mem_usage.hpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 37 | 2015-09-04T06:57:10.000Z | 2021-09-09T18:01:44.000Z | example/cust_paper/std_mem_usage/traits/framework/mem_usage.hpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 23 | 2015-01-27T11:09:18.000Z | 2021-10-04T02:23:30.000Z | // Copyright (C) 2016 Vicente J. Botet Escriba
//
// 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 JASEL_EXAMPLE_FRAMEWORK_MEM_USAGE_HPP
#define JASEL_EXAMPLE_FRAMEWORK_MEM_USAGE_HPP
#if __cplusplus >= 201402L
#include <type_traits>
#include <experimental/meta.hpp>
#include <cstddef>
// mem_usage_able/mem_usage.hpp
namespace std
{
namespace experimental
{
inline namespace fundamental_v3
{
namespace mem_usage_able
{
template <typename T, typename Enabler=void>
struct traits : traits<T, meta::when<true>> {};
template <typename R, bool B>
struct traits<R, meta::when<B>>
{
template <typename T>
static constexpr size_t apply(T&& v) = delete;
};
template <typename R>
struct traits<R, meta::when<std::is_trivial<R>::value>>
{
template <typename T>
static constexpr size_t apply(T&& ) noexcept { return sizeof ( remove_cv_t<remove_reference_t<T>> ); }
};
template <typename T>
constexpr auto mem_usage(T&& v) noexcept -> decltype(traits<remove_cv_t<remove_reference_t<T>>>::apply(std::forward<T>(v)))
{
return traits<remove_cv_t<remove_reference_t<T>>>::apply(std::forward<T>(v));
}
template <typename R>
struct traits<R*>
{
template <typename T>
static constexpr auto apply(T* v) noexcept -> decltype( mem_usage_able::mem_usage ( *v ) )
{
return sizeof v + (v?mem_usage_able::mem_usage ( *v ):0);
}
};
}
}
}
}
#endif
#endif
| 23.875 | 125 | 0.700916 | jwakely |
3a79ae0112806f5d82d7682409448ed0ad6f2758 | 634 | hpp | C++ | source/ashes/renderer/D3D11Renderer/Buffer/D3D11BufferView.hpp | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 227 | 2018-09-17T16:03:35.000Z | 2022-03-19T02:02:45.000Z | source/ashes/renderer/D3D11Renderer/Buffer/D3D11BufferView.hpp | DragonJoker/RendererLib | 0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a | [
"MIT"
] | 39 | 2018-02-06T22:22:24.000Z | 2018-08-29T07:11:06.000Z | source/ashes/renderer/D3D11Renderer/Buffer/D3D11BufferView.hpp | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 8 | 2019-05-04T10:33:32.000Z | 2021-04-05T13:19:27.000Z | /**
*\file
* TestBufferView.h
*\author
* Sylvain Doremus
*/
#ifndef ___D3D11Renderer_BufferView_HPP___
#define ___D3D11Renderer_BufferView_HPP___
#pragma once
#include "renderer/D3D11Renderer/D3D11RendererPrerequisites.hpp"
namespace ashes::d3d11
{
class BufferView
{
public:
BufferView( VkDevice device
, VkBufferViewCreateInfo createInfo );
~BufferView();
inline ID3D11ShaderResourceView * getView()const
{
return m_view;
}
inline VkDevice getDevice()const
{
return m_device;
}
private:
VkDevice m_device;
VkBufferViewCreateInfo m_createInfo;
ID3D11ShaderResourceView * m_view;
};
}
#endif
| 15.85 | 64 | 0.757098 | DragonJoker |
3a79f70814e9b0f0cfaeda0a987dc27d744ba1f5 | 5,800 | cpp | C++ | src/xercesc/internal/ValidationContextImpl.cpp | rsn8887/xerces-c-1 | be81663b9a6907a0db4d5a893a393865a1ebcbc6 | [
"Apache-2.0"
] | 486 | 2018-03-07T17:15:03.000Z | 2019-05-06T20:05:44.000Z | src/xercesc/internal/ValidationContextImpl.cpp | rsn8887/xerces-c-1 | be81663b9a6907a0db4d5a893a393865a1ebcbc6 | [
"Apache-2.0"
] | 172 | 2019-05-14T18:56:36.000Z | 2022-03-30T16:35:24.000Z | src/xercesc/internal/ValidationContextImpl.cpp | rsn8887/xerces-c-1 | be81663b9a6907a0db4d5a893a393865a1ebcbc6 | [
"Apache-2.0"
] | 83 | 2019-05-29T18:38:36.000Z | 2022-03-17T07:34:16.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.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/ValidationContextImpl.hpp>
#include <xercesc/framework/XMLRefInfo.hpp>
#include <xercesc/validators/DTD/DTDEntityDecl.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/validators/schema/NamespaceScope.hpp>
#include <xercesc/internal/ElemStack.hpp>
#include <xercesc/internal/XMLScanner.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Constructor and Destructor
// ---------------------------------------------------------------------------
ValidationContextImpl::~ValidationContextImpl()
{
if (fIdRefList)
delete fIdRefList;
}
ValidationContextImpl::ValidationContextImpl(MemoryManager* const manager)
:ValidationContext(manager)
,fIdRefList(0)
,fEntityDeclPool(0)
,fToCheckIdRefList(true)
,fValidatingMemberType(0)
,fElemStack(0)
,fScanner(0)
,fNamespaceScope(0)
{
fIdRefList = new (fMemoryManager) RefHashTableOf<XMLRefInfo>(109, fMemoryManager);
}
/**
* IdRefList
*
*/
RefHashTableOf<XMLRefInfo>* ValidationContextImpl::getIdRefList() const
{
return fIdRefList;
}
void ValidationContextImpl::setIdRefList(RefHashTableOf<XMLRefInfo>* const newIdRefList)
{
if (fIdRefList)
delete fIdRefList;
fIdRefList = newIdRefList;
}
void ValidationContextImpl::clearIdRefList()
{
if (fIdRefList)
fIdRefList->removeAll();
}
void ValidationContextImpl::addId(const XMLCh * const content)
{
if (!fIdRefList || !fToCheckIdRefList)
return;
XMLRefInfo* idEntry = fIdRefList->get(content);
if (idEntry)
{
if (idEntry->getDeclared())
{
ThrowXMLwithMemMgr1(InvalidDatatypeValueException
, XMLExcepts::VALUE_ID_Not_Unique
, content
, fMemoryManager);
}
}
else
{
idEntry = new (fMemoryManager) XMLRefInfo(content, false, false, fMemoryManager);
fIdRefList->put((void*)idEntry->getRefName(), idEntry);
}
//
// Mark it declared
//
idEntry->setDeclared(true);
}
void ValidationContextImpl::addIdRef(const XMLCh * const content)
{
if (!fIdRefList || !fToCheckIdRefList)
return;
XMLRefInfo* idEntry = fIdRefList->get(content);
if (!idEntry)
{
idEntry = new (fMemoryManager) XMLRefInfo(content, false, false, fMemoryManager);
fIdRefList->put((void*)idEntry->getRefName(), idEntry);
}
//
// Mark it used
//
idEntry->setUsed(true);
}
void ValidationContextImpl::toCheckIdRefList(bool toCheck)
{
fToCheckIdRefList = toCheck;
}
/**
* EntityDeclPool
*
*/
const NameIdPool<DTDEntityDecl>* ValidationContextImpl::getEntityDeclPool() const
{
return fEntityDeclPool;
}
const NameIdPool<DTDEntityDecl>* ValidationContextImpl::setEntityDeclPool(const NameIdPool<DTDEntityDecl>* const newEntityDeclPool)
{
// we don't own it so we return the existing one for the owner to delete
const NameIdPool<DTDEntityDecl>* tempPool = fEntityDeclPool;
fEntityDeclPool = newEntityDeclPool;
return tempPool;
}
void ValidationContextImpl::checkEntity(const XMLCh * const content) const
{
if (fEntityDeclPool)
{
const DTDEntityDecl* decl = fEntityDeclPool->getByKey(content);
if (!decl || !decl->isUnparsed())
{
ThrowXMLwithMemMgr1(InvalidDatatypeValueException
, XMLExcepts::VALUE_ENTITY_Invalid
, content
, fMemoryManager);
}
}
else
{
ThrowXMLwithMemMgr1
(
InvalidDatatypeValueException
, XMLExcepts::VALUE_ENTITY_Invalid
, content
, fMemoryManager
);
}
}
/* QName
*/
bool ValidationContextImpl::isPrefixUnknown(XMLCh* prefix) {
bool unknown = false;
if (XMLString::equals(prefix, XMLUni::fgXMLNSString)) {
return true;
}
else if (!XMLString::equals(prefix, XMLUni::fgXMLString)) {
if(fElemStack && !fElemStack->isEmpty())
fElemStack->mapPrefixToURI(prefix, unknown);
else if(fNamespaceScope)
unknown = (fNamespaceScope->getNamespaceForPrefix(prefix)==fNamespaceScope->getEmptyNamespaceId());
}
return unknown;
}
const XMLCh* ValidationContextImpl::getURIForPrefix(XMLCh* prefix) {
bool unknown = false;
unsigned int uriId = 0;
if(fElemStack)
uriId = fElemStack->mapPrefixToURI(prefix, unknown);
else if(fNamespaceScope)
{
uriId = fNamespaceScope->getNamespaceForPrefix(prefix);
unknown = uriId == fNamespaceScope->getEmptyNamespaceId();
}
if (!unknown)
return fScanner->getURIText(uriId);
return XMLUni::fgZeroLenString;
}
XERCES_CPP_NAMESPACE_END
| 26.605505 | 131 | 0.648276 | rsn8887 |
3a808b47a696adfe6813a4eb586d4916de517bab | 6,734 | hpp | C++ | MathIO.hpp | Elfhir/WoodyNatasha | febdae58ca3ad16fdf2b5fc4273b7ab177ed392f | [
"Beerware"
] | 1 | 2015-01-30T22:30:57.000Z | 2015-01-30T22:30:57.000Z | MathIO.hpp | Elfhir/WoodyNatasha | febdae58ca3ad16fdf2b5fc4273b7ab177ed392f | [
"Beerware"
] | null | null | null | MathIO.hpp | Elfhir/WoodyNatasha | febdae58ca3ad16fdf2b5fc4273b7ab177ed392f | [
"Beerware"
] | null | null | null | /*
* Anti-doublon
*/
#ifndef __OPENKN_MATH__MATH_IO_HPP__
#define __OPENKN_MATH__MATH_IO_HPP__
/*
* External Includes
*/
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include "Eigen/Dense"
using namespace Eigen;
/*
* Namespace
*/
namespace kn {
/**
* \cond
* \brief ignore the comments and read the header on a matrix file if specified; the user should not use this function.
* \param matrixFile the input matrix ifstream
* \return true if the matrix format is spefifyed, false otherwise
* \throw MathException invalid format
*/
bool readMatrixHeader(std::ifstream &matrixFile, unsigned int &row, unsigned int &column);
/// \endcond
/**
* \cond
* \brief ignore the comments and read the header on a matrix file if specified; the user should not use this function.
* \param matrixFile the input matrix ifstream
* \return true if the matrix format is spefifyed, false otherwise
* \throw MathException invalid format
*/
bool readMatrixHeader(std::ifstream &matrixFile, unsigned int &mat);
/// \endcond
/**
* \brief Load a Matrix from a file. The format is : some optional comments begining by '#', a optional header writing "row " and the number of rows, in the next line, "column " and the number of columns, and then, line by line, the matrix content.
* \param M the Matrix to be loaded
* \param fileName the name of the file to open
* \throw MathException matrix size is incorrect / error opening file / invalid format
*/
template <class EigenMatrix>
void loadMatrix(EigenMatrix &M, const std::string &fileName){
// open the file
std::ifstream matrixFile(fileName.c_str());
if(!matrixFile.is_open()){
std::cerr << "error opening file : " << fileName << std::endl;
exit(0);
}
// read header
unsigned int row = 0;
unsigned int column = 0;
bool header = readMatrixHeader(matrixFile,row,column);
// read the data
if(header) readMatrixFromHeader(M,matrixFile,row,column);
else readMatrix(M,matrixFile);
// close
matrixFile.close();
}
/**
* \cond
* \brief read the content of a Matrix from the header information (row,col); the user should not use this function.
* \param M the Matrix to be filled
* \param matrixFile the input matrix ifstream
* \param row the expected matrix row number
* \param column the expected matrix column number
* \throw MathException incompatible matrix size
*/
template <class EigenMatrix>
void readMatrixFromHeader(EigenMatrix &M,
std::ifstream &matrixFile,
const unsigned int &row,
const unsigned int &column) {
// if the matrix is already build
if((unsigned int)M.rows() != row || (unsigned int)M.cols() != column)
M.resize(row,column);
// read the matrix
for(unsigned int i=0; i<row; ++i)
for(unsigned int j=0; j<column; ++j)
matrixFile >> M(i,j);
}
/// \endcond
/**
* \cond
* \brief read the content of a Matrix without any size information (row,col); the user should not use this function.
* \param M the Matrix to be filled
* \param matrixFile the input matrix ifstream
* \throw MathException incompatible matrix size / invalid matrix file
*/
template <class EigenMatrix>
void readMatrix(EigenMatrix &M, std::ifstream &matrixFile){
unsigned int row = 0;
int column = -1; // unknown while you didn't read a line
std::vector<double> content;
std::string stringContent;
// first read the matrix in a std::vector to check the consistency of the data
do{ // for every line
std::getline(matrixFile,stringContent);
std::istringstream readContent(stringContent, std::istringstream::in);
unsigned int index = 0;
while(!readContent.eof() && stringContent != ""){ // for every element of a line
double value;
readContent >> value;
content.push_back(value);
index++;
}
// remove the eof
//content.erase(content.end()-1);
//index--;
if(column == -1 && index != 0){ // 1st line : find 'column'
column = index;
row++;
}else{
if(index != 0){ // check empty line or invalid column
if(column != (int)index ){
std::cerr << "readMatrix : invalid matrix file" << std::endl;
exit(0);
}else row++;
}else{
//Matrix reading complete (empty line found)
break;
}
}
}
while(!matrixFile.eof());
if(row==0 && column==-1) return;
// if the matrix is already build
if((unsigned int)M.rows() != row || M.cols() != column)
M.resize(row,column);
// copy the data
for(unsigned int i=0; i<row; ++i)
for(int j=0; j<column; ++j)
M(i,j) = content[i*column+j];
//std::copy(content.begin(), content.end(), M.data());
}
/// \endcond
/**
* \brief Export a Matrix in a file. The format is : some optional comments begining by '#', a optional header writing "row " and the number of rows, in the next line, "column " and the number of columns, and then, line by line, the matrix content.
* \param M the Matrix to be exported
* \param fileName the name of the target file
* \param headerMode if true, write the number of row and colums before the data, else write directly the data
* \param comments add some comments at the begining of the file, the caracter "#" is automatically added
* \throw MathException error opening file
*/
template <class EigenMatrix>
void saveMatrix(const EigenMatrix &M,
const std::string &fileName,
const bool headerMode = false,
const std::string &comments = "") {
// open the file
std::ofstream matrixFile(fileName.c_str());
if(!matrixFile.is_open()){
std::cerr << "error opening file : " << fileName << std::endl;
exit(0);
}
// write comments
if(comments != "")
matrixFile << "# " << comments << std::endl;
// write header
if(headerMode)
matrixFile << "row " << M.rows() << std::endl
<< "col " << M.cols() << std::endl;
// additional line
if(comments != "" || headerMode)
matrixFile << std::endl;
// write matrix content
for (unsigned int i=0; i<(unsigned int)M.rows(); ++i){
for (unsigned int j=0; j<(unsigned int)M.cols(); ++j)
matrixFile << M(i,j) << " ";
matrixFile << std::endl;
}
// close file
matrixFile.close();
}
/*
* End of Namespace
*/
}
/*
* End of Anti-doublon
*/
#endif
| 29.665198 | 250 | 0.619246 | Elfhir |
3a8263eabf5396b9aa9415df7bb9ce3be77a3a21 | 18,274 | cpp | C++ | cegui/src/widgets/Scrollbar.cpp | rpaciorek/cegui | f64435721df7d0ef0393bf7ace72473d1da1f1ac | [
"MIT"
] | 257 | 2020-01-03T10:13:29.000Z | 2022-03-26T14:55:12.000Z | cegui/src/widgets/Scrollbar.cpp | rpaciorek/cegui | f64435721df7d0ef0393bf7ace72473d1da1f1ac | [
"MIT"
] | 116 | 2020-01-09T18:13:13.000Z | 2022-03-15T18:32:02.000Z | cegui/src/widgets/Scrollbar.cpp | rpaciorek/cegui | f64435721df7d0ef0393bf7ace72473d1da1f1ac | [
"MIT"
] | 58 | 2020-01-09T03:07:02.000Z | 2022-03-22T17:21:36.000Z | /***********************************************************************
created: 13/4/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/widgets/Scrollbar.h"
#include "CEGUI/widgets/Thumb.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/Exceptions.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String Scrollbar::EventNamespace("Scrollbar");
const String Scrollbar::WidgetTypeName("CEGUI/Scrollbar");
//----------------------------------------------------------------------------//
const String Scrollbar::EventScrollPositionChanged("ScrollPositionChanged");
const String Scrollbar::EventThumbTrackStarted("ThumbTrackStarted");
const String Scrollbar::EventThumbTrackEnded("ThumbTrackEnded");
const String Scrollbar::EventScrollConfigChanged("ScrollConfigChanged");
//----------------------------------------------------------------------------//
const String Scrollbar::ThumbName("__auto_thumb__");
const String Scrollbar::IncreaseButtonName("__auto_incbtn__");
const String Scrollbar::DecreaseButtonName("__auto_decbtn__");
//----------------------------------------------------------------------------//
ScrollbarWindowRenderer::ScrollbarWindowRenderer(const String& name) :
WindowRenderer(name, Scrollbar::EventNamespace)
{
}
//----------------------------------------------------------------------------//
Scrollbar::Scrollbar(const String& type, const String& name) :
Window(type, name),
d_documentSize(1.0f),
d_pageSize(0.0f),
d_stepSize(1.0f),
d_overlapSize(0.0f),
d_position(0.0f),
d_endLockPosition(false)
{
addScrollbarProperties();
}
//----------------------------------------------------------------------------//
Scrollbar::~Scrollbar(void)
{
}
//----------------------------------------------------------------------------//
void Scrollbar::initialiseComponents()
{
// Set up thumb
Thumb* const t = getThumb();
t->subscribeEvent(Thumb::EventThumbPositionChanged,
Event::Subscriber(&CEGUI::Scrollbar::handleThumbMoved,
this));
t->subscribeEvent(Thumb::EventThumbTrackStarted,
Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackStarted,
this));
t->subscribeEvent(Thumb::EventThumbTrackEnded,
Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackEnded,
this));
// set up Increase button
getIncreaseButton()->
subscribeEvent(PushButton::EventCursorPressHold,
Event::Subscriber(&CEGUI::Scrollbar::handleIncreaseClicked,
this));
// set up Decrease button
getDecreaseButton()->
subscribeEvent(PushButton::EventCursorPressHold,
Event::Subscriber(&CEGUI::Scrollbar::handleDecreaseClicked,
this));
// do initial layout
Window::initialiseComponents();
}
//----------------------------------------------------------------------------//
void Scrollbar::setDocumentSize(float document_size)
{
if (d_documentSize != document_size)
{
const bool reset_max_position = d_endLockPosition && isAtEnd();
d_documentSize = document_size;
if (reset_max_position)
setScrollPosition(getMaxScrollPosition());
else
updateThumb();
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
}
//----------------------------------------------------------------------------//
void Scrollbar::setPageSize(float page_size)
{
if (d_pageSize != page_size)
{
const bool reset_max_position = d_endLockPosition && isAtEnd();
d_pageSize = page_size;
if (reset_max_position)
setScrollPosition(getMaxScrollPosition());
else
updateThumb();
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
}
//----------------------------------------------------------------------------//
void Scrollbar::setStepSize(float step_size)
{
if (d_stepSize != step_size)
{
d_stepSize = step_size;
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
}
//----------------------------------------------------------------------------//
void Scrollbar::setOverlapSize(float overlap_size)
{
if (d_overlapSize != overlap_size)
{
d_overlapSize = overlap_size;
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
}
//----------------------------------------------------------------------------//
void Scrollbar::setScrollPosition(float position)
{
const bool modified = setScrollPosition_impl(position);
updateThumb();
// notification if required
if (modified)
{
WindowEventArgs args(this);
onScrollPositionChanged(args);
}
}
//----------------------------------------------------------------------------//
bool Scrollbar::validateWindowRenderer(const WindowRenderer* renderer) const
{
return dynamic_cast<const ScrollbarWindowRenderer*>(renderer) != nullptr;
}
//----------------------------------------------------------------------------//
void Scrollbar::onScrollPositionChanged(WindowEventArgs& e)
{
fireEvent(EventScrollPositionChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Scrollbar::onThumbTrackStarted(WindowEventArgs& e)
{
fireEvent(EventThumbTrackStarted, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Scrollbar::onThumbTrackEnded(WindowEventArgs& e)
{
fireEvent(EventThumbTrackEnded, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Scrollbar::onScrollConfigChanged(WindowEventArgs& e)
{
performChildLayout(false, false);
fireEvent(EventScrollConfigChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Scrollbar::onCursorPressHold(CursorInputEventArgs& e)
{
// base class processing
Window::onCursorPressHold(e);
if (e.source != CursorInputSource::Left)
return;
const float adj = getAdjustDirectionFromPoint(e.position);
if (adj > 0)
scrollForwardsByPage();
else if (adj < 0)
scrollBackwardsByPage();
++e.handled;
}
//----------------------------------------------------------------------------//
void Scrollbar::onScroll(CursorInputEventArgs& e)
{
// base class processing
Window::onScroll(e);
// scroll by vertical scroll * stepSize
setScrollPosition(d_position + d_stepSize * -e.scroll);
// ensure the message does not go to our parent.
++e.handled;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleThumbMoved(const EventArgs&)
{
// adjust scroll bar position as required.
setScrollPosition(getValueFromThumb());
return true;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleIncreaseClicked(const EventArgs& e)
{
if (static_cast<const CursorInputEventArgs&>(e).source != CursorInputSource::Left)
return false;
scrollForwardsByStep();
return true;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleDecreaseClicked(const EventArgs& e)
{
if (static_cast<const CursorInputEventArgs&>(e).source != CursorInputSource::Left)
return false;
scrollBackwardsByStep();
return true;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleThumbTrackStarted(const EventArgs&)
{
// simply trigger our own version of this event
WindowEventArgs args(this);
onThumbTrackStarted(args);
return true;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleThumbTrackEnded(const EventArgs&)
{
// simply trigger our own version of this event
WindowEventArgs args(this);
onThumbTrackEnded(args);
return true;
}
//----------------------------------------------------------------------------//
void Scrollbar::addScrollbarProperties(void)
{
const String& propertyOrigin = WidgetTypeName;
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"DocumentSize", "Property to get/set the document size for the Scrollbar. Value is a float.",
&Scrollbar::setDocumentSize, &Scrollbar::getDocumentSize, 1.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"PageSize", "Property to get/set the page size for the Scrollbar. Value is a float.",
&Scrollbar::setPageSize, &Scrollbar::getPageSize, 0.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"StepSize", "Property to get/set the step size for the Scrollbar. Value is a float.",
&Scrollbar::setStepSize, &Scrollbar::getStepSize, 1.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"OverlapSize", "Property to get/set the overlap size for the Scrollbar. Value is a float.",
&Scrollbar::setOverlapSize, &Scrollbar::getOverlapSize, 0.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"ScrollPosition", "Property to get/set the scroll position of the Scrollbar. Value is a float.",
&Scrollbar::setScrollPosition, &Scrollbar::getScrollPosition, 0.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"UnitIntervalScrollPosition",
"Property to access the scroll position of the Scrollbar as a value in "
"the interval [0, 1]. Value is a float.",
&Scrollbar::setUnitIntervalScrollPosition,
&Scrollbar::getUnitIntervalScrollPosition, 0.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, bool,
"EndLockEnabled", "Property to get/set the 'end lock' mode setting for the Scrollbar. "
"Value is either \"true\" or \"false\".",
&Scrollbar::setEndLockEnabled, &Scrollbar::isEndLockEnabled, false
);
}
//----------------------------------------------------------------------------//
void Scrollbar::banPropertiesForAutoWindow()
{
Window::banPropertiesForAutoWindow();
banPropertyFromXML("DocumentSize");
banPropertyFromXML("PageSize");
banPropertyFromXML("StepSize");
banPropertyFromXML("OverlapSize");
banPropertyFromXML("ScrollPosition");
banPropertyFromXML("Visible");
}
//----------------------------------------------------------------------------//
PushButton* Scrollbar::getIncreaseButton() const
{
return static_cast<PushButton*>(getChild(IncreaseButtonName));
}
//----------------------------------------------------------------------------//
PushButton* Scrollbar::getDecreaseButton() const
{
return static_cast<PushButton*>(getChild(DecreaseButtonName));
}
//----------------------------------------------------------------------------//
Thumb* Scrollbar::getThumb() const
{
return static_cast<Thumb*>(getChild(ThumbName));
}
//----------------------------------------------------------------------------//
void Scrollbar::updateThumb(void)
{
if (!d_windowRenderer)
throw InvalidRequestException(
"This function must be implemented by the window renderer object "
"(no window renderer is assigned.)");
static_cast<ScrollbarWindowRenderer*>(d_windowRenderer)->updateThumb();
}
//----------------------------------------------------------------------------//
float Scrollbar::getValueFromThumb(void) const
{
if (!d_windowRenderer)
throw InvalidRequestException(
"This function must be implemented by the window renderer object "
"(no window renderer is assigned.)");
return static_cast<ScrollbarWindowRenderer*>(
d_windowRenderer)->getValueFromThumb();
}
//----------------------------------------------------------------------------//
float Scrollbar::getAdjustDirectionFromPoint(const glm::vec2& pt) const
{
if (!d_windowRenderer)
throw InvalidRequestException(
"This function must be implemented by the window renderer object "
"(no window renderer is assigned.)");
return static_cast<ScrollbarWindowRenderer*>(
d_windowRenderer)->getAdjustDirectionFromPoint(pt);
}
//----------------------------------------------------------------------------//
bool Scrollbar::setScrollPosition_impl(const float position)
{
const float old_pos = d_position;
const float max_pos = getMaxScrollPosition();
// limit position to valid range: 0 <= position <= max_pos
d_position = (position >= 0) ?
((position <= max_pos) ?
position :
max_pos) :
0.0f;
return d_position != old_pos;
}
//----------------------------------------------------------------------------//
void Scrollbar::setConfig(const float* const document_size,
const float* const page_size,
const float* const step_size,
const float* const overlap_size,
const float* const position)
{
const bool reset_max_position = d_endLockPosition && isAtEnd();
bool config_changed = false;
bool position_changed = false;
if (document_size && (d_documentSize != *document_size))
{
d_documentSize = *document_size;
config_changed = true;
}
if (page_size && (d_pageSize != *page_size))
{
d_pageSize = *page_size;
config_changed = true;
}
if (step_size && (d_stepSize != *step_size))
{
d_stepSize = *step_size;
config_changed = true;
}
if (overlap_size && (d_overlapSize != *overlap_size))
{
d_overlapSize = *overlap_size;
config_changed = true;
}
if (position)
position_changed = setScrollPosition_impl(*position);
else if (reset_max_position)
position_changed = setScrollPosition_impl(getMaxScrollPosition());
// _always_ update the thumb to keep things in sync. (though this
// can cause a double-trigger of EventScrollPositionChanged, which
// also happens with setScrollPosition anyway).
updateThumb();
//
// Fire appropriate events based on actions we took.
//
if (config_changed)
{
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
if (position_changed)
{
WindowEventArgs args(this);
onScrollPositionChanged(args);
}
}
//----------------------------------------------------------------------------//
float Scrollbar::getMaxScrollPosition() const
{
// max position is (docSize - pageSize)
// but must be at least 0 (in case doc size is very small)
return std::max((d_documentSize - d_pageSize), 0.0f);
}
//----------------------------------------------------------------------------//
bool Scrollbar::isAtEnd() const
{
return d_position >= getMaxScrollPosition();
}
//----------------------------------------------------------------------------//
void Scrollbar::setEndLockEnabled(const bool enabled)
{
d_endLockPosition = enabled;
}
//----------------------------------------------------------------------------//
bool Scrollbar::isEndLockEnabled() const
{
return d_endLockPosition;
}
//----------------------------------------------------------------------------//
float Scrollbar::getUnitIntervalScrollPosition() const
{
const float range = d_documentSize - d_pageSize;
return (range > 0) ? d_position / range : 0.0f;
}
//----------------------------------------------------------------------------//
void Scrollbar::setUnitIntervalScrollPosition(float position)
{
const float range = d_documentSize - d_pageSize;
setScrollPosition(range > 0 ? position * range : 0.0f);
}
//----------------------------------------------------------------------------//
void Scrollbar::scrollForwardsByStep()
{
setScrollPosition(d_position + d_stepSize);
}
//----------------------------------------------------------------------------//
void Scrollbar::scrollBackwardsByStep()
{
setScrollPosition(d_position - d_stepSize);
}
//----------------------------------------------------------------------------//
void Scrollbar::scrollForwardsByPage()
{
setScrollPosition(d_position + (d_pageSize - d_overlapSize));
}
//----------------------------------------------------------------------------//
void Scrollbar::scrollBackwardsByPage()
{
setScrollPosition(d_position - (d_pageSize - d_overlapSize));
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
| 33.045208 | 105 | 0.534585 | rpaciorek |
3a82f5ff6fbda9260f7b1179dd660112d5537c3d | 2,130 | cpp | C++ | Server/Source/App.cpp | deaf80/audiogridder | c688ec21f6d4141308885f725cb05a456b493ec9 | [
"MIT"
] | null | null | null | Server/Source/App.cpp | deaf80/audiogridder | c688ec21f6d4141308885f725cb05a456b493ec9 | [
"MIT"
] | null | null | null | Server/Source/App.cpp | deaf80/audiogridder | c688ec21f6d4141308885f725cb05a456b493ec9 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020 Andreas Pohl
* Licensed under MIT (https://github.com/apohl79/audiogridder/blob/master/COPYING)
*
* Author: Andreas Pohl
*/
#include "App.hpp"
#include <signal.h>
#include "Server.hpp"
namespace e47 {
App::App() : m_menuWindow(this) {}
void App::initialise(const String& commandLineParameters) {
m_logger = FileLogger::createDateStampedLogger(getApplicationName(), "Main_", ".log", "");
Logger::setCurrentLogger(m_logger);
signal(SIGPIPE, SIG_IGN);
showSplashWindow();
setSplashInfo("Starting server...");
m_server = std::make_unique<Server>();
m_server->startThread();
}
void App::shutdown() {
m_server->signalThreadShouldExit();
m_server->waitForThreadToExit(1000);
Logger::setCurrentLogger(nullptr);
delete m_logger;
}
void App::restartServer() {
hideEditor();
hidePluginList();
hideServerSettings();
m_server->signalThreadShouldExit();
m_server->waitForThreadToExit(1000);
m_server = std::make_unique<Server>();
m_server->startThread();
}
const KnownPluginList& App::getPluginList() { return m_server->getPluginList(); }
void App::showEditor(std::shared_ptr<AudioProcessor> proc, Thread::ThreadID tid, WindowCaptureCallback func) {
if (proc->hasEditor()) {
std::lock_guard<std::mutex> lock(m_windowMtx);
m_windowOwner = tid;
m_windowProc = proc;
m_windowFunc = func;
m_window = std::make_unique<ProcessorWindow>(m_windowProc, m_windowFunc);
}
}
void App::hideEditor(Thread::ThreadID tid) {
if (tid == 0 || tid == m_windowOwner) {
std::lock_guard<std::mutex> lock(m_windowMtx);
m_window.reset();
m_windowOwner = 0;
m_windowProc.reset();
m_windowFunc = nullptr;
}
}
void App::resetEditor() {
std::lock_guard<std::mutex> lock(m_windowMtx);
m_window.reset();
}
void App::restartEditor() {
std::lock_guard<std::mutex> lock(m_windowMtx);
m_window = std::make_unique<ProcessorWindow>(m_windowProc, m_windowFunc);
}
} // namespace e47
// This kicks the whole thing off..
START_JUCE_APPLICATION(e47::App)
| 25.97561 | 110 | 0.679343 | deaf80 |
3a871a82a1fe6f65822d6c0042bdf31cc37f9e6a | 948 | cpp | C++ | algorithms/0063_UniquePathsII/0063_UniquePathsII.cpp | 23468234/leetcode-question | 35aad4065401018414de63d1a983ceacb51732a6 | [
"MIT"
] | null | null | null | algorithms/0063_UniquePathsII/0063_UniquePathsII.cpp | 23468234/leetcode-question | 35aad4065401018414de63d1a983ceacb51732a6 | [
"MIT"
] | null | null | null | algorithms/0063_UniquePathsII/0063_UniquePathsII.cpp | 23468234/leetcode-question | 35aad4065401018414de63d1a983ceacb51732a6 | [
"MIT"
] | null | null | null | class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if (obstacleGrid.empty() || obstacleGrid[0].empty()){
return 0;
}
int row = obstacleGrid.size();
int column = obstacleGrid[0].size();
vector<vector<int>> board(row, vector<int>(column, 0));
if (obstacleGrid[0][0] == 1){
return 0;
}
board[0][0] = 1;
for (int i = 1; i < column; ++i){
board[0][i] = (obstacleGrid[0][i] == 1) ? 0 : board[0][i - 1] ;
}
for (int i = 1; i < row; ++i){
board[i][0] = (obstacleGrid[i][0] == 1) ? 0 : board[i - 1][0];
}
for (int i = 1; i < row; i ++){
for (int j = 1; j < column; ++j){
board[i][j] = (obstacleGrid[i][j] == 1) ? 0 : board[i - 1][j] + board[i][j - 1];
}
}
return board[row - 1][column - 1];
}
}; | 28.727273 | 96 | 0.439873 | 23468234 |
3a8c0426188f56e75e6505fbff3368e99c5555c7 | 2,433 | hpp | C++ | src/classical/plim/rm3_graph.hpp | msoeken/cirkit-addon-plim | 3af61430ec85754a1c63e50b3284781e80274407 | [
"MIT"
] | null | null | null | src/classical/plim/rm3_graph.hpp | msoeken/cirkit-addon-plim | 3af61430ec85754a1c63e50b3284781e80274407 | [
"MIT"
] | null | null | null | src/classical/plim/rm3_graph.hpp | msoeken/cirkit-addon-plim | 3af61430ec85754a1c63e50b3284781e80274407 | [
"MIT"
] | null | null | null | /* CirKit: A circuit toolkit
* Copyright (C) 2009-2015 University of Bremen
* Copyright (C) 2015-2016 EPFL
*
* 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.
*/
/**
* @file rm3_graph.hpp
*
* @brief A dedicated data-structure for RM3 graphs
*
* @author Mathias Soeken
* @since 2.3
*/
#ifndef RM3_GRAPH_HPP
#define RM3_GRAPH_HPP
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <core/utils/hash_utils.hpp>
namespace cirkit
{
using rm3_node = unsigned;
class rm3_graph
{
public:
rm3_graph( unsigned num_vars = 0u );
void create_po( const rm3_node& n, const std::string& name = std::string() );
rm3_node create_rm3( const rm3_node& x, const rm3_node& y, const rm3_node& z );
rm3_node create_not( const rm3_node& x );
unsigned num_gates() const;
unsigned num_inputs() const;
unsigned num_outputs() const;
void print_statistics( std::ostream& os ) const;
private:
unsigned num_vars = 0u;
std::vector<unsigned> nodes;
std::vector<std::string> inputs;
std::vector<std::pair<unsigned, std::string>> outputs;
using rm3_graph_hash_key_t = std::tuple<rm3_node, rm3_node, rm3_node>;
std::unordered_map<rm3_graph_hash_key_t, rm3_node, hash<rm3_graph_hash_key_t>> strash;
};
}
#endif
// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:
| 28.290698 | 88 | 0.733251 | msoeken |
3a8c17345fb877dd3920a09cafc7e902fcbe306d | 13,473 | cpp | C++ | modules/calib3d/test/test_chessboardgenerator.cpp | satnamsingh8912/opencv | 9c23f2f1a682faa9f0b2c2223a857c7d93ba65a6 | [
"BSD-3-Clause"
] | 163 | 2019-06-04T02:00:58.000Z | 2022-03-26T14:23:10.000Z | modules/calib3d/test/test_chessboardgenerator.cpp | nurisis/opencv | 4378b4d03d8415a132b6675883957243f95d75ee | [
"BSD-3-Clause"
] | 8 | 2019-11-03T10:16:58.000Z | 2022-03-16T17:00:14.000Z | modules/calib3d/test/test_chessboardgenerator.cpp | nurisis/opencv | 4378b4d03d8415a132b6675883957243f95d75ee | [
"BSD-3-Clause"
] | 29 | 2019-01-08T05:43:58.000Z | 2022-03-24T00:07:03.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#include "test_chessboardgenerator.hpp"
namespace cv {
ChessBoardGenerator::ChessBoardGenerator(const Size& _patternSize) : sensorWidth(32), sensorHeight(24),
squareEdgePointsNum(200), min_cos(std::sqrt(3.f)*0.5f), cov(0.5),
patternSize(_patternSize), rendererResolutionMultiplier(4), tvec(Mat::zeros(1, 3, CV_32F))
{
rvec.create(3, 1, CV_32F);
cvtest::Rodrigues(Mat::eye(3, 3, CV_32F), rvec);
}
void ChessBoardGenerator::generateEdge(const Point3f& p1, const Point3f& p2, vector<Point3f>& out) const
{
Point3f step = (p2 - p1) * (1.f/squareEdgePointsNum);
for(size_t n = 0; n < squareEdgePointsNum; ++n)
out.push_back( p1 + step * (float)n);
}
Size ChessBoardGenerator::cornersSize() const
{
return Size(patternSize.width-1, patternSize.height-1);
}
struct Mult
{
float m;
Mult(int mult) : m((float)mult) {}
Point2f operator()(const Point2f& p)const { return p * m; }
};
void ChessBoardGenerator::generateBasis(Point3f& pb1, Point3f& pb2) const
{
RNG& rng = theRNG();
Vec3f n;
for(;;)
{
n[0] = rng.uniform(-1.f, 1.f);
n[1] = rng.uniform(-1.f, 1.f);
n[2] = rng.uniform(0.0f, 1.f);
float len = (float)norm(n);
if (len < 1e-3)
continue;
n[0]/=len;
n[1]/=len;
n[2]/=len;
if (n[2] > min_cos)
break;
}
Vec3f n_temp = n; n_temp[0] += 100;
Vec3f b1 = n.cross(n_temp);
Vec3f b2 = n.cross(b1);
float len_b1 = (float)norm(b1);
float len_b2 = (float)norm(b2);
pb1 = Point3f(b1[0]/len_b1, b1[1]/len_b1, b1[2]/len_b1);
pb2 = Point3f(b2[0]/len_b1, b2[1]/len_b2, b2[2]/len_b2);
}
Mat ChessBoardGenerator::generateChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Point3f& zero, const Point3f& pb1, const Point3f& pb2,
float sqWidth, float sqHeight, const vector<Point3f>& whole,
vector<Point2f>& corners) const
{
vector< vector<Point> > squares_black;
for(int i = 0; i < patternSize.width; ++i)
for(int j = 0; j < patternSize.height; ++j)
if ( (i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0) )
{
vector<Point3f> pts_square3d;
vector<Point2f> pts_square2d;
Point3f p1 = zero + (i + 0) * sqWidth * pb1 + (j + 0) * sqHeight * pb2;
Point3f p2 = zero + (i + 1) * sqWidth * pb1 + (j + 0) * sqHeight * pb2;
Point3f p3 = zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2;
Point3f p4 = zero + (i + 0) * sqWidth * pb1 + (j + 1) * sqHeight * pb2;
generateEdge(p1, p2, pts_square3d);
generateEdge(p2, p3, pts_square3d);
generateEdge(p3, p4, pts_square3d);
generateEdge(p4, p1, pts_square3d);
projectPoints(Mat(pts_square3d), rvec, tvec, camMat, distCoeffs, pts_square2d);
squares_black.resize(squares_black.size() + 1);
vector<Point2f> temp;
approxPolyDP(Mat(pts_square2d), temp, 1.0, true);
transform(temp.begin(), temp.end(), back_inserter(squares_black.back()), Mult(rendererResolutionMultiplier));
}
/* calculate corners */
corners3d.clear();
for(int j = 0; j < patternSize.height - 1; ++j)
for(int i = 0; i < patternSize.width - 1; ++i)
corners3d.push_back(zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2);
corners.clear();
projectPoints(Mat(corners3d), rvec, tvec, camMat, distCoeffs, corners);
vector<Point3f> whole3d;
vector<Point2f> whole2d;
generateEdge(whole[0], whole[1], whole3d);
generateEdge(whole[1], whole[2], whole3d);
generateEdge(whole[2], whole[3], whole3d);
generateEdge(whole[3], whole[0], whole3d);
projectPoints(Mat(whole3d), rvec, tvec, camMat, distCoeffs, whole2d);
vector<Point2f> temp_whole2d;
approxPolyDP(Mat(whole2d), temp_whole2d, 1.0, true);
vector< vector<Point > > whole_contour(1);
transform(temp_whole2d.begin(), temp_whole2d.end(),
back_inserter(whole_contour.front()), Mult(rendererResolutionMultiplier));
Mat result;
if (rendererResolutionMultiplier == 1)
{
result = bg.clone();
drawContours(result, whole_contour, -1, Scalar::all(255), FILLED, LINE_AA);
drawContours(result, squares_black, -1, Scalar::all(0), FILLED, LINE_AA);
}
else
{
Mat tmp;
resize(bg, tmp, bg.size() * rendererResolutionMultiplier, 0, 0, INTER_LINEAR_EXACT);
drawContours(tmp, whole_contour, -1, Scalar::all(255), FILLED, LINE_AA);
drawContours(tmp, squares_black, -1, Scalar::all(0), FILLED, LINE_AA);
resize(tmp, result, bg.size(), 0, 0, INTER_AREA);
}
return result;
}
Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector<Point2f>& corners) const
{
cov = std::min(cov, 0.8);
double fovx, fovy, focalLen;
Point2d principalPoint;
double aspect;
calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight,
fovx, fovy, focalLen, principalPoint, aspect);
RNG& rng = theRNG();
float d1 = static_cast<float>(rng.uniform(0.1, 10.0));
float ah = static_cast<float>(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180);
float av = static_cast<float>(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180);
Point3f p;
p.z = cos(ah) * d1;
p.x = sin(ah) * d1;
p.y = p.z * tan(av);
Point3f pb1, pb2;
generateBasis(pb1, pb2);
float cbHalfWidth = static_cast<float>(norm(p) * sin( std::min(fovx, fovy) * 0.5 * CV_PI / 180));
float cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width;
float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width;
float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height;
vector<Point3f> pts3d(4);
vector<Point2f> pts2d(4);
for(;;)
{
pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
/* can remake with better perf */
projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d);
bool inrect1 = pts2d[0].x < bg.cols && pts2d[0].y < bg.rows && pts2d[0].x > 0 && pts2d[0].y > 0;
bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0;
bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0;
bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0;
if (inrect1 && inrect2 && inrect3 && inrect4)
break;
cbHalfWidth*=0.8f;
cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width;
cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width;
cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height;
}
Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2;
float sqWidth = 2 * cbHalfWidth/patternSize.width;
float sqHeight = 2 * cbHalfHeight/patternSize.height;
return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, sqWidth, sqHeight, pts3d, corners);
}
Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Size2f& squareSize, vector<Point2f>& corners) const
{
cov = std::min(cov, 0.8);
double fovx, fovy, focalLen;
Point2d principalPoint;
double aspect;
calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight,
fovx, fovy, focalLen, principalPoint, aspect);
RNG& rng = theRNG();
float d1 = static_cast<float>(rng.uniform(0.1, 10.0));
float ah = static_cast<float>(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180);
float av = static_cast<float>(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180);
Point3f p;
p.z = cos(ah) * d1;
p.x = sin(ah) * d1;
p.y = p.z * tan(av);
Point3f pb1, pb2;
generateBasis(pb1, pb2);
float cbHalfWidth = squareSize.width * patternSize.width * 0.5f;
float cbHalfHeight = squareSize.height * patternSize.height * 0.5f;
float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width;
float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height;
vector<Point3f> pts3d(4);
vector<Point2f> pts2d(4);
for(;;)
{
pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
/* can remake with better perf */
projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d);
bool inrect1 = pts2d[0].x < bg.cols && pts2d[0].y < bg.rows && pts2d[0].x > 0 && pts2d[0].y > 0;
bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0;
bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0;
bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0;
if ( inrect1 && inrect2 && inrect3 && inrect4)
break;
p.z *= 1.1f;
}
Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2;
return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2,
squareSize.width, squareSize.height, pts3d, corners);
}
Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Size2f& squareSize, const Point3f& pos, vector<Point2f>& corners) const
{
cov = std::min(cov, 0.8);
Point3f p = pos;
Point3f pb1, pb2;
generateBasis(pb1, pb2);
float cbHalfWidth = squareSize.width * patternSize.width * 0.5f;
float cbHalfHeight = squareSize.height * patternSize.height * 0.5f;
float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width;
float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height;
vector<Point3f> pts3d(4);
vector<Point2f> pts2d(4);
pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
/* can remake with better perf */
projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d);
Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2;
return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2,
squareSize.width, squareSize.height, pts3d, corners);
}
} // namespace
| 40.581325 | 125 | 0.61768 | satnamsingh8912 |
3a8ccd33b7f16948c3f3fdf813b7a86a98a607dc | 105,333 | cpp | C++ | kit/Kit.cpp | CaptainVal/online | a5de33496ccd27ca6d11a245c69f70fd28457092 | [
"BSD-2-Clause"
] | 1 | 2021-07-25T06:22:35.000Z | 2021-07-25T06:22:35.000Z | kit/Kit.cpp | CaptainVal/online | a5de33496ccd27ca6d11a245c69f70fd28457092 | [
"BSD-2-Clause"
] | null | null | null | kit/Kit.cpp | CaptainVal/online | a5de33496ccd27ca6d11a245c69f70fd28457092 | [
"BSD-2-Clause"
] | null | null | null | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
* 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/.
*/
/*
* The main entry point for the LibreOfficeKit process serving
* a document editing session.
*/
#include <config.h>
#include <dlfcn.h>
#ifdef __linux__
#include <ftw.h>
#include <sys/vfs.h>
#include <linux/magic.h>
#include <sys/capability.h>
#include <sys/sysmacros.h>
#endif
#ifdef __FreeBSD__
#include <sys/capsicum.h>
#include <ftw.h>
#define FTW_CONTINUE 0
#define FTW_STOP (-1)
#define FTW_SKIP_SUBTREE 0
#define FTW_ACTIONRETVAL 0
#endif
#include <unistd.h>
#include <utime.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sysexits.h>
#include <atomic>
#include <cassert>
#include <climits>
#include <condition_variable>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <thread>
#define LOK_USE_UNSTABLE_API
#include <LibreOfficeKit/LibreOfficeKitInit.h>
#include <Poco/File.h>
#include <Poco/Exception.h>
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Parser.h>
#include <Poco/Net/Socket.h>
#include <Poco/URI.h>
#include "ChildSession.hpp"
#include <Common.hpp>
#include <MobileApp.hpp>
#include <FileUtil.hpp>
#include <common/JailUtil.hpp>
#include <common/JsonUtil.hpp>
#include "KitHelper.hpp"
#include "Kit.hpp"
#include <Protocol.hpp>
#include <Log.hpp>
#include <Png.hpp>
#include <Rectangle.hpp>
#include <TileDesc.hpp>
#include <Unit.hpp>
#include <UserMessages.hpp>
#include <Util.hpp>
#include "Watermark.hpp"
#include "RenderTiles.hpp"
#include "SetupKitEnvironment.hpp"
#include <common/ConfigUtil.hpp>
#include <common/TraceEvent.hpp>
#if !MOBILEAPP
#include <common/SigUtil.hpp>
#include <common/Seccomp.hpp>
#include <utility>
#endif
#ifdef FUZZER
#include <kit/DummyLibreOfficeKit.hpp>
#include <wsd/COOLWSD.hpp>
#endif
#if MOBILEAPP
#include "COOLWSD.hpp"
#endif
#ifdef IOS
#include "ios.h"
#endif
#define LIB_SOFFICEAPP "lib" "sofficeapp" ".so"
#define LIB_MERGED "lib" "mergedlo" ".so"
using Poco::Exception;
using Poco::File;
using Poco::JSON::Array;
using Poco::JSON::Object;
using Poco::JSON::Parser;
using Poco::URI;
#ifndef BUILDING_TESTS
using Poco::Path;
#endif
using namespace COOLProtocol;
extern "C" { void dump_kit_state(void); /* easy for gdb */ }
#if !MOBILEAPP
// A Kit process hosts only a single document in its lifetime.
class Document;
static Document *singletonDocument = nullptr;
#endif
/// Used for test code to accelerating waiting until idle and to
/// flush sockets with a 'processtoidle' -> 'idle' reply.
static std::chrono::steady_clock::time_point ProcessToIdleDeadline;
#ifndef BUILDING_TESTS
static bool AnonymizeUserData = false;
static uint64_t AnonymizationSalt = 82589933;
#endif
/// When chroot is enabled, this is blank as all
/// the paths inside the jail, relative to it's jail.
/// E.g. /tmp/user/docs/...
/// However, without chroot, the jail path is
/// absolute in the system root.
/// I.e. ChildRoot/JailId/tmp/user/docs/...
/// We need to know where the jail really is
/// because WSD doesn't know if chroot will succeed
/// or fail, but it assumes the document path to
/// be relative to the root of the jail (i.e. chroot
/// expected to succeed). If it fails, or when caps
/// are disabled, file paths would be relative to the
/// system root, not the jail.
static std::string JailRoot;
#if !MOBILEAPP
static void flushTraceEventRecordings();
#endif
// Abnormally we get LOK events from another thread, which must be
// push safely into our main poll loop to process to keep all
// socket buffer & event processing in a single, thread.
bool pushToMainThread(LibreOfficeKitCallback cb, int type, const char *p, void *data);
#if !MOBILEAPP
static LokHookFunction2* initFunction = nullptr;
namespace
{
#ifndef BUILDING_TESTS
enum class LinkOrCopyType
{
All,
LO
};
LinkOrCopyType linkOrCopyType;
std::string sourceForLinkOrCopy;
Path destinationForLinkOrCopy;
bool forceInitialCopy; // some stackable file-systems have very slow first hard link creation
std::string linkableForLinkOrCopy; // Place to stash copies that we can hard-link from
std::chrono::time_point<std::chrono::steady_clock> linkOrCopyStartTime;
bool linkOrCopyVerboseLogging = false;
unsigned linkOrCopyFileCount = 0; // Track to help quantify the link-or-copy performance.
constexpr unsigned SlowLinkOrCopyLimitInSecs = 2; // After this many seconds, start spamming the logs.
bool detectSlowStackingFileSystem(const std::string &directory)
{
#ifdef __linux__
#ifndef OVERLAYFS_SUPER_MAGIC
// From linux/magic.h.
#define OVERLAYFS_SUPER_MAGIC 0x794c7630
#endif
struct statfs fs;
if (::statfs(directory.c_str(), &fs) != 0)
{
LOG_SYS("statfs failed on '" << directory << "'");
return false;
}
switch (fs.f_type) {
// case FUSE_SUPER_MAGIC: ?
case OVERLAYFS_SUPER_MAGIC:
return true;
default:
return false;
}
#else
(void)directory;
return false;
#endif
}
/// Returns the LinkOrCopyType as a human-readable string (for logging).
std::string linkOrCopyTypeString(LinkOrCopyType type)
{
switch (type)
{
case LinkOrCopyType::LO:
return "LibreOffice";
case LinkOrCopyType::All:
return "all";
default:
assert(!"Unknown LinkOrCopyType.");
return "unknown";
}
}
bool shouldCopyDir(const char *path)
{
switch (linkOrCopyType)
{
case LinkOrCopyType::LO:
return
strcmp(path, "program/wizards") != 0 &&
strcmp(path, "sdk") != 0 &&
strcmp(path, "debugsource") != 0 &&
strcmp(path, "share/basic") != 0 &&
strncmp(path, "share/extensions/dict-", // preloaded
sizeof("share/extensions/dict")) != 0 &&
strcmp(path, "share/Scripts/java") != 0 &&
strcmp(path, "share/Scripts/javascript") != 0 &&
strcmp(path, "share/config/wizard") != 0 &&
strcmp(path, "readmes") != 0 &&
strcmp(path, "help") != 0;
default: // LinkOrCopyType::All
return true;
}
}
bool shouldLinkFile(const char *path)
{
switch (linkOrCopyType)
{
case LinkOrCopyType::LO:
{
if (strstr(path, "LICENSE") || strstr(path, "EULA") || strstr(path, "CREDITS")
|| strstr(path, "NOTICE"))
return false;
const char* dot = strrchr(path, '.');
if (!dot)
return true;
if (!strcmp(dot, ".dbg"))
return false;
if (!strcmp(dot, ".so"))
{
// NSS is problematic ...
if (strstr(path, "libnspr4") ||
strstr(path, "libplds4") ||
strstr(path, "libplc4") ||
strstr(path, "libnss3") ||
strstr(path, "libnssckbi") ||
strstr(path, "libnsutil3") ||
strstr(path, "libssl3") ||
strstr(path, "libsoftokn3") ||
strstr(path, "libsqlite3") ||
strstr(path, "libfreeblpriv3"))
return true;
// As is Python ...
if (strstr(path, "python-core"))
return true;
// otherwise drop the rest of the code.
return false;
}
const char *vers;
if ((vers = strstr(path, ".so."))) // .so.[digit]+
{
for(int i = sizeof (".so."); vers[i] != '\0'; ++i)
if (!isdigit(vers[i]) && vers[i] != '.')
return true;
return false;
}
return true;
}
default: // LinkOrCopyType::All
return true;
}
}
void linkOrCopyFile(const char* fpath, const std::string& newPath)
{
++linkOrCopyFileCount;
if (linkOrCopyVerboseLogging)
LOG_INF("Linking file \"" << fpath << "\" to \"" << newPath << '"');
if (!forceInitialCopy)
{
// first try a simple hard-link
if (link(fpath, newPath.c_str()) == 0)
return;
}
// else always copy before linking to linkable/
// incrementally build our 'linkable/' copy nearby
static bool canChown = true; // only if we can get permissions right
if ((forceInitialCopy || errno == EXDEV) && canChown)
{
// then copy somewhere closer and hard link from there
if (!forceInitialCopy)
LOG_TRC("link(\"" << fpath << "\", \"" << newPath << "\") failed: " << strerror(errno)
<< ". Will try to link template.");
std::string linkableCopy = linkableForLinkOrCopy + fpath;
if (::link(linkableCopy.c_str(), newPath.c_str()) == 0)
return;
if (errno == ENOENT)
{
File(Path(linkableCopy).parent()).createDirectories();
if (!FileUtil::copy(fpath, linkableCopy.c_str(), /*log=*/false, /*throw_on_error=*/false))
LOG_TRC("Failed to create linkable copy [" << fpath << "] to [" << linkableCopy.c_str() << "]");
else {
// Match system permissions, so a file we can write is not shared across jails.
struct stat ownerInfo;
if (::stat(fpath, &ownerInfo) != 0 ||
::chown(linkableCopy.c_str(), ownerInfo.st_uid, ownerInfo.st_gid) != 0)
{
LOG_ERR("Failed to stat or chown " << ownerInfo.st_uid << ":" << ownerInfo.st_gid <<
" " << linkableCopy << ": " << strerror(errno) << " missing cap_chown?, disabling linkable");
unlink(linkableCopy.c_str());
canChown = false;
}
else if (::link(linkableCopy.c_str(), newPath.c_str()) == 0)
return;
}
}
LOG_TRC("link(\"" << linkableCopy << "\", \"" << newPath << "\") failed: " << strerror(errno)
<< ". Cannot create linkable copy.");
}
static bool warned = false;
if (!warned)
{
LOG_ERR("link(\"" << fpath << "\", \"" << newPath.c_str() << "\") failed: " << strerror(errno)
<< ". Very slow copying path triggered.");
warned = true;
} else
LOG_TRC("link(\"" << fpath << "\", \"" << newPath.c_str() << "\") failed: " << strerror(errno)
<< ". Will copy.");
if (!FileUtil::copy(fpath, newPath.c_str(), /*log=*/false, /*throw_on_error=*/false))
{
LOG_FTL("Failed to copy or link [" << fpath << "] to [" << newPath << "]. Exiting.");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
}
int linkOrCopyFunction(const char *fpath,
const struct stat* sb,
int typeflag,
struct FTW* /*ftwbuf*/)
{
if (strcmp(fpath, sourceForLinkOrCopy.c_str()) == 0)
{
LOG_TRC("nftw: Skipping redundant path: " << fpath);
return FTW_CONTINUE;
}
if (!linkOrCopyVerboseLogging)
{
const auto durationInSecs = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - linkOrCopyStartTime);
if (durationInSecs.count() > SlowLinkOrCopyLimitInSecs)
{
LOG_WRN("Linking/copying files from "
<< sourceForLinkOrCopy << " to " << destinationForLinkOrCopy.toString()
<< " is taking too much time. Enabling verbose link/copy logging.");
linkOrCopyVerboseLogging = true;
}
}
assert(fpath[strlen(sourceForLinkOrCopy.c_str())] == '/');
const char *relativeOldPath = fpath + strlen(sourceForLinkOrCopy.c_str()) + 1;
const Path newPath(destinationForLinkOrCopy, Path(relativeOldPath));
switch (typeflag)
{
case FTW_F:
case FTW_SLN:
File(newPath.parent()).createDirectories();
if (shouldLinkFile(relativeOldPath))
linkOrCopyFile(fpath, newPath.toString());
break;
case FTW_D:
{
struct stat st;
if (stat(fpath, &st) == -1)
{
LOG_SYS("nftw: stat(\"" << fpath << "\") failed");
return FTW_STOP;
}
if (!shouldCopyDir(relativeOldPath))
{
LOG_TRC("nftw: Skipping redundant path: " << relativeOldPath);
return FTW_SKIP_SUBTREE;
}
File(newPath).createDirectories();
struct utimbuf ut;
ut.actime = st.st_atime;
ut.modtime = st.st_mtime;
if (utime(newPath.toString().c_str(), &ut) == -1)
{
LOG_SYS("nftw: utime(\"" << newPath.toString() << "\") failed");
return FTW_STOP;
}
}
break;
case FTW_SL:
{
const std::size_t size = sb->st_size;
char target[size + 1];
const ssize_t written = readlink(fpath, target, size);
if (written <= 0 || static_cast<std::size_t>(written) > size)
{
LOG_SYS("nftw: readlink(\"" << fpath << "\") failed");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
target[written] = '\0';
File(newPath.parent()).createDirectories();
if (symlink(target, newPath.toString().c_str()) == -1)
{
LOG_SYS("nftw: symlink(\"" << target << "\", \"" << newPath.toString()
<< "\") failed");
return FTW_STOP;
}
}
break;
case FTW_DNR:
LOG_ERR("nftw: Cannot read directory '" << fpath << '\'');
return FTW_STOP;
case FTW_NS:
LOG_ERR("nftw: stat failed for '" << fpath << '\'');
return FTW_STOP;
default:
LOG_FTL("nftw: unexpected typeflag: '" << typeflag);
assert(!"nftw: unexpected typeflag.");
break;
}
return FTW_CONTINUE;
}
void linkOrCopy(std::string source,
const Path& destination,
std::string linkable,
LinkOrCopyType type)
{
std::string resolved = FileUtil::realpath(source);
if (resolved != source)
{
LOG_DBG("linkOrCopy: Using real path [" << resolved << "] instead of original link ["
<< source << "].");
source = std::move(resolved);
}
LOG_INF("linkOrCopy " << linkOrCopyTypeString(type) << " from [" << source << "] to ["
<< destination.toString() << "].");
linkOrCopyType = type;
sourceForLinkOrCopy = source;
if (sourceForLinkOrCopy.back() == '/')
sourceForLinkOrCopy.pop_back();
destinationForLinkOrCopy = destination;
linkableForLinkOrCopy = linkable;
linkOrCopyFileCount = 0;
linkOrCopyStartTime = std::chrono::steady_clock::now();
forceInitialCopy = detectSlowStackingFileSystem(destination.toString());
if (nftw(source.c_str(), linkOrCopyFunction, 10, FTW_ACTIONRETVAL|FTW_PHYS) == -1)
{
LOG_SYS("linkOrCopy: nftw() failed for '" << source << '\'');
}
if (linkOrCopyVerboseLogging)
{
linkOrCopyVerboseLogging = false;
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - linkOrCopyStartTime).count();
const double seconds = (ms + 1) / 1000.; // At least 1ms to avoid div-by-zero.
const auto rate = linkOrCopyFileCount / seconds;
LOG_INF("Linking/Copying of " << linkOrCopyFileCount << " files from " << source
<< " to " << destinationForLinkOrCopy.toString()
<< " finished in " << seconds << " seconds, or " << rate
<< " files / second.");
}
}
#ifndef __FreeBSD__
void dropCapability(cap_value_t capability)
{
cap_t caps;
cap_value_t cap_list[] = { capability };
caps = cap_get_proc();
if (caps == nullptr)
{
LOG_SFL("cap_get_proc() failed");
Log::shutdown();
std::_Exit(1);
}
char *capText = cap_to_text(caps, nullptr);
LOG_TRC("Capabilities first: " << capText);
cap_free(capText);
if (cap_set_flag(caps, CAP_EFFECTIVE, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1 ||
cap_set_flag(caps, CAP_PERMITTED, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1)
{
LOG_SFL("cap_set_flag() failed");
Log::shutdown();
std::_Exit(1);
}
if (cap_set_proc(caps) == -1)
{
LOG_SFL("cap_set_proc() failed");
Log::shutdown();
std::_Exit(1);
}
capText = cap_to_text(caps, nullptr);
LOG_TRC("Capabilities now: " << capText);
cap_free(capText);
cap_free(caps);
}
#endif // __FreeBSD__
#endif
}
#endif
/// A document container.
/// Owns LOKitDocument instance and connections.
/// Manages the lifetime of a document.
/// Technically, we can host multiple documents
/// per process. But for security reasons don't.
/// However, we could have a coolkit instance
/// per user or group of users (a trusted circle).
class Document final : public DocumentManagerInterface
{
public:
/// We have two types of password protected documents
/// 1) Documents which require password to view
/// 2) Document which require password to modify
enum class PasswordType { ToView, ToModify };
public:
Document(const std::shared_ptr<lok::Office>& loKit,
const std::string& jailId,
const std::string& docKey,
const std::string& docId,
const std::string& url,
std::shared_ptr<TileQueue> tileQueue,
const std::shared_ptr<WebSocketHandler>& websocketHandler,
unsigned mobileAppDocId)
: _loKit(loKit),
_jailId(jailId),
_docKey(docKey),
_docId(docId),
_url(url),
_obfuscatedFileId(Util::getFilenameFromURL(docKey)),
_tileQueue(std::move(tileQueue)),
_websocketHandler(websocketHandler),
_haveDocPassword(false),
_isDocPasswordProtected(false),
_docPasswordType(PasswordType::ToView),
_stop(false),
_editorId(-1),
_editorChangeWarning(false),
_mobileAppDocId(mobileAppDocId),
_inputProcessingEnabled(true)
{
LOG_INF("Document ctor for [" << _docKey <<
"] url [" << anonymizeUrl(_url) << "] on child [" << _jailId <<
"] and id [" << _docId << "].");
assert(_loKit);
#if !MOBILEAPP
assert(singletonDocument == nullptr);
singletonDocument = this;
#endif
}
virtual ~Document()
{
LOG_INF("~Document dtor for [" << _docKey <<
"] url [" << anonymizeUrl(_url) << "] on child [" << _jailId <<
"] and id [" << _docId << "]. There are " <<
_sessions.size() << " views.");
// Wait for the callback worker to finish.
_stop = true;
_tileQueue->put("eof");
for (const auto& session : _sessions)
{
session.second->resetDocManager();
}
#ifdef IOS
DocumentData::deallocate(_mobileAppDocId);
#endif
}
const std::string& getUrl() const { return _url; }
/// Post the message - in the unipoll world we're in the right thread anyway
bool postMessage(const char* data, int size, const WSOpCode code) const
{
LOG_TRC("postMessage called with: " << getAbbreviatedMessage(data, size));
if (!_websocketHandler)
{
LOG_ERR("Child Doc: Bad socket while sending [" << getAbbreviatedMessage(data, size) << "].");
return false;
}
_websocketHandler->sendMessage(data, size, code);
return true;
}
bool createSession(const std::string& sessionId, int canonicalViewId)
{
try
{
if (_sessions.find(sessionId) != _sessions.end())
{
LOG_ERR("Session [" << sessionId << "] on url [" << anonymizeUrl(_url) << "] already exists.");
return true;
}
LOG_INF("Creating " << (_sessions.empty() ? "first" : "new") <<
" session for url: " << anonymizeUrl(_url) << " for sessionId: " <<
sessionId << " on jailId: " << _jailId);
auto session = std::make_shared<ChildSession>(
_websocketHandler, sessionId,
_jailId, JailRoot, *this);
_sessions.emplace(sessionId, session);
session->setCanonicalViewId(canonicalViewId);
int viewId = session->getViewId();
_lastUpdatedAt[viewId] = std::chrono::steady_clock::now();
_speedCount[viewId] = 0;
LOG_DBG("Sessions: " << _sessions.size());
return true;
}
catch (const std::exception& ex)
{
LOG_ERR("Exception while creating session [" << sessionId <<
"] on url [" << anonymizeUrl(_url) << "] - '" << ex.what() << "'.");
return false;
}
}
/// Purges dead connections and returns
/// the remaining number of clients.
/// Returns -1 on failure.
std::size_t purgeSessions()
{
std::vector<std::shared_ptr<ChildSession>> deadSessions;
std::size_t num_sessions = 0;
{
// If there are no live sessions, we don't need to do anything at all and can just
// bluntly exit, no need to clean up our own data structures. Also, there is a bug that
// causes the deadSessions.clear() call below to crash in some situations when the last
// session is being removed.
for (auto it = _sessions.cbegin(); it != _sessions.cend(); )
{
if (it->second->isCloseFrame())
{
deadSessions.push_back(it->second);
it = _sessions.erase(it);
}
else
{
++it;
}
}
num_sessions = _sessions.size();
#if !MOBILEAPP
if (num_sessions == 0)
{
LOG_FTL("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly.");
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_OK);
}
#endif
}
deadSessions.clear();
return num_sessions;
}
/// Set Document password for given URL
void setDocumentPassword(int passwordType)
{
// Log whether the document is password protected and a password is provided
LOG_INF("setDocumentPassword: passwordProtected=" << _isDocPasswordProtected <<
" passwordProvided=" << _haveDocPassword);
if (_isDocPasswordProtected && _haveDocPassword)
{
// it means this is the second attempt with the wrong password; abort the load operation
_loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr);
return;
}
// One thing for sure, this is a password protected document
_isDocPasswordProtected = true;
if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD)
_docPasswordType = PasswordType::ToView;
else if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY)
_docPasswordType = PasswordType::ToModify;
LOG_INF("Calling _loKit->setDocumentPassword");
if (_haveDocPassword)
_loKit->setDocumentPassword(_jailedUrl.c_str(), _docPassword.c_str());
else
_loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr);
LOG_INF("setDocumentPassword returned.");
}
void renderTile(const StringVector& tokens)
{
TileCombined tileCombined(TileDesc::parse(tokens));
renderTiles(tileCombined, false);
}
void renderCombinedTiles(const StringVector& tokens)
{
TileCombined tileCombined = TileCombined::parse(tokens);
renderTiles(tileCombined, true);
}
void renderTiles(TileCombined &tileCombined, bool combined)
{
// Find a session matching our view / render settings.
const auto session = _sessions.findByCanonicalId(tileCombined.getNormalizedViewId());
if (!session)
{
LOG_ERR("Session is not found. Maybe exited after rendering request.");
return;
}
if (!_loKitDocument)
{
LOG_ERR("Tile rendering requested before loading document.");
return;
}
if (_loKitDocument->getViewsCount() <= 0)
{
LOG_ERR("Tile rendering requested without views.");
return;
}
#ifdef FIXME_RENDER_SETTINGS
// if necessary select a suitable rendering view eg. with 'show non-printing chars'
if (tileCombined.getNormalizedViewId())
_loKitDocument->setView(session->getViewId());
#endif
const auto blenderFunc = [&](unsigned char* data, int offsetX, int offsetY,
std::size_t pixmapWidth, std::size_t pixmapHeight,
int pixelWidth, int pixelHeight, LibreOfficeKitTileMode mode) {
if (session->watermark())
session->watermark()->blending(data, offsetX, offsetY, pixmapWidth, pixmapHeight,
pixelWidth, pixelHeight, mode);
};
const auto postMessageFunc = [&](const char* buffer, std::size_t length) {
postMessage(buffer, length, WSOpCode::Binary);
};
if (!RenderTiles::doRender(_loKitDocument, tileCombined, _pngCache, _pngPool, combined,
blenderFunc, postMessageFunc, _mobileAppDocId))
{
LOG_DBG("All tiles skipped, not producing empty tilecombine: message");
return;
}
}
bool sendTextFrame(const std::string& message)
{
return sendFrame(message.data(), message.size());
}
bool sendFrame(const char* buffer, int length, WSOpCode opCode = WSOpCode::Text) override
{
try
{
return postMessage(buffer, length, opCode);
}
catch (const Exception& exc)
{
LOG_ERR("Document::sendFrame: Exception: " << exc.displayText() <<
(exc.nested() ? "( " + exc.nested()->displayText() + ')' : ""));
}
return false;
}
void alertAllUsers(const std::string& cmd, const std::string& kind) override
{
alertAllUsers("errortoall: cmd=" + cmd + " kind=" + kind);
}
unsigned getMobileAppDocId() const override
{
return _mobileAppDocId;
}
static void GlobalCallback(const int type, const char* p, void* data)
{
if (SigUtil::getTerminationFlag())
return;
// unusual LOK event from another thread,
// pData - is Document with process' lifetime.
if (pushToMainThread(GlobalCallback, type, p, data))
return;
const std::string payload = p ? p : "(nil)";
Document* self = static_cast<Document*>(data);
if (type == LOK_CALLBACK_PROFILE_FRAME)
{
// We must send the trace data to the WSD process for output
LOG_TRC("Document::GlobalCallback " << lokCallbackTypeToString(type) << ": " << payload.length() << " bytes.");
self->sendTextFrame("traceevent: \n" + payload);
return;
}
LOG_TRC("Document::GlobalCallback " << lokCallbackTypeToString(type) <<
" [" << payload << "].");
if (type == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY ||
type == LOK_CALLBACK_DOCUMENT_PASSWORD)
{
// Mark the document password type.
self->setDocumentPassword(type);
return;
}
else if (type == LOK_CALLBACK_STATUS_INDICATOR_START ||
type == LOK_CALLBACK_STATUS_INDICATOR_SET_VALUE ||
type == LOK_CALLBACK_STATUS_INDICATOR_FINISH)
{
for (auto& it : self->_sessions)
{
std::shared_ptr<ChildSession> session = it.second;
if (session && !session->isCloseFrame())
{
session->loKitCallback(type, payload);
}
}
return;
}
else if (type == LOK_CALLBACK_JSDIALOG || type == LOK_CALLBACK_HYPERLINK_CLICKED)
{
if (self->_sessions.size() == 1)
{
auto it = self->_sessions.begin();
std::shared_ptr<ChildSession> session = it->second;
if (session && !session->isCloseFrame())
{
session->loKitCallback(type, payload);
// TODO. It should filter some messages
// before loading the document
session->getProtocol()->enableProcessInput(true);
}
}
}
// Broadcast leftover status indicator callbacks to all clients
self->broadcastCallbackToClients(type, payload);
}
static void ViewCallback(const int type, const char* p, void* data)
{
if (SigUtil::getTerminationFlag())
return;
// unusual LOK event from another thread.
// pData - is CallbackDescriptors which share process' lifetime.
if (pushToMainThread(ViewCallback, type, p, data))
return;
CallbackDescriptor* descriptor = static_cast<CallbackDescriptor*>(data);
assert(descriptor && "Null callback data.");
assert(descriptor->getDoc() && "Null Document instance.");
std::shared_ptr<TileQueue> tileQueue = descriptor->getDoc()->getTileQueue();
assert(tileQueue && "Null TileQueue.");
const std::string payload = p ? p : "(nil)";
LOG_TRC("Document::ViewCallback [" << descriptor->getViewId() <<
"] [" << lokCallbackTypeToString(type) <<
"] [" << payload << "].");
// when we examine the content of the JSON
std::string targetViewId;
if (type == LOK_CALLBACK_CELL_CURSOR)
{
StringVector tokens(Util::tokenize(payload, ','));
// Payload may be 'EMPTY'.
if (tokens.size() == 4)
{
int cursorX = std::stoi(tokens[0]);
int cursorY = std::stoi(tokens[1]);
int cursorWidth = std::stoi(tokens[2]);
int cursorHeight = std::stoi(tokens[3]);
tileQueue->updateCursorPosition(0, 0, cursorX, cursorY, cursorWidth, cursorHeight);
}
}
else if (type == LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR)
{
Poco::JSON::Parser parser;
const Poco::Dynamic::Var result = parser.parse(payload);
const auto& command = result.extract<Poco::JSON::Object::Ptr>();
std::string rectangle = command->get("rectangle").toString();
StringVector tokens(Util::tokenize(rectangle, ','));
// Payload may be 'EMPTY'.
if (tokens.size() == 4)
{
int cursorX = std::stoi(tokens[0]);
int cursorY = std::stoi(tokens[1]);
int cursorWidth = std::stoi(tokens[2]);
int cursorHeight = std::stoi(tokens[3]);
tileQueue->updateCursorPosition(0, 0, cursorX, cursorY, cursorWidth, cursorHeight);
}
}
else if (type == LOK_CALLBACK_INVALIDATE_VIEW_CURSOR ||
type == LOK_CALLBACK_CELL_VIEW_CURSOR)
{
Poco::JSON::Parser parser;
const Poco::Dynamic::Var result = parser.parse(payload);
const auto& command = result.extract<Poco::JSON::Object::Ptr>();
targetViewId = command->get("viewId").toString();
std::string part = command->get("part").toString();
std::string text = command->get("rectangle").toString();
StringVector tokens(Util::tokenize(text, ','));
// Payload may be 'EMPTY'.
if (tokens.size() == 4)
{
int cursorX = std::stoi(tokens[0]);
int cursorY = std::stoi(tokens[1]);
int cursorWidth = std::stoi(tokens[2]);
int cursorHeight = std::stoi(tokens[3]);
tileQueue->updateCursorPosition(std::stoi(targetViewId), std::stoi(part), cursorX, cursorY, cursorWidth, cursorHeight);
}
}
// merge various callback types together if possible
if (type == LOK_CALLBACK_INVALIDATE_TILES ||
type == LOK_CALLBACK_DOCUMENT_SIZE_CHANGED)
{
// no point in handling invalidations or page resizes per-view,
// all views have to be in sync
tileQueue->put("callback all " + std::to_string(type) + ' ' + payload);
}
else
tileQueue->put("callback " + std::to_string(descriptor->getViewId()) + ' ' + std::to_string(type) + ' ' + payload);
LOG_TRC("Document::ViewCallback end.");
}
private:
/// Helper method to broadcast callback and its payload to all clients
void broadcastCallbackToClients(const int type, const std::string& payload)
{
_tileQueue->put("callback all " + std::to_string(type) + ' ' + payload);
}
/// Load a document (or view) and register callbacks.
bool onLoad(const std::string& sessionId,
const std::string& uriAnonym,
const std::string& renderOpts) override
{
LOG_INF("Loading url [" << uriAnonym << "] for session [" << sessionId <<
"] which has " << (_sessions.size() - 1) << " sessions.");
// This shouldn't happen, but for sanity.
const auto it = _sessions.find(sessionId);
if (it == _sessions.end() || !it->second)
{
LOG_ERR("Cannot find session [" << sessionId << "] to load view for.");
return false;
}
std::shared_ptr<ChildSession> session = it->second;
try
{
if (!load(session, renderOpts))
return false;
}
catch (const std::exception &exc)
{
LOG_ERR("Exception while loading url [" << uriAnonym <<
"] for session [" << sessionId << "]: " << exc.what());
return false;
}
return true;
}
void onUnload(const ChildSession& session) override
{
const auto& sessionId = session.getId();
LOG_INF("Unloading session [" << sessionId << "] on url [" << anonymizeUrl(_url) << "].");
const int viewId = session.getViewId();
_tileQueue->removeCursorPosition(viewId);
if (_loKitDocument == nullptr)
{
LOG_ERR("Unloading session [" << sessionId << "] without loKitDocument.");
return;
}
_loKitDocument->setView(viewId);
_loKitDocument->registerCallback(nullptr, nullptr);
_loKit->registerCallback(nullptr, nullptr);
int viewCount = _loKitDocument->getViewsCount();
if (viewCount == 1)
{
#if !MOBILEAPP
if (_sessions.empty())
{
LOG_INF("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly.");
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_OK);
}
#endif
LOG_INF("Document [" << anonymizeUrl(_url) << "] has no more views, but has " <<
_sessions.size() << " sessions still. Destroying the document.");
#ifdef __ANDROID__
_loKitDocumentForAndroidOnly.reset();
#endif
_loKitDocument.reset();
LOG_INF("Document [" << anonymizeUrl(_url) << "] session [" << sessionId << "] unloaded Document.");
return;
}
else
{
_loKitDocument->destroyView(viewId);
}
// Since callback messages are processed on idle-timer,
// we could receive callbacks after destroying a view.
// Retain the CallbackDescriptor object, which is shared with Core.
// Do not: _viewIdToCallbackDescr.erase(viewId);
viewCount = _loKitDocument->getViewsCount();
LOG_INF("Document [" << anonymizeUrl(_url) << "] session [" <<
sessionId << "] unloaded view [" << viewId << "]. Have " <<
viewCount << " view" << (viewCount != 1 ? "s." : "."));
if (viewCount > 0)
{
// Broadcast updated view info
notifyViewInfo();
}
}
std::map<int, UserInfo> getViewInfo() override
{
return _sessionUserInfo;
}
std::shared_ptr<TileQueue>& getTileQueue() override
{
return _tileQueue;
}
int getEditorId() const override
{
return _editorId;
}
/// Notify all views with the given message
bool notifyAll(const std::string& msg) override
{
// Broadcast updated viewinfo to all clients.
return sendTextFrame("client-all " + msg);
}
/// Notify all views of viewId and their associated usernames
void notifyViewInfo() override
{
// Get the list of view ids from the core
const int viewCount = getLOKitDocument()->getViewsCount();
std::vector<int> viewIds(viewCount);
getLOKitDocument()->getViewIds(viewIds.data(), viewCount);
const std::map<int, UserInfo> viewInfoMap = getViewInfo();
const std::map<std::string, int> viewColorsMap = getViewColors();
// Double check if list of viewids from core and our list matches,
// and create an array of JSON objects containing id and username
std::ostringstream oss;
oss << "viewinfo: [";
for (const auto& viewId : viewIds)
{
oss << "{\"id\":" << viewId << ',';
int color = 0;
const auto itView = viewInfoMap.find(viewId);
if (itView == viewInfoMap.end())
{
LOG_ERR("No username found for viewId [" << viewId << "].");
oss << "\"username\":\"Unknown\",";
}
else
{
oss << "\"userid\":\"" << JsonUtil::escapeJSONValue(itView->second.getUserId()) << "\",";
const std::string username = itView->second.getUserName();
oss << "\"username\":\"" << JsonUtil::escapeJSONValue(username) << "\",";
if (!itView->second.getUserExtraInfo().empty())
oss << "\"userextrainfo\":" << itView->second.getUserExtraInfo() << ',';
const bool readonly = itView->second.isReadOnly();
oss << "\"readonly\":\"" << readonly << "\",";
const auto it = viewColorsMap.find(username);
if (it != viewColorsMap.end())
{
color = it->second;
}
}
oss << "\"color\":" << color << "},";
}
if (viewCount > 0)
oss.seekp(-1, std::ios_base::cur); // Remove last comma.
oss << ']';
// Broadcast updated viewinfo to all clients.
notifyAll(oss.str());
}
void updateEditorSpeeds(int id, int speed) override
{
int maxSpeed = -1, fastestUser = -1;
auto now = std::chrono::steady_clock::now();
_lastUpdatedAt[id] = now;
_speedCount[id] = speed;
for (const auto& it : _sessions)
{
const std::shared_ptr<ChildSession> session = it.second;
int sessionId = session->getViewId();
auto duration = (_lastUpdatedAt[id] - now);
std::chrono::milliseconds::rep durationInMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
if (_speedCount[sessionId] != 0 && durationInMs > 5000)
{
_speedCount[sessionId] = session->getSpeed();
_lastUpdatedAt[sessionId] = now;
}
if (_speedCount[sessionId] > maxSpeed)
{
maxSpeed = _speedCount[sessionId];
fastestUser = sessionId;
}
}
// 0 for preventing selection of the first always
// 1 for preventing new users from directly becoming editors
if (_editorId != fastestUser && (maxSpeed != 0 && maxSpeed != 1)) {
if (!_editorChangeWarning && _editorId != -1)
{
_editorChangeWarning = true;
}
else
{
_editorChangeWarning = false;
_editorId = fastestUser;
for (const auto& it : _sessions)
it.second->sendTextFrame("editor: " + std::to_string(_editorId));
}
}
else
_editorChangeWarning = false;
}
private:
// Get the color value for all author names from the core
std::map<std::string, int> getViewColors()
{
char* values = _loKitDocument->getCommandValues(".uno:TrackedChangeAuthors");
const std::string colorValues = std::string(values == nullptr ? "" : values);
std::free(values);
std::map<std::string, int> viewColors;
try
{
if (!colorValues.empty())
{
Poco::JSON::Parser parser;
Poco::JSON::Object::Ptr root = parser.parse(colorValues).extract<Poco::JSON::Object::Ptr>();
if (root->get("authors").type() == typeid(Poco::JSON::Array::Ptr))
{
Poco::JSON::Array::Ptr authorsArray = root->get("authors").extract<Poco::JSON::Array::Ptr>();
for (auto& authorVar: *authorsArray)
{
Poco::JSON::Object::Ptr authorObj = authorVar.extract<Poco::JSON::Object::Ptr>();
std::string authorName = authorObj->get("name").convert<std::string>();
int colorValue = authorObj->get("color").convert<int>();
viewColors[authorName] = colorValue;
}
}
}
}
catch(const Exception& exc)
{
LOG_ERR("Poco Exception: " << exc.displayText() <<
(exc.nested() ? " (" + exc.nested()->displayText() + ')' : ""));
}
return viewColors;
}
std::shared_ptr<lok::Document> load(const std::shared_ptr<ChildSession>& session,
const std::string& renderOpts)
{
const std::string sessionId = session->getId();
const std::string& uri = session->getJailedFilePath();
const std::string& uriAnonym = session->getJailedFilePathAnonym();
const std::string& userName = session->getUserName();
const std::string& userNameAnonym = session->getUserNameAnonym();
const std::string& docPassword = session->getDocPassword();
const bool haveDocPassword = session->getHaveDocPassword();
const std::string& lang = session->getLang();
const std::string& deviceFormFactor = session->getDeviceFormFactor();
const std::string& batchMode = session->getBatchMode();
const std::string& enableMacrosExecution = session->getEnableMacrosExecution();
const std::string& macroSecurityLevel = session->getMacroSecurityLevel();
std::string spellOnline;
std::string options;
if (!lang.empty())
options = "Language=" + lang;
if (!deviceFormFactor.empty())
options += ",DeviceFormFactor=" + deviceFormFactor;
if (!batchMode.empty())
options += ",Batch=" + batchMode;
if (!enableMacrosExecution.empty())
options += ",EnableMacrosExecution=" + enableMacrosExecution;
if (!macroSecurityLevel.empty())
options += ",MacroSecurityLevel=" + macroSecurityLevel;
if (!_loKitDocument)
{
// This is the first time we are loading the document
LOG_INF("Loading new document from URI: [" << uriAnonym << "] for session [" << sessionId << "].");
_loKit->registerCallback(GlobalCallback, this);
const int flags = LOK_FEATURE_DOCUMENT_PASSWORD
| LOK_FEATURE_DOCUMENT_PASSWORD_TO_MODIFY
| LOK_FEATURE_PART_IN_INVALIDATION_CALLBACK
| LOK_FEATURE_NO_TILED_ANNOTATIONS
| LOK_FEATURE_RANGE_HEADERS
| LOK_FEATURE_VIEWID_IN_VISCURSOR_INVALIDATION_CALLBACK;
_loKit->setOptionalFeatures(flags);
// Save the provided password with us and the jailed url
_haveDocPassword = haveDocPassword;
_docPassword = docPassword;
_jailedUrl = uri;
_isDocPasswordProtected = false;
const char *pURL = uri.c_str();
LOG_DBG("Calling lokit::documentLoad(" << FileUtil::anonymizeUrl(pURL) << ", \"" << options << "\").");
const auto start = std::chrono::steady_clock::now();
_loKitDocument.reset(_loKit->documentLoad(pURL, options.c_str()));
#ifdef __ANDROID__
_loKitDocumentForAndroidOnly = _loKitDocument;
#endif
const auto duration = std::chrono::steady_clock::now() - start;
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
LOG_DBG("Returned lokit::documentLoad(" << FileUtil::anonymizeUrl(pURL) << ") in "
<< elapsed);
#ifdef IOS
DocumentData::get(_mobileAppDocId).loKitDocument = _loKitDocument.get();
#endif
if (!_loKitDocument || !_loKitDocument->get())
{
LOG_ERR("Failed to load: " << uriAnonym << ", error: " << _loKit->getError());
// Checking if wrong password or no password was reason for failure.
if (_isDocPasswordProtected)
{
LOG_INF("Document [" << uriAnonym << "] is password protected.");
if (!_haveDocPassword)
{
LOG_INF("No password provided for password-protected document [" << uriAnonym << "].");
std::string passwordFrame = "passwordrequired:";
if (_docPasswordType == PasswordType::ToView)
passwordFrame += "to-view";
else if (_docPasswordType == PasswordType::ToModify)
passwordFrame += "to-modify";
session->sendTextFrameAndLogError("error: cmd=load kind=" + passwordFrame);
}
else
{
LOG_INF("Wrong password for password-protected document [" << uriAnonym << "].");
session->sendTextFrameAndLogError("error: cmd=load kind=wrongpassword");
}
return nullptr;
}
session->sendTextFrameAndLogError("error: cmd=load kind=faileddocloading");
return nullptr;
}
// Only save the options on opening the document.
// No support for changing them after opening a document.
_renderOpts = renderOpts;
spellOnline = session->getSpellOnline();
}
else
{
LOG_INF("Document with url [" << uriAnonym << "] already loaded. Need to create new view for session [" << sessionId << "].");
// Check if this document requires password
if (_isDocPasswordProtected)
{
if (!haveDocPassword)
{
std::string passwordFrame = "passwordrequired:";
if (_docPasswordType == PasswordType::ToView)
passwordFrame += "to-view";
else if (_docPasswordType == PasswordType::ToModify)
passwordFrame += "to-modify";
session->sendTextFrameAndLogError("error: cmd=load kind=" + passwordFrame);
return nullptr;
}
else if (docPassword != _docPassword)
{
session->sendTextFrameAndLogError("error: cmd=load kind=wrongpassword");
return nullptr;
}
}
LOG_INF("Creating view to url [" << uriAnonym << "] for session [" << sessionId << "] with " << options << '.');
_loKitDocument->createView(options.c_str());
LOG_TRC("View to url [" << uriAnonym << "] created.");
}
LOG_INF("Initializing for rendering session [" << sessionId << "] on document url [" <<
anonymizeUrl(_url) << "] with: [" << makeRenderParams(_renderOpts, userNameAnonym, spellOnline) << "].");
// initializeForRendering() should be called before
// registerCallback(), as the previous creates a new view in Impress.
const std::string renderParams = makeRenderParams(_renderOpts, userName, spellOnline);
_loKitDocument->initializeForRendering(renderParams.c_str());
const int viewId = _loKitDocument->getView();
session->setViewId(viewId);
_sessionUserInfo[viewId] = UserInfo(session->getViewUserId(), session->getViewUserName(),
session->getViewUserExtraInfo(), session->isReadOnly());
_loKitDocument->setViewLanguage(viewId, lang.c_str());
// viewId's monotonically increase, and CallbackDescriptors are never freed.
_viewIdToCallbackDescr.emplace(viewId,
std::unique_ptr<CallbackDescriptor>(new CallbackDescriptor({ this, viewId })));
_loKitDocument->registerCallback(ViewCallback, _viewIdToCallbackDescr[viewId].get());
const int viewCount = _loKitDocument->getViewsCount();
LOG_INF("Document url [" << anonymizeUrl(_url) << "] for session [" <<
sessionId << "] loaded view [" << viewId << "]. Have " <<
viewCount << " view" << (viewCount != 1 ? "s." : "."));
session->initWatermark();
return _loKitDocument;
}
bool forwardToChild(const std::string& prefix, const std::vector<char>& payload)
{
assert(payload.size() > prefix.size());
// Remove the prefix and trim.
std::size_t index = prefix.size();
for ( ; index < payload.size(); ++index)
{
if (payload[index] != ' ')
{
break;
}
}
const char* data = payload.data() + index;
std::size_t size = payload.size() - index;
std::string name;
std::string sessionId;
if (COOLProtocol::parseNameValuePair(prefix, name, sessionId, '-') && name == "child")
{
const auto it = _sessions.find(sessionId);
if (it != _sessions.end())
{
std::shared_ptr<ChildSession> session = it->second;
static const std::string disconnect("disconnect");
if (size == disconnect.size() &&
strncmp(data, disconnect.data(), disconnect.size()) == 0)
{
if(session->getViewId() == _editorId) {
_editorId = -1;
}
LOG_DBG("Removing ChildSession [" << sessionId << "].");
// Tell them we're going quietly.
session->sendTextFrame("disconnected:");
_sessions.erase(it);
const std::size_t count = _sessions.size();
LOG_DBG("Have " << count << " child" << (count == 1 ? "" : "ren") <<
" after removing ChildSession [" << sessionId << "].");
// No longer needed, and allow session dtor to take it.
session.reset();
return true;
}
// No longer needed, and allow the handler to take it.
if (session)
{
std::vector<char> vect(size);
vect.assign(data, data + size);
// TODO this is probably wrong...
session->handleMessage(vect);
return true;
}
}
const std::string abbrMessage = getAbbreviatedMessage(data, size);
LOG_ERR("Child session [" << sessionId << "] not found to forward message: " << abbrMessage);
}
else
{
LOG_ERR("Failed to parse prefix of forward-to-child message: " << prefix);
}
return false;
}
template <typename T>
static Object::Ptr makePropertyValue(const std::string& type, const T& val)
{
Object::Ptr obj = new Object();
obj->set("type", type);
obj->set("value", val);
return obj;
}
static std::string makeRenderParams(const std::string& renderOpts, const std::string& userName, const std::string& spellOnline)
{
Object::Ptr renderOptsObj;
// Fill the object with renderoptions, if any
if (!renderOpts.empty())
{
Parser parser;
Poco::Dynamic::Var var = parser.parse(renderOpts);
renderOptsObj = var.extract<Object::Ptr>();
}
else
{
renderOptsObj = new Object();
}
// Append name of the user, if any, who opened the document to rendering options
if (!userName.empty())
{
// userName must be decoded already.
renderOptsObj->set(".uno:Author", makePropertyValue("string", userName));
}
// By default we enable spell-checking, unless it's disabled explicitly.
const bool bSet = (spellOnline != "false");
renderOptsObj->set(".uno:SpellOnline", makePropertyValue("boolean", bSet));
if (renderOptsObj)
{
std::ostringstream ossRenderOpts;
renderOptsObj->stringify(ossRenderOpts);
return ossRenderOpts.str();
}
return std::string();
}
public:
void enableProcessInput(bool enable = true){ _inputProcessingEnabled = enable; }
bool processInputEnabled() const { return _inputProcessingEnabled; }
bool hasQueueItems() const
{
return _tileQueue && !_tileQueue->isEmpty();
}
// poll is idle, are we ?
void checkIdle()
{
if (!processInputEnabled() || hasQueueItems())
{
LOG_TRC("Nearly idle - but have more queued items to process");
return; // more to do
}
sendTextFrame("idle");
// get rid of idle check for now.
ProcessToIdleDeadline = std::chrono::steady_clock::now() - std::chrono::milliseconds(10);
}
void drainQueue()
{
try
{
while (processInputEnabled() && hasQueueItems())
{
if (_stop || SigUtil::getTerminationFlag())
{
LOG_INF("_stop or TerminationFlag is set, breaking Document::drainQueue of loop");
break;
}
const TileQueue::Payload input = _tileQueue->pop();
LOG_TRC("Kit handling queue message: " << COOLProtocol::getAbbreviatedMessage(input));
const StringVector tokens = Util::tokenize(input.data(), input.size());
if (tokens.equals(0, "eof"))
{
LOG_INF("Received EOF. Finishing.");
break;
}
if (tokens.equals(0, "tile"))
{
renderTile(tokens);
}
else if (tokens.equals(0, "tilecombine"))
{
renderCombinedTiles(tokens);
}
else if (tokens.startsWith(0, "child-"))
{
forwardToChild(tokens[0], input);
}
else if (tokens.equals(0, "processtoidle"))
{
ProcessToIdleDeadline = std::chrono::steady_clock::now();
uint32_t timeoutUs = 0;
if (tokens.getUInt32(1, "timeout", timeoutUs))
ProcessToIdleDeadline += std::chrono::microseconds(timeoutUs);
}
else if (tokens.equals(0, "callback"))
{
if (tokens.size() >= 3)
{
bool broadcast = false;
int viewId = -1;
int exceptViewId = -1;
const std::string& target = tokens[1];
if (target == "all")
{
broadcast = true;
}
else if (COOLProtocol::matchPrefix("except-", target))
{
exceptViewId = std::stoi(target.substr(7));
broadcast = true;
}
else
{
viewId = std::stoi(target);
}
const int type = std::stoi(tokens[2]);
// payload is the rest of the message
const std::size_t offset = tokens[0].length() + tokens[1].length()
+ tokens[2].length() + 3; // + delims
const std::string payload(input.data() + offset, input.size() - offset);
// Forward the callback to the same view, demultiplexing is done by the LibreOffice core.
bool isFound = false;
for (const auto& it : _sessions)
{
if (!it.second)
continue;
ChildSession& session = *it.second;
if ((broadcast && (session.getViewId() != exceptViewId))
|| (!broadcast && (session.getViewId() == viewId)))
{
if (!session.isCloseFrame())
{
isFound = true;
session.loKitCallback(type, payload);
}
else
{
LOG_ERR("Session-thread of session ["
<< session.getId() << "] for view [" << viewId
<< "] is not running. Dropping ["
<< lokCallbackTypeToString(type) << "] payload ["
<< payload << ']');
}
if (!broadcast)
{
break;
}
}
}
if (!isFound)
{
LOG_ERR("Document::ViewCallback. Session [" << viewId <<
"] is no longer active to process [" << lokCallbackTypeToString(type) <<
"] [" << payload << "] message to Master Session.");
}
}
else
{
LOG_ERR("Invalid callback message: [" << COOLProtocol::getAbbreviatedMessage(input) << "].");
}
}
else
{
LOG_ERR("Unexpected request: [" << COOLProtocol::getAbbreviatedMessage(input) << "].");
}
}
}
catch (const std::exception& exc)
{
LOG_FTL("drainQueue: Exception: " << exc.what());
#if !MOBILEAPP
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_SOFTWARE);
#endif
}
catch (...)
{
LOG_FTL("drainQueue: Unknown exception");
#if !MOBILEAPP
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_SOFTWARE);
#endif
}
}
private:
/// Return access to the lok::Office instance.
std::shared_ptr<lok::Office> getLOKit() override
{
return _loKit;
}
/// Return access to the lok::Document instance.
std::shared_ptr<lok::Document> getLOKitDocument() override
{
if (!_loKitDocument)
{
LOG_ERR("Document [" << _docKey << "] is not loaded.");
throw std::runtime_error("Document " + _docKey + " is not loaded.");
}
return _loKitDocument;
}
std::string getObfuscatedFileId() override
{
return _obfuscatedFileId;
}
void alertAllUsers(const std::string& msg)
{
sendTextFrame(msg);
}
public:
void dumpState(std::ostream& oss)
{
oss << "Kit Document:\n"
<< "\n\tstop: " << _stop
<< "\n\tjailId: " << _jailId
<< "\n\tdocKey: " << _docKey
<< "\n\tdocId: " << _docId
<< "\n\turl: " << _url
<< "\n\tobfuscatedFileId: " << _obfuscatedFileId
<< "\n\tjailedUrl: " << _jailedUrl
<< "\n\trenderOpts: " << _renderOpts
<< "\n\thaveDocPassword: " << _haveDocPassword // not the pwd itself
<< "\n\tisDocPasswordProtected: " << _isDocPasswordProtected
<< "\n\tdocPasswordType: " << (int)_docPasswordType
<< "\n\teditorId: " << _editorId
<< "\n\teditorChangeWarning: " << _editorChangeWarning
<< "\n\tmobileAppDocId: " << _mobileAppDocId
<< "\n\tinputProcessingEnabled: " << _inputProcessingEnabled
<< "\n";
// dumpState:
// TODO: _websocketHandler - but this is an odd one.
_tileQueue->dumpState(oss);
_pngCache.dumpState(oss);
oss << "\tviewIdToCallbackDescr:";
for (const auto &it : _viewIdToCallbackDescr)
{
oss << "\n\t\tviewId: " << it.first
<< " editorId: " << it.second->getDoc()->getEditorId()
<< " mobileAppDocId: " << it.second->getDoc()->getMobileAppDocId();
}
oss << "\n";
_pngPool.dumpState(oss);
_sessions.dumpState(oss);
oss << "\tlastUpdatedAt:";
for (const auto &it : _lastUpdatedAt)
{
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
it.second.time_since_epoch()).count();
oss << "\n\t\tviewId: " << it.first
<< " last update time(ms): " << ms;
}
oss << "\n";
oss << "\tspeedCount:";
for (const auto &it : _speedCount)
{
oss << "\n\t\tviewId: " << it.first
<< " speed: " << it.second;
}
oss << "\n";
/// For showing disconnected user info in the doc repair dialog.
oss << "\tsessionUserInfo:";
for (const auto &it : _sessionUserInfo)
{
oss << "\n\t\tviewId: " << it.first
<< " userId: " << it.second.getUserId()
<< " userName: " << it.second.getUserName()
<< " userExtraInfo: " << it.second.getUserExtraInfo()
<< " readOnly: " << it.second.isReadOnly();
}
oss << "\n";
}
private:
std::shared_ptr<lok::Office> _loKit;
const std::string _jailId;
/// URL-based key. May be repeated during the lifetime of WSD.
const std::string _docKey;
/// Short numerical ID. Unique during the lifetime of WSD.
const std::string _docId;
const std::string _url;
const std::string _obfuscatedFileId;
std::string _jailedUrl;
std::string _renderOpts;
std::shared_ptr<lok::Document> _loKitDocument;
#ifdef __ANDROID__
static std::shared_ptr<lok::Document> _loKitDocumentForAndroidOnly;
#endif
std::shared_ptr<TileQueue> _tileQueue;
std::shared_ptr<WebSocketHandler> _websocketHandler;
PngCache _pngCache;
// Document password provided
std::string _docPassword;
// Whether password was provided or not
bool _haveDocPassword;
// Whether document is password protected
bool _isDocPasswordProtected;
// Whether password is required to view the document, or modify it
PasswordType _docPasswordType;
std::atomic<bool> _stop;
ThreadPool _pngPool;
std::condition_variable _cvLoading;
int _editorId;
bool _editorChangeWarning;
std::map<int, std::unique_ptr<CallbackDescriptor>> _viewIdToCallbackDescr;
SessionMap<ChildSession> _sessions;
std::map<int, std::chrono::steady_clock::time_point> _lastUpdatedAt;
std::map<int, int> _speedCount;
/// For showing disconnected user info in the doc repair dialog.
std::map<int, UserInfo> _sessionUserInfo;
#ifdef __ANDROID__
friend std::shared_ptr<lok::Document> getLOKDocumentForAndroidOnly();
#endif
const unsigned _mobileAppDocId;
bool _inputProcessingEnabled;
};
#if !defined FUZZER && !defined BUILDING_TESTS && !MOBILEAPP
// When building the fuzzer we link COOLWSD.cpp into the same executable so the
// Protected::emitOneRecording() there gets used. When building the unit tests the one in
// TraceEvent.cpp gets used.
static constexpr int traceEventRecordingsCapacity = 100;
static std::vector<std::string> traceEventRecordings;
static void flushTraceEventRecordings()
{
if (traceEventRecordings.size() == 0)
return;
std::size_t totalLength = 0;
for (const auto& i: traceEventRecordings)
totalLength += i.length();
std::string recordings;
recordings.reserve(totalLength);
for (const auto& i: traceEventRecordings)
recordings += i;
singletonDocument->sendTextFrame("traceevent: \n" + recordings);
traceEventRecordings.clear();
}
// The checks for singletonDocument below are to catch if this gets called in the ForKit process.
void TraceEvent::emitOneRecordingIfEnabled(const std::string &recording)
{
// This can be called before the config system is initialized. Guard against that, as calling
// config::getBool() would cause an assertion failure.
static bool configChecked = false;
static bool traceEventsEnabled;
if (!configChecked && config::isInitialized())
{
traceEventsEnabled = config::getBool("trace_event[@enable]", false);
configChecked = true;
}
if (configChecked && !traceEventsEnabled)
return;
if (singletonDocument == nullptr)
return;
singletonDocument->sendTextFrame("forcedtraceevent: \n" + recording);
}
void TraceEvent::emitOneRecording(const std::string &recording)
{
static const bool traceEventsEnabled = config::getBool("trace_event[@enable]", false);
if (!traceEventsEnabled)
return;
if (!TraceEvent::isRecordingOn())
return;
if (singletonDocument == nullptr)
return;
if (traceEventRecordings.size() >= traceEventRecordingsCapacity)
flushTraceEventRecordings();
else if (traceEventRecordings.size() == 0 && traceEventRecordings.capacity() < traceEventRecordingsCapacity)
traceEventRecordings.reserve(traceEventRecordingsCapacity);
traceEventRecordings.emplace_back(recording + "\n");
}
#elif !MOBILEAPP
static void flushTraceEventRecordings()
{
}
#endif
#ifdef __ANDROID__
std::shared_ptr<lok::Document> Document::_loKitDocumentForAndroidOnly = std::shared_ptr<lok::Document>();
std::shared_ptr<lok::Document> getLOKDocumentForAndroidOnly()
{
return Document::_loKitDocumentForAndroidOnly;
}
#endif
class KitSocketPoll final : public SocketPoll
{
std::chrono::steady_clock::time_point _pollEnd;
std::shared_ptr<Document> _document;
static KitSocketPoll *mainPoll;
KitSocketPoll() :
SocketPoll("kit")
{
#ifdef IOS
terminationFlag = false;
#endif
mainPoll = this;
}
public:
~KitSocketPoll()
{
// Just to make it easier to set a breakpoint
mainPoll = nullptr;
}
static void dumpGlobalState(std::ostream &oss)
{
if (mainPoll)
{
if (!mainPoll->_document)
oss << "KitSocketPoll: no doc\n";
else
{
mainPoll->_document->dumpState(oss);
mainPoll->dumpState(oss);
}
}
else
oss << "KitSocketPoll: none\n";
}
static std::shared_ptr<KitSocketPoll> create()
{
KitSocketPoll *p = new KitSocketPoll();
auto result = std::shared_ptr<KitSocketPoll>(p);
#ifdef IOS
std::unique_lock<std::mutex> lock(KSPollsMutex);
KSPolls.push_back(result);
#endif
return result;
}
// process pending message-queue events.
void drainQueue()
{
SigUtil::checkDumpGlobalState(dump_kit_state);
if (_document)
_document->drainQueue();
}
// called from inside poll, inside a wakeup
void wakeupHook()
{
_pollEnd = std::chrono::steady_clock::now();
}
// a LOK compatible poll function merging the functions.
// returns the number of events signalled
int kitPoll(int timeoutMicroS)
{
ProfileZone profileZone("KitSocketPoll::kitPoll");
if (SigUtil::getTerminationFlag())
{
LOG_TRC("Termination of unipoll mainloop flagged");
return -1;
}
// The maximum number of extra events to process beyond the first.
int maxExtraEvents = 15;
int eventsSignalled = 0;
auto startTime = std::chrono::steady_clock::now();
// handle processtoidle waiting optimization
bool checkForIdle = ProcessToIdleDeadline >= startTime;
if (timeoutMicroS < 0)
{
// Flush at most 1 + maxExtraEvents, or return when nothing left.
while (poll(std::chrono::microseconds::zero()) > 0 && maxExtraEvents-- > 0)
++eventsSignalled;
}
else
{
if (checkForIdle)
timeoutMicroS = 0;
// Flush at most maxEvents+1, or return when nothing left.
_pollEnd = startTime + std::chrono::microseconds(timeoutMicroS);
do
{
int realTimeout = timeoutMicroS;
if (_document && _document->hasQueueItems())
realTimeout = 0;
if (poll(std::chrono::microseconds(realTimeout)) <= 0)
break;
const auto now = std::chrono::steady_clock::now();
drainQueue();
timeoutMicroS = std::chrono::duration_cast<std::chrono::microseconds>(_pollEnd - now).count();
++eventsSignalled;
}
while (timeoutMicroS > 0 && !SigUtil::getTerminationFlag() && maxExtraEvents-- > 0);
}
if (_document && checkForIdle && eventsSignalled == 0 &&
timeoutMicroS > 0 && !hasCallbacks() && !hasBuffered())
{
auto remainingTime = ProcessToIdleDeadline - startTime;
LOG_TRC("Poll of " << timeoutMicroS << " vs. remaining time of: " <<
std::chrono::duration_cast<std::chrono::microseconds>(remainingTime).count());
// would we poll until then if we could ?
if (remainingTime < std::chrono::microseconds(timeoutMicroS))
_document->checkIdle();
else
LOG_TRC("Poll of woudl not close gap - continuing");
}
drainQueue();
#if !MOBILEAPP
if (_document && _document->purgeSessions() == 0)
{
LOG_INF("Last session discarded. Setting TerminationFlag");
SigUtil::setTerminationFlag();
return -1;
}
#endif
// Report the number of events we processed.
return eventsSignalled;
}
void setDocument(std::shared_ptr<Document> document)
{
_document = std::move(document);
}
// unusual LOK event from another thread, push into our loop to process.
static bool pushToMainThread(LibreOfficeKitCallback callback, int type, const char *p, void *data)
{
if (mainPoll && mainPoll->getThreadOwner() != std::this_thread::get_id())
{
LOG_TRC("Unusual push callback to main thread");
std::shared_ptr<std::string> pCopy;
if (p)
pCopy = std::make_shared<std::string>(p, strlen(p));
mainPoll->addCallback([=]{
LOG_TRC("Unusual process callback in main thread");
callback(type, pCopy ? pCopy->c_str() : nullptr, data);
});
return true;
}
return false;
}
#ifdef IOS
static std::mutex KSPollsMutex;
// static std::condition_variable KSPollsCV;
static std::vector<std::weak_ptr<KitSocketPoll>> KSPolls;
std::mutex terminationMutex;
std::condition_variable terminationCV;
bool terminationFlag;
#endif
};
KitSocketPoll *KitSocketPoll::mainPoll = nullptr;
bool pushToMainThread(LibreOfficeKitCallback cb, int type, const char *p, void *data)
{
return KitSocketPoll::pushToMainThread(cb, type, p, data);
}
#ifdef IOS
std::mutex KitSocketPoll::KSPollsMutex;
// std::condition_variable KitSocketPoll::KSPollsCV;
std::vector<std::weak_ptr<KitSocketPoll>> KitSocketPoll::KSPolls;
#endif
class KitWebSocketHandler final : public WebSocketHandler
{
std::shared_ptr<TileQueue> _queue;
std::string _socketName;
std::shared_ptr<lok::Office> _loKit;
std::string _jailId;
std::shared_ptr<Document> _document;
std::shared_ptr<KitSocketPoll> _ksPoll;
const unsigned _mobileAppDocId;
public:
KitWebSocketHandler(const std::string& socketName, const std::shared_ptr<lok::Office>& loKit, const std::string& jailId, std::shared_ptr<KitSocketPoll> ksPoll, unsigned mobileAppDocId) :
WebSocketHandler(/* isClient = */ true, /* isMasking */ false),
_queue(std::make_shared<TileQueue>()),
_socketName(socketName),
_loKit(loKit),
_jailId(jailId),
_ksPoll(ksPoll),
_mobileAppDocId(mobileAppDocId)
{
}
~KitWebSocketHandler()
{
// Just to make it easier to set a breakpoint
}
protected:
void handleMessage(const std::vector<char>& data) override
{
// To get A LOT of Trace Events, to exercide their handling, uncomment this:
// ProfileZone profileZone("KitWebSocketHandler::handleMessage");
std::string message(data.data(), data.size());
#if !MOBILEAPP
if (UnitKit::get().filterKitMessage(this, message))
return;
#endif
StringVector tokens = Util::tokenize(message);
Log::StreamLogger logger = Log::debug();
if (logger.enabled())
{
logger << _socketName << ": recv [";
for (const auto& token : tokens)
{
// Don't log user-data, there are anonymized versions that get logged instead.
if (tokens.startsWith(token, "jail") ||
tokens.startsWith(token, "author") ||
tokens.startsWith(token, "name") ||
tokens.startsWith(token, "url"))
continue;
logger << tokens.getParam(token) << ' ';
}
LOG_END(logger, true);
}
// Note: Syntax or parsing errors here are unexpected and fatal.
if (SigUtil::getTerminationFlag())
{
LOG_DBG("Too late, TerminationFlag is set, we're going down");
}
else if (tokens.equals(0, "session"))
{
const std::string& sessionId = tokens[1];
const std::string& docKey = tokens[2];
const std::string& docId = tokens[3];
const int canonicalViewId = std::stoi(tokens[4]);
const std::string fileId = Util::getFilenameFromURL(docKey);
Util::mapAnonymized(fileId, fileId); // Identity mapping, since fileId is already obfuscated
std::string url;
URI::decode(docKey, url);
LOG_INF("New session [" << sessionId << "] request on url [" << url << "] with viewId " << canonicalViewId);
#ifndef IOS
Util::setThreadName("kit" SHARED_DOC_THREADNAME_SUFFIX + docId);
#endif
if (!_document)
{
_document = std::make_shared<Document>(
_loKit, _jailId, docKey, docId, url, _queue,
std::static_pointer_cast<WebSocketHandler>(shared_from_this()),
_mobileAppDocId);
_ksPoll->setDocument(_document);
// We need to send the process name information to WSD if Trace Event recording is enabled (but
// not turned on) because it might be turned on later.
// We can do this only after creating the Document object.
TraceEvent::emitOneRecordingIfEnabled(std::string("{\"name\":\"process_name\",\"ph\":\"M\",\"args\":{\"name\":\"")
+ "Kit-" + docId
+ "\"},\"pid\":"
+ std::to_string(getpid())
+ ",\"tid\":"
+ std::to_string(Util::getThreadId())
+ "},\n");
}
// Validate and create session.
if (!(url == _document->getUrl() && _document->createSession(sessionId, canonicalViewId)))
{
LOG_DBG("CreateSession failed.");
}
}
else if (tokens.equals(0, "exit"))
{
#if !MOBILEAPP
LOG_INF("Terminating immediately due to parent 'exit' command.");
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_SOFTWARE);
#else
#ifdef IOS
LOG_INF("Setting our KitSocketPoll's termination flag due to 'exit' command.");
std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex);
_ksPoll->terminationFlag = true;
_ksPoll->terminationCV.notify_all();
#else
LOG_INF("Setting TerminationFlag due to 'exit' command.");
SigUtil::setTerminationFlag();
#endif
_document.reset();
#endif
}
else if (tokens.equals(0, "tile") || tokens.equals(0, "tilecombine") || tokens.equals(0, "canceltiles") ||
tokens.equals(0, "paintwindow") || tokens.equals(0, "resizewindow") ||
COOLProtocol::getFirstToken(tokens[0], '-') == "child")
{
if (_document)
{
_queue->put(message);
}
else
{
LOG_WRN("No document while processing " << tokens[0] << " request.");
}
}
else if (tokens.size() == 3 && tokens.equals(0, "setconfig"))
{
#if !MOBILEAPP
// Currently only rlimit entries are supported.
if (!Rlimit::handleSetrlimitCommand(tokens))
{
LOG_ERR("Unknown setconfig command: " << message);
}
#endif
}
else if (tokens.equals(0, "setloglevel"))
{
Log::logger().setLevel(tokens[1]);
}
else
{
LOG_ERR("Bad or unknown token [" << tokens[0] << ']');
}
}
virtual void enableProcessInput(bool enable = true) override
{
WebSocketHandler::enableProcessInput(enable);
if (_document)
_document->enableProcessInput(enable);
// Wake up poll to process data from socket input buffer
if (enable && _ksPoll)
{
_ksPoll->wakeup();
}
}
void onDisconnect() override
{
#if !MOBILEAPP
LOG_ERR("Kit connection lost without exit arriving from wsd. Setting TerminationFlag");
SigUtil::setTerminationFlag();
#endif
#ifdef IOS
{
std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex);
_ksPoll->terminationFlag = true;
_ksPoll->terminationCV.notify_all();
}
#endif
_ksPoll.reset();
}
};
void documentViewCallback(const int type, const char* payload, void* data)
{
Document::ViewCallback(type, payload, data);
}
/// Called by LOK main-loop the central location for data processing.
int pollCallback(void* pData, int timeoutUs)
{
#ifndef IOS
if (!pData)
return 0;
else
return reinterpret_cast<KitSocketPoll*>(pData)->kitPoll(timeoutUs);
#else
std::unique_lock<std::mutex> lock(KitSocketPoll::KSPollsMutex);
std::vector<std::shared_ptr<KitSocketPoll>> v;
for (const auto &i : KitSocketPoll::KSPolls)
{
auto p = i.lock();
if (p)
v.push_back(p);
}
lock.unlock();
if (v.size() == 0)
{
std::this_thread::sleep_for(std::chrono::microseconds(timeoutUs));
}
else
{
for (const auto &p : v)
p->kitPoll(timeoutUs);
}
// We never want to exit the main loop
return 0;
#endif
}
/// Called by LOK main-loop
void wakeCallback(void* pData)
{
#ifndef IOS
if (!pData)
return;
else
return reinterpret_cast<KitSocketPoll*>(pData)->wakeup();
#else
std::unique_lock<std::mutex> lock(KitSocketPoll::KSPollsMutex);
if (KitSocketPoll::KSPolls.size() == 0)
return;
std::vector<std::shared_ptr<KitSocketPoll>> v;
for (const auto &i : KitSocketPoll::KSPolls)
{
auto p = i.lock();
if (p)
v.push_back(p);
}
lock.unlock();
for (const auto &p : v)
p->wakeup();
#endif
}
#ifndef BUILDING_TESTS
void lokit_main(
#if !MOBILEAPP
const std::string& childRoot,
const std::string& jailId,
const std::string& sysTemplate,
const std::string& loTemplate,
const std::string& loSubPath,
bool noCapabilities,
bool noSeccomp,
bool queryVersion,
bool displayVersion,
#else
int docBrokerSocket,
const std::string& userInterface,
#endif
std::size_t numericIdentifier
)
{
#if !MOBILEAPP
#ifndef FUZZER
SigUtil::setFatalSignals("kit startup of " COOLWSD_VERSION " " COOLWSD_VERSION_HASH);
SigUtil::setTerminationSignals();
#endif
Util::setThreadName("kit_spare_" + Util::encodeId(numericIdentifier, 3));
// Reinitialize logging when forked.
const bool logToFile = std::getenv("COOL_LOGFILE");
const char* logFilename = std::getenv("COOL_LOGFILENAME");
const char* logLevel = std::getenv("COOL_LOGLEVEL");
const bool logColor = config::getBool("logging.color", true) && isatty(fileno(stderr));
std::map<std::string, std::string> logProperties;
if (logToFile && logFilename)
{
logProperties["path"] = std::string(logFilename);
}
Util::rng::reseed();
const std::string LogLevel = logLevel ? logLevel : "trace";
const bool bTraceStartup = (std::getenv("COOL_TRACE_STARTUP") != nullptr);
Log::initialize("kit", bTraceStartup ? "trace" : logLevel, logColor, logToFile, logProperties);
if (bTraceStartup && LogLevel != "trace")
{
LOG_INF("Setting log-level to [trace] and delaying setting to configured [" << LogLevel << "] until after Kit initialization.");
}
const char* pAnonymizationSalt = std::getenv("COOL_ANONYMIZATION_SALT");
if (pAnonymizationSalt)
{
AnonymizationSalt = std::stoull(std::string(pAnonymizationSalt));
AnonymizeUserData = true;
}
LOG_INF("User-data anonymization is " << (AnonymizeUserData ? "enabled." : "disabled."));
assert(!childRoot.empty());
assert(!sysTemplate.empty());
assert(!loTemplate.empty());
assert(!loSubPath.empty());
LOG_INF("Kit process for Jail [" << jailId << "] started.");
std::string userdir_url;
std::string instdir_path;
int ProcSMapsFile = -1;
// lokit's destroy typically throws from
// framework/source/services/modulemanager.cxx:198
// So we insure it lives until std::_Exit is called.
std::shared_ptr<lok::Office> loKit;
ChildSession::NoCapsForKit = noCapabilities;
#endif // MOBILEAPP
try
{
#if !MOBILEAPP
const Path jailPath = Path::forDirectory(childRoot + '/' + jailId);
const std::string jailPathStr = jailPath.toString();
LOG_INF("Jail path: " << jailPathStr);
File(jailPath).createDirectories();
chmod(jailPathStr.c_str(), S_IXUSR | S_IWUSR | S_IRUSR);
if (!ChildSession::NoCapsForKit)
{
std::chrono::time_point<std::chrono::steady_clock> jailSetupStartTime
= std::chrono::steady_clock::now();
userdir_url = "file:///tmp/user";
instdir_path = '/' + loSubPath + "/program";
Poco::Path jailLOInstallation(jailPath, loSubPath);
jailLOInstallation.makeDirectory();
const std::string loJailDestPath = jailLOInstallation.toString();
// The bind-mount implementation: inlined here to mirror
// the fallback link/copy version bellow.
const auto mountJail = [&]() -> bool {
// Mount sysTemplate for the jail directory.
LOG_INF("Mounting " << sysTemplate << " -> " << jailPathStr);
if (!JailUtil::bind(sysTemplate, jailPathStr)
|| !JailUtil::remountReadonly(sysTemplate, jailPathStr))
{
LOG_ERR("Failed to mount [" << sysTemplate << "] -> [" << jailPathStr
<< "], will link/copy contents.");
return false;
}
// Mount loTemplate inside it.
LOG_INF("Mounting " << loTemplate << " -> " << loJailDestPath);
Poco::File(loJailDestPath).createDirectories();
if (!JailUtil::bind(loTemplate, loJailDestPath)
|| !JailUtil::remountReadonly(loTemplate, loJailDestPath))
{
LOG_WRN("Failed to mount [" << loTemplate << "] -> [" << loJailDestPath
<< "], will link/copy contents.");
return false;
}
// tmpdir inside the jail for added sercurity.
const std::string tempRoot = Poco::Path(childRoot, "tmp").toString();
const std::string tmpSubDir = Poco::Path(tempRoot, "cool-" + jailId).toString();
Poco::File(tmpSubDir).createDirectories();
const std::string jailTmpDir = Poco::Path(jailPath, "tmp").toString();
LOG_INF("Mounting random temp dir " << tmpSubDir << " -> " << jailTmpDir);
if (!JailUtil::bind(tmpSubDir, jailTmpDir))
{
LOG_ERR("Failed to mount [" << tmpSubDir << "] -> [" << jailTmpDir
<< "], will link/copy contents.");
return false;
}
return true;
};
// Copy (link) LO installation and other necessary files into it from the template.
bool bindMount = JailUtil::isBindMountingEnabled();
if (bindMount)
{
if (!mountJail())
{
LOG_INF("Cleaning up jail before linking/copying.");
JailUtil::removeJail(jailPathStr);
bindMount = false;
JailUtil::disableBindMounting();
}
}
if (!bindMount)
{
LOG_INF("Mounting is disabled, will link/copy " << sysTemplate << " -> "
<< jailPathStr);
const std::string linkablePath = childRoot + "/linkable";
linkOrCopy(sysTemplate, jailPath, linkablePath, LinkOrCopyType::All);
linkOrCopy(loTemplate, loJailDestPath, linkablePath, LinkOrCopyType::LO);
// Update the dynamic files inside the jail.
if (!JailUtil::SysTemplate::updateDynamicFiles(jailPathStr))
{
LOG_ERR(
"Failed to update the dynamic files in the jail ["
<< jailPathStr
<< "]. If the systemplate directory is owned by a superuser or is "
"read-only, running the installation scripts with the owner's account "
"should update these files. Some functionality may be missing.");
}
// Create a file to mark this a copied jail.
JailUtil::markJailCopied(jailPathStr);
}
// Setup the devices inside /tmp and set TMPDIR.
JailUtil::setupJailDevNodes(Poco::Path(jailPath, "/tmp").toString());
::setenv("TMPDIR", "/tmp", 1);
// HOME must be writable, so create it in /tmp.
constexpr const char* HomePathInJail = "/tmp/home";
Poco::File(Poco::Path(jailPath, HomePathInJail)).createDirectories();
::setenv("HOME", HomePathInJail, 1);
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - jailSetupStartTime);
LOG_DBG("Initialized jail files in " << ms);
ProcSMapsFile = open("/proc/self/smaps", O_RDONLY);
if (ProcSMapsFile < 0)
LOG_SYS("Failed to open /proc/self/smaps. Memory stats will be missing.");
LOG_INF("chroot(\"" << jailPathStr << "\")");
if (chroot(jailPathStr.c_str()) == -1)
{
LOG_SFL("chroot(\"" << jailPathStr << "\") failed");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
if (chdir("/") == -1)
{
LOG_SFL("chdir(\"/\") in jail failed");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
#ifndef __FreeBSD__
dropCapability(CAP_SYS_CHROOT);
dropCapability(CAP_MKNOD);
dropCapability(CAP_FOWNER);
dropCapability(CAP_CHOWN);
#else
cap_enter();
#endif
LOG_DBG("Initialized jail nodes, dropped caps.");
}
else // noCapabilities set
{
LOG_WRN("Security warning: running without chroot jails is insecure.");
LOG_INF("Using template ["
<< loTemplate << "] as install subpath directly, without chroot jail setup.");
userdir_url = "file:///" + jailPathStr + "/tmp/user";
instdir_path = '/' + loTemplate + "/program";
JailRoot = jailPathStr;
}
LOG_DBG("Initializing LOK with instdir [" << instdir_path << "] and userdir ["
<< userdir_url << "].");
LibreOfficeKit *kit;
{
const char *instdir = instdir_path.c_str();
const char *userdir = userdir_url.c_str();
#ifndef KIT_IN_PROCESS
kit = UnitKit::get().lok_init(instdir, userdir);
#else
kit = nullptr;
#ifdef FUZZER
if (COOLWSD::DummyLOK)
kit = dummy_lok_init_2(instdir, userdir);
#endif
#endif
if (!kit)
{
kit = (initFunction ? initFunction(instdir, userdir)
: lok_init_2(instdir, userdir));
}
loKit = std::make_shared<lok::Office>(kit);
if (!loKit)
{
LOG_FTL("LibreOfficeKit initialization failed. Exiting.");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
}
// Lock down the syscalls that can be used
if (!Seccomp::lockdown(Seccomp::Type::KIT))
{
if (!noSeccomp)
{
LOG_FTL("LibreOfficeKit seccomp security lockdown failed. Exiting.");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
LOG_ERR("LibreOfficeKit seccomp security lockdown failed, but configured to continue. "
"You are running in a significantly less secure mode.");
}
rlimit rlim = { 0, 0 };
if (getrlimit(RLIMIT_AS, &rlim) == 0)
LOG_INF("RLIMIT_AS is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)");
else
LOG_SYS("Failed to get RLIMIT_AS");
if (getrlimit(RLIMIT_STACK, &rlim) == 0)
LOG_INF("RLIMIT_STACK is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)");
else
LOG_SYS("Failed to get RLIMIT_STACK");
if (getrlimit(RLIMIT_FSIZE, &rlim) == 0)
LOG_INF("RLIMIT_FSIZE is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)");
else
LOG_SYS("Failed to get RLIMIT_FSIZE");
if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
LOG_INF("RLIMIT_NOFILE is " << rlim.rlim_max << " files.");
else
LOG_SYS("Failed to get RLIMIT_NOFILE");
LOG_INF("Kit process for Jail [" << jailId << "] is ready.");
std::string pathAndQuery(NEW_CHILD_URI);
pathAndQuery.append("?jailid=");
pathAndQuery.append(jailId);
if (queryVersion)
{
char* versionInfo = loKit->getVersionInfo();
std::string versionString(versionInfo);
if (displayVersion)
std::cout << "office version details: " << versionString << std::endl;
SigUtil::setVersionInfo(versionString);
// Add some parameters we want to pass to the client. Could not figure out how to get
// the configuration parameters from COOLWSD.cpp's initialize() or coolwsd.xml here, so
// oh well, just have the value hardcoded in KitHelper.hpp. It isn't really useful to
// "tune" it at end-user installations anyway, I think.
auto versionJSON = Poco::JSON::Parser().parse(versionString).extract<Poco::JSON::Object::Ptr>();
versionJSON->set("tunnelled_dialog_image_cache_size", std::to_string(LOKitHelper::tunnelledDialogImageCacheSize));
std::stringstream ss;
versionJSON->stringify(ss);
versionString = ss.str();
std::string encodedVersion;
Poco::URI::encode(versionString, "?#/", encodedVersion);
pathAndQuery.append("&version=");
pathAndQuery.append(encodedVersion);
free(versionInfo);
}
#else // MOBILEAPP
#ifndef IOS
// Was not done by the preload.
// For iOS we call it in -[AppDelegate application: didFinishLaunchingWithOptions:]
setupKitEnvironment(userInterface);
#endif
#if (defined(__linux__) && !defined(__ANDROID__)) || defined(__FreeBSD__)
Poco::URI userInstallationURI("file", LO_PATH);
LibreOfficeKit *kit = lok_init_2(LO_PATH "/program", userInstallationURI.toString().c_str());
#else
#ifdef IOS // In the iOS app we call lok_init_2() just once, when the app starts
static LibreOfficeKit *kit = lo_kit;
#else
static LibreOfficeKit *kit = lok_init_2(nullptr, nullptr);
#endif
#endif
assert(kit);
static std::shared_ptr<lok::Office> loKit = std::make_shared<lok::Office>(kit);
assert(loKit);
COOLWSD::LOKitVersion = loKit->getVersionInfo();
// Dummies
const std::string jailId = "jailid";
#endif // MOBILEAPP
auto mainKit = KitSocketPoll::create();
mainKit->runOnClientThread(); // We will do the polling on this thread.
std::shared_ptr<KitWebSocketHandler> websocketHandler =
std::make_shared<KitWebSocketHandler>("child_ws", loKit, jailId, mainKit, numericIdentifier);
#if !MOBILEAPP
mainKit->insertNewUnixSocket(MasterLocation, pathAndQuery, websocketHandler, ProcSMapsFile);
#else
mainKit->insertNewFakeSocket(docBrokerSocket, websocketHandler);
#endif
LOG_INF("New kit client websocket inserted.");
#if !MOBILEAPP
if (bTraceStartup && LogLevel != "trace")
{
LOG_INF("Kit initialization complete: setting log-level to [" << LogLevel << "] as configured.");
Log::logger().setLevel(LogLevel);
}
#endif
#ifndef IOS
if (!LIBREOFFICEKIT_HAS(kit, runLoop))
{
LOG_FTL("Kit is missing Unipoll API");
std::cout << "Fatal: out of date LibreOfficeKit - no Unipoll API\n";
std::_Exit(EX_SOFTWARE);
}
LOG_INF("Kit unipoll loop run");
loKit->runLoop(pollCallback, wakeCallback, mainKit.get());
LOG_INF("Kit unipoll loop run terminated.");
#if MOBILEAPP
SocketPoll::wakeupWorld();
#else
// Trap the signal handler, if invoked,
// to prevent exiting.
LOG_INF("Kit process for Jail [" << jailId << "] finished.");
Log::shutdown();
// Let forkit handle the jail cleanup.
#endif
#else // IOS
std::unique_lock<std::mutex> lock(mainKit->terminationMutex);
mainKit->terminationCV.wait(lock,[&]{ return mainKit->terminationFlag; } );
#endif // !IOS
}
catch (const Exception& exc)
{
LOG_ERR("Poco Exception: " << exc.displayText() <<
(exc.nested() ? " (" + exc.nested()->displayText() + ')' : ""));
}
catch (const std::exception& exc)
{
LOG_ERR("Exception: " << exc.what());
}
#if !MOBILEAPP
LOG_INF("Kit process for Jail [" << jailId << "] finished.");
flushTraceEventRecordings();
Log::shutdown();
// Wait for the signal handler, if invoked, to prevent exiting until done.
SigUtil::waitSigHandlerTrap();
std::_Exit(EX_OK);
#endif
}
#ifdef IOS
// In the iOS app we can have several documents open in the app process at the same time, thus
// several lokit_main() functions running at the same time. We want just one LO main loop, though,
// so we start it separately in its own thread.
void runKitLoopInAThread()
{
std::thread([&]
{
Util::setThreadName("lokit_runloop");
std::shared_ptr<lok::Office> loKit = std::make_shared<lok::Office>(lo_kit);
int dummy;
loKit->runLoop(pollCallback, wakeCallback, &dummy);
// Should never return
assert(false);
NSLog(@"loKit->runLoop() unexpectedly returned");
std::abort();
}).detach();
}
#endif // IOS
#endif // !BUILDING_TESTS
std::string anonymizeUrl(const std::string& url)
{
#ifndef BUILDING_TESTS
return AnonymizeUserData ? Util::anonymizeUrl(url, AnonymizationSalt) : url;
#else
return url;
#endif
}
#if !MOBILEAPP
/// Initializes LibreOfficeKit for cross-fork re-use.
bool globalPreinit(const std::string &loTemplate)
{
#ifdef FUZZER
if (COOLWSD::DummyLOK)
return true;
#endif
const std::string libSofficeapp = loTemplate + "/program/" LIB_SOFFICEAPP;
const std::string libMerged = loTemplate + "/program/" LIB_MERGED;
std::string loadedLibrary;
void *handle;
if (File(libMerged).exists())
{
LOG_TRC("dlopen(" << libMerged << ", RTLD_GLOBAL|RTLD_NOW)");
handle = dlopen(libMerged.c_str(), RTLD_GLOBAL|RTLD_NOW);
if (!handle)
{
LOG_FTL("Failed to load " << libMerged << ": " << dlerror());
return false;
}
loadedLibrary = libMerged;
}
else
{
if (File(libSofficeapp).exists())
{
LOG_TRC("dlopen(" << libSofficeapp << ", RTLD_GLOBAL|RTLD_NOW)");
handle = dlopen(libSofficeapp.c_str(), RTLD_GLOBAL|RTLD_NOW);
if (!handle)
{
LOG_FTL("Failed to load " << libSofficeapp << ": " << dlerror());
return false;
}
loadedLibrary = libSofficeapp;
}
else
{
LOG_FTL("Neither " << libSofficeapp << " or " << libMerged << " exist.");
return false;
}
}
LokHookPreInit* preInit = reinterpret_cast<LokHookPreInit *>(dlsym(handle, "lok_preinit"));
if (!preInit)
{
LOG_FTL("No lok_preinit symbol in " << loadedLibrary << ": " << dlerror());
return false;
}
initFunction = reinterpret_cast<LokHookFunction2 *>(dlsym(handle, "libreofficekit_hook_2"));
if (!initFunction)
{
LOG_FTL("No libreofficekit_hook_2 symbol in " << loadedLibrary << ": " << dlerror());
}
// Disable problematic components that may be present from a
// desktop or developer's install if env. var not set.
::setenv("UNODISABLELIBRARY",
"abp avmediagst avmediavlc cmdmail losessioninstall OGLTrans PresenterScreen "
"syssh ucpftp1 ucpgio1 ucphier1 ucpimage updatecheckui updatefeed updchk"
// Database
"dbaxml dbmm dbp dbu deployment firebird_sdbc mork "
"mysql mysqlc odbc postgresql-sdbc postgresql-sdbc-impl sdbc2 sdbt"
// Java
"javaloader javavm jdbc rpt rptui rptxml ",
0 /* no overwrite */);
LOG_TRC("Invoking lok_preinit(" << loTemplate << "/program\", \"file:///tmp/user\")");
const auto start = std::chrono::steady_clock::now();
if (preInit((loTemplate + "/program").c_str(), "file:///tmp/user") != 0)
{
LOG_FTL("lok_preinit() in " << loadedLibrary << " failed");
return false;
}
LOG_TRC("Finished lok_preinit(" << loTemplate << "/program\", \"file:///tmp/user\") in "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start));
return true;
}
/// Anonymize usernames.
std::string anonymizeUsername(const std::string& username)
{
#ifndef BUILDING_TESTS
return AnonymizeUserData ? Util::anonymize(username, AnonymizationSalt) : username;
#else
return username;
#endif
}
#endif // !MOBILEAPP
void dump_kit_state()
{
std::ostringstream oss;
KitSocketPoll::dumpGlobalState(oss);
const std::string msg = oss.str();
fprintf(stderr, "%s", msg.c_str());
LOG_TRC(msg);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| 35.465657 | 190 | 0.547075 | CaptainVal |
3a8d99afc16a7f74affe9733ea3657ef04d0c661 | 572 | cc | C++ | src/snakebird/level10.cc | jsnell/snakebird | ceba0c40dbd854c4a2eadc9da63b18b636397601 | [
"MIT"
] | null | null | null | src/snakebird/level10.cc | jsnell/snakebird | ceba0c40dbd854c4a2eadc9da63b18b636397601 | [
"MIT"
] | null | null | null | src/snakebird/level10.cc | jsnell/snakebird | ceba0c40dbd854c4a2eadc9da63b18b636397601 | [
"MIT"
] | null | null | null | #include "main.h"
int main() {
const char* base_map =
".............."
". ... ."
". .... * ."
". . ."
". O . v.. ."
". R<<. ."
". .... .. ."
". ... . ."
". . O ."
". . .. ."
". . .. ."
". .. .. ."
". .... ."
"~~~~~~~~~~~~~~";
using St = State<Setup<14, 14, 2, 1, 6>>;
St::Map map(base_map);
St st(map);
st.print(map);
EXPECT_EQ(33, search(st, map));
return 0;
}
| 20.428571 | 45 | 0.22028 | jsnell |
3a9214a83e6cc62137686ba75998bc6fdb1d21d1 | 2,303 | cpp | C++ | Renderer/phong_shader.cpp | ZoonLogonEchon/SimpleSceneRenderer | 500fff6d1aca5d8fd293f96cc952db23175dfa0e | [
"MIT"
] | null | null | null | Renderer/phong_shader.cpp | ZoonLogonEchon/SimpleSceneRenderer | 500fff6d1aca5d8fd293f96cc952db23175dfa0e | [
"MIT"
] | null | null | null | Renderer/phong_shader.cpp | ZoonLogonEchon/SimpleSceneRenderer | 500fff6d1aca5d8fd293f96cc952db23175dfa0e | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <random>
#include <string>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "phong_shader.hpp"
#include "Shaders/shaders.hpp"
PhongShader::PhongShader()
{
std::string vSSrc = Shaders::getVertexShader();
std::string fSSrc = Shaders::getFragmentShader();
prog = std::make_shared<OGLProgram>();
prog->compileAndAttachShader(vSSrc.c_str(), GL_VERTEX_SHADER);
prog->compileAndAttachShader(fSSrc.c_str(), GL_FRAGMENT_SHADER);
prog->link();
attributeBindingPoints["aPos"] = 0;
attributeBindingPoints["aNormal"] = 1;
binding_point_pos_att = 0;
binding_point_normal_att = 1;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// position
auto pos_loc = prog->getAttributeLocation("aPos");
glVertexAttribFormat(pos_loc, 3, GL_FLOAT, GL_FALSE, 0);
glVertexAttribBinding(pos_loc, attributeBindingPoints["aPos"]);
glEnableVertexAttribArray(pos_loc);
// normals
auto normal_loc = prog->getAttributeLocation("aNormal");
glVertexAttribFormat(normal_loc, 3, GL_FLOAT, GL_FALSE, 0);
glVertexAttribBinding(normal_loc, attributeBindingPoints["aNormal"]);
glEnableVertexAttribArray(normal_loc);
glBindVertexArray(0);
}
PhongShader::~PhongShader()
{
}
void PhongShader::use()
{
prog->use();
}
void PhongShader::draw(Mesh* mesh)
{
glBindVertexArray(vao);
//glBindVertexBuffer(attributeBindingPoints["aPos"], mesh->getPositionsPointer(), 0, 0);
//glBindVertexBuffer(attributeBindingPoints["aNormal"], mesh->getNormalsPointer(), 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->getIndecesPointer());
glDrawElements(GL_TRIANGLES, mesh->getFaceIndeces().size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void PhongShader::setAttributeBindingPoint(const char* attr_name, GLuint binding_point)
{
glBindVertexArray(vao);
prog->setAttributeBindingPoint(attr_name, binding_point);
glBindVertexArray(0);
}
void PhongShader::setUniformBlockBindingPoint(const char* unif_name, GLuint binding_point)
{
prog->setUniformBlockBindingPoint(unif_name, binding_point);
}
void PhongShader::setUniformMatrix4(const char* unif_name, const glm::mat4& mat)
{
prog->setUniformMatrix4(unif_name, mat);
}
void PhongShader::setUniformVector3(const char* unif_name, const glm::vec3& vec)
{
prog->setUniformVector3(unif_name, vec);
}
| 29.151899 | 90 | 0.775076 | ZoonLogonEchon |
3a966748ab81325074627b082b498a7023372bc4 | 688 | hpp | C++ | include/gridtools/stencil/core/cache_info.hpp | afanfa/gridtools | 6b1fd1f916d291f9a1cab1d27b48aa0282097d68 | [
"BSD-3-Clause"
] | 36 | 2019-04-05T15:54:48.000Z | 2022-03-31T13:25:40.000Z | include/gridtools/stencil/core/cache_info.hpp | afanfa/gridtools | 6b1fd1f916d291f9a1cab1d27b48aa0282097d68 | [
"BSD-3-Clause"
] | 411 | 2019-04-05T18:51:57.000Z | 2022-03-28T11:52:40.000Z | include/gridtools/stencil/core/cache_info.hpp | afanfa/gridtools | 6b1fd1f916d291f9a1cab1d27b48aa0282097d68 | [
"BSD-3-Clause"
] | 23 | 2019-04-05T15:48:26.000Z | 2021-09-28T16:54:24.000Z | /*
* GridTools
*
* Copyright (c) 2014-2021, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include "../../meta/list.hpp"
namespace gridtools {
namespace stencil {
namespace core {
template <class Plh, class CacheTypes = meta::list<>, class CacheIOPolicies = meta::list<>>
struct cache_info {
using plh_t = Plh;
using cache_types_t = CacheTypes;
using cache_io_policies_t = CacheIOPolicies;
};
} // namespace core
} // namespace stencil
} // namespace gridtools
| 26.461538 | 103 | 0.601744 | afanfa |
3a97da9892b03ccef4769225e3cead0e9d12c85f | 1,891 | cpp | C++ | src/telecom/src/telecomTest.cpp | GOFIRST-Robotics/NASA-Lunabotics-2022 | 6b9a2f8fa6e6a025274b3c5b305ef8bb07a42aa5 | [
"MIT"
] | 3 | 2021-11-05T22:05:40.000Z | 2022-01-25T23:58:40.000Z | src/telecom/src/telecomTest.cpp | GOFIRST-Robotics/NASA-Lunabotics-2022 | 6b9a2f8fa6e6a025274b3c5b305ef8bb07a42aa5 | [
"MIT"
] | 35 | 2019-10-12T15:34:30.000Z | 2020-10-07T23:45:03.000Z | src/telecom/src/telecomTest.cpp | GOFIRST-Robotics/NASA-RMC-2020-NorthstarRobotics | fd69e48baba53990fa60624005707b5edfb65741 | [
"MIT"
] | 2 | 2021-11-05T23:42:32.000Z | 2021-11-05T23:59:55.000Z | #include <cstdio>
#include <cstring>
#include <string>
//http://wjwwood.io/serial/doc/1.1.0/classserial_1_1_serial.html
#include "telecom/telecom.h"
#define ERR_CHECK \
do { if (com.status() != 0){ \
fprintf(stdout, "Error: %s\n", com.verboseStatus().c_str()); \
return com.status(); \
} } while(0)
int main(int argc, char *argv[]){
if (argc != 4){
fprintf(stderr, "usage: ./programname dst-hostname dst-udpport src-udpport\n");
exit(1);
}
Telecom com(argv[1], atoi(argv[2]), atoi(argv[3]));
com.setFailureAction(false);
com.setBlockingTime(0,0);
ERR_CHECK;
time_t timer;
time(&timer);
// Joystick js(); // #include "joystick.hh"
// Exit if !js.isFound()
// com.fdAdd(js.fd());
while(1){
com.update();
ERR_CHECK;
// JoystickEvent event;
// Receive from remote
if(com.recvAvail()){
std::string msg = com.recv();
//ERR_CHECK; // This makes it crash???
if(!msg.empty())
printf("Received message: %s\n", msg.c_str());
if(!msg.compare("EOM\n")){ break; } // delete if not want remote close
}
// Reboot if comunication channel closed
while(com.isComClosed()){
printf("Rebooting connection\n");
com.reboot();
}
// Get user stdio input to send
if(com.stdioReadAvail()){
std::string msg = com.stdioRead();
ERR_CHECK;
if(!msg.compare("EOM\n")){ // Assume desired for connection to close
com.send(msg); // Delete for debug connection testing
printf("Received EOM closing\n");
break;
}
com.send(msg);
ERR_CHECK;
}
// Example if including joystick
// if(com.fdReadAvail(js.fd()) && js.sample(&event)){
// ... process buttons and axis of event ... }
// heartbeat
if(difftime(time(NULL), timer) > 10){
timer = time(NULL);
printf(".\n");
}
}
}
| 23.936709 | 83 | 0.584876 | GOFIRST-Robotics |
3a981a399776b3a9d0d67b986dff21ebb8eca481 | 989 | cpp | C++ | 06-class-design/readerEx.06.05/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | 81 | 2018-11-15T21:23:19.000Z | 2022-03-06T09:46:36.000Z | 06-class-design/readerEx.06.05/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | null | null | null | 06-class-design/readerEx.06.05/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | 41 | 2018-11-15T21:23:24.000Z | 2022-02-24T03:02:26.000Z | //
// main.cpp
//
// Exercises the calendar class.
//
// --------------------------------------------------------------------------
// Attribution: "Programming Abstractions in C++" by Eric Roberts
// Chapter 6, Exercise 5
// Stanford University, Autumn Quarter 2012
// http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf
// --------------------------------------------------------------------------
//
// Created by Glenn Streiff on 12/16/15.
// Copyright © 2015 Glenn Streiff. All rights reserved.
//
#include <iostream>
#include "calendar.h"
const std::string HEADER = "CS106B Programming Abstractions in C++: Ex 6.5\n";
const std::string DETAIL = "Extend the Ex 2.11 calendar.h interface.";
const std::string BANNER = HEADER + DETAIL;
int main(int argc, char * argv[]) {
std::cout << BANNER << std::endl << std::endl;
Date moonLanding(JULY, 20, 1969);
std::cout << moonLanding.toString() << std::endl;
return 0;
}
| 29.969697 | 91 | 0.570273 | heavy3 |
3a9aab6dd9ef4684f24f77565cb943b6ef268c29 | 2,100 | cpp | C++ | Sources/AGEngine/Skinning/AnimationChannel.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 47 | 2015-03-29T09:44:25.000Z | 2020-11-30T10:05:56.000Z | Sources/AGEngine/Skinning/AnimationChannel.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 313 | 2015-01-01T18:16:30.000Z | 2015-11-30T07:54:07.000Z | Sources/AGEngine/Skinning/AnimationChannel.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 9 | 2015-06-07T13:21:54.000Z | 2020-08-25T09:50:07.000Z | #include "AnimationChannel.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/matrix_interpolation.hpp>
#include <Utils/Serialization/SerializationArchives.hpp>
namespace AGE{
void AnimationChannel::findKeyIndex(float t, glm::uvec3 &keys, glm::uvec3 &nextKeys)
{
if (scale.size() <= 1)
{
keys.x = 0;
nextKeys.x = 0;
}
else
{
for (unsigned int i = 0; i < scale.size() - 1; i++)
{
if (t < scale[i + 1].time) {
keys.x = i;
nextKeys.x = i + 1;
break;
}
}
}
if (rotation.size() <= 1)
{
keys.y = 0;
nextKeys.y = 0;
}
else
{
for (unsigned int i = 0; i < rotation.size() - 1; i++)
{
if (t < rotation[i + 1].time) {
keys.y = i;
nextKeys.y = i + 1;
break;
}
}
}
if (translation.size() <= 1)
{
keys.z = 0;
nextKeys.z = 0;
}
else
{
for (unsigned int i = 0; i < translation.size() - 1; i++)
{
if (t < translation[i + 1].time) {
keys.z = i;
nextKeys.z = i + 1;
break;
}
}
}
}
void AnimationChannel::getInterpolatedTransform(float t, glm::mat4 &res)
{
glm::uvec3 key = glm::uvec3(static_cast<unsigned int>(t));
glm::uvec3 nextKey = glm::uvec3(key.x + 1);
findKeyIndex(t, key, nextKey);
res = glm::translate(glm::mat4(1), glm::mix(translation[key.z].value, translation[nextKey.z].value, (t - translation[key.z].time) / translation[key.z].deltaTime));
res = glm::scale(res, glm::mix(scale[key.x].value, scale[nextKey.x].value, (t - scale[key.x].time) / scale[key.x].deltaTime));
res *= glm::mat4_cast(glm::normalize(glm::slerp(rotation[key.y].value, rotation[nextKey.y].value, (t - rotation[key.y].time) / rotation[key.y].deltaTime)));
}
}
SERIALIZATION_SERIALIZE_METHOD_DEFINITION(AGE::AnimationChannel, *"*/ ar(cereal::make_nvp(MACRO_STR(bone), boneIndex)); ar(cereal::make_nvp(MACRO_STR(scale), scale)); ar(cereal::make_nvp(MACRO_STR(rotation), rotation)); ar(cereal::make_nvp(MACRO_STR(translation), translation)); /*"*);
| 25.925926 | 285 | 0.618571 | Another-Game-Engine |
3a9b4ced3ebb2d74b1cb8a18b6e42f117ba63d10 | 2,229 | hpp | C++ | randomprime/nod_wrapper/nod/include/nod/IFileIO.hpp | MeriKatt/metroid-prime-randomizer-custom | c431358af2ce3159909c1ae26034547053560fc6 | [
"MIT"
] | null | null | null | randomprime/nod_wrapper/nod/include/nod/IFileIO.hpp | MeriKatt/metroid-prime-randomizer-custom | c431358af2ce3159909c1ae26034547053560fc6 | [
"MIT"
] | null | null | null | randomprime/nod_wrapper/nod/include/nod/IFileIO.hpp | MeriKatt/metroid-prime-randomizer-custom | c431358af2ce3159909c1ae26034547053560fc6 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <functional>
#include <cstdlib>
#include "IDiscIO.hpp"
#include "Util.hpp"
namespace nod {
class IFileIO {
public:
virtual ~IFileIO() = default;
virtual bool exists() = 0;
virtual uint64_t size() = 0;
struct IWriteStream : nod::IWriteStream {
uint64_t copyFromDisc(IPartReadStream& discio, uint64_t length) {
uint64_t read = 0;
uint8_t buf[0x7c00];
while (length) {
uint64_t thisSz = nod::min(uint64_t(0x7c00), length);
uint64_t readSz = discio.read(buf, thisSz);
if (thisSz != readSz) {
LogModule.report(logvisor::Error, "unable to read enough from disc");
return read;
}
if (write(buf, readSz) != readSz) {
LogModule.report(logvisor::Error, "unable to write in file");
return read;
}
length -= thisSz;
read += thisSz;
}
return read;
}
uint64_t copyFromDisc(IPartReadStream& discio, uint64_t length, const std::function<void(float)>& prog) {
uint64_t read = 0;
uint8_t buf[0x7c00];
uint64_t total = length;
while (length) {
uint64_t thisSz = nod::min(uint64_t(0x7c00), length);
uint64_t readSz = discio.read(buf, thisSz);
if (thisSz != readSz) {
LogModule.report(logvisor::Error, "unable to read enough from disc");
return read;
}
if (write(buf, readSz) != readSz) {
LogModule.report(logvisor::Error, "unable to write in file");
return read;
}
length -= thisSz;
read += thisSz;
prog(read / float(total));
}
return read;
}
};
virtual std::unique_ptr<IWriteStream> beginWriteStream() const = 0;
virtual std::unique_ptr<IWriteStream> beginWriteStream(uint64_t offset) const = 0;
struct IReadStream : nod::IReadStream {
virtual uint64_t copyToDisc(struct IPartWriteStream& discio, uint64_t length) = 0;
};
virtual std::unique_ptr<IReadStream> beginReadStream() const = 0;
virtual std::unique_ptr<IReadStream> beginReadStream(uint64_t offset) const = 0;
};
std::unique_ptr<IFileIO> NewFileIO(SystemStringView path, int64_t maxWriteSize = -1);
} // namespace nod
| 30.958333 | 109 | 0.631225 | MeriKatt |
3a9b949a19b0a3b27a2ae6c287d8caa4d4e2a04d | 633 | cpp | C++ | tests/101-150/test_problem106.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | 1 | 2019-12-25T10:17:15.000Z | 2019-12-25T10:17:15.000Z | tests/101-150/test_problem106.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | null | null | null | tests/101-150/test_problem106.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | null | null | null | //
// Created by Alex Beccaro on 03/12/18.
//
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "../../src/problems/101-150/106/problem106.hpp"
BOOST_AUTO_TEST_SUITE( Problem106 )
BOOST_AUTO_TEST_CASE( Example1 ) {
auto res = problems::problem106::solve(4);
BOOST_CHECK_EQUAL(res, 1);
}
BOOST_AUTO_TEST_CASE( Example2 ) {
auto res = problems::problem106::solve(7);
BOOST_CHECK_EQUAL(res, 70);
}
BOOST_AUTO_TEST_CASE( Solution ) {
auto res = problems::problem106::solve();
BOOST_CHECK_EQUAL(res, 21384);
}
BOOST_AUTO_TEST_SUITE_END() | 24.346154 | 56 | 0.665087 | abeccaro |
3a9ba823687c515f5d6f983ecc6e237fcc37bf80 | 5,030 | cpp | C++ | lib/tw/authenticator.cpp | frolv/lynxbot | e9c2e9ba23eca8918d69215850bd094488b9a33a | [
"MIT"
] | 3 | 2016-07-12T21:42:09.000Z | 2016-08-31T05:49:40.000Z | lib/tw/authenticator.cpp | frolv/osrs-twitch-bot | e9c2e9ba23eca8918d69215850bd094488b9a33a | [
"MIT"
] | null | null | null | lib/tw/authenticator.cpp | frolv/osrs-twitch-bot | e9c2e9ba23eca8918d69215850bd094488b9a33a | [
"MIT"
] | 1 | 2016-05-26T14:59:11.000Z | 2016-05-26T14:59:11.000Z | #include <algorithm>
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
#include <openssl/hmac.h>
#include <tw/authenticator.h>
#include <tw/base64.h>
#include <tw/oauth.h>
#include <utils.h>
static const char *INSTRUCTIONS = "In order to allow LynxBot to use your "
"Twitter account, you must register it as a Twitter app. This is done by "
"signing into https://apps.twitter.com and clicking the \"Create New App\" "
"button. Give your app a unique name (e.g. lynxbot-TWITTERNAME), fill in the "
"rest of the form and agree to the Developer Agreement.\n\nOnce you submit the "
"form you will be redirected to your app's overview page. You can change the "
"access level to read only (LynxBot does not do any writing).\nNext, click the "
"Keys and Access Tokens tab. Under \"Your Access Token\", click Create my "
"access token to generate access tokens for LynxBot.\n\nYou will now see four "
"tokens on the page:\nConsumer Key\nConsumer Secret\nAccess Token\nAccess "
"Token Secret\nYou will need to enter them into this console.\n\nWARNING: "
"Your access tokens will be stored in plaintext.\n";
static void get_str(std::string &target);
tw::Authenticator::Authenticator()
{
configpath = utils::configdir() + utils::config("twitter");
if (read_keys() == -1)
interactive_setup();
}
/* siggen: generate an oauth signature for a twitter api request */
void tw::Authenticator::siggen(const std::string &method, const std::string &URL,
const param_vec &head_params, const param_vec &body_params)
{
size_t i;
std::vector<std::string> enc_params;
std::string base_str, signing_key;
unsigned char digest[1024];
unsigned int digest_len;
/* get ouath data */
odata.c_key = consumerkey;
odata.nonce = noncegen();
odata.sig_method = "HMAC-SHA1";
odata.timestamp = std::to_string(time(nullptr));
odata.token = token;
odata.version = "1.0";
/* generate the base string */
for (auto p : head_params)
enc_params.push_back(pencode(p.first) + "=" + pencode(p.second));
for (auto p : body_params)
enc_params.push_back(pencode(p.first) + "=" + pencode(p.second));
enc_params.push_back("oauth_consumer_key=" + odata.c_key);
enc_params.push_back("oauth_nonce=" + odata.nonce);
enc_params.push_back("oauth_signature_method=" + odata.sig_method);
enc_params.push_back("oauth_timestamp=" + odata.timestamp);
enc_params.push_back("oauth_token=" + odata.token);
enc_params.push_back("oauth_version=" + odata.version);
std::sort(enc_params.begin(), enc_params.end());
std::string param_str;
for (i = 0; i < enc_params.size(); ++i) {
param_str += enc_params[i];
if (i != enc_params.size() - 1)
param_str += '&';
}
base_str += method + "&";
base_str += pencode(URL) + "&";
base_str += pencode(param_str);
/* get the signing key */
signing_key += pencode(consumersecret) + "&";
signing_key += pencode(tokensecret);
HMAC(EVP_sha1(), signing_key.c_str(), signing_key.length(),
(unsigned char *)base_str.c_str(), base_str.length(),
digest, &digest_len);
odata.sig = base64_enc((char *)digest, digest_len);
}
struct tw::Authenticator::oauth_data tw::Authenticator::auth_data()
{
return odata;
}
/* read_keys: read twitter keys from file (will be encrypted eventually) */
int tw::Authenticator::read_keys()
{
std::ifstream reader(configpath);
std::string line;
int lnum = 0;
if (!reader.is_open())
return -1;
while (std::getline(reader, line)) {
switch (++lnum) {
case 1:
consumerkey = line;
break;
case 2:
consumersecret = line;
break;
case 3:
token = line;
break;
case 4:
tokensecret = line;
break;
default:
return 1;
}
}
if (lnum != 4)
return 1;
return 0;
}
/* interactive_setup: obtain access tokens from user */
void tw::Authenticator::interactive_setup()
{
char c = '\0';
std::cout << configpath << " was not found." << std::endl;
std::cout << "Would you like to set up LynxBot to use Twitter? (y/n) ";
std::ofstream writer(configpath);
while (c != 'y' && c != 'n')
std::cin >> c;
if (c == 'n')
return;
std::cout << INSTRUCTIONS << std::endl;
std::cout << "Would you like to proceed? (y/n) ";
c = '\0';
while (c != 'y' && c != 'n')
std::cin >> c;
if (c == 'n')
return;
std::cout << "Enter your Consumer Key:" << std::endl;
get_str(consumerkey);
std::cout << "Enter your Consumer Secret:" << std::endl;
get_str(consumersecret);
std::cout << "Enter your Access Token:" << std::endl;
get_str(token);
std::cout << "Enter your Access Token Secret:" << std::endl;
get_str(tokensecret);
writer << consumerkey << std::endl << consumersecret << std::endl
<< token << std::endl << tokensecret << std::endl;
writer.close();
std::cout << "Your tokens have been saved to " << configpath
<< std::endl;
std::cin.get();
}
/* get_str: read a string from stdin */
static void get_str(std::string &target)
{
std::string line;
while (true) {
std::getline(std::cin, line);
if (!line.empty()) break;
std::cout << "Invalid string, try again:" << std::endl;
}
target = line;
}
| 28.418079 | 81 | 0.677932 | frolv |
3a9e726e49ad4e7c4d31553e219b2c382afc11ff | 9,414 | cc | C++ | src/db_logger.cc | sunnyxhuang/2D-Placement | 53310fa7336430a1b82b3ed3fa98409ab5d4b7d5 | [
"Apache-2.0"
] | 4 | 2017-09-01T14:43:01.000Z | 2017-09-02T04:58:55.000Z | src/db_logger.cc | little-by/2D-Placement | 53310fa7336430a1b82b3ed3fa98409ab5d4b7d5 | [
"Apache-2.0"
] | null | null | null | src/db_logger.cc | little-by/2D-Placement | 53310fa7336430a1b82b3ed3fa98409ab5d4b7d5 | [
"Apache-2.0"
] | 3 | 2017-09-21T08:24:51.000Z | 2018-10-30T04:46:15.000Z | #include <unistd.h>
#include "db_logger.h"
#include "util.h"
// static
bool DbLogger::LOG_FLOW_INFO_ = false;
bool DbLogger::Connect() {
//
return true;
}
DbLogger::DbLogger(string table_subfix) : table_subfix_(table_subfix) {
if (!Connect()) {
exit(-1);
}
has_init_coflow_info_table_ = false;
if (LOG_FLOW_INFO_) InitFlowInfoTable();
}
DbLogger::~DbLogger() {
// flush all data to database if needed
}
string DbLogger::GetTableName(string tabel_type) {
return tabel_type + (table_subfix_ == "" ? "" : "_" + table_subfix_);
}
bool DbLogger::DropIfExist(string table_type) {
if (!Connect()) {
return false;
}
string table_name = GetTableName(table_type);
// sql to drop table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// query << "drop table if exists " << table_name;
// if (!query.exec()) {
// cerr << query.str() << endl;
// cerr << query.error() << endl;
// return false;
// }
// cout << "Dropped table " << table_name << endl;
return true;
}
void DbLogger::InitCoflowInfoTable() {
if (has_init_coflow_info_table_) return;
if (!DropIfExist("CoflowInfo")) return;
string table_name = GetTableName("CoflowInfo");
// sql to write table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// query << "CREATE TABLE `" << table_name << "` (\n"
// << " `job_id` INT(11) NOT NULL,\n"
// << " `insert_ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n"
// << " `*cast` VARCHAR(5) DEFAULT NULL,\n"
// << " `bin` VARCHAR(5) DEFAULT NULL,\n"
// << " `map` SMALLINT DEFAULT NULL,\n"
// << " `red` SMALLINT DEFAULT NULL,\n"
// << " `flow#` INT DEFAULT NULL,\n"
// << " `map_loc` VARCHAR(500) DEFAULT NULL,\n"
// << " `red_loc` VARCHAR(500) DEFAULT NULL,\n"
// << " `bn_load_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `lb_optc` DOUBLE DEFAULT NULL,\n"
// << " `lb_elec` DOUBLE DEFAULT NULL,\n"
// << " `lb_elec_bit` BIGINT DEFAULT NULL,\n"
// << " `ttl_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `avg_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `min_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `max_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `tArr` DOUBLE DEFAULT NULL,\n"
// << " `tFin` DOUBLE DEFAULT NULL,\n"
// << " `cct` DOUBLE DEFAULT NULL,\n"
// << " `r_optc` DOUBLE DEFAULT NULL,\n"
// << " `r_elec` DOUBLE DEFAULT NULL,\n"
// << " PRIMARY KEY (`job_id`)\n"
// << ");";
// cout << "Created table " << table_name << endl;
has_init_coflow_info_table_ = true;
}
void DbLogger::WriteCoflowFeatures(Coflow *coflow) {
if (!Connect()) return;
if (!has_init_coflow_info_table_) InitCoflowInfoTable();
// read a coflow. start building up knowledge.
double total_flow_size_Gbit = 0.0;
double min_flow_size_Gbit = -1.0;
double max_flow_size_Gbit = -1.0;
const map<pair<int, int>, long> &mr_demand_byte = coflow->GetMRFlowBytes();
int flow_num = (int) coflow->GetFlows()->size();
for (Flow *flow : *(coflow->GetFlows())) {
double this_flow_size_Gbit = ((double) flow->GetSizeInBit() / 1e9);
total_flow_size_Gbit += this_flow_size_Gbit; // each flow >= 1MB
if (min_flow_size_Gbit > this_flow_size_Gbit || min_flow_size_Gbit < 0) {
min_flow_size_Gbit = this_flow_size_Gbit;
}
if (max_flow_size_Gbit < this_flow_size_Gbit || max_flow_size_Gbit < 0) {
max_flow_size_Gbit = this_flow_size_Gbit;
}
}
double avg_flow_size_Gbit = total_flow_size_Gbit / (double) flow_num;
string cast_pattern = "";
int map = coflow->GetNumMap();
int red = coflow->GetNumRed();
if (map == 1 && red == 1) {
cast_pattern = "1"; // single-flow
} else if (map > 1 && red == 1) {
cast_pattern = "m21"; // incast
} else if (map == 1 && red > 1) {
cast_pattern = "12m"; // one sender, multiple receiver.
} else if (map > 1 && red > 1) {
cast_pattern = "m2m"; // many-to-many
}
string bin;
// double lb_elec_MB = lb_elec / (double) 8.0/ 1000000;
bin += (avg_flow_size_Gbit / 8.0 * 1e3 < 5.0) ?
'S' : 'L'; // short if avg flow size < 5MB, long other wise
bin += (flow_num <= 50) ? 'N' : 'W';// narrow if max flow# <= 50
string table_name = GetTableName("CoflowInfo");
// sql to write table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// use INSERT and UPDATE so that part of the info written may stay.
// query << "INSERT INTO " << table_name << " "
// << "(`job_id`, `*cast`, `bin`, `map`, `red`, `flow#`, "
// << "`map_loc`, `red_loc`, "
// << "`bn_load_Gbit`, `lb_optc`, `lb_elec`, `lb_elec_bit`, "
// << "`ttl_Gbit`, `avg_Gbit`, `min_Gbit`, `max_Gbit`) VALUES ("
// << coflow->GetJobId() << ','
// << "'" << cast_pattern << "'" << ','
// << "'" << bin << "'" << ','
// << map << ','
// << red << ','
// << flow_num << ','
// << "'" << Join(coflow->GetMapperLocations(), '_') << "'" << ','
// << "'" << Join(coflow->GetReducerLocations(), '_') << "'" << ','
// << coflow->GetMaxMapRedLoadGb() << ',' // bn_load_GB
// << coflow->GetMaxOptimalWorkSpanInSeconds() << ',' // lb_optc
// << coflow->GetMaxPortLoadInSec() << ',' // lb_elec
// << coflow->GetMaxPortLoadInBits() << ',' // lb_elec_bit
// << total_flow_size_Gbit << ','
// << avg_flow_size_Gbit << ','
// << min_flow_size_Gbit << ','
// << max_flow_size_Gbit << ") "
// << "ON DUPLICATE KEY UPDATE "
// << "`*cast`= values (`*cast`), "
// << "`bin`= values (`bin`), "
// << "`map`= values (`map`), "
// << "`red`= values (`red`), "
// << "`flow#`= values (`flow#`), "
// << "`map_loc`= values (`map_loc`), "
// << "`red_loc`= values (`red_loc`), "
// << "`lb_optc`= values (`lb_optc`), "
// << "`lb_elec`= values (`lb_elec`), "
// << "`lb_elec_bit`= values (`lb_elec_bit`), "
// << "`ttl_Gbit`= values (`ttl_Gbit`), "
// << "`avg_Gbit`= values (`avg_Gbit`), "
// << "`min_Gbit`= values (`min_Gbit`), "
// << "`max_Gbit`= values (`max_Gbit`); ";
}
void DbLogger::WriteOnCoflowFinish(double finish_time,
Coflow *coflow) {
if (!has_init_coflow_info_table_) InitCoflowInfoTable();
double cct = (finish_time - coflow->GetStartTime());
double optc_lb = coflow->GetMaxOptimalWorkSpanInSeconds();
double elec_lb = coflow->GetMaxPortLoadInSeconds();
double cct_over_optc = cct / optc_lb;
double cct_over_elec = cct / elec_lb;
string table_name = GetTableName("CoflowInfo");
// sql to write table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// use INSERT and UPDATE so that part of the info written may stay.
// query << "INSERT INTO " << table_name << " "
// << "(`job_id`, `tArr`, `tFin`, `cct`, `r_optc`, `r_elec`) VALUES ("
// << coflow->GetJobId() << ','
// << coflow->GetStartTime() << ','
// << finish_time << ','
// << (cct > 0 ? to_string(cct) : "null") << ','
// << (optc_lb > 0 ? to_string(cct_over_optc) : "null") << ','
// << (optc_lb > 0 ? to_string(cct_over_elec) : "null") << ") "
// << "ON DUPLICATE KEY UPDATE "
// << "`tArr`= values (`tArr`), "
// << "`tFin`= values (`tFin`), "
// << "`cct`= values (`cct`), "
// << "`r_optc`= values (`r_optc`), "
// << "`r_elec`= values (`r_elec`); ";
}
void DbLogger::InitFlowInfoTable() {
if (!DropIfExist("FlowInfo")) return;
string table_name = GetTableName("FlowInfo");
// table schema
// query << "CREATE TABLE `" << table_name << "` (\n"
// << " `job_id` INT(11) NOT NULL,\n"
// << " `flow_id` INT(11) NOT NULL,\n"
// << " `insert_ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n"
// << " `src` smallint NOT NULL,\n"
// << " `dst` smallint NOT NULL,\n"
// << " `flow_size_bit` BIGINT DEFAULT NULL,\n"
// << " `tArr` DOUBLE DEFAULT NULL,\n"
// << " `tFin` DOUBLE DEFAULT NULL,\n"
// << " `fct` DOUBLE DEFAULT NULL,\n"
// << " PRIMARY KEY (`flow_id`)\n"
// << ");";
// cout << "Created table " << table_name << endl;
}
void DbLogger::WriteOnFlowFinish(double finish_time, Flow *flow) {
if (!LOG_FLOW_INFO_) return;
double fct = (finish_time - flow->GetStartTime());
string table_name = GetTableName("FlowInfo");
// sql to write table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// always use INSERT as there is appending.
// query << "INSERT INTO " << table_name << " "
// << "(`job_id`, `flow_id`, `src` ,`dst`, `flow_size_bit`, "
// << "`tArr`, `tFin`, `fct`) VALUES ("
// << flow->GetParentCoflow()->GetJobId() << ','
// << flow->GetFlowId() << ','
// << flow->GetSrc() << ','
// << flow->GetDest() << ','
// << flow->GetSizeInBit() << ','
// << flow->GetStartTime() << ','
// << finish_time << ','
// << fct << ");";
} | 41.10917 | 81 | 0.533142 | sunnyxhuang |
3aa08ecdc21572485cd6784378357e823e2fc9a4 | 3,206 | cpp | C++ | Helper/Source/HelperApp.cpp | williamih/asset-pipeline | 077a50442e780f72c238c22d1eec8ab1b99e72f7 | [
"BSD-3-Clause"
] | null | null | null | Helper/Source/HelperApp.cpp | williamih/asset-pipeline | 077a50442e780f72c238c22d1eec8ab1b99e72f7 | [
"BSD-3-Clause"
] | null | null | null | Helper/Source/HelperApp.cpp | williamih/asset-pipeline | 077a50442e780f72c238c22d1eec8ab1b99e72f7 | [
"BSD-3-Clause"
] | null | null | null | #include "HelperApp.h"
#include <vector>
#include <QApplication>
#include <QHostAddress>
#include <Core/Macros.h>
HelperApp::HelperApp(u16 port, QObject* parent)
: QObject(parent)
, m_menu()
, m_tcpSocket()
, m_socketReadData()
, m_dbConn()
, m_projectsWindow(m_dbConn)
, m_errorsWindow(m_dbConn)
, m_aboutWindow()
, m_callbackQueue()
{
QHostAddress address(QHostAddress::LocalHost);
m_tcpSocket.connectToHost(address, port);
connect(&m_tcpSocket, &QTcpSocket::readyRead,
this, &HelperApp::SocketReadyForRead);
connect(&m_tcpSocket, &QTcpSocket::bytesWritten,
this, &HelperApp::OnBytesWritten);
QAction* aboutAction = m_menu.addAction("About Asset Pipeline");
aboutAction->setMenuRole(QAction::AboutRole);
connect(aboutAction, &QAction::triggered, this, &HelperApp::ShowAboutWindow);
QAction* quitAction = m_menu.addAction("Quit Asset Pipeline");
quitAction->setMenuRole(QAction::QuitRole);
quitAction->setShortcut(QKeySequence::Quit);
connect(quitAction, &QAction::triggered, [=] {
SendIPCMessage(IPCHELPERTOAPP_QUIT);
RegisterOnBytesSent([](size_t bytes) {
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
});
});
m_tcpSocket.waitForConnected();
}
HelperApp::~HelperApp()
{}
void HelperApp::ShowAboutWindow()
{
m_aboutWindow.show();
}
void HelperApp::SocketReadyForRead()
{
qint64 bytesAvailable = m_tcpSocket.bytesAvailable();
m_socketReadData.resize((size_t)bytesAvailable);
m_tcpSocket.read((char*)&m_socketReadData[0],
(qint64)m_socketReadData.size());
for (size_t i = 0; i < m_socketReadData.size(); ++i) {
ReceiveByte(m_socketReadData[i]);
}
}
void HelperApp::ReceiveByte(u8 byte)
{
IPCAppToHelperAction action = (IPCAppToHelperAction)byte;
switch (action) {
case IPCAPPTOHELPER_SHOW_PROJECTS_WINDOW:
m_projectsWindow.show();
break;
case IPCAPPTOHELPER_SHOW_ERRORS_WINDOW:
m_errorsWindow.show();
break;
case IPCAPPTOHELPER_SHOW_ABOUT_WINDOW:
ShowAboutWindow();
break;
case IPCAPPTOHELPER_REFRESH_ERRORS:
// Only actually reload if the window is visible (this is a
// performance optimization). If the window becomes visible after
// this, it will reload the data anyway.
if (m_errorsWindow.isVisible())
m_errorsWindow.ReloadErrors();
break;
case IPCAPPTOHELPER_QUIT:
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
break;
}
}
void HelperApp::SendIPCMessage(IPCHelperToAppAction action)
{
if ((u32)action > 0xFF)
FATAL("Size of message exceeded one byte");
u8 byte = (u8)action;
m_tcpSocket.write((const char*)&byte, 1);
}
void HelperApp::RegisterOnBytesSent(const BytesSentFunc& func)
{
m_callbackQueue.push_back(func);
}
void HelperApp::OnBytesWritten(qint64 bytes)
{
for (size_t i = 0; i < m_callbackQueue.size(); ++i) {
m_callbackQueue[i]((size_t)bytes);
}
m_callbackQueue.clear();
}
| 29.412844 | 81 | 0.66126 | williamih |
3aa1a076d877d5556c3738d2229ea097eaef5a92 | 3,094 | cc | C++ | src/parameters_parser.cc | krackers/kakoune | 7672387738ae1a2f38b843fe4b490a6ad882d94f | [
"Unlicense"
] | 10 | 2018-03-22T09:39:19.000Z | 2021-02-17T19:24:19.000Z | src/parameters_parser.cc | krackers/kakoune | 7672387738ae1a2f38b843fe4b490a6ad882d94f | [
"Unlicense"
] | null | null | null | src/parameters_parser.cc | krackers/kakoune | 7672387738ae1a2f38b843fe4b490a6ad882d94f | [
"Unlicense"
] | null | null | null | #include "parameters_parser.hh"
#include "flags.hh"
namespace Kakoune
{
String generate_switches_doc(const SwitchMap& switches)
{
String res;
if (switches.empty())
return res;
auto switch_len = [](auto& sw) { return sw.key.column_length() + (sw.value.takes_arg ? 5 : 0); };
auto switches_len = switches | transform(switch_len);
const ColumnCount maxlen = *std::max_element(switches_len.begin(), switches_len.end());
for (auto& sw : switches) {
res += format("-{} {}{}{}\n",
sw.key,
sw.value.takes_arg ? "<arg>" : "",
String{' ', maxlen - switch_len(sw) + 1},
sw.value.description);
}
return res;
}
ParametersParser::ParametersParser(ParameterList params, const ParameterDesc& desc)
: m_params(params),
m_desc(desc)
{
const bool switches_only_at_start = desc.flags & ParameterDesc::Flags::SwitchesOnlyAtStart;
const bool ignore_unknown_switches = desc.flags & ParameterDesc::Flags::IgnoreUnknownSwitches;
bool only_pos = desc.flags & ParameterDesc::Flags::SwitchesAsPositional;
Vector<bool> switch_seen(desc.switches.size(), false);
for (size_t i = 0; i < params.size(); ++i)
{
if (not only_pos and not ignore_unknown_switches and params[i] == "--")
only_pos = true;
else if (not only_pos and not params[i].empty() and params[i][0_byte] == '-')
{
auto it = m_desc.switches.find(params[i].substr(1_byte));
if (it == m_desc.switches.end())
{
if (ignore_unknown_switches)
{
m_positional_indices.push_back(i);
if (switches_only_at_start)
only_pos = true;
continue;
}
throw unknown_option(params[i]);
}
auto switch_index = it - m_desc.switches.begin();
if (switch_seen[switch_index])
throw runtime_error{format("switch '-{}' specified more than once", it->key)};
switch_seen[switch_index] = true;
if (it->value.takes_arg and ++i == params.size())
throw missing_option_value(it->key);
}
else // positional
{
if (switches_only_at_start)
only_pos = true;
m_positional_indices.push_back(i);
}
}
size_t count = m_positional_indices.size();
if (count > desc.max_positionals or count < desc.min_positionals)
throw wrong_argument_count();
}
Optional<StringView> ParametersParser::get_switch(StringView name) const
{
auto it = m_desc.switches.find(name);
kak_assert(it != m_desc.switches.end());
for (size_t i = 0; i < m_params.size(); ++i)
{
const auto& param = m_params[i];
if (param.substr(0_byte, 1_byte) == "-" and param.substr(1_byte) == name)
return it->value.takes_arg ? m_params[i+1] : StringView{};
if (param == "--")
break;
}
return {};
}
}
| 33.268817 | 101 | 0.572721 | krackers |
3aa1eb9ba9ba7eae43f867c0b1bfacbd702d6d77 | 500 | cpp | C++ | Control Work 2021.11.15/Project4/Source.cpp | ElitProffi/HW2021-2022 | 375abed060ad5a79e6486af0af367725294730d8 | [
"Apache-2.0"
] | null | null | null | Control Work 2021.11.15/Project4/Source.cpp | ElitProffi/HW2021-2022 | 375abed060ad5a79e6486af0af367725294730d8 | [
"Apache-2.0"
] | null | null | null | Control Work 2021.11.15/Project4/Source.cpp | ElitProffi/HW2021-2022 | 375abed060ad5a79e6486af0af367725294730d8 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int n = 0;
cin >> n;
int* o = new int[n] {0};
for (int i = 0; i < n; ++i)
{
cin >> o[i];
}
int max = o[0];
int min = o[0];
for (int i = 0; i < n; ++i)
{
if (o[i] < min)
{
min = o[i];
}
if (o[i] > max)
{
max = o[i];
}
}
for (int i = 0; i < n; ++i)
{
if (o[i] == max)
{
o[i] = min;
}
}
for (int i = 0; i < n; ++i)
{
cout << o[i] << " ";
}
delete[] o;
return EXIT_SUCCESS;
} | 11.904762 | 32 | 0.414 | ElitProffi |
3aa2208960d7e1d9b1ef35c8b5979e8090a2c3d9 | 2,961 | cpp | C++ | turnpike/src/SED.cpp | shuai-huang/turnpike-beltway | 20b68a48b68c2daad02346b1c076c0dce99c4431 | [
"Apache-2.0"
] | null | null | null | turnpike/src/SED.cpp | shuai-huang/turnpike-beltway | 20b68a48b68c2daad02346b1c076c0dce99c4431 | [
"Apache-2.0"
] | null | null | null | turnpike/src/SED.cpp | shuai-huang/turnpike-beltway | 20b68a48b68c2daad02346b1c076c0dce99c4431 | [
"Apache-2.0"
] | 1 | 2020-01-06T17:17:17.000Z | 2020-01-06T17:17:17.000Z | #include "SED.h"
// Could remove the columns that are all zeros and speed up the computation
SED::SED(){}
void SED::ComputeObjFunMuti( vector<int> all_distance_block, VectorXd* smp_vec_muti, vector<double>* obj_seq_pt, int val_idx ) {
double obj_tmp = 0;
for (int i=0; i<all_distance_block.size(); i++) {
est_distribution[all_distance_block[i]] = ComputeEstDbt(smp_vec_muti, all_distance_block[i]);
obj_tmp += pow( est_distribution[all_distance_block[i]] - all_distribution[all_distance_block[i]] , 2);
}
(*obj_seq_pt)[val_idx] = obj_tmp;
}
double SED::ComputeObjFun(VectorXd smp_vec) {
vector<double> obj_seq(num_thread_assign, 0);
if (num_thread_assign>1) {
thread *multi_thread = new thread[num_thread_assign-1];
for (int i=0; i<num_thread_assign-1; i++) {
multi_thread[i] = thread(&SED::ComputeObjFunMuti, this, all_partition[i], &smp_vec, &obj_seq, i);
}
ComputeObjFunMuti( all_partition[num_thread_assign-1], &smp_vec, &obj_seq, num_thread-1);
for (int i=0; i<num_thread_assign-1; i++) {
multi_thread[i].join();
}
delete [] multi_thread;
} else {
ComputeObjFunMuti( all_partition[num_thread_assign-1], &smp_vec, &obj_seq, num_thread-1);
}
double obj = 0;
for (int i=0; i<num_thread_assign; i++) {
obj += obj_seq[i];
}
return obj;
}
void SED::ComputeGradientMuti( vector<int> all_distance_block, VectorXd* smp_vec_muti, VectorXd* smp_der_seq_pt, int val_idx ) {
VectorXd smp_der_seq_tmp = VectorXd::Zero(M);
for (int i=0; i<all_distance_block.size(); i++) {
double mut_factor = (2.0*( est_distribution[all_distance_block[i]] - all_distribution[all_distance_block[i]] ) );
ComputeEstProj(smp_vec_muti, smp_der_seq_pt, mut_factor, all_distance_block[i]);
}
}
VectorXd SED::ComputeGradient(VectorXd smp_vec) {
vector<VectorXd> smp_der_seq(num_thread_assign, VectorXd::Zero(M));
if (num_thread_assign>1) {
thread *multi_thread = new thread[num_thread_assign-1];
for (int i=0; i<num_thread_assign-1; i++) {
multi_thread[i] = thread(&SED::ComputeGradientMuti, this, all_partition[i], &smp_vec, &smp_der_seq[i], i);
}
ComputeGradientMuti( all_partition[num_thread_assign-1], &smp_vec, &smp_der_seq[num_thread_assign-1], num_thread_assign-1 );
for (int i=0; i<num_thread_assign-1; i++) {
multi_thread[i].join();
}
delete [] multi_thread;
} else {
ComputeGradientMuti( all_partition[num_thread_assign-1], &smp_vec, &smp_der_seq[num_thread_assign-1], num_thread_assign-1 );
}
VectorXd smp_der = VectorXd::Zero(M);
for (int i=0; i<num_thread_assign; i++) {
smp_der.noalias() += smp_der_seq[i];
}
return smp_der;
}
SED::~SED() {}
| 32.9 | 132 | 0.638973 | shuai-huang |
3aa833e12e577cec543cb98e218b4b660b0a1cd7 | 3,366 | cc | C++ | test/test_kjv.cc | yhirose/cpp-searchlib | dd9102bbf0f3a22e77a0bacb8ab2a510ce96890e | [
"MIT"
] | 15 | 2021-08-13T06:28:15.000Z | 2022-03-14T06:43:53.000Z | test/test_kjv.cc | yhirose/cpp-searchlib | dd9102bbf0f3a22e77a0bacb8ab2a510ce96890e | [
"MIT"
] | null | null | null | test/test_kjv.cc | yhirose/cpp-searchlib | dd9102bbf0f3a22e77a0bacb8ab2a510ce96890e | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <searchlib.h>
#include <filesystem>
#include <fstream>
#include "test_utils.h"
using namespace searchlib;
const auto KJV_PATH = "../../test/t_kjv.tsv";
auto normalizer = [](auto sv) { return unicode::to_lowercase(sv); };
static auto kjv_index() {
InMemoryInvertedIndex<TextRange> invidx;
InMemoryIndexer indexer(invidx, normalizer);
std::ifstream fs(KJV_PATH);
if (fs) {
std::string line;
while (std::getline(fs, line)) {
auto fields = split(line, '\t');
auto document_id = std::stoi(fields[0]);
const auto &s = fields[4];
indexer.index_document(document_id, UTF8PlainTextTokenizer(s));
}
}
return invidx;
}
TEST(KJVTest, SimpleTest) {
const auto &invidx = kjv_index();
{
auto expr = parse_query(invidx, normalizer, R"( apple )");
ASSERT_TRUE(expr);
auto postings = perform_search(invidx, *expr);
ASSERT_TRUE(postings);
ASSERT_EQ(8, postings->size());
auto term = U"apple";
EXPECT_EQ(8, invidx.df(term));
EXPECT_AP(0.411, tf_idf_score(invidx, *expr, *postings, 0));
EXPECT_AP(0.745, tf_idf_score(invidx, *expr, *postings, 1));
EXPECT_AP(0.852, tf_idf_score(invidx, *expr, *postings, 2));
EXPECT_AP(0.351, tf_idf_score(invidx, *expr, *postings, 3));
EXPECT_AP(0.341, tf_idf_score(invidx, *expr, *postings, 4));
EXPECT_AP(0.341, tf_idf_score(invidx, *expr, *postings, 5));
EXPECT_AP(0.298, tf_idf_score(invidx, *expr, *postings, 6));
EXPECT_AP(0.385, tf_idf_score(invidx, *expr, *postings, 7));
EXPECT_AP(0.660, bm25_score(invidx, *expr, *postings, 0));
EXPECT_AP(1.753, bm25_score(invidx, *expr, *postings, 1));
EXPECT_AP(2.146, bm25_score(invidx, *expr, *postings, 2));
EXPECT_AP(0.500, bm25_score(invidx, *expr, *postings, 3));
EXPECT_AP(0.475, bm25_score(invidx, *expr, *postings, 4));
EXPECT_AP(0.475, bm25_score(invidx, *expr, *postings, 5));
EXPECT_AP(0.374, bm25_score(invidx, *expr, *postings, 6));
EXPECT_AP(0.588, bm25_score(invidx, *expr, *postings, 7));
}
{
auto expr = parse_query(invidx, normalizer, R"( "apple tree" )");
ASSERT_TRUE(expr);
auto postings = perform_search(invidx, *expr);
ASSERT_TRUE(postings);
ASSERT_EQ(3, postings->size());
EXPECT_EQ(1, postings->search_hit_count(0));
EXPECT_EQ(1, postings->search_hit_count(1));
EXPECT_EQ(1, postings->search_hit_count(2));
EXPECT_EQ(2, term_count_score(invidx, *expr, *postings, 0));
EXPECT_EQ(2, term_count_score(invidx, *expr, *postings, 1));
EXPECT_EQ(5, term_count_score(invidx, *expr, *postings, 2));
EXPECT_AP(0.572, tf_idf_score(invidx, *expr, *postings, 0));
EXPECT_AP(0.556, tf_idf_score(invidx, *expr, *postings, 1));
EXPECT_AP(1.051, tf_idf_score(invidx, *expr, *postings, 2));
EXPECT_AP(0.817, bm25_score(invidx, *expr, *postings, 0));
EXPECT_AP(0.776, bm25_score(invidx, *expr, *postings, 1));
EXPECT_AP(1.285, bm25_score(invidx, *expr, *postings, 2));
}
}
TEST(KJVTest, UTF8DecodePerformance) {
// auto normalizer = [](const auto &str) {
// return unicode::to_lowercase(str);
// };
auto normalizer = to_lowercase;
std::ifstream fs(KJV_PATH);
std::string s;
while (std::getline(fs, s)) {
UTF8PlainTextTokenizer tokenizer(s);
tokenizer(normalizer, [&](auto &str, auto, auto) {});
}
}
| 31.754717 | 69 | 0.663102 | yhirose |
3aac997c8c7811035e9e2501c962c99e6a0f7bdf | 4,048 | cpp | C++ | server/src/lidar_controller.cpp | jenny5-robot/jenny5-html5-controller | b23ab10d6a0896cbf8d7c5728fa6fdb4b4327e9c | [
"MIT"
] | 1 | 2020-06-02T02:18:32.000Z | 2020-06-02T02:18:32.000Z | server/src/lidar_controller.cpp | jenny5-robot/jenny5-html5 | b23ab10d6a0896cbf8d7c5728fa6fdb4b4327e9c | [
"MIT"
] | null | null | null | server/src/lidar_controller.cpp | jenny5-robot/jenny5-html5 | b23ab10d6a0896cbf8d7c5728fa6fdb4b4327e9c | [
"MIT"
] | null | null | null | // Author: Mihai Oltean, https://mihaioltean.github.io, mihai.oltean@gmail.com
// More details: https://jenny5.org, https://jenny5-robot.github.io/
// Source code: github.com/jenny5-robot
// License: MIT
// ---------------------------------------------------------------------------
#include "lidar_controller.h"
#include "jenny5_defs.h"
t_lidar_controller LIDAR_controller;
//----------------------------------------------------------------
t_lidar_controller::t_lidar_controller(void)
{
}
//----------------------------------------------------------------
int t_lidar_controller::connect(const char* port)
{
//-------------- START INITIALIZATION ------------------------------
if (!arduino_controller.connect(port, 115200)) { // real number - 1
//sprintf(error_string, "Error attaching to Jenny 5' LIDAR!\n");
return CANNOT_CONNECT_TO_JENNY5_LIDAR_ERROR;
}
// now wait to see if I have been connected
// wait for no more than 3 seconds. If it takes more it means that something is not right, so we have to abandon it
clock_t start_time = clock();
bool LIDAR_responded = false;
while (1) {
if (!arduino_controller.update_commands_from_serial())
Sleep(5); // no new data from serial ... we make a little pause so that we don't kill the processor
if (!LIDAR_responded)
if (arduino_controller.query_for_event(IS_ALIVE_EVENT)) { // have we received the event from Serial ?
LIDAR_responded = true;
break;
}
// measure the passed time
clock_t end_time = clock();
double wait_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
// if more than 3 seconds then game over
if (wait_time > NUM_SECONDS_TO_WAIT_FOR_CONNECTION) {
if (!LIDAR_responded)
return LIDAR_does_not_respond_ERROR;
}
}
return E_OK;
}
//----------------------------------------------------------------
bool t_lidar_controller::setup(char* error_string)
{
arduino_controller.send_create_LiDAR(8, 9, 10, 12);// dir, step, enable, IR_pin
clock_t start_time = clock();
bool lidar_controller_created = false;
while (1) {
if (!arduino_controller.update_commands_from_serial())
Sleep(5); // no new data from serial ... we make a little pause so that we don't kill the processor
if (!lidar_controller_created)
if (arduino_controller.query_for_event(LIDAR_CONTROLLER_CREATED_EVENT)) // have we received the event from Serial ?
lidar_controller_created = true;
if (lidar_controller_created)
break;
// measure the passed time
clock_t end_time = clock();
double wait_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
// if more than 3 seconds then game over
if (wait_time > NUM_SECONDS_TO_WAIT_FOR_CONNECTION) {
if (!lidar_controller_created)
sprintf(error_string, "Cannot create LIDAR controller! Game over!\n");
return false;
}
}
return true;
}
//----------------------------------------------------------------
bool t_lidar_controller::update_data(void)
{
int motor_position;
intptr_t distance;
bool at_least_one_new_LIDAR_distance = false;
while (arduino_controller.query_for_event(LIDAR_READ_EVENT, &motor_position, &distance)) { // have we received the event from Serial ?
lidar_distances[motor_position] = int(distance);
at_least_one_new_LIDAR_distance = true;
}
return at_least_one_new_LIDAR_distance;
}
//----------------------------------------------------------------
void t_lidar_controller::disconnect(void)
{
arduino_controller.close_connection();
}
//----------------------------------------------------------------
bool t_lidar_controller::is_connected(void)
{
return arduino_controller.is_open();
}
//----------------------------------------------------------------
const char *t_lidar_controller::error_to_string(int error)
{
switch (error) {
case E_OK:
return "LIDAR PERFECT\n";
case CANNOT_CONNECT_TO_JENNY5_LIDAR_ERROR:
return CANNOT_CONNECT_TO_JENNY5_LIDAR_STR;
case LIDAR_does_not_respond_ERROR:
return LIDAR_does_not_respond_STR;
}
return NULL;
}
//---------------------------------------------------------------- | 32.126984 | 136 | 0.629447 | jenny5-robot |
3ab0a6b9c8ddbdd037e4722c75ea71ba10b1e211 | 11,113 | cpp | C++ | DT3Windows8/DeviceGraphicsDX11Shader.cpp | 9heart/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 3 | 2018-10-05T15:03:27.000Z | 2019-03-19T11:01:56.000Z | DT3Windows8/DeviceGraphicsDX11Shader.cpp | pakoito/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 1 | 2016-01-28T14:39:49.000Z | 2016-01-28T22:12:07.000Z | DT3Windows8/DeviceGraphicsDX11Shader.cpp | adderly/DT3 | e2605be091ec903d3582e182313837cbaf790857 | [
"MIT"
] | 3 | 2016-01-25T16:44:51.000Z | 2021-01-29T19:59:45.000Z | //==============================================================================
///
/// File: DeviceGraphicsDX11Shader.cpp
///
/// Copyright (C) 2000-2013 by Smells Like Donkey, Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DeviceGraphicsDX11Shader.hpp"
#include "DeviceGraphicsDX11Renderer.hpp"
#include "DeviceGraphicsDX11VertexShader.hpp"
#include "DeviceGraphicsDX11PixelShader.hpp"
#include "MoreMath.hpp"
#include "DeviceGlobalsManager.hpp"
#include "System.hpp"
#include "DeviceConsole.hpp"
#include "Factory.hpp"
#include "FilePath.hpp"
#include "ShaderResource.hpp"
#include "TextFileStream.hpp"
#include "DeviceFileManager.hpp"
#include "CheckedCast.hpp"
#include "StringCast.hpp"
#include "FragmentShaderResource.hpp"
#include "VertexShaderResource.hpp"
#include "GeometryShaderResource.hpp"
//==============================================================================
//==============================================================================
namespace DT2 {
//==============================================================================
/// Register with object factory
//==============================================================================
IMPLEMENT_FACTORY_CREATION(DeviceGraphicsDX11Shader)
//==============================================================================
/// Standard class constructors/destructors
//==============================================================================
DeviceGraphicsDX11Shader::DeviceGraphicsDX11Shader (void)
: _layout (NULL),
_pixel_shader (NULL),
_vertex_shader (NULL)
{
for (DTuint i = 0; i < ARRAY_SIZE(_constants); ++i) {
_constants[i] = NULL;
}
}
DeviceGraphicsDX11Shader::~DeviceGraphicsDX11Shader (void)
{
clear();
RELEASE(_pixel_shader);
RELEASE(_vertex_shader);
}
//==============================================================================
//==============================================================================
void DeviceGraphicsDX11Shader::clear(void)
{
SAFE_RELEASE(_layout);
for (DTuint i = 0; i < ARRAY_SIZE(_constants); ++i) {
SAFE_RELEASE(_constants[i]);
}
for (DTuint i = 0; i < _parameters.size(); ++i) {
SAFE_RELEASE(_parameters[i]);
}
_parameters.clear();
}
//==============================================================================
//==============================================================================
#define ADD_DESC(A,F) \
if (program->hasAttrib(A)) { \
String attrib_name = program->getAttribName(A); \
String index = attrib_name.endDigits(); \
name_buffer[desc_index] = attrib_name.trimEndDigits(); \
desc[desc_index].SemanticName = name_buffer[desc_index].cStr(); \
desc[desc_index].SemanticIndex = index.size() ? castFromString<DTint>(index) : 0; \
desc[desc_index].Format = F; \
desc[desc_index].InputSlot = A; \
desc[desc_index].AlignedByteOffset = 0; \
desc[desc_index].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; \
desc[desc_index].InstanceDataStepRate = 0; \
++desc_index; \
}
#define ADD_CONSTANT(A,S) \
if (!program->getUniformName(A).empty()) { \
String constant_name = program->getUniformName(A); \
DTint ps_resource_index = program->getFragmentShader() ? program->getFragmentShader()->getShaderResourceIndex (constant_name) : -1; \
DTint vs_resource_index = program->getVertexShader() ? program->getVertexShader()->getShaderResourceIndex (constant_name) : -1; \
\
D3D11_BUFFER_DESC desc; \
desc.ByteWidth = S; \
desc.MiscFlags = 0; \
desc.StructureByteStride = 0; \
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; \
desc.Usage = D3D11_USAGE_DYNAMIC; \
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; \
\
HRESULT hr = device->CreateBuffer(&desc, NULL, &_constants[A]); \
Assert(SUCCEEDED(hr)); \
\
if (vs_resource_index >= 0) _vs_constants[vs_resource_index] = _constants[A]; \
if (ps_resource_index >= 0) _ps_constants[ps_resource_index] = _constants[A]; \
}
void DeviceGraphicsDX11Shader::syncToResource (ShaderResource *program)
{
if (program->getRecacheData()) {
DeviceGraphicsDX11Renderer *renderer = checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer());
ID3D11Device1 *device = renderer->getD3D11Device();
ID3D11DeviceContext1 *context = renderer->getD3D11Context();
SAFE_ASSIGN(_pixel_shader, checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer())->getPixelShaderCached(program->getFragmentShader()));
SAFE_ASSIGN(_vertex_shader, checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer())->getVertexShaderCached(program->getVertexShader()));
if (!_pixel_shader || !_vertex_shader) { // Geometry shader is optional
program->setRecacheData(false);
return;
}
// Clear previous resources
clear();
HRESULT hr;
//
// Build a layout (Input element description)
//
D3D11_INPUT_ELEMENT_DESC desc[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
String name_buffer[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
::memset(desc,0,sizeof(desc));
DTuint desc_index = 0;
ADD_DESC(ShaderResource::ATTRIB_POSITION, DXGI_FORMAT_R32G32B32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_COLOR, DXGI_FORMAT_R8G8B8A8_UNORM);
ADD_DESC(ShaderResource::ATTRIB_NORMAL, DXGI_FORMAT_R32G32B32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_TEXCOORD0, DXGI_FORMAT_R32G32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_TEXCOORD1, DXGI_FORMAT_R32G32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_TEXCOORD2, DXGI_FORMAT_R32G32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_TEXCOORD3, DXGI_FORMAT_R32G32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_WEIGHTS_INDEX, DXGI_FORMAT_R16G16B16A16_UINT);
ADD_DESC(ShaderResource::ATTRIB_WEIGHTS_STRENGTH, DXGI_FORMAT_R32G32B32A32_FLOAT);
const String *bytecode = program->getVertexShader()->getShader("HLSL");
hr = device->CreateInputLayout(desc,desc_index,&(*bytecode)[0],bytecode->size(),&_layout);
Assert(SUCCEEDED(hr));
//
// Constants (Uniforms)
//
::memset(_constants,0,sizeof(_constants));
::memset(_vs_constants,0,sizeof(_vs_constants));
::memset(_ps_constants,0,sizeof(_ps_constants));
ADD_CONSTANT(ShaderResource::UNIFORM_COLOR, sizeof(float) * 4);
ADD_CONSTANT(ShaderResource::UNIFORM_TEXTURE0, sizeof(float) * 16);
ADD_CONSTANT(ShaderResource::UNIFORM_TEXTURE1, sizeof(float) * 16);
ADD_CONSTANT(ShaderResource::UNIFORM_MODELVIEW, sizeof(float) * 16);
ADD_CONSTANT(ShaderResource::UNIFORM_PROJECTION, sizeof(float) * 16);
ADD_CONSTANT(ShaderResource::UNIFORM_CAMERA, sizeof(float) * 16);
//ADD_CONSTANT(ShaderResource::UNIFORM_SKELETON,???);
const Array<ShaderResource::Parameter> ¶meters = program->getParameters();
_parameters.resize(parameters.size());
for (DTuint i = 0; i < parameters.size(); ++i) {
String constant_name = parameters[i].name;
DTint ps_resource_index = program->getFragmentShader() ? program->getFragmentShader()->getShaderResourceIndex (constant_name) : -1;
DTint vs_resource_index = program->getVertexShader() ? program->getVertexShader()->getShaderResourceIndex (constant_name) : -1;
D3D11_BUFFER_DESC desc;
desc.ByteWidth = parameters[i].data.size();
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
HRESULT hr = device->CreateBuffer(&desc, NULL, &_parameters[i]);
Assert(SUCCEEDED(hr));
if (vs_resource_index >= 0) _vs_constants[vs_resource_index] = _parameters[i];
if (ps_resource_index >= 0) _ps_constants[ps_resource_index] = _parameters[i];
}
program->setRecacheData(false);
}
// recache all of our parameters
if (program->getRecacheParameters()) {
DeviceGraphicsDX11Renderer *renderer = checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer());
ID3D11DeviceContext1 *context = renderer->getD3D11Context();
// Get Parameters. This creates a mapping from our internal index to an opengl uniform location
const Array<ShaderResource::Parameter> ¶meters = program->getParameters();
for (DTuint i = 0; i < parameters.size(); ++i) {
const ShaderResource::Parameter &p = parameters[i];
context->UpdateSubresource(_parameters[i], 0, NULL, ¶meters[0].data[0], parameters[i].data.size(), parameters[i].data.size());
}
program->setRecacheParameters(false);
}
}
//==============================================================================
//==============================================================================
void DeviceGraphicsDX11Shader::setConstantValue (ID3D11Buffer *buffer, DTubyte *data, DTuint size)
{
if (!buffer)
return;
DeviceGraphicsDX11Renderer *renderer = checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer());
ID3D11DeviceContext1 *context = renderer->getD3D11Context();
D3D11_MAPPED_SUBRESOURCE res;
HRESULT hr = context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &res);
::memcpy(res.pData,data,size);
context->Unmap(buffer, 0);
}
//==============================================================================
//==============================================================================
} // DT2
| 39.407801 | 154 | 0.541528 | 9heart |
3ab212d5c0c143d3fd822e31fe379b44bab6f909 | 1,162 | cpp | C++ | library/math/longestArithmeticSubsequence.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 40 | 2017-11-26T05:29:18.000Z | 2020-11-13T00:29:26.000Z | library/math/longestArithmeticSubsequence.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 101 | 2019-02-09T06:06:09.000Z | 2021-12-25T16:55:37.000Z | library/math/longestArithmeticSubsequence.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 6 | 2017-01-03T14:17:58.000Z | 2021-01-22T10:37:04.000Z | #include <vector>
#include <algorithm>
using namespace std;
#include "longestArithmeticSubsequence.h"
/////////// For Testing ///////////////////////////////////////////////////////
#include <time.h>
#include <cassert>
#include <string>
#include <iostream>
#include "../common/iostreamhelper.h"
void testLongestArithmeticSubsequence() {
//return; //TODO: if you want to test, make this line a comment.
cout << "--- Longest Arithmetic Subsequence -----------------------" << endl;
{
auto las1 = buildLongestArithmeticSubsequenceK(5, 2);
auto las1Len = lenghtOfLongestArithmeticSubsequence(las1);
cout << las1 << ", " << las1Len << endl;
assert(las1Len == 2);
auto las2 = buildLongestArithmeticSubsequenceK(5, 3);
auto las2Len = lenghtOfLongestArithmeticSubsequence(las2);
cout << las2 << ", " << las2Len << endl;
assert(las2Len == 3);
auto las3 = buildLongestArithmeticSubsequenceK(8, 2);
auto las3Len = lenghtOfLongestArithmeticSubsequence(las3);
cout << las3 << ", " << las3Len << endl;
assert(las3Len == 2);
}
cout << "OK!" << endl;
}
| 29.794872 | 81 | 0.589501 | bluedawnstar |
3ab3a9ccf58887f4ab68196cd4b1f5b8ba487aec | 294 | cpp | C++ | patterns/floyds_pattern.cpp | neerajsingh869/data-structures-and-algorithms | 96087e68fdce743f90f75228af1c7d111f6b92b7 | [
"MIT"
] | null | null | null | patterns/floyds_pattern.cpp | neerajsingh869/data-structures-and-algorithms | 96087e68fdce743f90f75228af1c7d111f6b92b7 | [
"MIT"
] | null | null | null | patterns/floyds_pattern.cpp | neerajsingh869/data-structures-and-algorithms | 96087e68fdce743f90f75228af1c7d111f6b92b7 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main(){
// Floyd's Pattern
int n;
cin>>n;
int count = 0;
for(int i=1; i<=n; i++){
for(int j=1; j<=i; j++){
cout<<count+1<<" ";
count = count + 1;
}
cout<<endl;
}
return 0;
} | 17.294118 | 32 | 0.431973 | neerajsingh869 |
3ab45abf91c927889ac85ae800ae6cf75c6e1dd8 | 124,497 | cpp | C++ | Source/WebKit/UIProcess/API/glib/WebKitSettings.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | Source/WebKit/UIProcess/API/glib/WebKitSettings.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/WebKit/UIProcess/API/glib/WebKitSettings.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2011 Motorola Mobility, 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 Motorola Mobility, 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 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 "config.h"
#include "WebKitSettings.h"
#include "WebKitEnumTypes.h"
#include "WebKitSettingsPrivate.h"
#include "WebPageProxy.h"
#include "WebPreferences.h"
#include <WebCore/UserAgent.h>
#include <glib/gi18n-lib.h>
#include <wtf/glib/WTFGType.h>
#include <wtf/text/CString.h>
#if PLATFORM(GTK)
#include "HardwareAccelerationManager.h"
#endif
#if PLATFORM(WAYLAND)
#include <WebCore/PlatformDisplay.h>
#endif
using namespace WebKit;
struct _WebKitSettingsPrivate {
_WebKitSettingsPrivate()
: preferences(WebPreferences::create(String(), "WebKit2.", "WebKit2."))
{
defaultFontFamily = preferences->standardFontFamily().utf8();
monospaceFontFamily = preferences->fixedFontFamily().utf8();
serifFontFamily = preferences->serifFontFamily().utf8();
sansSerifFontFamily = preferences->sansSerifFontFamily().utf8();
cursiveFontFamily = preferences->cursiveFontFamily().utf8();
fantasyFontFamily = preferences->fantasyFontFamily().utf8();
pictographFontFamily = preferences->pictographFontFamily().utf8();
defaultCharset = preferences->defaultTextEncodingName().utf8();
}
RefPtr<WebPreferences> preferences;
CString defaultFontFamily;
CString monospaceFontFamily;
CString serifFontFamily;
CString sansSerifFontFamily;
CString cursiveFontFamily;
CString fantasyFontFamily;
CString pictographFontFamily;
CString defaultCharset;
CString userAgent;
bool allowModalDialogs { false };
bool zoomTextOnly { false };
};
/**
* SECTION:WebKitSettings
* @short_description: Control the behaviour of a #WebKitWebView
*
* #WebKitSettings can be applied to a #WebKitWebView to control text charset,
* color, font sizes, printing mode, script support, loading of images and various
* other things on a #WebKitWebView. After creation, a #WebKitSettings object
* contains default settings.
*
* <informalexample><programlisting>
* /<!-- -->* Disable JavaScript. *<!-- -->/
* WebKitSettings *settings = webkit_web_view_group_get_settings (my_view_group);
* webkit_settings_set_enable_javascript (settings, FALSE);
*
* </programlisting></informalexample>
*/
WEBKIT_DEFINE_TYPE(WebKitSettings, webkit_settings, G_TYPE_OBJECT)
enum {
PROP_0,
PROP_ENABLE_JAVASCRIPT,
PROP_AUTO_LOAD_IMAGES,
PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING,
PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE,
PROP_ENABLE_HTML5_LOCAL_STORAGE,
PROP_ENABLE_HTML5_DATABASE,
PROP_ENABLE_XSS_AUDITOR,
PROP_ENABLE_FRAME_FLATTENING,
PROP_ENABLE_PLUGINS,
PROP_ENABLE_JAVA,
PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY,
PROP_ENABLE_HYPERLINK_AUDITING,
PROP_DEFAULT_FONT_FAMILY,
PROP_MONOSPACE_FONT_FAMILY,
PROP_SERIF_FONT_FAMILY,
PROP_SANS_SERIF_FONT_FAMILY,
PROP_CURSIVE_FONT_FAMILY,
PROP_FANTASY_FONT_FAMILY,
PROP_PICTOGRAPH_FONT_FAMILY,
PROP_DEFAULT_FONT_SIZE,
PROP_DEFAULT_MONOSPACE_FONT_SIZE,
PROP_MINIMUM_FONT_SIZE,
PROP_DEFAULT_CHARSET,
PROP_ENABLE_PRIVATE_BROWSING,
PROP_ENABLE_DEVELOPER_EXTRAS,
PROP_ENABLE_RESIZABLE_TEXT_AREAS,
PROP_ENABLE_TABS_TO_LINKS,
PROP_ENABLE_DNS_PREFETCHING,
PROP_ENABLE_CARET_BROWSING,
PROP_ENABLE_FULLSCREEN,
PROP_PRINT_BACKGROUNDS,
PROP_ENABLE_WEBAUDIO,
PROP_ENABLE_WEBGL,
PROP_ALLOW_MODAL_DIALOGS,
PROP_ZOOM_TEXT_ONLY,
PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD,
PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE,
PROP_MEDIA_PLAYBACK_ALLOWS_INLINE,
PROP_DRAW_COMPOSITING_INDICATORS,
PROP_ENABLE_SITE_SPECIFIC_QUIRKS,
PROP_ENABLE_PAGE_CACHE,
PROP_USER_AGENT,
PROP_ENABLE_SMOOTH_SCROLLING,
PROP_ENABLE_ACCELERATED_2D_CANVAS,
PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT,
PROP_ENABLE_MEDIA_STREAM,
PROP_ENABLE_SPATIAL_NAVIGATION,
PROP_ENABLE_MEDIASOURCE,
PROP_ALLOW_FILE_ACCESS_FROM_FILE_URLS,
PROP_ALLOW_UNIVERSAL_ACCESS_FROM_FILE_URLS,
#if PLATFORM(GTK)
PROP_HARDWARE_ACCELERATION_POLICY,
#endif
};
static void webKitSettingsConstructed(GObject* object)
{
G_OBJECT_CLASS(webkit_settings_parent_class)->constructed(object);
WebPreferences* prefs = WEBKIT_SETTINGS(object)->priv->preferences.get();
prefs->setShouldRespectImageOrientation(true);
}
static void webKitSettingsSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec)
{
WebKitSettings* settings = WEBKIT_SETTINGS(object);
switch (propId) {
case PROP_ENABLE_JAVASCRIPT:
webkit_settings_set_enable_javascript(settings, g_value_get_boolean(value));
break;
case PROP_AUTO_LOAD_IMAGES:
webkit_settings_set_auto_load_images(settings, g_value_get_boolean(value));
break;
case PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING:
webkit_settings_set_load_icons_ignoring_image_load_setting(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE:
webkit_settings_set_enable_offline_web_application_cache(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_HTML5_LOCAL_STORAGE:
webkit_settings_set_enable_html5_local_storage(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_HTML5_DATABASE:
webkit_settings_set_enable_html5_database(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_XSS_AUDITOR:
webkit_settings_set_enable_xss_auditor(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_FRAME_FLATTENING:
webkit_settings_set_enable_frame_flattening(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_PLUGINS:
webkit_settings_set_enable_plugins(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_JAVA:
webkit_settings_set_enable_java(settings, g_value_get_boolean(value));
break;
case PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY:
webkit_settings_set_javascript_can_open_windows_automatically(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_HYPERLINK_AUDITING:
webkit_settings_set_enable_hyperlink_auditing(settings, g_value_get_boolean(value));
break;
case PROP_DEFAULT_FONT_FAMILY:
webkit_settings_set_default_font_family(settings, g_value_get_string(value));
break;
case PROP_MONOSPACE_FONT_FAMILY:
webkit_settings_set_monospace_font_family(settings, g_value_get_string(value));
break;
case PROP_SERIF_FONT_FAMILY:
webkit_settings_set_serif_font_family(settings, g_value_get_string(value));
break;
case PROP_SANS_SERIF_FONT_FAMILY:
webkit_settings_set_sans_serif_font_family(settings, g_value_get_string(value));
break;
case PROP_CURSIVE_FONT_FAMILY:
webkit_settings_set_cursive_font_family(settings, g_value_get_string(value));
break;
case PROP_FANTASY_FONT_FAMILY:
webkit_settings_set_fantasy_font_family(settings, g_value_get_string(value));
break;
case PROP_PICTOGRAPH_FONT_FAMILY:
webkit_settings_set_pictograph_font_family(settings, g_value_get_string(value));
break;
case PROP_DEFAULT_FONT_SIZE:
webkit_settings_set_default_font_size(settings, g_value_get_uint(value));
break;
case PROP_DEFAULT_MONOSPACE_FONT_SIZE:
webkit_settings_set_default_monospace_font_size(settings, g_value_get_uint(value));
break;
case PROP_MINIMUM_FONT_SIZE:
webkit_settings_set_minimum_font_size(settings, g_value_get_uint(value));
break;
case PROP_DEFAULT_CHARSET:
webkit_settings_set_default_charset(settings, g_value_get_string(value));
break;
case PROP_ENABLE_PRIVATE_BROWSING:
G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
webkit_settings_set_enable_private_browsing(settings, g_value_get_boolean(value));
G_GNUC_END_IGNORE_DEPRECATIONS;
break;
case PROP_ENABLE_DEVELOPER_EXTRAS:
webkit_settings_set_enable_developer_extras(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_RESIZABLE_TEXT_AREAS:
webkit_settings_set_enable_resizable_text_areas(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_TABS_TO_LINKS:
webkit_settings_set_enable_tabs_to_links(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_DNS_PREFETCHING:
webkit_settings_set_enable_dns_prefetching(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_CARET_BROWSING:
webkit_settings_set_enable_caret_browsing(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_FULLSCREEN:
webkit_settings_set_enable_fullscreen(settings, g_value_get_boolean(value));
break;
case PROP_PRINT_BACKGROUNDS:
webkit_settings_set_print_backgrounds(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_WEBAUDIO:
webkit_settings_set_enable_webaudio(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_WEBGL:
webkit_settings_set_enable_webgl(settings, g_value_get_boolean(value));
break;
case PROP_ALLOW_MODAL_DIALOGS:
webkit_settings_set_allow_modal_dialogs(settings, g_value_get_boolean(value));
break;
case PROP_ZOOM_TEXT_ONLY:
webkit_settings_set_zoom_text_only(settings, g_value_get_boolean(value));
break;
case PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD:
webkit_settings_set_javascript_can_access_clipboard(settings, g_value_get_boolean(value));
break;
case PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE:
webkit_settings_set_media_playback_requires_user_gesture(settings, g_value_get_boolean(value));
break;
case PROP_MEDIA_PLAYBACK_ALLOWS_INLINE:
webkit_settings_set_media_playback_allows_inline(settings, g_value_get_boolean(value));
break;
case PROP_DRAW_COMPOSITING_INDICATORS:
if (g_value_get_boolean(value))
webkit_settings_set_draw_compositing_indicators(settings, g_value_get_boolean(value));
else {
char* debugVisualsEnvironment = getenv("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS");
bool showDebugVisuals = debugVisualsEnvironment && !strcmp(debugVisualsEnvironment, "1");
webkit_settings_set_draw_compositing_indicators(settings, showDebugVisuals);
}
break;
case PROP_ENABLE_SITE_SPECIFIC_QUIRKS:
webkit_settings_set_enable_site_specific_quirks(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_PAGE_CACHE:
webkit_settings_set_enable_page_cache(settings, g_value_get_boolean(value));
break;
case PROP_USER_AGENT:
webkit_settings_set_user_agent(settings, g_value_get_string(value));
break;
case PROP_ENABLE_SMOOTH_SCROLLING:
webkit_settings_set_enable_smooth_scrolling(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_ACCELERATED_2D_CANVAS:
webkit_settings_set_enable_accelerated_2d_canvas(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT:
webkit_settings_set_enable_write_console_messages_to_stdout(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_MEDIA_STREAM:
webkit_settings_set_enable_media_stream(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_SPATIAL_NAVIGATION:
webkit_settings_set_enable_spatial_navigation(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_MEDIASOURCE:
webkit_settings_set_enable_mediasource(settings, g_value_get_boolean(value));
break;
case PROP_ALLOW_FILE_ACCESS_FROM_FILE_URLS:
webkit_settings_set_allow_file_access_from_file_urls(settings, g_value_get_boolean(value));
break;
case PROP_ALLOW_UNIVERSAL_ACCESS_FROM_FILE_URLS:
webkit_settings_set_allow_universal_access_from_file_urls(settings, g_value_get_boolean(value));
break;
#if PLATFORM(GTK)
case PROP_HARDWARE_ACCELERATION_POLICY:
webkit_settings_set_hardware_acceleration_policy(settings, static_cast<WebKitHardwareAccelerationPolicy>(g_value_get_enum(value)));
break;
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec);
break;
}
}
static void webKitSettingsGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec)
{
WebKitSettings* settings = WEBKIT_SETTINGS(object);
switch (propId) {
case PROP_ENABLE_JAVASCRIPT:
g_value_set_boolean(value, webkit_settings_get_enable_javascript(settings));
break;
case PROP_AUTO_LOAD_IMAGES:
g_value_set_boolean(value, webkit_settings_get_auto_load_images(settings));
break;
case PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING:
g_value_set_boolean(value, webkit_settings_get_load_icons_ignoring_image_load_setting(settings));
break;
case PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE:
g_value_set_boolean(value, webkit_settings_get_enable_offline_web_application_cache(settings));
break;
case PROP_ENABLE_HTML5_LOCAL_STORAGE:
g_value_set_boolean(value, webkit_settings_get_enable_html5_local_storage(settings));
break;
case PROP_ENABLE_HTML5_DATABASE:
g_value_set_boolean(value, webkit_settings_get_enable_html5_database(settings));
break;
case PROP_ENABLE_XSS_AUDITOR:
g_value_set_boolean(value, webkit_settings_get_enable_xss_auditor(settings));
break;
case PROP_ENABLE_FRAME_FLATTENING:
g_value_set_boolean(value, webkit_settings_get_enable_frame_flattening(settings));
break;
case PROP_ENABLE_PLUGINS:
g_value_set_boolean(value, webkit_settings_get_enable_plugins(settings));
break;
case PROP_ENABLE_JAVA:
g_value_set_boolean(value, webkit_settings_get_enable_java(settings));
break;
case PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY:
g_value_set_boolean(value, webkit_settings_get_javascript_can_open_windows_automatically(settings));
break;
case PROP_ENABLE_HYPERLINK_AUDITING:
g_value_set_boolean(value, webkit_settings_get_enable_hyperlink_auditing(settings));
break;
case PROP_DEFAULT_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_default_font_family(settings));
break;
case PROP_MONOSPACE_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_monospace_font_family(settings));
break;
case PROP_SERIF_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_serif_font_family(settings));
break;
case PROP_SANS_SERIF_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_sans_serif_font_family(settings));
break;
case PROP_CURSIVE_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_cursive_font_family(settings));
break;
case PROP_FANTASY_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_fantasy_font_family(settings));
break;
case PROP_PICTOGRAPH_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_pictograph_font_family(settings));
break;
case PROP_DEFAULT_FONT_SIZE:
g_value_set_uint(value, webkit_settings_get_default_font_size(settings));
break;
case PROP_DEFAULT_MONOSPACE_FONT_SIZE:
g_value_set_uint(value, webkit_settings_get_default_monospace_font_size(settings));
break;
case PROP_MINIMUM_FONT_SIZE:
g_value_set_uint(value, webkit_settings_get_minimum_font_size(settings));
break;
case PROP_DEFAULT_CHARSET:
g_value_set_string(value, webkit_settings_get_default_charset(settings));
break;
case PROP_ENABLE_PRIVATE_BROWSING:
G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
g_value_set_boolean(value, webkit_settings_get_enable_private_browsing(settings));
G_GNUC_END_IGNORE_DEPRECATIONS;
break;
case PROP_ENABLE_DEVELOPER_EXTRAS:
g_value_set_boolean(value, webkit_settings_get_enable_developer_extras(settings));
break;
case PROP_ENABLE_RESIZABLE_TEXT_AREAS:
g_value_set_boolean(value, webkit_settings_get_enable_resizable_text_areas(settings));
break;
case PROP_ENABLE_TABS_TO_LINKS:
g_value_set_boolean(value, webkit_settings_get_enable_tabs_to_links(settings));
break;
case PROP_ENABLE_DNS_PREFETCHING:
g_value_set_boolean(value, webkit_settings_get_enable_dns_prefetching(settings));
break;
case PROP_ENABLE_CARET_BROWSING:
g_value_set_boolean(value, webkit_settings_get_enable_caret_browsing(settings));
break;
case PROP_ENABLE_FULLSCREEN:
g_value_set_boolean(value, webkit_settings_get_enable_fullscreen(settings));
break;
case PROP_PRINT_BACKGROUNDS:
g_value_set_boolean(value, webkit_settings_get_print_backgrounds(settings));
break;
case PROP_ENABLE_WEBAUDIO:
g_value_set_boolean(value, webkit_settings_get_enable_webaudio(settings));
break;
case PROP_ENABLE_WEBGL:
g_value_set_boolean(value, webkit_settings_get_enable_webgl(settings));
break;
case PROP_ALLOW_MODAL_DIALOGS:
g_value_set_boolean(value, webkit_settings_get_allow_modal_dialogs(settings));
break;
case PROP_ZOOM_TEXT_ONLY:
g_value_set_boolean(value, webkit_settings_get_zoom_text_only(settings));
break;
case PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD:
g_value_set_boolean(value, webkit_settings_get_javascript_can_access_clipboard(settings));
break;
case PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE:
g_value_set_boolean(value, webkit_settings_get_media_playback_requires_user_gesture(settings));
break;
case PROP_MEDIA_PLAYBACK_ALLOWS_INLINE:
g_value_set_boolean(value, webkit_settings_get_media_playback_allows_inline(settings));
break;
case PROP_DRAW_COMPOSITING_INDICATORS:
g_value_set_boolean(value, webkit_settings_get_draw_compositing_indicators(settings));
break;
case PROP_ENABLE_SITE_SPECIFIC_QUIRKS:
g_value_set_boolean(value, webkit_settings_get_enable_site_specific_quirks(settings));
break;
case PROP_ENABLE_PAGE_CACHE:
g_value_set_boolean(value, webkit_settings_get_enable_page_cache(settings));
break;
case PROP_USER_AGENT:
g_value_set_string(value, webkit_settings_get_user_agent(settings));
break;
case PROP_ENABLE_SMOOTH_SCROLLING:
g_value_set_boolean(value, webkit_settings_get_enable_smooth_scrolling(settings));
break;
case PROP_ENABLE_ACCELERATED_2D_CANVAS:
g_value_set_boolean(value, webkit_settings_get_enable_accelerated_2d_canvas(settings));
break;
case PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT:
g_value_set_boolean(value, webkit_settings_get_enable_write_console_messages_to_stdout(settings));
break;
case PROP_ENABLE_MEDIA_STREAM:
g_value_set_boolean(value, webkit_settings_get_enable_media_stream(settings));
break;
case PROP_ENABLE_SPATIAL_NAVIGATION:
g_value_set_boolean(value, webkit_settings_get_enable_spatial_navigation(settings));
break;
case PROP_ENABLE_MEDIASOURCE:
g_value_set_boolean(value, webkit_settings_get_enable_mediasource(settings));
break;
case PROP_ALLOW_FILE_ACCESS_FROM_FILE_URLS:
g_value_set_boolean(value, webkit_settings_get_allow_file_access_from_file_urls(settings));
break;
case PROP_ALLOW_UNIVERSAL_ACCESS_FROM_FILE_URLS:
g_value_set_boolean(value, webkit_settings_get_allow_universal_access_from_file_urls(settings));
break;
#if PLATFORM(GTK)
case PROP_HARDWARE_ACCELERATION_POLICY:
g_value_set_enum(value, webkit_settings_get_hardware_acceleration_policy(settings));
break;
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec);
break;
}
}
static void webkit_settings_class_init(WebKitSettingsClass* klass)
{
GObjectClass* gObjectClass = G_OBJECT_CLASS(klass);
gObjectClass->constructed = webKitSettingsConstructed;
gObjectClass->set_property = webKitSettingsSetProperty;
gObjectClass->get_property = webKitSettingsGetProperty;
GParamFlags readWriteConstructParamFlags = static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT);
/**
* WebKitSettings:enable-javascript:
*
* Determines whether or not JavaScript executes within a page.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_JAVASCRIPT,
g_param_spec_boolean("enable-javascript",
_("Enable JavaScript"),
_("Enable JavaScript."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:auto-load-images:
*
* Determines whether images should be automatically loaded or not.
* On devices where network bandwidth is of concern, it might be
* useful to turn this property off.
*/
g_object_class_install_property(gObjectClass,
PROP_AUTO_LOAD_IMAGES,
g_param_spec_boolean("auto-load-images",
_("Auto load images"),
_("Load images automatically."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:load-icons-ignoring-image-load-setting:
*
* Determines whether a site can load favicons irrespective
* of the value of #WebKitSettings:auto-load-images.
*/
g_object_class_install_property(gObjectClass,
PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING,
g_param_spec_boolean("load-icons-ignoring-image-load-setting",
_("Load icons ignoring image load setting"),
_("Whether to load site icons ignoring image load setting."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-offline-web-application-cache:
*
* Whether to enable HTML5 offline web application cache support. Offline
* web application cache allows web applications to run even when
* the user is not connected to the network.
*
* HTML5 offline web application specification is available at
* http://dev.w3.org/html5/spec/offline.html.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE,
g_param_spec_boolean("enable-offline-web-application-cache",
_("Enable offline web application cache"),
_("Whether to enable offline web application cache."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-html5-local-storage:
*
* Whether to enable HTML5 local storage support. Local storage provides
* simple synchronous storage access.
*
* HTML5 local storage specification is available at
* http://dev.w3.org/html5/webstorage/.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_HTML5_LOCAL_STORAGE,
g_param_spec_boolean("enable-html5-local-storage",
_("Enable HTML5 local storage"),
_("Whether to enable HTML5 Local Storage support."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-html5-database:
*
* Whether to enable HTML5 client-side SQL database support. Client-side
* SQL database allows web pages to store structured data and be able to
* use SQL to manipulate that data asynchronously.
*
* HTML5 database specification is available at
* http://www.w3.org/TR/webdatabase/.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_HTML5_DATABASE,
g_param_spec_boolean("enable-html5-database",
_("Enable HTML5 database"),
_("Whether to enable HTML5 database support."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-xss-auditor:
*
* Whether to enable the XSS auditor. This feature filters some kinds of
* reflective XSS attacks on vulnerable web sites.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_XSS_AUDITOR,
g_param_spec_boolean("enable-xss-auditor",
_("Enable XSS auditor"),
_("Whether to enable the XSS auditor."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-frame-flattening:
*
* Whether to enable the frame flattening. With this setting each subframe is expanded
* to its contents, which will flatten all the frames to become one scrollable page.
* On touch devices scrollable subframes on a page can result in a confusing user experience.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_FRAME_FLATTENING,
g_param_spec_boolean("enable-frame-flattening",
_("Enable frame flattening"),
_("Whether to enable frame flattening."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-plugins:
*
* Determines whether or not plugins on the page are enabled.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_PLUGINS,
g_param_spec_boolean("enable-plugins",
_("Enable plugins"),
_("Enable embedded plugin objects."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-java:
*
* Determines whether or not Java is enabled on the page.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_JAVA,
g_param_spec_boolean("enable-java",
_("Enable Java"),
_("Whether Java support should be enabled."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:javascript-can-open-windows-automatically:
*
* Whether JavaScript can open popup windows automatically without user
* intervention.
*/
g_object_class_install_property(gObjectClass,
PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY,
g_param_spec_boolean("javascript-can-open-windows-automatically",
_("JavaScript can open windows automatically"),
_("Whether JavaScript can open windows automatically."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-hyperlink-auditing:
*
* Determines whether or not hyperlink auditing is enabled.
*
* The hyperlink auditing specification is available at
* http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_HYPERLINK_AUDITING,
g_param_spec_boolean("enable-hyperlink-auditing",
_("Enable hyperlink auditing"),
_("Whether <a ping> should be able to send pings."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:default-font-family:
*
* The font family to use as the default for content that does not specify a font.
*/
g_object_class_install_property(gObjectClass,
PROP_DEFAULT_FONT_FAMILY,
g_param_spec_string("default-font-family",
_("Default font family"),
_("The font family to use as the default for content that does not specify a font."),
"sans-serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:monospace-font-family:
*
* The font family used as the default for content using a monospace font.
*
*/
g_object_class_install_property(gObjectClass,
PROP_MONOSPACE_FONT_FAMILY,
g_param_spec_string("monospace-font-family",
_("Monospace font family"),
_("The font family used as the default for content using monospace font."),
"monospace",
readWriteConstructParamFlags));
/**
* WebKitSettings:serif-font-family:
*
* The font family used as the default for content using a serif font.
*/
g_object_class_install_property(gObjectClass,
PROP_SERIF_FONT_FAMILY,
g_param_spec_string("serif-font-family",
_("Serif font family"),
_("The font family used as the default for content using serif font."),
"serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:sans-serif-font-family:
*
* The font family used as the default for content using a sans-serif font.
*/
g_object_class_install_property(gObjectClass,
PROP_SANS_SERIF_FONT_FAMILY,
g_param_spec_string("sans-serif-font-family",
_("Sans-serif font family"),
_("The font family used as the default for content using sans-serif font."),
"sans-serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:cursive-font-family:
*
* The font family used as the default for content using a cursive font.
*/
g_object_class_install_property(gObjectClass,
PROP_CURSIVE_FONT_FAMILY,
g_param_spec_string("cursive-font-family",
_("Cursive font family"),
_("The font family used as the default for content using cursive font."),
"serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:fantasy-font-family:
*
* The font family used as the default for content using a fantasy font.
*/
g_object_class_install_property(gObjectClass,
PROP_FANTASY_FONT_FAMILY,
g_param_spec_string("fantasy-font-family",
_("Fantasy font family"),
_("The font family used as the default for content using fantasy font."),
"serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:pictograph-font-family:
*
* The font family used as the default for content using a pictograph font.
*/
g_object_class_install_property(gObjectClass,
PROP_PICTOGRAPH_FONT_FAMILY,
g_param_spec_string("pictograph-font-family",
_("Pictograph font family"),
_("The font family used as the default for content using pictograph font."),
"serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:default-font-size:
*
* The default font size in pixels to use for content displayed if
* no font size is specified.
*/
g_object_class_install_property(gObjectClass,
PROP_DEFAULT_FONT_SIZE,
g_param_spec_uint("default-font-size",
_("Default font size"),
_("The default font size used to display text."),
0, G_MAXUINT, 16,
readWriteConstructParamFlags));
/**
* WebKitSettings:default-monospace-font-size:
*
* The default font size in pixels to use for content displayed in
* monospace font if no font size is specified.
*/
g_object_class_install_property(gObjectClass,
PROP_DEFAULT_MONOSPACE_FONT_SIZE,
g_param_spec_uint("default-monospace-font-size",
_("Default monospace font size"),
_("The default font size used to display monospace text."),
0, G_MAXUINT, 13,
readWriteConstructParamFlags));
/**
* WebKitSettings:minimum-font-size:
*
* The minimum font size in points used to display text. This setting
* controls the absolute smallest size. Values other than 0 can
* potentially break page layouts.
*/
g_object_class_install_property(gObjectClass,
PROP_MINIMUM_FONT_SIZE,
g_param_spec_uint("minimum-font-size",
_("Minimum font size"),
_("The minimum font size used to display text."),
0, G_MAXUINT, 0,
readWriteConstructParamFlags));
/**
* WebKitSettings:default-charset:
*
* The default text charset used when interpreting content with an unspecified charset.
*/
g_object_class_install_property(gObjectClass,
PROP_DEFAULT_CHARSET,
g_param_spec_string("default-charset",
_("Default charset"),
_("The default text charset used when interpreting content with unspecified charset."),
"iso-8859-1",
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-private-browsing:
*
* Determines whether or not private browsing is enabled. Private browsing
* will disable history, cache and form auto-fill for any pages visited.
*
* Deprecated: 2.16. Use #WebKitWebView:is-ephemeral or #WebKitWebsiteDataManager:is-ephemeral instead.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_PRIVATE_BROWSING,
g_param_spec_boolean("enable-private-browsing",
_("Enable private browsing"),
_("Whether to enable private browsing"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-developer-extras:
*
* Determines whether or not developer tools, such as the Web Inspector, are enabled.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_DEVELOPER_EXTRAS,
g_param_spec_boolean("enable-developer-extras",
_("Enable developer extras"),
_("Whether to enable developer extras"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-resizable-text-areas:
*
* Determines whether or not text areas can be resized.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_RESIZABLE_TEXT_AREAS,
g_param_spec_boolean("enable-resizable-text-areas",
_("Enable resizable text areas"),
_("Whether to enable resizable text areas"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-tabs-to-links:
*
* Determines whether the tab key cycles through the elements on the page.
* When this setting is enabled, users will be able to focus the next element
* in the page by pressing the tab key. If the selected element is editable,
* then pressing tab key will insert the tab character.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_TABS_TO_LINKS,
g_param_spec_boolean("enable-tabs-to-links",
_("Enable tabs to links"),
_("Whether to enable tabs to links"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-dns-prefetching:
*
* Determines whether or not to prefetch domain names. DNS prefetching attempts
* to resolve domain names before a user tries to follow a link.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_DNS_PREFETCHING,
g_param_spec_boolean("enable-dns-prefetching",
_("Enable DNS prefetching"),
_("Whether to enable DNS prefetching"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-caret-browsing:
*
* Whether to enable accessibility enhanced keyboard navigation.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_CARET_BROWSING,
g_param_spec_boolean("enable-caret-browsing",
_("Enable Caret Browsing"),
_("Whether to enable accessibility enhanced keyboard navigation"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-fullscreen:
*
* Whether to enable the Javascript Fullscreen API. The API
* allows any HTML element to request fullscreen display. See also
* the current draft of the spec:
* http://www.w3.org/TR/fullscreen/
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_FULLSCREEN,
g_param_spec_boolean("enable-fullscreen",
_("Enable Fullscreen"),
_("Whether to enable the Javascript Fullscreen API"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:print-backgrounds:
*
* Whether background images should be drawn during printing.
*/
g_object_class_install_property(gObjectClass,
PROP_PRINT_BACKGROUNDS,
g_param_spec_boolean("print-backgrounds",
_("Print Backgrounds"),
_("Whether background images should be drawn during printing"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-webaudio:
*
*
* Enable or disable support for WebAudio on pages. WebAudio is an
* experimental proposal for allowing web pages to generate Audio
* WAVE data from JavaScript. The standard is currently a
* work-in-progress by the W3C Audio Working Group.
*
* See also https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_WEBAUDIO,
g_param_spec_boolean("enable-webaudio",
_("Enable WebAudio"),
_("Whether WebAudio content should be handled"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-webgl:
*
* Enable or disable support for WebGL on pages. WebGL is an experimental
* proposal for allowing web pages to use OpenGL ES-like calls directly. The
* standard is currently a work-in-progress by the Khronos Group.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_WEBGL,
g_param_spec_boolean("enable-webgl",
_("Enable WebGL"),
_("Whether WebGL content should be rendered"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:allow-modal-dialogs:
*
* Determine whether it's allowed to create and run modal dialogs
* from a #WebKitWebView through JavaScript with
* <function>window.showModalDialog</function>. If it's set to
* %FALSE, the associated #WebKitWebView won't be able to create
* new modal dialogs, so not even the #WebKitWebView::create
* signal will be emitted.
*/
g_object_class_install_property(gObjectClass,
PROP_ALLOW_MODAL_DIALOGS,
g_param_spec_boolean("allow-modal-dialogs",
_("Allow modal dialogs"),
_("Whether it is possible to create modal dialogs"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:zoom-text-only:
*
* Whether #WebKitWebView:zoom-level affects only the
* text of the page or all the contents. Other contents containing text
* like form controls will be also affected by zoom factor when
* this property is enabled.
*/
g_object_class_install_property(gObjectClass,
PROP_ZOOM_TEXT_ONLY,
g_param_spec_boolean("zoom-text-only",
_("Zoom Text Only"),
_("Whether zoom level of web view changes only the text size"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:javascript-can-access-clipboard:
*
* Whether JavaScript can access the clipboard. The default value is %FALSE. If
* set to %TRUE, document.execCommand() allows cut, copy and paste commands.
*
*/
g_object_class_install_property(gObjectClass,
PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD,
g_param_spec_boolean("javascript-can-access-clipboard",
_("JavaScript can access clipboard"),
_("Whether JavaScript can access Clipboard"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:media-playback-requires-user-gesture:
*
* Whether a user gesture (such as clicking the play button)
* would be required to start media playback or load media. This is off
* by default, so media playback could start automatically.
* Setting it on requires a gesture by the user to start playback, or to
* load the media.
*/
g_object_class_install_property(gObjectClass,
PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE,
g_param_spec_boolean("media-playback-requires-user-gesture",
_("Media playback requires user gesture"),
_("Whether media playback requires user gesture"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:media-playback-allows-inline:
*
* Whether media playback is full-screen only or inline playback is allowed.
* This is %TRUE by default, so media playback can be inline. Setting it to
* %FALSE allows specifying that media playback should be always fullscreen.
*/
g_object_class_install_property(gObjectClass,
PROP_MEDIA_PLAYBACK_ALLOWS_INLINE,
g_param_spec_boolean("media-playback-allows-inline",
_("Media playback allows inline"),
_("Whether media playback allows inline"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:draw-compositing-indicators:
*
* Whether to draw compositing borders and repaint counters on layers drawn
* with accelerated compositing. This is useful for debugging issues related
* to web content that is composited with the GPU.
*/
g_object_class_install_property(gObjectClass,
PROP_DRAW_COMPOSITING_INDICATORS,
g_param_spec_boolean("draw-compositing-indicators",
_("Draw compositing indicators"),
_("Whether to draw compositing borders and repaint counters"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-site-specific-quirks:
*
* Whether to turn on site-specific quirks. Turning this on will
* tell WebKit to use some site-specific workarounds for
* better web compatibility. For example, older versions of
* MediaWiki will incorrectly send to WebKit a CSS file with KHTML
* workarounds. By turning on site-specific quirks, WebKit will
* special-case this and other cases to make some specific sites work.
*/
g_object_class_install_property(
gObjectClass,
PROP_ENABLE_SITE_SPECIFIC_QUIRKS,
g_param_spec_boolean(
"enable-site-specific-quirks",
_("Enable Site Specific Quirks"),
_("Enables the site-specific compatibility workarounds"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-page-cache:
*
* Enable or disable the page cache. Disabling the page cache is
* generally only useful for special circumstances like low-memory
* scenarios or special purpose applications like static HTML
* viewers. This setting only controls the Page Cache, this cache
* is different than the disk-based or memory-based traditional
* resource caches, its point is to make going back and forth
* between pages much faster. For details about the different types
* of caches and their purposes see:
* http://webkit.org/blog/427/webkit-page-cache-i-the-basics/
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_PAGE_CACHE,
g_param_spec_boolean("enable-page-cache",
_("Enable page cache"),
_("Whether the page cache should be used"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:user-agent:
*
* The user-agent string used by WebKit. Unusual user-agent strings may cause web
* content to render incorrectly or fail to run, as many web pages are written to
* parse the user-agent strings of only the most popular browsers. Therefore, it's
* typically better to not completely override the standard user-agent, but to use
* webkit_settings_set_user_agent_with_application_details() instead.
*
* If this property is set to the empty string or %NULL, it will revert to the standard
* user-agent.
*/
g_object_class_install_property(gObjectClass,
PROP_USER_AGENT,
g_param_spec_string("user-agent",
_("User agent string"),
_("The user agent string"),
0, // A null string forces the standard user agent.
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-smooth-scrolling:
*
* Enable or disable smooth scrolling.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_SMOOTH_SCROLLING,
g_param_spec_boolean("enable-smooth-scrolling",
_("Enable smooth scrolling"),
_("Whether to enable smooth scrolling"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-accelerated-2d-canvas:
*
* Enable or disable accelerated 2D canvas. Accelerated 2D canvas is only available
* if WebKitGTK+ was compiled with a version of Cairo including the unstable CairoGL API.
* When accelerated 2D canvas is enabled, WebKit may render some 2D canvas content
* using hardware accelerated drawing operations.
*
* Since: 2.2
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_ACCELERATED_2D_CANVAS,
g_param_spec_boolean("enable-accelerated-2d-canvas",
_("Enable accelerated 2D canvas"),
_("Whether to enable accelerated 2D canvas"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-write-console-messages-to-stdout:
*
* Enable or disable writing console messages to stdout. These are messages
* sent to the console with console.log and related methods.
*
* Since: 2.2
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT,
g_param_spec_boolean("enable-write-console-messages-to-stdout",
_("Write console messages on stdout"),
_("Whether to write console messages on stdout"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-media-stream:
*
* Enable or disable support for MediaStream on pages. MediaStream
* is an experimental proposal for allowing web pages to access
* audio and video devices for capture.
*
* See also http://dev.w3.org/2011/webrtc/editor/getusermedia.html
*
* Since: 2.4
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_MEDIA_STREAM,
g_param_spec_boolean("enable-media-stream",
_("Enable MediaStream"),
_("Whether MediaStream content should be handled"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-spatial-navigation:
*
* Whether to enable Spatial Navigation. This feature consists in the ability
* to navigate between focusable elements in a Web page, such as hyperlinks
* and form controls, by using Left, Right, Up and Down arrow keys.
* For example, if an user presses the Right key, heuristics determine whether
* there is an element they might be trying to reach towards the right, and if
* there are multiple elements, which element they probably wants.
*
* Since: 2.4
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_SPATIAL_NAVIGATION,
g_param_spec_boolean("enable-spatial-navigation",
_("Enable Spatial Navigation"),
_("Whether to enable Spatial Navigation support."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-mediasource:
*
* Enable or disable support for MediaSource on pages. MediaSource is an
* experimental proposal which extends HTMLMediaElement to allow
* JavaScript to generate media streams for playback. The standard is
* currently a work-in-progress by the W3C HTML Media Task Force.
*
* See also http://www.w3.org/TR/media-source/
*
* Since: 2.4
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_MEDIASOURCE,
g_param_spec_boolean("enable-mediasource",
_("Enable MediaSource"),
_("Whether MediaSource should be enabled."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:allow-file-access-from-file-urls:
*
* Whether file access is allowed from file URLs. By default, when
* something is loaded in a #WebKitWebView using a file URI, cross
* origin requests to other file resources are not allowed. This
* setting allows you to change that behaviour, so that it would be
* possible to do a XMLHttpRequest of a local file, for example.
*
* Since: 2.10
*/
g_object_class_install_property(gObjectClass,
PROP_ALLOW_FILE_ACCESS_FROM_FILE_URLS,
g_param_spec_boolean("allow-file-access-from-file-urls",
_("Allow file access from file URLs"),
_("Whether file access is allowed from file URLs."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:allow-universal-access-from-file-urls:
*
* Whether or not JavaScript running in the context of a file scheme URL
* should be allowed to access content from any origin. By default, when
* something is loaded in a #WebKitWebView using a file scheme URL,
* access to the local file system and arbitrary local storage is not
* allowed. This setting allows you to change that behaviour, so that
* it would be possible to use local storage, for example.
*
* Since: 2.14
*/
g_object_class_install_property(gObjectClass,
PROP_ALLOW_UNIVERSAL_ACCESS_FROM_FILE_URLS,
g_param_spec_boolean("allow-universal-access-from-file-urls",
_("Allow universal access from the context of file scheme URLs"),
_("Whether or not universal access is allowed from the context of file scheme URLs"),
FALSE,
readWriteConstructParamFlags));
#if PLATFORM(GTK)
/**
* WebKitSettings:hardware-acceleration-policy:
*
* The #WebKitHardwareAccelerationPolicy to decide how to enable and disable
* hardware acceleration. The default value %WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND
* enables the hardware acceleration when the web contents request it, disabling it again
* when no longer needed. It's possible to enforce hardware acceleration to be always enabled
* by using %WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS. And it's also possible to disable it
* completely using %WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER. Note that disabling hardware
* acceleration might cause some websites to not render correctly or consume more CPU.
*
* Note that changing this setting might not be possible if hardware acceleration is not
* supported by the hardware or the system. In that case you can get the value to know the
* actual policy being used, but changing the setting will not have any effect.
*
* Since: 2.16
*/
g_object_class_install_property(gObjectClass,
PROP_HARDWARE_ACCELERATION_POLICY,
g_param_spec_enum("hardware-acceleration-policy",
_("Hardware Acceleration Policy"),
_("The policy to decide how to enable and disable hardware acceleration"),
WEBKIT_TYPE_HARDWARE_ACCELERATION_POLICY,
WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND,
readWriteConstructParamFlags));
#endif // PLATFOTM(GTK)
}
WebPreferences* webkitSettingsGetPreferences(WebKitSettings* settings)
{
return settings->priv->preferences.get();
}
/**
* webkit_settings_new:
*
* Creates a new #WebKitSettings instance with default values. It must
* be manually attached to a #WebKitWebView.
* See also webkit_settings_new_with_settings().
*
* Returns: a new #WebKitSettings instance.
*/
WebKitSettings* webkit_settings_new()
{
return WEBKIT_SETTINGS(g_object_new(WEBKIT_TYPE_SETTINGS, NULL));
}
/**
* webkit_settings_new_with_settings:
* @first_setting_name: name of first setting to set
* @...: value of first setting, followed by more settings,
* %NULL-terminated
*
* Creates a new #WebKitSettings instance with the given settings. It must
* be manually attached to a #WebKitWebView.
*
* Returns: a new #WebKitSettings instance.
*/
WebKitSettings* webkit_settings_new_with_settings(const gchar* firstSettingName, ...)
{
va_list args;
va_start(args, firstSettingName);
WebKitSettings* settings = WEBKIT_SETTINGS(g_object_new_valist(WEBKIT_TYPE_SETTINGS, firstSettingName, args));
va_end(args);
return settings;
}
/**
* webkit_settings_get_enable_javascript:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-javascript property.
*
* Returns: %TRUE If JavaScript is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_javascript(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->javaScriptEnabled();
}
/**
* webkit_settings_set_enable_javascript:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-javascript property.
*/
void webkit_settings_set_enable_javascript(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->javaScriptEnabled();
if (currentValue == enabled)
return;
priv->preferences->setJavaScriptEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-javascript");
}
/**
* webkit_settings_get_auto_load_images:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:auto-load-images property.
*
* Returns: %TRUE If auto loading of images is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_auto_load_images(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->loadsImagesAutomatically();
}
/**
* webkit_settings_set_auto_load_images:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:auto-load-images property.
*/
void webkit_settings_set_auto_load_images(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->loadsImagesAutomatically();
if (currentValue == enabled)
return;
priv->preferences->setLoadsImagesAutomatically(enabled);
g_object_notify(G_OBJECT(settings), "auto-load-images");
}
/**
* webkit_settings_get_load_icons_ignoring_image_load_setting:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:load-icons-ignoring-image-load-setting property.
*
* Returns: %TRUE If site icon can be loaded irrespective of image loading preference or %FALSE otherwise.
*/
gboolean webkit_settings_get_load_icons_ignoring_image_load_setting(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->loadsSiteIconsIgnoringImageLoadingPreference();
}
/**
* webkit_settings_set_load_icons_ignoring_image_load_setting:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:load-icons-ignoring-image-load-setting property.
*/
void webkit_settings_set_load_icons_ignoring_image_load_setting(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->loadsSiteIconsIgnoringImageLoadingPreference();
if (currentValue == enabled)
return;
priv->preferences->setLoadsSiteIconsIgnoringImageLoadingPreference(enabled);
g_object_notify(G_OBJECT(settings), "load-icons-ignoring-image-load-setting");
}
/**
* webkit_settings_get_enable_offline_web_application_cache:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-offline-web-application-cache property.
*
* Returns: %TRUE If HTML5 offline web application cache support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_offline_web_application_cache(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->offlineWebApplicationCacheEnabled();
}
/**
* webkit_settings_set_enable_offline_web_application_cache:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-offline-web-application-cache property.
*/
void webkit_settings_set_enable_offline_web_application_cache(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->offlineWebApplicationCacheEnabled();
if (currentValue == enabled)
return;
priv->preferences->setOfflineWebApplicationCacheEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-offline-web-application-cache");
}
/**
* webkit_settings_get_enable_html5_local_storage:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-html5-local-storage property.
*
* Returns: %TRUE If HTML5 local storage support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_html5_local_storage(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->localStorageEnabled();
}
/**
* webkit_settings_set_enable_html5_local_storage:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-html5-local-storage property.
*/
void webkit_settings_set_enable_html5_local_storage(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->localStorageEnabled();
if (currentValue == enabled)
return;
priv->preferences->setLocalStorageEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-html5-local-storage");
}
/**
* webkit_settings_get_enable_html5_database:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-html5-database property.
*
* Returns: %TRUE If HTML5 database support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_html5_database(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->databasesEnabled();
}
/**
* webkit_settings_set_enable_html5_database:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-html5-database property.
*/
void webkit_settings_set_enable_html5_database(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->databasesEnabled();
if (currentValue == enabled)
return;
priv->preferences->setDatabasesEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-html5-database");
}
/**
* webkit_settings_get_enable_xss_auditor:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-xss-auditor property.
*
* Returns: %TRUE If XSS auditing is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_xss_auditor(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->xssAuditorEnabled();
}
/**
* webkit_settings_set_enable_xss_auditor:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-xss-auditor property.
*/
void webkit_settings_set_enable_xss_auditor(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->xssAuditorEnabled();
if (currentValue == enabled)
return;
priv->preferences->setXSSAuditorEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-xss-auditor");
}
/**
* webkit_settings_get_enable_frame_flattening:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-frame-flattening property.
*
* Returns: %TRUE If frame flattening is enabled or %FALSE otherwise.
*
**/
gboolean webkit_settings_get_enable_frame_flattening(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
// FIXME: Expose more frame flattening values.
return settings->priv->preferences->frameFlattening() != WebCore::FrameFlatteningDisabled;
}
/**
* webkit_settings_set_enable_frame_flattening:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-frame-flattening property.
*/
void webkit_settings_set_enable_frame_flattening(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->frameFlattening() != WebCore::FrameFlatteningDisabled;
if (currentValue == enabled)
return;
// FIXME: Expose more frame flattening values.
priv->preferences->setFrameFlattening(enabled ? WebCore::FrameFlatteningFullyEnabled : WebCore::FrameFlatteningDisabled);
g_object_notify(G_OBJECT(settings), "enable-frame-flattening");
}
/**
* webkit_settings_get_enable_plugins:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-plugins property.
*
* Returns: %TRUE If plugins are enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_plugins(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->pluginsEnabled();
}
/**
* webkit_settings_set_enable_plugins:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-plugins property.
*/
void webkit_settings_set_enable_plugins(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->pluginsEnabled();
if (currentValue == enabled)
return;
priv->preferences->setPluginsEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-plugins");
}
/**
* webkit_settings_get_enable_java:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-java property.
*
* Returns: %TRUE If Java is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_java(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->javaEnabled();
}
/**
* webkit_settings_set_enable_java:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-java property.
*/
void webkit_settings_set_enable_java(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->javaEnabled();
if (currentValue == enabled)
return;
priv->preferences->setJavaEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-java");
}
/**
* webkit_settings_get_javascript_can_open_windows_automatically:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:javascript-can-open-windows-automatically property.
*
* Returns: %TRUE If JavaScript can open window automatically or %FALSE otherwise.
*/
gboolean webkit_settings_get_javascript_can_open_windows_automatically(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->javaScriptCanOpenWindowsAutomatically();
}
/**
* webkit_settings_set_javascript_can_open_windows_automatically:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:javascript-can-open-windows-automatically property.
*/
void webkit_settings_set_javascript_can_open_windows_automatically(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->javaScriptCanOpenWindowsAutomatically();
if (currentValue == enabled)
return;
priv->preferences->setJavaScriptCanOpenWindowsAutomatically(enabled);
g_object_notify(G_OBJECT(settings), "javascript-can-open-windows-automatically");
}
/**
* webkit_settings_get_enable_hyperlink_auditing:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-hyperlink-auditing property.
*
* Returns: %TRUE If hyper link auditing is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_hyperlink_auditing(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->hyperlinkAuditingEnabled();
}
/**
* webkit_settings_set_enable_hyperlink_auditing:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-hyperlink-auditing property.
*/
void webkit_settings_set_enable_hyperlink_auditing(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->hyperlinkAuditingEnabled();
if (currentValue == enabled)
return;
priv->preferences->setHyperlinkAuditingEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-hyperlink-auditing");
}
/**
* webkit_web_settings_get_default_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:default-font-family property.
*
* Returns: The default font family used to display content that does not specify a font.
*/
const gchar* webkit_settings_get_default_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->defaultFontFamily.data();
}
/**
* webkit_settings_set_default_font_family:
* @settings: a #WebKitSettings
* @default_font_family: the new default font family
*
* Set the #WebKitSettings:default-font-family property.
*/
void webkit_settings_set_default_font_family(WebKitSettings* settings, const gchar* defaultFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(defaultFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->defaultFontFamily.data(), defaultFontFamily))
return;
String standardFontFamily = String::fromUTF8(defaultFontFamily);
priv->preferences->setStandardFontFamily(standardFontFamily);
priv->defaultFontFamily = standardFontFamily.utf8();
g_object_notify(G_OBJECT(settings), "default-font-family");
}
/**
* webkit_settings_get_monospace_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:monospace-font-family property.
*
* Returns: Default font family used to display content marked with monospace font.
*/
const gchar* webkit_settings_get_monospace_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->monospaceFontFamily.data();
}
/**
* webkit_settings_set_monospace_font_family:
* @settings: a #WebKitSettings
* @monospace_font_family: the new default monospace font family
*
* Set the #WebKitSettings:monospace-font-family property.
*/
void webkit_settings_set_monospace_font_family(WebKitSettings* settings, const gchar* monospaceFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(monospaceFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->monospaceFontFamily.data(), monospaceFontFamily))
return;
String fixedFontFamily = String::fromUTF8(monospaceFontFamily);
priv->preferences->setFixedFontFamily(fixedFontFamily);
priv->monospaceFontFamily = fixedFontFamily.utf8();
g_object_notify(G_OBJECT(settings), "monospace-font-family");
}
/**
* webkit_settings_get_serif_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:serif-font-family property.
*
* Returns: The default font family used to display content marked with serif font.
*/
const gchar* webkit_settings_get_serif_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->serifFontFamily.data();
}
/**
* webkit_settings_set_serif_font_family:
* @settings: a #WebKitSettings
* @serif_font_family: the new default serif font family
*
* Set the #WebKitSettings:serif-font-family property.
*/
void webkit_settings_set_serif_font_family(WebKitSettings* settings, const gchar* serifFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(serifFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->serifFontFamily.data(), serifFontFamily))
return;
String serifFontFamilyString = String::fromUTF8(serifFontFamily);
priv->preferences->setSerifFontFamily(serifFontFamilyString);
priv->serifFontFamily = serifFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "serif-font-family");
}
/**
* webkit_settings_get_sans_serif_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:sans-serif-font-family property.
*
* Returns: The default font family used to display content marked with sans-serif font.
*/
const gchar* webkit_settings_get_sans_serif_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->sansSerifFontFamily.data();
}
/**
* webkit_settings_set_sans_serif_font_family:
* @settings: a #WebKitSettings
* @sans_serif_font_family: the new default sans-serif font family
*
* Set the #WebKitSettings:sans-serif-font-family property.
*/
void webkit_settings_set_sans_serif_font_family(WebKitSettings* settings, const gchar* sansSerifFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(sansSerifFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->sansSerifFontFamily.data(), sansSerifFontFamily))
return;
String sansSerifFontFamilyString = String::fromUTF8(sansSerifFontFamily);
priv->preferences->setSansSerifFontFamily(sansSerifFontFamilyString);
priv->sansSerifFontFamily = sansSerifFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "sans-serif-font-family");
}
/**
* webkit_settings_get_cursive_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:cursive-font-family property.
*
* Returns: The default font family used to display content marked with cursive font.
*/
const gchar* webkit_settings_get_cursive_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->cursiveFontFamily.data();
}
/**
* webkit_settings_set_cursive_font_family:
* @settings: a #WebKitSettings
* @cursive_font_family: the new default cursive font family
*
* Set the #WebKitSettings:cursive-font-family property.
*/
void webkit_settings_set_cursive_font_family(WebKitSettings* settings, const gchar* cursiveFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(cursiveFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->cursiveFontFamily.data(), cursiveFontFamily))
return;
String cursiveFontFamilyString = String::fromUTF8(cursiveFontFamily);
priv->preferences->setCursiveFontFamily(cursiveFontFamilyString);
priv->cursiveFontFamily = cursiveFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "cursive-font-family");
}
/**
* webkit_settings_get_fantasy_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:fantasy-font-family property.
*
* Returns: The default font family used to display content marked with fantasy font.
*/
const gchar* webkit_settings_get_fantasy_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->fantasyFontFamily.data();
}
/**
* webkit_settings_set_fantasy_font_family:
* @settings: a #WebKitSettings
* @fantasy_font_family: the new default fantasy font family
*
* Set the #WebKitSettings:fantasy-font-family property.
*/
void webkit_settings_set_fantasy_font_family(WebKitSettings* settings, const gchar* fantasyFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(fantasyFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->fantasyFontFamily.data(), fantasyFontFamily))
return;
String fantasyFontFamilyString = String::fromUTF8(fantasyFontFamily);
priv->preferences->setFantasyFontFamily(fantasyFontFamilyString);
priv->fantasyFontFamily = fantasyFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "fantasy-font-family");
}
/**
* webkit_settings_get_pictograph_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:pictograph-font-family property.
*
* Returns: The default font family used to display content marked with pictograph font.
*/
const gchar* webkit_settings_get_pictograph_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->pictographFontFamily.data();
}
/**
* webkit_settings_set_pictograph_font_family:
* @settings: a #WebKitSettings
* @pictograph_font_family: the new default pictograph font family
*
* Set the #WebKitSettings:pictograph-font-family property.
*/
void webkit_settings_set_pictograph_font_family(WebKitSettings* settings, const gchar* pictographFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(pictographFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->pictographFontFamily.data(), pictographFontFamily))
return;
String pictographFontFamilyString = String::fromUTF8(pictographFontFamily);
priv->preferences->setPictographFontFamily(pictographFontFamilyString);
priv->pictographFontFamily = pictographFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "pictograph-font-family");
}
/**
* webkit_settings_get_default_font_size:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:default-font-size property.
*
* Returns: The default font size.
*/
guint32 webkit_settings_get_default_font_size(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->preferences->defaultFontSize();
}
/**
* webkit_settings_set_default_font_size:
* @settings: a #WebKitSettings
* @font_size: default font size to be set in pixels
*
* Set the #WebKitSettings:default-font-size property.
*/
void webkit_settings_set_default_font_size(WebKitSettings* settings, guint32 fontSize)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
uint32_t currentSize = priv->preferences->defaultFontSize();
if (currentSize == fontSize)
return;
priv->preferences->setDefaultFontSize(fontSize);
g_object_notify(G_OBJECT(settings), "default-font-size");
}
/**
* webkit_settings_get_default_monospace_font_size:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:default-monospace-font-size property.
*
* Returns: Default monospace font size.
*/
guint32 webkit_settings_get_default_monospace_font_size(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->preferences->defaultFixedFontSize();
}
/**
* webkit_settings_set_default_monospace_font_size:
* @settings: a #WebKitSettings
* @font_size: default monospace font size to be set in pixels
*
* Set the #WebKitSettings:default-monospace-font-size property.
*/
void webkit_settings_set_default_monospace_font_size(WebKitSettings* settings, guint32 fontSize)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
uint32_t currentSize = priv->preferences->defaultFixedFontSize();
if (currentSize == fontSize)
return;
priv->preferences->setDefaultFixedFontSize(fontSize);
g_object_notify(G_OBJECT(settings), "default-monospace-font-size");
}
/**
* webkit_settings_get_minimum_font_size:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:minimum-font-size property.
*
* Returns: Minimum font size.
*/
guint32 webkit_settings_get_minimum_font_size(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->preferences->minimumFontSize();
}
/**
* webkit_settings_set_minimum_font_size:
* @settings: a #WebKitSettings
* @font_size: minimum font size to be set in points
*
* Set the #WebKitSettings:minimum-font-size property.
*/
void webkit_settings_set_minimum_font_size(WebKitSettings* settings, guint32 fontSize)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
uint32_t currentSize = priv->preferences->minimumFontSize();
if (currentSize == fontSize)
return;
priv->preferences->setMinimumFontSize(fontSize);
g_object_notify(G_OBJECT(settings), "minimum-font-size");
}
/**
* webkit_settings_get_default_charset:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:default-charset property.
*
* Returns: Default charset.
*/
const gchar* webkit_settings_get_default_charset(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->defaultCharset.data();
}
/**
* webkit_settings_set_default_charset:
* @settings: a #WebKitSettings
* @default_charset: default charset to be set
*
* Set the #WebKitSettings:default-charset property.
*/
void webkit_settings_set_default_charset(WebKitSettings* settings, const gchar* defaultCharset)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(defaultCharset);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->defaultCharset.data(), defaultCharset))
return;
String defaultCharsetString = String::fromUTF8(defaultCharset);
priv->preferences->setDefaultTextEncodingName(defaultCharsetString);
priv->defaultCharset = defaultCharsetString.utf8();
g_object_notify(G_OBJECT(settings), "default-charset");
}
/**
* webkit_settings_get_enable_private_browsing:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-private-browsing property.
*
* Returns: %TRUE If private browsing is enabled or %FALSE otherwise.
*
* Deprecated: 2.16. Use #WebKitWebView:is-ephemeral or #WebKitWebContext:is-ephemeral instead.
*/
gboolean webkit_settings_get_enable_private_browsing(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->privateBrowsingEnabled();
}
/**
* webkit_settings_set_enable_private_browsing:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-private-browsing property.
*
* Deprecated: 2.16. Use #WebKitWebView:is-ephemeral or #WebKitWebContext:is-ephemeral instead.
*/
void webkit_settings_set_enable_private_browsing(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->privateBrowsingEnabled();
if (currentValue == enabled)
return;
priv->preferences->setPrivateBrowsingEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-private-browsing");
}
/**
* webkit_settings_get_enable_developer_extras:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-developer-extras property.
*
* Returns: %TRUE If developer extras is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_developer_extras(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->developerExtrasEnabled();
}
/**
* webkit_settings_set_enable_developer_extras:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-developer-extras property.
*/
void webkit_settings_set_enable_developer_extras(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->developerExtrasEnabled();
if (currentValue == enabled)
return;
priv->preferences->setDeveloperExtrasEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-developer-extras");
}
/**
* webkit_settings_get_enable_resizable_text_areas:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-resizable-text-areas property.
*
* Returns: %TRUE If text areas can be resized or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_resizable_text_areas(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->textAreasAreResizable();
}
/**
* webkit_settings_set_enable_resizable_text_areas:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-resizable-text-areas property.
*/
void webkit_settings_set_enable_resizable_text_areas(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->textAreasAreResizable();
if (currentValue == enabled)
return;
priv->preferences->setTextAreasAreResizable(enabled);
g_object_notify(G_OBJECT(settings), "enable-resizable-text-areas");
}
/**
* webkit_settings_get_enable_tabs_to_links:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-tabs-to-links property.
*
* Returns: %TRUE If tabs to link is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_tabs_to_links(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->tabsToLinks();
}
/**
* webkit_settings_set_enable_tabs_to_links:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-tabs-to-links property.
*/
void webkit_settings_set_enable_tabs_to_links(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->tabsToLinks();
if (currentValue == enabled)
return;
priv->preferences->setTabsToLinks(enabled);
g_object_notify(G_OBJECT(settings), "enable-tabs-to-links");
}
/**
* webkit_settings_get_enable_dns_prefetching:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-dns-prefetching property.
*
* Returns: %TRUE If DNS prefetching is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_dns_prefetching(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->dnsPrefetchingEnabled();
}
/**
* webkit_settings_set_enable_dns_prefetching:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-dns-prefetching property.
*/
void webkit_settings_set_enable_dns_prefetching(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->dnsPrefetchingEnabled();
if (currentValue == enabled)
return;
priv->preferences->setDNSPrefetchingEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-dns-prefetching");
}
/**
* webkit_settings_get_enable_caret_browsing:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-caret-browsing property.
*
* Returns: %TRUE If caret browsing is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_caret_browsing(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->caretBrowsingEnabled();
}
/**
* webkit_settings_set_enable_caret_browsing:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-caret-browsing property.
*/
void webkit_settings_set_enable_caret_browsing(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->caretBrowsingEnabled();
if (currentValue == enabled)
return;
priv->preferences->setCaretBrowsingEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-caret-browsing");
}
/**
* webkit_settings_get_enable_fullscreen:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-fullscreen property.
*
* Returns: %TRUE If fullscreen support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_fullscreen(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->fullScreenEnabled();
}
/**
* webkit_settings_set_enable_fullscreen:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-fullscreen property.
*/
void webkit_settings_set_enable_fullscreen(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->fullScreenEnabled();
if (currentValue == enabled)
return;
priv->preferences->setFullScreenEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-fullscreen");
}
/**
* webkit_settings_get_print_backgrounds:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:print-backgrounds property.
*
* Returns: %TRUE If background images should be printed or %FALSE otherwise.
*/
gboolean webkit_settings_get_print_backgrounds(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->shouldPrintBackgrounds();
}
/**
* webkit_settings_set_print_backgrounds:
* @settings: a #WebKitSettings
* @print_backgrounds: Value to be set
*
* Set the #WebKitSettings:print-backgrounds property.
*/
void webkit_settings_set_print_backgrounds(WebKitSettings* settings, gboolean printBackgrounds)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->shouldPrintBackgrounds();
if (currentValue == printBackgrounds)
return;
priv->preferences->setShouldPrintBackgrounds(printBackgrounds);
g_object_notify(G_OBJECT(settings), "print-backgrounds");
}
/**
* webkit_settings_get_enable_webaudio:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-webaudio property.
*
* Returns: %TRUE If webaudio support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_webaudio(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->webAudioEnabled();
}
/**
* webkit_settings_set_enable_webaudio:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-webaudio property.
*/
void webkit_settings_set_enable_webaudio(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->webAudioEnabled();
if (currentValue == enabled)
return;
priv->preferences->setWebAudioEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-webaudio");
}
/**
* webkit_settings_get_enable_webgl:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-webgl property.
*
* Returns: %TRUE If WebGL support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_webgl(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->webGLEnabled();
}
/**
* webkit_settings_set_enable_webgl:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-webgl property.
*/
void webkit_settings_set_enable_webgl(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->webGLEnabled();
if (currentValue == enabled)
return;
priv->preferences->setWebGLEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-webgl");
}
/**
* webkit_settings_get_allow_modal_dialogs:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:allow-modal-dialogs property.
*
* Returns: %TRUE if it's allowed to create and run modal dialogs or %FALSE otherwise.
*/
gboolean webkit_settings_get_allow_modal_dialogs(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->allowModalDialogs;
}
/**
* webkit_settings_set_allow_modal_dialogs:
* @settings: a #WebKitSettings
* @allowed: Value to be set
*
* Set the #WebKitSettings:allow-modal-dialogs property.
*/
void webkit_settings_set_allow_modal_dialogs(WebKitSettings* settings, gboolean allowed)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->allowModalDialogs == allowed)
return;
priv->allowModalDialogs = allowed;
g_object_notify(G_OBJECT(settings), "allow-modal-dialogs");
}
/**
* webkit_settings_get_zoom_text_only:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:zoom-text-only property.
*
* Returns: %TRUE If zoom level of the view should only affect the text
* or %FALSE if all view contents should be scaled.
*/
gboolean webkit_settings_get_zoom_text_only(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->zoomTextOnly;
}
/**
* webkit_settings_set_zoom_text_only:
* @settings: a #WebKitSettings
* @zoom_text_only: Value to be set
*
* Set the #WebKitSettings:zoom-text-only property.
*/
void webkit_settings_set_zoom_text_only(WebKitSettings* settings, gboolean zoomTextOnly)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->zoomTextOnly == zoomTextOnly)
return;
priv->zoomTextOnly = zoomTextOnly;
g_object_notify(G_OBJECT(settings), "zoom-text-only");
}
/**
* webkit_settings_get_javascript_can_access_clipboard:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:javascript-can-access-clipboard property.
*
* Returns: %TRUE If javascript-can-access-clipboard is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_javascript_can_access_clipboard(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->javaScriptCanAccessClipboard()
&& settings->priv->preferences->domPasteAllowed();
}
/**
* webkit_settings_set_javascript_can_access_clipboard:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:javascript-can-access-clipboard property.
*/
void webkit_settings_set_javascript_can_access_clipboard(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->javaScriptCanAccessClipboard() && priv->preferences->domPasteAllowed();
if (currentValue == enabled)
return;
priv->preferences->setJavaScriptCanAccessClipboard(enabled);
priv->preferences->setDOMPasteAllowed(enabled);
g_object_notify(G_OBJECT(settings), "javascript-can-access-clipboard");
}
/**
* webkit_settings_get_media_playback_requires_user_gesture:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:media-playback-requires-user-gesture property.
*
* Returns: %TRUE If an user gesture is needed to play or load media
* or %FALSE if no user gesture is needed.
*/
gboolean webkit_settings_get_media_playback_requires_user_gesture(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->requiresUserGestureForMediaPlayback();
}
/**
* webkit_settings_set_media_playback_requires_user_gesture:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:media-playback-requires-user-gesture property.
*/
void webkit_settings_set_media_playback_requires_user_gesture(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->requiresUserGestureForMediaPlayback();
if (currentValue == enabled)
return;
priv->preferences->setRequiresUserGestureForMediaPlayback(enabled);
g_object_notify(G_OBJECT(settings), "media-playback-requires-user-gesture");
}
/**
* webkit_settings_get_media_playback_allows_inline:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:media-playback-allows-inline property.
*
* Returns: %TRUE If inline playback is allowed for media
* or %FALSE if only fullscreen playback is allowed.
*/
gboolean webkit_settings_get_media_playback_allows_inline(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), TRUE);
return settings->priv->preferences->allowsInlineMediaPlayback();
}
/**
* webkit_settings_set_media_playback_allows_inline:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:media-playback-allows-inline property.
*/
void webkit_settings_set_media_playback_allows_inline(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->allowsInlineMediaPlayback();
if (currentValue == enabled)
return;
priv->preferences->setAllowsInlineMediaPlayback(enabled);
g_object_notify(G_OBJECT(settings), "media-playback-allows-inline");
}
/**
* webkit_settings_get_draw_compositing_indicators:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:draw-compositing-indicators property.
*
* Returns: %TRUE If compositing borders are drawn or %FALSE otherwise.
*/
gboolean webkit_settings_get_draw_compositing_indicators(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->compositingBordersVisible()
&& settings->priv->preferences->compositingRepaintCountersVisible();
}
/**
* webkit_settings_set_draw_compositing_indicators:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:draw-compositing-indicators property.
*/
void webkit_settings_set_draw_compositing_indicators(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->preferences->compositingBordersVisible() == enabled
&& priv->preferences->compositingRepaintCountersVisible() == enabled)
return;
priv->preferences->setCompositingBordersVisible(enabled);
priv->preferences->setCompositingRepaintCountersVisible(enabled);
g_object_notify(G_OBJECT(settings), "draw-compositing-indicators");
}
/**
* webkit_settings_get_enable_site_specific_quirks:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-site-specific-quirks property.
*
* Returns: %TRUE if site specific quirks are enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_site_specific_quirks(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->needsSiteSpecificQuirks();
}
/**
* webkit_settings_set_enable_site_specific_quirks:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-site-specific-quirks property.
*/
void webkit_settings_set_enable_site_specific_quirks(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->needsSiteSpecificQuirks();
if (currentValue == enabled)
return;
priv->preferences->setNeedsSiteSpecificQuirks(enabled);
g_object_notify(G_OBJECT(settings), "enable-site-specific-quirks");
}
/**
* webkit_settings_get_enable_page_cache:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-page-cache property.
*
* Returns: %TRUE if page cache enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_page_cache(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->usesPageCache();
}
/**
* webkit_settings_set_enable_page_cache:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-page-cache property.
*/
void webkit_settings_set_enable_page_cache(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->usesPageCache();
if (currentValue == enabled)
return;
priv->preferences->setUsesPageCache(enabled);
g_object_notify(G_OBJECT(settings), "enable-page-cache");
}
/**
* webkit_settings_get_user_agent:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:user-agent property.
*
* Returns: The current value of the user-agent property.
*/
const char* webkit_settings_get_user_agent(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
WebKitSettingsPrivate* priv = settings->priv;
ASSERT(!priv->userAgent.isNull());
return priv->userAgent.data();
}
/**
* webkit_settings_set_user_agent:
* @settings: a #WebKitSettings
* @user_agent: (allow-none): The new custom user agent string or %NULL to use the default user agent
*
* Set the #WebKitSettings:user-agent property.
*/
void webkit_settings_set_user_agent(WebKitSettings* settings, const char* userAgent)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
CString newUserAgent = (!userAgent || !strlen(userAgent)) ? WebCore::standardUserAgent("").utf8() : userAgent;
if (newUserAgent == priv->userAgent)
return;
priv->userAgent = newUserAgent;
g_object_notify(G_OBJECT(settings), "user-agent");
}
/**
* webkit_settings_set_user_agent_with_application_details:
* @settings: a #WebKitSettings
* @application_name: (allow-none): The application name used for the user agent or %NULL to use the default user agent.
* @application_version: (allow-none): The application version for the user agent or %NULL to user the default version.
*
* Set the #WebKitSettings:user-agent property by appending the application details to the default user
* agent. If no application name or version is given, the default user agent used will be used. If only
* the version is given, the default engine version is used with the given application name.
*/
void webkit_settings_set_user_agent_with_application_details(WebKitSettings* settings, const char* applicationName, const char* applicationVersion)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
CString newUserAgent = WebCore::standardUserAgent(String::fromUTF8(applicationName), String::fromUTF8(applicationVersion)).utf8();
webkit_settings_set_user_agent(settings, newUserAgent.data());
}
/**
* webkit_settings_get_enable_smooth_scrolling:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-smooth-scrolling property.
*
* Returns: %TRUE if smooth scrolling is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_smooth_scrolling(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->scrollAnimatorEnabled();
}
/**
* webkit_settings_set_enable_smooth_scrolling:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-smooth-scrolling property.
*/
void webkit_settings_set_enable_smooth_scrolling(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->scrollAnimatorEnabled();
if (currentValue == enabled)
return;
priv->preferences->setScrollAnimatorEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-smooth-scrolling");
}
/**
* webkit_settings_get_enable_accelerated_2d_canvas:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-accelerated-2d-canvas property.
*
* Returns: %TRUE if accelerated 2D canvas is enabled or %FALSE otherwise.
*
* Since: 2.2
*/
gboolean webkit_settings_get_enable_accelerated_2d_canvas(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->accelerated2dCanvasEnabled();
}
/**
* webkit_settings_set_enable_accelerated_2d_canvas:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-accelerated-2d-canvas property.
*
* Since: 2.2
*/
void webkit_settings_set_enable_accelerated_2d_canvas(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->preferences->accelerated2dCanvasEnabled() == enabled)
return;
priv->preferences->setAccelerated2dCanvasEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-accelerated-2d-canvas");
}
/**
* webkit_settings_get_enable_write_console_messages_to_stdout:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-write-console-messages-to-stdout property.
*
* Returns: %TRUE if writing console messages to stdout is enabled or %FALSE
* otherwise.
*
* Since: 2.2
*/
gboolean webkit_settings_get_enable_write_console_messages_to_stdout(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->logsPageMessagesToSystemConsoleEnabled();
}
/**
* webkit_settings_set_enable_write_console_messages_to_stdout:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-write-console-messages-to-stdout property.
*
* Since: 2.2
*/
void webkit_settings_set_enable_write_console_messages_to_stdout(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->logsPageMessagesToSystemConsoleEnabled();
if (currentValue == enabled)
return;
priv->preferences->setLogsPageMessagesToSystemConsoleEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-write-console-messages-to-stdout");
}
/**
* webkit_settings_get_enable_media_stream:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-media-stream property.
*
* Returns: %TRUE If mediastream support is enabled or %FALSE otherwise.
*
* Since: 2.4
*/
gboolean webkit_settings_get_enable_media_stream(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->mediaStreamEnabled();
}
/**
* webkit_settings_set_enable_media_stream:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-media-stream property.
*
* Since: 2.4
*/
void webkit_settings_set_enable_media_stream(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->mediaStreamEnabled();
if (currentValue == enabled)
return;
priv->preferences->setMediaDevicesEnabled(enabled);
priv->preferences->setMediaStreamEnabled(enabled);
priv->preferences->setPeerConnectionEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-media-stream");
}
/**
* webkit_settings_set_enable_spatial_navigation:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-spatial-navigation property.
*
* Since: 2.2
*/
void webkit_settings_set_enable_spatial_navigation(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->spatialNavigationEnabled();
if (currentValue == enabled)
return;
priv->preferences->setSpatialNavigationEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-spatial-navigation");
}
/**
* webkit_settings_get_enable_spatial_navigation:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-spatial-navigation property.
*
* Returns: %TRUE If HTML5 spatial navigation support is enabled or %FALSE otherwise.
*
* Since: 2.2
*/
gboolean webkit_settings_get_enable_spatial_navigation(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->spatialNavigationEnabled();
}
/**
* webkit_settings_get_enable_mediasource:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-mediasource property.
*
* Returns: %TRUE If MediaSource support is enabled or %FALSE otherwise.
*
* Since: 2.4
*/
gboolean webkit_settings_get_enable_mediasource(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->mediaSourceEnabled();
}
/**
* webkit_settings_set_enable_mediasource:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-mediasource property.
*
* Since: 2.4
*/
void webkit_settings_set_enable_mediasource(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->mediaSourceEnabled();
if (currentValue == enabled)
return;
priv->preferences->setMediaSourceEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-mediasource");
}
/**
* webkit_settings_get_allow_file_access_from_file_urls:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:allow-file-access-from-file-urls property.
*
* Returns: %TRUE If file access from file URLs is allowed or %FALSE otherwise.
*
* Since: 2.10
*/
gboolean webkit_settings_get_allow_file_access_from_file_urls(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->allowFileAccessFromFileURLs();
}
/**
* webkit_settings_set_allow_file_access_from_file_urls:
* @settings: a #WebKitSettings
* @allowed: Value to be set
*
* Set the #WebKitSettings:allow-file-access-from-file-urls property.
*
* Since: 2.10
*/
void webkit_settings_set_allow_file_access_from_file_urls(WebKitSettings* settings, gboolean allowed)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->preferences->allowFileAccessFromFileURLs() == allowed)
return;
priv->preferences->setAllowFileAccessFromFileURLs(allowed);
g_object_notify(G_OBJECT(settings), "allow-file-access-from-file-urls");
}
/**
* webkit_settings_get_allow_universal_access_from_file_urls:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:allow-universal-access-from-file-urls property.
*
* Returns: %TRUE If universal access from file URLs is allowed or %FALSE otherwise.
*
* Since: 2.14
*/
gboolean webkit_settings_get_allow_universal_access_from_file_urls(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->allowUniversalAccessFromFileURLs();
}
/**
* webkit_settings_set_allow_universal_access_from_file_urls:
* @settings: a #WebKitSettings
* @allowed: Value to be set
*
* Set the #WebKitSettings:allow-universal-access-from-file-urls property.
*
* Since: 2.14
*/
void webkit_settings_set_allow_universal_access_from_file_urls(WebKitSettings* settings, gboolean allowed)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->preferences->allowUniversalAccessFromFileURLs() == allowed)
return;
priv->preferences->setAllowUniversalAccessFromFileURLs(allowed);
g_object_notify(G_OBJECT(settings), "allow-universal-access-from-file-urls");
}
#if PLATFORM(GTK)
/**
* webkit_settings_get_hardware_acceleration_policy:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:hardware-acceleration-policy property.
*
* Return: a #WebKitHardwareAccelerationPolicy
*
* Since: 2.16
*/
WebKitHardwareAccelerationPolicy webkit_settings_get_hardware_acceleration_policy(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND);
WebKitSettingsPrivate* priv = settings->priv;
if (!priv->preferences->acceleratedCompositingEnabled())
return WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER;
if (priv->preferences->forceCompositingMode())
return WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS;
return WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND;
}
/**
* webkit_settings_set_hardware_acceleration_policy:
* @settings: a #WebKitSettings
* @policy: a #WebKitHardwareAccelerationPolicy
*
* Set the #WebKitSettings:hardware-acceleration-policy property.
*
* Since: 2.16
*/
void webkit_settings_set_hardware_acceleration_policy(WebKitSettings* settings, WebKitHardwareAccelerationPolicy policy)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool changed = false;
switch (policy) {
case WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS:
if (!HardwareAccelerationManager::singleton().canUseHardwareAcceleration())
return;
if (!priv->preferences->acceleratedCompositingEnabled()) {
priv->preferences->setAcceleratedCompositingEnabled(true);
changed = true;
}
if (!priv->preferences->forceCompositingMode()) {
priv->preferences->setForceCompositingMode(true);
changed = true;
}
break;
case WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER:
if (HardwareAccelerationManager::singleton().forceHardwareAcceleration())
return;
if (priv->preferences->acceleratedCompositingEnabled()) {
priv->preferences->setAcceleratedCompositingEnabled(false);
changed = true;
}
if (priv->preferences->forceCompositingMode()) {
priv->preferences->setForceCompositingMode(false);
changed = true;
}
break;
case WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND:
if (!priv->preferences->acceleratedCompositingEnabled() && HardwareAccelerationManager::singleton().canUseHardwareAcceleration()) {
priv->preferences->setAcceleratedCompositingEnabled(true);
changed = true;
}
if (priv->preferences->forceCompositingMode() && !HardwareAccelerationManager::singleton().forceHardwareAcceleration()) {
priv->preferences->setForceCompositingMode(false);
changed = true;
}
break;
}
if (changed)
g_object_notify(G_OBJECT(settings), "hardware-acceleration-policy");
}
#endif // PLATFORM(GTK)
| 38.03758 | 147 | 0.680129 | ijsf |
3ab967d72f4e80ea5ef374a7ab3eccdd5bbfa3df | 3,283 | hpp | C++ | src/xercesc/dom/deprecated/DOM_RangeException.hpp | ksmyth/xerces-c | 245d0f626041add542ab7deabd6ba9c3e4641f6d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/xercesc/dom/deprecated/DOM_RangeException.hpp | ksmyth/xerces-c | 245d0f626041add542ab7deabd6ba9c3e4641f6d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/xercesc/dom/deprecated/DOM_RangeException.hpp | ksmyth/xerces-c | 245d0f626041add542ab7deabd6ba9c3e4641f6d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DOM_RangeException.hpp 568078 2007-08-21 11:43:25Z amassari $
*/
#ifndef DOM_RangeException_HEADER_GUARD_
#define DOM_RangeException_HEADER_GUARD_
#include "DOM_DOMException.hpp"
XERCES_CPP_NAMESPACE_BEGIN
/**
* Encapsulate range related DOM error or warning. DOM level 2 implementation.
*
* <p> The DOM will create and throw an instance of DOM_RangeException
* when an error condition in range is detected. Exceptions can occur
* when an application directly manipulates the range elements in DOM document
* tree that is produced by the parser.
*
* <p>Unlike the other classes in the C++ DOM API, DOM_RangeException
* is NOT a reference to an underlying implementation class, and
* does not provide automatic memory management. Code that catches
* a DOM Range exception is responsible for deleting it, or otherwise
* arranging for its disposal.
*
*/
class DEPRECATED_DOM_EXPORT DOM_RangeException : public DOM_DOMException {
public:
/** @name Enumerators for DOM Range Exceptions */
//@{
enum RangeExceptionCode {
BAD_BOUNDARYPOINTS_ERR = 1,
INVALID_NODE_TYPE_ERR = 2
};
//@}
public:
/** @name Constructors and assignment operator */
//@{
/**
* Default constructor for DOM_RangeException.
*
*/
DOM_RangeException();
/**
* Constructor which takes an error code and a message.
*
* @param code The error code which indicates the exception
* @param message The string containing the error message
*/
DOM_RangeException(RangeExceptionCode code, const DOMString &message);
/**
* Copy constructor.
*
* @param other The object to be copied.
*/
DOM_RangeException(const DOM_RangeException &other);
//@}
/** @name Destructor. */
//@{
/**
* Destructor for DOM_RangeException. Applications are responsible
* for deleting DOM_RangeException objects that they catch after they
* have completed their exception processing.
*
*/
virtual ~DOM_RangeException();
//@}
/** @name Public variables. */
//@{
/**
* A code value, from the set defined by the RangeExceptionCode enum,
* indicating the type of error that occured.
*/
RangeExceptionCode code;
//@}
};
XERCES_CPP_NAMESPACE_END
#endif
| 30.971698 | 80 | 0.670423 | ksmyth |
3ac3a182940b0e79008ca76a10863f6924418311 | 2,177 | cpp | C++ | rosbag2_cpp/src/rosbag2_cpp/cache/cache_consumer.cpp | youliangtan/rosbag2 | 140169befa6f7179a49a6cfd312f48db47094a23 | [
"Apache-2.0"
] | null | null | null | rosbag2_cpp/src/rosbag2_cpp/cache/cache_consumer.cpp | youliangtan/rosbag2 | 140169befa6f7179a49a6cfd312f48db47094a23 | [
"Apache-2.0"
] | 14 | 2021-11-30T00:30:00.000Z | 2022-03-22T14:06:55.000Z | rosbag2_cpp/src/rosbag2_cpp/cache/cache_consumer.cpp | youliangtan/rosbag2 | 140169befa6f7179a49a6cfd312f48db47094a23 | [
"Apache-2.0"
] | 3 | 2022-01-25T15:02:52.000Z | 2022-03-13T22:51:04.000Z | // Copyright 2020, Robotec.ai sp. z o.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include "rosbag2_cpp/cache/cache_consumer.hpp"
#include "rosbag2_cpp/logging.hpp"
namespace rosbag2_cpp
{
namespace cache
{
CacheConsumer::CacheConsumer(
std::shared_ptr<MessageCacheInterface> message_cache,
consume_callback_function_t consume_callback)
: message_cache_(message_cache),
consume_callback_(consume_callback)
{
consumer_thread_ = std::thread(&CacheConsumer::exec_consuming, this);
}
CacheConsumer::~CacheConsumer()
{
stop();
}
void CacheConsumer::stop()
{
message_cache_->begin_flushing();
is_stop_issued_ = true;
ROSBAG2_CPP_LOG_INFO_STREAM(
"Writing remaining messages from cache to the bag. It may take a while");
if (consumer_thread_.joinable()) {
consumer_thread_.join();
}
message_cache_->done_flushing();
}
void CacheConsumer::start()
{
is_stop_issued_ = false;
if (!consumer_thread_.joinable()) {
consumer_thread_ = std::thread(&CacheConsumer::exec_consuming, this);
}
}
void CacheConsumer::exec_consuming()
{
bool exit_flag = false;
bool flushing = false;
while (!exit_flag) {
message_cache_->wait_for_data();
message_cache_->swap_buffers();
// Get the current consumer buffer.
auto consumer_buffer = message_cache_->get_consumer_buffer();
consume_callback_(consumer_buffer->data());
consumer_buffer->clear();
message_cache_->release_consumer_buffer();
if (flushing) {exit_flag = true;} // this was the final run
if (is_stop_issued_) {flushing = true;} // run one final time to flush
}
}
} // namespace cache
} // namespace rosbag2_cpp
| 26.876543 | 77 | 0.734497 | youliangtan |
3ac3f0c2fed63182b0b49f0cd779a79f7eef3b61 | 8,742 | cpp | C++ | src/frameworks/wilhelm/src/itf/IRecord.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | src/frameworks/wilhelm/src/itf/IRecord.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | src/frameworks/wilhelm/src/itf/IRecord.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /*
* Copyright (C) 2010 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.
*/
/* Record implementation */
#include "sles_allinclusive.h"
static SLresult IRecord_SetRecordState(SLRecordItf self, SLuint32 state)
{
SL_ENTER_INTERFACE
switch (state) {
case SL_RECORDSTATE_STOPPED:
case SL_RECORDSTATE_PAUSED:
case SL_RECORDSTATE_RECORDING:
{
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
thiz->mState = state;
#ifdef ANDROID
android_audioRecorder_setRecordState(InterfaceToCAudioRecorder(thiz), state);
#endif
interface_unlock_exclusive(thiz);
result = SL_RESULT_SUCCESS;
}
break;
default:
result = SL_RESULT_PARAMETER_INVALID;
break;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetRecordState(SLRecordItf self, SLuint32 *pState)
{
SL_ENTER_INTERFACE
IRecord *thiz = (IRecord *) self;
if (NULL == pState) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
interface_lock_shared(thiz);
SLuint32 state = thiz->mState;
interface_unlock_shared(thiz);
*pState = state;
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_SetDurationLimit(SLRecordItf self, SLmillisecond msec)
{
SL_ENTER_INTERFACE
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
if (thiz->mDurationLimit != msec) {
thiz->mDurationLimit = msec;
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetPosition(SLRecordItf self, SLmillisecond *pMsec)
{
SL_ENTER_INTERFACE
if (NULL == pMsec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
SLmillisecond position;
interface_lock_shared(thiz);
#ifdef ANDROID
// Android does not use the mPosition field for audio recorders
if (SL_OBJECTID_AUDIORECORDER == InterfaceToObjectID(thiz)) {
android_audioRecorder_getPosition(InterfaceToCAudioRecorder(thiz), &position);
} else {
position = thiz->mPosition;
}
#else
position = thiz->mPosition;
#endif
interface_unlock_shared(thiz);
*pMsec = position;
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_RegisterCallback(SLRecordItf self, slRecordCallback callback,
void *pContext)
{
SL_ENTER_INTERFACE
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
thiz->mCallback = callback;
thiz->mContext = pContext;
interface_unlock_exclusive(thiz);
result = SL_RESULT_SUCCESS;
SL_LEAVE_INTERFACE
}
static SLresult IRecord_SetCallbackEventsMask(SLRecordItf self, SLuint32 eventFlags)
{
SL_ENTER_INTERFACE
if (eventFlags & ~(
SL_RECORDEVENT_HEADATLIMIT |
SL_RECORDEVENT_HEADATMARKER |
SL_RECORDEVENT_HEADATNEWPOS |
SL_RECORDEVENT_HEADMOVING |
SL_RECORDEVENT_HEADSTALLED |
SL_RECORDEVENT_BUFFER_FULL)) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
if (thiz->mCallbackEventsMask != eventFlags) {
thiz->mCallbackEventsMask = eventFlags;
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetCallbackEventsMask(SLRecordItf self, SLuint32 *pEventFlags)
{
SL_ENTER_INTERFACE
if (NULL == pEventFlags) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_shared(thiz);
SLuint32 callbackEventsMask = thiz->mCallbackEventsMask;
interface_unlock_shared(thiz);
*pEventFlags = callbackEventsMask;
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_SetMarkerPosition(SLRecordItf self, SLmillisecond mSec)
{
SL_ENTER_INTERFACE
if (SL_TIME_UNKNOWN == mSec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
bool significant = false;
interface_lock_exclusive(thiz);
if (thiz->mMarkerPosition != mSec) {
thiz->mMarkerPosition = mSec;
if (thiz->mCallbackEventsMask & SL_PLAYEVENT_HEADATMARKER) {
significant = true;
}
}
if (significant) {
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_ClearMarkerPosition(SLRecordItf self)
{
SL_ENTER_INTERFACE
IRecord *thiz = (IRecord *) self;
bool significant = false;
interface_lock_exclusive(thiz);
// clearing the marker position is equivalent to setting the marker to SL_TIME_UNKNOWN
if (thiz->mMarkerPosition != SL_TIME_UNKNOWN) {
thiz->mMarkerPosition = SL_TIME_UNKNOWN;
if (thiz->mCallbackEventsMask & SL_PLAYEVENT_HEADATMARKER) {
significant = true;
}
}
if (significant) {
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetMarkerPosition(SLRecordItf self, SLmillisecond *pMsec)
{
SL_ENTER_INTERFACE
if (NULL == pMsec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_shared(thiz);
SLmillisecond markerPosition = thiz->mMarkerPosition;
interface_unlock_shared(thiz);
*pMsec = markerPosition;
if (SL_TIME_UNKNOWN == markerPosition) {
result = SL_RESULT_PRECONDITIONS_VIOLATED;
} else {
result = SL_RESULT_SUCCESS;
}
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_SetPositionUpdatePeriod(SLRecordItf self, SLmillisecond mSec)
{
SL_ENTER_INTERFACE
if (0 == mSec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
if (thiz->mPositionUpdatePeriod != mSec) {
thiz->mPositionUpdatePeriod = mSec;
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetPositionUpdatePeriod(SLRecordItf self, SLmillisecond *pMsec)
{
SL_ENTER_INTERFACE
if (NULL == pMsec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_shared(thiz);
SLmillisecond positionUpdatePeriod = thiz->mPositionUpdatePeriod;
interface_unlock_shared(thiz);
*pMsec = positionUpdatePeriod;
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static const struct SLRecordItf_ IRecord_Itf = {
IRecord_SetRecordState,
IRecord_GetRecordState,
IRecord_SetDurationLimit,
IRecord_GetPosition,
IRecord_RegisterCallback,
IRecord_SetCallbackEventsMask,
IRecord_GetCallbackEventsMask,
IRecord_SetMarkerPosition,
IRecord_ClearMarkerPosition,
IRecord_GetMarkerPosition,
IRecord_SetPositionUpdatePeriod,
IRecord_GetPositionUpdatePeriod
};
void IRecord_init(void *self)
{
IRecord *thiz = (IRecord *) self;
thiz->mItf = &IRecord_Itf;
thiz->mState = SL_RECORDSTATE_STOPPED;
thiz->mDurationLimit = 0;
thiz->mPosition = (SLmillisecond) 0;
thiz->mCallback = NULL;
thiz->mContext = NULL;
thiz->mCallbackEventsMask = 0;
thiz->mMarkerPosition = SL_TIME_UNKNOWN;
thiz->mPositionUpdatePeriod = 1000; // per spec
}
| 26.981481 | 90 | 0.676847 | dAck2cC2 |
3ac5f4c99e4f14bbff71d760129abf7f22f09de3 | 147 | cpp | C++ | assets/listings/item42-2.cpp | feserr/ResumenEffectiveCpp | 8c535b2c9acc53fc117d38e35e1dd2cb7c8750fc | [
"BSD-2-Clause"
] | null | null | null | assets/listings/item42-2.cpp | feserr/ResumenEffectiveCpp | 8c535b2c9acc53fc117d38e35e1dd2cb7c8750fc | [
"BSD-2-Clause"
] | null | null | null | assets/listings/item42-2.cpp | feserr/ResumenEffectiveCpp | 8c535b2c9acc53fc117d38e35e1dd2cb7c8750fc | [
"BSD-2-Clause"
] | null | null | null | template<typename C>
void print2nd(const C& container) {
if (container.size() > 2) {
C::const_iterator iter(container.begin());
...
}
} | 21 | 46 | 0.632653 | feserr |
3ac637de6c0ff0e9fef3fe12e8118a0cca33519a | 10,305 | cpp | C++ | src/renderer/src/SimpleRenderModeFactory.cpp | Ashimaru/narnia_engine | 66419b9e19a05546616b4450b12cb5f426dd6be7 | [
"MIT"
] | null | null | null | src/renderer/src/SimpleRenderModeFactory.cpp | Ashimaru/narnia_engine | 66419b9e19a05546616b4450b12cb5f426dd6be7 | [
"MIT"
] | null | null | null | src/renderer/src/SimpleRenderModeFactory.cpp | Ashimaru/narnia_engine | 66419b9e19a05546616b4450b12cb5f426dd6be7 | [
"MIT"
] | null | null | null | #include "SimpleRenderModeFactory.h"
#include "LoggerAPI.h"
#include "Vertex.h"
#include <array>
#include <cassert>
using std::array;
SimpleRenderModeFactory::SimpleRenderModeFactory(GPUPtr &gpu, const ScenePtr &scene) :
m_gpu(gpu),
m_scene(scene)
{
}
SimpleRenderMode SimpleRenderModeFactory::createRenderMode(vk::Format swapchainFormat, vk::Extent2D extent, const std::vector<vk::PipelineShaderStageCreateInfo> &shaders)
{
bool succeed = createRenderPass(swapchainFormat);
assert(succeed);
createPipelineLayout();
auto viewport = vk::Viewport();
viewport.setWidth((float)extent.width);
viewport.setHeight((float)extent.height);
viewport.setX(0);
viewport.setY(0);
viewport.setMinDepth(0.0f);
viewport.setMaxDepth(1.0f);
auto scissors = vk::Rect2D();
scissors.setOffset({ 0,0 });
scissors.setExtent(extent);
succeed = createPipeline(shaders, viewport, scissors);
assert(succeed);
succeed = createSwapchain(extent);
assert(succeed);
createCommandPool();
recordCommandBuffers();
return m_result;
}
void SimpleRenderModeFactory::recordCommandBuffers()
{
m_result.commandBuffers.resize(m_result.swapchainFramebuffers.size());
auto commandBufferAllocInfo = vk::CommandBufferAllocateInfo();
commandBufferAllocInfo.setCommandBufferCount(static_cast<uint32_t>(m_result.commandBuffers.size()));
commandBufferAllocInfo.setCommandPool(m_result.commandPool);
commandBufferAllocInfo.setLevel(vk::CommandBufferLevel::ePrimary);
m_gpu->createCommandBuffers(commandBufferAllocInfo, m_result.commandBuffers.data());
for (size_t i = 0; i < m_result.commandBuffers.size(); ++i)
{
auto beginInfo = vk::CommandBufferBeginInfo();
beginInfo.setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
if (vk::Result::eSuccess != m_result.commandBuffers[i].begin(&beginInfo))
{
LoggerAPI::getLogger()->logCritical("Could not begin record command buffer");
}
auto renderPassBeginInfo = vk::RenderPassBeginInfo();
renderPassBeginInfo.setRenderPass(m_result.renderPass);
renderPassBeginInfo.setFramebuffer(m_result.swapchainFramebuffers[i]);
auto renderArea = vk::Rect2D({ 0,0 }, m_gpu->getPresentationExtent());
renderPassBeginInfo.setRenderArea(renderArea);
renderPassBeginInfo.setClearValueCount(1);
vk::ClearValue clearValues[] = { 0.0, 0.0, 0.0, 1.0 };
renderPassBeginInfo.setPClearValues(clearValues);
m_result.commandBuffers[i].beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline);
m_result.commandBuffers[i].bindPipeline(vk::PipelineBindPoint::eGraphics, m_result.pipeline);
for (const auto &ro : m_scene->renderableObjects)
{
vk::DeviceSize offset[] = { 0 };
m_result.commandBuffers[i].bindVertexBuffers(0, 1, &ro->sharedBuffer, offset);
m_result.commandBuffers[i].bindIndexBuffer(ro->sharedBuffer, ro->vertexOffset, vk::IndexType::eUint32);
m_result.commandBuffers[i].drawIndexed(ro->indexCount, 1, 0, 0, 0);
}
m_result.commandBuffers[i].endRenderPass();
m_result.commandBuffers[i].end();
}
}
bool SimpleRenderModeFactory::createRenderPass(vk::Format swapchainFormat)
{
auto colorAttachment = vk::AttachmentDescription();
colorAttachment.setFormat(swapchainFormat);
colorAttachment.setSamples(vk::SampleCountFlagBits::e1);
colorAttachment.setLoadOp(vk::AttachmentLoadOp::eClear);
colorAttachment.setStoreOp(vk::AttachmentStoreOp::eStore);
colorAttachment.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare);
colorAttachment.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare);
colorAttachment.setInitialLayout(vk::ImageLayout::eUndefined);
colorAttachment.setFinalLayout(vk::ImageLayout::ePresentSrcKHR);
auto attatchmentRef = vk::AttachmentReference();
attatchmentRef.setAttachment(0);
attatchmentRef.setLayout(vk::ImageLayout::eColorAttachmentOptimal);
auto subpassDesc = vk::SubpassDescription();
subpassDesc.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics);
subpassDesc.setColorAttachmentCount(1);
subpassDesc.setPColorAttachments(&attatchmentRef);
auto subpassDependency = vk::SubpassDependency();
subpassDependency.setSrcSubpass(VK_SUBPASS_EXTERNAL);
subpassDependency.setDstSubpass(0);
subpassDependency.setSrcStageMask(vk::PipelineStageFlags(vk::PipelineStageFlagBits::eColorAttachmentOutput));
subpassDependency.setSrcAccessMask(vk::AccessFlags(0));
subpassDependency.setDstStageMask(vk::PipelineStageFlags(vk::PipelineStageFlagBits::eColorAttachmentOutput));
subpassDependency.setDstAccessMask(vk::AccessFlags(vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite));
auto renderPassInfo = vk::RenderPassCreateInfo();
renderPassInfo.setSubpassCount(1);
renderPassInfo.setPSubpasses(&subpassDesc);
renderPassInfo.setAttachmentCount(1);
renderPassInfo.setPAttachments(&colorAttachment);
renderPassInfo.setDependencyCount(1);
renderPassInfo.setPDependencies(&subpassDependency);
m_gpu->createRenderPass(renderPassInfo, m_result.renderPass);
return true;
}
void SimpleRenderModeFactory::createPipelineLayout()
{
auto layoutCreateInfo = vk::PipelineLayoutCreateInfo();
layoutCreateInfo.setSetLayoutCount(0);
layoutCreateInfo.setPushConstantRangeCount(0);
m_gpu->createPipelineLayout(layoutCreateInfo, m_result.pipelineLayout);
}
bool SimpleRenderModeFactory::createPipeline(const std::vector<vk::PipelineShaderStageCreateInfo> &shaders, const vk::Viewport &viewport, const vk::Rect2D &scissors)
{
auto pipelineCreateInfo = vk::GraphicsPipelineCreateInfo();
pipelineCreateInfo.setStageCount(static_cast<uint32_t>(shaders.size()));
pipelineCreateInfo.setPStages(shaders.data());
auto bindingDescription = new vk::VertexInputBindingDescription();
bindingDescription->setBinding(0);
bindingDescription->setInputRate(vk::VertexInputRate::eVertex);
bindingDescription->setStride(sizeof(Vertex));
auto attributeDescriptions = array<vk::VertexInputAttributeDescription, 2>();
attributeDescriptions.at(0).setBinding(0);
attributeDescriptions.at(0).setFormat(vk::Format::eR32G32B32Sfloat);
attributeDescriptions.at(0).setLocation(0);
attributeDescriptions.at(0).setOffset(offsetof(Vertex, Vertex::postion));
attributeDescriptions.at(1).setBinding(0);
attributeDescriptions.at(1).setFormat(vk::Format::eR32G32B32A32Sfloat);
attributeDescriptions.at(1).setLocation(1);
attributeDescriptions.at(1).setOffset(offsetof(Vertex, Vertex::color));
auto vertexInputState = vk::PipelineVertexInputStateCreateInfo();
vertexInputState.setPVertexAttributeDescriptions(attributeDescriptions.data());
vertexInputState.setPVertexBindingDescriptions(bindingDescription);
vertexInputState.setVertexAttributeDescriptionCount(static_cast<uint32_t>(attributeDescriptions.size()));
vertexInputState.setVertexBindingDescriptionCount(1);
pipelineCreateInfo.setPVertexInputState(&vertexInputState);
auto inputAssemblyState = vk::PipelineInputAssemblyStateCreateInfo();
inputAssemblyState.setTopology(vk::PrimitiveTopology::eTriangleList);
inputAssemblyState.setPrimitiveRestartEnable(false);
pipelineCreateInfo.setPInputAssemblyState(&inputAssemblyState);
auto viewportState = vk::PipelineViewportStateCreateInfo();
viewportState.setViewportCount(1);
viewportState.setScissorCount(1);
viewportState.setPScissors(&scissors);
viewportState.setPViewports(&viewport);
pipelineCreateInfo.setPViewportState(&viewportState);
auto rasteizerState = vk::PipelineRasterizationStateCreateInfo();
rasteizerState.setDepthClampEnable(false);
rasteizerState.setRasterizerDiscardEnable(false);
rasteizerState.setPolygonMode(vk::PolygonMode::eFill);
rasteizerState.setLineWidth(1.0f);
rasteizerState.setCullMode(vk::CullModeFlagBits::eBack);
rasteizerState.setFrontFace(vk::FrontFace::eClockwise);
rasteizerState.setDepthBiasEnable(false);
pipelineCreateInfo.setPRasterizationState(&rasteizerState);
auto multisampleState = vk::PipelineMultisampleStateCreateInfo();
multisampleState.setSampleShadingEnable(false);
multisampleState.setRasterizationSamples(vk::SampleCountFlagBits::e1);
pipelineCreateInfo.setPMultisampleState(&multisampleState);
pipelineCreateInfo.setPDepthStencilState(nullptr);
auto attachState = vk::PipelineColorBlendAttachmentState();
attachState.setColorWriteMask(vk::ColorComponentFlags(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA));
attachState.setBlendEnable(false);
attachState.setSrcAlphaBlendFactor(vk::BlendFactor::eOne);
attachState.setDstAlphaBlendFactor(vk::BlendFactor::eZero);
attachState.setColorBlendOp(vk::BlendOp::eAdd);
attachState.setAlphaBlendOp(vk::BlendOp::eAdd);
auto colorBlendState = vk::PipelineColorBlendStateCreateInfo();
colorBlendState.setLogicOpEnable(false);
colorBlendState.setLogicOp(vk::LogicOp::eCopy);
colorBlendState.setBlendConstants({ 0.0f, 0.0f, 0.0f, 0.0f });
colorBlendState.setAttachmentCount(1);
colorBlendState.setPAttachments(&attachState);
pipelineCreateInfo.setPColorBlendState(&colorBlendState);
pipelineCreateInfo.setPDynamicState(nullptr); //not supported
pipelineCreateInfo.setLayout(m_result.pipelineLayout);
pipelineCreateInfo.setRenderPass(m_result.renderPass);
pipelineCreateInfo.setSubpass(0);
m_gpu->createPipeline(pipelineCreateInfo, m_result.pipeline);
return true;
}
bool SimpleRenderModeFactory::createSwapchain(vk::Extent2D extent)
{
m_result.swapchainFramebuffers.resize(m_gpu->getSwapchainImagesCount());
for (int i = 0; i < m_result.swapchainFramebuffers.size(); ++i)
{
auto createInfo = vk::FramebufferCreateInfo();
createInfo.setRenderPass(m_result.renderPass);
createInfo.setAttachmentCount(1);
createInfo.setWidth(extent.width);
createInfo.setHeight(extent.height);
createInfo.setLayers(1);
m_gpu->createFramebuffer(createInfo, i, m_result.swapchainFramebuffers[i]);
}
return true;
}
void SimpleRenderModeFactory::createCommandPool()
{
m_gpu->createGraphicsCommandPool(m_result.commandPool);
}
bool createCommandBuffers()
{
return false;
}
bool createSyncObjects()
{
return false;
}
| 36.803571 | 171 | 0.787579 | Ashimaru |
3ac652eda4f48a1019464c983ff25cd02ef7cc8f | 1,522 | cpp | C++ | src/tracker/src/track.cpp | apennisi/mctracker | 29a89046f796f84eac922b2dc9cf4cd6c7aebb6b | [
"MIT"
] | 16 | 2019-08-04T04:29:12.000Z | 2022-03-07T02:18:49.000Z | src/tracker/src/track.cpp | apennisi/mctracker | 29a89046f796f84eac922b2dc9cf4cd6c7aebb6b | [
"MIT"
] | 3 | 2020-06-03T02:15:08.000Z | 2021-01-07T03:31:10.000Z | src/tracker/src/track.cpp | apennisi/mctracker | 29a89046f796f84eac922b2dc9cf4cd6c7aebb6b | [
"MIT"
] | 1 | 2021-01-06T03:33:05.000Z | 2021-01-06T03:33:05.000Z | #include "track.h"
using namespace mctracker::tracker;
Track
::Track(const float& _x, const float& _y, const KalmanParam& _param, const cv::Mat& h, const int cameraNum)
: Entity(), hist(h)
{
kf = std::shared_ptr<KalmanFilter>(new KalmanFilter(_x, _y, _param.getDt()));
ntimes_propagated = 0;
freezed = 0;
ntime_missed = 0;
isgood = false;
m_label = -1;
time = (double)cv::getTickCount();
sizes.resize(cameraNum);
}
const cv::Mat
Track::update()
{
if(points.size() > 0)
{
cv::Point2f result(0,0);
for(const auto& p : points)
{
result += p;
}
const auto& correction = correct(result.x, result.y);
points.clear();
return correction;
}
ntime_missed++;
return cv::Mat();
}
const cv::Mat
Track::predict()
{
const auto& prediction = kf->predict();
m_history.push_back(cv::Point2f(prediction.at<float>(0), prediction.at<float>(1)));
checkHistory();
return prediction;
}
const cv::Mat
Track::correct(const float& _x, const float& _y)
{
ntimes_propagated++;
time_in_sec = ((double) cv::getTickCount() - time) / cv::getTickFrequency();
return kf->correct(_x, _y);
}
const cv::Point2f
Track::getPoint()
{
const auto& prediction = kf->getPrediction();
return cv::Point2f(prediction.at<float>(0), prediction.at<float>(1));
}
const std::string
Track::label2string()
{
std::stringstream ss;
ss << m_label;
return ss.str();
}
| 21.138889 | 108 | 0.604468 | apennisi |
3aca6ffb1e33d1985823da482e25a1befeb417b7 | 556 | hpp | C++ | include/Table.hpp | DeynegaEkaterina/lab_01 | 60f6621f48a4ca2beb1a635c8d162631852f4877 | [
"MIT"
] | null | null | null | include/Table.hpp | DeynegaEkaterina/lab_01 | 60f6621f48a4ca2beb1a635c8d162631852f4877 | [
"MIT"
] | null | null | null | include/Table.hpp | DeynegaEkaterina/lab_01 | 60f6621f48a4ca2beb1a635c8d162631852f4877 | [
"MIT"
] | null | null | null | //
// Created by ekaterina on 08.10.2020.
//
// Copyright 2020 Your Name <ekaterina>
#ifndef INCLUDE_HEADER_HPP_
#define INCLUDE_HEADER_HPP_
#include <vector>
#include <string>
#include "Student.hpp"
class Table {
public:
explicit Table(const json& j);
~Table();
static Table parseFile(const std::string& s);
//вызов метода без создания экземпляра класса
size_t w_name, w_group, w_avg, w_debt, w_space;
void print(std::ostream& out) const;
std::vector<Student> m_students;
std::vector<size_t> m_w;
};
#endif // INCLUDE_HEADER_HPP_
| 18.533333 | 49 | 0.719424 | DeynegaEkaterina |
3acbe8e00fec917d08f548a155df54140c293df0 | 53,068 | cpp | C++ | src/tests/relay/t_relay_io_hdf5.cpp | aaroncblack/conduit | f54f834eb8aaff4fc97613e04cfdb360997867be | [
"BSD-3-Clause"
] | null | null | null | src/tests/relay/t_relay_io_hdf5.cpp | aaroncblack/conduit | f54f834eb8aaff4fc97613e04cfdb360997867be | [
"BSD-3-Clause"
] | null | null | null | src/tests/relay/t_relay_io_hdf5.cpp | aaroncblack/conduit | f54f834eb8aaff4fc97613e04cfdb360997867be | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) Lawrence Livermore National Security, LLC and other Conduit
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Conduit.
//-----------------------------------------------------------------------------
///
/// file: t_relay_io_hdf5.cpp
///
//-----------------------------------------------------------------------------
#include "conduit_relay.hpp"
#include "conduit_relay_io_hdf5.hpp"
#include "hdf5.h"
#include <iostream>
#include "gtest/gtest.h"
using namespace conduit;
using namespace conduit::relay;
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_by_file_name)
{
uint32 a_val = 20;
uint32 b_val = 8;
uint32 c_val = 13;
uint32 d_val = 121;
Node n;
n["a"] = a_val;
n["b"] = b_val;
n["c"] = c_val;
EXPECT_EQ(n["a"].as_uint32(), a_val);
EXPECT_EQ(n["b"].as_uint32(), b_val);
EXPECT_EQ(n["c"].as_uint32(), c_val);
// write our node as a group @ "myobj"
io::hdf5_write(n,"tout_hdf5_wr.hdf5:myobj");
// directly read our object
Node n_load;
io::hdf5_read("tout_hdf5_wr.hdf5:myobj",n_load);
n_load.print_detailed();
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
EXPECT_EQ(n_load["c"].as_uint32(), c_val);
Node n_load_2;
// read from root of hdf5 file
io::hdf5_read("tout_hdf5_wr.hdf5",n_load_2);
EXPECT_EQ(n_load_2["myobj/a"].as_uint32(), a_val);
EXPECT_EQ(n_load_2["myobj/b"].as_uint32(), b_val);
EXPECT_EQ(n_load_2["myobj/c"].as_uint32(), c_val);
Node n_load_generic;
// read from root of hdf5 file
io::load("tout_hdf5_wr.hdf5",n_load_generic);
EXPECT_EQ(n_load_generic["myobj/a"].as_uint32(), a_val);
EXPECT_EQ(n_load_generic["myobj/b"].as_uint32(), b_val);
EXPECT_EQ(n_load_generic["myobj/c"].as_uint32(), c_val);
// save load from generic io interface
io::save(n_load_generic["myobj"],"tout_hdf5_wr_generic.hdf5:myobj");
n_load_generic["myobj/d"] = d_val;
io::load_merged("tout_hdf5_wr_generic.hdf5",n_load_generic);
EXPECT_EQ(n_load_generic["myobj/a"].as_uint32(), a_val);
EXPECT_EQ(n_load_generic["myobj/b"].as_uint32(), b_val);
EXPECT_EQ(n_load_generic["myobj/c"].as_uint32(), c_val);
EXPECT_EQ(n_load_generic["myobj/d"].as_uint32(), d_val);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_special_paths)
{
uint32 a_val = 20;
uint32 b_val = 8;
Node n;
n["a"] = a_val;
n["b"] = b_val;
EXPECT_EQ(n["a"].as_uint32(), a_val);
EXPECT_EQ(n["b"].as_uint32(), b_val);
// write our node as a group @ "/myobj"
io::hdf5_write(n,"tout_hdf5_wr_special_paths_1.hdf5:/myobj");
// write our node as a group @ "/"
// make sure "/" works
io::hdf5_write(n,"tout_hdf5_wr_special_paths_2.hdf5:/");
// make sure empty after ":" this works
io::hdf5_write(n,"tout_hdf5_wr_special_paths_3.hdf5:");
Node n_load;
io::hdf5_read("tout_hdf5_wr_special_paths_2.hdf5:/",n_load);
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
n_load.reset();
io::hdf5_read("tout_hdf5_wr_special_paths_2.hdf5:/",n_load);
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
n_load.reset();
io::hdf5_read("tout_hdf5_wr_special_paths_2.hdf5:",n_load);
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_string)
{
uint32 a_val = 20;
std::string s_val = "{string value!}";
Node n;
n["a"] = a_val;
n["s"] = s_val;
EXPECT_EQ(n["a"].as_uint32(), a_val);
EXPECT_EQ(n["s"].as_string(), s_val);
// write our node as a group @ "myobj"
io::hdf5_write(n,"tout_hdf5_wr_string.hdf5:myobj");
Node n_out;
io::hdf5_read("tout_hdf5_wr_string.hdf5:myobj",n_out);
EXPECT_EQ(n_out["a"].as_uint32(), a_val);
EXPECT_EQ(n_out["s"].as_string(), s_val);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_array)
{
Node n_in(DataType::float64(10));
float64_array val_in = n_in.value();
for(index_t i=0;i<10;i++)
{
val_in[i] = 3.1415 * i;
}
// write our node as a group @ "myobj"
io::hdf5_write(n_in,"tout_hdf5_wr_array.hdf5:myobj");
Node n_out;
io::hdf5_read("tout_hdf5_wr_array.hdf5:myobj",n_out);
float64_array val_out = n_out.value();
for(index_t i=0;i<10;i++)
{
EXPECT_EQ(val_in[i],val_out[i]);
}
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_and_read_conduit_leaf_to_hdf5_dataset_handle)
{
std::string ofname = "tout_hdf5_wr_conduit_leaf_to_hdf5_dataset_handle.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// create a dataset for a 16-bit signed integer array with 2 elements
hid_t h5_dtype = H5T_NATIVE_SHORT;
hsize_t num_eles = 2;
hid_t h5_dspace_id = H5Screate_simple(1,
&num_eles,
NULL);
// create new dataset
hid_t h5_dset_id = H5Dcreate(h5_file_id,
"mydata",
h5_dtype,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
Node n;
n.set(DataType::c_short(2));
short_array vals = n.value();
vals[0] = -16;
vals[1] = -16;
// this should succeed
io::hdf5_write(n,h5_dset_id);
// this should also succeed
vals[1] = 16;
io::hdf5_write(n,h5_dset_id);
n.set(DataType::uint16(10));
// this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id),Error);
Node n_read;
io::hdf5_read(h5_dset_id,n_read);
// check values of data
short_array read_vals = n_read.value();
EXPECT_EQ(-16,read_vals[0]);
EXPECT_EQ(16,read_vals[1]);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_and_read_conduit_leaf_to_extendible_hdf5_dataset_handle_with_offset)
{
std::string ofname = "tout_hdf5_wr_conduit_leaf_to_hdf5_extendible_dataset_handle_with_offset.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// create a dataset for a 16-bit signed integer array with 2 elements
hid_t h5_dtype = H5T_NATIVE_SHORT;
hsize_t num_eles = 2;
hsize_t dims[1] = {H5S_UNLIMITED};
hid_t h5_dspace_id = H5Screate_simple(1,
&num_eles,
dims);
/*
* Modify dataset creation properties, i.e. enable chunking.
*/
hid_t cparms;
hsize_t chunk_dims[1] = {1};
cparms = H5Pcreate (H5P_DATASET_CREATE);
H5Pset_chunk(cparms, 1, chunk_dims);
// create new dataset
hid_t h5_dset_id = H5Dcreate1(h5_file_id,
"mydata",
h5_dtype,
h5_dspace_id,
cparms);
Node n, opts;
n.set(DataType::c_short(2));
short_array vals = n.value();
vals[0] = -16;
vals[1] = -15;
// this should succeed
io::hdf5_write(n,h5_dset_id);
vals[0] = 1;
vals[1] = 2;
opts["offset"] = 2;
opts["stride"] = 1;
io::hdf5_write(n,h5_dset_id,opts);
Node n_read, opts_read;
io::hdf5_read_info(h5_dset_id,opts_read,n_read);
EXPECT_EQ(4,(int) n_read["num_elements"].to_value());
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
short_array read_vals = n_read.value();
EXPECT_EQ(-16,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(1,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
opts_read["offset"] = 2;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(1,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
vals[0] = -1;
vals[1] = -3;
opts["offset"] = 0;
opts["stride"] = 2;
io::hdf5_write(n,h5_dset_id,opts);
opts_read["offset"] = 0;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(-1,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(-3,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
vals[0] = 5;
vals[1] = 6;
opts["offset"] = 7;
opts["stride"] = 1;
io::hdf5_write(n,h5_dset_id,opts);
opts_read["offset"] = 0;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(-1,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(-3,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
EXPECT_EQ(0,read_vals[4]);
EXPECT_EQ(0,read_vals[5]);
EXPECT_EQ(0,read_vals[6]);
EXPECT_EQ(5,read_vals[7]);
EXPECT_EQ(6,read_vals[8]);
opts["offset"] = -1;
opts["stride"] = 2;
opts_read["offset"] = -1;
opts_read["stride"] = 2;
//this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id,opts),Error);
EXPECT_THROW(io::hdf5_read(h5_dset_id,opts_read,n_read),Error);
opts["offset"] = 0;
opts["stride"] = 0;
opts_read["offset"] = 0;
opts_read["stride"] = 0;
//this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id,opts),Error);
EXPECT_THROW(io::hdf5_read(h5_dset_id,opts_read,n_read),Error);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_and_read_conduit_leaf_to_fixed_hdf5_dataset_handle_with_offset)
{
std::string ofname = "tout_hdf5_wr_conduit_leaf_to_fixed_hdf5_dataset_handle_with_offset.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// create a dataset for a 16-bit signed integer array with 2 elements
hid_t h5_dtype = H5T_NATIVE_SHORT;
hsize_t num_eles = 2;
hid_t h5_dspace_id = H5Screate_simple(1,
&num_eles,
NULL);
// create new dataset
hid_t h5_dset_id = H5Dcreate(h5_file_id,
"mydata",
h5_dtype,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
Node n, opts;
n.set(DataType::c_short(2));
short_array vals = n.value();
vals[0] = -16;
vals[1] = -15;
// this should succeed
io::hdf5_write(n,h5_dset_id);
vals[0] = 1;
vals[1] = 2;
opts["offset"] = 2;
opts["stride"] = 1;
io::hdf5_write(n,h5_dset_id,opts);
Node n_read, opts_read;
io::hdf5_read_info(h5_dset_id,opts_read,n_read);
EXPECT_EQ(4,(int) n_read["num_elements"].to_value());
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
short_array read_vals = n_read.value();
EXPECT_EQ(-16,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(1,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
opts_read["offset"] = 2;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(1,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
vals[0] = -1;
vals[1] = -3;
opts["offset"] = 0;
opts["stride"] = 2;
io::hdf5_write(n,h5_dset_id,opts);
opts_read["offset"] = 0;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(-1,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(-3,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
vals[0] = 5;
vals[1] = 6;
opts["offset"] = 7;
opts["stride"] = 1;
io::hdf5_write(n,h5_dset_id,opts);
opts_read["offset"] = 0;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(-1,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(-3,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
EXPECT_EQ(0,read_vals[4]);
EXPECT_EQ(0,read_vals[5]);
EXPECT_EQ(0,read_vals[6]);
EXPECT_EQ(5,read_vals[7]);
EXPECT_EQ(6,read_vals[8]);
opts["offset"] = -1;
opts["stride"] = 2;
opts_read["offset"] = -1;
opts_read["stride"] = 2;
//this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id,opts),Error);
EXPECT_THROW(io::hdf5_read(h5_dset_id,opts_read,n_read),Error);
opts["offset"] = 0;
opts["stride"] = 0;
opts_read["offset"] = 0;
opts_read["stride"] = 0;
//this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id,opts),Error);
EXPECT_THROW(io::hdf5_read(h5_dset_id,opts_read,n_read),Error);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_conduit_object_to_hdf5_group_handle_with_offset)
{
std::string ofname = "tout_hdf5_wr_conduit_object_to_hdf5_group_handle_with_offset.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
hid_t h5_group_id = H5Gcreate(h5_file_id,
"mygroup",
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
Node n, opts;
n["a/b"].set(DataType::int16(2));
int16_array vals = n["a/b"].value();
vals[0] =-16;
vals[1] =-16;
// this should succeed
io::hdf5_write(n,h5_group_id);
n["a/c"] = "mystring";
// this should also succeed
vals[1] = 16;
io::hdf5_write(n,h5_group_id);
Node n_read;
io::hdf5_read(h5_group_id,n_read);
n["a/b"].set(DataType::int16(10));
// this should fail
EXPECT_THROW(io::hdf5_write(n,h5_group_id),Error);
n["a/b"].set(DataType::int16(10));
vals = n["a/b"].value();
opts["offset"] = 5;
for (int i = 0; i < 10; i++) {
vals[i] = i + 1;
}
io::hdf5_write(n,h5_group_id,opts);
io::hdf5_read(h5_group_id,n_read);
// check values of data with offset
int16_array read_vals = n_read["a/b"].value();
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[i + 5]);
}
// this is also offset
EXPECT_EQ("mystrmystring",n_read["a/c"].as_string());
opts["offset"] = 20;
opts["stride"] = 2;
for (int i = 0; i < 10; i++) {
vals[i] = i + 1;
}
n["a/d"].set(DataType::int16(5));
int16_array vals2 = n["a/d"].value();
for (int i = 0; i < 5; i++) {
vals2[i] = (i + 1) * -1;
}
io::hdf5_write(n,h5_group_id,opts);
io::hdf5_read(h5_group_id,n_read);
// check values of data
read_vals = n_read["a/b"].value();
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[i + 5]);
}
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[2*i + 20]);
}
read_vals = n_read["a/d"].value();
for (int i = 0; i < 5; i++) {
EXPECT_EQ((i + 1) * -1, read_vals[2*i + 20]);
}
Node n_read_info;
io::hdf5_read_info(h5_group_id,n_read_info);
EXPECT_EQ(39,(int) n_read_info["a/b/num_elements"].to_value());
EXPECT_EQ(37,(int) n_read_info["a/c/num_elements"].to_value());
EXPECT_EQ(29,(int) n_read_info["a/d/num_elements"].to_value());
// this doesn't change because the null-terminated character
// wasn't overwritten
EXPECT_EQ("mystrmystring",n_read["a/c"].as_string());
Node opts_read;
opts_read["offset"] = 5;
io::hdf5_read_info(h5_group_id,opts_read,n_read_info);
io::hdf5_read(h5_group_id,opts_read,n_read);
// check values of data
read_vals = n_read["a/b"].value();
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[i]);
}
EXPECT_EQ("mystring",n_read["a/c"].as_string());
EXPECT_EQ(34,(int) n_read_info["a/b/num_elements"].to_value());
EXPECT_EQ(32,(int) n_read_info["a/c/num_elements"].to_value());
opts_read["offset"] = 20;
opts_read["stride"] = 2;
io::hdf5_read_info(h5_group_id,opts_read,n_read_info);
io::hdf5_read(h5_group_id,opts_read,n_read);
// check values of data
read_vals = n_read["a/b"].value();
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[i]);
}
read_vals = n_read["a/d"].value();
for (int i = 0; i < 5; i++) {
EXPECT_EQ((i + 1) * -1, read_vals[i]);
}
EXPECT_EQ(10,(int) n_read_info["a/b/num_elements"].to_value());
EXPECT_EQ(5,(int) n_read_info["a/d/num_elements"].to_value());
opts_read["offset"] = 20;
opts_read["stride"] = 3;
io::hdf5_read_info(h5_group_id,opts_read,n_read_info);
io::hdf5_read(h5_group_id,opts_read,n_read);
// check values of data
read_vals = n_read["a/b"].value();
EXPECT_EQ(1, read_vals[0]);
EXPECT_EQ(4, read_vals[2]);
EXPECT_EQ(7, read_vals[4]);
EXPECT_EQ(10, read_vals[6]);
read_vals = n_read["a/d"].value();
EXPECT_EQ(-1, read_vals[0]);
EXPECT_EQ(-4, read_vals[2]);
EXPECT_EQ(7,(int) n_read_info["a/b/num_elements"].to_value());
EXPECT_EQ(3,(int) n_read_info["a/d/num_elements"].to_value());
H5Gclose(h5_group_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_conduit_object_to_hdf5_group_handle)
{
std::string ofname = "tout_hdf5_wr_conduit_object_to_hdf5_group_handle.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
hid_t h5_group_id = H5Gcreate(h5_file_id,
"mygroup",
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
Node n;
n["a/b"].set(DataType::int16(2));
int16_array vals = n["a/b"].value();
vals[0] =-16;
vals[1] =-16;
// this should succeed
io::hdf5_write(n,h5_group_id);
n["a/c"] = "mystring";
// this should also succeed
vals[1] = 16;
io::hdf5_write(n,h5_group_id);
n["a/b"].set(DataType::uint16(10));
// this should fail
EXPECT_THROW(io::hdf5_write(n,h5_group_id),Error);
Node n_read;
io::hdf5_read(h5_group_id,n_read);
// check values of data
int16_array read_vals = n_read["a/b"].value();
EXPECT_EQ(-16,read_vals[0]);
EXPECT_EQ(16,read_vals[1]);
EXPECT_EQ("mystring",n_read["a/c"].as_string());
H5Gclose(h5_group_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
// This variant tests when a caller code has already opened a HDF5 file
// and has a handle ready.
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_by_file_handle)
{
uint32 a_val = 20;
uint32 b_val = 8;
uint32 c_val = 13;
Node n;
n["a"] = a_val;
n["b"] = b_val;
n["c"] = c_val;
EXPECT_EQ(n["a"].as_uint32(), a_val);
EXPECT_EQ(n["b"].as_uint32(), b_val);
EXPECT_EQ(n["c"].as_uint32(), c_val);
std::string test_file_name = "tout_hdf5_write_read_by_file_handle.hdf5";
// Set up hdf5 file and group that caller code would already have.
hid_t h5_file_id = H5Fcreate(test_file_name.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// Prepare group that caller code wants conduit to save it's tree to that
// group. (could also specify group name for conduit to create via
// hdf5_path argument to write call.
hid_t h5_group_id = H5Gcreate(h5_file_id,
"sample_group_name",
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
io::hdf5_write(n,h5_group_id);
hid_t status = H5Gclose(h5_group_id);
// Another variant of this - caller code has a pre-existing group they
// want to write into, but they want to use the 'group name' arg to do it
// Relay should be able to write into existing group.
h5_group_id = H5Gcreate(h5_file_id,
"sample_group_name2",
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
io::hdf5_write(n,h5_file_id, "sample_group_name2");
status = H5Gclose(h5_group_id);
status = H5Fclose(h5_file_id);
h5_file_id = H5Fopen(test_file_name.c_str(),
H5F_ACC_RDONLY,
H5P_DEFAULT);
// Caller code switches to group it wants to read in. (could also
// specify group name for conduit to read out via hdf5_path arg to read
// call)
h5_group_id = H5Gopen(h5_file_id, "sample_group_name", 0);
Node n_load;
io::hdf5_read(h5_group_id, n_load);
status = H5Gclose(h5_group_id);
status = H5Fclose(h5_file_id);
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
EXPECT_EQ(n_load["c"].as_uint32(), c_val);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_to_existing_dset)
{
Node n_in(DataType::uint32(2));
uint32_array val_in = n_in.value();
val_in[0] = 1;
val_in[1] = 2;
// Set up hdf5 file and group that caller code would already have.
hid_t h5_file_id = H5Fcreate("tout_hdf5_wr_existing_dset.hdf5",
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
io::hdf5_write(n_in,h5_file_id,"myarray");
val_in[0] = 3;
val_in[1] = 4;
io::hdf5_write(n_in,h5_file_id,"myarray");
// trying to write an incompatible dataset will throw an error
Node n_incompat;
n_incompat = 64;
EXPECT_THROW(io::hdf5_write(n_incompat,h5_file_id,"myarray"),
conduit::Error);
H5Fclose(h5_file_id);
// check that the second set of values are the ones we get back
Node n_read;
io::hdf5_read("tout_hdf5_wr_existing_dset.hdf5:myarray",n_read);
uint32_array val = n_read.value();
EXPECT_EQ(val[0],3);
EXPECT_EQ(val[1],4);
Node n_w2;
n_w2["myarray"].set_external(n_read);
n_w2["a/b/c"].set_uint64(123);
// this should be compatible
io::hdf5_write(n_w2,"tout_hdf5_wr_existing_dset.hdf5");
n_read.reset();
io::hdf5_read("tout_hdf5_wr_existing_dset.hdf5",n_read);
uint32_array myarray_val = n_read["myarray"].value();
uint64 a_b_c_val = n_read["a/b/c"].value();
EXPECT_EQ(myarray_val[0],3);
EXPECT_EQ(myarray_val[1],4);
EXPECT_EQ(a_b_c_val,123);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_leaf_arrays)
{
Node n;
n["v_int8"].set(DataType::int8(5));
n["v_int16"].set(DataType::int16(5));
n["v_int32"].set(DataType::int32(5));
n["v_int64"].set(DataType::int64(5));
n["v_uint8"].set(DataType::uint8(5));
n["v_uint16"].set(DataType::uint16(5));
n["v_uint32"].set(DataType::uint32(5));
n["v_uint64"].set(DataType::uint64(5));
n["v_float32"].set(DataType::float32(5));
n["v_float64"].set(DataType::float64(5));
n["v_string"].set("my_string");
int8 *v_int8_ptr = n["v_int8"].value();
int16 *v_int16_ptr = n["v_int16"].value();
int32 *v_int32_ptr = n["v_int32"].value();
int64 *v_int64_ptr = n["v_int64"].value();
uint8 *v_uint8_ptr = n["v_uint8"].value();
uint16 *v_uint16_ptr = n["v_uint16"].value();
uint32 *v_uint32_ptr = n["v_uint32"].value();
uint64 *v_uint64_ptr = n["v_uint64"].value();
float32 *v_float32_ptr = n["v_float32"].value();
float64 *v_float64_ptr = n["v_float64"].value();
for(index_t i=0; i < 5; i++)
{
v_int8_ptr[i] = -8;
v_int16_ptr[i] = -16;
v_int32_ptr[i] = -32;
v_int64_ptr[i] = -64;
v_uint8_ptr[i] = 8;
v_uint16_ptr[i] = 16;
v_uint32_ptr[i] = 32;
v_uint64_ptr[i] = 64;
v_float32_ptr[i] = 32.0;
v_float64_ptr[i] = 64.0;
}
n.print_detailed();
io::hdf5_write(n,"tout_hdf5_wr_leaf_arrays.hdf5");
Node n_load;
io::hdf5_read("tout_hdf5_wr_leaf_arrays.hdf5",n_load);
n_load.print_detailed();
int8_array v_int8_out = n_load["v_int8"].value();
int16_array v_int16_out = n_load["v_int16"].value();
int32_array v_int32_out = n_load["v_int32"].value();
int64_array v_int64_out = n_load["v_int64"].value();
EXPECT_EQ(v_int8_out.number_of_elements(),5);
EXPECT_EQ(v_int16_out.number_of_elements(),5);
EXPECT_EQ(v_int32_out.number_of_elements(),5);
EXPECT_EQ(v_int64_out.number_of_elements(),5);
uint8_array v_uint8_out = n_load["v_uint8"].value();
uint16_array v_uint16_out = n_load["v_uint16"].value();
uint32_array v_uint32_out = n_load["v_uint32"].value();
uint64_array v_uint64_out = n_load["v_uint64"].value();
EXPECT_EQ(v_uint8_out.number_of_elements(),5);
EXPECT_EQ(v_uint16_out.number_of_elements(),5);
EXPECT_EQ(v_uint32_out.number_of_elements(),5);
EXPECT_EQ(v_uint64_out.number_of_elements(),5);
float32_array v_float32_out = n_load["v_float32"].value();
float64_array v_float64_out = n_load["v_float64"].value();
EXPECT_EQ(v_float32_out.number_of_elements(),5);
EXPECT_EQ(v_float64_out.number_of_elements(),5);
std::string v_string_out = n_load["v_string"].as_string();
EXPECT_EQ(v_string_out,"my_string");
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_empty)
{
Node n;
n["path/to/empty"];
n.print_detailed();
io::hdf5_write(n,"tout_hdf5_wr_empty.hdf5");
Node n_load;
io::hdf5_read("tout_hdf5_wr_empty.hdf5",n_load);
n_load.print_detailed();
EXPECT_EQ(n["path/to/empty"].dtype().id(),
n_load["path/to/empty"].dtype().id());
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, hdf5_write_zero_sized_leaf)
{
// this tests
Node n;
n["a"].set(DataType::float64(0));
n.print_detailed();
io::hdf5_write(n,"tout_hdf5_w_0.hdf5");
EXPECT_EQ(n["a"].dtype().number_of_elements(),0);
EXPECT_EQ(n["a"].dtype().id(),DataType::FLOAT64_ID);
Node n_load;
io::hdf5_read("tout_hdf5_w_0.hdf5",n_load);
n_load.print_detailed();
EXPECT_EQ(n_load["a"].dtype().number_of_elements(),0);
EXPECT_EQ(n_load["a"].dtype().id(),DataType::FLOAT64_ID);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_childless_object)
{
Node n;
n["path/to/empty"].set(DataType::object());
n.print_detailed();
io::hdf5_write(n,"tout_hdf5_wr_cl_obj.hdf5");
Node n_load;
io::hdf5_read("tout_hdf5_wr_cl_obj.hdf5",n_load);
n_load.print_detailed();
EXPECT_EQ(n["path/to/empty"].dtype().id(),
n_load["path/to/empty"].dtype().id());
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_test_write_incompat)
{
Node n;
n["a/b/leaf"] = DataType::uint32(2);
n["a/b/grp/leaf"].set_uint32(10);
uint32_array vals = n["a/b/leaf"].value();
vals[0] = 1;
vals[1] = 2;
io::hdf5_write(n,"tout_hdf5_test_write_incompat.hdf5");
n.print();
Node n2;
n2["a/b/leaf/v"] = DataType::float64(2);
n2["a/b/grp/leaf/v"].set_float64(10.0);
n2.print();
hid_t h5_file_id = H5Fopen("tout_hdf5_test_write_incompat.hdf5",
H5F_ACC_RDWR,
H5P_DEFAULT);
try
{
io::hdf5_write(n2,h5_file_id);
}
catch(Error &e)
{
CONDUIT_INFO(e.message());
}
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, auto_endian)
{
Node n;
n["a"].set_int64(12345689);
n["b"].set_int64(-12345689);
if(Endianness::machine_is_big_endian())
{
n.endian_swap_to_little();
}
else
{
n.endian_swap_to_big();
}
io::hdf5_write(n,"tout_hdf5_wr_opp_endian.hdf5");
Node n_load;
io::hdf5_read("tout_hdf5_wr_opp_endian.hdf5",n_load);
EXPECT_EQ(n_load["a"].as_int64(),12345689);
EXPECT_EQ(n_load["b"].as_int64(),-12345689);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, hdf5_path_exists)
{
std::string test_file_name = "tout_hdf5_wr_hdf5_path_exists.hdf5";
Node n;
n["a/b/c/d"] = 10;
n["a/b/c/f"] = 20;
io::hdf5_write(n,test_file_name);
hid_t h5_file_id = H5Fopen(test_file_name.c_str(),
H5F_ACC_RDONLY,
H5P_DEFAULT);
hid_t h5_grp_a = H5Gopen(h5_file_id, "a", 0);
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c/d"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c/f"));
EXPECT_TRUE(io::hdf5_has_path(h5_grp_a,"b"));
EXPECT_TRUE(io::hdf5_has_path(h5_grp_a,"b/c"));
EXPECT_TRUE(io::hdf5_has_path(h5_grp_a,"b/c/d"));
EXPECT_TRUE(io::hdf5_has_path(h5_grp_a,"b/c/f"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"a/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"a/b/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"a/b/c/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"a/b/c/d/e/f/g"));
EXPECT_FALSE(io::hdf5_has_path(h5_grp_a,"BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_grp_a,"b/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_grp_a,"b/c/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_grp_a,"b/c/d/e/f/g"));
H5Gclose(h5_grp_a);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, hdf5_create_append_methods)
{
std::string test_file_name = "tout_hdf5_open_append.hdf5";
utils::remove_path_if_exists(test_file_name);
Node n;
n["a/b/c/d"] = 10;
io::hdf5_write(n,test_file_name,true);
n.reset();
n["a/b/c/e"] = 20;
io::hdf5_write(n,test_file_name,true);
Node n_load;
io::hdf5_read(test_file_name,n_load);
EXPECT_TRUE(n_load.has_path("a"));
EXPECT_TRUE(n_load.has_path("a/b"));
EXPECT_TRUE(n_load.has_path("a/b/c"));
EXPECT_TRUE(n_load.has_path("a/b/c/d"));
EXPECT_TRUE(n_load.has_path("a/b/c/e"));
EXPECT_EQ(n_load["a/b/c/d"].to_int32(),10);
EXPECT_EQ(n_load["a/b/c/e"].to_int32(),20);
io::hdf5_write(n,test_file_name,false);
n_load.reset();
io::hdf5_read(test_file_name,n_load);
EXPECT_FALSE(n_load.has_path("a/b/c/d"));
EXPECT_EQ(n_load["a/b/c/e"].to_int32(),20);
n.reset();
n["a/b/c/d"] = 10;
io::hdf5_save(n,test_file_name);
n_load.reset();
io::hdf5_read(test_file_name,n_load);
EXPECT_FALSE(n_load.has_path("a/b/c/e"));
EXPECT_EQ(n_load["a/b/c/d"].to_int32(),10);
n.reset();
n["a/b/c/e"] = 20;
io::hdf5_write(n,test_file_name,true);
n.reset();
n["a/b/c/e"] = 20;
io::hdf5_append(n,test_file_name);
n_load.reset();
io::hdf5_read(test_file_name,n_load);
EXPECT_TRUE(n_load.has_path("a/b/c/d"));
EXPECT_TRUE(n_load.has_path("a/b/c/e"));
EXPECT_EQ(n_load["a/b/c/d"].to_int32(),10);
EXPECT_EQ(n_load["a/b/c/e"].to_int32(),20);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, hdf5_create_open_methods)
{
std::string test_file_name = "tout_hdf5_open_and_create.hdf5";
Node n;
n["a/b/c/d"] = 10;
hid_t h5_file_id = io::hdf5_create_file(test_file_name);
io::hdf5_write(n,h5_file_id);
io::hdf5_close_file(h5_file_id);
h5_file_id = io::hdf5_open_file_for_read(test_file_name);
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c/d"));
Node n_read;
io::hdf5_read(h5_file_id,"a/b/c/d",n_read);
EXPECT_EQ(10,n_read.to_int());
io::hdf5_close_file(h5_file_id);
h5_file_id = io::hdf5_open_file_for_read_write(test_file_name);
Node n2;
n2 = 12;
io::hdf5_write(n2,h5_file_id,"a/b/c/e");
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c/e"));
io::hdf5_read(h5_file_id,"a/b/c/e",n_read);
EXPECT_EQ(12,n_read.to_int());
io::hdf5_close_file(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_save_generic_options)
{
// 5k zeros, should compress well, but under default
// threshold size
Node n;
n["value"] = DataType::float64(5000);
Node opts;
opts["hdf5/chunking/threshold"] = 2000;
opts["hdf5/chunking/chunk_size"] = 2000;
std::string tout_std = "tout_hdf5_save_generic_default_options.hdf5";
std::string tout_cmp = "tout_hdf5_save_generic_test_options.hdf5";
utils::remove_path_if_exists(tout_std);
utils::remove_path_if_exists(tout_cmp);
io::save(n,tout_std, "hdf5");
io::save(n,tout_cmp, "hdf5", opts);
EXPECT_TRUE(utils::is_file(tout_std));
EXPECT_TRUE(utils::is_file(tout_cmp));
int64 tout_std_fs = utils::file_size(tout_std);
int64 tout_cmp_fs = utils::file_size(tout_cmp);
CONDUIT_INFO("fs test: std = "
<< tout_std_fs
<< ", cmp ="
<< tout_cmp_fs);
EXPECT_TRUE(tout_cmp_fs < tout_std_fs);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_group_list_children)
{
Node n;
n["path/sub1/a"];
n["path/sub1/b"];
n["path/sub1/c"];
n["path/sub2/d"];
n["path/sub2/e"];
n["path/sub2/f"];
std::string tout = "tout_hdf5_grp_chld_names.hdf5";
utils::remove_path_if_exists(tout);
io::save(n,tout, "hdf5");
EXPECT_TRUE(utils::is_file(tout));
hid_t h5_file_id = io::hdf5_open_file_for_read(tout);
std::vector<std::string> cnames;
io::hdf5_group_list_child_names(h5_file_id,"/",cnames);
EXPECT_EQ(cnames.size(),1);
EXPECT_EQ(cnames[0],"path");
io::hdf5_group_list_child_names(h5_file_id,"path",cnames);
EXPECT_EQ(cnames.size(),2);
EXPECT_EQ(cnames[0],"sub1");
EXPECT_EQ(cnames[1],"sub2");
io::hdf5_group_list_child_names(h5_file_id,"path/sub1",cnames);
EXPECT_EQ(cnames.size(),3);
EXPECT_EQ(cnames[0],"a");
EXPECT_EQ(cnames[1],"b");
EXPECT_EQ(cnames[2],"c");
io::hdf5_group_list_child_names(h5_file_id,"path/sub2",cnames);
EXPECT_EQ(cnames.size(),3);
EXPECT_EQ(cnames[0],"d");
EXPECT_EQ(cnames[1],"e");
EXPECT_EQ(cnames[2],"f");
// check leaf, which has no children
// this doesn't throw an error, but it creates an empty list
io::hdf5_group_list_child_names(h5_file_id,"path/sub1/a",cnames);
EXPECT_EQ(cnames.size(),0);
// totally bogus paths will trigger an error
EXPECT_THROW(io::hdf5_group_list_child_names(h5_file_id,"this/isnt/right",cnames),Error);
// empty string won't work in this case
EXPECT_THROW(io::hdf5_group_list_child_names(h5_file_id,"",cnames),Error);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, check_if_file_is_hdf5_file)
{
Node n;
n["path/mydata"] = 20;
std::string tout = "tout_hdf5_check_hdf5_file.hdf5";
utils::remove_path_if_exists(tout);
io::save(n,tout, "hdf5");
// this should be recoged as hdf5
EXPECT_TRUE(io::is_hdf5_file(tout));
// check behavior with files that have open handles
hid_t h5_file_id = io::hdf5_open_file_for_read_write(tout);
EXPECT_TRUE(io::is_hdf5_file(tout));
io::hdf5_close_file(h5_file_id);
h5_file_id = io::hdf5_open_file_for_read(tout);
EXPECT_TRUE(io::is_hdf5_file(tout));
io::hdf5_close_file(h5_file_id);
tout = "tout_hdf5_check_non_hdf5_file.json";
utils::remove_path_if_exists(tout);
io::save(n,tout,"json");
// this should *not* be recoged as hdf5
EXPECT_FALSE(io::is_hdf5_file(tout));
// check totally bad path
EXPECT_FALSE(io::is_hdf5_file("/path/to/somewhere/that/cant/exist"));
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, test_remove_path)
{
Node n;
n["path/mydata"] = 20;
n["path/otherdata/leaf"] = 42;
std::string tout = "tout_test_remove_path.hdf5";
utils::remove_path_if_exists(tout);
io::save(n,tout, "hdf5");
hid_t h5_file_id = io::hdf5_open_file_for_read_write(tout);
io::hdf5_remove_path(h5_file_id,"path/otherdata/leaf");
io::hdf5_close_file(h5_file_id);
n.reset();
io::load(tout,n);
EXPECT_FALSE(n.has_path("path/otherdata/leaf"));
EXPECT_TRUE(n.has_path("path/otherdata"));
n.print();
h5_file_id = io::hdf5_open_file_for_read_write(tout);
io::hdf5_remove_path(h5_file_id,"path/otherdata");
io::hdf5_close_file(h5_file_id);
n.reset();
io::load(tout,n);
EXPECT_FALSE(n.has_path("path/otherdata"));
EXPECT_TRUE(n.has_path("path"));
n.print();
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, file_name_in_error)
{
Node n;
n["path/mydata"] = 20;
n["path/otherdata/leaf"] = 42;
std::string tout = "tout_our_file_to_test.hdf5";
utils::remove_path_if_exists(tout);
io::save(n,tout, "hdf5");
hid_t h5_file_id = io::hdf5_open_file_for_read_write(tout);
Node n_read;
bool had_error = false;
try
{
io::hdf5_read(h5_file_id,"bad",n_read);
}
catch(Error &e)
{
had_error = true;
std::cout << "error message: " << e.message() ;
// error should have the file name in it
std::size_t found = e.message().find(tout);
EXPECT_TRUE(found!=std::string::npos);
}
// make sure we took the error path
EXPECT_TRUE(had_error);
io::hdf5_close_file(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, test_read_various_string_style)
{
std::string tout = "tout_hdf5_wr_various_string_style.hdf5";
hid_t h5_file_id = H5Fcreate(tout.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// write this string several ways and make sure relay
// can reads them all as we expect
// 21 chars + null term (22 total)
std::string my_string = "this is my {} string!";
// case 0: conduit's current way to of doing things
Node n;
n.set(my_string);
io::hdf5_write(n,h5_file_id,"case_0");
// case 1: string that reflects our current data type
hid_t h5_dtype_id = H5Tcopy(H5T_C_S1);
// set size
hsize_t num_eles = 22;
H5Tset_size(h5_dtype_id, (size_t)num_eles);
H5Tset_strpad(h5_dtype_id, H5T_STR_NULLTERM);
hid_t h5_dspace_id = H5Screate(H5S_SCALAR);
// create new dataset
hid_t h5_dset_id = H5Dcreate(h5_file_id,
"case_1",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
hid_t status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
my_string.c_str());
H5Tclose(h5_dtype_id);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
// case 2: string that is a simple array (old conduit way)
h5_dtype_id = H5T_C_S1;
num_eles = 22;
h5_dspace_id = H5Screate_simple(1,
&num_eles,
NULL);
// create new dataset
h5_dset_id = H5Dcreate(h5_file_id,
"case_2",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
my_string.c_str());
// H5Tclose(h5_dtype_id) -- don't need b/c we are using standard dtype
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
// case 3: fixed lenght with diff term style
std::string my_string3 = "this is my {} string! ";
// len w/o null = 30
h5_dtype_id = H5Tcopy(H5T_C_S1);
num_eles = 30;
H5Tset_size(h5_dtype_id, (size_t)num_eles);
H5Tset_strpad(h5_dtype_id, H5T_STR_SPACEPAD);
h5_dspace_id = H5Screate(H5S_SCALAR);
// create new dataset
h5_dset_id = H5Dcreate(h5_file_id,
"case_3",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
my_string3.c_str());
H5Tclose(h5_dtype_id);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
// temp buffer to create a null padded string as
// input to write to hdf5
Node n_tmp;
n_tmp.set(DataType::uint8(30));
uint8 *mystring4_char_ptr = n_tmp.value();
// null out entire string (leave no doubt for test)
for(int i=0; i < 30; i++)
{
mystring4_char_ptr[i] = 0;
}
// copy over part of my_string before final space pad
for(size_t i=0; i < my_string.size(); i++)
{
mystring4_char_ptr[i] = my_string[i];
}
h5_dtype_id = H5Tcopy(H5T_C_S1);
num_eles = 30;
H5Tset_size(h5_dtype_id, (size_t)num_eles);
H5Tset_strpad(h5_dtype_id, H5T_STR_NULLPAD);
h5_dspace_id = H5Screate(H5S_SCALAR);
// create new dataset
h5_dset_id = H5Dcreate(h5_file_id,
"case_4",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
mystring4_char_ptr);
H5Tclose(h5_dtype_id);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
// case 5: string written using variable length
h5_dtype_id = H5Tcreate(H5T_STRING, H5T_VARIABLE);
h5_dspace_id = H5Screate(H5S_SCALAR);
const char *mystr_char_ptr = my_string.c_str();
// create new dataset
h5_dset_id = H5Dcreate(h5_file_id,
"case_5",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
&mystr_char_ptr);
//
H5Tclose(h5_dtype_id);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
H5Fclose(h5_file_id);
// load back in and make sure we get the correct string for each case
Node n_load;
io::load(tout,n_load);
n_load.print();
EXPECT_EQ(n_load["case_0"].as_string(), my_string );
EXPECT_EQ(n_load["case_1"].as_string(), my_string );
EXPECT_EQ(n_load["case_2"].as_string(), my_string );
EXPECT_EQ(n_load["case_3"].as_string(), my_string3 );
EXPECT_EQ(n_load["case_4"].as_string(), my_string );
EXPECT_EQ(n_load["case_5"].as_string(), my_string );
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_string_compress)
{
uint32 s_len = 10000;
std::string tout_std = "tout_hdf5_wr_string_no_compression.hdf5";
std::string tout_cmp = "tout_hdf5_wr_string_with_compression.hdf5";
std::string s_val = std::string(s_len, 'z');
Node n;
n["my_string"] = s_val;
Node opts;
opts["hdf5/chunking/threshold"] = 100;
opts["hdf5/chunking/chunk_size"] = 100;
// write out the string w and w/o compression
io::save(n,tout_std, "hdf5");
io::save(n,tout_cmp, "hdf5", opts);
Node n_out;
io::hdf5_read(tout_cmp,n_out);
EXPECT_EQ(n_out["my_string"].as_string(), s_val);
int64 tout_std_fs = utils::file_size(tout_std);
int64 tout_cmp_fs = utils::file_size(tout_cmp);
CONDUIT_INFO("fs test: std = "
<< tout_std_fs
<< ", cmp ="
<< tout_cmp_fs);
EXPECT_TRUE(tout_cmp_fs < tout_std_fs);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_list)
{
std::string tout_std = "tout_hdf5_list.hdf5";
Node n;
n.append() = "42";
n.append() = "42";
n.append() = "42";
n.append() = "42";
Node &n_sub = n.append();
n_sub.append() = 42;
n_sub.append() = 42;
n_sub.append() = 42;
n_sub.append() = 42;
n_sub.append() = 42.0;
io::save(n,tout_std, "hdf5");
Node n_load, info;
io::load(tout_std,"hdf5",n_load);
n_load.print();
EXPECT_FALSE(n.diff(n_load,info));
hid_t h5_file_id = io::hdf5_open_file_for_read(tout_std);
/// check subpath of written list
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"0"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"4"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"5"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"4/0"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"4/4"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"4/5"));
n_load.reset();
io::hdf5_read(h5_file_id,"4/4",n_load);
EXPECT_EQ(n_load.to_float64(),42.0);
io::hdf5_close_file(h5_file_id);
// simple compat check (could be expanded)
Node n_check;
n_check = 42.0;
// this isn't compat with the existing file
h5_file_id = io::hdf5_open_file_for_read_write(tout_std);
EXPECT_THROW(io::hdf5_write(n_check,h5_file_id),Error);
// orig should be compat
n_check.set(n);
io::hdf5_write(n_check,h5_file_id);
// lets change the value of one of the list entries
n_check[4][4] = 3.1415;
io::hdf5_write(n_check,h5_file_id);
io::hdf5_close_file(h5_file_id);
io::load(tout_std,"hdf5",n_load);
n_load.print();
EXPECT_FALSE(n_check.diff(n_load,info));
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_list_with_offset)
{
std::string tout_std = "tout_hdf5_list_with_offset.hdf5";
Node n, opts;
n.append() = DataType::c_short(1);
short_array vals = n[0].value();
vals[0] = 1;
io::save(n,tout_std, "hdf5");
vals[0] = 2;
opts["offset"] = 1;
io::save(n,tout_std, "hdf5",opts);
Node n_load, info;
io::load(tout_std,"hdf5",n_load);
// check values of data
// since we didn't use save_merged, the first value should be overwritten
short_array read_vals = n_load[0].value();
EXPECT_EQ(0,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
// let's try again
vals[0] = 1;
io::save(n,tout_std, "hdf5");
vals[0] = 2;
opts["offset"] = 1;
io::save_merged(n,tout_std, "hdf5",opts);
io::load(tout_std,"hdf5",n_load);
read_vals = n_load[0].value();
EXPECT_EQ(1,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
vals[0] = 3;
opts["offset"] = 2;
io::save_merged(n,tout_std, "hdf5",opts);
vals[0] = 4;
opts["offset"] = 3;
io::save_merged(n,tout_std, "hdf5",opts);
vals[0] = 5;
opts["offset"] = 4;
io::save_merged(n,tout_std, "hdf5",opts);
vals[0] = 6;
opts["offset"] = 5;
io::save_merged(n,tout_std, "hdf5",opts);
io::load_merged(tout_std,"hdf5",n_load);
read_vals = n_load[0].value();
EXPECT_EQ(1,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
EXPECT_EQ(3,read_vals[2]);
EXPECT_EQ(4,read_vals[3]);
EXPECT_EQ(5,read_vals[4]);
EXPECT_EQ(6,read_vals[5]);
// try loading with offset and size
Node opts_read;
opts_read["offset"] = 2;
opts_read["size"] = 2;
io::load(tout_std,"hdf5",opts_read,n_load);
read_vals = n_load[0].value();
EXPECT_EQ(3,read_vals[0]);
EXPECT_EQ(4,read_vals[1]);
EXPECT_EQ(2, read_vals.number_of_elements());
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_compat_with_empty)
{
std::string tout_std = "tout_hdf5_empty_compat.hdf5";
Node n;
n["myval"] = 42;
io::save(n,tout_std);
n["empty"] = DataType::empty();
n.print();
io::save_merged(n,tout_std);
// used to fail due to bad compat check
io::save_merged(n,tout_std);
Node n_load, n_diff_info;
io::load(tout_std,"hdf5",n_load);
n_load.print();
EXPECT_FALSE(n.diff(n_load,n_diff_info));
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, test_ref_path_error_msg)
{
// check that ref path only appears in the error message string once
Node n_about;
io::about(n_about);
// skip test if hdf5 isn't enabled
if(n_about["protocols/hdf5"].as_string() != "enabled")
return;
std::string tfile_out = "tout_hdf5_io_for_ref_path_error_msg.hdf5";
// remove files if they already exist
utils::remove_path_if_exists(tfile_out);
Node n, n_read, n_check, opts, info;
n["my/path/to/some/data"]= { 0,1,2,3,4,5,6,7,8,9};
io::save(n,tfile_out, "hdf5");
// bad offset
opts.reset();
opts["offset"] = 1000;
try
{
io::load(tfile_out,"hdf5",opts,n_read);
}
catch(conduit::Error &e)
{
std::string msg = e.message();
std::cout << "error message:"
<< msg << std::endl;
int count = 0;
std::string::size_type pos = 0;
std::string path = "my/path/to/some/data";
while ((pos = msg.find(path, pos )) != std::string::npos)
{
count++;
pos += path.length();
}
std::cout << "# of occurrences of path: " << count << std::endl;
// the path should only appear in the error message string once
EXPECT_EQ(count,1);
}
}
| 27.496373 | 104 | 0.572548 | aaroncblack |
3accd4ecf9d7168deee13dfd0f91a40e2270d982 | 721 | cpp | C++ | Painting Fence Algorithm/code_1.cpp | Jatin-Goyal5/Data-Structures-and-Algorithms | f6bd0f77e5640c2e0568f3fffc4694758e77af96 | [
"MIT"
] | 27 | 2019-01-31T10:22:29.000Z | 2021-08-29T08:25:12.000Z | Painting Fence Algorithm/code_1.cpp | Jatin-Goyal5/Data-Structures-and-Algorithms | f6bd0f77e5640c2e0568f3fffc4694758e77af96 | [
"MIT"
] | 6 | 2020-09-30T19:01:49.000Z | 2020-12-17T15:10:54.000Z | Painting Fence Algorithm/code_1.cpp | Jatin-Goyal5/Data-Structures-and-Algorithms | f6bd0f77e5640c2e0568f3fffc4694758e77af96 | [
"MIT"
] | 27 | 2019-09-21T14:19:32.000Z | 2021-09-15T03:06:41.000Z | //
// code_1.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 23/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
using namespace std;
long countWays(int n, int k) {
long dp[n + 1];
memset(dp, 0, sizeof(dp));
int mod = 1000000007;
dp[1] = k;
long same = 0, diff = k;
for (int i = 2; i <= n; i++) {
same = diff;
diff = dp[i-1] * (k-1);
diff = diff % mod;
dp[i] = (same + diff) % mod;
}
return dp[n];
}
int main() {
int n;
cout << "\nEnter N\t:\t";
cin >> n;
int k;
cout << "\nEnter K\t:\t";
cin >> k;
cout << "\nNumber of Ways\t:\t" << countWays(n,k) << endl;
return 0;
}
| 18.025 | 62 | 0.496533 | Jatin-Goyal5 |
3acdf001bfc1070540e2bab81a7d5715a5784b1f | 7,723 | cpp | C++ | Control_movement/chassis/Src/CrosshairDrawer.cpp | PhilosopheAM/21_Fall_project_gabbishSorting | 15ef612d9e483ad72f9e37953875a7303f94b38e | [
"MIT"
] | 1 | 2021-12-31T09:27:00.000Z | 2021-12-31T09:27:00.000Z | Control_movement/chassis/Src/CrosshairDrawer.cpp | PhilosopheAM/21_Fall_project_gabbishSorting | 15ef612d9e483ad72f9e37953875a7303f94b38e | [
"MIT"
] | null | null | null | Control_movement/chassis/Src/CrosshairDrawer.cpp | PhilosopheAM/21_Fall_project_gabbishSorting | 15ef612d9e483ad72f9e37953875a7303f94b38e | [
"MIT"
] | 1 | 2021-12-22T03:34:04.000Z | 2021-12-22T03:34:04.000Z | #include "CrosshairDrawer.hpp"
#include "Dr16.hpp"
#include "math.h"
#include "BoardPacket.hpp"
void CrosshairDrawner::Init()
{
SetDefaultTicksToUpdate(550);
m_pGimbalController = (GimbalController*)GetOwner()->GetEntity(ECT_GimbalController);
m_rpcIndex = 255;
BoardPacketManager::Instance()->GetTestPacket().AddObserver(this);
m_lastMaxProjectileVelocity = JudgeSystem::Instance()->GameRobotStatus.shooter_id1_17mm_speed_limit;
}
void CrosshairDrawner::Update()
{
if(m_rpcIndex == 0)
{
m_DrawBuffer.operate_tpye = JudgeSystem::GOT_Add;
m_DrawBuffer.graphic_name[2] = 1;
m_DrawBuffer.color = JudgeSystem::GCT_Cyan;
m_DrawBuffer.width = 2;
m_DrawBuffer.graphic_tpye = JudgeSystem::GT_Line;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.color = JudgeSystem::GCT_Green;
m_DrawBuffer.graphic_name[2] = 2;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 3;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 4;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 5;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 6;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 7;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
}
uint16_t latestMaxVel = JudgeSystem::Instance()->GameRobotStatus.shooter_id1_17mm_speed_limit;
if(latestMaxVel == m_lastMaxProjectileVelocity)
{
return;
}
m_lastMaxProjectileVelocity = latestMaxVel;
if(m_rpcIndex == 1)
{
m_DrawBuffer.operate_tpye = JudgeSystem::GOT_Modify;
m_DrawBuffer.graphic_tpye = JudgeSystem::GT_Line;
float _v = m_lastMaxProjectileVelocity;
float _v2 = _v * _v;
float _gimbalPitchAngle = - m_pGimbalController->GetGimbalMotor(GimbalController::GMT_Pitch)->sensorFeedBack.positionFdb;
float _cos = cos(_gimbalPitchAngle);
float _sin = sin(_gimbalPitchAngle);
float _time = 0.0f;
float _atan = 0.0f;
float _halfArmorLanding = 0.0;
float _l = 0.0f;
int16_t _dropPixel;
float _invV = 1 / _v;
m_DrawBuffer.graphic_name[2] = 1;
m_DrawBuffer.color = JudgeSystem::GCT_Orange;
m_DrawBuffer.width = 2;
_time = (_v * _sin + sqrt(_v2 * _sin * _sin + 2.0f * GRAVITY * GIMBAL_HEIGHT)) * INV_GRAVITY;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_x = 960;
m_DrawBuffer.start_y = 540;
m_DrawBuffer.end_x = 960;
m_DrawBuffer.end_y = 540 - _dropPixel;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 2;
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 3;
m_DrawBuffer.color = JudgeSystem::GCT_Green;
_time = 0.1f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 4;
_time = 0.2f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 5;
_time = 0.4f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 6;
_time = 0.6f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 7;
_time = 0.8f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
}
else if(m_rpcIndex == 2)
{
/* code */
m_DrawBuffer.operate_tpye = JudgeSystem::GOT_Delete;
m_DrawBuffer.graphic_tpye = JudgeSystem::GT_Line;
m_DrawBuffer.layer = 0;
m_DrawBuffer.color = JudgeSystem::GCT_Black;
m_DrawBuffer.width = 2;
m_DrawBuffer.start_x = 960;
m_DrawBuffer.start_y = 540;
m_DrawBuffer.radius = m_Radius;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
}
}
void CrosshairDrawner::OnNotify(void* _param)
{
m_rpcIndex = *(uint8_t*)_param;
}
| 31.913223 | 129 | 0.628512 | PhilosopheAM |
3ace55404cef53142c74d770448f7e0c120997ca | 13,990 | hh | C++ | src/vp8/decoder/boolreader.hh | interiorem/lepton | 8435d22b1f0ee9180b8b99610f8823589d7cb982 | [
"Apache-2.0"
] | 4 | 2018-10-29T20:11:40.000Z | 2018-11-01T11:10:47.000Z | src/vp8/decoder/boolreader.hh | interiorem/lepton | 8435d22b1f0ee9180b8b99610f8823589d7cb982 | [
"Apache-2.0"
] | 4 | 2018-11-08T14:11:42.000Z | 2018-12-18T17:03:52.000Z | src/vp8/decoder/boolreader.hh | interiorem/lepton | 8435d22b1f0ee9180b8b99610f8823589d7cb982 | [
"Apache-2.0"
] | 1 | 2018-12-13T08:34:54.000Z | 2018-12-13T08:34:54.000Z | /*
* Copyright (c) 2010 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE banner below
* An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the VPX_AUTHORS file in this directory
*/
/*
Copyright (c) 2010, Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Google 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.
*/
#ifndef VPX_DSP_BITREADER_H_
#define VPX_DSP_BITREADER_H_
#include <stddef.h>
#include <assert.h>
#include <limits.h>
#include <stdint.h>
#include "vpx_config.hh"
#include "billing.hh"
#include "../model/numeric.hh"
//#include "vpx_ports/mem.h"
//#include "vpx/vp8dx.h"
//#include "vpx/vpx_integer.h"
//#include "vpx_dsp/prob.h"
typedef size_t BD_VALUE;
#define BD_VALUE_SIZE ((int)sizeof(BD_VALUE) * CHAR_BIT)
// This is meant to be a large, positive constant that can still be efficiently
// loaded as an immediate (on platforms like ARM, for example).
// Even relatively modest values like 100 would work fine.
#define LOTS_OF_BITS 0x40000000
static std::atomic<uint32_t> test_packet_reader_atomic_test;
typedef std::pair<const uint8_t*, const uint8_t*> ROBuffer;
class PacketReader{
protected:
bool isEof;
public:
PacketReader() {
isEof = false;
}
// returns a buffer with at least sizeof(BD_VALUE) before it
virtual ROBuffer getNext() = 0;
bool eof()const {
return isEof;
}
virtual ~PacketReader(){}
};
class TestPacketReader :public PacketReader{
const uint8_t*cur;
const uint8_t*end;
public:
TestPacketReader(const uint8_t *start, const uint8_t *ed) {
isEof = false;
cur = start;
end = ed;
}
ROBuffer getNext(){
if (cur == end) {
isEof = true;
return {NULL, NULL};
}
if (end - cur > 16) {
size_t val = (test_packet_reader_atomic_test += 7)%16 + 1;
cur += val;
return {cur - val, cur};
}
const uint8_t *ret = cur;
cur = end;
return {ret, end};
}
bool eof()const {
return isEof;
}
};
class BiRope {
public:
ROBuffer rope[2];
// if we want partial data from a previous valuex
uint8_t backing[sizeof(BD_VALUE)];
BiRope() {
memset(&backing[0], 0, sizeof(BD_VALUE));
for (size_t i= 0; i < sizeof(rope)/sizeof(rope[0]); ++i) {
rope[i] = {NULL, NULL};
}
}
void push(ROBuffer data) {
if(rope[0].first == NULL) {
rope[0] = data;
}else {
always_assert(rope[1].first == NULL);
rope[1] = data;
}
}
size_t size() const {
return (rope[0].second-rope[0].first) +
(rope[1].second - rope[1].first);
}
void memcpy_ro(uint8_t *dest, size_t size) const {
if ((ptrdiff_t)size < rope[0].second-rope[0].first) {
memcpy(dest, rope[0].first, size);
return;
}
size_t del = rope[0].second-rope[0].first;
if (del) {
memcpy(dest, rope[0].first, del);
}
dest += del;
size -=del;
if (size) {
always_assert(rope[1].second - rope[1].first >= (ptrdiff_t)size);
memcpy(dest, rope[1].first, size);
}
}
void operator += (size_t del) {
if ((ptrdiff_t)del < rope[0].second - rope[0].first) {
rope[0].first += del;
return;
}
del -= rope[0].second - rope[0].first;
rope[0] = rope[1];
rope[1] = {NULL, NULL};
always_assert((ptrdiff_t)del <= rope[0].second - rope[0].first);
rope[0].first += del;
if (rope[0].first == rope[0].second) {
rope[0] = {NULL, NULL};
}
}
/*
void memcpy_pop(uint8_t *dest, size_t size) {
if (size < rope[0].second-rope[0].first) {
memcpy(dest, rope[0].first, size);
rope[0].first += size;
return;
} else {
size_t del = rope[0].second-rope[0].first;
memcpy(dest, rope[0].first, del);
dest += del;
size -= del;
rope[0] = rope[1];
rope[1] = {NULL, NULL};
}
if (size) {
always_assert(rope[0].second - rope[0].first < size);
memcpy(dest, rope[0].first, size);
rope[0].first += size;
if (rope[0].first == rope[0].second) {
rope[0] = {NULL, NULL};
}
}
}*/
};
typedef struct {
// Be careful when reordering this struct, it may impact the cache negatively.
BD_VALUE value;
unsigned int range;
int count;
BiRope buffer;
PacketReader *reader;
// vpx_decrypt_cb decrypt_cb;
// void *decrypt_state;
} vpx_reader;
int vpx_reader_init(vpx_reader *r,
PacketReader *reader);
static INLINE void vpx_reader_fill(vpx_reader *r) {
BD_VALUE value = r->value;
int count = r->count;
size_t bytes_left = r->buffer.size();
size_t bits_left = bytes_left * CHAR_BIT;
int shift = BD_VALUE_SIZE - CHAR_BIT - (count + CHAR_BIT);
if (bits_left <= BD_VALUE_SIZE && !r->reader->eof()) {
// pull some from reader
uint8_t local_buffer[sizeof(BD_VALUE)] = {0};
r->buffer.memcpy_ro(local_buffer, bytes_left);
r->buffer += bytes_left; // clear it out
while(true) {
auto next = r->reader->getNext();
if (next.second - next.first + bytes_left <= sizeof(BD_VALUE)) {
if (next.first != next.second) {
memcpy(local_buffer + bytes_left, next.first, next.second - next.first);
}
bytes_left += next.second - next.first;
} else {
if (bytes_left) {
memcpy(r->buffer.backing, local_buffer, bytes_left);
r->buffer.push({r->buffer.backing, r->buffer.backing + bytes_left});
}
r->buffer.push(next);
break;
}
if (r->reader->eof()) {
always_assert(bytes_left <= sizeof(BD_VALUE)); // otherwise we'd have break'd
memcpy(r->buffer.backing, local_buffer, bytes_left);
r->buffer.push({r->buffer.backing, r->buffer.backing + bytes_left});
break; // setup a simplistic rope that just points to the backing store
}
}
bytes_left = r->buffer.size();
bits_left = bytes_left * CHAR_BIT;
}
if (bits_left > BD_VALUE_SIZE) {
const int bits = (shift & 0xfffffff8) + CHAR_BIT;
BD_VALUE nv;
BD_VALUE big_endian_values;
r->buffer.memcpy_ro((uint8_t*)&big_endian_values, sizeof(BD_VALUE));
if (sizeof(BD_VALUE) == 8) {
big_endian_values = htobe64(big_endian_values);
} else {
big_endian_values = htobe32(big_endian_values);
}
nv = big_endian_values >> (BD_VALUE_SIZE - bits);
count += bits;
r->buffer += (bits >> 3);
value = r->value | (nv << (shift & 0x7));
} else {
const int bits_over = (int)(shift + CHAR_BIT - bits_left);
int loop_end = 0;
if (bits_over >= 0) {
count += LOTS_OF_BITS;
loop_end = bits_over;
}
if (bits_over < 0 || bits_left) {
while (shift >= loop_end) {
count += CHAR_BIT;
uint8_t cur_val = 0;
r->buffer.memcpy_ro(&cur_val, 1);
r->buffer += 1;
value |= ((BD_VALUE)cur_val) << shift;
shift -= CHAR_BIT;
}
}
}
// NOTE: Variable 'buffer' may not relate to 'r->buffer' after decryption,
// so we increase 'r->buffer' by the amount that 'buffer' moved, rather than
// assign 'buffer' to 'r->buffer'.
r->value = value;
r->count = count;
}
// Check if we have reached the end of the buffer.
//
// Variable 'count' stores the number of bits in the 'value' buffer, minus
// 8. The top byte is part of the algorithm, and the remainder is buffered
// to be shifted into it. So if count == 8, the top 16 bits of 'value' are
// occupied, 8 for the algorithm and 8 in the buffer.
//
// When reading a byte from the user's buffer, count is filled with 8 and
// one byte is filled into the value buffer. When we reach the end of the
// data, count is additionally filled with LOTS_OF_BITS. So when
// count == LOTS_OF_BITS - 1, the user's data has been exhausted.
//
// 1 if we have tried to decode bits after the end of stream was encountered.
// 0 No error.
#define vpx_reader_has_error(r) ((r)->count > BD_VALUE_SIZE && (r)->count < LOTS_OF_BITS)
extern int r_bitcount;
constexpr static uint8_t vpx_norm[256] = {
0, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
inline unsigned int count_leading_zeros_uint8(uint8_t split) {
unsigned int shift = 0;
if (split < 128) {
shift = 1;
}
if (split < 64) {
shift = 2;
}
if (split < 32) {
shift = 3;
}
if (split < 16) {
shift = 4;
}
if (split < 8) {
shift = 5;
}
if (split < 4) {
shift = 6;
}
if (split == 1) {
shift = 7;
}
return shift;
}
*/
#ifndef _WIN32
__attribute__((always_inline))
#endif
inline uint8_t count_leading_zeros_uint8(uint8_t v) {
return vpx_norm[v];
dev_assert(v);
return __builtin_clz((uint32_t)v) - 24; // slower
uint8_t r = 0; // result of log2(v) will go here
if (v & 0xf0) {
r |= 4;
v >>= 4;
}
if (v & 0xc) {
v >>= 2;
r |= 2;
}
if (v & 0x2) {
v >>= 1;
r |= 1;
}
return 7 - r;
}
inline bool vpx_reader_fill_and_read(vpx_reader *r, unsigned int split, Billing bill) {
BD_VALUE bigsplit = (BD_VALUE)split << (BD_VALUE_SIZE - CHAR_BIT);
vpx_reader_fill(r);
BD_VALUE value = r->value;
bool bit = (value >= bigsplit);
int count = r->count;
unsigned int range;
if (bit) {
range = r->range - split;
value = value - bigsplit;
} else {
range = split;
}
//unsigned int shift = vpx_norm[range];
unsigned int shift = count_leading_zeros_uint8(range);
range <<= shift;
value <<= shift;
count -= shift;
write_bit_bill(bill, true, shift);
r->value = value;
r->count = count;
r->range = range;
return bit;
}
#ifndef _WIN32
__attribute__((always_inline))
#endif
inline bool vpx_read(vpx_reader *r, int prob, Billing bill) {
int split = (r->range * prob + (256 - prob)) >> CHAR_BIT;
BD_VALUE value = r->value;
int count = r->count;
BD_VALUE bigsplit = (BD_VALUE)split << (BD_VALUE_SIZE - CHAR_BIT);
bool bit = value >= bigsplit;
unsigned int range;
#if 0
BD_VALUE mask = -(long long)bit;
value -= mask & bigsplit;
range = (r->range & mask) + (split ^ mask) - mask;
#else
if (bit) {
range = r->range - split;
value = value - bigsplit;
} else {
range = split;
}
#endif
if (__builtin_expect(r->count < 0, 0)) {
bit = vpx_reader_fill_and_read(r, split, bill);
#ifdef DEBUG_ARICODER
fprintf(stderr, "R %d %d %d\n", r_bitcount++, prob, bit);
#endif
return bit;
}
//unsigned int shift = vpx_norm[range];
unsigned int shift = count_leading_zeros_uint8(range);
range <<= shift;
value <<= shift;
count -= shift;
write_bit_bill(bill, true, shift);
r->value = value;
r->count = count;
r->range = range;
#ifdef DEBUG_ARICODER
fprintf(stderr, "R %d %d %d\n", r_bitcount++, prob, bit);
#endif
return bit;
}
#endif // VPX_DSP_BITREADER_H_
| 33.549161 | 755 | 0.573838 | interiorem |
3ad2fa631e1b001886c4bd5911ef229e87d4de44 | 14,056 | cpp | C++ | gen/blink/bindings/core/v8/V8TouchEvent.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | 8 | 2019-05-05T16:38:05.000Z | 2021-11-09T11:45:38.000Z | gen/blink/bindings/core/v8/V8TouchEvent.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | null | null | null | gen/blink/bindings/core/v8/V8TouchEvent.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | 4 | 2018-12-14T07:52:46.000Z | 2021-06-11T18:06:09.000Z | // Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8TouchEvent.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8TouchList.h"
#include "bindings/core/v8/V8Window.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/UseCounter.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8TouchEvent::wrapperTypeInfo = { gin::kEmbedderBlink, V8TouchEvent::domTemplate, V8TouchEvent::refObject, V8TouchEvent::derefObject, V8TouchEvent::trace, 0, 0, V8TouchEvent::preparePrototypeObject, V8TouchEvent::installConditionallyEnabledProperties, "TouchEvent", &V8UIEvent::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::WillBeGarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TouchEvent.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& TouchEvent::s_wrapperTypeInfo = V8TouchEvent::wrapperTypeInfo;
namespace TouchEventV8Internal {
static void touchesAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
RefPtrWillBeRawPtr<TouchList> cppValue(impl->touches());
if (cppValue && DOMDataStore::setReturnValue(info.GetReturnValue(), cppValue.get()))
return;
v8::Local<v8::Value> v8Value(toV8(cppValue.get(), holder, info.GetIsolate()));
if (!v8Value.IsEmpty()) {
V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "touches"), v8Value);
v8SetReturnValue(info, v8Value);
}
}
static void touchesAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::touchesAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void targetTouchesAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
RefPtrWillBeRawPtr<TouchList> cppValue(impl->targetTouches());
if (cppValue && DOMDataStore::setReturnValue(info.GetReturnValue(), cppValue.get()))
return;
v8::Local<v8::Value> v8Value(toV8(cppValue.get(), holder, info.GetIsolate()));
if (!v8Value.IsEmpty()) {
V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "targetTouches"), v8Value);
v8SetReturnValue(info, v8Value);
}
}
static void targetTouchesAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::targetTouchesAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void changedTouchesAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
RefPtrWillBeRawPtr<TouchList> cppValue(impl->changedTouches());
if (cppValue && DOMDataStore::setReturnValue(info.GetReturnValue(), cppValue.get()))
return;
v8::Local<v8::Value> v8Value(toV8(cppValue.get(), holder, info.GetIsolate()));
if (!v8Value.IsEmpty()) {
V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "changedTouches"), v8Value);
v8SetReturnValue(info, v8Value);
}
}
static void changedTouchesAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::changedTouchesAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void altKeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
v8SetReturnValueBool(info, impl->altKey());
}
static void altKeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::altKeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void metaKeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
v8SetReturnValueBool(info, impl->metaKey());
}
static void metaKeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::metaKeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void ctrlKeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
v8SetReturnValueBool(info, impl->ctrlKey());
}
static void ctrlKeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::ctrlKeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void shiftKeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
v8SetReturnValueBool(info, impl->shiftKey());
}
static void shiftKeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::shiftKeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void initTouchEventMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "initTouchEvent", "TouchEvent", info.Holder(), info.GetIsolate());
TouchEvent* impl = V8TouchEvent::toImpl(info.Holder());
TouchList* touches;
TouchList* targetTouches;
TouchList* changedTouches;
V8StringResource<> type;
DOMWindow* view;
int unused1;
int unused2;
int unused3;
int unused4;
bool ctrlKey;
bool altKey;
bool shiftKey;
bool metaKey;
{
touches = V8TouchList::toImplWithTypeCheck(info.GetIsolate(), info[0]);
targetTouches = V8TouchList::toImplWithTypeCheck(info.GetIsolate(), info[1]);
changedTouches = V8TouchList::toImplWithTypeCheck(info.GetIsolate(), info[2]);
type = info[3];
if (!type.prepare())
return;
view = toDOMWindow(info.GetIsolate(), info[4]);
unused1 = toInt32(info.GetIsolate(), info[5], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
unused2 = toInt32(info.GetIsolate(), info[6], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
unused3 = toInt32(info.GetIsolate(), info[7], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
unused4 = toInt32(info.GetIsolate(), info[8], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
ctrlKey = toBoolean(info.GetIsolate(), info[9], exceptionState);
if (exceptionState.throwIfNeeded())
return;
altKey = toBoolean(info.GetIsolate(), info[10], exceptionState);
if (exceptionState.throwIfNeeded())
return;
shiftKey = toBoolean(info.GetIsolate(), info[11], exceptionState);
if (exceptionState.throwIfNeeded())
return;
metaKey = toBoolean(info.GetIsolate(), info[12], exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
impl->initTouchEvent(scriptState, touches, targetTouches, changedTouches, type, view, unused1, unused2, unused3, unused4, ctrlKey, altKey, shiftKey, metaKey);
}
static void initTouchEventMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
UseCounter::countIfNotPrivateScript(info.GetIsolate(), callingExecutionContext(info.GetIsolate()), UseCounter::V8TouchEvent_InitTouchEvent_Method);
TouchEventV8Internal::initTouchEventMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace TouchEventV8Internal
static const V8DOMConfiguration::AccessorConfiguration V8TouchEventAccessors[] = {
{"touches", TouchEventV8Internal::touchesAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"targetTouches", TouchEventV8Internal::targetTouchesAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"changedTouches", TouchEventV8Internal::changedTouchesAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"altKey", TouchEventV8Internal::altKeyAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"metaKey", TouchEventV8Internal::metaKeyAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"ctrlKey", TouchEventV8Internal::ctrlKeyAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"shiftKey", TouchEventV8Internal::shiftKeyAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};
static const V8DOMConfiguration::MethodConfiguration V8TouchEventMethods[] = {
{"initTouchEvent", TouchEventV8Internal::initTouchEventMethodCallback, 0, 0, V8DOMConfiguration::ExposedToAllScripts},
};
static void installV8TouchEventTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "TouchEvent", V8UIEvent::domTemplate(isolate), V8TouchEvent::internalFieldCount,
0, 0,
V8TouchEventAccessors, WTF_ARRAY_LENGTH(V8TouchEventAccessors),
V8TouchEventMethods, WTF_ARRAY_LENGTH(V8TouchEventMethods));
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8TouchEvent::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TouchEventTemplate);
}
bool V8TouchEvent::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8TouchEvent::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
TouchEvent* V8TouchEvent::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8TouchEvent::refObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<TouchEvent>()->ref();
#endif
}
void V8TouchEvent::derefObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<TouchEvent>()->deref();
#endif
}
} // namespace blink
| 47.647458 | 516 | 0.75434 | gergul |
3ad4e3bc5b94c28b7cebaed5d154cd076fb3d5a8 | 9,310 | cpp | C++ | src/boost/webclient/polyfill/shared_composed_op.spec.cpp | madmongo1/webclient | 7eb52899443a76ced83b6f286b0e0d688f02fc65 | [
"BSL-1.0"
] | 3 | 2020-06-12T02:22:41.000Z | 2021-03-23T14:18:01.000Z | src/boost/webclient/polyfill/shared_composed_op.spec.cpp | madmongo1/webclient | 7eb52899443a76ced83b6f286b0e0d688f02fc65 | [
"BSL-1.0"
] | 1 | 2020-06-12T02:29:08.000Z | 2020-07-18T10:07:05.000Z | src/boost/webclient/polyfill/shared_composed_op.spec.cpp | madmongo1/webclient | 7eb52899443a76ced83b6f286b0e0d688f02fc65 | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2020 Richard Hodges (hodges.r@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/madmongo1/webclient
//
// This project was made possible with the generous support of:
// The C++ Alliance (https://cppalliance.org/)
// Jetbrains (https://www.jetbrains.com/)
//
// Talk to us on Slack (https://cppalliance.org/slack/)
//
// Many thanks to Vinnie Falco for continuous mentoring and support
//
#include "boost/webclient/polyfill/shared_composed_op.hpp"
#include <boost/asio/async_result.hpp>
#include <boost/asio/coroutine.hpp>
#include <boost/asio/executor.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/_experimental/test/handler.hpp>
#include <boost/beast/core/bind_handler.hpp>
#include <catch2/catch.hpp>
#include <iostream>
using namespace boost::webclient;
using boost::beast::bind_front_handler;
struct has_error
{
error_code error;
error_code &assign_error(error_code &ec)
{
if (not error.failed() and ec.failed())
error = ec;
return error;
}
};
template < class Derived >
struct has_timeout
{
has_timeout(net::executor e, std::chrono::milliseconds to)
: timer_(e)
, to_(to)
{
}
struct timer_event
{
};
template < class Self >
void start_timeout(Self self)
{
timer_.expires_after(to_);
timer_.async_wait(bind_front_handler(self, timer_event()));
}
void cancel_timeout() { timer_.cancel(); }
template < class Self >
void operator()(Self &self, timer_event, error_code ec)
{
auto &this_ = *static_cast< Derived * >(this);
timeout = true;
if (ec == net::error::operation_aborted)
ec.clear();
else if (ec == error_code())
{
ec = net::error::timed_out;
this_.on_timeout();
}
this_(self, this_.assign_error(ec));
}
bool timeout = false;
net::high_resolution_timer timer_;
net::high_resolution_timer::duration to_;
};
template < class Protocol, class Derived >
struct has_resolver
{
using resolver = typename Protocol::resolver;
using resolver_results = typename resolver::results_type;
has_resolver(net::executor e)
: resolver_(e)
{
}
void cancel_resolver() { resolver_.cancel(); }
template < class Self >
void start_resolving(Self self, std::string const &hostname, std::string const &service)
{
resolver_.async_resolve(hostname, service, self);
}
template < class Self >
void operator()(Self &self, error_code ec, typename resolver::results_type results)
{
auto &this_ = *static_cast< Derived * >(this);
resolved = true;
if (ec == net::error::operation_aborted)
ec.clear();
else if (ec.failed())
this_.cancel_timeout();
else
endpoints = results;
this_(self, this_.assign_error(ec));
}
resolver resolver_;
resolver_results endpoints;
bool resolved = false;
};
template < class Protocol, class Derived >
struct has_multiconnect
{
has_multiconnect() {}
private:
using protocol = Protocol;
using socket_type = typename protocol::socket;
using endpoint_type = typename protocol::endpoint;
using resolver = typename protocol::resolver;
using resolver_results = typename resolver::results_type;
struct socket_id
{
std::size_t sock;
};
public:
void cancel_connects()
{
if (not sockets_canceled)
{
sockets_canceled = true;
for (auto &s : socks)
s.cancel();
}
}
template < class Self >
void operator()(Self &self, socket_id id, error_code ec)
{
auto &this_ = *static_cast< Derived * >(this);
--sockets_remaining;
if (not ec.failed() and not sockets_canceled) // we are first socket to complete
{
this->cancel_connects();
this_.on_socket_connect(std::move(socks[id.sock]));
}
else if (ec == net::error::operation_aborted)
ec.clear();
if (sockets_remaining)
ec.clear();
this_(self, this_.assign_error(ec));
}
template < class Self >
void initiate_connects(Self self, resolver_results const &endpoints)
{
std::transform(endpoints.begin(),
endpoints.end(),
std::back_inserter(socks),
[&](typename resolver_results::value_type const&) { return socket_type(self.get_executor()); });
auto i = std::size_t(0);
for (auto &&epi : endpoints)
{
socks[i].async_connect(epi.endpoint(), boost::beast::bind_front_handler(self, socket_id { i }));
++i;
}
sockets_remaining = i;
}
std::vector< socket_type > socks;
std::size_t sockets_remaining = 0;
bool sockets_canceled = false;
};
template < class Socket >
struct mass_connect_op
: net::coroutine
, has_error
, has_timeout< mass_connect_op< Socket > >
, has_resolver< typename Socket::protocol_type, mass_connect_op< Socket > >
, has_multiconnect< typename Socket::protocol_type, mass_connect_op< Socket > >
{
using protocol = typename Socket::protocol_type;
using socket_type = typename protocol::socket;
using endpoint_type = typename protocol::endpoint;
using resolver = typename protocol::resolver;
mass_connect_op(Socket &sock, std::string hostname, std::string port, std::chrono::milliseconds timeout)
: net::coroutine()
, has_error()
, has_timeout< mass_connect_op< Socket > >(sock.get_executor(), timeout)
, has_resolver< protocol, mass_connect_op< Socket > >(sock.get_executor())
, has_multiconnect< protocol, mass_connect_op< Socket > >()
, sock_(sock)
, hostname_(std::move(hostname))
, port_(std::move(port))
{
}
using has_timeout< mass_connect_op< Socket > >:: operator();
using has_resolver< protocol, mass_connect_op< Socket > >:: operator();
using has_multiconnect< protocol, mass_connect_op< Socket > >::operator();
void on_timeout()
{
this->cancel_resolver();
this->cancel_connects();
}
void on_resolved() { this->cancel_timeout(); }
void on_socket_connect(Socket s)
{
this->cancel_timeout();
sock_ = std::move(s);
}
template < class Self >
void operator()(Self &self, error_code ec = {})
{
using polyfill::share;
#include <boost/asio/yield.hpp>
reenter(this) for (;;)
{
// transform this coroutine into a shared coroutine
yield share(self);
// start the timer and a resolve operation
yield
{
this->start_timeout(share(self));
this->start_resolving(share(self), hostname_, port_);
}
// wait for the resolve to complete one way or another
while (not this->resolved)
yield;
// if we have a failure, complete...
if (ec.failed())
{
// ... after ensuring that the timer completion handler has been invoked
while (not this->timeout)
yield;
}
else
{
// otherwise, simulatenously connect to all endpoints
yield this->initiate_connects(share(self), this->endpoints);
// yield until all connect completion handlers have been invoked
while (this->sockets_remaining)
yield;
// and yield until the timer completion handler has been invoked
while (not this->timeout)
yield;
}
// return the result of the connect
return self.complete(ec);
}
#include <boost/asio/unyield.hpp>
}
Socket & sock_;
std::string hostname_, port_;
};
template < class Socket, class CompletionToken >
auto async_mass_connect(Socket & sock,
std::string host,
std::string port,
std::chrono::milliseconds timeout,
CompletionToken && token)
-> BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void(error_code))
{
return net::async_compose< CompletionToken, void(error_code) >(
mass_connect_op< Socket >(sock, std::move(host), std::move(port), timeout), token, sock);
}
TEST_CASE("boost::webclient::polyfill::shared_composed_op")
{
net::io_context ioc;
auto s = net::ip::tcp::socket(ioc);
async_mass_connect(s, "www.example.com", "http", std::chrono::seconds(10), [&](error_code ec) {
std::cout << ec.message() << std::endl;
auto ep = s.remote_endpoint(ec);
std::cout << ep << std::endl;
});
boost::beast::test::run(ioc);
} | 29.27673 | 119 | 0.596563 | madmongo1 |
3ad60ba5845969a9b65dbf3984d84a27b34c7700 | 13,036 | tcc | C++ | include/elements/3d/hexahedron_bspline_element.tcc | jgiven100/mpm-1 | adc83ab57782874d4dce1ac13be46bca1754a0fe | [
"MIT"
] | null | null | null | include/elements/3d/hexahedron_bspline_element.tcc | jgiven100/mpm-1 | adc83ab57782874d4dce1ac13be46bca1754a0fe | [
"MIT"
] | null | null | null | include/elements/3d/hexahedron_bspline_element.tcc | jgiven100/mpm-1 | adc83ab57782874d4dce1ac13be46bca1754a0fe | [
"MIT"
] | null | null | null | //! Assign nodal connectivity property for bspline elements
template <unsigned Tdim, unsigned Tnfunctions>
void mpm::HexahedronBSplineElement<Tdim, Tnfunctions>::
initialise_bspline_connectivity_properties(
const Eigen::MatrixXd& nodal_coordinates,
const std::vector<std::vector<unsigned>>& nodal_properties) {
assert(nodal_coordinates.rows() == nodal_properties.size());
this->nconnectivity_ = nodal_coordinates.rows();
this->nodal_coordinates_ = nodal_coordinates;
this->node_type_ = nodal_properties;
//! Uniform spacing length in 3D
this->spacing_length_ =
std::abs(nodal_coordinates(1, 0) - nodal_coordinates(0, 0));
}
//! Return shape functions of a Hexahedron BSpline Element at a given
//! local coordinate
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::VectorXd
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::shapefn(
const Eigen::Matrix<double, Tdim, 1>& xi,
const Eigen::Matrix<double, Tdim, 1>& particle_size,
const Eigen::Matrix<double, Tdim, 1>& deformation_gradient) const {
//! To store shape functions
Eigen::VectorXd shapefn =
Eigen::VectorXd::Constant(this->nconnectivity_, 1.0);
if (this->nconnectivity_ == 8)
return mpm::HexahedronElement<Tdim, 8>::shapefn(xi, particle_size,
deformation_gradient);
try {
//! Convert local coordinates to real coordinates
Eigen::Matrix<double, Tdim, 1> pcoord;
pcoord.setZero();
auto local_shapefn =
this->shapefn_local(xi, particle_size, deformation_gradient);
for (unsigned i = 0; i < local_shapefn.size(); ++i)
pcoord.noalias() +=
local_shapefn(i) * nodal_coordinates_.row(i).transpose();
//! Compute shape function following a multiplicative rule
for (unsigned n = 0; n < this->nconnectivity_; ++n) {
//! Loop over dimension
for (unsigned i = 0; i < Tdim; ++i) {
double N = this->kernel(pcoord[i], nodal_coordinates_.row(n)[i],
this->node_type_[n][i], Tpolynomial);
switch (this->node_type_[n][i]) {
case 1:
N += this->kernel(pcoord[i], nodal_coordinates_.row(n)[i], 5,
Tpolynomial);
break;
case 4:
N += this->kernel(pcoord[i], nodal_coordinates_.row(n)[i], 6,
Tpolynomial);
break;
}
shapefn[n] = shapefn[n] * N;
}
}
} catch (std::exception& exception) {
console_->error("{} #{}: {}\n", __FILE__, __LINE__, exception.what());
return shapefn;
}
return shapefn;
}
//! Return gradient of shape functions of a Hexahedron BSpline Element at a
//! given local coordinate
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::MatrixXd
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::grad_shapefn(
const Eigen::Matrix<double, Tdim, 1>& xi,
const Eigen::Matrix<double, Tdim, 1>& particle_size,
const Eigen::Matrix<double, Tdim, 1>& deformation_gradient) const {
//! To store grad shape functions
Eigen::MatrixXd grad_shapefn(this->nconnectivity_, Tdim);
if (this->nconnectivity_ == 8)
return mpm::HexahedronElement<Tdim, 8>::grad_shapefn(xi, particle_size,
deformation_gradient);
try {
//! Convert local coordinates to real coordinates
Eigen::Matrix<double, Tdim, 1> pcoord;
pcoord.setZero();
auto local_shapefn =
this->shapefn_local(xi, particle_size, deformation_gradient);
for (unsigned i = 0; i < local_shapefn.size(); ++i)
pcoord.noalias() +=
local_shapefn(i) * nodal_coordinates_.row(i).transpose();
//! Compute the shape function gradient following a multiplicative rule
for (unsigned n = 0; n < this->nconnectivity_; ++n)
//! Loop over dimension
for (unsigned i = 0; i < Tdim; ++i) {
double dN_dx = this->gradient(pcoord[i], nodal_coordinates_.row(n)[i],
(this->node_type_[n])[i], Tpolynomial);
switch (this->node_type_[n][i]) {
case 1:
dN_dx += this->gradient(pcoord[i], nodal_coordinates_.row(n)[i], 5,
Tpolynomial);
break;
case 4:
dN_dx += this->gradient(pcoord[i], nodal_coordinates_.row(n)[i], 6,
Tpolynomial);
break;
}
for (unsigned j = 0; j < Tdim; ++j) {
if (j != i) {
double N = this->kernel(pcoord[j], nodal_coordinates_.row(n)[j],
this->node_type_[n][j], Tpolynomial);
switch (this->node_type_[n][j]) {
case 1:
N += this->kernel(pcoord[j], nodal_coordinates_.row(n)[j], 5,
Tpolynomial);
break;
case 4:
N += this->kernel(pcoord[j], nodal_coordinates_.row(n)[j], 6,
Tpolynomial);
break;
}
dN_dx = dN_dx * N;
}
}
grad_shapefn(n, i) = dN_dx;
}
} catch (std::exception& exception) {
console_->error("{} #{}: {}\n", __FILE__, __LINE__, exception.what());
return grad_shapefn;
}
return grad_shapefn;
}
//! Return local shape functions of a BSpline Hexahedron Element at a given
//! Return local shape functions of a Hexahedron Element at a given local
//! coordinate, with particle size and deformation gradient
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::VectorXd
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::shapefn_local(
const Eigen::Matrix<double, Tdim, 1>& xi,
const Eigen::Matrix<double, Tdim, 1>& particle_size,
const Eigen::Matrix<double, Tdim, 1>& deformation_gradient) const {
return mpm::HexahedronElement<Tdim, 8>::shapefn(xi, particle_size,
deformation_gradient);
}
//! Compute Jacobian
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::Matrix<double, Tdim, Tdim>
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::jacobian(
const Eigen::Matrix<double, 3, 1>& xi,
const Eigen::MatrixXd& nodal_coordinates,
const Eigen::Matrix<double, 3, 1>& particle_size,
const Eigen::Matrix<double, 3, 1>& deformation_gradient) const {
// Get gradient shape functions
const Eigen::MatrixXd grad_shapefn =
this->grad_shapefn(xi, particle_size, deformation_gradient);
try {
// Check if dimensions are correct
if ((grad_shapefn.rows() != nodal_coordinates.rows()) ||
(xi.size() != nodal_coordinates.cols()))
throw std::runtime_error(
"Jacobian calculation: Incorrect dimension of xi and "
"nodal_coordinates");
} catch (std::exception& exception) {
console_->error("{} #{}: {}\n", __FILE__, __LINE__, exception.what());
return Eigen::Matrix<double, Tdim, Tdim>::Zero();
}
// Jacobian
return (grad_shapefn.transpose() * nodal_coordinates);
}
//! Compute dn_dx
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::MatrixXd mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::dn_dx(
const VectorDim& xi, const Eigen::MatrixXd& nodal_coordinates,
const VectorDim& particle_size,
const VectorDim& deformation_gradient) const {
// Get gradient shape functions
return this->grad_shapefn(xi, particle_size, deformation_gradient);
}
//! Compute Jacobian local with particle size and deformation gradient
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::Matrix<double, Tdim, Tdim>
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::jacobian_local(
const Eigen::Matrix<double, 3, 1>& xi,
const Eigen::MatrixXd& nodal_coordinates,
const Eigen::Matrix<double, 3, 1>& particle_size,
const Eigen::Matrix<double, 3, 1>& deformation_gradient) const {
// Jacobian dx_i/dxi_j
return this->jacobian(xi, nodal_coordinates, particle_size,
deformation_gradient);
}
//! Compute Bmatrix
template <unsigned Tdim, unsigned Tpolynomial>
inline std::vector<Eigen::MatrixXd>
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::bmatrix(
const VectorDim& xi, const Eigen::MatrixXd& nodal_coordinates,
const VectorDim& particle_size,
const VectorDim& deformation_gradient) const {
// Get gradient shape functions
Eigen::MatrixXd grad_sf =
this->grad_shapefn(xi, particle_size, deformation_gradient);
// B-Matrix
std::vector<Eigen::MatrixXd> bmatrix;
bmatrix.reserve(this->nconnectivity_);
try {
// Check if matrices dimensions are correct
if ((grad_sf.rows() != nodal_coordinates.rows()) ||
(xi.rows() != nodal_coordinates.cols()))
throw std::runtime_error(
"BMatrix - Jacobian calculation: Incorrect dimension of xi and "
"nodal_coordinates");
} catch (std::exception& exception) {
console_->error("{} #{}: {}\n", __FILE__, __LINE__, exception.what());
return bmatrix;
}
// Jacobian dx_i/dxi_j
Eigen::Matrix<double, Tdim, Tdim> jacobian =
(grad_sf.transpose() * nodal_coordinates);
// Gradient shapefn of the cell
// dN/dx = [J]^-1 * dN/dxi
Eigen::MatrixXd grad_shapefn = grad_sf * (jacobian.inverse()).transpose();
for (unsigned i = 0; i < this->nconnectivity_; ++i) {
// clang-format off
Eigen::Matrix<double, 6, Tdim> bi;
bi(0, 0) = grad_shapefn(i, 0); bi(0, 1) = 0.; bi(0, 2) = 0.;
bi(1, 0) = 0.; bi(1, 1) = grad_shapefn(i, 1); bi(1, 2) = 0.;
bi(2, 0) = 0.; bi(2, 1) = 0.; bi(2, 2) = grad_shapefn(i, 2);
bi(3, 0) = grad_shapefn(i, 1); bi(3, 1) = grad_shapefn(i, 0); bi(3, 2) = 0.;
bi(4, 0) = 0.; bi(4, 1) = grad_shapefn(i, 2); bi(4, 2) = grad_shapefn(i, 1);
bi(5, 0) = grad_shapefn(i, 2); bi(5, 1) = 0.; bi(5, 2) = grad_shapefn(i, 0);
// clang-format on
bmatrix.push_back(bi);
}
return bmatrix;
}
//! Compute B-Spline Basis Function using the recursive De Boor's algorithm
//! for single direction
template <unsigned Tdim, unsigned Tpolynomial>
double mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::kernel(
double point_coord, double nodal_coord, unsigned node_type,
unsigned poly_order, unsigned index) const {
double value = 0.0;
//! Compute knot coordinate
Eigen::VectorXd knot_vector = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(
(this->knot(node_type)).data(), (this->knot(node_type)).size());
const Eigen::VectorXd one =
Eigen::VectorXd::Constant(knot_vector.size(), 1.0);
const Eigen::VectorXd knot_coord =
nodal_coord * one + spacing_length_ * knot_vector;
if (poly_order == 0) {
if (point_coord >= knot_coord[index] &&
point_coord < knot_coord[index + 1]) {
value = 1.0;
} else {
value = 0.0;
}
} else {
const double den_a = (knot_coord[index + poly_order] - knot_coord[index]);
double a = (point_coord - knot_coord(index)) / den_a;
if (den_a < std::numeric_limits<double>::epsilon()) a = 0;
const double den_b =
(knot_coord[index + poly_order + 1] - knot_coord[index + 1]);
double b = (knot_coord[index + poly_order + 1] - point_coord) / den_b;
if (den_b < std::numeric_limits<double>::epsilon()) b = 0;
value = a * this->kernel(point_coord, nodal_coord, node_type,
poly_order - 1, index) +
b * this->kernel(point_coord, nodal_coord, node_type,
poly_order - 1, index + 1);
}
return value;
}
//! Compute B-Spline Basis Function Gradient using the recursive De Boor's
//! algorithm for single direction
template <unsigned Tdim, unsigned Tpolynomial>
double mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::gradient(
double point_coord, double nodal_coord, unsigned node_type,
unsigned poly_order, unsigned index) const {
double value = 0;
Eigen::VectorXd knot_vector = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(
(this->knot(node_type)).data(), (this->knot(node_type)).size());
const Eigen::VectorXd one =
Eigen::VectorXd::Constant(knot_vector.size(), 1.0);
const Eigen::VectorXd knot_coord =
nodal_coord * one + spacing_length_ * knot_vector;
const double den_a = (knot_coord[index + poly_order] - knot_coord[index]);
double a = poly_order / den_a;
if (den_a < std::numeric_limits<double>::epsilon()) a = 0;
const double den_b =
(knot_coord[index + poly_order + 1] - knot_coord[index + 1]);
double b = poly_order / den_b;
if (den_b < std::numeric_limits<double>::epsilon()) b = 0;
value = a * this->kernel(point_coord, nodal_coord, node_type, poly_order - 1,
index) -
b * this->kernel(point_coord, nodal_coord, node_type, poly_order - 1,
index + 1);
return value;
}
| 39.98773 | 96 | 0.625038 | jgiven100 |
3ad6b4e1d8a65ef656542d390021b5ac8527d0aa | 1,262 | hpp | C++ | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/Skeleton2D.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | 5 | 2021-05-27T21:50:33.000Z | 2022-01-28T11:54:32.000Z | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/Skeleton2D.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | null | null | null | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/Skeleton2D.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | 1 | 2021-01-04T21:12:05.000Z | 2021-01-04T21:12:05.000Z | #ifndef GODOT_CPP_SKELETON2D_HPP
#define GODOT_CPP_SKELETON2D_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "Node2D.hpp"
namespace godot {
class Bone2D;
class Skeleton2D : public Node2D {
struct ___method_bindings {
godot_method_bind *mb__update_bone_setup;
godot_method_bind *mb__update_transform;
godot_method_bind *mb_get_bone;
godot_method_bind *mb_get_bone_count;
godot_method_bind *mb_get_skeleton;
};
static ___method_bindings ___mb;
static void *_detail_class_tag;
public:
static void ___init_method_bindings();
inline static size_t ___get_id() { return (size_t)_detail_class_tag; }
static inline const char *___get_class_name() { return (const char *) "Skeleton2D"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
// constants
static Skeleton2D *_new();
// methods
void _update_bone_setup();
void _update_transform();
Bone2D *get_bone(const int64_t idx);
int64_t get_bone_count() const;
RID get_skeleton() const;
};
}
#endif | 24.269231 | 245 | 0.774168 | jerry871002 |
3ad6fc8a6037695e2b52cf5b74671b4f27aa8896 | 1,104 | cc | C++ | Graph_ADTs_Interfaces/SparseMultiGRAPH.cc | mightyjoe781/Markdown-Notes | 4d8afdbfed75dc2a9f474579b49c9948dd3b4978 | [
"MIT"
] | null | null | null | Graph_ADTs_Interfaces/SparseMultiGRAPH.cc | mightyjoe781/Markdown-Notes | 4d8afdbfed75dc2a9f474579b49c9948dd3b4978 | [
"MIT"
] | null | null | null | Graph_ADTs_Interfaces/SparseMultiGRAPH.cc | mightyjoe781/Markdown-Notes | 4d8afdbfed75dc2a9f474579b49c9948dd3b4978 | [
"MIT"
] | null | null | null | class SparseMultiGRAPH
{
int Vcnt, Ecnt; bool digraph;
struct node
{
int v; node* next;
node(int x, node* t){ v = x; next = t; }
};
typedef node* link;
vector<link> adj;
public:
SparseMultiGRAPH(int V, bool digraph = false):
adj(V), Vcnt(V), Ecnt(0), digraph(digraph)
{ adj.assign(V,0);}
int V() const { return Vcnt; }
int E() const { return Ecnt; }
bool directed() const { return digraph; }
void insert(Edge e)
{
int v = e.v , w = e.w;
adj[v] = new node(w, adj[v]);
if(!digraph) adj[w] = new node(v,adj[w]);
}
void remove(Edge e);
bool edge(int v,int w) const;
class adjIterator;
friend class adjIterator;
};
class SparseMultiGRAPH::adjIterator
{
const SparseMultiGRAPH &G;
int v;
link t;
public:
adjIterator(const SparseMultiGRAPH &G, int v):
G(G), v(v) { t= 0; }
int begin()
{ t= G.adj[v]; return t? t->v : -1;}
int nxt()
{if(t) t = t->next; return t ? t->v : -1;}
bool end()
{ return t == 0; }
};
| 25.090909 | 51 | 0.522645 | mightyjoe781 |
3ae0f76780a921ad7ef212da44f73b1fcff75d11 | 1,947 | cpp | C++ | modules/task_1/krasilnikov_a_count_sentences/count_sentences.cpp | RachinIA/pp_2020_autumn_engineer | 23f7df688a77cad9496b9d95bbe2645e0528f106 | [
"BSD-3-Clause"
] | 1 | 2020-10-30T13:49:58.000Z | 2020-10-30T13:49:58.000Z | modules/task_1/krasilnikov_a_count_sentences/count_sentences.cpp | RachinIA/pp_2020_autumn_engineer | 23f7df688a77cad9496b9d95bbe2645e0528f106 | [
"BSD-3-Clause"
] | 2 | 2020-11-14T18:00:55.000Z | 2020-11-19T16:12:50.000Z | modules/task_1/krasilnikov_a_count_sentences/count_sentences.cpp | RachinIA/pp_2020_autumn_engineer | 23f7df688a77cad9496b9d95bbe2645e0528f106 | [
"BSD-3-Clause"
] | 1 | 2020-10-14T19:37:21.000Z | 2020-10-14T19:37:21.000Z | // Copyright 2020 Krasilnikov Alexey
#include "../../../modules/task_1/krasilnikov_a_count_sentences/count_sentences.h"
#include <mpi.h>
#include <ctime>
#include <random>
#include <string>
std::string getRandomString(const size_t size) {
std::mt19937 generator;
std::string str(size, '_');
for (auto &symbol : str) {
if (generator() % 10 == 0) {
symbol = '.';
} else {
symbol = static_cast<char>(generator() % 128);
}
}
return str;
}
uint32_t getCountSentencesSequential(const std::string& str) {
uint32_t count_sentences = 0;
for (const auto symbol : str) {
if (symbol == '.') {
++count_sentences;
}
}
return count_sentences;
}
uint32_t getCountSentencesParallel(const std::string& str, const size_t size_str) {
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
uint32_t total_count = 0;
std::string local_str;
const uint32_t delta = size_str / size;
const uint32_t remain = size_str % size;
if (rank == 0) {
for (size_t process = 0; process < remain; ++process) {
MPI_Send(&str[0] + process * (delta + 1), delta + 1, MPI_CHAR, process + 1, 0, MPI_COMM_WORLD);
}
for (size_t process = remain; static_cast<int>(process) < size - 1; ++process) {
MPI_Send(&str[0] + process * delta + remain, delta, MPI_CHAR, process + 1, 0, MPI_COMM_WORLD);
}
local_str = str.substr((size - 1) * delta + remain);
} else {
MPI_Status status;
if (rank <= static_cast<int>(remain)) {
local_str.resize(delta + 1);
MPI_Recv(&local_str[0], delta + 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);
} else {
local_str.resize(delta);
MPI_Recv(&local_str[0], delta, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);
}
}
uint32_t local_count = getCountSentencesSequential(local_str);
MPI_Reduce(&local_count, &total_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
return total_count;
}
| 30.904762 | 101 | 0.655367 | RachinIA |
3ae350e30f2d4ad631b19ae59993bcd027abfe05 | 1,784 | cpp | C++ | test/test-Color.inc.cpp | Arnaud-de-Grandmaison/ratrac | d2ab18235ff9b61e6f63694e02f53790e81ed4a7 | [
"Apache-2.0"
] | null | null | null | test/test-Color.inc.cpp | Arnaud-de-Grandmaison/ratrac | d2ab18235ff9b61e6f63694e02f53790e81ed4a7 | [
"Apache-2.0"
] | null | null | null | test/test-Color.inc.cpp | Arnaud-de-Grandmaison/ratrac | d2ab18235ff9b61e6f63694e02f53790e81ed4a7 | [
"Apache-2.0"
] | null | null | null | TEST(Color, base) {
// Testing same operations on colors.
// ==================================
// Colors are red, green, blue tuples.
Color c(-0.5, 0.4, 1.7);
EXPECT_EQ(c.red(), -0.5f);
EXPECT_EQ(c.green(), 0.4f);
EXPECT_EQ(c.blue(), 1.7f);
// Adding colors.
Color c1(0.9, 0.6, 0.75);
Color c2(0.7, 0.1, 0.25);
EXPECT_EQ(c1 + c2, Color(1.6, 0.7, 1.0));
// Subtracting colors.
c1 = Color(0.9, 0.6, 0.75);
c2 = Color(0.7, 0.1, 0.25);
EXPECT_EQ(c1 - c2, Color(0.2, 0.5, 0.5));
// Multiplying a color by a scalar.
c = Color(0.2, 0.3, 0.4);
EXPECT_EQ(c * 2.0, Color(0.4, 0.6, 0.8));
EXPECT_EQ(2.0 * c, Color(0.4, 0.6, 0.8));
// Dividing a color by a scalar.
c = Color(0.4, 0.6, 0.8);
EXPECT_EQ(c / 2.0, Color(0.2, 0.3, 0.4));
// Multiplying colors.
c1 = Color(1.0, 0.2, 0.4);
c2 = Color(0.9, 1.0, 0.1);
EXPECT_EQ(c1 * c2, Color(0.9, 0.2, 0.04));
// Multiplying colors/Hadamard product/Schur product
}
TEST(Color, output) {
Color c1(0.9, 0.6, 0.75);
EXPECT_EQ(std::string(c1),
"Color { red:0.9, green:0.6, blue:0.75, alpha:1}");
std::ostringstream string_stream;
string_stream << c1;
EXPECT_EQ(string_stream.str(),
"Color { red:0.9, green:0.6, blue:0.75, alpha:1}");
string_stream.str("");
Color c2(0.7, 0.1, 0.25, 0.5);
EXPECT_EQ(std::string(c2),
"Color { red:0.7, green:0.1, blue:0.25, alpha:0.5}");
string_stream << c2;
EXPECT_EQ(string_stream.str(),
"Color { red:0.7, green:0.1, blue:0.25, alpha:0.5}");
}
TEST(Color, helpers) {
EXPECT_EQ(Color::BLACK(), Color(0, 0, 0));
EXPECT_EQ(Color::WHITE(), Color(1, 1, 1));
EXPECT_EQ(Color::RED(), Color(1, 0, 0));
EXPECT_EQ(Color::GREEN(), Color(0, 1, 0));
EXPECT_EQ(Color::BLUE(), Color(0, 0, 1));
}
| 28.31746 | 65 | 0.559978 | Arnaud-de-Grandmaison |
3af749b9c4ef66f3153c8bc9dd4d7d3b25dcc599 | 1,635 | cpp | C++ | lib/SDL/src/renderer.cpp | mkschleg/PhysicsEngine | 583c26d4674dcf38cd213d0bd49ddb9b4efe5f09 | [
"MIT"
] | null | null | null | lib/SDL/src/renderer.cpp | mkschleg/PhysicsEngine | 583c26d4674dcf38cd213d0bd49ddb9b4efe5f09 | [
"MIT"
] | null | null | null | lib/SDL/src/renderer.cpp | mkschleg/PhysicsEngine | 583c26d4674dcf38cd213d0bd49ddb9b4efe5f09 | [
"MIT"
] | null | null | null |
#include "renderer.h"
#include <SDL.h>
namespace SDL{
Renderer::Renderer():renderer(nullptr){}
Renderer::Renderer(const Window& window, int index, Uint32 flags){
//SDL_CreateRenderer(SDL_Window *window, int index, Uint32 flags)
renderer.reset(SDL_CreateRenderer(window.window.get(), index, flags), SDL_DestroyRenderer);
if (renderer == nullptr) renderer.reset(SDL_GetRenderer(window.window.get()), SDL_DestroyRenderer);
// if (renderer == nullptr) throw (SDLException("Renderer null __file__ at line __line__"));
}
Renderer::Renderer(Renderer&& rend){
renderer = rend.renderer;
rend.renderer = nullptr;
}
Renderer::Renderer(SDL_Renderer* rend){
renderer.reset(rend, SDL_DestroyRenderer);
}
std::shared_ptr<SDL_Renderer> Renderer::get(){
return renderer;
}
void Renderer::present(){
if(renderer != nullptr) SDL_RenderPresent(renderer.get());
else ; //Throw an error?
}
void Renderer::clear(){
if (renderer != nullptr) SDL_RenderClear(renderer.get());
}
void Renderer::fill(uint8_t r, uint8_t g, uint8_t b, uint8_t a){
//SDL_RenderFillRect(SDL_Renderer *renderer, const SDL_Rect *rect)
uint8_t pr,pg,pb,pa;
SDL_GetRenderDrawColor(renderer.get(), &pr, &pg, &pb, &pa);
SDL_SetRenderDrawColor(renderer.get(), r,g,b, a);
clear();
SDL_SetRenderDrawColor(renderer.get(), pr, pg, pb, pa);
}
void Renderer::operator=(Renderer&& rhs){
if(renderer != nullptr) SDL_DestroyRenderer(renderer.get());
renderer = rhs.renderer;
rhs.renderer = nullptr;
}
SDL_Renderer* Renderer::getRaw(){
return renderer.get();
}
}
| 26.803279 | 103 | 0.686239 | mkschleg |
3af89945eff88b6ae2bf937782fca1f5c2426e02 | 8,141 | cpp | C++ | src/sim-cache/machine.cpp | EverNebula/RISC-V_Simulator | 23dcb6885834ec5f922e0ccf2546a1b0e66aca7b | [
"MIT"
] | null | null | null | src/sim-cache/machine.cpp | EverNebula/RISC-V_Simulator | 23dcb6885834ec5f922e0ccf2546a1b0e66aca7b | [
"MIT"
] | null | null | null | src/sim-cache/machine.cpp | EverNebula/RISC-V_Simulator | 23dcb6885834ec5f922e0ccf2546a1b0e66aca7b | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include "machine.hpp"
#include "utils.hpp"
#define MAX(a, b) ((a) > (b) ? (a) : (b))
void SingleStepInfo()
{
printf("Single Step Mode Help:\n");
printf("c: continue\n");
printf("r: print all registers\n");
printf("d: dump machine status to file 'status_dump.txt'\n");
printf("p: print page table\n");
printf("m <address/hex> <size/dec>: get data from address\n");
printf("q: quit\n\n");
}
void
Machine::SingleStepDebug()
{
char buf[100], tbuf[100];
while (true)
{
fgets(buf, 100, stdin);
switch (buf[0])
{
case 'c':
return;
case 'r':
PrintReg();
break;
case 'd':
FILE *dump_out;
dump_out = fopen("status_dump.txt", "w");
Status(dump_out);
fclose(dump_out);
break;
case 'p':
PrintPageTable();
break;
case 'm':
uint64_t addr, data;
int size;
sscanf(buf, "%s %llx %d", tbuf, &addr, &size);
printf("%llx %d\n", addr, size);
if (!ReadMem(addr, size, (void*)&data))
{
printf("cannot access that address.\n");
continue;
}
printf("data in %08llx: ", addr);
for (int i = size - 1; i >= 0 ; --i)
{
printf("%02llx ", (data >> (i * 8)) & 0xff);
}
printf("\n");
break;
case 'q':
exit(0);
default:
printf("unknown command.\n");
SingleStepInfo();
}
}
}
Machine::Machine(PRED_TYPE mode)
{
// register initialization
memset(reg, 0, sizeof reg);
// page table initialization
for (int i = 0; i < PhysicalPageNum; ++i)
freePage.push(i);
pte = new PageTableEntry[PhysicalPageNum];
predictor = new Predictor(mode);
cycCount = 0;
cpuCount = 0;
instCount = 0;
runTime = .0;
loadHzdCount = 0;
ctrlHzdCount = 0;
ecallStlCount = 0;
jalrStlCount = 0;
totalBranch = 0;
l1cache = NULL;
l2cache = NULL;
l3cache = NULL;
}
Machine::~Machine()
{
delete mainMem;
delete l1cache;
delete pte;
delete predictor;
}
void Machine::StorageInit(int cacheLevel)
{
// storage initialization
StorageLatency ll;
StorageStats s;
CacheConfig l1c;
s.access_time = 0;
mainMem = new Memory();
mainMem->SetStats(s);
ll.bus_latency = 0;
ll.hit_latency = cfg.GetConfig("MEM_CYC");
mainMem->SetLatency(ll);
if (cacheLevel > 2)
{
l3cache = new Cache("L3 cache", (CACHE_METHOD)cfg.GetConfig("L3C_METHOD"));
l3cache->SetStats(s);
ll.bus_latency = cfg.GetConfig("L3C_BUS_CYC");
ll.hit_latency = cfg.GetConfig("L3C_HIT_CYC");
l3cache->SetLatency(ll);
l1c.size = cfg.GetConfig("L3C_SIZE");
l1c.assoc = cfg.GetConfig("L3C_ASSOC");
l1c.line_size = cfg.GetConfig("L3C_BSIZE"); // Size of cache line
l1c.write_through = (bool)cfg.GetConfig("L3C_WT"); // 0|1 for back|through
l1c.write_allocate = (bool)cfg.GetConfig("L3C_WA"); // 0|1 for no-alc|alc
l3cache->SetConfig(l1c);
l3cache->SetPrefetch(cfg.GetConfig("L3C_PREFETCH"));
l3cache->Allocate();
l3cache->SetLower(mainMem);
}
if (cacheLevel > 1)
{
l2cache = new Cache("L2 cache", (CACHE_METHOD)cfg.GetConfig("L2C_METHOD"));
l2cache->SetStats(s);
ll.bus_latency = cfg.GetConfig("L2C_BUS_CYC");
ll.hit_latency = cfg.GetConfig("L2C_HIT_CYC");
l2cache->SetLatency(ll);
l1c.size = cfg.GetConfig("L2C_SIZE");
l1c.assoc = cfg.GetConfig("L2C_ASSOC");
l1c.line_size = cfg.GetConfig("L2C_BSIZE"); // Size of cache line
l1c.write_through = (bool)cfg.GetConfig("L2C_WT"); // 0|1 for back|through
l1c.write_allocate = (bool)cfg.GetConfig("L2C_WA"); // 0|1 for no-alc|alc
l2cache->SetConfig(l1c);
l2cache->SetPrefetch(cfg.GetConfig("L2C_PREFETCH"));
l2cache->Allocate();
if (cacheLevel > 2)
l2cache->SetLower(l3cache);
else
l2cache->SetLower(mainMem);
}
if (cacheLevel > 0)
{
l1cache = new Cache("L1 cache", (CACHE_METHOD)cfg.GetConfig("L1C_METHOD"));
l1cache->SetStats(s);
ll.bus_latency = cfg.GetConfig("L1C_BUS_CYC");
ll.hit_latency = cfg.GetConfig("L1C_HIT_CYC");
l1cache->SetLatency(ll);
l1c.size = cfg.GetConfig("L1C_SIZE");
l1c.assoc = cfg.GetConfig("L1C_ASSOC");
l1c.line_size = cfg.GetConfig("L1C_BSIZE"); // Size of cache line
l1c.write_through = (bool)cfg.GetConfig("L1C_WT"); // 0|1 for back|through
l1c.write_allocate = (bool)cfg.GetConfig("L1C_WA"); // 0|1 for no-alc|alc
l1cache->SetConfig(l1c);
l1cache->SetPrefetch(cfg.GetConfig("L1C_PREFETCH"));
l1cache->Allocate();
if (cacheLevel > 1)
l1cache->SetLower(l2cache);
else
l1cache->SetLower(mainMem);
}
if (cacheLevel != 0)
topStorage = l1cache;
else
topStorage = mainMem;
}
void
Machine::Run()
{
Timer timer;
runTime = 0;
F_reg.bubble = false;
if(singleStep)
SingleStepInfo();
for ( ; ; )
{
int mxCyc = 1, useCyc;
timer.StepTime();
if ((useCyc = Fetch()) == 0)
{
panic("Fetch error!\n");
}
else
{
vprintf("- Fetch CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
if ((useCyc = Decode()) == 0)
{
panic("Decode error!\n");
}
else
{
vprintf("- Decode CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
if ((useCyc = Execute()) == 0)
{
panic("Execute error!\n");
}
else
{
vprintf("- Execute CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
if ((useCyc = MemoryAccess()) == 0)
{
panic("Memory error!\n");
}
else
{
vprintf("- Memory CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
if ((useCyc = WriteBack()) == 0)
{
panic("WriteBack error!\n");
}
else
{
vprintf("- WriteBack CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
UpdatePipeline();
cycCount++;
cpuCount += mxCyc;
runTime += timer.StepTime();
if (debug)
{
PrintReg();
}
if (singleStep)
SingleStepDebug();
}
Status();
}
void
Machine::Status(FILE *fout)
{
bool isnull = fout == NULL;
if (isnull)
{
fout = stdout;
}
fprintf(fout, "\n---------------- Machine ---------------\n");
fprintf(fout, "BASIC STATUS: \n");
fprintf(fout, "- Cycle Count: %d\n", cycCount);
fprintf(fout, "- Inst. Count: %d\n", instCount);
fprintf(fout, "- Run Time: %.4lf\n", runTime);
fprintf(fout, "- Pipeline Cyc CpI: %.2lf\n", (double)cycCount/instCount);
fprintf(fout, "- CPU Cyc CpI: %.2lf\n\n", (double)cpuCount/instCount);
fprintf(fout, "- Pred Strategy: %s\n", predictor->Name());
fprintf(fout, "- Branch Pred Acc: %.2lf%%\t(%d / %d)\n", (double)(totalBranch - ctrlHzdCount)/totalBranch*100,
totalBranch - ctrlHzdCount, totalBranch);
fprintf(fout, "- Load-use Hazard: %d\n", loadHzdCount);
fprintf(fout, "- Ctrl. Hazard: %d * 2\t(cycles)\n", ctrlHzdCount);
fprintf(fout, "- ECALL Stall: %d * 3\t(cycles)\n", ecallStlCount);
fprintf(fout, "- JALR Stall: %d * 2\t(cycles)\n", jalrStlCount);
fprintf(fout, "\nREGISTER FILE: \n");
fprintf(fout, "- Reg. Num %d\n", RegNum);
PrintReg(fout);
fprintf(fout, "----------------------------------------\n");
// cfg.Print(fout);
fprintf(fout, "\n----------------- Cache ----------------\n");
fprintf(fout, "L1 Cache: \n");
if (l1cache)
{
l1cache->Print(fout);
}
else
{
fprintf(fout, " None\n");
}
fprintf(fout, "\nL2 Cache: \n");
if (l2cache)
{
l2cache->Print(fout);
}
else
{
fprintf(fout, " None\n");
}
fprintf(fout, "\nL3 Cache: \n");
if (l3cache)
{
l3cache->Print(fout);
}
else
{
fprintf(fout, " None\n");
}
fprintf(fout, "----------------------------------------\n");
if (isnull)
{
PrintMem(NULL, true);
fout = fopen("status_dump.txt", "w");
}
PrintMem(fout);
if (isnull)
{
printf("memory status dumped to file 'status_dump.txt'.\n");
fclose(fout);
}
else
{
printf("machine status dumped.\n");
}
}
void
Machine::PrintReg(FILE *fout)
{
if (fout == NULL)
fout = stdout;
for (int i = 0; i < RegNum; i += 4)
{
for (int j = 0; j < 4; j++)
fprintf(fout, "[%4s]: 0x%08llx(%10lld) ", i+j>33?"na":reg_str[i+j], reg[i+j], reg[i+j]);
fprintf(fout, "\n");
}
}
| 22.67688 | 113 | 0.585309 | EverNebula |
3afb2a6dc103166391199d28207cef89006d0e50 | 34,597 | cpp | C++ | applications/demosSandbox/sdkDemos/demos/BalancingCharacter.cpp | JernejL/newton-dynamics | 70d9465185d8f1fc2c4fe7718b4537771d04db02 | [
"Zlib"
] | 1 | 2019-12-10T23:26:14.000Z | 2019-12-10T23:26:14.000Z | applications/demosSandbox/sdkDemos/demos/BalancingCharacter.cpp | mikiec84/newton-dynamics | 20693b597e93da6fbda9025cb55cff6d274616b0 | [
"Zlib"
] | null | null | null | applications/demosSandbox/sdkDemos/demos/BalancingCharacter.cpp | mikiec84/newton-dynamics | 20693b597e93da6fbda9025cb55cff6d274616b0 | [
"Zlib"
] | 1 | 2021-11-18T02:12:49.000Z | 2021-11-18T02:12:49.000Z | /* Copyright (c) <2003-2019> <Newton Game Dynamics>
*
* 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
*/
#include "toolbox_stdafx.h"
#include "SkyBox.h"
#include "DemoMesh.h"
#include "DemoCamera.h"
#include "PhysicsUtils.h"
#include "TargaToOpenGl.h"
#include "DemoEntityManager.h"
#include "DebugDisplay.h"
#include "HeightFieldPrimitive.h"
class dBalancingCharacterBoneDefinition
{
public:
enum jointType
{
m_none,
m_ball,
m_0dof,
m_1dof,
m_2dof,
m_3dof,
m_ikEffector,
m_fkEffector,
};
struct dJointLimit
{
dFloat m_minTwistAngle;
dFloat m_maxTwistAngle;
dFloat m_coneAngle;
};
struct dFrameMatrix
{
dFloat m_pitch;
dFloat m_yaw;
dFloat m_roll;
};
char* m_boneName;
jointType m_type;
dFloat m_massFraction;
dJointLimit m_jointLimits;
dFrameMatrix m_frameBasics;
};
static dBalancingCharacterBoneDefinition tredDefinition[] =
{
{ "bone_pelvis", dBalancingCharacterBoneDefinition::m_none, 1.0f },
{ "bone_rightLeg", dBalancingCharacterBoneDefinition::m_3dof, 0.3f, {60.0f, 60.0f, 70.0f}, { 0.0f, 90.0f, 0.0f }},
{ "bone_righCalf", dBalancingCharacterBoneDefinition::m_1dof, 0.2f, {-60.0f, 60.0f, 0.0f}, { 0.0f, 0.0f, 90.0f }},
{ "bone_rightAnkle", dBalancingCharacterBoneDefinition::m_fkEffector, 0.2f, {0.0f, 0.0f, 0.0f}, {-90.0f, 0.0f, 90.0f } },
{ "effector_rightAnkle", dBalancingCharacterBoneDefinition::m_ikEffector},
{ "bone_rightFoot", dBalancingCharacterBoneDefinition::m_3dof, 0.2f, {-30.0f, 30.0f, 0.0f}, { 0.0f, 0.0f, 90.0f }},
{ "bone_leftLeg", dBalancingCharacterBoneDefinition::m_3dof, 0.3f, { 60.0f, 60.0f, 70.0f }, { 0.0f, 90.0f, 0.0f } },
{ "bone_leftCalf", dBalancingCharacterBoneDefinition::m_1dof, 0.2f, {-60.0f, 60.0f, 0.0f }, { 0.0f, 0.0f, 90.0f } },
{ "bone_leftAnkle", dBalancingCharacterBoneDefinition::m_fkEffector, 0.2f,{ 0.0f, 0.0f, 0.0f },{ -90.0f, 0.0f, 90.0f } },
{ "effector_leftAnkle", dBalancingCharacterBoneDefinition::m_ikEffector},
{ "bone_leftFoot", dBalancingCharacterBoneDefinition::m_3dof, 0.2f, { -30.0f, 30.0f, 0.0f }, { 0.0f, 0.0f, 90.0f } },
{ NULL},
};
class dModelDescritor
{
public:
char* m_filename;
dFloat m_mass;
dBalancingCharacterBoneDefinition* m_skeletonDefinition;
};
static dModelDescritor tred = {"tred.ngd", 500.0f, tredDefinition};
class dBalacingCharacterEffector: public dCustomKinematicController
{
public:
dBalacingCharacterEffector(NewtonBody* const body, NewtonBody* const referenceBody, const dMatrix& attachmentMatrixInGlobalSpace, dFloat modelMass)
:dCustomKinematicController(body, attachmentMatrixInGlobalSpace, referenceBody)
,m_origin(GetTargetMatrix())
{
SetSolverModel(1);
SetControlMode(dCustomKinematicController::m_linearAndTwist);
SetMaxAngularFriction(modelMass * 100.0f);
SetMaxLinearFriction(modelMass * 9.8f * 10.0f);
dVector euler0;
dVector euler1;
m_origin.GetEulerAngles(euler0, euler1);
m_pitch = euler0.m_x;
m_yaw = euler0.m_y;
m_roll = euler0.m_z;
}
//void SetMatrix (dFloat x, dFloat y, dFloat z, dFloat pitch, dFloat yaw, dFloat roll)
void SetMatrix(dFloat x, dFloat y, dFloat z, dFloat pitch)
{
dMatrix matrix (dPitchMatrix(m_pitch + pitch) * dYawMatrix(m_yaw) * dRollMatrix(m_roll));
matrix.m_posit = m_origin.TransformVector(dVector (x, y, z, dFloat (1.0f)));
SetTargetMatrix(matrix);
}
dMatrix m_origin;
dFloat m_pitch;
dFloat m_yaw;
dFloat m_roll;
};
class dModelAnimTreeFootBase: public dModelAnimTree
{
public:
dModelAnimTreeFootBase(dModelRootNode* const model, dModelAnimTree* const child, dCustomKinematicController* const footEffector0, dCustomKinematicController* const footEffector1)
:dModelAnimTree(model)
,m_child(child)
,m_rootEffector0(footEffector0)
,m_rootEffector1(footEffector1)
{
}
~dModelAnimTreeFootBase()
{
delete m_child;
}
virtual void Debug(dCustomJoint::dDebugDisplay* const debugContext) const
{
m_child->Debug(debugContext);
}
int GetModelKeyFrames(const dModelKeyFramePose& input, dModelKeyFrame** const output) const
{
int count = 0;
for (dModelKeyFramePose::dListNode* node = input.GetFirst(); node; node = node->GetNext()) {
dModelKeyFrame& transform = node->GetInfo();
if ((transform.m_effector == m_rootEffector0) || (transform.m_effector == m_rootEffector1)) {
output[count] = &transform;
count++;
}
}
return count;
}
dModelAnimTree* m_child;
dCustomKinematicController* m_rootEffector0;
dCustomKinematicController* m_rootEffector1;
};
class dModelAnimTreePoseBalance: public dModelAnimTreeFootBase
{
public:
dModelAnimTreePoseBalance(dModelRootNode* const model, dModelAnimTree* const child, dCustomKinematicController* const footEffector0, dCustomKinematicController* const footEffector1)
:dModelAnimTreeFootBase(model, child, footEffector0, footEffector1)
{
}
virtual void Debug(dCustomJoint::dDebugDisplay* const debugContext) const
{
dMatrix matrix;
NewtonBodyGetMatrix(GetRoot()->GetBody(), &matrix[0][0]);
matrix.m_posit = CalculateCenterOfMass();
debugContext->DrawFrame(matrix);
m_child->Debug(debugContext);
}
/*
bool CalculateUpVector(dVector& upvector, dCustomKinematicController* const effector) const
{
bool ret = false;
NewtonBody* const body0 = effector->GetBody0();
for (NewtonJoint* contactjoint = NewtonBodyGetFirstContactJoint(body0); contactjoint; contactjoint = NewtonBodyGetNextContactJoint(body0, contactjoint)) {
ret = true;
dVector averageNormal(0.0f);
for (void* contact = NewtonContactJointGetFirstContact(contactjoint); contact; contact = NewtonContactJointGetNextContact(contactjoint, contact)) {
NewtonMaterial* const material = NewtonContactGetMaterial(contact);
dVector point(0.0f);
dVector normal(0.0f);
NewtonMaterialGetContactPositionAndNormal(material, body0, &point.m_x, &normal.m_x);
averageNormal += normal;
}
upvector = averageNormal.Normalize();
break;
}
ret = true;
upvector = dVector (0.0f, 1.0f, 0.0f, 0.0f);
upvector = dPitchMatrix(30.0f * dDegreeToRad).RotateVector(upvector);
return ret;
}
*/
dVector CalculateCenterOfMass() const
{
dMatrix matrix;
dVector com(0.0f);
dVector localCom;
dFloat Ixx;
dFloat Iyy;
dFloat Izz;
dFloat mass;
dFloat totalMass = 0.0f;
int stack = 1;
int bodyCount = 0;
const dModelNode* stackBuffer[32];
stackBuffer[0] = GetRoot();
while (stack) {
stack--;
const dModelNode* const root = stackBuffer[stack];
NewtonBody* const body = root->GetBody();
NewtonBodyGetMatrix(body, &matrix[0][0]);
NewtonBodyGetCentreOfMass(body, &localCom[0]);
NewtonBodyGetMass(body, &mass, &Ixx, &Iyy, &Izz);
totalMass += mass;
com += matrix.TransformVector(localCom).Scale(mass);
bodyCount++;
const dModelChildrenList& children = root->GetChildren();
for (const dModelChildrenList::dListNode* node = children.GetFirst(); node; node = node->GetNext()) {
stackBuffer[stack] = node->GetInfo();
stack++;
}
}
com = com.Scale(1.0f / totalMass);
com.m_w = 1.0f;
return com;
}
void GeneratePose(dFloat timestep, dModelKeyFramePose& output)
{
m_child->GeneratePose(timestep, output);
/*
dModelKeyFrame* feetPose[2];
const int count = GetModelKeyFrames(output, &feetPose[0]);
for (int i = 0; i < count; i++) {
dMatrix targetMatrix (m_rootEffector0->GetBodyMatrix());
dVector com (CalculateCenterOfMass());
dVector error (targetMatrix.m_posit - com);
//error.m_x = 0.0f;
error.m_y = 0.0f;
//error.m_z = 0.0f;
targetMatrix.m_posit -= error.Scale (0.35f);
//dTrace (("(%f %f %f) (%f %f %f)\n", com.m_x, com.m_y, com.m_z, targetMatrix.m_posit.m_x, targetMatrix.m_posit.m_y, targetMatrix.m_posit.m_z));
dMatrix rootMatrix;
NewtonBodyGetMatrix (m_rootEffector0->GetBody1(), &rootMatrix[0][0]);
dMatrix effectorMatrix (targetMatrix * rootMatrix.Inverse());
for (dModelKeyFramePose::dListNode* node = output.GetFirst(); node; node = node->GetNext()) {
//dModelKeyFrame& transform = node->GetInfo();
//transform.m_posit = effectorMatrix.m_posit;
//transform.SetMatrix(effectorMatrix);
}
}
*/
}
};
/*
class dModelAnimTreeFootAlignment: public dModelAnimTreeFootBase
{
#define RAY_CAST_LENGHT0 0.125f
#define RAY_CAST_LENGHT1 2.0f
class dFeetRayHitSensor
{
public:
dFeetRayHitSensor(dCustomKinematicController* const effector)
:m_rotation()
,m_footBody(NULL)
,m_ankleBody(NULL)
,m_effector(effector)
{
if (m_effector) {
m_footBody = effector->GetBody0();
NewtonCollision* const box = NewtonBodyGetCollision(m_footBody);
dMatrix matrix;
NewtonBodyGetMatrix(m_footBody, &matrix[0][0]);
dVector worldDir[] = {
{ 1.0f, -1.0f, 1.0, 0.0f },
{ -1.0f, -1.0f, 1.0, 0.0f },
{ -1.0f, -1.0f, -1.0, 0.0f },
{ 1.0f, -1.0f, -1.0, 0.0f }
};
for (int i = 0; i < 4; i++) {
dVector dir = matrix.UnrotateVector(worldDir[i]);
NewtonCollisionSupportVertex(box, &dir[0], &m_sensorHitPoint[i][0]);
m_sensorHitPoint[i].m_w = 0.0f;
}
for (NewtonJoint* joint = NewtonBodyGetFirstJoint(m_footBody); joint; joint = NewtonBodyGetNextJoint(m_footBody, joint)) {
dCustomJoint* const customJoint = (dCustomJoint*)NewtonJointGetUserData(joint);
NewtonBody* const body0 = customJoint->GetBody0();
NewtonBody* const body1 = customJoint->GetBody1();
NewtonBody* const otherBody = (body0 == m_footBody) ? body1 : body0;
if (otherBody != m_footBody) {
m_ankleBody = otherBody;
break;
}
}
}
}
dCustomKinematicController* GetEffector() const
{
return m_effector;
}
void DebugDraw(dCustomJoint::dDebugDisplay* const debugContext) const
{
if (m_effector) {
dMatrix matrix;
NewtonBodyGetMatrix(m_footBody, &matrix[0][0]);
for (int i = 0; i < 4; i++) {
dVector point0(matrix.TransformVector(m_sensorHitPoint[i]));
dVector point1(point0);
point0.m_y += RAY_CAST_LENGHT0;
point1.m_y -= RAY_CAST_LENGHT1;
debugContext->DrawLine(point0, point1);
}
}
}
void AlignMatrix(dModelKeyFrame* const transform, dFloat timestep)
{
dVector upvector;
if (CalculateSupportNormal(upvector)) {
// calculate foot desired matrix
dMatrix rootMatrix;
NewtonBodyGetMatrix(m_effector->GetBody1(), &rootMatrix[0][0]);
dMatrix targetMatrix(dMatrix(transform->m_rotation, transform->m_posit) * rootMatrix);
dFloat cosAngle = upvector.DotProduct3(targetMatrix.m_up);
if (cosAngle < 0.9997f) {
if (cosAngle > 0.87f) {
// align the matrix to the floor contacts.
dVector lateralDir(targetMatrix.m_up.CrossProduct(upvector));
lateralDir = lateralDir.Normalize();
dFloat coneAngle = dAcos(dClamp(cosAngle, dFloat(-1.0f), dFloat(1.0f)));
dMatrix pivotMatrix(m_effector->GetMatrix0().Inverse() * targetMatrix);
dQuaternion rotation(lateralDir, coneAngle);
dMatrix coneRotation(rotation, pivotMatrix.m_posit);
coneRotation.m_posit -= coneRotation.RotateVector(pivotMatrix.m_posit);
targetMatrix = targetMatrix * coneRotation;
// calculate and set new modified effector matrix.
transform->SetMatrix(targetMatrix * rootMatrix.Inverse());
} else {
cosAngle = 0;
}
}
}
}
private:
static unsigned FindFloorPrefilter(const NewtonBody* const body, const NewtonCollision* const collision, void* const userData)
{
dFeetRayHitSensor* const data = (dFeetRayHitSensor*)userData;
return ((data->m_footBody == body) || (data->m_ankleBody == body)) ? 0 : 1;
}
static dFloat FindFloor(const NewtonBody* const body, const NewtonCollision* const shapeHit, const dFloat* const hitContact, const dFloat* const hitNormal, dLong collisionID, void* const userData, dFloat intersectParam)
{
dFeetRayHitSensor* const data = (dFeetRayHitSensor*)userData;
dAssert(body != data->m_footBody);
dAssert(body != data->m_ankleBody);
if (intersectParam < data->m_hitParam) {
data->m_hitParam = intersectParam;
}
return data->m_hitParam;
}
bool CalculateSupportNormal(dVector& upvector)
{
bool ret = false;
dMatrix matrix;
dVector supportPlane[4];
NewtonWorld* const world = NewtonBodyGetWorld(m_footBody);
NewtonBodyGetMatrix(m_footBody, &matrix[0][0]);
int count = 0;
for (int i = 0; i < 4; i++) {
dVector point0(matrix.TransformVector(m_sensorHitPoint[i]));
dVector point1(point0);
m_hitParam = 1.2f;
point0.m_y += RAY_CAST_LENGHT0;
point1.m_y -= RAY_CAST_LENGHT1;
NewtonWorldRayCast(world, &point0[0], &point1[0], FindFloor, this, FindFloorPrefilter, 0);
if (m_hitParam < 1.0f) {
supportPlane[count] = point0 + (point1 - point0).Scale(m_hitParam);
count++;
}
}
if (count >= 3) {
dVector area(0.0f);
dVector e0(supportPlane[1] - supportPlane[0]);
for (int i = 2; i < count; i++) {
dVector e1(supportPlane[i] - supportPlane[0]);
area += e1.CrossProduct(e0);
e0 = e1;
}
ret = true;
upvector = area.Normalize();
//upvector = dPitchMatrix(45.0f * dDegreeToRad).RotateVector(dVector (0, 1.0f, 0.0f, 0.0f));
}
ret = true;
static dFloat angle = 0.0f;
dMatrix xxxx(dPitchMatrix(angle));
angle -= 0.002f;
upvector = xxxx[1];
//upvector = area.Normalize();
//upvector = dPitchMatrix(45.0f * dDegreeToRad).RotateVector(dVector (0, 1.0f, 0.0f, 0.0f));
return ret;
}
dVector m_sensorHitPoint[4];
dQuaternion m_rotation;
NewtonBody* m_footBody;
NewtonBody* m_ankleBody;
dCustomKinematicController* m_effector;
dFloat m_hitParam;
};
public:
dModelAnimTreeFootAlignment(dModelRootNode* const model, dModelAnimTree* const child, dCustomKinematicController* const footEffector0, dCustomKinematicController* const footEffector1)
:dModelAnimTreeFootBase(model, child, footEffector0, footEffector1)
,m_foot0(footEffector0)
,m_foot1(footEffector1)
{
}
virtual void Debug(dCustomJoint::dDebugDisplay* const debugContext) const
{
m_foot0.DebugDraw(debugContext);
m_foot1.DebugDraw(debugContext);
m_child->Debug(debugContext);
}
void GeneratePose(dFloat timestep, dModelKeyFramePose& output)
{
m_child->GeneratePose(timestep, output);
dModelKeyFrame* feetPose[2];
const int count = GetModelKeyFrames(output, &feetPose[0]);
for (int i = 0; i < count; i++) {
dMatrix rootMatrix;
dModelKeyFrame* const transform = feetPose[i];
dCustomKinematicController* const effector = transform->m_effector;
if (effector == m_foot0.GetEffector()) {
m_foot0.AlignMatrix(transform, timestep);
}
if (effector == m_foot1.GetEffector()) {
m_foot1.AlignMatrix(transform, timestep);
}
}
}
dFeetRayHitSensor m_foot0;
dFeetRayHitSensor m_foot1;
};
*/
class dModelAnimTreeAnkleAndFootController: public dModelAnimTree
{
public:
dModelAnimTreeAnkleAndFootController(dModelRootNode* const model, dModelAnimTree* const child, int count, dCustomKinematicController** const effectors)
:dModelAnimTree(model)
,m_child(child)
{
}
~dModelAnimTreeAnkleAndFootController()
{
delete m_child;
}
virtual void Debug(dCustomJoint::dDebugDisplay* const debugContext) const
{
//dMatrix matrix;
//NewtonBodyGetMatrix(GetRoot()->GetBody(), &matrix[0][0]);
//matrix.m_posit = CalculateCenterOfMass();
//debugContext->DrawFrame(matrix);
m_child->Debug(debugContext);
}
/*
bool CalculateUpVector(dVector& upvector, dCustomKinematicController* const effector) const
{
bool ret = false;
NewtonBody* const body0 = effector->GetBody0();
for (NewtonJoint* contactjoint = NewtonBodyGetFirstContactJoint(body0); contactjoint; contactjoint = NewtonBodyGetNextContactJoint(body0, contactjoint)) {
ret = true;
dVector averageNormal(0.0f);
for (void* contact = NewtonContactJointGetFirstContact(contactjoint); contact; contact = NewtonContactJointGetNextContact(contactjoint, contact)) {
NewtonMaterial* const material = NewtonContactGetMaterial(contact);
dVector point(0.0f);
dVector normal(0.0f);
NewtonMaterialGetContactPositionAndNormal(material, body0, &point.m_x, &normal.m_x);
averageNormal += normal;
}
upvector = averageNormal.Normalize();
break;
}
ret = true;
upvector = dVector (0.0f, 1.0f, 0.0f, 0.0f);
upvector = dPitchMatrix(30.0f * dDegreeToRad).RotateVector(upvector);
return ret;
}
*/
void GeneratePose(dFloat timestep, dModelKeyFramePose& output)
{
m_child->GeneratePose(timestep, output);
/*
dModelKeyFrame* feetPose[2];
const int count = GetModelKeyFrames(output, &feetPose[0]);
for (int i = 0; i < count; i++) {
dMatrix targetMatrix (m_rootEffector0->GetBodyMatrix());
dVector com (CalculateCenterOfMass());
dVector error (targetMatrix.m_posit - com);
//error.m_x = 0.0f;
error.m_y = 0.0f;
//error.m_z = 0.0f;
targetMatrix.m_posit -= error.Scale (0.35f);
//dTrace (("(%f %f %f) (%f %f %f)\n", com.m_x, com.m_y, com.m_z, targetMatrix.m_posit.m_x, targetMatrix.m_posit.m_y, targetMatrix.m_posit.m_z));
dMatrix rootMatrix;
NewtonBodyGetMatrix (m_rootEffector0->GetBody1(), &rootMatrix[0][0]);
dMatrix effectorMatrix (targetMatrix * rootMatrix.Inverse());
for (dModelKeyFramePose::dListNode* node = output.GetFirst(); node; node = node->GetNext()) {
//dModelKeyFrame& transform = node->GetInfo();
//transform.m_posit = effectorMatrix.m_posit;
//transform.SetMatrix(effectorMatrix);
}
}
*/
}
dModelAnimTree* m_child;
};
class dBalancingCharacter: public dModelRootNode
{
public:
dBalancingCharacter(NewtonBody* const rootBody)
:dModelRootNode(rootBody, dGetIdentityMatrix())
,m_pose()
,m_animtree(NULL)
{
}
~dBalancingCharacter()
{
if (m_animtree) {
delete m_animtree;
}
}
void SetAllPartsNonCollidable()
{
int stack = 1;
dModelNode* stackBuffer[32];
stackBuffer[0] = this;
void* const aggregate = NewtonCollisionAggregateCreate(NewtonBodyGetWorld(GetBody()));
while (stack) {
stack--;
dModelNode* const root = stackBuffer[stack];
NewtonBody* const body = root->GetBody();
NewtonCollisionAggregateAddBody(aggregate, body);
const dModelChildrenList& children = root->GetChildren();
for (dModelChildrenList::dListNode* node = children.GetFirst(); node; node = node->GetNext()) {
stackBuffer[stack] = node->GetInfo();
stack++;
}
}
NewtonCollisionAggregateSetSelfCollision(aggregate, false);
}
void SetAnimTree(int count, dCustomKinematicController** const effectors)
{
dModelAnimTree* const poseGenerator = new dModelAnimTreePose(this, m_pose);
dModelAnimTree* const feetController = new dModelAnimTreeAnkleAndFootController(this, poseGenerator, count, effectors);
//dModelAnimTreePoseBalance* const poseBalance = new dModelAnimTreePoseBalance(this, poseGenerator, rootEffector0, rootEffector1);
//dModelAnimTree* const footRoll = new dModelAnimTreeFootAlignment(this, poseBalance, rootEffector0, rootEffector1);
//m_animtree = footRoll;
//m_animtree = poseBalance;
m_animtree = feetController;
//m_animtree = poseGenerator;
}
void OnDebug(dCustomJoint::dDebugDisplay* const debugContext)
{
dFloat scale = debugContext->GetScale();
debugContext->SetScale(0.5f);
for (dModelKeyFramePose::dListNode* node = m_pose.GetFirst(); node; node = node->GetNext()) {
const dModelKeyFrame& keyFrame = node->GetInfo();
keyFrame.m_effector->Debug(debugContext);
}
if (m_animtree) {
m_animtree->Debug(debugContext);
}
debugContext->SetScale(scale);
}
void ApplyControls (dFloat timestep, dFloat x, dFloat y, dFloat z, dFloat pitch)
{
m_animtree->GeneratePose(timestep, m_pose);
//for (dModelKeyFramePose::dListNode* node = m_pose.GetFirst(); node; node = node->GetNext()) {
// dModelKeyFrame& transform = node->GetInfo();
// transform.m_effector->SetTargetMatrix(dMatrix(transform.m_rotation, transform.m_posit));
// //dBalacingCharacterEffector* const effector = (dBalacingCharacterEffector*)transform.m_effector;
// //effector->SetMatrix (x, y, z, pitch);
// //break;
//}
//dModelKeyFramePose::dListNode* node = m_pose.GetFirst();
//if (node) {
// dModelKeyFrame& transform = node->GetInfo();
// dBalacingCharacterEffector* const effector = (dBalacingCharacterEffector*)transform.m_effector;
// effector->SetMatrix(x, y, z, pitch);
//}
}
dModelKeyFramePose m_pose;
dModelAnimTree* m_animtree;
};
class dBalancingCharacterManager: public dModelManager
{
public:
dBalancingCharacterManager(DemoEntityManager* const scene)
:dModelManager(scene->GetNewton())
//,m_currentController(NULL)
{
m_pitch = 0.0f;
m_posit_x = 0.0f;
m_posit_y = 0.0f;
m_posit_z = 0.0f;
scene->Set2DDisplayRenderFunction(RenderHelpMenu, NULL, this);
}
~dBalancingCharacterManager()
{
}
static void RenderHelpMenu(DemoEntityManager* const scene, void* const context)
{
dVector color(1.0f, 1.0f, 0.0f, 0.0f);
dBalancingCharacterManager* const me = (dBalancingCharacterManager*)context;
scene->Print(color, "linear degrees of freedom");
ImGui::SliderFloat("pitch", &me->m_pitch, -30.0f, 30.0f);
ImGui::SliderFloat("posit_x", &me->m_posit_x, -1.0f, 1.0f);
ImGui::SliderFloat("posit_y", &me->m_posit_y, -1.0f, 1.0f);
ImGui::SliderFloat("posit_z", &me->m_posit_z, -1.0f, 1.0f);
//
//ImGui::Separator();
//scene->Print(color, "angular degrees of freedom");
//ImGui::SliderFloat("pitch", &me->m_gripper_pitch, -180.0f, 180.0f);
//ImGui::SliderFloat("yaw", &me->m_gripper_yaw, -80.0f, 80.0f);
//ImGui::SliderFloat("roll", &me->m_gripper_roll, -180.0f, 180.0f);
}
static void ClampAngularVelocity(const NewtonBody* body, dFloat timestep, int threadIndex)
{
dVector omega;
NewtonBodyGetOmega(body, &omega[0]);
omega.m_w = 0.0f;
dFloat mag2 = omega.DotProduct3(omega);
if (mag2 > (100.0f * 100.0f)) {
omega = omega.Normalize().Scale(100.0f);
NewtonBodySetOmega(body, &omega[0]);
}
PhysicsApplyGravityForce(body, timestep, threadIndex);
}
NewtonBody* CreateBodyPart(DemoEntity* const bodyPart, const dBalancingCharacterBoneDefinition& definition)
{
NewtonWorld* const world = GetWorld();
NewtonCollision* const shape = bodyPart->CreateCollisionFromchildren(world);
dAssert(shape);
// calculate the boneBody matrix
dMatrix matrix(bodyPart->CalculateGlobalMatrix());
// create the rigid body that will make this boneBody
NewtonBody* const boneBody = NewtonCreateDynamicBody(world, shape, &matrix[0][0]);
// calculate the moment of inertia and the relative center of mass of the solid
//NewtonBodySetMassProperties (boneBody, definition.m_mass, shape);
NewtonBodySetMassProperties(boneBody, definition.m_massFraction, shape);
// save the user data with the boneBody body (usually the visual geometry)
NewtonBodySetUserData(boneBody, bodyPart);
// assign the material for early collision culling
//NewtonBodySetMaterialGroupID(boneBody, m_material);
NewtonBodySetMaterialGroupID(boneBody, 0);
//dVector damping (0.0f);
//NewtonBodySetLinearDamping(boneBody, damping.m_x);
//NewtonBodySetAngularDamping(boneBody, &damping[0]);
// set the bod part force and torque call back to the gravity force, skip the transform callback
//NewtonBodySetForceAndTorqueCallback (boneBody, PhysicsApplyGravityForce);
NewtonBodySetForceAndTorqueCallback(boneBody, ClampAngularVelocity);
// destroy the collision helper shape
NewtonDestroyCollision(shape);
return boneBody;
}
dCustomKinematicController* ConnectEffector(dModelNode* const effectorNode, const dMatrix& effectorMatrix, const dFloat modelMass)
{
//const dModelNode* const referenceNode = effectorNode->GetParent()->GetParent();
//dAssert(referenceNode);
//dCustomJoint* const pivotJoint = FindJoint(referenceNode->GetBody(), referenceNode->GetParent()->GetBody());
//dAssert(pivotJoint);
//Assert(joint->GetBody1() == effectorNode->GetRoot()->GetBody());
//Matrix pivotMatrix(joint->GetMatrix1());
//dBalacingCharacterEffector* const effector = new dBalacingCharacterEffector(effectorNode->GetBody(), effectorNode->GetRoot()->GetBody(), effectorMatrix, modelMass, pivotJoint);
dBalacingCharacterEffector* const effector = new dBalacingCharacterEffector(effectorNode->GetBody(), effectorNode->GetRoot()->GetBody(), effectorMatrix, modelMass);
return effector;
}
dCustomJoint* ConnectLimb(NewtonBody* const bone, NewtonBody* const parent, const dBalancingCharacterBoneDefinition& definition)
{
dMatrix matrix;
NewtonBodyGetMatrix(bone, &matrix[0][0]);
dBalancingCharacterBoneDefinition::dFrameMatrix frameAngle(definition.m_frameBasics);
dMatrix pinAndPivotInGlobalSpace(dPitchMatrix(frameAngle.m_pitch * dDegreeToRad) * dYawMatrix(frameAngle.m_yaw * dDegreeToRad) * dRollMatrix(frameAngle.m_roll * dDegreeToRad));
pinAndPivotInGlobalSpace = pinAndPivotInGlobalSpace * matrix;
dCustomJoint* ret = NULL;
switch (definition.m_type)
{
case dBalancingCharacterBoneDefinition::m_ball:
{
dCustomBallAndSocket* const joint = new dCustomBallAndSocket(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableCone(false);
joint->EnableTwist(false);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_0dof:
{
dCustomHinge* const joint = new dCustomHinge(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableLimits(true);
joint->SetLimits(0.0f, 0.0f);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_1dof:
{
dCustomBallAndSocket* const joint = new dCustomBallAndSocket(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableTwist(true);
joint->SetTwistLimits(definition.m_jointLimits.m_minTwistAngle * dDegreeToRad, definition.m_jointLimits.m_maxTwistAngle * dDegreeToRad);
joint->EnableCone(true);
joint->SetConeLimits(0.0f);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_2dof:
{
dCustomBallAndSocket* const joint = new dCustomBallAndSocket(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableTwist(true);
joint->SetTwistLimits(0.0f, 0.0f);
joint->EnableCone(true);
joint->SetConeLimits(definition.m_jointLimits.m_coneAngle * dDegreeToRad);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_3dof:
{
dCustomBallAndSocket* const joint = new dCustomBallAndSocket(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableTwist(true);
joint->SetTwistLimits(definition.m_jointLimits.m_minTwistAngle * dDegreeToRad, definition.m_jointLimits.m_maxTwistAngle * dDegreeToRad);
joint->EnableCone(true);
joint->SetConeLimits(definition.m_jointLimits.m_coneAngle * dDegreeToRad);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_fkEffector:
{
dCustomKinematicController* const effector = new dCustomKinematicController(bone, pinAndPivotInGlobalSpace, parent);
effector->SetSolverModel(1);
effector->SetControlMode(dCustomKinematicController::m_full6dof);
effector->SetMaxAngularFriction(1.0e20f);
effector->SetMaxLinearFriction(1.0e20f);
ret = effector;
break;
}
default:
ret = NULL;
dAssert (0);
}
return ret;
}
void NormalizeMassAndInertia(dModelRootNode* const model, dFloat modelMass) const
{
int stack = 1;
int bodyCount = 0;
NewtonBody* bodyArray[1024];
dModelNode* stackBuffer[32];
stackBuffer[0] = model;
while (stack) {
stack--;
dModelNode* const root = stackBuffer[stack];
bodyArray[bodyCount] = root->GetBody();
bodyCount++;
const dModelChildrenList& children = root->GetChildren();
for (dModelChildrenList::dListNode* node = children.GetFirst(); node; node = node->GetNext()) {
stackBuffer[stack] = node->GetInfo();
stack++;
}
}
dFloat totalMass = 0.0f;
for (int i = 0; i < bodyCount; i++) {
dFloat Ixx;
dFloat Iyy;
dFloat Izz;
dFloat mass;
NewtonBody* const body = bodyArray[i];
NewtonBodyGetMass(body, &mass, &Ixx, &Iyy, &Izz);
totalMass += mass;
}
dFloat massNormalize = modelMass / totalMass;
for (int i = 0; i < bodyCount; i++) {
dFloat Ixx;
dFloat Iyy;
dFloat Izz;
dFloat mass;
NewtonBody* const body = bodyArray[i];
NewtonBodyGetMass(body, &mass, &Ixx, &Iyy, &Izz);
mass *= massNormalize;
Ixx *= massNormalize;
Iyy *= massNormalize;
Izz *= massNormalize;
dFloat minInertia = dMin(Ixx, dMin(Iyy, Izz));
if (minInertia < 10.0f) {
dFloat maxInertia = dMax(dFloat(10.0f), dMax(Ixx, dMax(Iyy, Izz)));
Ixx = maxInertia;
Iyy = maxInertia;
Izz = maxInertia;
}
NewtonBodySetMassMatrix(body, mass, Ixx, Iyy, Izz);
}
}
void CreateKinematicModel(dModelDescritor& descriptor, const dMatrix& location)
{
NewtonWorld* const world = GetWorld();
DemoEntityManager* const scene = (DemoEntityManager*)NewtonWorldGetUserData(world);
DemoEntity* const entityModel = DemoEntity::LoadNGD_mesh(descriptor.m_filename, world, scene->GetShaderCache());
scene->Append(entityModel);
dMatrix matrix0(entityModel->GetCurrentMatrix());
entityModel->ResetMatrix(*scene, matrix0 * location);
// create the root body, do not set the transform call back
NewtonBody* const rootBody = CreateBodyPart(entityModel, descriptor.m_skeletonDefinition[0]);
// make a kinematic controlled model.
dBalancingCharacter* const model = new dBalancingCharacter(rootBody);
// add the model to the manager
AddRoot(model);
// the the model to calculate the local transformation
model->SetTranformMode(true);
// save the controller as the collision user data, for collision culling
//NewtonCollisionSetUserData(NewtonBodyGetCollision(rootBone), controller);
int stackIndex = 0;
dModelNode* parentBones[32];
DemoEntity* childEntities[32];
for (DemoEntity* child = entityModel->GetChild(); child; child = child->GetSibling()) {
parentBones[stackIndex] = model;
childEntities[stackIndex] = child;
stackIndex++;
//dTrace(("name: %s\n", child->GetName().GetStr()));
}
// walk model hierarchic adding all children designed as rigid body bones.
int effectorsCount = 0;
dCustomKinematicController* effectorList[16];
while (stackIndex) {
stackIndex--;
DemoEntity* const entity = childEntities[stackIndex];
dModelNode* parentBone = parentBones[stackIndex];
const char* const name = entity->GetName().GetStr();
dTrace(("name: %s\n", name));
for (int i = 1; descriptor.m_skeletonDefinition[i].m_boneName; i++) {
if (!strcmp(descriptor.m_skeletonDefinition[i].m_boneName, name)) {
NewtonBody* const parentBody = parentBone->GetBody();
if (descriptor.m_skeletonDefinition[i].m_type == dBalancingCharacterBoneDefinition::m_ikEffector) {
dModelKeyFrame effectorPose;
dMatrix effectorMatrix(entity->CalculateGlobalMatrix());
effectorPose.m_effector = ConnectEffector(parentBone, effectorMatrix, descriptor.m_mass);
effectorPose.SetMatrix (effectorPose.m_effector->GetTargetMatrix());
model->m_pose.Append(effectorPose);
effectorList[effectorsCount] = effectorPose.m_effector;
effectorsCount++;
} else {
NewtonBody* const childBody = CreateBodyPart(entity, descriptor.m_skeletonDefinition[i]);
dCustomJoint* const joint = ConnectLimb(childBody, parentBody, descriptor.m_skeletonDefinition[i]);
dMatrix bindMatrix(entity->GetParent()->CalculateGlobalMatrix((DemoEntity*)NewtonBodyGetUserData(parentBody)).Inverse());
dModelNode* const bone = new dModelNode(childBody, bindMatrix, parentBone);
if (joint->IsType(dCustomKinematicController::GetType())) {
dModelKeyFrame effectorPose;
effectorPose.m_effector = (dCustomKinematicController*)joint;
effectorPose.SetMatrix(effectorPose.m_effector->GetTargetMatrix());
model->m_pose.Append(effectorPose);
effectorList[effectorsCount] = effectorPose.m_effector;
effectorsCount++;
}
for (DemoEntity* child = entity->GetChild(); child; child = child->GetSibling()) {
parentBones[stackIndex] = bone;
childEntities[stackIndex] = child;
stackIndex++;
}
}
break;
}
}
}
// set mass distribution by density and volume
NormalizeMassAndInertia(model, descriptor.m_mass);
// make internal part non collidable
model->SetAllPartsNonCollidable();
#if 0
dCustomHinge* const fixToWorld = new dCustomHinge (matrix0 * location, model->GetBody(), NULL);
fixToWorld->EnableLimits(true);
fixToWorld->SetLimits(0.0f, 0.0f);
#endif
// setup the pose generator
model->SetAnimTree(effectorsCount, effectorList);
//m_currentController = robot;
}
virtual void OnDebug(dModelRootNode* const root, dCustomJoint::dDebugDisplay* const debugContext)
{
dBalancingCharacter* const model = (dBalancingCharacter*)root;
model->OnDebug(debugContext);
}
virtual void OnUpdateTransform(const dModelNode* const bone, const dMatrix& localMatrix) const
{
NewtonBody* const body = bone->GetBody();
DemoEntity* const ent = (DemoEntity*)NewtonBodyGetUserData(body);
DemoEntityManager* const scene = (DemoEntityManager*)NewtonWorldGetUserData(NewtonBodyGetWorld(body));
dQuaternion rot(localMatrix);
ent->SetMatrix(*scene, rot, localMatrix.m_posit);
}
virtual void OnPreUpdate(dModelRootNode* const root, dFloat timestep) const
{
dBalancingCharacter* const model = (dBalancingCharacter*)root;
model->ApplyControls (timestep, m_posit_x, m_posit_y, m_posit_z, dDegreeToRad * m_pitch);
}
//dBalancingCharacter* m_currentController;
dFloat32 m_pitch;
dFloat32 m_posit_x;
dFloat32 m_posit_y;
dFloat32 m_posit_z;
};
void BalancingCharacter(DemoEntityManager* const scene)
{
// load the sky box
scene->CreateSkyBox();
CreateLevelMesh(scene, "flatPlane.ngd", true);
dBalancingCharacterManager* const manager = new dBalancingCharacterManager(scene);
NewtonWorld* const world = scene->GetNewton();
int defaultMaterialID = NewtonMaterialGetDefaultGroupID(world);
NewtonMaterialSetDefaultFriction(world, defaultMaterialID, defaultMaterialID, 1.0f, 1.0f);
NewtonMaterialSetDefaultElasticity(world, defaultMaterialID, defaultMaterialID, 0.0f);
dMatrix origin (dYawMatrix(-90.0f * dDegreeToRad));
origin.m_posit.m_y += 1.0f;
manager->CreateKinematicModel(tred, origin);
origin.m_posit.m_x = -8.0f;
origin.m_posit.m_y = 1.0f;
origin.m_posit.m_z = 0.0f;
scene->SetCameraMatrix(dGetIdentityMatrix(), origin.m_posit);
}
| 32.424555 | 221 | 0.724456 | JernejL |
3affc0447276fdbd8f52a61b72a451ed999d9aa8 | 4,458 | cpp | C++ | src/Libs/CodecUtils/ImagePlaneDecoder.cpp | miseri/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | 1 | 2021-07-14T08:15:05.000Z | 2021-07-14T08:15:05.000Z | src/Libs/CodecUtils/ImagePlaneDecoder.cpp | 7956968/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | null | null | null | src/Libs/CodecUtils/ImagePlaneDecoder.cpp | 7956968/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T08:15:02.000Z | 2021-07-14T08:56:10.000Z | /** @file
MODULE : ImagePlaneDecoder
TAG : IPD
FILE NAME : ImagePlaneDecoder.cpp
DESCRIPTION : A base class with the common implementations for a
family of implementations to read sequentially from
a bit stream, decode and inverse quantise each colour
plane in an image. The colour plane info is held in
ColourPlaneDecoding objects. The process is as follows:
// Instantiate.
ImagePlaneDecoder* p = new ImagePlaneDecoderImpl();
p->Create();
p->SetEndOfPlaneMarkerVlc();
p->SetEndOfImageMarkerVlc();
.
.
// Attach utility classes.
p->AttachVectorQuantiser();
.
.
p->AttachBitStreamReader();
.
.
// Use.
p->Decode();
.
.
// Delete.
p->Destroy()
delete p;
REVISION HISTORY :
COPYRIGHT :
RESTRICTIONS :
===========================================================================
*/
#ifdef _WINDOWS
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#else
#include <stdio.h>
#endif
#include <memory.h>
#include <string.h>
#include <stdlib.h>
#include "ImagePlaneDecoder.h"
/*
--------------------------------------------------------------------------
Construction and destruction.
--------------------------------------------------------------------------
*/
ImagePlaneDecoder::ImagePlaneDecoder(void)
{
// Colour plane info.
for(int i = 0; i < IPD_COLOUR_PLANES; i++)
_pColourPlane[i] = NULL;
// References to helper classes not owned by this.
_pVectorQuantiser = NULL;
_pRunVlcDecoder = NULL;
_pVqVlcDecoder = NULL;
_pIntraVlcDecoder = NULL; // For INTRA coded images.
// Bit stream to read the encoded bits from.
_pBitStreamReader = NULL;
_minPelValue = 0; // Default to 6 bit range.
_maxPelValue = 63;
_endOfPlaneMarker = 32;
_endOfImageMarker = 33;
}//end constructor.
ImagePlaneDecoder::~ImagePlaneDecoder(void)
{
Destroy();
}//end destructor.
int ImagePlaneDecoder::Create(cpdType* refLum,
int lumWidth, int lumHeight,
cpdType* refChrU,
cpdType* refChrV,
int chrWidth, int chrHeight,
int vecLumWidth, int vecLumHeight,
int vecChrWidth, int vecChrHeight)
{
// Clear out any old baggage.
Destroy();
// For decoding an array of decoded data objects are required
// for each colour component in a plane. Create the colour
// plane info holders.
for(int colour = 0; colour < IPD_COLOUR_PLANES; colour++)
{
_pColourPlane[colour] = new ColourPlaneDecoding();
if( _pColourPlane[colour] == NULL )
{
Destroy();
return(0);
}//end if !_pColourPlane[colour]...
int created = 1;
switch(colour)
{
case IPD_LUM:
created &= _pColourPlane[colour]->Create( refLum,
lumWidth, lumHeight,
vecLumWidth, vecLumHeight);
break;
case IPD_CHRU:
created &= _pColourPlane[colour]->Create( refChrU,
chrWidth, chrHeight,
vecChrWidth, vecChrHeight);
break;
case IPD_CHRV:
created &= _pColourPlane[colour]->Create( refChrV,
chrWidth, chrHeight,
vecChrWidth, vecChrHeight);
break;
}//end switch colour...
if( !created )
{
Destroy();
return(0);
}//end if !created...
// All colours have the same range.
_pColourPlane[colour]->SetPelValueRange(_minPelValue, _maxPelValue);
}//end for colour...
return(1);
}//end Create.
void ImagePlaneDecoder::Destroy(void)
{
for(int i = 0; i < IPD_COLOUR_PLANES; i++)
{
if(_pColourPlane[i] != NULL)
delete _pColourPlane[i];
_pColourPlane[i] = NULL;
}//end for i...
// References.
_pVectorQuantiser = NULL;
_pRunVlcDecoder = NULL;
_pVqVlcDecoder = NULL;
_pIntraVlcDecoder = NULL;
_pBitStreamReader = NULL;
}//end Destroy.
/*
--------------------------------------------------------------------------
Common utility methods.
--------------------------------------------------------------------------
*/
| 27.182927 | 79 | 0.531629 | miseri |
d700d9c29b98326384634d116c11d53c4d293497 | 8,397 | cpp | C++ | re/sniffer/sniffermodel.cpp | thiesmoeller/SavvyCAN | 326455f255da05a3414b219600246c46bb517592 | [
"MIT"
] | 3 | 2021-01-02T21:54:42.000Z | 2022-01-21T13:29:05.000Z | re/sniffer/sniffermodel.cpp | thiesmoeller/SavvyCAN | 326455f255da05a3414b219600246c46bb517592 | [
"MIT"
] | null | null | null | re/sniffer/sniffermodel.cpp | thiesmoeller/SavvyCAN | 326455f255da05a3414b219600246c46bb517592 | [
"MIT"
] | 1 | 2021-11-02T20:56:08.000Z | 2021-11-02T20:56:08.000Z | #include <QDebug>
#include <Qt>
#include <QApplication>
#include "sniffermodel.h"
#include "snifferwindow.h"
#include "SnifferDelegate.h"
SnifferModel::SnifferModel(QObject *parent)
: QAbstractItemModel(parent),
mFilter(false),
mNeverExpire(false),
mFadeInactive(false),
mMuteNotched(false),
mTimeSequence(0)
{
QColor TextColor = QApplication::palette().color(QPalette::Text);
if (TextColor.red() + TextColor.green() + TextColor.blue() < 200)
{
mDarkMode = false;
}
else mDarkMode = true;
}
SnifferModel::~SnifferModel()
{
qDeleteAll(mMap);
mMap.clear();
mFilters.clear();
}
int SnifferModel::columnCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : tc::LAST+1;
}
int SnifferModel::rowCount(const QModelIndex &parent) const
{
const QMap<quint32, SnifferItem*>& map = mFilter ? mFilters : mMap;
return parent.isValid() ? 0 : map.size();
}
QVariant SnifferModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
SnifferItem *item = static_cast<SnifferItem*>(index.internalPointer());
if(!item) QVariant();
int col = index.column();
switch(role)
{
case Qt::DisplayRole:
{
switch(col)
{
case tc::DELTA:
return QString::number(item->getDelta(), 'f');
case tc::ID:
return QString("%1").arg(item->getId(), 5, 16, QLatin1Char(' ')).toUpper();
default:
break;
}
if(tc::DATA_0<=col && col <=tc::DATA_7)
{
int data = item->getData(col-tc::DATA_0);
if(data >= 0)
{
return QString("%1").arg((uint8_t)data, 2, 16, QLatin1Char('0')).toUpper();
}
}
break;
}
case Qt::ForegroundRole:
{
if (!mFadeInactive || col < 2) return QApplication::palette().brush(QPalette::Text);
int v = item->getSeqInterval(col - 2) * 10;
//qDebug() << "mTS: " << mTimeSequence << " gDT(" << (col - 2) << ") " << item->getDataTimestamp(col - 2);
if (v > 225) v = 225;
if (v < 0) v = 0;
if (!mDarkMode) //text defaults to being dark
{
return QBrush(QColor(v,v,v,255));
}
else //text defaults to being light
{
return QBrush(QColor(255-v,255-v,255-v,255));
}
}
case Qt::BackgroundRole:
{
if(tc::ID==col)
{
if(item->elapsed() > 4000)
{
if (!mDarkMode) return QBrush(Qt::red);
return QBrush(QColor(128,0,0));
}
}
else if(tc::DATA_0<=col && col<=tc::DATA_7)
{
dc change = item->dataChange(col-tc::DATA_0);
switch(change)
{
case dc::INC:
if (!mDarkMode) return QBrush(Qt::green);
return QBrush(QColor(0,128,0));
case dc::DEINC:
if (!mDarkMode) return QBrush(Qt::red);
return QBrush(QColor(128,0,0));
default:
return QApplication::palette().brush(QPalette::Base);
}
}
break;
}
}
return QVariant();
}
Qt::ItemFlags SnifferModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return QAbstractItemModel::flags(index);
}
QVariant SnifferModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
switch(section)
{
case tc::DELTA:
return QString("Delta");
case tc::ID:
return QString("ID");
default:
break;
}
if(tc::DATA_0<=section && section <=tc::DATA_7)
return QString::number(section-tc::DATA_0);
}
return QVariant();
}
QModelIndex SnifferModel::index(int row, int column, const QModelIndex &parent) const
{
if (parent.isValid())
return QModelIndex();
const QMap<quint32, SnifferItem*>& map = mFilter ? mFilters : mMap;
if(column>tc::LAST || row>=map.size())
return QModelIndex();
/* ugly but I can't find best without creating a list to keep indexes */
QMap<quint32, SnifferItem*>::const_iterator iter;
int i;
for(iter = map.begin(), i=0 ; i<row ; ++i, ++iter);
return createIndex(row, column, iter.value());
}
QModelIndex SnifferModel::parent(const QModelIndex &) const
{
return QModelIndex();
}
bool SnifferModel::getNeverExpire()
{
return mNeverExpire;
}
bool SnifferModel::getFadeInactive()
{
return mFadeInactive;
}
bool SnifferModel::getMuteNotched()
{
return mMuteNotched;
}
void SnifferModel::setNeverExpire(bool val)
{
mNeverExpire = val;
}
void SnifferModel::setFadeInactive(bool val)
{
mFadeInactive = val;
}
void SnifferModel::setMuteNotched(bool val)
{
mMuteNotched = val;
}
void SnifferModel::clear()
{
beginResetModel();
qDeleteAll(mMap);
mMap.clear();
mFilters.clear();
mFilter = false;
endResetModel();
}
//Called from window with a timer (currently 200ms)
void SnifferModel::refresh()
{
QMap<quint32, SnifferItem*>::iterator i;
QVector<quint32> toRemove;
SnifferItem* item;
mTimeSequence++;
/* update markers */
for (i = mMap.begin(); i != mMap.end(); ++i)
{
i.value()->updateMarker();
if(i.value()->elapsed()>5000 && !mNeverExpire)
toRemove.append(i.key());
}
if(toRemove.size())
{
beginResetModel();
foreach(quint32 id, toRemove)
{
/* remove element */
item = mMap.take(id);
mFilters.remove(id);
delete item;
/* send notification */
emit idChange(id, false);
}
endResetModel();
}
else
/* refresh data */
dataChanged(createIndex(0, 0),
createIndex(rowCount()-1, columnCount()-1), QVector<int>(Qt::DisplayRole));
}
void SnifferModel::filter(fltType pType, int pId)
{
beginResetModel();
switch(pType)
{
case fltType::NONE:
/* erase everything */
mFilter = true;
mFilters.clear();
break;
case fltType::ADD:
/* add filter to list */
mFilter = true;
mFilters[pId] = mMap[pId];
break;
case fltType::REMOVE:
/* remove filter */
if(!mFilter)
mFilters = mMap;
mFilter = true;
mFilters.remove(pId);
break;
case fltType::ALL:
/* stop filtering */
mFilter = false;
mFilters.clear();
break;
}
endResetModel();
}
/***********************************************/
/********** slots ****************/
/***********************************************/
void SnifferModel::update(CANConnection*, QVector<CANFrame>& pFrames)
{
foreach(const CANFrame& frame, pFrames)
{
if(!mMap.contains(frame.frameId()))
{
int index = std::distance(mMap.begin(), mMap.lowerBound(frame.frameId()));
/* add the frame */
beginInsertRows(QModelIndex(), index, index);
mMap[frame.frameId()] = new SnifferItem(frame, mTimeSequence);
mMap[frame.frameId()]->update(frame, mTimeSequence, mMuteNotched);
endInsertRows();
emit idChange(frame.frameId(), true);
}
else
//updateData
mMap[frame.frameId()]->update(frame, mTimeSequence, mMuteNotched);
}
}
void SnifferModel::notch()
{
QMap<quint32, SnifferItem*>& map = mFilter ? mFilters : mMap;
foreach(SnifferItem* item, map)
item->notch(true);
}
void SnifferModel::unNotch()
{
QMap<quint32, SnifferItem*>& map = mFilter ? mFilters : mMap;
foreach(SnifferItem* item, map)
item->notch(false);
}
| 24.916914 | 118 | 0.524354 | thiesmoeller |
d704ea7ea118fbc72defa9be344e0c570724e4cd | 1,424 | hpp | C++ | Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/mirror_update__traits.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | null | null | null | Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/mirror_update__traits.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | null | null | null | Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/mirror_update__traits.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | 2 | 2021-06-21T07:32:09.000Z | 2021-08-17T03:05:38.000Z | // generated from rosidl_generator_cpp/resource/idl__traits.hpp.em
// with input from rmf_traffic_msgs:msg/MirrorUpdate.idl
// generated code does not contain a copyright notice
#ifndef RMF_TRAFFIC_MSGS__MSG__DETAIL__MIRROR_UPDATE__TRAITS_HPP_
#define RMF_TRAFFIC_MSGS__MSG__DETAIL__MIRROR_UPDATE__TRAITS_HPP_
#include "rmf_traffic_msgs/msg/detail/mirror_update__struct.hpp"
#include <rosidl_runtime_cpp/traits.hpp>
#include <stdint.h>
#include <type_traits>
// Include directives for member types
// Member 'patch'
#include "rmf_traffic_msgs/msg/detail/schedule_patch__traits.hpp"
namespace rosidl_generator_traits
{
template<>
inline const char * data_type<rmf_traffic_msgs::msg::MirrorUpdate>()
{
return "rmf_traffic_msgs::msg::MirrorUpdate";
}
template<>
inline const char * name<rmf_traffic_msgs::msg::MirrorUpdate>()
{
return "rmf_traffic_msgs/msg/MirrorUpdate";
}
template<>
struct has_fixed_size<rmf_traffic_msgs::msg::MirrorUpdate>
: std::integral_constant<bool, has_fixed_size<rmf_traffic_msgs::msg::SchedulePatch>::value> {};
template<>
struct has_bounded_size<rmf_traffic_msgs::msg::MirrorUpdate>
: std::integral_constant<bool, has_bounded_size<rmf_traffic_msgs::msg::SchedulePatch>::value> {};
template<>
struct is_message<rmf_traffic_msgs::msg::MirrorUpdate>
: std::true_type {};
} // namespace rosidl_generator_traits
#endif // RMF_TRAFFIC_MSGS__MSG__DETAIL__MIRROR_UPDATE__TRAITS_HPP_
| 30.297872 | 99 | 0.810393 | flitzmo-hso |
d704f817fe2238749665d71df40f0d148620e5f0 | 2,797 | cpp | C++ | SOURCES/graphics/renderer/renderwire.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/graphics/renderer/renderwire.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/graphics/renderer/renderwire.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | /***************************************************************************\
RenderWire.h
Scott Randolph
May 5, 1998
This sub class draws an out the window view in wire frame mode.
\***************************************************************************/
#include "TOD.h"
#include "Tpost.h"
#include "RViewPnt.h"
#include "RenderWire.h"
/***************************************************************************\
Setup the rendering context for this view
\***************************************************************************/
void RenderWire::Setup( ImageBuffer *imageBuffer, RViewPoint *vp )
{
// Call our base classes setup routine
RenderOTW::Setup( imageBuffer, vp );
// Set our drawing properties
// SetSmoothShadingMode( FALSE );
SetObjectTextureState( TRUE ); // Start with object textures ON
SetHazeMode( TRUE ); // Start with hazing turned ON
// Use a black terrain filler
haze_ground_color.r = haze_ground_color.g = haze_ground_color.b = 0.0f;
earth_end_color.r = earth_end_color.g = earth_end_color.b = 0.0f;
// Use a midnight blue sky
sky_color.r = 0.0f;
sky_color.g = 0.0f;
sky_color.b = 0.125f;
haze_sky_color.r = 0.0f;
haze_sky_color.g = 0.0f;
haze_sky_color.b = 0.25f;
// Use only moderate ambient lighting on the objects
lightAmbient = 0.8f;
lightDiffuse = 0.0f;
// Update our colors to account for our changes to the default settings
TimeUpdateCallback( this );
}
/***************************************************************************\
Do end of frame housekeeping
\***************************************************************************/
void RenderWire::StartFrame( void ) {
RenderOTW::StartDraw();
TheColorBank.SetColorMode( ColorBankClass::UnlitMode );
}
#define BLEND_MIN 0.25f
#define BLEND_MAX 0.95f
/***************************************************************************\
Compute the color and texture blend value for a single terrain vertex.
\***************************************************************************/
//void RenderWire::ComputeVertexColor( TerrainVertex *vert, Tpost *post, float distance )
void RenderWire::ComputeVertexColor( TerrainVertex *vert, Tpost *, float distance )
{
// float alpha;
// Set all verts to black
vert->r = 0.0f;
vert->g = 0.0f;
vert->b = 0.0f;
// Blend out the textures in the distance
/* if ( hazed && (distance > blend_start)) {
alpha = (distance - blend_start) / blend_depth;
if (alpha < BLEND_MIN) alpha = BLEND_MIN;
if (alpha > BLEND_MAX) alpha = BLEND_MAX;
vert->a = 1.0f - alpha;
vert->RenderingStateHandle = state_mid;
} else {
vert->a = BLEND_MAX;
if (distance < PERSPECTIVE_RANGE) {
vert->RenderingStateHandle = state_fore;
} else {
vert->RenderingStateHandle = state_near;
}
}*/
}
| 29.755319 | 89 | 0.54916 | IsraelyFlightSimulator |
d7058d32ef9f800fcd6a1f6ca7a3aab13d23b874 | 3,293 | cpp | C++ | wrappers/src/object-store/tests/parser.cpp | datasprings/Realm | 00cbfc26268d2a8559913361e0cd067b1d275df5 | [
"Apache-2.0"
] | 3 | 2016-10-13T17:17:05.000Z | 2017-01-13T20:00:39.000Z | src/object-store/tests/parser.cpp | Osedea/realm-js | b06ee441bd7c2fced07e8e496f265a7578a06d07 | [
"Apache-2.0"
] | null | null | null | src/object-store/tests/parser.cpp | Osedea/realm-js | b06ee441bd7c2fced07e8e496f265a7578a06d07 | [
"Apache-2.0"
] | null | null | null | #include "catch.hpp"
#include "parser/parser.hpp"
#include <vector>
#include <string>
static std::vector<std::string> valid_queries = {
// true/false predicates
"truepredicate",
"falsepredicate",
" TRUEPREDICATE ",
" FALSEPREDICATE ",
"truepredicates = falsepredicates", // keypaths
// characters/strings
"\"\" = ''",
"'azAZ09/ :()[]{}<>,.^@-+=*&~`' = '\\\" \\' \\\\ \\/ \\b \\f \\n \\r \\t \\0'",
"\"azAZ09/\" = \"\\\" \\' \\\\ \\/ \\b \\f \\n \\r \\t \\0\"",
"'\\uffFf' = '\\u0020'",
"'\\u01111' = 'asdf\\u0111asdf'",
// expressions (numbers, bools, keypaths, arguments)
"-1 = 12",
"0 = 001",
"0x0 = -0X398235fcAb",
"10. = -.034",
"10.0 = 5.034",
"true = false",
"truelove = false",
"true = falsey",
"nullified = null",
"_ = a",
"_a = _.aZ",
"a09._br.z = __-__.Z-9",
"$0 = $19",
"$0=$0",
// operators
"0=0",
"0 = 0",
"0 =[c] 0",
"0!=0",
"0 != 0",
"0==0",
"0 == 0",
"0==[c]0",
"0 == [c] 0",
"0>0",
"0 > 0",
"0>=0",
"0 >= 0",
"0<0",
"0 < 0",
"0<=0",
"0 <= 0",
"0 contains 0",
"a CONTAINS[c] b",
"a contains [c] b",
"'a'CONTAINS[c]b",
"0 BeGiNsWiTh 0",
"0 ENDSWITH 0",
"contains contains 'contains'",
"beginswith beginswith 'beginswith'",
"endswith endswith 'endswith'",
"NOT NOT != 'NOT'",
"AND == 'AND' AND OR == 'OR'",
// FIXME - bug
// "truepredicate == 'falsepredicate' && truepredicate",
// atoms/groups
"(0=0)",
"( 0=0 )",
"((0=0))",
"!0=0",
"! 0=0",
"!(0=0)",
"! (0=0)",
"NOT0=0", // keypath NOT0
"NOT0.a=0", // keypath NOT0
"NOT0a.b=0", // keypath NOT0a
"not-1=1",
"not 0=0",
"NOT(0=0)",
"not (0=0)",
"NOT (!0=0)",
// compound
"a==a && a==a",
"a==a || a==a",
"a==a&&a==a||a=a",
"a==a and a==a",
"a==a OR a==a",
"and=='AND'&&'or'=='||'",
"and == or && ORE > GRAND",
"a=1AND NOTb=2",
};
static std::vector<std::string> invalid_queries = {
"predicate",
"'\\a' = ''", // invalid escape
// invalid unicode
"'\\u0' = ''",
// invalid strings
"\"' = ''",
"\" = ''",
"' = ''",
// expressions
"03a = 1",
"1..0 = 1",
"1.0. = 1",
"1-0 = 1",
"0x = 1",
"- = a",
"a..b = a",
"a$a = a",
"{} = $0",
"$-1 = $0",
"$a = $0",
"$ = $",
// operators
"0===>0",
"0 <> 0",
"0 contains1",
"a contains_something",
"endswith 0",
// atoms/groups
"0=0)",
"(0=0",
"(0=0))",
"! =0",
"NOTNOT(0=0)",
"not.a=0",
"(!!0=0)",
"0=0 !",
// compound
"a==a & a==a",
"a==a | a==a",
"a==a &| a==a",
"a==a && OR a==a",
"a==aORa==a",
"a==a ORa==a",
"a==a AND==a",
"a==a ANDa==a",
"a=1ANDNOT b=2",
"truepredicate &&",
"truepredicate & truepredicate",
};
TEST_CASE("valid queries") {
for (auto& query : valid_queries) {
INFO("query: " << query);
CHECK_NOTHROW(realm::parser::parse(query));
}
}
TEST_CASE("invalid queries") {
for (auto& query : invalid_queries) {
INFO("query: " << query);
CHECK_THROWS(realm::parser::parse(query));
}
}
| 19.485207 | 83 | 0.412694 | datasprings |
d706229cc4d2c6bce330f865844b1d24c679b1d4 | 557 | cpp | C++ | chapter09/ex13_rational/main.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 124 | 2018-06-23T10:16:56.000Z | 2022-03-19T15:16:12.000Z | chapter09/ex13_rational/main.cpp | therootfolder/stroustrup-ppp | b1e936c9a67b9205fdc9712c42496b45200514e2 | [
"MIT"
] | 23 | 2018-02-08T20:57:46.000Z | 2021-10-08T13:58:29.000Z | chapter09/ex13_rational/main.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 65 | 2019-05-27T03:05:56.000Z | 2022-03-26T03:43:05.000Z | #include "rational.h"
#include <iostream>
using std::cout;
using std::cin;
using std::cerr;
int main()
try {
cout << "Enter the integers of two rational numbers:\n";
int a, b, c, d;
cin >> a >> b >> c >> d;
Rational r1{a, b};
Rational r2{c, d};
cout << "Add: " << r1 + r2 << '\n'
<< "Sub: " << r1 - r2 << '\n'
<< "Mul: " << r1 * r2 << '\n'
<< "Div: " << r1 / r2 << '\n';
return 0;
}
catch(std::exception& e) {
cerr << e.what() << '\n';
}
catch(...) {
cerr << "unknown exception" << '\n';
}
| 19.206897 | 60 | 0.452424 | ClassAteam |
d707944624be9c4dcb972aaae04b20e0adadf28b | 20,448 | cpp | C++ | Source/astcenc_integer_sequence.cpp | mcraiha/astc-encoder | 4a29609782e852e20478098d11eb2c892bba8c61 | [
"Apache-2.0"
] | 1 | 2022-02-15T21:02:20.000Z | 2022-02-15T21:02:20.000Z | Source/astcenc_integer_sequence.cpp | mcraiha/astc-encoder | 4a29609782e852e20478098d11eb2c892bba8c61 | [
"Apache-2.0"
] | null | null | null | Source/astcenc_integer_sequence.cpp | mcraiha/astc-encoder | 4a29609782e852e20478098d11eb2c892bba8c61 | [
"Apache-2.0"
] | null | null | null | // SPDX-License-Identifier: Apache-2.0
// ----------------------------------------------------------------------------
// Copyright 2011-2021 Arm Limited
//
// 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.
// ----------------------------------------------------------------------------
/**
* @brief Functions for encoding/decoding Bounded Integer Sequence Encoding.
*/
#include "astcenc_internal.h"
#include <array>
// unpacked quint triplets <low,middle,high> for each packed-quint value
static const uint8_t quints_of_integer[128][3] = {
{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {3, 0, 0},
{4, 0, 0}, {0, 4, 0}, {4, 4, 0}, {4, 4, 4},
{0, 1, 0}, {1, 1, 0}, {2, 1, 0}, {3, 1, 0},
{4, 1, 0}, {1, 4, 0}, {4, 4, 1}, {4, 4, 4},
{0, 2, 0}, {1, 2, 0}, {2, 2, 0}, {3, 2, 0},
{4, 2, 0}, {2, 4, 0}, {4, 4, 2}, {4, 4, 4},
{0, 3, 0}, {1, 3, 0}, {2, 3, 0}, {3, 3, 0},
{4, 3, 0}, {3, 4, 0}, {4, 4, 3}, {4, 4, 4},
{0, 0, 1}, {1, 0, 1}, {2, 0, 1}, {3, 0, 1},
{4, 0, 1}, {0, 4, 1}, {4, 0, 4}, {0, 4, 4},
{0, 1, 1}, {1, 1, 1}, {2, 1, 1}, {3, 1, 1},
{4, 1, 1}, {1, 4, 1}, {4, 1, 4}, {1, 4, 4},
{0, 2, 1}, {1, 2, 1}, {2, 2, 1}, {3, 2, 1},
{4, 2, 1}, {2, 4, 1}, {4, 2, 4}, {2, 4, 4},
{0, 3, 1}, {1, 3, 1}, {2, 3, 1}, {3, 3, 1},
{4, 3, 1}, {3, 4, 1}, {4, 3, 4}, {3, 4, 4},
{0, 0, 2}, {1, 0, 2}, {2, 0, 2}, {3, 0, 2},
{4, 0, 2}, {0, 4, 2}, {2, 0, 4}, {3, 0, 4},
{0, 1, 2}, {1, 1, 2}, {2, 1, 2}, {3, 1, 2},
{4, 1, 2}, {1, 4, 2}, {2, 1, 4}, {3, 1, 4},
{0, 2, 2}, {1, 2, 2}, {2, 2, 2}, {3, 2, 2},
{4, 2, 2}, {2, 4, 2}, {2, 2, 4}, {3, 2, 4},
{0, 3, 2}, {1, 3, 2}, {2, 3, 2}, {3, 3, 2},
{4, 3, 2}, {3, 4, 2}, {2, 3, 4}, {3, 3, 4},
{0, 0, 3}, {1, 0, 3}, {2, 0, 3}, {3, 0, 3},
{4, 0, 3}, {0, 4, 3}, {0, 0, 4}, {1, 0, 4},
{0, 1, 3}, {1, 1, 3}, {2, 1, 3}, {3, 1, 3},
{4, 1, 3}, {1, 4, 3}, {0, 1, 4}, {1, 1, 4},
{0, 2, 3}, {1, 2, 3}, {2, 2, 3}, {3, 2, 3},
{4, 2, 3}, {2, 4, 3}, {0, 2, 4}, {1, 2, 4},
{0, 3, 3}, {1, 3, 3}, {2, 3, 3}, {3, 3, 3},
{4, 3, 3}, {3, 4, 3}, {0, 3, 4}, {1, 3, 4}
};
// packed quint-value for every unpacked quint-triplet
// indexed by [high][middle][low]
static const uint8_t integer_of_quints[5][5][5] = {
{
{0, 1, 2, 3, 4},
{8, 9, 10, 11, 12},
{16, 17, 18, 19, 20},
{24, 25, 26, 27, 28},
{5, 13, 21, 29, 6}
},
{
{32, 33, 34, 35, 36},
{40, 41, 42, 43, 44},
{48, 49, 50, 51, 52},
{56, 57, 58, 59, 60},
{37, 45, 53, 61, 14}
},
{
{64, 65, 66, 67, 68},
{72, 73, 74, 75, 76},
{80, 81, 82, 83, 84},
{88, 89, 90, 91, 92},
{69, 77, 85, 93, 22}
},
{
{96, 97, 98, 99, 100},
{104, 105, 106, 107, 108},
{112, 113, 114, 115, 116},
{120, 121, 122, 123, 124},
{101, 109, 117, 125, 30}
},
{
{102, 103, 70, 71, 38},
{110, 111, 78, 79, 46},
{118, 119, 86, 87, 54},
{126, 127, 94, 95, 62},
{39, 47, 55, 63, 31}
}
};
// unpacked trit quintuplets <low,_,_,_,high> for each packed-quint value
static const uint8_t trits_of_integer[256][5] = {
{0, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {2, 0, 0, 0, 0}, {0, 0, 2, 0, 0},
{0, 1, 0, 0, 0}, {1, 1, 0, 0, 0}, {2, 1, 0, 0, 0}, {1, 0, 2, 0, 0},
{0, 2, 0, 0, 0}, {1, 2, 0, 0, 0}, {2, 2, 0, 0, 0}, {2, 0, 2, 0, 0},
{0, 2, 2, 0, 0}, {1, 2, 2, 0, 0}, {2, 2, 2, 0, 0}, {2, 0, 2, 0, 0},
{0, 0, 1, 0, 0}, {1, 0, 1, 0, 0}, {2, 0, 1, 0, 0}, {0, 1, 2, 0, 0},
{0, 1, 1, 0, 0}, {1, 1, 1, 0, 0}, {2, 1, 1, 0, 0}, {1, 1, 2, 0, 0},
{0, 2, 1, 0, 0}, {1, 2, 1, 0, 0}, {2, 2, 1, 0, 0}, {2, 1, 2, 0, 0},
{0, 0, 0, 2, 2}, {1, 0, 0, 2, 2}, {2, 0, 0, 2, 2}, {0, 0, 2, 2, 2},
{0, 0, 0, 1, 0}, {1, 0, 0, 1, 0}, {2, 0, 0, 1, 0}, {0, 0, 2, 1, 0},
{0, 1, 0, 1, 0}, {1, 1, 0, 1, 0}, {2, 1, 0, 1, 0}, {1, 0, 2, 1, 0},
{0, 2, 0, 1, 0}, {1, 2, 0, 1, 0}, {2, 2, 0, 1, 0}, {2, 0, 2, 1, 0},
{0, 2, 2, 1, 0}, {1, 2, 2, 1, 0}, {2, 2, 2, 1, 0}, {2, 0, 2, 1, 0},
{0, 0, 1, 1, 0}, {1, 0, 1, 1, 0}, {2, 0, 1, 1, 0}, {0, 1, 2, 1, 0},
{0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {2, 1, 1, 1, 0}, {1, 1, 2, 1, 0},
{0, 2, 1, 1, 0}, {1, 2, 1, 1, 0}, {2, 2, 1, 1, 0}, {2, 1, 2, 1, 0},
{0, 1, 0, 2, 2}, {1, 1, 0, 2, 2}, {2, 1, 0, 2, 2}, {1, 0, 2, 2, 2},
{0, 0, 0, 2, 0}, {1, 0, 0, 2, 0}, {2, 0, 0, 2, 0}, {0, 0, 2, 2, 0},
{0, 1, 0, 2, 0}, {1, 1, 0, 2, 0}, {2, 1, 0, 2, 0}, {1, 0, 2, 2, 0},
{0, 2, 0, 2, 0}, {1, 2, 0, 2, 0}, {2, 2, 0, 2, 0}, {2, 0, 2, 2, 0},
{0, 2, 2, 2, 0}, {1, 2, 2, 2, 0}, {2, 2, 2, 2, 0}, {2, 0, 2, 2, 0},
{0, 0, 1, 2, 0}, {1, 0, 1, 2, 0}, {2, 0, 1, 2, 0}, {0, 1, 2, 2, 0},
{0, 1, 1, 2, 0}, {1, 1, 1, 2, 0}, {2, 1, 1, 2, 0}, {1, 1, 2, 2, 0},
{0, 2, 1, 2, 0}, {1, 2, 1, 2, 0}, {2, 2, 1, 2, 0}, {2, 1, 2, 2, 0},
{0, 2, 0, 2, 2}, {1, 2, 0, 2, 2}, {2, 2, 0, 2, 2}, {2, 0, 2, 2, 2},
{0, 0, 0, 0, 2}, {1, 0, 0, 0, 2}, {2, 0, 0, 0, 2}, {0, 0, 2, 0, 2},
{0, 1, 0, 0, 2}, {1, 1, 0, 0, 2}, {2, 1, 0, 0, 2}, {1, 0, 2, 0, 2},
{0, 2, 0, 0, 2}, {1, 2, 0, 0, 2}, {2, 2, 0, 0, 2}, {2, 0, 2, 0, 2},
{0, 2, 2, 0, 2}, {1, 2, 2, 0, 2}, {2, 2, 2, 0, 2}, {2, 0, 2, 0, 2},
{0, 0, 1, 0, 2}, {1, 0, 1, 0, 2}, {2, 0, 1, 0, 2}, {0, 1, 2, 0, 2},
{0, 1, 1, 0, 2}, {1, 1, 1, 0, 2}, {2, 1, 1, 0, 2}, {1, 1, 2, 0, 2},
{0, 2, 1, 0, 2}, {1, 2, 1, 0, 2}, {2, 2, 1, 0, 2}, {2, 1, 2, 0, 2},
{0, 2, 2, 2, 2}, {1, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {2, 0, 2, 2, 2},
{0, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {2, 0, 0, 0, 1}, {0, 0, 2, 0, 1},
{0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {2, 1, 0, 0, 1}, {1, 0, 2, 0, 1},
{0, 2, 0, 0, 1}, {1, 2, 0, 0, 1}, {2, 2, 0, 0, 1}, {2, 0, 2, 0, 1},
{0, 2, 2, 0, 1}, {1, 2, 2, 0, 1}, {2, 2, 2, 0, 1}, {2, 0, 2, 0, 1},
{0, 0, 1, 0, 1}, {1, 0, 1, 0, 1}, {2, 0, 1, 0, 1}, {0, 1, 2, 0, 1},
{0, 1, 1, 0, 1}, {1, 1, 1, 0, 1}, {2, 1, 1, 0, 1}, {1, 1, 2, 0, 1},
{0, 2, 1, 0, 1}, {1, 2, 1, 0, 1}, {2, 2, 1, 0, 1}, {2, 1, 2, 0, 1},
{0, 0, 1, 2, 2}, {1, 0, 1, 2, 2}, {2, 0, 1, 2, 2}, {0, 1, 2, 2, 2},
{0, 0, 0, 1, 1}, {1, 0, 0, 1, 1}, {2, 0, 0, 1, 1}, {0, 0, 2, 1, 1},
{0, 1, 0, 1, 1}, {1, 1, 0, 1, 1}, {2, 1, 0, 1, 1}, {1, 0, 2, 1, 1},
{0, 2, 0, 1, 1}, {1, 2, 0, 1, 1}, {2, 2, 0, 1, 1}, {2, 0, 2, 1, 1},
{0, 2, 2, 1, 1}, {1, 2, 2, 1, 1}, {2, 2, 2, 1, 1}, {2, 0, 2, 1, 1},
{0, 0, 1, 1, 1}, {1, 0, 1, 1, 1}, {2, 0, 1, 1, 1}, {0, 1, 2, 1, 1},
{0, 1, 1, 1, 1}, {1, 1, 1, 1, 1}, {2, 1, 1, 1, 1}, {1, 1, 2, 1, 1},
{0, 2, 1, 1, 1}, {1, 2, 1, 1, 1}, {2, 2, 1, 1, 1}, {2, 1, 2, 1, 1},
{0, 1, 1, 2, 2}, {1, 1, 1, 2, 2}, {2, 1, 1, 2, 2}, {1, 1, 2, 2, 2},
{0, 0, 0, 2, 1}, {1, 0, 0, 2, 1}, {2, 0, 0, 2, 1}, {0, 0, 2, 2, 1},
{0, 1, 0, 2, 1}, {1, 1, 0, 2, 1}, {2, 1, 0, 2, 1}, {1, 0, 2, 2, 1},
{0, 2, 0, 2, 1}, {1, 2, 0, 2, 1}, {2, 2, 0, 2, 1}, {2, 0, 2, 2, 1},
{0, 2, 2, 2, 1}, {1, 2, 2, 2, 1}, {2, 2, 2, 2, 1}, {2, 0, 2, 2, 1},
{0, 0, 1, 2, 1}, {1, 0, 1, 2, 1}, {2, 0, 1, 2, 1}, {0, 1, 2, 2, 1},
{0, 1, 1, 2, 1}, {1, 1, 1, 2, 1}, {2, 1, 1, 2, 1}, {1, 1, 2, 2, 1},
{0, 2, 1, 2, 1}, {1, 2, 1, 2, 1}, {2, 2, 1, 2, 1}, {2, 1, 2, 2, 1},
{0, 2, 1, 2, 2}, {1, 2, 1, 2, 2}, {2, 2, 1, 2, 2}, {2, 1, 2, 2, 2},
{0, 0, 0, 1, 2}, {1, 0, 0, 1, 2}, {2, 0, 0, 1, 2}, {0, 0, 2, 1, 2},
{0, 1, 0, 1, 2}, {1, 1, 0, 1, 2}, {2, 1, 0, 1, 2}, {1, 0, 2, 1, 2},
{0, 2, 0, 1, 2}, {1, 2, 0, 1, 2}, {2, 2, 0, 1, 2}, {2, 0, 2, 1, 2},
{0, 2, 2, 1, 2}, {1, 2, 2, 1, 2}, {2, 2, 2, 1, 2}, {2, 0, 2, 1, 2},
{0, 0, 1, 1, 2}, {1, 0, 1, 1, 2}, {2, 0, 1, 1, 2}, {0, 1, 2, 1, 2},
{0, 1, 1, 1, 2}, {1, 1, 1, 1, 2}, {2, 1, 1, 1, 2}, {1, 1, 2, 1, 2},
{0, 2, 1, 1, 2}, {1, 2, 1, 1, 2}, {2, 2, 1, 1, 2}, {2, 1, 2, 1, 2},
{0, 2, 2, 2, 2}, {1, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {2, 1, 2, 2, 2}
};
// packed trit-value for every unpacked trit-quintuplet
// indexed by [high][][][][low]
static const uint8_t integer_of_trits[3][3][3][3][3] = {
{
{
{
{0, 1, 2},
{4, 5, 6},
{8, 9, 10}
},
{
{16, 17, 18},
{20, 21, 22},
{24, 25, 26}
},
{
{3, 7, 15},
{19, 23, 27},
{12, 13, 14}
}
},
{
{
{32, 33, 34},
{36, 37, 38},
{40, 41, 42}
},
{
{48, 49, 50},
{52, 53, 54},
{56, 57, 58}
},
{
{35, 39, 47},
{51, 55, 59},
{44, 45, 46}
}
},
{
{
{64, 65, 66},
{68, 69, 70},
{72, 73, 74}
},
{
{80, 81, 82},
{84, 85, 86},
{88, 89, 90}
},
{
{67, 71, 79},
{83, 87, 91},
{76, 77, 78}
}
}
},
{
{
{
{128, 129, 130},
{132, 133, 134},
{136, 137, 138}
},
{
{144, 145, 146},
{148, 149, 150},
{152, 153, 154}
},
{
{131, 135, 143},
{147, 151, 155},
{140, 141, 142}
}
},
{
{
{160, 161, 162},
{164, 165, 166},
{168, 169, 170}
},
{
{176, 177, 178},
{180, 181, 182},
{184, 185, 186}
},
{
{163, 167, 175},
{179, 183, 187},
{172, 173, 174}
}
},
{
{
{192, 193, 194},
{196, 197, 198},
{200, 201, 202}
},
{
{208, 209, 210},
{212, 213, 214},
{216, 217, 218}
},
{
{195, 199, 207},
{211, 215, 219},
{204, 205, 206}
}
}
},
{
{
{
{96, 97, 98},
{100, 101, 102},
{104, 105, 106}
},
{
{112, 113, 114},
{116, 117, 118},
{120, 121, 122}
},
{
{99, 103, 111},
{115, 119, 123},
{108, 109, 110}
}
},
{
{
{224, 225, 226},
{228, 229, 230},
{232, 233, 234}
},
{
{240, 241, 242},
{244, 245, 246},
{248, 249, 250}
},
{
{227, 231, 239},
{243, 247, 251},
{236, 237, 238}
}
},
{
{
{28, 29, 30},
{60, 61, 62},
{92, 93, 94}
},
{
{156, 157, 158},
{188, 189, 190},
{220, 221, 222}
},
{
{31, 63, 127},
{159, 191, 255},
{252, 253, 254}
}
}
}
};
/**
* @brief The number of bits, trits, and quints needed for a quant level.
*/
struct btq_count {
/**< The quantization level. */
uint8_t quant;
/**< The number of bits. */
uint8_t bits;
/**< The number of trits. */
uint8_t trits;
/**< The number of quints. */
uint8_t quints;
};
/**
* @brief The table of bits, trits, and quints needed for a quant encode.
*/
static const std::array<btq_count, 21> btq_counts = {{
{ QUANT_2, 1, 0, 0 },
{ QUANT_3, 0, 1, 0 },
{ QUANT_4, 2, 0, 0 },
{ QUANT_5, 0, 0, 1 },
{ QUANT_6, 1, 1, 0 },
{ QUANT_8, 3, 0, 0 },
{ QUANT_10, 1, 0, 1 },
{ QUANT_12, 2, 1, 0 },
{ QUANT_16, 4, 0, 0 },
{ QUANT_20, 2, 0, 1 },
{ QUANT_24, 3, 1, 0 },
{ QUANT_32, 5, 0, 0 },
{ QUANT_40, 3, 0, 1 },
{ QUANT_48, 4, 1, 0 },
{ QUANT_64, 6, 0, 0 },
{ QUANT_80, 4, 0, 1 },
{ QUANT_96, 5, 1, 0 },
{ QUANT_128, 7, 0, 0 },
{ QUANT_160, 5, 0, 1 },
{ QUANT_192, 6, 1, 0 },
{ QUANT_256, 8, 0, 0 }
}};
/**
* @brief The sequence scale, round, and divisors needed to compute sizing.
*
* The length of a quantized sequence in bits is:
* (scale * <sequence_len> + round) / divisor
*/
struct ise_size {
/**< The quantization level. */
uint8_t quant;
/**< The scaling parameter. */
uint8_t scale;
/**< The rounding parameter. */
uint8_t round;
/**< The divisor parameter. */
uint8_t divisor;
};
/**
* @brief The table of scale, round, and divisors needed for quant sizing.
*/
static const std::array<ise_size, 21> ise_sizes = {{
{ QUANT_2, 1, 0, 1 },
{ QUANT_3, 8, 4, 5 },
{ QUANT_4, 2, 0, 1 },
{ QUANT_5, 7, 2, 3 },
{ QUANT_6, 13, 4, 5 },
{ QUANT_8, 3, 0, 1 },
{ QUANT_10, 10, 2, 3 },
{ QUANT_12, 18, 4, 5 },
{ QUANT_16, 4, 0, 1 },
{ QUANT_20, 13, 2, 3 },
{ QUANT_24, 23, 4, 5 },
{ QUANT_32, 5, 0, 1 },
{ QUANT_40, 16, 2, 3 },
{ QUANT_48, 28, 4, 5 },
{ QUANT_64, 6, 0, 1 },
{ QUANT_80, 19, 2, 3 },
{ QUANT_96, 33, 4, 5 },
{ QUANT_128, 7, 0, 1 },
{ QUANT_160, 22, 2, 3 },
{ QUANT_192, 38, 4, 5 },
{ QUANT_256, 8, 0, 1 }
}};
/* See header for documentation. */
int get_ise_sequence_bitcount(
int items,
quant_method quant
) {
// Cope with out-of bounds values - input might be invalid
if (static_cast<size_t>(quant) >= ise_sizes.size())
{
// Arbitrary large number that's more than an ASTC block can hold
return 1024;
}
auto& entry = ise_sizes[quant];
return (entry.scale * items + entry.round) / entry.divisor;
}
// routine to write up to 8 bits
static inline void write_bits(
int value,
int bitcount,
int bitoffset,
uint8_t* ptr
) {
int mask = (1 << bitcount) - 1;
value &= mask;
ptr += bitoffset >> 3;
bitoffset &= 7;
value <<= bitoffset;
mask <<= bitoffset;
mask = ~mask;
ptr[0] &= mask;
ptr[0] |= value;
ptr[1] &= mask >> 8;
ptr[1] |= value >> 8;
}
// routine to read up to 8 bits
static inline int read_bits(
int bitcount,
int bitoffset,
const uint8_t* ptr
) {
int mask = (1 << bitcount) - 1;
ptr += bitoffset >> 3;
bitoffset &= 7;
int value = ptr[0] | (ptr[1] << 8);
value >>= bitoffset;
value &= mask;
return value;
}
void encode_ise(
int quant_level,
int elements,
const uint8_t* input_data,
uint8_t* output_data,
int bit_offset
) {
int bits = btq_counts[quant_level].bits;
int trits = btq_counts[quant_level].trits;
int quints = btq_counts[quant_level].quints;
int mask = (1 << bits) - 1;
// Write out trits and bits
if (trits)
{
int i = 0;
int full_trit_blocks = elements / 5;
for (int j = 0; j < full_trit_blocks; j++)
{
int i4 = input_data[i + 4] >> bits;
int i3 = input_data[i + 3] >> bits;
int i2 = input_data[i + 2] >> bits;
int i1 = input_data[i + 1] >> bits;
int i0 = input_data[i + 0] >> bits;
uint8_t T = integer_of_trits[i4][i3][i2][i1][i0];
// The max size of a trit bit count is 6, so we can always safely
// pack a single MX value with the following 1 or 2 T bits.
uint8_t pack;
// Element 0 + T0 + T1
pack = (input_data[i++] & mask) | (((T >> 0) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
// Element 1 + T2 + T3
pack = (input_data[i++] & mask) | (((T >> 2) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
// Element 2 + T4
pack = (input_data[i++] & mask) | (((T >> 4) & 0x1) << bits);
write_bits(pack, bits + 1, bit_offset, output_data);
bit_offset += bits + 1;
// Element 3 + T5 + T6
pack = (input_data[i++] & mask) | (((T >> 5) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
// Element 4 + T7
pack = (input_data[i++] & mask) | (((T >> 7) & 0x1) << bits);
write_bits(pack, bits + 1, bit_offset, output_data);
bit_offset += bits + 1;
}
// Loop tail for a partial block
if (i != elements)
{
// i4 cannot be present - we know the block is partial
// i0 must be present - we know the block isn't empty
int i4 = 0;
int i3 = i + 3 >= elements ? 0 : input_data[i + 3] >> bits;
int i2 = i + 2 >= elements ? 0 : input_data[i + 2] >> bits;
int i1 = i + 1 >= elements ? 0 : input_data[i + 1] >> bits;
int i0 = input_data[i + 0] >> bits;
uint8_t T = integer_of_trits[i4][i3][i2][i1][i0];
for (int j = 0; i < elements; i++, j++)
{
// Truncated table as this iteration is always partital
static const uint8_t tbits[4] { 2, 2, 1, 2 };
static const uint8_t tshift[4] { 0, 2, 4, 5 };
uint8_t pack = (input_data[i] & mask) |
(((T >> tshift[j]) & ((1 << tbits[j]) - 1)) << bits);
write_bits(pack, bits + tbits[j], bit_offset, output_data);
bit_offset += bits + tbits[j];
}
}
}
// Write out quints and bits
else if (quints)
{
int i = 0;
int full_quint_blocks = elements / 3;
for (int j = 0; j < full_quint_blocks; j++)
{
int i2 = input_data[i + 2] >> bits;
int i1 = input_data[i + 1] >> bits;
int i0 = input_data[i + 0] >> bits;
uint8_t T = integer_of_quints[i2][i1][i0];
// The max size of a quint bit count is 5, so we can always safely
// pack a single M value with the following 2 or 3 T bits.
uint8_t pack;
// Element 0
pack = (input_data[i++] & mask) | (((T >> 0) & 0x7) << bits);
write_bits(pack, bits + 3, bit_offset, output_data);
bit_offset += bits + 3;
// Element 1
pack = (input_data[i++] & mask) | (((T >> 3) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
// Element 2
pack = (input_data[i++] & mask) | (((T >> 5) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
}
// Loop tail for a partial block
if (i != elements)
{
// i2 cannot be present - we know the block is partial
// i0 must be present - we know the block isn't empty
int i2 = 0;
int i1 = i + 1 >= elements ? 0 : input_data[i + 1] >> bits;
int i0 = input_data[i + 0] >> bits;
uint8_t T = integer_of_quints[i2][i1][i0];
for (int j = 0; i < elements; i++, j++)
{
// Truncated table as this iteration is always partital
static const uint8_t tbits[2] { 3, 2 };
static const uint8_t tshift[2] { 0, 3 };
uint8_t pack = (input_data[i] & mask) |
(((T >> tshift[j]) & ((1 << tbits[j]) - 1)) << bits);
write_bits(pack, bits + tbits[j], bit_offset, output_data);
bit_offset += bits + tbits[j];
}
}
}
// Write out just bits
else
{
promise(elements > 0);
for (int i = 0; i < elements; i++)
{
write_bits(input_data[i], bits, bit_offset, output_data);
bit_offset += bits;
}
}
}
void decode_ise(
int quant_level,
int elements,
const uint8_t* input_data,
uint8_t* output_data,
int bit_offset
) {
// note: due to how the trit/quint-block unpacking is done in this function,
// we may write more temporary results than the number of outputs
// The maximum actual number of results is 64 bit, but we keep 4 additional elements
// of padding.
uint8_t results[68];
uint8_t tq_blocks[22]; // trit-blocks or quint-blocks
int bits = btq_counts[quant_level].bits;
int trits = btq_counts[quant_level].trits;
int quints = btq_counts[quant_level].quints;
int lcounter = 0;
int hcounter = 0;
// trit-blocks or quint-blocks must be zeroed out before we collect them in the loop below.
for (int i = 0; i < 22; i++)
{
tq_blocks[i] = 0;
}
// collect bits for each element, as well as bits for any trit-blocks and quint-blocks.
for (int i = 0; i < elements; i++)
{
results[i] = read_bits(bits, bit_offset, input_data);
bit_offset += bits;
if (trits)
{
static const int bits_to_read[5] { 2, 2, 1, 2, 1 };
static const int block_shift[5] { 0, 2, 4, 5, 7 };
static const int next_lcounter[5] { 1, 2, 3, 4, 0 };
static const int hcounter_incr[5] { 0, 0, 0, 0, 1 };
int tdata = read_bits(bits_to_read[lcounter], bit_offset, input_data);
bit_offset += bits_to_read[lcounter];
tq_blocks[hcounter] |= tdata << block_shift[lcounter];
hcounter += hcounter_incr[lcounter];
lcounter = next_lcounter[lcounter];
}
if (quints)
{
static const int bits_to_read[3] { 3, 2, 2 };
static const int block_shift[3] { 0, 3, 5 };
static const int next_lcounter[3] { 1, 2, 0 };
static const int hcounter_incr[3] { 0, 0, 1 };
int tdata = read_bits(bits_to_read[lcounter], bit_offset, input_data);
bit_offset += bits_to_read[lcounter];
tq_blocks[hcounter] |= tdata << block_shift[lcounter];
hcounter += hcounter_incr[lcounter];
lcounter = next_lcounter[lcounter];
}
}
// unpack trit-blocks or quint-blocks as needed
if (trits)
{
int trit_blocks = (elements + 4) / 5;
for (int i = 0; i < trit_blocks; i++)
{
const uint8_t *tritptr = trits_of_integer[tq_blocks[i]];
results[5 * i ] |= tritptr[0] << bits;
results[5 * i + 1] |= tritptr[1] << bits;
results[5 * i + 2] |= tritptr[2] << bits;
results[5 * i + 3] |= tritptr[3] << bits;
results[5 * i + 4] |= tritptr[4] << bits;
}
}
if (quints)
{
int quint_blocks = (elements + 2) / 3;
for (int i = 0; i < quint_blocks; i++)
{
const uint8_t *quintptr = quints_of_integer[tq_blocks[i]];
results[3 * i ] |= quintptr[0] << bits;
results[3 * i + 1] |= quintptr[1] << bits;
results[3 * i + 2] |= quintptr[2] << bits;
}
}
for (int i = 0; i < elements; i++)
{
output_data[i] = results[i];
}
}
| 28.204138 | 92 | 0.474129 | mcraiha |
d70a542567640fbbfc7db0105734f135eeddc7f7 | 18,661 | cpp | C++ | big_vec.cpp | jlinton/x4vecs | 1b91810f1ae8e793005687f0d04a6f0a1ec3ed96 | [
"MIT"
] | 2 | 2015-05-12T02:33:14.000Z | 2016-07-13T13:49:18.000Z | big_vec.cpp | jlinton/x4vecs | 1b91810f1ae8e793005687f0d04a6f0a1ec3ed96 | [
"MIT"
] | null | null | null | big_vec.cpp | jlinton/x4vecs | 1b91810f1ae8e793005687f0d04a6f0a1ec3ed96 | [
"MIT"
] | 1 | 2020-09-04T01:27:24.000Z | 2020-09-04T01:27:24.000Z | // Copyright (c) 2021 Jeremy Linton
//
// big_vec.cpp
// C++ wrapper around the $PLAT_objs.cpp vector to extend its len
//
//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.
// To build some basic unit tests for this module do:
// g++ -mfloat-abi=softfp -mfpu=neon -g -O3 -std=c++11 big_vec.cpp
// or
// g++ -msse3 -g -O3 -std=c++11 big_vec.cpp
// AVXx8 version
// g++ -mavx -g -O3 -std=c++11 big_vec.cpp
#define NO_MAIN
#ifdef __ARM_NEON__
#include "neon_objs.cpp"
#elif defined(__SSE3__)
#include "sse_objs2.cpp"
#else
#include "portable_objs.cpp"
#endif
// big allocs might need something like -Wl,-z,stack-size=XXXX; ulimit -s XXXXX
// define arbitrary len vector in relation to HW vector class
//
#define VECS ((ELEM_CNT/VEC_CNT)?(ELEM_CNT/VEC_CNT):1)
template<int VEC_CNT, int ELEM_CNT, class VEC_T> class BigVector
{
public:
BigVector():vec() {}; //construct unititalized
BigVector(BigVector *src) { for (int x=0;x<VECS;x++) vec[x]=src->vec[x]; };
BigVector(BigVector &src) { for (int x=0;x<VECS;x++) vec[x]=src.vec[x]; };
BigVector(VEC_T *src,int src_cnt) { VEC_T tmp(0.0); for (int x=0;x<VECS;x++) vec[x]=tmp; for (int x=0;x<src_cnt;x++) vec[x]=src[x]; }; //allows a resize op
//BigVector(double *fill) {VEC_T tmp(fill); for (int x=0;x<VECS;x++) vec[x]=tmp;}
template <typename... Args> BigVector(Args... args) {VEC_T tmp(0.0); for (int x=0;x<VECS;x++) vec[x]=tmp; Set(0, args...); }; // if this aborts, verify vec is properly aligned (32 bytes for x8)
// POD copy construct
// assign
BigVector & operator=(const BigVector &src_prm) { for (int x=0;x<VECS;x++) vec[x]=src_prm.vec[x]; return *this;}
BigVector & operator=(const float src[ELEM_CNT]) { for (int x=0;x<ELEM_CNT;x++) vec[x/VEC_CNT].Set(x-(x/VEC_CNT)*VEC_CNT,src[x]); return *this;};
void Set(int off, float Val) {const int n=off/VEC_CNT; vec[n].Set(off-n*VEC_CNT, Val); }
void Fill(float Val) {VEC_T tmp(Val); for (int x=1;x<VEC_CNT;x++) tmp.Set(x,Val); for (int x=0;x<VECS;x++) vec[x]=tmp;}
template <typename... Args> void Set(int off, float Val, Args... args) { int n=off/VEC_CNT; vec[n].Set(off-n*VEC_CNT, Val); Set(++off,args...); };
// reads
float operator[](int index_prm) const {int n=index_prm/VEC_CNT; return vec[n][index_prm-n*VEC_CNT];};
//BigVector Get(int index_prm);
//void save(float *dst_prm) { };
std::string as_str(const char *format_prm="%05.2f ") { std::string fmt; for (int x=0;x<VEC_CNT;x++) fmt+=format_prm; std::string tmp; for (int x=0;x<VECS;x++) tmp+=vec[x].as_str(fmt.c_str()); return tmp; }
// adds urinary
BigVector & operator+=(const BigVector &src2) { for (int x=0;x<VECS;x++) vec[x]+=src2.vec[x]; return *this;}
BigVector & operator-=(const BigVector &src2) { for (int x=0;x<VECS;x++) vec[x]-=src2.vec[x]; return *this;}
BigVector & operator+=(const float src2) { for (int x=0;x<VECS;x++) vec[x]+=src2; return *this;}
BigVector & operator-=(const float src2) { for (int x=0;x<VECS;x++) vec[x]-=src2;; return *this;}
// adds binary
BigVector const operator+ (const BigVector &src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]+src2.vec[x]; return tmp;}
BigVector const operator- (const BigVector &src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]-src2.vec[x]; return tmp;}
BigVector const operator+ (const float src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]+src2; return tmp;}
BigVector const operator- (const float src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]-src2; return tmp;}
// muls urinary
BigVector & operator*=(const BigVector &src2) { for (int x=0;x<VECS;x++) vec[x]*src2.vec[x]; return *this;}
BigVector & operator/=(const BigVector &src2) { for (int x=0;x<VECS;x++) vec[x]/src2.vec[x]; return *this;}
BigVector & operator*=(const float src2) { for (int x=0;x<VECS;x++) vec[x]=vec[x]*src2; return *this;}
BigVector & operator/=(const float src2) { for (int x=0;x<VECS;x++) vec[x]=vec[x]/src2; return *this;}
// muls binary
BigVector const operator* (const BigVector &src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]*src2.vec[x]; return tmp;}
BigVector const operator/ (const BigVector &src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]/src2.vec[x]; return tmp;}
BigVector const operator* (const float src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]*src2; return tmp;}
BigVector const operator/ (const float src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]/src2; return tmp;}
// other manipulations
float ElementSum(void) const { float tmp=0; for (int x=0;x<VECS;x++) tmp+=vec[x].ElementSum(); return tmp; }
float fma(BigVector &src2) {return 0.0;}//implement fma (which requires the underlying vector to do it too)
VEC_T *raw() {return vec;}
int raw_sz() {return VECS;}
private:
VEC_T vec[VECS];
};
// square matrix based on big vecs above
// most of these loops should be expanded with openMP if the matrix sizes get sufficiently large
template<int SIZE, class VEC_T> class MatrixS
{
public:
MatrixS() {} //construct unititalized
MatrixS(float val) { VEC_T tmp; tmp.Fill(val); for (int x=0;x<SIZE;x++) vecs[x]=tmp; }
MatrixS(const MatrixS &orig) {for (int x=0; x<SIZE; x++) vecs[x]=orig.vecs[x]; }
// assign
//BigVector & operator=(const BigVector &src_prm) { for (int x=0;x<VECS;x++) vec[x]=src_prm.vec[x]; }
//BigVector & operator=(const float src[ELEM_CNT]) { for (int x=0;x<ELEM_CNT;x++) vec[x/VEC_CNT].Set(x-(x/VEC_CNT)*VEC_CNT,src[x]);};
void Set(int col, int row, float Val) { vecs[row].Set(col, Val); }
//template <typename... Args> void Set(int off, float Val, Args... args) { int n=off/VEC_CNT; vec[n].Set(off-n*VEC_CNT, Val); Set(++off,args...); };
// reads
VEC_T &operator[](int index_prm) {return vecs[index_prm];};
float Get(int row,int col) {return vecs[row][col];}
//void save(float *dst_prm) { };
std::string as_str(const char *format_prm="%05.2f,") { std::string ret; for (int x=0;x<SIZE;x++) ret+=vecs[x].as_str(format_prm)+";\n"; return ret; }
// adds urinary
MatrixS & operator+=(const MatrixS &src2) { for (int x=0;x<SIZE;x++) vecs[x]+=src2.vec[x]; return *this;}
MatrixS & operator-=(const MatrixS &src2) { for (int x=0;x<SIZE;x++) vecs[x]-=src2.vec[x]; return *this;}
MatrixS & operator+=(const float src2) { for (int x=0;x<SIZE;x++) vecs[x]+=src2; return *this;}
MatrixS & operator-=(const float src2) { for (int x=0;x<SIZE;x++) vecs[x]-=src2;; return *this;}
// muls urinary
MatrixS & operator*=(const MatrixS &src2)
{
MatrixS Trans(src2); //todo heap allocate if matrix is really large (or maybe do something requiring the caller to pre transpose it?, or just use the gather loads..
Trans.Transpose();
for (int x=0; x<SIZE; x++)
{
VEC_T result;
for (int y=0; y<SIZE; y++)
{
float val = (vecs[x] * Trans.vecs[y]).ElementSum();
result.Set(y, val);
}
vecs[x]=result;
}
return *this;
}
MatrixS & operator/=(const MatrixS &src2)
{
MatrixS Trans(src2);
Trans.Transpose();
for (int x=0; x<SIZE; x++)
{
VEC_T result;
for (int y=0; y<SIZE; y++)
{
float val = (vecs[x] / Trans.vecs[y]).ElementSum();
result.Set(y, val);
}
vecs[x]=result;
}
return *this;
}
VEC_T & operator*=(const VEC_T &src2) { VEC_T ret; for (int x=0;x<SIZE;x++) ret.Set(x,(vecs[x]*src2).ElementSum()); return *this;}
VEC_T & operator/=(const VEC_T &src2) { VEC_T ret; for (int x=0;x<SIZE;x++) ret.Set(x,(vecs[x]/src2).ElementSum()); return *this;} //probably should build inverse vec?
MatrixS & operator*=(const float src2) { for (int x=0;x<SIZE;x++) vecs[x]*=src2; return *this;}
MatrixS & operator/=(const float src2) { for (int x=0;x<SIZE;x++) vecs[x]/=src2;; return *this;}
//other ops
void Transpose() { for (int x=1;x<SIZE;x++) for (int y=0;y<x;y++) { float tmp=vecs[x][y]; vecs[x].Set(y,vecs[y][x]); vecs[y].Set(x,tmp); } } //do something smarter?
void det() {
MatrixS ret(0);
for (int i=0;i<SIZE;i++)
{
}
}
// inverse
private:
VEC_T vecs[SIZE];
};
// non square matrix based on big vecs above
// most of these loops should be expanded with openMP if the matrix sizes get sufficiently large
#ifdef __AVX__
template<int SIZE_ROW,int SIZE_COL, class VEC_TR = BigVector<8,SIZE_ROW,SSEx8>, class VEC_TC = BigVector<8,SIZE_COL,SSEx8>> class MatrixST
#else
template<int SIZE_ROW,int SIZE_COL, class VEC_TR = BigVector<4,SIZE_ROW,Vec4>, class VEC_TC = BigVector<4,SIZE_COL,Vec4>> class MatrixST
#endif
{
// typedef BigVector<4,SIZE_ROW,Vec4> VEC_TX;
public:
MatrixST() {} //construct unititalized
MatrixST(float val) { VEC_TR tmp; tmp.Fill(val); for (int y=0;y<SIZE_COL;y++) vecs[y]=tmp; }
MatrixST(const MatrixST &orig) {for (int y=0; y<SIZE_COL; y++) vecs[y]=orig.vecs[y]; }
// assign
//BigVector & operator=(const BigVector &src_prm) { for (int x=0;x<VECS;x++) vec[x]=src_prm.vec[x]; }
//BigVector & operator=(const float src[ELEM_CNT]) { for (int x=0;x<ELEM_CNT;x++) vec[x/VEC_CNT].Set(x-(x/VEC_CNT)*VEC_CNT,src[x]);};
void Set(int col, int row, float Val) { vecs[row].Set(col, Val); }
//template <typename... Args> void Set(int off, float Val, Args... args) { int n=off/VEC_CNT; vec[n].Set(off-n*VEC_CNT, Val); Set(++off,args...); };
// reads
VEC_TR &operator[](int index_prm) {return vecs[index_prm];};
float Get(int col,int row) {return vecs[row][col];}
//void save(float *dst_prm) { };
std::string as_str(const char *format_prm="%05.2f,") { std::string ret; for (int x=0;x<SIZE_COL;x++) ret+=vecs[x].as_str(format_prm)+";\n"; return ret; }
// adds urinary
MatrixST & operator+=(const MatrixST &src2) { for (int y=0;y<SIZE_COL;y++) vecs[y]+=src2.vec[y]; return *this;}
MatrixST & operator-=(const MatrixST &src2) { for (int y=0;y<SIZE_COL;y++) vecs[y]-=src2.vec[y]; return *this;}
MatrixST & operator+=(const float src2) { for (int y=0;y<SIZE_COL;y++) vecs[y]+=src2; return *this;}
MatrixST & operator-=(const float src2) { for (int y=0;y<SIZE_COL;y++) vecs[y]-=src2;; return *this;}
// muls urinary (can't change the dimensions, so this only works when the result doesn't change dimensions)
template<int S2_ROW,int S2_COL, class S2_VR,class S2_VC>
MatrixST<SIZE_ROW, S2_COL, VEC_TR, S2_VC> & operator*=(const MatrixST<S2_ROW, S2_COL, S2_VR, S2_VC> &src2)
{
//MatrixST<SIZE_COL,SIZE_ROW, VEC_TC, VEC_TR> Trans(src2); //todo heap allocate if matrix is really large (or maybe do something requiring the caller to pre transpose it?, or just use the gather loads..
MatrixST<S2_COL, S2_ROW, S2_VC, S2_VR> Trans=src2.Transpose();
for (int x=0; x<SIZE_ROW; x++)
{
VEC_TR result;
for (int y=0; y<S2_COL; y++)
{
float val = (vecs[x] * Trans.vecs[y]).ElementSum();
result.Set(y, val);
}
vecs[x]=result;
}
return *this;
}
// muls binary, because it returns a type it can be used to change the dimensions
template<int S2_ROW,int S2_COL, class S2_VR,class S2_VC>
MatrixST<SIZE_COL, S2_ROW, VEC_TC, S2_VR> operator*(const MatrixST<S2_ROW, S2_COL, S2_VR, S2_VC> &src2)
{
//MatrixST<SIZE_COL,SIZE_ROW, VEC_TC, VEC_TR> Trans(src2); //todo heap allocate if matrix is really large (or maybe do something requiring the caller to pre transpose it?, or just use the gather loads..
MatrixST<S2_COL, S2_ROW, S2_VC, S2_VR> Trans=src2.Transpose();
MatrixST<SIZE_COL, S2_ROW, VEC_TC, S2_VR> ret(0);
for (int x=0; x<SIZE_COL; x++)
{
VEC_TC result;
for (int y=0; y<S2_ROW; y++)
{
float val = (vecs[x] * Trans.vecs[y]).ElementSum();
result.Set(y, val);
}
ret[x]=result;
}
return ret;
}
// version of above with the src pre-transposed
// template<int S2_ROW,int S2_COL, class S2_VR,class S2_VC>
// MatrixST<SIZE_COL, S2_ROW, VEC_TC, S2_VR> MultNoTrans(const MatrixST<S2_ROW, S2_COL, S2_VR, S2_VC> &src2)
VEC_TR & operator*=(const VEC_TR &src2) { VEC_TR ret; for (int y=0;y<SIZE_ROW;y++) ret.Set(y,(vecs[y]*src2).ElementSum()); return *this;}
VEC_TR & operator/=(const VEC_TR &src2) { VEC_TR ret; for (int y=0;y<SIZE_ROW;y++) ret.Set(y,(vecs[y]/src2).ElementSum()); return *this;} //probably should build inverse vec?
MatrixST & operator*=(const float src2) { for (int y=0;y<SIZE_ROW;y++) vecs[y]*=src2; return *this;}
MatrixST & operator/=(const float src2) { for (int y=0;y<SIZE_ROW;y++) vecs[y]/=src2;; return *this;}
//other ops
// must return transposed matrix because m X n becomes n X m
MatrixST<SIZE_COL,SIZE_ROW, VEC_TC, VEC_TR> Transpose() const
{
MatrixST<SIZE_COL,SIZE_ROW, VEC_TC, VEC_TR> ret;
for (int y=0;y<SIZE_ROW;y++)
{
for (int x=0;x<SIZE_COL;x++)
{
ret.Set(x, y, vecs[x][y]);
}
}
return ret; //should be move?!
} //do something smarter?
//void ITranspose() { for (int x=1;x<SIZE;x++) for (int y=0;y<=x;y++) { float tmp=vecs[x][y]; vecs[x].Set(y,1.0/vecs[y][x]); vecs[y].Set(x,1.0/tmp); } } //do something smarter?
MatrixST LU(void)
{
MatrixST U(0),L(0);
if (SIZE_ROW != SIZE_COL)
{
throw "can't deal with non square matrix";
}
for (int i=0;i<SIZE_COL;i++)
{
//U[i][i] = 1.0;
U.Set(i,i,1.0);
}
for (int j=0;j<SIZE_COL;j++)
{
for (int y=j;y<SIZE_COL;y++)
{
float sum = 0;
for (int k=0;k<j;k++)
{
sum += L[y][k] * U[k][j];
}
L.Set(j,y,vecs[y][j]-sum);
//printf("L:\n%s\n", L.as_str().c_str());
}
for (int i=j;i<SIZE_COL;i++)
{
float sum = 0;
for (int k=0;k<j;k++)
{
sum += L[j][k] * U[k][i];
}
if (L[j][j]== 0.0) L.Set(j,j,0.0000001);
U.Set(i,j,(vecs[j][i]-sum)/L[j][j]);
}
}
printf("L:\n%s\n", L.as_str().c_str());
printf("U:\n%s\n", U.as_str().c_str());
return L;
}
float Det(void)
{
MatrixST L=LU();
float det = L[0][0];//*U[0][0];
for (int i=1;i<SIZE_COL;i++)
{
det *= L[i][i];
// det *= U[i][i];
}
printf("Det:%f\n", det);
return det;
}
private:
VEC_TR vecs[SIZE_COL]; //number of rows
};
template<int A,int B,class C,class D,int SA,int SB,class SC,class SD,template<int ,int ,class ,class > class T1, template<int ,int ,class ,class > class T2>void muls(T1<A,B,C,D> &s1, T2<SA,SB,SC,SD> &s)
{
MatrixST<A,SB,C,SD> tmp(0);
printf("new big vec (%d,%d):(%d,%d):\n%s\n", A,B,SA,SB,tmp.as_str().c_str());
}
#ifdef __AVX__
typedef BigVector<8,8,SSEx8> Vec8;
typedef BigVector<8,16,SSEx8> Vec16;
typedef BigVector<8,32,SSEx8> Vec32;
typedef BigVector<8,64,SSEx8> Vec64;
typedef BigVector<8,4096,SSEx8> Vec4k;
#else
typedef BigVector<4,8,Vec4> Vec8;
typedef BigVector<4,16,Vec4> Vec16;
typedef BigVector<4,32,Vec4> Vec32;
typedef BigVector<4,64,Vec4> Vec64;
typedef BigVector<4,4096,Vec4> Vec4k;
#endif
// recursive template calls? sure why not. This breaks the raw() import method (and printing)..
typedef BigVector<64,128,Vec64> Vec128;
#include <memory>
int main(int argv,char *argc[])
{
Vec8 x8vec(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0);
Vec8 x8vec2;
x8vec2.Fill(1.0);
Vec16 x16vec(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0);
Vec128 x128vec(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0);
printf(" big vec %s\n", x8vec.as_str().c_str());
x8vec+=10;
printf("+10 big vec %s\n", x8vec.as_str().c_str());
x8vec/=2;
printf("/2 big vec %s\n", x8vec.as_str().c_str());
x8vec+=x8vec;
printf("*2 big vec %s\n", x8vec.as_str().c_str());
x8vec+=x8vec2;
printf("+1 big vec %s\n", x8vec.as_str().c_str());
printf("\nbig vec %s\n", x16vec.as_str().c_str());
x16vec+=Vec16(x8vec.raw(), x8vec.raw_sz());
printf("big vec %s\n", x16vec.as_str().c_str());
//printf("\nbig vec %s\n", x128vec.as_str().c_str());
//std::unique_ptr<Vec4k> x4kvec=std::make_unique<Vec4096>();
Vec4k *x4kvec=new Vec4k(0.0);
*x4kvec+=6.5;
printf("\nbig vec %s\n", x4kvec->as_str().c_str());
delete x4kvec;
MatrixS<8,Vec8> x8Mat(1);
for (int x=0;x<8;x++) x8Mat.Set(x,x,float(x));
for (int x=0;x<8;x++) x8Mat.Set(0,x,float(x));
printf("\nbig mat:\n%s\n", x8Mat.as_str().c_str());
MatrixS<8,Vec8> x8Mat2(x8Mat);
x8Mat2.Transpose();
printf("big mat:\n%s\n", x8Mat2.as_str().c_str());
x8Mat2*=x8Mat;
printf("big mat:\n%s\n", x8Mat2.as_str().c_str());
/* not computed correctly yet because we want to calc inverse (and det()) first
x8Mat2/=x8Mat;
printf("big mat:\n%s\n", x8Mat2.as_str().c_str());*/
// square version, validate against above.
MatrixST<8,8,Vec8,Vec8> x8nsMat(1);
for (int x=0;x<8;x++) x8nsMat.Set(x,x,float(x));
for (int x=0;x<8;x++) x8nsMat.Set(0,x,float(x));
printf("\nbig matv:\n%s\n", x8nsMat.as_str().c_str());
MatrixST<8,8,Vec8,Vec8> x8nsMat2(x8nsMat.Transpose());
printf("big matv:\n%s\n", x8nsMat2.as_str().c_str());
x8nsMat2*=x8nsMat;
printf("big matv:\n%s\n", x8nsMat2.as_str().c_str());
// nonsquare version (with default prms)
MatrixST<16,8> x8nsMat3(0);
for (int x=0;x<8;x++) { x8nsMat3.Set(x,x,float(x)); x8nsMat3.Set(x+8,x,float(x));}
for (int x=0;x<8;x++) x8nsMat3.Set(0,x,float(x));
printf("big mat:\n%s\n", x8nsMat3.as_str().c_str());
MatrixST<8,16> x8nsMat4(x8nsMat3.Transpose());
// auto x8nsMat4(x8nsMat3.Transpose()); // this works?!!
printf("big mat:\n%s\n", x8nsMat4.as_str().c_str());
auto x8nsMat5 = x8nsMat4 * x8nsMat3;
printf("big mat:\n%s\n", x8nsMat5.as_str().c_str());
auto x8nsMat6 = x8nsMat3 * x8nsMat4;
printf("big mat:\n%s\n", x8nsMat6.as_str().c_str());
//x8nsMat6.LU();
//x8nsMat2.LU();
x8nsMat2.Det();
MatrixST<2,2> x2Mat(1);
printf("small mat:\n%s\n", x2Mat.as_str().c_str());
MatrixST<8,8> x2Mat2(1);
printf("small mat:\n%s\n", x2Mat2.as_str().c_str());
x2Mat2.LU();
// x8nsMat4 *= x8nsMat3; //could one get away with changing the type? lol!
// printf("big mat:\n%s\n", x8nsMat4.as_str().c_str());
// this will eat all your stack! lol
// MatrixST<4096,4096> x8nsMat7(1);
// printf("big mat:\n%s\n", x8nsMat7.as_str().c_str());
// muls(x8nsMat3,x8nsMat2);
}
| 40.567391 | 206 | 0.656664 | jlinton |
d71059c713d55a14cf2ae3f271b4e913c3f0fcce | 1,403 | cpp | C++ | 3rd semester/lab_05/src/List.cpp | kmalski/cpp_labs | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | 1 | 2020-05-19T17:14:55.000Z | 2020-05-19T17:14:55.000Z | 3rd semester/lab_05/src/List.cpp | kmalski/CPP_Laboratories | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | null | null | null | 3rd semester/lab_05/src/List.cpp | kmalski/CPP_Laboratories | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | null | null | null | #include "List.h"
#include <iostream>
Node *prepareNewNode(const int array[][2]) {
Node *tmp = new Node();
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
tmp->data[i][j] = array[i][j];
}
}
tmp->next = nullptr;
return tmp;
}
void prepare(List *list) {
list->head = nullptr;
list->tail = nullptr;
}
void prepare(List *to, const List *from) {
Node *tmp = from->head;
while(tmp != nullptr) {
add(to, tmp->data);
tmp = tmp->next;
}
}
void add(List *list, int array[][2]) {
if(empty(list)) {
list->head = list->tail = prepareNewNode(array);
} else {
list->tail->next = prepareNewNode(array);
list->tail = list->tail->next;
}
}
bool empty(const List *list) {
return list->head == nullptr;
}
void print(const List *list) {
for(int i = 0; i < 2; i++) {
Node *tmp = list->head;
while(tmp != nullptr) {
for(int j = 0; j < 2; j++) {
std::cout << tmp->data[i][j] << " ";
}
std::cout << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
}
void clear(List *list) {
Node *tmp = list->head;
Node *toDelete;
while(tmp != nullptr) {
toDelete = tmp;
tmp = tmp->next;
delete toDelete;
}
list->head = list->tail = nullptr;
}
| 20.632353 | 56 | 0.478261 | kmalski |
d711a20407c4abaa06a76558df1e9c0c00f3423c | 3,292 | cxx | C++ | Applications/OverView/Core/vtkSMClientDeliverySource.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 1 | 2021-07-31T19:38:03.000Z | 2021-07-31T19:38:03.000Z | Applications/OverView/Core/vtkSMClientDeliverySource.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | null | null | null | Applications/OverView/Core/vtkSMClientDeliverySource.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 2 | 2019-01-22T19:51:40.000Z | 2021-07-31T19:38:05.000Z | /*=========================================================================
Program: ParaView
Module: $RCSfile$
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "vtkSMClientDeliverySource.h"
#include "vtkDataObject.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkSMClientDeliverySource, "$Revision$");
vtkStandardNewMacro(vtkSMClientDeliverySource);
// Construct programmable filter with empty execute method.
vtkSMClientDeliverySource::vtkSMClientDeliverySource() :
DeliveryProxy(0)
{
this->SetNumberOfInputPorts(0);
}
vtkSMClientDeliverySource::~vtkSMClientDeliverySource()
{
this->SetDeliveryProxy(0);
}
int vtkSMClientDeliverySource::RequestData(
vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
// Just update the delivery proxy and copy it to the output.
this->DeliveryProxy->Update();
vtkDataObject* input = this->DeliveryProxy->GetOutput();
vtkDataObject* output = outputVector->GetInformationObject(0)->
Get(vtkDataObject::DATA_OBJECT());
output->ShallowCopy(input);
return 1;
}
int vtkSMClientDeliverySource::RequestDataObject(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* outputVector)
{
if (!this->DeliveryProxy)
{
vtkErrorMacro("Delivery proxy must be set before update.");
}
// Make the algorithm's output type match the proxy's output.
this->DeliveryProxy->Update();
vtkDataObject* input = this->DeliveryProxy->GetOutput();
vtkInformation* info = outputVector->GetInformationObject(0);
vtkDataObject* output = info->Get(vtkDataObject::DATA_OBJECT());
if (!output || output->GetDataObjectType() != input->GetDataObjectType())
{
output = input->NewInstance();
output->SetPipelineInformation(info);
output->Delete();
this->GetOutputPortInformation(0)->Set(
vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType());
}
return 1;
}
void vtkSMClientDeliverySource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
| 32.594059 | 75 | 0.725395 | matthb2 |
d713dc8c43bf2828009f01f1f6874c83dccf151f | 16,642 | cpp | C++ | src/ripple/protocol/impl/Feature.cpp | shichengripple001/rippled | 7c66747d27869f9f3c96617bd4227038f1fa92b8 | [
"ISC"
] | null | null | null | src/ripple/protocol/impl/Feature.cpp | shichengripple001/rippled | 7c66747d27869f9f3c96617bd4227038f1fa92b8 | [
"ISC"
] | null | null | null | src/ripple/protocol/impl/Feature.cpp | shichengripple001/rippled | 7c66747d27869f9f3c96617bd4227038f1fa92b8 | [
"ISC"
] | null | null | null | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/protocol/Feature.h>
#include <ripple/basics/Slice.h>
#include <ripple/basics/contract.h>
#include <ripple/protocol/digest.h>
#include <boost/container_hash/hash.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/key_extractors.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index_container.hpp>
#include <cstring>
namespace ripple {
inline std::size_t
hash_value(ripple::uint256 const& feature)
{
std::size_t seed = 0;
using namespace boost;
for (auto const& n : feature)
hash_combine(seed, n);
return seed;
}
namespace {
enum class Supported : bool { no = false, yes };
// *NOTE*
//
// Features, or Amendments as they are called elsewhere, are enabled on the
// network at some specific time based on Validator voting. Features are
// enabled using run-time conditionals based on the state of the amendment.
// There is value in retaining that conditional code for some time after
// the amendment is enabled to make it simple to replay old transactions.
// However, once an Amendment has been enabled for, say, more than two years
// then retaining that conditional code has less value since it is
// uncommon to replay such old transactions.
//
// Starting in January of 2020 Amendment conditionals from before January
// 2018 are being removed. So replaying any ledger from before January
// 2018 needs to happen on an older version of the server code. There's
// a log message in Application.cpp that warns about replaying old ledgers.
//
// At some point in the future someone may wish to remove Amendment
// conditional code for Amendments that were enabled after January 2018.
// When that happens then the log message in Application.cpp should be
// updated.
class FeatureCollections
{
struct Feature
{
std::string name;
uint256 feature;
Feature() = delete;
explicit Feature(std::string const& name_, uint256 const& feature_)
: name(name_), feature(feature_)
{
}
// These structs are used by the `features` multi_index_container to
// provide access to the features collection by size_t index, string
// name, and uint256 feature identifier
struct byIndex
{
};
struct byName
{
};
struct byFeature
{
};
};
// Intermediate types to help with readability
template <class tag, typename Type, Type Feature::*PtrToMember>
using feature_hashed_unique = boost::multi_index::hashed_unique<
boost::multi_index::tag<tag>,
boost::multi_index::member<Feature, Type, PtrToMember>>;
// Intermediate types to help with readability
using feature_indexing = boost::multi_index::indexed_by<
boost::multi_index::random_access<
boost::multi_index::tag<Feature::byIndex>>,
feature_hashed_unique<Feature::byFeature, uint256, &Feature::feature>,
feature_hashed_unique<Feature::byName, std::string, &Feature::name>>;
// This multi_index_container provides access to the features collection by
// name, index, and uint256 feature identifier
boost::multi_index::multi_index_container<Feature, feature_indexing>
features;
std::map<std::string, DefaultVote> supported;
std::size_t upVotes = 0;
std::size_t downVotes = 0;
mutable std::atomic<bool> readOnly = false;
// These helper functions provide access to the features collection by name,
// index, and uint256 feature identifier, so the details of
// multi_index_container can be hidden
Feature const&
getByIndex(size_t i) const
{
if (i >= features.size())
LogicError("Invalid FeatureBitset index");
const auto& sequence = features.get<Feature::byIndex>();
return sequence[i];
}
size_t
getIndex(Feature const& feature) const
{
const auto& sequence = features.get<Feature::byIndex>();
auto const it_to = sequence.iterator_to(feature);
return it_to - sequence.begin();
}
Feature const*
getByFeature(uint256 const& feature) const
{
const auto& feature_index = features.get<Feature::byFeature>();
auto const feature_it = feature_index.find(feature);
return feature_it == feature_index.end() ? nullptr : &*feature_it;
}
Feature const*
getByName(std::string const& name) const
{
const auto& name_index = features.get<Feature::byName>();
auto const name_it = name_index.find(name);
return name_it == name_index.end() ? nullptr : &*name_it;
}
public:
FeatureCollections();
std::optional<uint256>
getRegisteredFeature(std::string const& name) const;
uint256
registerFeature(
std::string const& name,
Supported support,
DefaultVote vote);
/** Tell FeatureCollections when registration is complete. */
bool
registrationIsDone();
std::size_t
featureToBitsetIndex(uint256 const& f) const;
uint256 const&
bitsetIndexToFeature(size_t i) const;
std::string
featureToName(uint256 const& f) const;
/** Amendments that this server supports.
Whether they are enabled depends on the Rules defined in the validated
ledger */
std::map<std::string, DefaultVote> const&
supportedAmendments() const
{
return supported;
}
/** Amendments that this server WON'T vote for by default. */
std::size_t
numDownVotedAmendments() const
{
return downVotes;
}
/** Amendments that this server WILL vote for by default. */
std::size_t
numUpVotedAmendments() const
{
return upVotes;
}
};
//------------------------------------------------------------------------------
FeatureCollections::FeatureCollections()
{
features.reserve(ripple::detail::numFeatures);
}
std::optional<uint256>
FeatureCollections::getRegisteredFeature(std::string const& name) const
{
assert(readOnly);
Feature const* feature = getByName(name);
if (feature)
return feature->feature;
return std::nullopt;
}
void
check(bool condition, const char* logicErrorMessage)
{
if (!condition)
LogicError(logicErrorMessage);
}
uint256
FeatureCollections::registerFeature(
std::string const& name,
Supported support,
DefaultVote vote)
{
check(!readOnly, "Attempting to register a feature after startup.");
check(
support == Supported::yes || vote == DefaultVote::no,
"Invalid feature parameters. Must be supported to be up-voted.");
Feature const* i = getByName(name);
if (!i)
{
// If this check fails, and you just added a feature, increase the
// numFeatures value in Feature.h
check(
features.size() < detail::numFeatures,
"More features defined than allocated. Adjust numFeatures in "
"Feature.h.");
auto const f = sha512Half(Slice(name.data(), name.size()));
features.emplace_back(name, f);
if (support == Supported::yes)
{
supported.emplace(name, vote);
if (vote == DefaultVote::yes)
++upVotes;
else
++downVotes;
}
check(
upVotes + downVotes == supported.size(),
"Feature counting logic broke");
check(
supported.size() <= features.size(),
"More supported features than defined features");
return f;
}
else
// Each feature should only be registered once
LogicError("Duplicate feature registration");
}
/** Tell FeatureCollections when registration is complete. */
bool
FeatureCollections::registrationIsDone()
{
readOnly = true;
return true;
}
size_t
FeatureCollections::featureToBitsetIndex(uint256 const& f) const
{
assert(readOnly);
Feature const* feature = getByFeature(f);
if (!feature)
LogicError("Invalid Feature ID");
return getIndex(*feature);
}
uint256 const&
FeatureCollections::bitsetIndexToFeature(size_t i) const
{
assert(readOnly);
Feature const& feature = getByIndex(i);
return feature.feature;
}
std::string
FeatureCollections::featureToName(uint256 const& f) const
{
assert(readOnly);
Feature const* feature = getByFeature(f);
return feature ? feature->name : to_string(f);
}
static FeatureCollections featureCollections;
} // namespace
/** Amendments that this server supports.
Whether they are enabled depends on the Rules defined in the validated
ledger */
std::map<std::string, DefaultVote> const&
detail::supportedAmendments()
{
return featureCollections.supportedAmendments();
}
/** Amendments that this server won't vote for by default. */
std::size_t
detail::numDownVotedAmendments()
{
return featureCollections.numDownVotedAmendments();
}
/** Amendments that this server will vote for by default. */
std::size_t
detail::numUpVotedAmendments()
{
return featureCollections.numUpVotedAmendments();
}
//------------------------------------------------------------------------------
std::optional<uint256>
getRegisteredFeature(std::string const& name)
{
return featureCollections.getRegisteredFeature(name);
}
uint256
registerFeature(std::string const& name, Supported support, DefaultVote vote)
{
return featureCollections.registerFeature(name, support, vote);
}
// Retired features are in the ledger and have no code controlled by the
// feature. They need to be supported, but do not need to be voted on.
uint256
retireFeature(std::string const& name)
{
return registerFeature(name, Supported::yes, DefaultVote::no);
}
/** Tell FeatureCollections when registration is complete. */
bool
registrationIsDone()
{
return featureCollections.registrationIsDone();
}
size_t
featureToBitsetIndex(uint256 const& f)
{
return featureCollections.featureToBitsetIndex(f);
}
uint256
bitsetIndexToFeature(size_t i)
{
return featureCollections.bitsetIndexToFeature(i);
}
std::string
featureToName(uint256 const& f)
{
return featureCollections.featureToName(f);
}
#pragma push_macro("REGISTER_FEATURE")
#undef REGISTER_FEATURE
/**
Takes the name of a feature, whether it's supported, and the default vote. Will
register the feature, and create a variable whose name is "feature" plus the
feature name.
*/
#define REGISTER_FEATURE(fName, supported, defaultvote) \
uint256 const feature##fName = \
registerFeature(#fName, supported, defaultvote)
#pragma push_macro("REGISTER_FIX")
#undef REGISTER_FIX
/**
Takes the name of a feature, whether it's supported, and the default vote. Will
register the feature, and create a variable whose name is the unmodified feature
name.
*/
#define REGISTER_FIX(fName, supported, defaultvote) \
uint256 const fName = registerFeature(#fName, supported, defaultvote)
// clang-format off
// All known amendments must be registered either here or below with the
// "retired" amendments
REGISTER_FEATURE(OwnerPaysFee, Supported::no, DefaultVote::no);
REGISTER_FEATURE(Flow, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(FlowCross, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(CryptoConditionsSuite, Supported::yes, DefaultVote::no);
REGISTER_FIX (fix1513, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(DepositAuth, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(Checks, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fix1571, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fix1543, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fix1623, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(DepositPreauth, Supported::yes, DefaultVote::yes);
// Use liquidity from strands that consume max offers, but mark as dry
REGISTER_FIX (fix1515, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fix1578, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(MultiSignReserve, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixTakerDryOfferRemoval, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixMasterKeyAsRegularKey, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixCheckThreading, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixPayChanRecipientOwnerDir, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(DeletableAccounts, Supported::yes, DefaultVote::yes);
// fixQualityUpperBound should be activated before FlowCross
REGISTER_FIX (fixQualityUpperBound, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(RequireFullyCanonicalSig, Supported::yes, DefaultVote::yes);
// fix1781: XRPEndpointSteps should be included in the circular payment check
REGISTER_FIX (fix1781, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(HardenedValidations, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixAmendmentMajorityCalc, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(NegativeUNL, Supported::yes, DefaultVote::no);
REGISTER_FEATURE(TicketBatch, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(FlowSortStrands, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixSTAmountCanonicalize, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixRmSmallIncreasedQOffers, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(CheckCashMakesTrustLine, Supported::yes, DefaultVote::no);
REGISTER_FEATURE(NonFungibleTokensV1, Supported::yes, DefaultVote::no);
// The following amendments have been active for at least two years. Their
// pre-amendment code has been removed and the identifiers are deprecated.
// All known amendments and amendments that may appear in a validated
// ledger must be registered either here or above with the "active" amendments
[[deprecated("The referenced amendment has been retired"), maybe_unused]]
uint256 const
retiredMultiSign = retireFeature("MultiSign"),
retiredTrustSetAuth = retireFeature("TrustSetAuth"),
retiredFeeEscalation = retireFeature("FeeEscalation"),
retiredPayChan = retireFeature("PayChan"),
retiredCryptoConditions = retireFeature("CryptoConditions"),
retiredTickSize = retireFeature("TickSize"),
retiredFix1368 = retireFeature("fix1368"),
retiredEscrow = retireFeature("Escrow"),
retiredFix1373 = retireFeature("fix1373"),
retiredEnforceInvariants = retireFeature("EnforceInvariants"),
retiredSortedDirectories = retireFeature("SortedDirectories"),
retiredFix1201 = retireFeature("fix1201"),
retiredFix1512 = retireFeature("fix1512"),
retiredFix1523 = retireFeature("fix1523"),
retiredFix1528 = retireFeature("fix1528");
// clang-format on
#undef REGISTER_FIX
#pragma pop_macro("REGISTER_FIX")
#undef REGISTER_FEATURE
#pragma pop_macro("REGISTER_FEATURE")
// All of the features should now be registered, since variables in a cpp file
// are initialized from top to bottom.
//
// Use initialization of one final static variable to set
// featureCollections::readOnly.
[[maybe_unused]] static const bool readOnlySet =
featureCollections.registrationIsDone();
} // namespace ripple
| 34.598753 | 82 | 0.678584 | shichengripple001 |
d7155c2cfe2603c3147c8afb64c2f3f056f2e349 | 486 | hpp | C++ | examples/boids3d/lightsource.hpp | patrick-oliveira/abcg | 729c5f2fcc860ff527d44bcfd91e331f8fa44f04 | [
"MIT"
] | null | null | null | examples/boids3d/lightsource.hpp | patrick-oliveira/abcg | 729c5f2fcc860ff527d44bcfd91e331f8fa44f04 | [
"MIT"
] | null | null | null | examples/boids3d/lightsource.hpp | patrick-oliveira/abcg | 729c5f2fcc860ff527d44bcfd91e331f8fa44f04 | [
"MIT"
] | null | null | null | #ifndef LIGHTSOURCE_HPP_
#define LIGHTSOURCE_HPP_
#include <glm/vec3.hpp>
#include "abcg.hpp"
#include <glm/vec3.hpp>
#include "boids.hpp"
class OpenGLWindow;
class Boids;
class LightSource {
public:
void update(float deltaTime);
private:
friend OpenGLWindow;
friend Boids;
float scale{0.10f};
float rotationAngle{1.00f};
glm::vec3 lightSourcePosition;
void setupLightSource();
};
#endif | 17.357143 | 39 | 0.623457 | patrick-oliveira |
d71574925a78477b2d29a37d5681e6b54443d587 | 1,066 | cpp | C++ | Piensa en C++/Vol1/C03/Menu.cpp | Gabroide/TextAdvenure | d2fc9b2ef21d66a17b9b716975087093c592abbc | [
"MIT"
] | null | null | null | Piensa en C++/Vol1/C03/Menu.cpp | Gabroide/TextAdvenure | d2fc9b2ef21d66a17b9b716975087093c592abbc | [
"MIT"
] | null | null | null | Piensa en C++/Vol1/C03/Menu.cpp | Gabroide/TextAdvenure | d2fc9b2ef21d66a17b9b716975087093c592abbc | [
"MIT"
] | null | null | null | //: C03:Menu.cpp
// Simple menu program demostrating
#include <iostream>
using namespace std;
int main()
{
char c;
while(true)
{
cout << "MAIN MENU: " << endl;
cout << "l: left, r: right, q: quit -> ";
cin >> c;
if(c == 'q')
break; // Out of "while(1)"
if(c == 'l')
{
cout << "LEFT MENU: " <<endl;
cout << "select a or b: ";
cin >> c;
if(c == 'a')
{
cout << "you chose 'a'" << endl;
continue; // Back to main menu
}
if(c == 'b')
{
cout << "you chose 'b'" << endl;
continue;
}
else
{
cout << "you didn't choose a or b!" << endl;
continue;
}
}
if(c == 'r')
{
cout << "RIGHT MENU: " << endl;
cout << "select c or d: ";
cin >> c;
if(c == 'c')
{
cout << "you chose 'c'" << endl;
continue;
}
if(c == 'd')
{
cout << "you chise 'd'" << endl;
continue;
}
else
{
cout << "you didn's choose c or d!" << endl;
continue;
}
}
else
cout << "you ust tyoe l or r or q!" << endl;
}
cout << "quitting menu..." << endl;
}///:~
| 16.4 | 48 | 0.454034 | Gabroide |
d71ad630401b00c0a2231611eae30719b376fbd1 | 9,460 | cpp | C++ | test/InputValidationTest.cpp | LuckyCode7/bowling | 9d00f5b2509a975143b73ef9460cd047f0bd3136 | [
"MIT"
] | null | null | null | test/InputValidationTest.cpp | LuckyCode7/bowling | 9d00f5b2509a975143b73ef9460cd047f0bd3136 | [
"MIT"
] | 33 | 2018-08-27T20:12:23.000Z | 2018-09-17T09:12:26.000Z | test/InputValidationTest.cpp | LuckyCode7/bowling | 9d00f5b2509a975143b73ef9460cd047f0bd3136 | [
"MIT"
] | 2 | 2018-08-28T12:05:55.000Z | 2018-08-30T14:45:14.000Z | #include <../inc/InputValidation.hpp>
#include <gtest/gtest.h>
struct InputValidationTest : public ::testing::Test
{
};
TEST_F(InputValidationTest,
check_if_substring_from_object_input_will_be_correct)
{
// GIVEN
InputValidation input("Player:x|--|4/|x|");
// WHEN call gestSubstring method
// THEN
ASSERT_EQ("x|--|4/|x|", input.getSubstring());
}
TEST_F(InputValidationTest, expect_false_when_there_is_no_players_name)
{
// GIVEN
InputValidation input(":x|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_players_name_is_correct)
{
// GIVEN
InputValidation input("Mike:x|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_there_are_two_sticks_around_x)
{
// GIVEN
InputValidation input("Mike:|x|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_miss_is_before_strike)
{
// GIVEN
InputValidation input("Mike:-x|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_no_stick_after_two_signs)
{
// GIVEN
InputValidation input("Mike:x|--");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_there_are_is_stick_after_two_signs)
{
// GIVEN
InputValidation input("Mike:X|--|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_before_miss_is_correct_number)
{
// GIVEN
InputValidation input("Mike:x|5-|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_after_stirke_is_miss)
{
// GIVEN
InputValidation input("Mike:x|x-|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_spare_is_the_first_sign)
{
// GIVEN
InputValidation input("Mike:x|/-|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_two_sticks_are_too_early)
{
// GIVEN
InputValidation input("Mike:x||-|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_spare_is_after_miss)
{
// GIVEN
InputValidation input("Mike:x|6-|-/|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_number_less_then_one)
{
// GIVEN
InputValidation input("Mike:x|0-|-/|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_undefined_sign)
{
// GIVEN
InputValidation input("Mike:x|k-|-/|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_spare_is_after_strike)
{
// GIVEN
InputValidation input("Mike:x|--|x/|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, epect_false_when_spare_is_the_first_sign_in_frame)
{
// GIVEN
InputValidation input("Mike:x|--|//|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_spare_is_after_number_less_then_ten)
{
// GIVEN
InputValidation input("Mike:x|--|9/|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_sum_of_numbers_is_bigger_then_nine)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|19|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_sum_of_numbers_is_less_then_nine)
{
// GIVEN
InputValidation input("Mike:x|--|9/|X|-3|18|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_are_two_sticks_in_incorrect_place)
{
// GIVEN
InputValidation input("Mike:x|--|9/|X|-3|18|x|-3||");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_are_no_two_sticks_in_correct_place)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|--|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_are_two_sticks_in_correct_place)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|--||");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_spare_is_before_two_sticks)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_is_strike_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||x");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_is_one_miss_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||-");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_is_number_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||9");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_is_spare_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||/");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_is_too_many_signs_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||5/");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_is_strike_after_two_sticks_and_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||x");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_are_two_miss_after_two_sticks_and_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||--");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(
InputValidationTest,
expect_true_when_there_are_2_numbers_which_sum_is_less_then_9_after_two_sticks_and_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||17");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_is_spare_after_two_sticks_and_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||/6");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_are_too_many_signs_after_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||123");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_the_game_is_in_progress)
{
// GIVEN
InputValidation input("Mike:x|--|3");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_no_stick_after_strike)
{
// GIVEN
InputValidation input("Mike:x|--|x");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_only_spare_after_stick)
{
// GIVEN
InputValidation input("Mike:x|--|/");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_the_game_is_not_finished)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, check_if_player_name_is_correct)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||/");
// WHEN call checkInputData method
// THEN
ASSERT_EQ(input.getPlayerName(), "Mike");
}
| 25.846995 | 94 | 0.700106 | LuckyCode7 |
d71e0641b1f72560cd25a27397e1cfe929c84946 | 6,566 | cpp | C++ | src/org/apache/poi/ss/formula/FormulaRenderer.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/formula/FormulaRenderer.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/formula/FormulaRenderer.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/ss/formula/FormulaRenderer.java
#include <org/apache/poi/ss/formula/FormulaRenderer.hpp>
#include <java/io/Serializable.hpp>
#include <java/lang/ArrayStoreException.hpp>
#include <java/lang/CharSequence.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/Comparable.hpp>
#include <java/lang/IllegalArgumentException.hpp>
#include <java/lang/IllegalStateException.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/RuntimeException.hpp>
#include <java/lang/String.hpp>
#include <java/lang/StringBuilder.hpp>
#include <java/util/Stack.hpp>
#include <org/apache/poi/ss/formula/WorkbookDependentFormula.hpp>
#include <org/apache/poi/ss/formula/ptg/AttrPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/MemAreaPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/MemErrPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/MemFuncPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/OperationPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/ParenthesisPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/Ptg.hpp>
#include <SubArray.hpp>
#include <ObjectArray.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
namespace io
{
typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray;
} // io
namespace lang
{
typedef ::SubArray< ::java::lang::CharSequence, ObjectArray > CharSequenceArray;
typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray;
typedef ::SubArray< ::java::lang::String, ObjectArray, ::java::io::SerializableArray, ComparableArray, CharSequenceArray > StringArray;
} // lang
} // java
namespace poi
{
namespace ss
{
namespace formula
{
namespace ptg
{
typedef ::SubArray< ::poi::ss::formula::ptg::Ptg, ::java::lang::ObjectArray > PtgArray;
} // ptg
} // formula
} // ss
} // poi
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::ss::formula::FormulaRenderer::FormulaRenderer(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::ss::formula::FormulaRenderer::FormulaRenderer()
: FormulaRenderer(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
java::lang::String* poi::ss::formula::FormulaRenderer::toFormulaString(FormulaRenderingWorkbook* book, ::poi::ss::formula::ptg::PtgArray* ptgs)
{
clinit();
if(ptgs == nullptr || npc(ptgs)->length == 0) {
throw new ::java::lang::IllegalArgumentException(u"ptgs must not be null"_j);
}
auto stack = new ::java::util::Stack();
for(auto ptg : *npc(ptgs)) {
if(dynamic_cast< ::poi::ss::formula::ptg::MemAreaPtg* >(ptg) != nullptr || dynamic_cast< ::poi::ss::formula::ptg::MemFuncPtg* >(ptg) != nullptr || dynamic_cast< ::poi::ss::formula::ptg::MemErrPtg* >(ptg) != nullptr) {
continue;
}
if(dynamic_cast< ::poi::ss::formula::ptg::ParenthesisPtg* >(ptg) != nullptr) {
auto contents = java_cast< ::java::lang::String* >(npc(stack)->pop());
npc(stack)->push(::java::lang::StringBuilder().append(u"("_j)->append(contents)
->append(u")"_j)->toString());
continue;
}
if(dynamic_cast< ::poi::ss::formula::ptg::AttrPtg* >(ptg) != nullptr) {
auto attrPtg = (java_cast< ::poi::ss::formula::ptg::AttrPtg* >(ptg));
if(npc(attrPtg)->isOptimizedIf() || npc(attrPtg)->isOptimizedChoose() || npc(attrPtg)->isSkip()) {
continue;
}
if(npc(attrPtg)->isSpace()) {
continue;
}
if(npc(attrPtg)->isSemiVolatile()) {
continue;
}
if(npc(attrPtg)->isSum()) {
auto operands = getOperands(stack, npc(attrPtg)->getNumberOfOperands());
npc(stack)->push(npc(attrPtg)->toFormulaString(operands));
continue;
}
throw new ::java::lang::RuntimeException(::java::lang::StringBuilder().append(u"Unexpected tAttr: "_j)->append(static_cast< ::java::lang::Object* >(attrPtg))->toString());
}
if(dynamic_cast< WorkbookDependentFormula* >(ptg) != nullptr) {
auto optg = java_cast< WorkbookDependentFormula* >(ptg);
npc(stack)->push(npc(optg)->toFormulaString(book));
continue;
}
if(!(dynamic_cast< ::poi::ss::formula::ptg::OperationPtg* >(ptg) != nullptr)) {
npc(stack)->push(npc(ptg)->toFormulaString());
continue;
}
auto o = java_cast< ::poi::ss::formula::ptg::OperationPtg* >(ptg);
auto operands = getOperands(stack, npc(o)->getNumberOfOperands());
npc(stack)->push(npc(o)->toFormulaString(operands));
}
if(npc(stack)->isEmpty()) {
throw new ::java::lang::IllegalStateException(u"Stack underflow"_j);
}
auto result = java_cast< ::java::lang::String* >(npc(stack)->pop());
if(!npc(stack)->isEmpty()) {
throw new ::java::lang::IllegalStateException(u"too much stuff left on the stack"_j);
}
return result;
}
java::lang::StringArray* poi::ss::formula::FormulaRenderer::getOperands(::java::util::Stack* stack, int32_t nOperands)
{
clinit();
auto operands = new ::java::lang::StringArray(nOperands);
for (auto j = nOperands - int32_t(1); j >= 0; j--) {
if(npc(stack)->isEmpty()) {
auto msg = ::java::lang::StringBuilder().append(u"Too few arguments supplied to operation. Expected ("_j)->append(nOperands)
->append(u") operands but got ("_j)
->append((nOperands - j - int32_t(1)))
->append(u")"_j)->toString();
throw new ::java::lang::IllegalStateException(msg);
}
operands->set(j, java_cast< ::java::lang::String* >(npc(stack)->pop()));
}
return operands;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::ss::formula::FormulaRenderer::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.FormulaRenderer", 41);
return c;
}
java::lang::Class* poi::ss::formula::FormulaRenderer::getClass0()
{
return class_();
}
| 37.735632 | 225 | 0.630064 | pebble2015 |
d7259262a33ae40e1358f79814d6400d7e3b2f50 | 36,367 | cpp | C++ | unit_tests/os_interface/windows/wddm20_tests.cpp | jdanecki/compute-runtime | 0d7be1066d61a4e803fee9dcea6e9e9b4213b3b9 | [
"MIT"
] | null | null | null | unit_tests/os_interface/windows/wddm20_tests.cpp | jdanecki/compute-runtime | 0d7be1066d61a4e803fee9dcea6e9e9b4213b3b9 | [
"MIT"
] | null | null | null | unit_tests/os_interface/windows/wddm20_tests.cpp | jdanecki/compute-runtime | 0d7be1066d61a4e803fee9dcea6e9e9b4213b3b9 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017 - 2018, Intel Corporation
*
* 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 "unit_tests/os_interface/windows/wddm_fixture.h"
#include "runtime/execution_environment/execution_environment.h"
#include "runtime/gmm_helper/gmm.h"
#include "runtime/gmm_helper/gmm_helper.h"
#include "runtime/helpers/hw_info.h"
#include "runtime/helpers/options.h"
#include "runtime/memory_manager/os_agnostic_memory_manager.h"
#include "runtime/os_interface/windows/os_interface.h"
#include "runtime/os_interface/os_library.h"
#include "runtime/os_interface/windows/wddm_allocation.h"
#include "runtime/os_interface/windows/wddm_memory_manager.h"
#include "unit_tests/helpers/debug_manager_state_restore.h"
#include "unit_tests/mocks/mock_gmm_resource_info.h"
#include "gtest/gtest.h"
#include "runtime/os_interface/os_time.h"
#include <memory>
#include <functional>
using namespace OCLRT;
namespace GmmHelperFunctions {
Gmm *getGmm(void *ptr, size_t size) {
size_t alignedSize = alignSizeWholePage(ptr, size);
void *alignedPtr = alignUp(ptr, 4096);
Gmm *gmm = new Gmm(alignedPtr, alignedSize, false);
EXPECT_NE(gmm->gmmResourceInfo.get(), nullptr);
return gmm;
}
} // namespace GmmHelperFunctions
using Wddm20Tests = WddmTest;
using Wddm20WithMockGdiDllTests = WddmTestWithMockGdiDll;
using Wddm20InstrumentationTest = WddmInstrumentationTest;
HWTEST_F(Wddm20Tests, givenMinWindowsAddressWhenWddmIsInitializedThenWddmUseThisAddress) {
uintptr_t expectedAddress = 0x200000;
EXPECT_EQ(expectedAddress, OCLRT::windowsMinAddress);
bool status = wddm->init<FamilyType>();
EXPECT_TRUE(status);
EXPECT_TRUE(wddm->isInitialized());
EXPECT_EQ(expectedAddress, wddm->getWddmMinAddress());
}
HWTEST_F(Wddm20Tests, creation) {
bool error = wddm->init<FamilyType>();
EXPECT_TRUE(error);
EXPECT_TRUE(wddm->isInitialized());
}
HWTEST_F(Wddm20Tests, doubleCreation) {
bool error = wddm->init<FamilyType>();
EXPECT_EQ(1u, wddm->createContextResult.called);
error |= wddm->init<FamilyType>();
EXPECT_EQ(1u, wddm->createContextResult.called);
EXPECT_TRUE(error);
EXPECT_TRUE(wddm->isInitialized());
}
TEST_F(Wddm20Tests, givenNullPageTableManagerWhenUpdateAuxTableCalledThenReturnFalse) {
wddm->resetPageTableManager(nullptr);
EXPECT_EQ(nullptr, wddm->getPageTableManager());
auto gmm = std::unique_ptr<Gmm>(new Gmm(nullptr, 1, false));
auto mockGmmRes = reinterpret_cast<MockGmmResourceInfo *>(gmm->gmmResourceInfo.get());
mockGmmRes->setUnifiedAuxTranslationCapable();
EXPECT_FALSE(wddm->updateAuxTable(1234u, gmm.get(), true));
}
TEST(Wddm20EnumAdaptersTest, expectTrue) {
HardwareInfo outHwInfo;
const HardwareInfo hwInfo = *platformDevices[0];
OsLibrary *mockGdiDll = setAdapterInfo(hwInfo.pPlatform, hwInfo.pSysInfo);
bool success = Wddm::enumAdapters(outHwInfo);
EXPECT_TRUE(success);
const HardwareInfo *hwinfo = *platformDevices;
ASSERT_NE(nullptr, outHwInfo.pPlatform);
EXPECT_EQ(outHwInfo.pPlatform->eDisplayCoreFamily, hwinfo->pPlatform->eDisplayCoreFamily);
delete mockGdiDll;
delete outHwInfo.pPlatform;
delete outHwInfo.pSkuTable;
delete outHwInfo.pSysInfo;
delete outHwInfo.pWaTable;
}
TEST(Wddm20EnumAdaptersTest, givenEmptyHardwareInfoWhenEnumAdapterIsCalledThenCapabilityTableIsSet) {
HardwareInfo outHwInfo = {};
auto hwInfo = *platformDevices[0];
std::unique_ptr<OsLibrary> mockGdiDll(setAdapterInfo(hwInfo.pPlatform, hwInfo.pSysInfo));
bool success = Wddm::enumAdapters(outHwInfo);
EXPECT_TRUE(success);
const HardwareInfo *hwinfo = *platformDevices;
ASSERT_NE(nullptr, outHwInfo.pPlatform);
EXPECT_EQ(outHwInfo.pPlatform->eDisplayCoreFamily, hwinfo->pPlatform->eDisplayCoreFamily);
EXPECT_EQ(outHwInfo.capabilityTable.defaultProfilingTimerResolution, hwInfo.capabilityTable.defaultProfilingTimerResolution);
EXPECT_EQ(outHwInfo.capabilityTable.clVersionSupport, hwInfo.capabilityTable.clVersionSupport);
EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.enableKmdNotify, hwInfo.capabilityTable.kmdNotifyProperties.enableKmdNotify);
EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds, hwInfo.capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds);
EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.enableQuickKmdSleep, hwInfo.capabilityTable.kmdNotifyProperties.enableQuickKmdSleep);
EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds, hwInfo.capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds);
delete outHwInfo.pPlatform;
delete outHwInfo.pSkuTable;
delete outHwInfo.pSysInfo;
delete outHwInfo.pWaTable;
}
TEST(Wddm20EnumAdaptersTest, givenUnknownPlatformWhenEnumAdapterIsCalledThenFalseIsReturnedAndOutputIsEmpty) {
HardwareInfo outHwInfo;
memset(&outHwInfo, 0, sizeof(outHwInfo));
HardwareInfo hwInfo = *platformDevices[0];
auto bkp = hwInfo.pPlatform->eProductFamily;
PLATFORM platform = *(hwInfo.pPlatform);
platform.eProductFamily = IGFX_UNKNOWN;
std::unique_ptr<OsLibrary, std::function<void(OsLibrary *)>> mockGdiDll(
setAdapterInfo(&platform, hwInfo.pSysInfo),
[&](OsLibrary *ptr) {
platform.eProductFamily = bkp;
typedef void(__stdcall * pfSetAdapterInfo)(const void *, const void *);
pfSetAdapterInfo fSetAdpaterInfo = reinterpret_cast<pfSetAdapterInfo>(ptr->getProcAddress("MockSetAdapterInfo"));
fSetAdpaterInfo(&platform, hwInfo.pSysInfo);
delete ptr;
});
bool ret = Wddm::enumAdapters(outHwInfo);
EXPECT_FALSE(ret);
EXPECT_EQ(nullptr, outHwInfo.pPlatform);
EXPECT_EQ(nullptr, outHwInfo.pSkuTable);
EXPECT_EQ(nullptr, outHwInfo.pSysInfo);
EXPECT_EQ(nullptr, outHwInfo.pWaTable);
}
HWTEST_F(Wddm20Tests, context) {
EXPECT_TRUE(wddm->getOsDeviceContext() == static_cast<D3DKMT_HANDLE>(0));
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
EXPECT_TRUE(wddm->createContext());
auto context = wddm->getOsDeviceContext();
EXPECT_TRUE(context != static_cast<D3DKMT_HANDLE>(0));
EXPECT_TRUE(wddm->destroyContext(context));
}
HWTEST_F(Wddm20Tests, allocation) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_TRUE(allocation.handle != 0);
auto error = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(error);
delete gmm;
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenAllocationSmallerUnderlyingThanAlignedSizeWhenCreatedThenWddmUseAligned) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
void *ptr = reinterpret_cast<void *>(wddm->virtualAllocAddress + 0x1000);
size_t underlyingSize = 0x2100;
size_t alignedSize = 0x3000;
size_t underlyingPages = underlyingSize / MemoryConstants::pageSize;
size_t alignedPages = alignedSize / MemoryConstants::pageSize;
WddmAllocation allocation(ptr, 0x2100, ptr, 0x3000, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getAlignedCpuPtr(), allocation.getAlignedSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_NE(0, allocation.handle);
bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false);
EXPECT_TRUE(ret);
EXPECT_EQ(alignedPages, getLastCallMapGpuVaArgFcn()->SizeInPages);
EXPECT_NE(underlyingPages, getLastCallMapGpuVaArgFcn()->SizeInPages);
ret = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(ret);
delete gmm;
}
HWTEST_F(Wddm20Tests, createAllocation32bit) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
uint64_t heap32baseAddress = 0x40000;
uint64_t heap32Size = 0x40000;
wddm->setHeap32(heap32baseAddress, heap32Size);
void *alignedPtr = (void *)0x12000;
size_t alignedSize = 0x2000;
WddmAllocation allocation(alignedPtr, alignedSize, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
allocation.is32BitAllocation = true; // mark 32 bit allocation
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_TRUE(allocation.handle != 0);
bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false);
EXPECT_TRUE(ret);
EXPECT_EQ(1u, wddm->mapGpuVirtualAddressResult.called);
EXPECT_LE(heap32baseAddress, allocation.gpuPtr);
EXPECT_GT(heap32baseAddress + heap32Size, allocation.gpuPtr);
auto success = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(success);
delete gmm;
}
HWTEST_F(Wddm20Tests, givenGraphicsAllocationWhenItIsMappedInHeap1ThenItHasGpuAddressWithingHeap1Limits) {
wddm->init<FamilyType>();
void *alignedPtr = (void *)0x12000;
size_t alignedSize = 0x2000;
WddmAllocation allocation(alignedPtr, alignedSize, nullptr);
allocation.handle = ALLOCATION_HANDLE;
allocation.gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), false, false, true);
EXPECT_TRUE(ret);
auto cannonizedHeapBase = GmmHelper::canonize(this->wddm->getGfxPartition().Heap32[1].Base);
auto cannonizedHeapEnd = GmmHelper::canonize(this->wddm->getGfxPartition().Heap32[1].Limit);
EXPECT_GE(allocation.gpuPtr, cannonizedHeapBase);
EXPECT_LE(allocation.gpuPtr, cannonizedHeapEnd);
delete allocation.gmm;
}
HWTEST_F(Wddm20WithMockGdiDllTests, GivenThreeOsHandlesWhenAskedForDestroyAllocationsThenAllMarkedAllocationsAreDestroyed) {
EXPECT_TRUE(wddm->init<FamilyType>());
OsHandleStorage storage;
OsHandle osHandle1 = {0};
OsHandle osHandle2 = {0};
OsHandle osHandle3 = {0};
osHandle1.handle = ALLOCATION_HANDLE;
osHandle2.handle = ALLOCATION_HANDLE;
osHandle3.handle = ALLOCATION_HANDLE;
storage.fragmentStorageData[0].osHandleStorage = &osHandle1;
storage.fragmentStorageData[0].freeTheFragment = true;
storage.fragmentStorageData[1].osHandleStorage = &osHandle2;
storage.fragmentStorageData[1].freeTheFragment = false;
storage.fragmentStorageData[2].osHandleStorage = &osHandle3;
storage.fragmentStorageData[2].freeTheFragment = true;
D3DKMT_HANDLE handles[3] = {ALLOCATION_HANDLE, ALLOCATION_HANDLE, ALLOCATION_HANDLE};
bool retVal = wddm->destroyAllocations(handles, 3, 0, 0);
EXPECT_TRUE(retVal);
auto destroyWithResourceHandleCalled = 0u;
D3DKMT_DESTROYALLOCATION2 *ptrToDestroyAlloc2 = nullptr;
getSizesFcn(destroyWithResourceHandleCalled, ptrToDestroyAlloc2);
EXPECT_EQ(0u, ptrToDestroyAlloc2->Flags.SynchronousDestroy);
EXPECT_EQ(1u, ptrToDestroyAlloc2->Flags.AssumeNotInUse);
}
HWTEST_F(Wddm20Tests, mapAndFreeGpuVa) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_TRUE(allocation.handle != 0);
auto error = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getUnderlyingBufferSize(), false, false, false);
EXPECT_TRUE(error);
EXPECT_TRUE(allocation.gpuPtr != 0);
error = wddm->freeGpuVirtualAddres(allocation.gpuPtr, allocation.getUnderlyingBufferSize());
EXPECT_TRUE(error);
EXPECT_TRUE(allocation.gpuPtr == 0);
error = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(error);
delete gmm;
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20Tests, givenNullAllocationWhenCreateThenAllocateAndMap) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(nullptr, 100, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false);
EXPECT_TRUE(ret);
EXPECT_NE(0u, allocation.gpuPtr);
EXPECT_EQ(allocation.gpuPtr, GmmHelper::canonize(allocation.gpuPtr));
delete gmm;
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20Tests, makeResidentNonResident) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_TRUE(allocation.handle != 0);
auto error = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getUnderlyingBufferSize(), false, false, false);
EXPECT_TRUE(error);
EXPECT_TRUE(allocation.gpuPtr != 0);
error = wddm->makeResident(&allocation.handle, 1, false, nullptr);
EXPECT_TRUE(error);
uint64_t sizeToTrim;
error = wddm->evict(&allocation.handle, 1, sizeToTrim);
EXPECT_TRUE(error);
auto monitoredFence = wddm->getMonitoredFence();
UINT64 fenceValue = 100;
monitoredFence.cpuAddress = &fenceValue;
monitoredFence.currentFenceValue = 101;
error = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(error);
delete gmm;
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
TEST_F(Wddm20Tests, GetCpuTime) {
uint64_t time = 0;
std::unique_ptr<OSTime> osTime(OSTime::create(nullptr).release());
auto error = osTime->getCpuTime(&time);
EXPECT_TRUE(error);
EXPECT_NE(0, time);
}
TEST_F(Wddm20Tests, GivenNoOSInterfaceGetCpuGpuTimeReturnsError) {
TimeStampData CPUGPUTime = {0};
std::unique_ptr<OSTime> osTime(OSTime::create(nullptr).release());
auto success = osTime->getCpuGpuTime(&CPUGPUTime);
EXPECT_FALSE(success);
EXPECT_EQ(0, CPUGPUTime.CPUTimeinNS);
EXPECT_EQ(0, CPUGPUTime.GPUTimeStamp);
}
TEST_F(Wddm20Tests, GetCpuGpuTime) {
TimeStampData CPUGPUTime01 = {0};
TimeStampData CPUGPUTime02 = {0};
std::unique_ptr<OSInterface> osInterface(new OSInterface());
osInterface->get()->setWddm(wddm.get());
std::unique_ptr<OSTime> osTime(OSTime::create(osInterface.get()).release());
auto success = osTime->getCpuGpuTime(&CPUGPUTime01);
EXPECT_TRUE(success);
EXPECT_NE(0, CPUGPUTime01.CPUTimeinNS);
EXPECT_NE(0, CPUGPUTime01.GPUTimeStamp);
success = osTime->getCpuGpuTime(&CPUGPUTime02);
EXPECT_TRUE(success);
EXPECT_NE(0, CPUGPUTime02.CPUTimeinNS);
EXPECT_NE(0, CPUGPUTime02.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.GPUTimeStamp, CPUGPUTime01.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.CPUTimeinNS, CPUGPUTime01.CPUTimeinNS);
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenSharedHandleWhenCreateGraphicsAllocationFromSharedHandleIsCalledThenGraphicsAllocationWithSharedPropertiesIsCreated) {
void *pSysMem = (void *)0x1000;
std::unique_ptr<Gmm> gmm(new Gmm(pSysMem, 4096u, false));
auto status = setSizesFcn(gmm->gmmResourceInfo.get(), 1u, 1024u, 1u);
EXPECT_EQ(0u, status);
wddm->init<FamilyType>();
WddmMemoryManager mm(false, wddm.release());
auto graphicsAllocation = mm.createGraphicsAllocationFromSharedHandle(ALLOCATION_HANDLE, false, false);
auto wddmAllocation = (WddmAllocation *)graphicsAllocation;
ASSERT_NE(nullptr, wddmAllocation);
EXPECT_EQ(ALLOCATION_HANDLE, wddmAllocation->peekSharedHandle());
EXPECT_EQ(RESOURCE_HANDLE, wddmAllocation->resourceHandle);
EXPECT_NE(0u, wddmAllocation->handle);
EXPECT_EQ(ALLOCATION_HANDLE, wddmAllocation->handle);
EXPECT_NE(0u, wddmAllocation->getGpuAddress());
EXPECT_EQ(wddmAllocation->gpuPtr, wddmAllocation->getGpuAddress());
EXPECT_EQ(4096u, wddmAllocation->getUnderlyingBufferSize());
EXPECT_EQ(nullptr, wddmAllocation->getAlignedCpuPtr());
EXPECT_NE(nullptr, wddmAllocation->gmm);
EXPECT_EQ(4096u, wddmAllocation->gmm->gmmResourceInfo->getSizeAllocation());
mm.freeGraphicsMemory(graphicsAllocation);
auto destroyWithResourceHandleCalled = 0u;
D3DKMT_DESTROYALLOCATION2 *ptrToDestroyAlloc2 = nullptr;
status = getSizesFcn(destroyWithResourceHandleCalled, ptrToDestroyAlloc2);
EXPECT_EQ(0u, ptrToDestroyAlloc2->Flags.SynchronousDestroy);
EXPECT_EQ(1u, ptrToDestroyAlloc2->Flags.AssumeNotInUse);
EXPECT_EQ(0u, status);
EXPECT_EQ(1u, destroyWithResourceHandleCalled);
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenSharedHandleWhenCreateGraphicsAllocationFromSharedHandleIsCalledThenMapGpuVaWithCpuPtrDepensOnBitness) {
void *pSysMem = (void *)0x1000;
std::unique_ptr<Gmm> gmm(new Gmm(pSysMem, 4096u, false));
auto status = setSizesFcn(gmm->gmmResourceInfo.get(), 1u, 1024u, 1u);
EXPECT_EQ(0u, status);
auto mockWddm = wddm.release();
mockWddm->init<FamilyType>();
WddmMemoryManager mm(false, mockWddm);
auto graphicsAllocation = mm.createGraphicsAllocationFromSharedHandle(ALLOCATION_HANDLE, false, false);
auto wddmAllocation = (WddmAllocation *)graphicsAllocation;
ASSERT_NE(nullptr, wddmAllocation);
if (is32bit) {
EXPECT_NE(mockWddm->mapGpuVirtualAddressResult.cpuPtrPassed, nullptr);
} else {
EXPECT_EQ(mockWddm->mapGpuVirtualAddressResult.cpuPtrPassed, nullptr);
}
mm.freeGraphicsMemory(graphicsAllocation);
}
HWTEST_F(Wddm20Tests, givenWddmCreatedWhenNotInitedThenMinAddressZero) {
uintptr_t expected = 0;
uintptr_t actual = wddm->getWddmMinAddress();
EXPECT_EQ(expected, actual);
}
HWTEST_F(Wddm20Tests, givenWddmCreatedWhenInitedThenMinAddressValid) {
bool ret = wddm->init<FamilyType>();
EXPECT_TRUE(ret);
uintptr_t expected = windowsMinAddress;
uintptr_t actual = wddm->getWddmMinAddress();
EXPECT_EQ(expected, actual);
}
HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceOnInit) {
SYSTEM_INFO sysInfo = {};
WddmMock::getSystemInfo(&sysInfo);
uintptr_t maxAddr = reinterpret_cast<uintptr_t>(sysInfo.lpMaximumApplicationAddress) + 1;
D3DKMT_HANDLE adapterHandle = ADAPTER_HANDLE;
D3DKMT_HANDLE deviceHandle = DEVICE_HANDLE;
const HardwareInfo hwInfo = *platformDevices[0];
ExecutionEnvironment execEnv;
execEnv.initGmm(&hwInfo);
BOOLEAN FtrL3IACoherency = hwInfo.pSkuTable->ftrL3IACoherency ? 1 : 0;
EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(adapterHandle,
deviceHandle,
wddm->gdi->escape.mFunc,
maxAddr,
0,
0,
FtrL3IACoherency,
0,
0))
.Times(1)
.WillRepeatedly(::testing::Return(true));
wddm->init<FamilyType>();
EXPECT_TRUE(wddm->isInitialized());
}
HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoAdapter) {
wddm->adapter = static_cast<D3DKMT_HANDLE>(0);
ExecutionEnvironment execEnv;
execEnv.initGmm(*platformDevices);
EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(static_cast<D3DKMT_HANDLE>(0),
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_))
.Times(1)
.WillRepeatedly(::testing::Return(false));
auto ret = wddm->configureDeviceAddressSpace<FamilyType>();
EXPECT_FALSE(ret);
}
HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoDevice) {
wddm->device = static_cast<D3DKMT_HANDLE>(0);
ExecutionEnvironment execEnv;
execEnv.initGmm(*platformDevices);
EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(::testing::_,
static_cast<D3DKMT_HANDLE>(0),
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_))
.Times(1)
.WillRepeatedly(::testing::Return(false));
auto ret = wddm->configureDeviceAddressSpace<FamilyType>();
EXPECT_FALSE(ret);
}
HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoEscFunc) {
wddm->gdi->escape = static_cast<PFND3DKMT_ESCAPE>(nullptr);
ExecutionEnvironment execEnv;
execEnv.initGmm(*platformDevices);
EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(::testing::_,
::testing::_,
static_cast<PFND3DKMT_ESCAPE>(nullptr),
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_))
.Times(1)
.WillRepeatedly(::testing::Return(false));
auto ret = wddm->configureDeviceAddressSpace<FamilyType>();
EXPECT_FALSE(ret);
}
HWTEST_F(Wddm20Tests, getMaxApplicationAddress) {
wddm->init<FamilyType>();
EXPECT_TRUE(wddm->isInitialized());
uint64_t maxAddr = wddm->getMaxApplicationAddress();
if (is32bit) {
EXPECT_EQ(maxAddr, MemoryConstants::max32BitAppAddress);
} else {
EXPECT_EQ(maxAddr, MemoryConstants::max64BitAppAddress);
}
}
HWTEST_F(Wddm20Tests, dontCallCreateContextBeforeConfigureDeviceAddressSpace) {
wddm->createContext();
EXPECT_EQ(1u, wddm->createContextResult.called); // dont care about the result
wddm->configureDeviceAddressSpace<FamilyType>();
EXPECT_EQ(1u, wddm->configureDeviceAddressSpaceResult.called);
EXPECT_FALSE(wddm->configureDeviceAddressSpaceResult.success);
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenUseNoRingFlushesKmdModeDebugFlagToFalseWhenCreateContextIsCalledThenNoRingFlushesKmdModeIsSetToFalse) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.UseNoRingFlushesKmdMode.set(false);
wddm->init<FamilyType>();
auto createContextParams = this->getCreateContextDataFcn();
auto privateData = (CREATECONTEXT_PVTDATA *)createContextParams->pPrivateDriverData;
EXPECT_FALSE(!!privateData->NoRingFlushes);
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenUseNoRingFlushesKmdModeDebugFlagToTrueWhenCreateContextIsCalledThenNoRingFlushesKmdModeIsSetToTrue) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.UseNoRingFlushesKmdMode.set(true);
wddm->init<FamilyType>();
auto createContextParams = this->getCreateContextDataFcn();
auto privateData = (CREATECONTEXT_PVTDATA *)createContextParams->pPrivateDriverData;
EXPECT_TRUE(!!privateData->NoRingFlushes);
}
HWTEST_F(Wddm20WithMockGdiDllTests, whenCreateContextIsCalledThenDisableHwQueues) {
wddm->init<FamilyType>();
EXPECT_FALSE(wddm->hwQueuesSupported());
EXPECT_EQ(0u, getCreateContextDataFcn()->Flags.HwQueueSupported);
}
TEST_F(Wddm20Tests, whenCreateHwQueueIsCalledThenAlwaysReturnFalse) {
EXPECT_FALSE(wddm->createHwQueue());
}
HWTEST_F(Wddm20Tests, whenInitCalledThenDontCallToCreateHwQueue) {
wddm->init<FamilyType>();
EXPECT_EQ(0u, wddm->createHwQueueResult.called);
}
HWTEST_F(Wddm20Tests, whenWddmIsInitializedThenGdiDoesntHaveHwQueueDDIs) {
wddm->init<FamilyType>();
EXPECT_EQ(nullptr, wddm->gdi->createHwQueue.mFunc);
EXPECT_EQ(nullptr, wddm->gdi->destroyHwQueue.mFunc);
EXPECT_EQ(nullptr, wddm->gdi->submitCommandToHwQueue.mFunc);
}
HWTEST_F(Wddm20Tests, givenDebugManagerWhenGetForUseNoRingFlushesKmdModeIsCalledThenTrueIsReturned) {
EXPECT_TRUE(DebugManager.flags.UseNoRingFlushesKmdMode.get());
}
HWTEST_F(Wddm20Tests, makeResidentMultipleHandles) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
allocation.handle = ALLOCATION_HANDLE;
D3DKMT_HANDLE handles[2] = {0};
handles[0] = allocation.handle;
handles[1] = allocation.handle;
gdi->getMakeResidentArg().NumAllocations = 0;
gdi->getMakeResidentArg().AllocationList = nullptr;
bool error = wddm->makeResident(handles, 2, false, nullptr);
EXPECT_TRUE(error);
EXPECT_EQ(2u, gdi->getMakeResidentArg().NumAllocations);
EXPECT_EQ(handles, gdi->getMakeResidentArg().AllocationList);
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20Tests, makeResidentMultipleHandlesWithReturnBytesToTrim) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
allocation.handle = ALLOCATION_HANDLE;
D3DKMT_HANDLE handles[2] = {0};
handles[0] = allocation.handle;
handles[1] = allocation.handle;
gdi->getMakeResidentArg().NumAllocations = 0;
gdi->getMakeResidentArg().AllocationList = nullptr;
gdi->getMakeResidentArg().NumBytesToTrim = 30;
uint64_t bytesToTrim = 0;
bool success = wddm->makeResident(handles, 2, false, &bytesToTrim);
EXPECT_TRUE(success);
EXPECT_EQ(gdi->getMakeResidentArg().NumBytesToTrim, bytesToTrim);
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20Tests, makeNonResidentCallsEvict) {
wddm->init<FamilyType>();
D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234;
gdi->getEvictArg().AllocationList = nullptr;
gdi->getEvictArg().Flags.Value = 0;
gdi->getEvictArg().hDevice = 0;
gdi->getEvictArg().NumAllocations = 0;
gdi->getEvictArg().NumBytesToTrim = 20;
uint64_t sizeToTrim = 10;
wddm->evict(&handle, 1, sizeToTrim);
EXPECT_EQ(1u, gdi->getEvictArg().NumAllocations);
EXPECT_EQ(&handle, gdi->getEvictArg().AllocationList);
EXPECT_EQ(wddm->getDevice(), gdi->getEvictArg().hDevice);
EXPECT_EQ(0u, gdi->getEvictArg().NumBytesToTrim);
}
HWTEST_F(Wddm20Tests, destroyAllocationWithLastFenceValueGreaterThanCurrentValueCallsWaitFromCpu) {
wddm->init<FamilyType>();
WddmAllocation allocation((void *)0x23000, 0x1000, nullptr);
allocation.getResidencyData().lastFence = 20;
allocation.handle = ALLOCATION_HANDLE;
*wddm->getMonitoredFence().cpuAddress = 10;
D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234;
gdi->getWaitFromCpuArg().FenceValueArray = nullptr;
gdi->getWaitFromCpuArg().Flags.Value = 0;
gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getWaitFromCpuArg().ObjectCount = 0;
gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr;
gdi->getDestroyArg().AllocationCount = 0;
gdi->getDestroyArg().Flags.Value = 0;
gdi->getDestroyArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getDestroyArg().hResource = (D3DKMT_HANDLE)0;
gdi->getDestroyArg().phAllocationList = nullptr;
wddm->destroyAllocation(&allocation);
EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().FenceValueArray);
EXPECT_EQ(wddm->getDevice(), gdi->getWaitFromCpuArg().hDevice);
EXPECT_EQ(1u, gdi->getWaitFromCpuArg().ObjectCount);
EXPECT_EQ(&wddm->getMonitoredFence().fenceHandle, gdi->getWaitFromCpuArg().ObjectHandleArray);
EXPECT_EQ(wddm->getDevice(), gdi->getDestroyArg().hDevice);
EXPECT_EQ(1u, gdi->getDestroyArg().AllocationCount);
EXPECT_NE(nullptr, gdi->getDestroyArg().phAllocationList);
}
HWTEST_F(Wddm20Tests, destroyAllocationWithLastFenceValueLessEqualToCurrentValueDoesNotCallWaitFromCpu) {
wddm->init<FamilyType>();
WddmAllocation allocation((void *)0x23000, 0x1000, nullptr);
allocation.getResidencyData().lastFence = 10;
allocation.handle = ALLOCATION_HANDLE;
*wddm->getMonitoredFence().cpuAddress = 10;
D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234;
gdi->getWaitFromCpuArg().FenceValueArray = nullptr;
gdi->getWaitFromCpuArg().Flags.Value = 0;
gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getWaitFromCpuArg().ObjectCount = 0;
gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr;
gdi->getDestroyArg().AllocationCount = 0;
gdi->getDestroyArg().Flags.Value = 0;
gdi->getDestroyArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getDestroyArg().hResource = (D3DKMT_HANDLE)0;
gdi->getDestroyArg().phAllocationList = nullptr;
wddm->destroyAllocation(&allocation);
EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().FenceValueArray);
EXPECT_EQ((D3DKMT_HANDLE)0, gdi->getWaitFromCpuArg().hDevice);
EXPECT_EQ(0u, gdi->getWaitFromCpuArg().ObjectCount);
EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray);
EXPECT_EQ(wddm->getDevice(), gdi->getDestroyArg().hDevice);
EXPECT_EQ(1u, gdi->getDestroyArg().AllocationCount);
EXPECT_NE(nullptr, gdi->getDestroyArg().phAllocationList);
}
HWTEST_F(Wddm20Tests, WhenLastFenceLessEqualThanMonitoredThenWaitFromCpuIsNotCalled) {
wddm->init<FamilyType>();
WddmAllocation allocation((void *)0x23000, 0x1000, nullptr);
allocation.getResidencyData().lastFence = 10;
allocation.handle = ALLOCATION_HANDLE;
*wddm->getMonitoredFence().cpuAddress = 10;
gdi->getWaitFromCpuArg().FenceValueArray = nullptr;
gdi->getWaitFromCpuArg().Flags.Value = 0;
gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getWaitFromCpuArg().ObjectCount = 0;
gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr;
auto status = wddm->waitFromCpu(10);
EXPECT_TRUE(status);
EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().FenceValueArray);
EXPECT_EQ((D3DKMT_HANDLE)0, gdi->getWaitFromCpuArg().hDevice);
EXPECT_EQ(0u, gdi->getWaitFromCpuArg().ObjectCount);
EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray);
}
HWTEST_F(Wddm20Tests, WhenLastFenceGreaterThanMonitoredThenWaitFromCpuIsCalled) {
wddm->init<FamilyType>();
WddmAllocation allocation((void *)0x23000, 0x1000, nullptr);
allocation.getResidencyData().lastFence = 10;
allocation.handle = ALLOCATION_HANDLE;
*wddm->getMonitoredFence().cpuAddress = 10;
gdi->getWaitFromCpuArg().FenceValueArray = nullptr;
gdi->getWaitFromCpuArg().Flags.Value = 0;
gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getWaitFromCpuArg().ObjectCount = 0;
gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr;
auto status = wddm->waitFromCpu(20);
EXPECT_TRUE(status);
EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().FenceValueArray);
EXPECT_EQ((D3DKMT_HANDLE)wddm->getDevice(), gdi->getWaitFromCpuArg().hDevice);
EXPECT_EQ(1u, gdi->getWaitFromCpuArg().ObjectCount);
EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray);
}
HWTEST_F(Wddm20Tests, createMonitoredFenceIsInitializedWithFenceValueZeroAndCurrentFenceValueIsSetToOne) {
wddm->init<FamilyType>();
gdi->createSynchronizationObject2 = gdi->createSynchronizationObject2Mock;
gdi->getCreateSynchronizationObject2Arg().Info.MonitoredFence.InitialFenceValue = 300;
wddm->createMonitoredFence();
EXPECT_EQ(0u, gdi->getCreateSynchronizationObject2Arg().Info.MonitoredFence.InitialFenceValue);
EXPECT_EQ(1u, wddm->getMonitoredFence().currentFenceValue);
}
NTSTATUS APIENTRY queryResourceInfoMock(D3DKMT_QUERYRESOURCEINFO *pData) {
pData->NumAllocations = 0;
return 0;
}
HWTEST_F(Wddm20Tests, givenOpenSharedHandleWhenZeroAllocationsThenReturnNull) {
wddm->init<FamilyType>();
D3DKMT_HANDLE handle = 0;
WddmAllocation *alloc = nullptr;
gdi->queryResourceInfo = reinterpret_cast<PFND3DKMT_QUERYRESOURCEINFO>(queryResourceInfoMock);
auto ret = wddm->openSharedHandle(handle, alloc);
EXPECT_EQ(false, ret);
}
HWTEST_F(Wddm20Tests, givenReadOnlyMemoryWhenCreateAllocationFailsWithNoVideoMemoryThenCorrectStatusIsReturned) {
class MockCreateAllocation {
public:
static NTSTATUS APIENTRY mockCreateAllocation(D3DKMT_CREATEALLOCATION *param) {
return STATUS_GRAPHICS_NO_VIDEO_MEMORY;
};
};
gdi->createAllocation = MockCreateAllocation::mockCreateAllocation;
wddm->init<FamilyType>();
OsHandleStorage handleStorage;
OsHandle handle = {0};
ResidencyData residency;
handleStorage.fragmentCount = 1;
handleStorage.fragmentStorageData[0].cpuPtr = (void *)0x1000;
handleStorage.fragmentStorageData[0].fragmentSize = 0x1000;
handleStorage.fragmentStorageData[0].freeTheFragment = false;
handleStorage.fragmentStorageData[0].osHandleStorage = &handle;
handleStorage.fragmentStorageData[0].residency = &residency;
handleStorage.fragmentStorageData[0].osHandleStorage->gmm = GmmHelperFunctions::getGmm(nullptr, 0);
NTSTATUS result = wddm->createAllocationsAndMapGpuVa(handleStorage);
EXPECT_EQ(STATUS_GRAPHICS_NO_VIDEO_MEMORY, result);
delete handleStorage.fragmentStorageData[0].osHandleStorage->gmm;
}
HWTEST_F(Wddm20Tests, whenGetOsDeviceContextIsCalledThenWddmOsDeviceContextIsReturned) {
D3DKMT_HANDLE ctx = 0xc1;
wddm->context = ctx;
EXPECT_EQ(ctx, wddm->getOsDeviceContext());
}
| 38.895187 | 167 | 0.718921 | jdanecki |
d7270870006c2211dd2a228cf7cf92408265ad29 | 218 | hpp | C++ | app/world/GroundType.hpp | isonil/survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2017-05-12T10:12:41.000Z | 2017-05-12T10:12:41.000Z | app/world/GroundType.hpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | null | null | null | app/world/GroundType.hpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2019-01-09T04:05:36.000Z | 2019-01-09T04:05:36.000Z | #ifndef APP_GROUND_TYPE_HPP
#define APP_GROUND_TYPE_HPP
namespace app
{
enum class GroundType
{
Ground1,
Ground2,
Ground3,
Slope,
UnderWater
};
} // namespace app
#endif // APP_GROUND_TYPE_HPP
| 10.9 | 29 | 0.701835 | isonil |
d727d30ca9f1dd4fe28f34e093e93adb1eb79fd5 | 2,365 | cpp | C++ | SDK/g100IO/G100Config.cpp | mariusl/step2mach | 3ac7ff6c3b29a25f4520e4325e7922f2d34c547a | [
"MIT"
] | 6 | 2019-05-22T03:18:38.000Z | 2022-02-07T20:54:38.000Z | SDK/g100IO/G100Config.cpp | mariusl/step2mach | 3ac7ff6c3b29a25f4520e4325e7922f2d34c547a | [
"MIT"
] | 1 | 2019-11-10T05:57:09.000Z | 2020-07-01T05:50:49.000Z | SDK/g100IO/G100Config.cpp | mariusl/step2mach | 3ac7ff6c3b29a25f4520e4325e7922f2d34c547a | [
"MIT"
] | 9 | 2019-05-20T06:03:55.000Z | 2022-02-01T10:16:41.000Z | // G100Config.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "MachDevice.h"
#include "G100Config.h"
#include "G100-Structs.h"
#include ".\g100config.h"
#include "LocalIPQuery.h"
#include "GRexControl.h"
extern GRexControl *TheRex;
bool Exit;
// G100Config dialog
IMPLEMENT_DYNAMIC(G100Config, CDialog)
G100Config::G100Config(CWnd* pParent /*=NULL*/)
: CDialog(G100Config::IDD, pParent)
, m_Error(_T(""))
, m_Perm(FALSE)
{
Exit = false;
}
G100Config::~G100Config()
{
}
void G100Config::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_IPG100, m_G100IP);
DDX_Control(pDX, IDC_NMG100, m_G100NM);
DDX_Control(pDX, IDC_MYIP, m_MyIP);
DDX_Text(pDX, IDC_ERRORS, m_Error);
}
BEGIN_MESSAGE_MAP(G100Config, CDialog)
ON_BN_CLICKED(IDC_SENDNEW, OnBnClickedSendnew)
ON_BN_CLICKED(IDOK, OnBnClickedOk)
ON_BN_CLICKED(IDC_BUTTON2, OnBnClickedButton2)
END_MESSAGE_MAP()
// G100Config message handlers
BOOL G100Config::OnInitDialog()
{
CDialog::OnInitDialog();
//Lets show what we have recieved so far in terms of G100 Address.
unsigned ipaddr, netmask;
if (!TheRex->ge || !TheRex->ge->getIP(TheRex->inst, ipaddr, netmask))
ipaddr = netmask = 0;
m_G100IP.SetAddress(ipaddr);
m_G100NM.SetAddress(netmask);
//now lets get ours..
LocalIPQuery LocalMachine; //setup a localIp search class
// Search for an address which is _not_ 127.****
//FIXME: should display a list of addresses to do this properly.
DWORD test;
for (unsigned i = 0; i < LocalMachine.m_vIPAddress.size(); ++i) {
test = (LocalMachine.m_vIPAddress[LocalMachine.m_vIPAddress.size()-1].GetNBO());
if ((test & 0xFF) != 127)
break;
}
m_MyIP.SetAddress(test);
m_Error = TheRex->Disability;
UpdateData( false );
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void G100Config::OnBnClickedSendnew()
{
UpdateData( true );
DWORD data;
m_G100IP.GetAddress( data );
unsigned ipaddr = (unsigned)data;
m_G100NM.GetAddress( data);
unsigned netmask = (unsigned)data;
TheRex->ge->setIP(TheRex->inst, ipaddr, netmask);
TheRex->PHASE = SETIP;
UpdateData( false );
}
void G100Config::OnBnClickedOk()
{
if( !Exit )
{
TheRex->PHASE = DISCOVERY;
}
OnOK();
}
void G100Config::OnBnClickedButton2()
{
Exit = true;
OnOK();
}
| 22.102804 | 82 | 0.725159 | mariusl |
c01240b42907caa001f23783aeaea04a8a9633d1 | 4,736 | hpp | C++ | rclcpp/include/rclcpp/experimental/buffers/ring_buffer_implementation.hpp | hemalshahNV/rclcpp | bca3fd7da18e779a6c1aee118440c962503ee6b2 | [
"Apache-2.0"
] | 1 | 2022-02-28T21:29:12.000Z | 2022-02-28T21:29:12.000Z | rclcpp/include/rclcpp/experimental/buffers/ring_buffer_implementation.hpp | stokekld/rclcpp | 025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3 | [
"Apache-2.0"
] | null | null | null | rclcpp/include/rclcpp/experimental/buffers/ring_buffer_implementation.hpp | stokekld/rclcpp | 025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Open Source Robotics Foundation, 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.
#ifndef RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_
#define RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_
#include <mutex>
#include <stdexcept>
#include <utility>
#include <vector>
#include "rclcpp/experimental/buffers/buffer_implementation_base.hpp"
#include "rclcpp/logger.hpp"
#include "rclcpp/logging.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/visibility_control.hpp"
namespace rclcpp
{
namespace experimental
{
namespace buffers
{
/// Store elements in a fixed-size, FIFO buffer
/**
* All public member functions are thread-safe.
*/
template<typename BufferT>
class RingBufferImplementation : public BufferImplementationBase<BufferT>
{
public:
explicit RingBufferImplementation(size_t capacity)
: capacity_(capacity),
ring_buffer_(capacity),
write_index_(capacity_ - 1),
read_index_(0),
size_(0)
{
if (capacity == 0) {
throw std::invalid_argument("capacity must be a positive, non-zero value");
}
}
virtual ~RingBufferImplementation() {}
/// Add a new element to store in the ring buffer
/**
* This member function is thread-safe.
*
* \param request the element to be stored in the ring buffer
*/
void enqueue(BufferT request)
{
std::lock_guard<std::mutex> lock(mutex_);
write_index_ = next_(write_index_);
ring_buffer_[write_index_] = std::move(request);
if (is_full_()) {
read_index_ = next_(read_index_);
} else {
size_++;
}
}
/// Remove the oldest element from ring buffer
/**
* This member function is thread-safe.
*
* \return the element that is being removed from the ring buffer
*/
BufferT dequeue()
{
std::lock_guard<std::mutex> lock(mutex_);
if (!has_data_()) {
RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Calling dequeue on empty intra-process buffer");
throw std::runtime_error("Calling dequeue on empty intra-process buffer");
}
auto request = std::move(ring_buffer_[read_index_]);
read_index_ = next_(read_index_);
size_--;
return request;
}
/// Get the next index value for the ring buffer
/**
* This member function is thread-safe.
*
* \param val the current index value
* \return the next index value
*/
inline size_t next(size_t val)
{
std::lock_guard<std::mutex> lock(mutex_);
return next_(val);
}
/// Get if the ring buffer has at least one element stored
/**
* This member function is thread-safe.
*
* \return `true` if there is data and `false` otherwise
*/
inline bool has_data() const
{
std::lock_guard<std::mutex> lock(mutex_);
return has_data_();
}
/// Get if the size of the buffer is equal to its capacity
/**
* This member function is thread-safe.
*
* \return `true` if the size of the buffer is equal is capacity
* and `false` otherwise
*/
inline bool is_full() const
{
std::lock_guard<std::mutex> lock(mutex_);
return is_full_();
}
void clear() {}
private:
/// Get the next index value for the ring buffer
/**
* This member function is not thread-safe.
*
* \param val the current index value
* \return the next index value
*/
inline size_t next_(size_t val)
{
return (val + 1) % capacity_;
}
/// Get if the ring buffer has at least one element stored
/**
* This member function is not thread-safe.
*
* \return `true` if there is data and `false` otherwise
*/
inline bool has_data_() const
{
return size_ != 0;
}
/// Get if the size of the buffer is equal to its capacity
/**
* This member function is not thread-safe.
*
* \return `true` if the size of the buffer is equal is capacity
* and `false` otherwise
*/
inline bool is_full_() const
{
return size_ == capacity_;
}
size_t capacity_;
std::vector<BufferT> ring_buffer_;
size_t write_index_;
size_t read_index_;
size_t size_;
mutable std::mutex mutex_;
};
} // namespace buffers
} // namespace experimental
} // namespace rclcpp
#endif // RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_
| 24.53886 | 98 | 0.686233 | hemalshahNV |
c013c6ac7c33ece9f3b12466553654cad46ecb3a | 15,147 | cpp | C++ | src/Random.cpp | tehilinski/Random | 3aa9f5c067c2532611198627300606e97c2b2451 | [
"Apache-2.0"
] | null | null | null | src/Random.cpp | tehilinski/Random | 3aa9f5c067c2532611198627300606e97c2b2451 | [
"Apache-2.0"
] | null | null | null | src/Random.cpp | tehilinski/Random | 3aa9f5c067c2532611198627300606e97c2b2451 | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------------------------------------
// File: Random.cpp
// Class: teh::Random
//
// Description:
// Random number generator using the code from zufall.h/.c.
// See header file for more details.
//
// Author: Thomas E. Hilinski <https://github.com/tehilinski>
//
// Copyright 2020 Thomas E. Hilinski. 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
// and in the accompanying file LICENSE.md.
// 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 "Random.h"
#include <cmath>
using std::exp;
using std::cos;
using std::sin;
using std::sqrt;
using std::log;
#include <stdexcept>
#include <string>
#include <ctime>
namespace teh {
namespace zufall {
//---------------------------------------- class RandomSeed ----------------------------------------
unsigned int const RandomSeed::seedUpperLimit = UINT_MAX - 144U;
RandomSeed::RandomSeed (
unsigned int const entropy,
unsigned int const minSeed,
unsigned int const maxSeed )
: seedMin ( minSeed > 0 ? minSeed : 1 ),
seedMax ( maxSeed < seedUpperLimit ? maxSeed : seedUpperLimit - 1 ),
seed ( entropy == 0 ?
std::time(NULL) % GetRange().second :
entropy % GetRange().second )
{
if ( seed < seedMin || seed >= seedMax )
{
std::string msg = "Random: seed is out of range.";
throw std::runtime_error( msg );
}
if ( seedMin >= seedMax )
{
std::string msg = "Either minimum or maximum seed (or both) is invalid.";
throw std::runtime_error( msg );
}
}
//---------------------------------------- private to Random ----------------------------------------
struct klotz0_1_
{
static short const size = 607;
std::vector<double> buff;
unsigned int ptr;
klotz0_1_ ()
: buff (size, 0.0),
ptr (0)
{
}
};
klotz0_1_ klotz0_1;
// private to Random
struct klotz1_1_
{
static short const size = 1024;
std::vector<double> xbuff;
unsigned int first, xptr;
klotz1_1_ ()
: xbuff (size, 0.0),
first (0),
xptr (0)
{
}
};
static klotz1_1_ klotz1_1;
//---------------------------------------- class Random ----------------------------------------
Random::Random (
unsigned int const seed )
{
InitializeSeedBuffer (seed);
}
// ----------------------------------------------------------------------------
// InitializeSeedBuffer (formerly zufalli)
// Generates initial seed buffer by linear congruential
// method. Taken from Marsaglia, FSU report FSU-SCRI-87-50
// Variable seed should be 0 < seed < ( numeric_limits<unsigned int> - 144 )
// ----------------------------------------------------------------------------
void Random::InitializeSeedBuffer (
unsigned int const seed)
{
unsigned int const ij = seed;
unsigned int i = ij / 177 % 177 + 2;
unsigned int j = ij % 177 + 2;
unsigned int k = 9373 / 169 % 178 + 1;
unsigned int l = 9373 % 169;
for (unsigned int ii = 0; ii < (unsigned int)klotz0_1.size; ++ii)
{
double s = 0.0;
double t = 0.5;
for (unsigned int jj = 1; jj <= 24; ++jj)
{
unsigned int m = i * j % 179 * k % 179;
i = j;
j = k;
k = m;
l = (l * 53 + 1) % 169;
if (l * m % 64 >= 32)
s += t;
t *= 0.5;
}
klotz0_1.buff[ii] = s;
}
}
// ----------------------------------------------------------------------------
// Uniform (formerly zufall)
// portable lagged Fibonacci series uniform random number
// generator with "lags" -273 und -607:
// W.P. Petersen, IPS, ETH Zuerich, 19 Mar. 92
// ----------------------------------------------------------------------------
double Random::Uniform ()
{
std::vector<double> a;
Uniform( 1, a );
return a[0];
}
void Random::Uniform (
unsigned int const n,
std::vector<double> & a)
{
if (n == 0)
return;
a.assign (n, 0.0);
unsigned int left, bptr, aptr0;
double t;
unsigned int vl, k273, k607, kptr;
unsigned int aptr = 0;
unsigned int nn = n;
L1:
if (nn == 0)
return;
/* factor nn = q*607 + r */
unsigned int q = (nn - 1) / klotz0_1.size;
left = klotz0_1.size - klotz0_1.ptr;
if (q <= 1)
{
/* only one or fewer full segments */
if (nn < left)
{
kptr = klotz0_1.ptr;
for (unsigned int i = 0; i < nn; ++i)
a[i + aptr] = klotz0_1.buff[kptr + i];
klotz0_1.ptr += nn;
return;
}
else
{
kptr = klotz0_1.ptr;
#pragma _CRI ivdep
for (unsigned int i = 0; i < left; ++i)
a[i + aptr] = klotz0_1.buff[kptr + i];
klotz0_1.ptr = 0;
aptr += left;
nn -= left;
/* buff -> buff case */
vl = 273;
k273 = 334;
k607 = 0;
for (unsigned int k = 0; k < 3; ++k)
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = klotz0_1.buff[k273+i]+klotz0_1.buff[k607+i];
klotz0_1.buff[k607+i] = t - (double) ((unsigned int) t);
}
k607 += vl;
k273 += vl;
vl = 167;
if (k == 0)
{
k273 = 0;
}
}
goto L1;
}
}
else
{
/* more than 1 full segment */
kptr = klotz0_1.ptr;
#pragma _CRI ivdep
for (unsigned int i = 0; i < left; ++i)
a[i + aptr] = klotz0_1.buff[kptr + i];
nn -= left;
klotz0_1.ptr = 0;
aptr += left;
/* buff -> a(aptr0) */
vl = 273;
k273 = 334;
k607 = 0;
for (unsigned int k = 0; k < 3; ++k)
{
if (k == 0)
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = klotz0_1.buff[k273+i]+klotz0_1.buff[k607+i];
a[aptr + i] = t - (double) ((unsigned int) t);
}
k273 = aptr;
k607 += vl;
aptr += vl;
vl = 167;
}
else
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = a[k273 + i] + klotz0_1.buff[k607 + i];
a[aptr + i] = t - (double) ((unsigned int) t);
}
k607 += vl;
k273 += vl;
aptr += vl;
}
}
nn += -klotz0_1.size;
/* a(aptr-607) -> a(aptr) for last of the q-1 segments */
aptr0 = aptr - klotz0_1.size;
vl = klotz0_1.size;
for (unsigned int qq = 0; qq < q-2; ++qq)
{
k273 = aptr0 + 334;
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = a[k273 + i] + a[aptr0 + i];
a[aptr + i] = t - (double) ((unsigned int) t);
}
nn += -klotz0_1.size;
aptr += vl;
aptr0 += vl;
}
/* a(aptr0) -> buff, last segment before residual */
vl = 273;
k273 = aptr0 + 334;
k607 = aptr0;
bptr = 0;
for (unsigned int k = 0; k < 3; ++k)
{
if (k == 0)
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = a[k273 + i] + a[k607 + i];
klotz0_1.buff[bptr + i] = t - (double) ((unsigned int) t);
}
k273 = 0;
k607 += vl;
bptr += vl;
vl = 167;
}
else
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = klotz0_1.buff[k273 + i] + a[k607 + i];
klotz0_1.buff[bptr + i] = t - (double) ((unsigned int) t);
}
k607 += vl;
k273 += vl;
bptr += vl;
}
}
goto L1;
}
}
// ----------------------------------------------------------------------------
// Normal (formerly normalen)
// Box-Muller method for Gaussian random numbers.
// ----------------------------------------------------------------------------
double Random::Normal ()
{
std::vector<double> x;
Uniform( 1, x );
return x[0];
}
void Random::Normal (
unsigned int const n,
std::vector<double> & x)
{
if (n == 0)
return;
x.assign (n, 0.0);
if (klotz1_1.first == 0)
{
normal00();
klotz1_1.first = 1;
}
unsigned int ptr = 0;
unsigned int nn = n;
L1:
unsigned int const left = klotz1_1.size - klotz1_1.xptr;
unsigned int const kptr = klotz1_1.xptr;
if (nn < left)
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < nn; ++i)
x[i + ptr] = klotz1_1.xbuff[kptr + i];
klotz1_1.xptr += nn;
return;
}
else
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < left; ++i)
x[i + ptr] = klotz1_1.xbuff[kptr + i];
klotz1_1.xptr = 0;
ptr += left;
nn -= left;
normal00();
goto L1;
}
}
// ----------------------------------------------------------------------------
// Poisson (formerly fische)
// Poisson generator for distribution function of p's:
// q(mu,p) = exp(-mu) mu**p/p!
// ----------------------------------------------------------------------------
unsigned int Random::Poisson (
double const mu)
{
std::vector<unsigned int> p;
Poisson( 1, mu, p );
return p[0];
}
void Random::Poisson (
unsigned int const n,
double const mu,
std::vector<unsigned int> & p)
{
if (n == 0)
return;
p.assign (n, 0);
double const pmu = exp(-mu);
unsigned int p0 = 0;
unsigned int nsegs = (n - 1) / klotz1_1.size;
unsigned int left = n - (nsegs << 10);
++nsegs;
unsigned int nl0 = left;
std::vector<unsigned int> indx (klotz1_1.size);
std::vector<double> q (klotz1_1.size);
std::vector<double> u (klotz1_1.size);
for (unsigned int k = 0; k < nsegs; ++k)
{
for (unsigned int i = 0; i < left; ++i)
{
indx[i] = i;
p[p0 + i] = 0;
q[i] = 1.;
}
/* Begin iterative loop on segment of p's */
do
{
Uniform (left, u); // Get the needed uniforms
unsigned int jj = 0;
for (unsigned int i = 0; i < left; ++i)
{
unsigned int const ii = indx[i];
double const q0 = q[ii] * u[i];
q[ii] = q0;
if (q0 > pmu)
{
indx[jj++] = ii;
++p[p0 + ii];
}
}
left = jj; // any left in this segment?
}
while (left > 0);
p0 += nl0;
nl0 = klotz1_1.size;
left = klotz1_1.size;
}
}
// ----------------------------------------------------------------------------
// zufallsv
// saves common blocks klotz0, containing seeds and
// pointer to position in seed block. IMPORTANT: svblk must be
// dimensioned at least 608 in driver. The entire contents
// of klotz0 (pointer in buff, and buff) must be saved.
// ----------------------------------------------------------------------------
void Random::zufallsv (
std::vector<double> & saveBuffer) // size = klotz0_1_.size + 1
{
saveBuffer.resize (klotz0_1_::size + 1);
saveBuffer[0] = (double) klotz0_1.ptr;
#pragma _CRI ivdep
for (short i = 0; i < klotz0_1.size; ++i)
saveBuffer[i + 1] = klotz0_1.buff[i];
}
// ----------------------------------------------------------------------------
// zufallrs
// restores common block klotz0, containing seeds and pointer
// to position in seed block. IMPORTANT: saveBuffer must be
// dimensioned at least 608 in driver. The entire contents
// of klotz0 must be restored.
// ----------------------------------------------------------------------------
void Random::zufallrs (
std::vector<double> const & saveBuffer) // size = klotz0_1_.size + 1
{
if ( saveBuffer.size() != klotz0_1_::size + 1 )
{
std::string msg;
msg = "Random::zufallrs, restore of uninitialized block.";
throw std::runtime_error (msg);
}
klotz0_1.ptr = (unsigned int) saveBuffer[0];
#pragma _CRI ivdep
for (short i = 0; i < klotz0_1.size; ++i)
klotz0_1.buff[i] = saveBuffer[i + 1];
}
// ----------------------------------------------------------------------------
// normalsv
// save zufall block klotz0
// IMPORTANT: svbox must be dimensioned at
// least 1634 in driver. The entire contents of blocks
// klotz0 (via zufallsv) and klotz1 must be saved.
// ----------------------------------------------------------------------------
void Random::normalsv (
std::vector<double> & saveBuffer) // size = 1634
{
if (klotz1_1.first == 0)
{
std::string msg;
msg = "Random::normalsv, save of uninitialized block.";
throw std::runtime_error (msg);
}
saveBuffer.resize (1634);
zufallsv (saveBuffer);
saveBuffer[klotz0_1.size + 1] = (double) klotz1_1.first; // [608]
saveBuffer[klotz0_1.size + 2] = (double) klotz1_1.xptr; // [609]
unsigned int const k = klotz0_1.size + 3; // 610
#pragma _CRI ivdep
for (short i = 0; i < klotz1_1.size; ++i)
saveBuffer[i + k] = klotz1_1.xbuff[i];
}
// ----------------------------------------------------------------------------
// normalrs
// restore zufall blocks klotz0 and klotz1
// IMPORTANT: saveBuffer must be dimensioned at
// least 1634 in driver. The entire contents
// of klotz0 and klotz1 must be restored.
// ----------------------------------------------------------------------------
void Random::normalrs (
std::vector<double> const & saveBuffer) // size = 1634
{
zufallrs (saveBuffer);
klotz1_1.first = (unsigned int) saveBuffer[klotz0_1.size + 1]; // [608]
if (klotz1_1.first == 0)
{
std::string msg;
msg = "Random::normalrs, restore of uninitialized block.";
throw std::runtime_error (msg);
}
klotz1_1.xptr = (unsigned int) saveBuffer[klotz0_1.size + 2]; // [609]
unsigned int const k = klotz0_1.size + 3; // 610
#pragma _CRI ivdep
for (short i = 0; i < klotz1_1.size; ++i)
klotz1_1.xbuff[i] = saveBuffer[i + k];
}
// ----------------------------------------------------------------------------
// normal00
// ----------------------------------------------------------------------------
void Random::normal00 ()
{
/* Builtin functions */
/* double cos(), sin(), log(), sqrt(); */
double const twopi = 6.2831853071795862;
Uniform (klotz1_1.size, klotz1_1.xbuff);
// std::vector<double>::iterator i = klotz1_1.xbuff.begin();
// std::vector<double>::iterator ip1 = klotz1_1.xbuff.begin();
// while ( ip1 != klotz1_1.xbuff.end() )
// {
// double const r1 = twopi * (*i);
// double const t1 = cos(r1);
// double const t2 = sin(r1);
// double const r2 = sqrt(-2.0 * ( log(1.0 - (*ip1) ) ) );
// (*i) = t1 * r2;
// (*ip1) = t2 * r2;
// ++i; ++i;
// ++ip1; ++ip1;
// }
#pragma _CRI ivdep
for (short i = 0; i < klotz1_1.size - 1; i += 2)
{
double const r1 = twopi * klotz1_1.xbuff[i];
double const t1 = cos(r1);
double const t2 = sin(r1);
double const r2 = sqrt(-2.0 * ( log(1.0 - klotz1_1.xbuff[i+1] ) ) );
klotz1_1.xbuff[i] = t1 * r2;
klotz1_1.xbuff[i+1] = t2 * r2;
}
} // class Random
} // namespace zufall
} // namespace teh
| 25.936644 | 110 | 0.494355 | tehilinski |
c01a0bc743f10f3bfff54218a1db9ca4026e8dd8 | 4,185 | cpp | C++ | CsUserInterface/Source/CsUI/Public/Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsUserInterface/Source/CsUI/Public/Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsUserInterface/Source/CsUI/Public/Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
#include "Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.h"
// Library
#include "Managers/Pool/Payload/CsLibrary_Payload_PooledObject.h"
// Pool
#include "Managers/Pool/Payload/CsPayload_PooledObject.h"
// FX
#include "Managers/WidgetActor/Payload/CsPayload_WidgetActor.h"
#include "NiagaraComponent.h"
// Component
#include "Components/CsWidgetComponent.h"
const FName NCsWidgetActor::NCache::FImpl::Name = FName("NCsWidgetActor::NCache::FImpl");
namespace NCsWidgetActor
{
namespace NCache
{
namespace NImplCached
{
namespace Str
{
CS_DEFINE_CACHED_FUNCTION_NAME_AS_STRING(NCsWidgetActor::NCache::FImpl, Allocate);
}
}
FImpl::FImpl() :
// ICsGetInterfaceMap
InterfaceMap(nullptr),
// PooledCacheType (NCsPooledObject::NCache::ICache)
Index(INDEX_NONE),
bAllocated(false),
bQueueDeallocate(false),
State(NCsPooledObject::EState::Inactive),
UpdateType(NCsPooledObject::EUpdate::Manager),
Instigator(),
Owner(),
Parent(),
WarmUpTime(0.0f),
LifeTime(0.0f),
StartTime(),
ElapsedTime(),
// WidgetActorCacheType (NCsWidgetActor::NCache::ICache)
DeallocateMethod(ECsWidgetActorDeallocateMethod::Complete),
QueuedLifeTime(0.0f)
{
InterfaceMap = new FCsInterfaceMap();
InterfaceMap->SetRoot<FImpl>(this);
typedef NCsPooledObject::NCache::ICache PooledCacheType;
typedef NCsWidgetActor::NCache::ICache WidgetActorCacheType;
InterfaceMap->Add<PooledCacheType>(static_cast<PooledCacheType*>(this));
InterfaceMap->Add<WidgetActorCacheType>(static_cast<WidgetActorCacheType*>(this));
}
FImpl::~FImpl()
{
delete InterfaceMap;
}
// PooledCacheType (NCsPooledObject::NCache::ICache)
#pragma region
#define PooledPayloadType NCsPooledObject::NPayload::IPayload
void FImpl::Allocate(PooledPayloadType* Payload)
{
#undef PooledPayloadType
using namespace NImplCached;
const FString& Context = Str::Allocate;
// PooledCacheType (NCsPooledObject::NCache::ICache)
bAllocated = true;
State = NCsPooledObject::EState::Active;
UpdateType = Payload->GetUpdateType();
Instigator = Payload->GetInstigator();
Owner = Payload->GetOwner();
Parent = Payload->GetParent();
StartTime = Payload->GetTime();
// WidgetActorCacheType (NCsWidgetActor::NPayload::IPayload)
typedef NCsWidgetActor::NPayload::IPayload WidgetPayloadType;
typedef NCsPooledObject::NPayload::FLibrary PooledPayloadLibrary;
WidgetPayloadType* WidgetPayload = PooledPayloadLibrary::GetInterfaceChecked<WidgetPayloadType>(Context, Payload);
DeallocateMethod = WidgetPayload->GetDeallocateMethod();
QueuedLifeTime = WidgetPayload->GetLifeTime();
}
void FImpl::Deallocate()
{
Reset();
}
void FImpl::QueueDeallocate()
{
bQueueDeallocate = true;
// LifeTime
if (DeallocateMethod == ECsWidgetActorDeallocateMethod::LifeTime)
{
// Reset ElapsedTime
ElapsedTime.Reset();
// Set LifeTime
LifeTime = QueuedLifeTime;
}
}
bool FImpl::ShouldDeallocate() const
{
if (bQueueDeallocate)
{
// LifeTime, let HasLifeTimeExpired handle deallocation
if (DeallocateMethod == ECsWidgetActorDeallocateMethod::LifeTime)
{
return false;
}
return bQueueDeallocate;
}
return false;
}
bool FImpl::HasLifeTimeExpired()
{
return LifeTime > 0.0f && ElapsedTime.Time > LifeTime;
}
void FImpl::Reset()
{
// PooledCacheType (NCsPooledObject::NCache::ICache)
bAllocated = false;
bQueueDeallocate = false;
State = NCsPooledObject::EState::Inactive;
UpdateType = NCsPooledObject::EUpdate::Manager;
Instigator.Reset();
Owner.Reset();
Parent.Reset();
WarmUpTime = 0.0f;
LifeTime = 0.0f;
StartTime.Reset();
ElapsedTime.Reset();
// WidgetActorCacheType (NCsWidgetActor::NPayload::IPayload)
DeallocateMethod = ECsWidgetActorDeallocateMethod::ECsWidgetActorDeallocateMethod_MAX;
QueuedLifeTime = 0.0f;
}
#pragma endregion PooledCacheType (NCsPooledObject::NCache::ICache)
void FImpl::Update(const FCsDeltaTime& DeltaTime)
{
ElapsedTime += DeltaTime;
}
}
} | 26.320755 | 117 | 0.726165 | closedsum |
c01e6226129e42352202a53cc0a8e810e048e6c2 | 2,217 | cpp | C++ | src/platform/new_platform/core.cpp | mokoi/luxengine | 965532784c4e6112141313997d040beda4b56d07 | [
"MIT"
] | 11 | 2015-03-02T07:43:00.000Z | 2021-12-04T04:53:02.000Z | src/platform/new_platform/core.cpp | mokoi/luxengine | 965532784c4e6112141313997d040beda4b56d07 | [
"MIT"
] | 1 | 2015-03-28T17:17:13.000Z | 2016-10-10T05:49:07.000Z | src/platform/new_platform/core.cpp | mokoi/luxengine | 965532784c4e6112141313997d040beda4b56d07 | [
"MIT"
] | 3 | 2016-11-04T01:14:31.000Z | 2020-05-07T23:42:27.000Z | /****************************
Copyright (c) 2006-2012 Luke Salisbury
Copyright (c) 2008 Mokoi Gaming
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 "core.h"
#include "luxengine.h"
/* Local functions */
CoreSystem::CoreSystem()
{
}
CoreSystem::~CoreSystem()
{
}
uint32_t CoreSystem::WasInit(uint32_t flag)
{
return 1;
}
void CoreSystem::QuitSubSystem(uint32_t flag)
{
}
bool CoreSystem::InitSubSystem(uint32_t flag)
{
return true;
}
bool CoreSystem::Good()
{
return this->good;
}
uint32_t CoreSystem::GetTime()
{
return 0;
}
uint32_t CoreSystem::GetFrameDelta()
{
return 15;
}
bool CoreSystem::DelayIf(uint32_t diff)
{
return false;
}
void CoreSystem::Idle()
{
}
LuxState CoreSystem::HandleFrame(LuxState old_state)
{
if ( this->state > PAUSED || old_state >= SAVING )
{
this->state = old_state;
}
this->RefreshInput(lux::display);
this->time = this->GetTime();
return this->state;
}
int16_t CoreSystem::GetInput(InputDevice device, uint32_t device_number, int32_t symbol)
{
if (device == NOINPUT)
{
return 0;
}
switch (device)
{
case CONTROLAXIS:
{
return 0;
}
case CONTROLBUTTON:
{
return 0;
}
case KEYBOARD:
case MOUSEAXIS:
case MOUSEBUTTON:
case NOINPUT:
default:
return 0;
}
return 0;
}
void CoreSystem::RefreshInput( DisplaySystem * display )
{
}
bool CoreSystem::InputLoopGet(uint16_t & key)
{
// Keyboard Stuff
return 0;
}
| 18.322314 | 243 | 0.710419 | mokoi |
c0211263b554e3e0e0447535d61fdbbf331b1d03 | 2,468 | cpp | C++ | input-output_example_gen/bench/gramschmidt.cpp | dongchen-coder/symRIByInputOuputExamples | e7434699f44ceb01f153ac8623b5bafac57f8abf | [
"MIT"
] | null | null | null | input-output_example_gen/bench/gramschmidt.cpp | dongchen-coder/symRIByInputOuputExamples | e7434699f44ceb01f153ac8623b5bafac57f8abf | [
"MIT"
] | null | null | null | input-output_example_gen/bench/gramschmidt.cpp | dongchen-coder/symRIByInputOuputExamples | e7434699f44ceb01f153ac8623b5bafac57f8abf | [
"MIT"
] | null | null | null | #include "./utility/rt.h"
#include <math.h>
int N;
int M;
#define A_OFFSET 0
#define R_OFFSET N * M
#define Q_OFFSET N * M + N * N
void gramschmidt_trace(double* A, double* R, double* Q) {
int k, i, j;
double nrm;
vector<int> idx;
for (k = 0; k < N; k++) {
nrm = 0.0;
for (i = 0; i < M; i++) {
idx.clear(); idx.push_back(k); idx.push_back(i);
nrm += A[i * N + k] * A[i * N + k];
rtTmpAccess(A_OFFSET + i * N + k, 0, 0, idx);
rtTmpAccess(A_OFFSET + i * N + k, 1, 0, idx);
}
idx.clear(); idx.push_back(k);
R[k * N + k] = sqrt(nrm);
rtTmpAccess(R_OFFSET + k * N + k, 2, 1, idx);
for (i = 0; i < M; i++) {
idx.clear(); idx.push_back(k); idx.push_back(i);
Q[i * N + k] = A[i * N + k] / R[k * N + k];
rtTmpAccess(A_OFFSET + i * N + k, 3, 0, idx);
rtTmpAccess(R_OFFSET + k * N + k, 4, 1, idx);
rtTmpAccess(Q_OFFSET + i * N + k, 5, 2, idx);
}
for (j = k + 1; j < N; j++) {
idx.clear(); idx.push_back(k); idx.push_back(j);
R[k * N + j] = 0.0;
rtTmpAccess(R_OFFSET + k * N + j, 6, 1, idx);
for (i = 0; i < M; i++) {
idx.clear(); idx.push_back(k); idx.push_back(j); idx.push_back(i);
R[k * N + j] += Q[i * N + k] * A[i * N + j];
rtTmpAccess(Q_OFFSET + i * N + k, 7, 2, idx);
rtTmpAccess(A_OFFSET + i * N + j, 8, 0, idx);
rtTmpAccess(R_OFFSET + k * N + j, 9, 1, idx);
rtTmpAccess(R_OFFSET + k * N + j, 10, 1, idx);
}
for (i = 0; i < M; i++) {
idx.clear(); idx.push_back(k); idx.push_back(j); idx.push_back(i);
A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j];
rtTmpAccess(A_OFFSET + i * N + j, 11, 0, idx);
rtTmpAccess(Q_OFFSET + i * N + k, 12, 2, idx);
rtTmpAccess(R_OFFSET + k * N + j, 13, 1, idx);
rtTmpAccess(A_OFFSET + i * N + j, 14, 0, idx);
}
}
}
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cout << "This benchmark needs 2 loop bounds" << endl;
return 0;
}
for (int i = 1; i < argc; i++) {
if (!isdigit(argv[i][0])) {
cout << "arguments must be integer" << endl;
return 0;
}
}
M = stoi(argv[1]);
N = stoi(argv[2]);
double * A = (double *)malloc(N * M * sizeof(double));
double * R = (double *)malloc(N * N * sizeof(double));
double * Q = (double *)malloc(M * N * sizeof(double));
gramschmidt_trace(A, R, Q);
dumpRIHistogram();
return 0;
}
| 29.035294 | 82 | 0.487844 | dongchen-coder |
c02159588cf3470fdc6f54a34837abb9ee14a163 | 8,958 | hpp | C++ | include/eosio/time.hpp | swang-b1/abieos | 52ea28c0c2d771d101a2fe0ae4d176bb35a2f0cb | [
"MIT"
] | 71 | 2019-05-17T03:02:30.000Z | 2022-02-11T03:59:10.000Z | include/eosio/time.hpp | swang-b1/abieos | 52ea28c0c2d771d101a2fe0ae4d176bb35a2f0cb | [
"MIT"
] | 49 | 2019-05-21T18:52:57.000Z | 2022-03-07T16:44:40.000Z | include/eosio/time.hpp | swang-b1/abieos | 52ea28c0c2d771d101a2fe0ae4d176bb35a2f0cb | [
"MIT"
] | 36 | 2018-07-19T02:40:22.000Z | 2022-03-14T13:51:59.000Z | #pragma once
#include "chain_conversions.hpp"
#include "check.hpp"
#include "operators.hpp"
#include "reflection.hpp"
#include "from_json.hpp"
#include <stdint.h>
#include <string>
namespace eosio {
/**
* @defgroup time
* @ingroup core
* @brief Classes for working with time.
*/
class microseconds {
public:
microseconds() = default;
explicit microseconds(int64_t c) : _count(c) {}
/// @cond INTERNAL
static microseconds maximum() { return microseconds(0x7fffffffffffffffll); }
friend microseconds operator+(const microseconds& l, const microseconds& r) {
return microseconds(l._count + r._count);
}
friend microseconds operator-(const microseconds& l, const microseconds& r) {
return microseconds(l._count - r._count);
}
microseconds& operator+=(const microseconds& c) {
_count += c._count;
return *this;
}
microseconds& operator-=(const microseconds& c) {
_count -= c._count;
return *this;
}
int64_t count() const { return _count; }
int64_t to_seconds() const { return _count / 1000000; }
int64_t _count = 0;
/// @endcond
};
EOSIO_REFLECT(microseconds, _count);
EOSIO_COMPARE(microseconds);
inline microseconds seconds(int64_t s) { return microseconds(s * 1000000); }
inline microseconds milliseconds(int64_t s) { return microseconds(s * 1000); }
inline microseconds minutes(int64_t m) { return seconds(60 * m); }
inline microseconds hours(int64_t h) { return minutes(60 * h); }
inline microseconds days(int64_t d) { return hours(24 * d); }
/**
* High resolution time point in microseconds
*
* @ingroup time
*/
class time_point {
public:
time_point() = default;
explicit time_point(microseconds e) : elapsed(e) {}
const microseconds& time_since_epoch() const { return elapsed; }
uint32_t sec_since_epoch() const { return uint32_t(elapsed.count() / 1000000); }
static time_point max() { return time_point( microseconds::maximum() ); }
/// @cond INTERNAL
time_point& operator+=(const microseconds& m) {
elapsed += m;
return *this;
}
time_point& operator-=(const microseconds& m) {
elapsed -= m;
return *this;
}
time_point operator+(const microseconds& m) const { return time_point(elapsed + m); }
time_point operator+(const time_point& m) const { return time_point(elapsed + m.elapsed); }
time_point operator-(const microseconds& m) const { return time_point(elapsed - m); }
microseconds operator-(const time_point& m) const { return microseconds(elapsed.count() - m.elapsed.count()); }
microseconds elapsed;
/// @endcond
};
EOSIO_REFLECT(time_point, elapsed);
EOSIO_COMPARE(time_point);
template <typename S>
void from_json(time_point& obj, S& stream) {
auto s = stream.get_string();
uint64_t utc_microseconds;
if (!eosio::string_to_utc_microseconds(utc_microseconds, s.data(), s.data() + s.size())) {
check(false, convert_json_error(eosio::from_json_error::expected_time_point));
}
obj = time_point(microseconds(utc_microseconds));
}
template <typename S>
void to_json(const time_point& obj, S& stream) {
return to_json(eosio::microseconds_to_str(obj.elapsed._count), stream);
}
/**
* A lower resolution time_point accurate only to seconds from 1970
*
* @ingroup time
*/
class time_point_sec {
public:
time_point_sec() : utc_seconds(0) {}
explicit time_point_sec(uint32_t seconds) : utc_seconds(seconds) {}
time_point_sec(const time_point& t) : utc_seconds(uint32_t(t.time_since_epoch().count() / 1000000ll)) {}
static time_point_sec maximum() { return time_point_sec(0xffffffff); }
static time_point_sec min() { return time_point_sec(0); }
operator time_point() const { return time_point(eosio::seconds(utc_seconds)); }
uint32_t sec_since_epoch() const { return utc_seconds; }
/// @cond INTERNAL
time_point_sec operator=(const eosio::time_point& t) {
utc_seconds = uint32_t(t.time_since_epoch().count() / 1000000ll);
return *this;
}
time_point_sec& operator+=(uint32_t m) {
utc_seconds += m;
return *this;
}
time_point_sec& operator+=(microseconds m) {
utc_seconds += m.to_seconds();
return *this;
}
time_point_sec& operator+=(time_point_sec m) {
utc_seconds += m.utc_seconds;
return *this;
}
time_point_sec& operator-=(uint32_t m) {
utc_seconds -= m;
return *this;
}
time_point_sec& operator-=(microseconds m) {
utc_seconds -= m.to_seconds();
return *this;
}
time_point_sec& operator-=(time_point_sec m) {
utc_seconds -= m.utc_seconds;
return *this;
}
time_point_sec operator+(uint32_t offset) const { return time_point_sec(utc_seconds + offset); }
time_point_sec operator-(uint32_t offset) const { return time_point_sec(utc_seconds - offset); }
friend time_point operator+(const time_point_sec& t, const microseconds& m) { return time_point(t) + m; }
friend time_point operator-(const time_point_sec& t, const microseconds& m) { return time_point(t) - m; }
friend microseconds operator-(const time_point_sec& t, const time_point_sec& m) {
return time_point(t) - time_point(m);
}
friend microseconds operator-(const time_point& t, const time_point_sec& m) { return time_point(t) - time_point(m); }
uint32_t utc_seconds;
/// @endcond
};
EOSIO_REFLECT(time_point_sec, utc_seconds);
EOSIO_COMPARE(time_point);
template <typename S>
void from_json(time_point_sec& obj, S& stream) {
auto s = stream.get_string();
const char* p = s.data();
if (!eosio::string_to_utc_seconds(obj.utc_seconds, p, s.data() + s.size(), true, true)) {
check(false, convert_json_error(from_json_error::expected_time_point));
}
}
template <typename S>
void to_json(const time_point_sec& obj, S& stream) {
return to_json(eosio::microseconds_to_str(uint64_t(obj.utc_seconds) * 1'000'000), stream);
}
/**
* This class is used in the block headers to represent the block time
* It is a parameterised class that takes an Epoch in milliseconds and
* and an interval in milliseconds and computes the number of slots.
*
* @ingroup time
**/
class block_timestamp {
public:
block_timestamp() = default;
explicit block_timestamp(uint32_t s) : slot(s) {}
block_timestamp(const time_point& t) { set_time_point(t); }
block_timestamp(const time_point_sec& t) { set_time_point(t); }
static block_timestamp maximum() { return block_timestamp(0xffff); }
static block_timestamp min() { return block_timestamp(0); }
block_timestamp next() const {
eosio::check(std::numeric_limits<uint32_t>::max() - slot >= 1, "block timestamp overflow");
auto result = block_timestamp(*this);
result.slot += 1;
return result;
}
time_point to_time_point() const { return (time_point)(*this); }
operator time_point() const {
int64_t msec = slot * (int64_t)block_interval_ms;
msec += block_timestamp_epoch;
return time_point(milliseconds(msec));
}
/// @cond INTERNAL
void operator=(const time_point& t) { set_time_point(t); }
bool operator>(const block_timestamp& t) const { return slot > t.slot; }
bool operator>=(const block_timestamp& t) const { return slot >= t.slot; }
bool operator<(const block_timestamp& t) const { return slot < t.slot; }
bool operator<=(const block_timestamp& t) const { return slot <= t.slot; }
bool operator==(const block_timestamp& t) const { return slot == t.slot; }
bool operator!=(const block_timestamp& t) const { return slot != t.slot; }
uint32_t slot = 0;
static constexpr int32_t block_interval_ms = 500;
static constexpr int64_t block_timestamp_epoch = 946684800000ll; // epoch is year 2000
/// @endcond
private:
void set_time_point(const time_point& t) {
int64_t micro_since_epoch = t.time_since_epoch().count();
int64_t msec_since_epoch = micro_since_epoch / 1000;
slot = uint32_t((msec_since_epoch - block_timestamp_epoch) / int64_t(block_interval_ms));
}
void set_time_point(const time_point_sec& t) {
int64_t sec_since_epoch = t.sec_since_epoch();
slot = uint32_t((sec_since_epoch * 1000 - block_timestamp_epoch) / block_interval_ms);
}
}; // block_timestamp
/**
* @ingroup time
*/
typedef block_timestamp block_timestamp_type;
EOSIO_REFLECT(block_timestamp_type, slot);
template <typename S>
void from_json(block_timestamp& obj, S& stream) {
time_point tp;
from_json(tp, stream);
obj = block_timestamp(tp);
}
template <typename S>
void to_json(const block_timestamp& obj, S& stream) {
return to_json(time_point(obj), stream);
}
} // namespace eosio
| 33.803774 | 120 | 0.674816 | swang-b1 |
c0231d0ad488c3862a528706c7e05b0003e20dee | 950 | cpp | C++ | sources/urlify_in_place/urlify_in_place.cpp | jacek143/code_area_template | 57784b1d6139c6f7cb8be0ebd3fee162f1d5e558 | [
"MIT"
] | null | null | null | sources/urlify_in_place/urlify_in_place.cpp | jacek143/code_area_template | 57784b1d6139c6f7cb8be0ebd3fee162f1d5e558 | [
"MIT"
] | null | null | null | sources/urlify_in_place/urlify_in_place.cpp | jacek143/code_area_template | 57784b1d6139c6f7cb8be0ebd3fee162f1d5e558 | [
"MIT"
] | null | null | null | #include "urlify_in_place.h"
using urlify_in_place::buffer_t;
namespace {
struct Lengths {
size_t current;
size_t urlficated;
};
Lengths compute_lengths(const buffer_t *p_buffer) {
Lengths lengths = {0, 0};
for (size_t i = 0; p_buffer->at(i) != '\0'; i++) {
lengths.current++;
lengths.urlficated += p_buffer->at(i) == ' ' ? 3 : 1;
}
return lengths;
}
void urlify_knowing_lengths(buffer_t *p_buffer, Lengths lengths) {
auto destination = lengths.urlficated;
auto source = lengths.current;
while (destination != source) {
auto character = p_buffer->at(source--);
if (character != ' ') {
p_buffer->at(destination--) = character;
} else {
p_buffer->at(destination--) = '0';
p_buffer->at(destination--) = '2';
p_buffer->at(destination--) = '%';
}
}
}
} // namespace
void urlify_in_place::urlify(buffer_t *p_buffer) {
urlify_knowing_lengths(p_buffer, compute_lengths(p_buffer));
}
| 24.358974 | 66 | 0.650526 | jacek143 |
c02398d674739626eea07d0ea5211e05da1cfa0c | 4,470 | cpp | C++ | NanoTest/Source/Nano/Threads/TThreadPool.cpp | refnum/Nano | dceb0907061f7845d8a3c662f309ca164e932e6f | [
"BSD-3-Clause"
] | 23 | 2019-11-12T09:31:11.000Z | 2021-09-13T08:59:37.000Z | NanoTest/Source/Nano/Threads/TThreadPool.cpp | refnum/nano | dceb0907061f7845d8a3c662f309ca164e932e6f | [
"BSD-3-Clause"
] | 1 | 2020-10-30T09:54:12.000Z | 2020-10-30T09:54:12.000Z | NanoTest/Source/Nano/Threads/TThreadPool.cpp | refnum/Nano | dceb0907061f7845d8a3c662f309ca164e932e6f | [
"BSD-3-Clause"
] | 3 | 2015-09-08T11:00:02.000Z | 2017-09-11T05:42:30.000Z | /* NAME:
TThreadPool.cpp
DESCRIPTION:
NThreadPool tests.
COPYRIGHT:
Copyright (c) 2006-2021, refNum Software
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.
___________________________________________________________________________
*/
//=============================================================================
// Includes
//-----------------------------------------------------------------------------
// Nano
#include "NTestFixture.h"
#include "NThreadPool.h"
#include "NThreadTask.h"
//=============================================================================
// Fixture
//-----------------------------------------------------------------------------
NANO_FIXTURE(TThreadPool)
{
std::unique_ptr<NThreadPool> thePool;
SETUP
{
thePool = std::make_unique<NThreadPool>("TThreadPool");
}
};
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "Default")
{
// Perform the test
REQUIRE(thePool->GetThreads() == 0);
REQUIRE(thePool->GetMinThreads() == 1);
REQUIRE(thePool->GetMaxThreads() != 0);
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "IsPaused")
{
// Perform the test
REQUIRE(!thePool->IsPaused());
thePool->Pause();
REQUIRE(thePool->IsPaused());
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "PauseResume")
{
// Perform the test
REQUIRE(!thePool->IsPaused());
thePool->Pause();
REQUIRE(thePool->IsPaused());
thePool->Resume();
REQUIRE(!thePool->IsPaused());
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "AddFunction")
{
// Perform the test
NSemaphore theSemaphore;
thePool->Add(
[&]()
{
theSemaphore.Signal();
});
REQUIRE(theSemaphore.Wait());
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "AddTask")
{
// Perform the test
NSemaphore theSemaphore;
auto theTask = std::make_shared<NThreadTask>(
[&]()
{
theSemaphore.Signal();
});
thePool->Add(theTask);
REQUIRE(theSemaphore.Wait());
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "GetMain")
{
// Perform the test
NThreadPool* mainPool = NThreadPool::GetMain();
REQUIRE(mainPool != nullptr);
REQUIRE(mainPool != thePool.get());
}
| 24.162162 | 79 | 0.521477 | refnum |
c0261a7fc43991509d789e99d7efe01691644fe1 | 517 | hpp | C++ | include/mass.hpp | zyuchuan/krypton | 449f39563ccc79659e61af954bd550c89c33d35e | [
"MIT"
] | null | null | null | include/mass.hpp | zyuchuan/krypton | 449f39563ccc79659e61af954bd550c89c33d35e | [
"MIT"
] | null | null | null | include/mass.hpp | zyuchuan/krypton | 449f39563ccc79659e61af954bd550c89c33d35e | [
"MIT"
] | null | null | null | //
// mass.hpp
// krypton
//
// Created by Jack Zou on 2018/4/7.
// Copyright © 2018年 jack.zou. All rights reserved.
//
#ifndef mass_h
#define mass_h
#include "core/common.hpp"
#include "core/quantity.hpp"
BEGIN_KR_NAMESPACE
template<class T> using microgram = quantity<T, mass, std::micro>;
template<class T> using gram = quantity<T, mass>;
template<class T> using kilogram = quantity<T, mass, std::kilo>;
template<class T> using ton = quantity<T, mass, std::mega>;
END_KR_NAMESPACE
#endif /* mass_h */
| 20.68 | 66 | 0.698259 | zyuchuan |
c0267365170fc4d17d96fe32f56d947acd899bd4 | 1,760 | cpp | C++ | PS_Fgen_FW/UI_Lib/Controls/ButtonControl.cpp | M1S2/PowerSupplySigGen | f2d352d9c24db985327d0286db58c6938da2507e | [
"MIT"
] | null | null | null | PS_Fgen_FW/UI_Lib/Controls/ButtonControl.cpp | M1S2/PowerSupplySigGen | f2d352d9c24db985327d0286db58c6938da2507e | [
"MIT"
] | 24 | 2020-11-10T13:03:05.000Z | 2021-05-12T16:26:02.000Z | PS_Fgen_FW/UI_Lib/Controls/ButtonControl.cpp | M1S2/PowerSupplySigGen | f2d352d9c24db985327d0286db58c6938da2507e | [
"MIT"
] | 1 | 2021-06-25T12:26:36.000Z | 2021-06-25T12:26:36.000Z | /*
* ButtonControl.cpp
* Created: 31.03.2021 20:42:49
* Author: Markus Scheich
*/
#include "ButtonControl.h"
#include <string.h>
template <int StringLength>
ButtonControl<StringLength>::ButtonControl(unsigned char locX, unsigned char locY, unsigned char width, unsigned char height, const char* buttonText, void* controlContext, void(*onClick)(void* controlContext)) : UIElement(locX, locY, UI_CONTROL)
{
Width = width;
Height = height;
strncpy(_buttonText, buttonText, StringLength); // Copy a maximum number of StringLength characters to the _buttonText buffer. If text is shorter, the array is zero padded.
_buttonText[StringLength - 1] = '\0'; // The _buttonText buffer must contain at least one termination character ('\0') at the end to protect from overflow.
_controlContext = controlContext;
_onClick = onClick;
}
template <int StringLength>
void ButtonControl<StringLength>::Draw(u8g_t *u8g, bool isFirstPage)
{
if (Visible)
{
u8g_DrawHLine(u8g, LocX - 1, LocY - 1, 3); // Upper left corner
u8g_DrawVLine(u8g, LocX - 1, LocY - 1, 3);
u8g_DrawHLine(u8g, LocX + Width - 2, LocY - 1, 3); // Upper right corner
u8g_DrawVLine(u8g, LocX + Width, LocY - 1, 3);
u8g_DrawHLine(u8g, LocX - 1, LocY + Height, 3); // Lower left corner
u8g_DrawVLine(u8g, LocX - 1, LocY + Height - 2, 3);
u8g_DrawHLine(u8g, LocX + Width - 2, LocY + Height, 3); // Lower right corner
u8g_DrawVLine(u8g, LocX + Width, LocY + Height - 2, 3);
u8g_DrawStr(u8g, LocX, LocY, _buttonText);
}
}
template <int StringLength>
bool ButtonControl<StringLength>::KeyInput(Keys_t key)
{
switch (key)
{
case KEYOK:
if (_onClick != NULL) { _onClick(_controlContext); return true; }
else { return false; }
default:
return false;
}
} | 35.918367 | 245 | 0.703977 | M1S2 |
c02ba756765a754fbfc21525f6ad0aeece3c8c2c | 11,092 | cpp | C++ | gecode/int/var-imp/int.cpp | SaGagnon/gecode-5.5.0-cbs | e871b320a9b2031423bb0fa452b1a5c09641a041 | [
"MIT-feh"
] | null | null | null | gecode/int/var-imp/int.cpp | SaGagnon/gecode-5.5.0-cbs | e871b320a9b2031423bb0fa452b1a5c09641a041 | [
"MIT-feh"
] | null | null | null | gecode/int/var-imp/int.cpp | SaGagnon/gecode-5.5.0-cbs | e871b320a9b2031423bb0fa452b1a5c09641a041 | [
"MIT-feh"
] | null | null | null | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2002
*
* Last modified:
* $Date: 2017-02-21 06:45:56 +0100 (Tue, 21 Feb 2017) $ by $Author: schulte $
* $Revision: 15465 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.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 <gecode/int.hh>
namespace Gecode { namespace Int {
forceinline bool
IntVarImp::closer_min(int n) const {
unsigned int l = static_cast<unsigned int>(n - dom.min());
unsigned int r = static_cast<unsigned int>(dom.max() - n);
return l < r;
}
int
IntVarImp::med(void) const {
// Computes the median
if (fst() == NULL)
return (dom.min()+dom.max())/2 - ((dom.min()+dom.max())%2 < 0 ? 1 : 0);
unsigned int i = size() / 2;
if (size() % 2 == 0)
i--;
const RangeList* p = NULL;
const RangeList* c = fst();
while (i >= c->width()) {
i -= c->width();
const RangeList* n=c->next(p); p=c; c=n;
}
return c->min() + static_cast<int>(i);
}
bool
IntVarImp::in_full(int m) const {
if (closer_min(m)) {
const RangeList* p = NULL;
const RangeList* c = fst();
while (m > c->max()) {
const RangeList* n=c->next(p); p=c; c=n;
}
return (m >= c->min());
} else {
const RangeList* n = NULL;
const RangeList* c = lst();
while (m < c->min()) {
const RangeList* p=c->prev(n); n=c; c=p;
}
return (m <= c->max());
}
}
/*
* "Standard" tell operations
*
*/
ModEvent
IntVarImp::lq_full(Space& home, int m) {
assert((m >= dom.min()) && (m <= dom.max()));
IntDelta d(m+1,dom.max());
ModEvent me = ME_INT_BND;
if (range()) { // Is already range...
dom.max(m);
if (assigned()) me = ME_INT_VAL;
} else if (m < fst()->next(NULL)->min()) { // Becomes range...
dom.max(std::min(m,fst()->max()));
fst()->dispose(home,NULL,lst());
fst(NULL); holes = 0;
if (assigned()) me = ME_INT_VAL;
} else { // Stays non-range...
RangeList* n = NULL;
RangeList* c = lst();
unsigned int h = 0;
while (m < c->min()) {
RangeList* p = c->prev(n); c->fix(n);
h += (c->min() - p->max() - 1);
n=c; c=p;
}
holes -= h;
int max_c = std::min(m,c->max());
dom.max(max_c); c->max(max_c);
if (c != lst()) {
n->dispose(home,lst());
c->next(n,NULL); lst(c);
}
}
return notify(home,me,d);
}
ModEvent
IntVarImp::gq_full(Space& home, int m) {
assert((m >= dom.min()) && (m <= dom.max()));
IntDelta d(dom.min(),m-1);
ModEvent me = ME_INT_BND;
if (range()) { // Is already range...
dom.min(m);
if (assigned()) me = ME_INT_VAL;
} else if (m > lst()->prev(NULL)->max()) { // Becomes range...
dom.min(std::max(m,lst()->min()));
fst()->dispose(home,NULL,lst());
fst(NULL); holes = 0;
if (assigned()) me = ME_INT_VAL;
} else { // Stays non-range...
RangeList* p = NULL;
RangeList* c = fst();
unsigned int h = 0;
while (m > c->max()) {
RangeList* n = c->next(p); c->fix(n);
h += (n->min() - c->max() - 1);
p=c; c=n;
}
holes -= h;
int min_c = std::max(m,c->min());
dom.min(min_c); c->min(min_c);
if (c != fst()) {
fst()->dispose(home,p);
c->prev(p,NULL); fst(c);
}
}
return notify(home,me,d);
}
ModEvent
IntVarImp::eq_full(Space& home, int m) {
dom.min(m); dom.max(m);
if (!range()) {
bool failed = false;
RangeList* p = NULL;
RangeList* c = fst();
while (m > c->max()) {
RangeList* n=c->next(p); c->fix(n); p=c; c=n;
}
if (m < c->min())
failed = true;
while (c != NULL) {
RangeList* n=c->next(p); c->fix(n); p=c; c=n;
}
assert(p == lst());
fst()->dispose(home,p);
fst(NULL); holes = 0;
if (failed)
return fail(home);
}
IntDelta d;
return notify(home,ME_INT_VAL,d);
}
ModEvent
IntVarImp::nq_full(Space& home, int m) {
assert(!((m < dom.min()) || (m > dom.max())));
ModEvent me = ME_INT_DOM;
if (range()) {
if ((m == dom.min()) && (m == dom.max()))
return fail(home);
if (m == dom.min()) {
dom.min(m+1);
me = assigned() ? ME_INT_VAL : ME_INT_BND;
} else if (m == dom.max()) {
dom.max(m-1);
me = assigned() ? ME_INT_VAL : ME_INT_BND;
} else {
RangeList* f = new (home) RangeList(dom.min(),m-1);
RangeList* l = new (home) RangeList(m+1,dom.max());
f->prevnext(NULL,l);
l->prevnext(f,NULL);
fst(f); lst(l); holes = 1;
}
} else if (m < fst()->next(NULL)->min()) { // Concerns the first range...
int f_max = fst()->max();
if (m > f_max)
return ME_INT_NONE;
int f_min = dom.min();
if ((m == f_min) && (m == f_max)) {
RangeList* f_next = fst()->next(NULL);
dom.min(f_next->min());
if (f_next == lst()) { // Turns into range
// Works as at the ends there are only NULL pointers
fst()->dispose(home,f_next);
fst(NULL); holes = 0;
me = assigned() ? ME_INT_VAL : ME_INT_BND;
} else { // Remains non-range
f_next->prev(fst(),NULL);
fst()->dispose(home); fst(f_next);
holes -= dom.min() - f_min - 1;
me = ME_INT_BND;
}
} else if (m == f_min) {
dom.min(m+1); fst()->min(m+1);
me = ME_INT_BND;
} else if (m == f_max) {
fst()->max(m-1); holes += 1;
} else {
// Create new hole
RangeList* f = new (home) RangeList(f_min,m-1);
f->prevnext(NULL,fst());
fst()->min(m+1); fst()->prev(NULL,f);
fst(f); holes += 1;
}
} else if (m > lst()->prev(NULL)->max()) { // Concerns the last range...
int l_min = lst()->min();
if (m < l_min)
return ME_INT_NONE;
int l_max = dom.max();
if ((m == l_min) && (m == l_max)) {
RangeList* l_prev = lst()->prev(NULL);
dom.max(l_prev->max());
if (l_prev == fst()) {
// Turns into range
l_prev->dispose(home,lst());
fst(NULL); holes = 0;
me = assigned() ? ME_INT_VAL : ME_INT_BND;
} else { // Remains non-range
l_prev->next(lst(),NULL);
lst()->dispose(home); lst(l_prev);
holes -= l_max - dom.max() - 1;
me = ME_INT_BND;
}
} else if (m == l_max) {
dom.max(m-1); lst()->max(m-1);
me = ME_INT_BND;
} else if (m == l_min) {
lst()->min(m+1); holes += 1;
} else { // Create new hole
RangeList* l = new (home) RangeList(m+1,l_max);
l->prevnext(lst(),NULL);
lst()->max(m-1); lst()->next(NULL,l);
lst(l); holes += 1;
}
} else { // Concerns element in the middle of the list of ranges
RangeList* p;
RangeList* c;
RangeList* n;
if (closer_min(m)) {
assert(m > fst()->max());
p = NULL;
c = fst();
do {
n=c->next(p); p=c; c=n;
} while (m > c->max());
if (m < c->min())
return ME_INT_NONE;
n=c->next(p);
} else {
assert(m < lst()->min());
n = NULL;
c = lst();
do {
p=c->prev(n); n=c; c=p;
} while (m < c->min());
if (m > c->max())
return ME_INT_NONE;
p=c->prev(n);
}
assert((fst() != c) && (lst() != c));
assert((m >= c->min()) && (m <= c->max()));
holes += 1;
int c_min = c->min();
int c_max = c->max();
if ((c_min == m) && (c_max == m)) {
c->dispose(home);
p->next(c,n); n->prev(c,p);
} else if (c_min == m) {
c->min(m+1);
} else {
c->max(m-1);
if (c_max != m) {
RangeList* l = new (home) RangeList(m+1,c_max);
l->prevnext(c,n);
c->next(n,l);
n->prev(c,l);
}
}
}
IntDelta d(m,m);
return notify(home,me,d);
}
/*
* Copying variables
*
*/
forceinline
IntVarImp::IntVarImp(Space& home, bool share, IntVarImp& x)
: IntVarImpBase(home,share,x), dom(x.dom.min(),x.dom.max()) {
holes = x.holes;
if (holes) {
int m = 1;
// Compute length
{
RangeList* s_p = x.fst();
RangeList* s_c = s_p->next(NULL);
do {
m++;
RangeList* s_n = s_c->next(s_p); s_p=s_c; s_c=s_n;
} while (s_c != NULL);
}
RangeList* d_c = home.alloc<RangeList>(m);
fst(d_c); lst(d_c+m-1);
d_c->min(x.fst()->min());
d_c->max(x.fst()->max());
d_c->prevnext(NULL,NULL);
RangeList* s_p = x.fst();
RangeList* s_c = s_p->next(NULL);
do {
RangeList* d_n = d_c + 1;
d_c->next(NULL,d_n);
d_n->prevnext(d_c,NULL);
d_n->min(s_c->min()); d_n->max(s_c->max());
d_c = d_n;
RangeList* s_n=s_c->next(s_p); s_p=s_c; s_c=s_n;
} while (s_c != NULL);
d_c->next(NULL,NULL);
} else {
fst(NULL);
}
}
IntVarImp*
IntVarImp::perform_copy(Space& home, bool share) {
return new (home) IntVarImp(home,share,*this);
}
/*
* Dependencies
*
*/
void
IntVarImp::subscribe(Space& home, Propagator& p, PropCond pc,
bool schedule) {
IntVarImpBase::subscribe(home,p,pc,dom.min()==dom.max(),schedule);
}
void
IntVarImp::reschedule(Space& home, Propagator& p, PropCond pc) {
IntVarImpBase::reschedule(home,p,pc,dom.min()==dom.max());
}
void
IntVarImp::subscribe(Space& home, Advisor& a, bool fail) {
IntVarImpBase::subscribe(home,a,dom.min()==dom.max(),fail);
}
}}
// STATISTICS: int-var
| 29.036649 | 82 | 0.508745 | SaGagnon |
c031ee5e139bc7dcb84faf06b0eff6bfcbdb76a4 | 545 | cpp | C++ | STEM4U/Utility.cpp | Libraries4U/STEM4U | 41472ce21420ff5bcf69577efefd924cf1e7c2cf | [
"Apache-2.0"
] | null | null | null | STEM4U/Utility.cpp | Libraries4U/STEM4U | 41472ce21420ff5bcf69577efefd924cf1e7c2cf | [
"Apache-2.0"
] | null | null | null | STEM4U/Utility.cpp | Libraries4U/STEM4U | 41472ce21420ff5bcf69577efefd924cf1e7c2cf | [
"Apache-2.0"
] | null | null | null | #include <Core/Core.h>
#include <Functions4U/Functions4U.h>
#include <Eigen/Eigen.h>
#include "Utility.h"
namespace Upp {
using namespace Eigen;
double R2(const VectorXd &serie, const VectorXd &serie0, double mean) {
if (IsNull(mean))
mean = serie.mean();
double sse = 0, sst = 0;
for (Eigen::Index i = 0; i < serie.size(); ++i) {
double y = serie(i);
double err = y - serie0(i);
sse += err*err;
double d = y - mean;
sst += d*d;
}
if (sst < 1E-50 || sse > sst)
return 0;
return 1 - sse/sst;
}
} | 20.185185 | 72 | 0.588991 | Libraries4U |
c0333f3235d1a372eee2aaa2d13fa8058ceccc4e | 8,121 | cpp | C++ | src/autorotate-iio.cpp | kode54/wayfire-plugins-extra | 11bbf1c5468138dea47ef162ac65d4a93914306b | [
"MIT"
] | null | null | null | src/autorotate-iio.cpp | kode54/wayfire-plugins-extra | 11bbf1c5468138dea47ef162ac65d4a93914306b | [
"MIT"
] | null | null | null | src/autorotate-iio.cpp | kode54/wayfire-plugins-extra | 11bbf1c5468138dea47ef162ac65d4a93914306b | [
"MIT"
] | null | null | null | #include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/render-manager.hpp>
#include <wayfire/input-device.hpp>
#include <wayfire/output-layout.hpp>
#include <wayfire/core.hpp>
#include <wayfire/util/log.hpp>
#include <giomm/dbusconnection.h>
#include <giomm/dbuswatchname.h>
#include <giomm/dbusproxy.h>
#include <giomm/init.h>
#include <glibmm/main.h>
#include <glibmm/init.h>
#include <map>
extern "C"
{
#include <wlr/types/wlr_cursor.h>
#include <wlr/types/wlr_seat.h>
}
using namespace Gio;
class WayfireAutorotateIIO : public wf::plugin_interface_t
{
/* Tries to detect whether autorotate is enabled for the current output.
* Currently it is enabled only for integrated panels */
bool is_autorotate_enabled()
{
static const std::string integrated_connectors[] = {
"eDP",
"LVDS",
"DSI",
};
/* In wlroots, the output name is based on the connector */
auto output_connector = std::string(output->handle->name);
for (auto iconnector : integrated_connectors)
{
if (output_connector.find(iconnector) != iconnector.npos)
{
return true;
}
}
return false;
}
wf::signal_callback_t on_input_devices_changed = [=] (void*)
{
if (!is_autorotate_enabled())
{
return;
}
auto devices = wf::get_core().get_input_devices();
for (auto& dev : devices)
{
if (dev->get_wlr_handle()->type == WLR_INPUT_DEVICE_TOUCH)
{
auto cursor = wf::get_core().get_wlr_cursor();
wlr_cursor_map_input_to_output(cursor, dev->get_wlr_handle(),
output->handle);
}
}
};
wf::option_wrapper_t<wf::activatorbinding_t>
rotate_up_opt{"autorotate-iio/rotate_up"},
rotate_left_opt{"autorotate-iio/rotate_left"},
rotate_down_opt{"autorotate-iio/rotate_down"},
rotate_right_opt{"autorotate-iio/rotate_right"};
wf::option_wrapper_t<bool>
config_rotation_locked{"autorotate-iio/lock_rotation"};
guint watch_id;
wf::activator_callback on_rotate_left = [=] (wf::activator_source_t src, int32_t)
{
return on_rotate_binding(WL_OUTPUT_TRANSFORM_270);
};
wf::activator_callback on_rotate_right =
[=] (wf::activator_source_t src, int32_t)
{
return on_rotate_binding(WL_OUTPUT_TRANSFORM_90);
};
wf::activator_callback on_rotate_up = [=] (wf::activator_source_t src, int32_t)
{
return on_rotate_binding(WL_OUTPUT_TRANSFORM_NORMAL);
};
wf::activator_callback on_rotate_down = [=] (wf::activator_source_t src, int32_t)
{
return on_rotate_binding(WL_OUTPUT_TRANSFORM_180);
};
/* User-specified rotation via keybinding, -1 means not set */
int32_t user_rotation = -1;
/* Transform coming from the iio-sensors, -1 means not set */
int32_t sensor_transform = -1;
bool on_rotate_binding(int32_t target_rotation)
{
if (!output->can_activate_plugin(grab_interface))
{
return false;
}
/* If the user presses the same rotation binding twice, this means
* unlock the rotation. Otherwise, just use the new rotation. */
if (target_rotation == user_rotation)
{
user_rotation = -1;
} else
{
user_rotation = target_rotation;
}
return update_transform();
}
/** Calculate the transform based on user and sensor data, and apply it */
bool update_transform()
{
wl_output_transform transform_to_use;
if (user_rotation >= 0)
{
transform_to_use = (wl_output_transform)user_rotation;
} else if ((sensor_transform >= 0) && !config_rotation_locked)
{
transform_to_use = (wl_output_transform)sensor_transform;
} else
{
/* No user rotation set, and no sensor data */
return false;
}
auto configuration =
wf::get_core().output_layout->get_current_configuration();
if (configuration[output->handle].transform == transform_to_use)
{
return false;
}
configuration[output->handle].transform = transform_to_use;
wf::get_core().output_layout->apply_configuration(configuration);
return true;
}
wf::effect_hook_t on_frame = [=] ()
{
Glib::MainContext::get_default()->iteration(false);
};
Glib::RefPtr<Glib::MainLoop> loop;
public:
void init() override
{
output->add_activator(rotate_left_opt, &on_rotate_left);
output->add_activator(rotate_right_opt, &on_rotate_right);
output->add_activator(rotate_up_opt, &on_rotate_up);
output->add_activator(rotate_down_opt, &on_rotate_down);
on_input_devices_changed(nullptr);
wf::get_core().connect_signal("input-device-added",
&on_input_devices_changed);
init_iio_sensors();
}
void init_iio_sensors()
{
if (!is_autorotate_enabled())
{
return;
}
Glib::init();
Gio::init();
loop = Glib::MainLoop::create(true);
output->render->add_effect(&on_frame, wf::OUTPUT_EFFECT_PRE);
watch_id = DBus::watch_name(DBus::BUS_TYPE_SYSTEM, "net.hadess.SensorProxy",
sigc::mem_fun(this, &WayfireAutorotateIIO::on_iio_appeared),
sigc::mem_fun(this, &WayfireAutorotateIIO::on_iio_disappeared));
}
Glib::RefPtr<DBus::Proxy> iio_proxy;
void on_iio_appeared(const Glib::RefPtr<DBus::Connection>& conn,
Glib::ustring name, Glib::ustring owner)
{
LOGI("iio-sensors appeared, connecting ...");
iio_proxy = DBus::Proxy::create_sync(conn,
name, "/net/hadess/SensorProxy", "net.hadess.SensorProxy");
if (!iio_proxy)
{
LOGE("Failed to connect to iio-proxy.");
return;
}
iio_proxy->signal_properties_changed().connect_notify(
sigc::mem_fun(this, &WayfireAutorotateIIO::on_properties_changed));
iio_proxy->call_sync("ClaimAccelerometer");
}
void on_properties_changed(
const Gio::DBus::Proxy::MapChangedProperties& properties,
const std::vector<Glib::ustring>& invalidated)
{
update_orientation();
}
void update_orientation()
{
if (!iio_proxy)
{
return;
}
Glib::Variant<Glib::ustring> orientation;
iio_proxy->get_cached_property(orientation, "AccelerometerOrientation");
LOGI("IIO Accelerometer orientation: %s", orientation.get().c_str());
static const std::map<std::string, wl_output_transform> transform_by_name =
{
{"normal", WL_OUTPUT_TRANSFORM_NORMAL},
{"left-up", WL_OUTPUT_TRANSFORM_270},
{"right-up", WL_OUTPUT_TRANSFORM_90},
{"bottom-up", WL_OUTPUT_TRANSFORM_180},
};
if (transform_by_name.count(orientation.get()))
{
sensor_transform = transform_by_name.find(orientation.get())->second;
update_transform();
}
}
void on_iio_disappeared(const Glib::RefPtr<DBus::Connection>& conn,
Glib::ustring name)
{
LOGI("lost connection to iio-sensors.");
iio_proxy.reset();
}
void fini() override
{
output->rem_binding(&on_rotate_left);
output->rem_binding(&on_rotate_right);
output->rem_binding(&on_rotate_up);
output->rem_binding(&on_rotate_down);
wf::get_core().disconnect_signal("input-device-added",
&on_input_devices_changed);
/* If loop is NULL, autorotate was disabled for the current output */
if (loop)
{
iio_proxy.reset();
DBus::unwatch_name(watch_id);
loop->quit();
output->render->rem_effect(&on_frame);
}
}
};
DECLARE_WAYFIRE_PLUGIN(WayfireAutorotateIIO);
| 29.747253 | 85 | 0.617165 | kode54 |
c033d3df203f58b8ac95b6d0c49d38a653cffdb1 | 1,022 | hpp | C++ | third-party/sprawl/include/sprawl/common/errors.hpp | 3Jade/Ocean | a17bbd6ece6ba0a7539c933cadfc7faad564f9d2 | [
"MIT"
] | null | null | null | third-party/sprawl/include/sprawl/common/errors.hpp | 3Jade/Ocean | a17bbd6ece6ba0a7539c933cadfc7faad564f9d2 | [
"MIT"
] | null | null | null | third-party/sprawl/include/sprawl/common/errors.hpp | 3Jade/Ocean | a17bbd6ece6ba0a7539c933cadfc7faad564f9d2 | [
"MIT"
] | null | null | null | #pragma once
#if defined(SPRAWL_NO_EXCEPTIONS)
# define SPRAWL_EXCEPTIONS_ENABLED 0
#elif defined(__clang__)
# define SPRAWL_EXCEPTIONS_ENABLED __has_feature(cxx_exceptions)
#elif defined(__GNUC__)
# ifdef __EXCEPTIONS
# define SPRAWL_EXCEPTIONS_ENABLED 1
# else
# define SPRAWL_EXCEPTIONS_ENABLED 0
# endif
#elif defined(_WIN32)
# ifdef _CPPUNWIND
# define SPRAWL_EXCEPTIONS_ENABLED 1
# else
# define SPRAWL_EXCEPTIONS_ENABLED 0
# endif
#else
# define SPRAWL_EXCEPTIONS_ENABLED 0
#endif
#if SPRAWL_EXCEPTIONS_ENABLED
# define SPRAWL_THROW_EXCEPTION(exception, returnValue) throw exception
#else
namespace sprawl { void throw_exception(std::exception const& exception); }
# define SPRAWL_THROW_EXCEPTION(exception, returnValue) sprawl::throw_exception(exception); return returnValue
#endif
#define SPRAWL_ABORT_MSG(msg, ...) fprintf(stderr, msg, ## __VA_ARGS__); fputs("\n", stderr); abort();
#define SPRAWL_UNIMPLEMENTED_BASE_CLASS_METHOD SPRAWL_ABORT_MSG("This method called is not implemented on this object")
| 30.969697 | 119 | 0.812133 | 3Jade |
c034722ddeff7aed7bd73ff0853f2419ccb04701 | 4,340 | cxx | C++ | lio/PMLIO.cxx | kanait/hsphparam | 00158f81d00e496fed469779bf73094495ac8671 | [
"MIT"
] | 1 | 2021-08-23T06:55:22.000Z | 2021-08-23T06:55:22.000Z | lio/PMLIO.cxx | kanait/hsphparam | 00158f81d00e496fed469779bf73094495ac8671 | [
"MIT"
] | null | null | null | lio/PMLIO.cxx | kanait/hsphparam | 00158f81d00e496fed469779bf73094495ac8671 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////
//
// $Id: PMLIO.cxx 2021/06/05 13:58:48 kanai Exp $
//
// Copyright (c) 2021 Takashi Kanai
// Released under the MIT license
//
////////////////////////////////////////////////////////////////////
#include "envDep.h"
#include <iostream>
#include <fstream>
#include <string>
#include "MeshL.hxx"
#include "VertexL.hxx"
#include "FaceL.hxx"
#include "VSplitL.hxx"
#include "PMLIO.hxx"
// open ppd file using STL fstream
bool PMLIO::outputToFile( const char * const pmfile )
{
std::ofstream ofs( pmfile ); if ( !ofs ) return false;
int vn = mesh().vertices().size() + vsplist().size() * 2;
int fn = mesh().faces().size() + vsplist().size() * 2;
ofs << "header" << std::endl;
ofs << "\tsolid\t1" << std::endl;
ofs << "\tpart\t1" << std::endl;
ofs << "\tvertex\t" << mesh().vertices().size() << std::endl;
ofs << "\tface\t" << mesh().faces().size() << std::endl;
ofs << "\tfnode\t" << mesh().faces().size() * 3 << std::endl;
ofs << "\tvsplit\t " << vsplist().size() << std::endl;
ofs << "\tvall\t " << vn << std::endl;
ofs << "\tfall\t " << fn << std::endl;
ofs << "end" << std::endl;
std::vector<int> v_id_( orgVtSize() );
std::vector<int> f_id_( orgFcSize() );
// solid, part
ofs << "solid" << std::endl;
ofs << "\t1\t/p 1 1 ";
if ( mesh().vertices().size() ) ofs << "/v 1 " << mesh().vertices().size() << " ";
if ( mesh().faces().size() ) ofs << "/f 1 " << mesh().faces().size() << " ";
ofs << std::endl;
ofs << "end" << std::endl;
ofs << "part" << std::endl;
if ( mesh().faces().size() ) ofs << "\t1\t/f 1 " << mesh().faces().size() << std::endl;
ofs << "end" << std::endl;
int v_sid = 1;
int vid = 1;
if ( vn )
{
ofs << "vall" << std::endl;
foreach ( std::list<VertexL*>, mesh().vertices(), vt )
{
// cout << "vt (in vertex) " << (*vt)->id() << endl;
Point3d p( (*vt)->point() );
if ( mesh().isNormalized() )
{
p.scale( mesh().maxLength() );
p += mesh().center();
}
ofs << "\t" << v_sid << "\t"
<< p.x << " "
<< p.y << " "
<< p.z << std::endl;
v_id_[ (*vt)->id() ] = vid;
++vid;
++v_sid;
}
for ( int i = vsplist().size()-1 ; i >= 0; --i )
{
Point3d p( vspl(i)->pos(0) );
if ( mesh().isNormalized() )
{
p.scale( mesh().maxLength() );
p += mesh().center();
}
// cout << "i = " << i << endl;
// cout << "vt = " << vspl(i)->id() << endl;
ofs << "\t" << v_sid << "\t"
<< p.x << " "
<< p.y << " "
<< p.z << std::endl;
++v_sid;
p.set( vspl(i)->pos(1) );
if ( mesh().isNormalized() )
{
p.scale( mesh().maxLength() );
p += mesh().center();
}
ofs << "\t" << v_sid << "\t"
<< p.x << " "
<< p.y << " "
<< p.z << std::endl;
++v_sid;
}
ofs << "end" << std::endl;
}
int id = 1;
if ( mesh().faces().size() )
{
ofs << "face" << std::endl;
foreach ( std::list<FaceL*>, mesh().faces(), fc )
{
ofs << "\t" << id << "\t";
foreach ( std::list<HalfedgeL*>, (*fc)->halfedges(), he )
{
ofs << v_id_[ (*he)->vertex()->id() ];
ofs << " ";
}
ofs << std::endl;
f_id_[ (*fc)->id() ] = id;
++id;
}
ofs << "end" << std::endl;
}
if ( vsplist().size() )
{
ofs << "vsplit" << std::endl;
int vspl_id = 1;
for ( int i = vsplist().size()-1 ; i >= 0; --i )
{
//cout << "vt (in vsplit) " << vspl(i)->vt() << endl;
f_id_[ vspl(i)->fl() ] = id++;
f_id_[ vspl(i)->fr() ] = id++;
ofs << "\t" << vspl_id << "\t"
<< v_id_[ vspl(i)->vt() ] << " /f "
<< f_id_[ vspl(i)->fn(0) ] << " "
<< f_id_[ vspl(i)->fn(1) ] << " "
<< f_id_[ vspl(i)->fn(2) ] << " "
<< f_id_[ vspl(i)->fn(3) ] << std::endl;
v_id_[ vspl(i)->vn(0) ] = vid; vid++;
v_id_[ vspl(i)->vn(1) ] = vid; vid++;
++vspl_id;
}
ofs << "end" << std::endl;
}
ofs.close();
return true;
}
| 26.956522 | 89 | 0.400691 | kanait |
c03736e763431b1e68749adf99ca97bf8629c554 | 33,341 | cpp | C++ | src/CompressedAssemblyGraph.cpp | AustinHartman/shasta | 105b8e85e272247f72ced59005c88879631931c0 | [
"BSD-3-Clause"
] | null | null | null | src/CompressedAssemblyGraph.cpp | AustinHartman/shasta | 105b8e85e272247f72ced59005c88879631931c0 | [
"BSD-3-Clause"
] | null | null | null | src/CompressedAssemblyGraph.cpp | AustinHartman/shasta | 105b8e85e272247f72ced59005c88879631931c0 | [
"BSD-3-Clause"
] | null | null | null | // Shasta.
#include "CompressedAssemblyGraph.hpp"
#include "Assembler.hpp"
#include "deduplicate.hpp"
#include "findLinearChains.hpp"
#include "html.hpp"
#include "platformDependent.hpp"
#include "runCommandWithTimeout.hpp"
#include "subgraph.hpp"
using namespace shasta;
// Boost libraries.
#include <boost/algorithm/string.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
// Standard library.
#include "fstream.hpp"
#include "vector.hpp"
// Create the CompressedAssemblyGraph from the AssemblyGraph.
CompressedAssemblyGraph::CompressedAssemblyGraph(
const Assembler& assembler)
{
CompressedAssemblyGraph& graph = *this;
const AssemblyGraph& assemblyGraph = *(assembler.assemblyGraphPointer);
cout << "The assembly graph has " << assemblyGraph.vertices.size() <<
" vertices and " << assemblyGraph.edges.size() << " edges." << endl;
// Create a vertex for each vertex of the assembly graph.
vector<vertex_descriptor> vertexTable;
createVertices(assemblyGraph.vertices.size(), vertexTable);
// Create an edge for each set of parallel edges of the assembly graph.
createEdges(assemblyGraph, vertexTable);
removeReverseBubbles();
// Merge linear chains of edges.
mergeLinearChains();
cout << "The compressed assembly graph has " <<
num_vertices(graph) <<
" vertices and " << num_edges(graph) << " edges." << endl;
// Assign an id to each edge.
assignEdgeIds();
// Fill in the assembly graph edges that go into each
// edge of the compressed assembly graph.
fillContributingEdges(assemblyGraph);
// Fill in minimum and maximum marker counts for each edge.
fillMarkerCounts(assemblyGraph);
// Find the oriented reads that appear in marker graph vertices
// internal to each edge of the compressed assembly graph.
findOrientedReads(assembler);
fillOrientedReadTable(assembler);
// Find edges that have at least one common oriented read
// which each edge.
findRelatedEdges();
}
// Create a vertex for each vertex of the assembly graph.
void CompressedAssemblyGraph::createVertices(
uint64_t vertexCount,
vector<vertex_descriptor>& vertexTable)
{
CompressedAssemblyGraph& graph = *this;
vertexTable.resize(vertexCount, null_vertex());
for(VertexId vertexId=0; vertexId<vertexCount; vertexId++) {
const vertex_descriptor v = add_vertex(CompressedAssemblyGraphVertex(vertexId), graph);
vertexTable[vertexId] = v;
}
}
// Create an edge for each set of parallel edges of the assembly graph.
void CompressedAssemblyGraph::createEdges(
const AssemblyGraph& assemblyGraph,
const vector<vertex_descriptor>& vertexTable)
{
CompressedAssemblyGraph& graph = *this;
// Loop over assembly graph edges.
for(const AssemblyGraph::Edge& edge: assemblyGraph.edges) {
const vertex_descriptor v0 = vertexTable[edge.source];
const vertex_descriptor v1 = vertexTable[edge.target];
// Do we already have an edge between these two vertices?
bool edgeExists = false;
tie(ignore, edgeExists) = boost::edge(v0, v1, graph);
// If we don't already have an edge between these two vertices, add it.
// We only create one of each set of parallel edges.
if(not edgeExists) {
edge_descriptor e;
bool edgeWasAdded = false;
tie(e, edgeWasAdded) = add_edge(v0, v1, graph);
SHASTA_ASSERT(edgeWasAdded);
// Store the assembly graph vertices.
CompressedAssemblyGraphEdge& edge = graph[e];
edge.vertices.push_back(graph[v0].vertexId);
edge.vertices.push_back(graph[v1].vertexId);
}
}
}
// Remove back edges that create reverse bubbles.
// A reverse bubble is defined by two vertices v0 and v1 such that:
// - Edge v0->v1 exists.
// - Edge v1->v0 exists.
// - Out-degree(v0) = 1
// - In-degree(v1) = 1.
// Under these conditions, we remove vertex v1->v0.
void CompressedAssemblyGraph::removeReverseBubbles()
{
CompressedAssemblyGraph& graph = *this;
// Vector to contain the edges that we wil remove.
vector<edge_descriptor> edgesToBeRemoved;
// Try all edges.
BGL_FORALL_EDGES(e01, graph, CompressedAssemblyGraph) {
// Check that v0 has out-degree 1.
const vertex_descriptor v0 = source(e01, graph);
if(out_degree(v0, graph) != 1) {
continue;
}
// Check that v1 has in-degree 1.
const vertex_descriptor v1 = target(e01, graph);
if(in_degree(v1, graph) != 1) {
continue;
}
// Look for edges v1->v0.
// Try all edges v1->v2. Fkag to be renmoved if v2=v0.
BGL_FORALL_OUTEDGES(v1, e12, graph, CompressedAssemblyGraph) {
const vertex_descriptor v2 = target(e12, graph);
if(v2 == v0) {
edgesToBeRemoved.push_back(e12);
}
}
}
// Remove the edges we flagged.
deduplicate(edgesToBeRemoved);
for(const edge_descriptor e: edgesToBeRemoved) {
boost::remove_edge(e, graph);
}
}
// Merge linear chains of edges.
void CompressedAssemblyGraph::mergeLinearChains()
{
CompressedAssemblyGraph& graph = *this;
// Find linear chains.
vector< std::list<edge_descriptor> > chains;
findLinearChains(graph, chains);
// Replace each chain with a single edge.
for(const std::list<edge_descriptor>& chain: chains) {
// If the chain has length 1, leave it alone.
if(chain.size() == 1) {
continue;
}
// Add the new edge.
const vertex_descriptor v0 = source(chain.front(), graph);
const vertex_descriptor v1 = target(chain.back(), graph);
edge_descriptor eNew;
bool edgeWasAdded = false;
tie(eNew, edgeWasAdded) = add_edge(v0, v1, graph);
SHASTA_ASSERT(edgeWasAdded);
CompressedAssemblyGraphEdge& newEdge = graph[eNew];
// Fill in the assembly graph vertices corresponding to this new edge.
newEdge.vertices.push_back(graph[v0].vertexId);
for(const edge_descriptor e: chain) {
const vertex_descriptor v = target(e, graph);
newEdge.vertices.push_back(graph[v].vertexId);
}
// Remove the edges of the chain.
// We will remove the vertices later.
for(const edge_descriptor e: chain) {
boost::remove_edge(e, graph);
}
}
// Remove the vertices that have become isolated.
vector<vertex_descriptor> verticesToBeRemoved;
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
if(in_degree(v, graph) == 0 and out_degree(v, graph) == 0) {
verticesToBeRemoved.push_back(v);
}
}
for(const vertex_descriptor v: verticesToBeRemoved) {
remove_vertex(v, graph);
}
}
// Assign an id to each edge.
void CompressedAssemblyGraph::assignEdgeIds()
{
CompressedAssemblyGraph& graph = *this;
uint64_t edgeId = 0;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
graph[e].id = edgeId++;
}
}
// Fill in the assembly graph edges that go into each
// edge of the compressed assembly graph.
void CompressedAssemblyGraph::fillContributingEdges(
const AssemblyGraph& assemblyGraph)
{
CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
CompressedAssemblyGraphEdge& edge = graph[e];
edge.edges.resize(edge.vertices.size() - 1);
for(uint64_t i=0; i<edge.edges.size(); i++) {
const VertexId vertexId0 = edge.vertices[i];
const VertexId vertexId1 = edge.vertices[i+1];
const span<const EdgeId> edges0 = assemblyGraph.edgesBySource[vertexId0];
for(const EdgeId edge01: edges0) {
if(assemblyGraph.edges[edge01].target == vertexId1) {
edge.edges[i].push_back(edge01);
}
}
}
}
}
// Find the oriented reads that appear in marker graph vertices
// internal to each edge of the compressed assembly graph.
void CompressedAssemblyGraph::findOrientedReads(
const Assembler& assembler)
{
CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
graph[e].findOrientedReads(assembler);
}
// Fill in the oriented read table, which tells us
// which edges each read appears in.
orientedReadTable.resize(2 * assembler.getReads().readCount());
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
for(const OrientedReadId orientedReadId: graph[e].orientedReadIds) {
orientedReadTable[orientedReadId.getValue()].push_back(e);
}
}
}
void CompressedAssemblyGraph::fillOrientedReadTable(
const Assembler& assembler)
{
CompressedAssemblyGraph& graph = *this;
orientedReadTable.clear();
orientedReadTable.resize(2 * assembler.getReads().readCount());
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
for(const OrientedReadId orientedReadId: graph[e].orientedReadIds) {
orientedReadTable[orientedReadId.getValue()].push_back(e);
}
}
}
// Find the oriented reads that appear in marker graph vertices
// internal to an edge of the compressed assembly graph.
void CompressedAssemblyGraphEdge::findOrientedReads(
const Assembler& assembler)
{
const AssemblyGraph& assemblyGraph = *assembler.assemblyGraphPointer;
// Loop over assembly graph edges.
for(const vector<AssemblyGraph::EdgeId>& edgesHere: edges) {
for(const AssemblyGraph::EdgeId assemblyGraphEdgeId: edgesHere) {
// Loop over marker graph edges corresponding to this
// assembly graph edge.
const span<const MarkerGraph::EdgeId> markerGraphEdgeIds =
assemblyGraph.edgeLists[assemblyGraphEdgeId];
for(const MarkerGraph::EdgeId markerGraphEdgeId: markerGraphEdgeIds) {
findOrientedReads(assembler, markerGraphEdgeId);
}
}
}
// Deduplicate oriented reads and count their occurrences.
deduplicateAndCount(orientedReadIds, orientedReadIdsFrequency);
}
// Append to orientedReadIds the oriented reads that
// appear in a given marker graph edge.
void CompressedAssemblyGraphEdge::findOrientedReads(
const Assembler& assembler,
const MarkerGraph::EdgeId& markerGraphEdgeId)
{
const span<const MarkerInterval> markerIntervals =
assembler.markerGraph.edgeMarkerIntervals[markerGraphEdgeId];
for(const MarkerInterval markerInterval: markerIntervals) {
orientedReadIds.push_back(markerInterval.orientedReadId);
}
}
// Find edges that have at least one common oriented read
// which each edge.
void CompressedAssemblyGraph::findRelatedEdges()
{
CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
findRelatedEdges(e);
}
}
void CompressedAssemblyGraph::findRelatedEdges(edge_descriptor e0)
{
CompressedAssemblyGraph& graph = *this;
CompressedAssemblyGraphEdge& edge0 = graph[e0];
for(const OrientedReadId orientedReadId: edge0.orientedReadIds) {
const vector<edge_descriptor>& edges = orientedReadTable[orientedReadId.getValue()];
for(const edge_descriptor e1: edges) {
if(e1 != e0) {
edge0.relatedEdges.push_back(e1);
}
}
}
deduplicate(edge0.relatedEdges);
edge0.relatedEdges.shrink_to_fit();
/*
cout << edge0.gfaId() << ":";
for(const edge_descriptor e1: edge0.relatedEdges) {
cout << " " << graph[e1].gfaId();
}
cout << endl;
*/
}
string CompressedAssemblyGraphEdge::gfaId() const
{
if(edges.size()==1 and edges.front().size()==1) {
// Return the one and only assembly graph edge associated with this
// compressed assembly graph edge.
return to_string(edges.front().front());
} else {
// Return the id of this compressed assembly graph edge,
// prefixed with "C".
return "C" + to_string(id);
}
}
// Return the edge with a given GFA id.
pair<CompressedAssemblyGraph::edge_descriptor, bool>
CompressedAssemblyGraph::getEdgeFromGfaId(
const string& s) const
{
const CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
if(graph[e].gfaId() == s) {
return make_pair(e, true);
}
}
return make_pair(edge_descriptor(), false);
}
uint64_t CompressedAssemblyGraph::maxPloidy() const
{
const CompressedAssemblyGraph& graph = *this;
uint64_t returnValue = 0;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
returnValue = max(returnValue, graph[e].maxPloidy());
}
return returnValue;
}
uint64_t CompressedAssemblyGraphEdge::maxPloidy() const
{
uint64_t returnValue = 0;
for(const auto& v: edges) {
returnValue = max(returnValue, uint64_t(v.size()));
}
return returnValue;
}
// GFA output (without sequence).
void CompressedAssemblyGraph::writeGfa(const string& fileName, double basesPerMarker) const
{
ofstream gfa(fileName);
writeGfa(gfa, basesPerMarker);
}
void CompressedAssemblyGraph::writeGfa(ostream& gfa, double basesPerMarker) const
{
const CompressedAssemblyGraph& graph = *this;
// Write the header line.
gfa << "H\tVN:Z:1.0\n";
// Write a segment record for each edge.
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
gfa <<
"S\t" <<
edge.gfaId() << "\t" <<
"*\t" <<
"LN:i:" << uint64_t(basesPerMarker * 0.5 *
double(edge.minMarkerCount + edge.maxMarkerCount)) <<
"\n";
}
// Write GFA links.
// For each vertex in the compressed assembly graph there is a link for
// each combination of in-edges and out-edges.
// Therefore each vertex generates a number of
// links equal to the product of its in-degree and out-degree.
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
BGL_FORALL_INEDGES(v, eIn, graph, CompressedAssemblyGraph) {
BGL_FORALL_OUTEDGES(v, eOut, graph, CompressedAssemblyGraph) {
gfa <<
"L\t" <<
graph[eIn].gfaId() << "\t" <<
"+\t" <<
graph[eOut].gfaId() << "\t" <<
"+\t" <<
"*\n";
}
}
}
}
void CompressedAssemblyGraph::writeCsv() const
{
writeCsvEdges();
writeCsvBubbleChains();
writeCsvOrientedReadsByEdge();
writeCsvOrientedReads();
}
void CompressedAssemblyGraph::writeCsvEdges() const
{
const CompressedAssemblyGraph& graph = *this;
ofstream csv("CompressedGraph-Edges.csv");
csv << "Id,GFA id,Source,Target,MinMarkerCount,MaxMarkerCount,OrientedReadsCount,RelatedEdgesCount,\n";
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
csv << edge.id << ",";
csv << edge.gfaId() << ",";
csv << graph[v0].vertexId << ",";
csv << graph[v1].vertexId << ",";
csv << edge.minMarkerCount << ",";
csv << edge.maxMarkerCount << ",";
csv << edge.orientedReadIds.size() << ",";
csv << edge.relatedEdges.size() << ",";
csv << "\n";
}
}
void CompressedAssemblyGraph::writeCsvOrientedReadsByEdge() const
{
const CompressedAssemblyGraph& graph = *this;
ofstream csv("CompressedGraph-OrientedReadsByEdge.csv");
csv << "Id,GFA id,OrientedRead,Frequency\n";
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
SHASTA_ASSERT(edge.orientedReadIds.size() == edge.orientedReadIdsFrequency.size());
for(uint64_t i=0; i<edge.orientedReadIds.size(); i++) {
const OrientedReadId orientedReadId = edge.orientedReadIds[i];
const uint64_t frequency = edge.orientedReadIdsFrequency[i];
csv << edge.id << ",";
csv << edge.gfaId() << ",";
csv << orientedReadId << ",";
csv << frequency << "\n";
}
}
}
void CompressedAssemblyGraph::writeCsvBubbleChains() const
{
const CompressedAssemblyGraph& graph = *this;
const uint64_t maxPloidy = graph.maxPloidy();
ofstream csv("CompressedGraph-BubbleChains.csv");
csv << "Id,GFA id,Position,";
for(uint64_t i=0; i<maxPloidy; i++) {
csv << "Edge" << i << ",";
}
csv << "\n";
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
for(uint64_t position=0; position<edge.edges.size(); position++) {
const vector<AssemblyGraph::EdgeId>& edgesAtPosition = edge.edges[position];
csv << edge.id << ",";
csv << edge.gfaId() << ",";
csv << position << ",";
for(const AssemblyGraph::EdgeId edgeId: edgesAtPosition) {
csv << edgeId << ",";
}
csv << "\n";
}
}
}
void CompressedAssemblyGraph::writeCsvOrientedReads() const
{
const CompressedAssemblyGraph& graph = *this;
ofstream csv("CompressedGraph-OrientedReads.csv");
csv << "OrientedReadId,Id,GFA id,\n";
for(OrientedReadId::Int orientedReadId=0; orientedReadId<orientedReadTable.size();
orientedReadId++) {
const vector<edge_descriptor>& edges = orientedReadTable[orientedReadId];
for(const edge_descriptor e: edges) {
const CompressedAssemblyGraphEdge& edge = graph[e];
csv << OrientedReadId(orientedReadId) << ",";
csv << edge.id << ",";
csv << edge.gfaId() << "\n";
}
}
}
// Fill in minimum and maximum marker counts for each edge.
void CompressedAssemblyGraph::fillMarkerCounts(const AssemblyGraph& assemblyGraph)
{
CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
graph[e].fillMarkerCounts(assemblyGraph);
}
}
void CompressedAssemblyGraphEdge::fillMarkerCounts(const AssemblyGraph& assemblyGraph)
{
minMarkerCount = 0;
maxMarkerCount = 0;
for(const vector<AssemblyGraph::EdgeId>& parallelEdges: edges) {
SHASTA_ASSERT(not parallelEdges.empty());
// Compute the minimum and maximum number of markers
// over this set of parallel edges.
uint64_t minMarkerCountHere = std::numeric_limits<uint64_t>::max();
uint64_t maxMarkerCountHere = 0;
for(const AssemblyGraph::EdgeId edgeId: parallelEdges) {
const uint64_t markerCount = assemblyGraph.edgeLists.size(edgeId);
minMarkerCountHere = min(minMarkerCountHere, markerCount);
maxMarkerCountHere = max(maxMarkerCountHere, markerCount);
}
// Update the totals.
minMarkerCount += minMarkerCountHere;
maxMarkerCount += maxMarkerCountHere;
}
}
// Create a local subgraph.
// See createLocalSubgraph for argument explanation.
CompressedAssemblyGraph::CompressedAssemblyGraph(
const CompressedAssemblyGraph& graph,
const Assembler& assembler,
const vector<vertex_descriptor>& startVertices,
uint64_t maxDistance,
boost::bimap<vertex_descriptor, vertex_descriptor>& vertexMap,
boost::bimap<edge_descriptor, edge_descriptor>& edgeMap,
std::map<vertex_descriptor, uint64_t>& distanceMap
)
{
CompressedAssemblyGraph& subgraph = *this;
createLocalSubgraph(
graph,
startVertices,
maxDistance,
subgraph,
vertexMap,
edgeMap,
distanceMap);
// Make sure the relatedEdges of each edge contain
// edge descriptors in the subgraph.
BGL_FORALL_EDGES(e0, subgraph, CompressedAssemblyGraph) {
vector<edge_descriptor> relatedEdges;
for(const edge_descriptor e1: subgraph[e0].relatedEdges) {
const auto it = edgeMap.right.find(e1);
if(it != edgeMap.right.end()) {
relatedEdges.push_back(it->second);
}
}
subgraph[e0].relatedEdges.swap(relatedEdges);
}
subgraph.fillOrientedReadTable(assembler);
}
// Graphviz output.
void CompressedAssemblyGraph::writeGraphviz(
const string& fileName,
uint64_t sizePixels,
double vertexScalingFactor,
double edgeLengthScalingFactor,
double edgeThicknessScalingFactor,
double edgeArrowScalingFactor,
std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const
{
ofstream s(fileName);
writeGraphviz(s,
sizePixels,
vertexScalingFactor,
edgeLengthScalingFactor,
edgeThicknessScalingFactor,
edgeArrowScalingFactor,
vertexPositions) ;
}
void CompressedAssemblyGraph::writeGraphviz(
ostream& s,
uint64_t sizePixels,
double vertexScalingFactor,
double edgeLengthScalingFactor,
double edgeThicknessScalingFactor,
double edgeArrowScalingFactor,
std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const
{
const CompressedAssemblyGraph& graph = *this;
s << "digraph CompressedAssemblyGraph {\n"
"layout=neato;\n"
"size=" << uint64_t(double(sizePixels)/72.) << ";\n"
"ratio=expand;\n"
"splines=true;\n"
"node [shape=point];\n"
"node [width=" << vertexScalingFactor << "];\n"
"edge [penwidth=" << edgeThicknessScalingFactor << "];\n"
"edge [arrowsize=" << edgeArrowScalingFactor << "];\n";
// Write the vertices.
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
const auto it = vertexPositions.find(v);
SHASTA_ASSERT(it != vertexPositions.end());
const auto& x = it->second;
s << graph[v].vertexId <<
" [pos=\"" << x[0] << "," << x[1] << "\"];\n";
}
// Write the edges.
// Each edge is written as a number of dummy edges,
// to make it look longer, proportionally to its number of markers.
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
const string gfaId = edge.gfaId();
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
// To color the edge, use a hash function of the edge id,
// so the same edge always gets colored the same way.
const uint32_t hashValue = MurmurHash2(&edge.id, sizeof(edge.id), 757);
const double H = double(hashValue) / double(std::numeric_limits<uint32_t>::max());
const double S = 0.7;
const double V = 0.7;
s <<
graph[v0].vertexId << "->" <<
graph[v1].vertexId <<
"[tooltip=\"" << gfaId << "\" "
"color = \"" << H << "," << S << "," << "," << V << "\"" <<
"];\n";
}
s << "}";
}
#if 0
void CompressedAssemblyGraph::writeGraphviz(
ostream& s,
uint64_t sizePixels,
double vertexScalingFactor,
double edgeLengthScalingFactor,
double edgeThicknessScalingFactor,
double edgeArrowScalingFactor,
std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const
{
const CompressedAssemblyGraph& graph = *this;
s << "digraph CompressedAssemblyGraph {\n"
"layout=sfdp;\n"
"size=" << uint64_t(double(sizePixels)/72.) << ";\n"
"ratio=expand;\n"
"rankdir=LR;\n"
"node [shape=point];\n"
"node [width=" << vertexScalingFactor << "];\n"
"edge [penwidth=" << edgeThicknessScalingFactor << "];\n"
"edge [arrowsize=" << edgeArrowScalingFactor << "];\n"
"edge [arrowhead=none];\n";
// Write the vertices.
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
s << graph[v].vertexId << ";\n";
}
// Write the edges.
// Each edge is written as a number of dummy edges,
// to make it look longer, proportionally to its number of markers.
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
const string gfaId = edge.gfaId();
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
const uint64_t dummyEdgeCount =
max(uint64_t(1), uint64_t(0.5 + edgeLengthScalingFactor * edge.averageMarkerCount()));
// Write the dummy vertices.
for(uint64_t i=1; i<dummyEdgeCount; i++) {
s << "\"" << gfaId << "-dummy" << i << "\" [width=" <<
edgeThicknessScalingFactor/72 << "];\n";
}
// Write the dummy edges.
for(uint64_t i=0; i<dummyEdgeCount; i++) {
// First vertex - either v0 or a dummy vertex.
s << "\"";
if(i == 0) {
s << graph[v0].vertexId;
} else {
s << gfaId << "-dummy" << i;
}
s << "\"->\"";
// Second vertex - either v1 or a dummy vertex.
if(i == dummyEdgeCount-1) {
s << graph[v1].vertexId;
} else {
s << gfaId << "-dummy" << i+1;
}
s << "\"";
s << " [";
if(i == dummyEdgeCount-1) {
s << "style=tapered";
}
/*
if(i == dummyEdgeCount/2) {
s << " label=" << edge.gfaId();
}
*/
s << "]";
s << ";\n";
}
}
s << "}";
}
#endif
// Use sfdp to compute a vertex layout.
// But sfdp does not support edges of different length
// (it tries to make all edges the same length).
// Here, we expand each edge into a variable number
// of dummy edges. Longer edges are expanded into more
// dummy edges. Then we use sfdp to compute a layout
// including all these dummy edges (and their vertices).
// Finally, we extract the coordinates for the original
// vertices only.
void CompressedAssemblyGraph::computeVertexLayout(
uint64_t sizePixels,
double vertexScalingFactor,
double edgeLengthPower,
double edgeLengthScalingFactor,
double timeout,
std::map<vertex_descriptor, array<double, 2 > >& vertexPositions
) const
{
const CompressedAssemblyGraph& graph = *this;
// Create a dot file to contain the graph including the dummy edges.
const string uuid = to_string(boost::uuids::random_generator()());
const string dotFileName = tmpDirectory() + uuid + ".dot";
ofstream graphOut(dotFileName);
graphOut <<
"digraph G{\n"
"layout=sfdp;\n"
"smoothing=triangle;\n"
"overlap=false;\n" <<
"size=" << uint64_t(double(sizePixels)/72.) << ";\n"
"ratio=expand;\n"
"node [shape=point];\n"
"node [width=" << vertexScalingFactor << "];\n";
// Write the vertices.
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
graphOut << graph[v].vertexId << ";\n";
}
// Write the dummy edges.
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
const string gfaId = edge.gfaId();
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
// Figure out the number of dummy edges, based on the number of
// markers on this edge.
const double desiredDummyEdgeCount =
edgeLengthScalingFactor * std::pow(edge.averageMarkerCount(), edgeLengthPower);
const uint64_t dummyEdgeCount = max(
uint64_t(1),
uint64_t(0.5 + desiredDummyEdgeCount));
// Write the dummy edges.
for(uint64_t i=0; i<dummyEdgeCount; i++) {
// First vertex - either v0 or a dummy vertex.
if(i == 0) {
graphOut << graph[v0].vertexId;
} else {
graphOut << "D" << i << "_" << gfaId;
}
graphOut << "->";
// Second vertex - either v1 or a dummy vertex.
if(i == dummyEdgeCount-1) {
graphOut << graph[v1].vertexId;
} else {
graphOut << "D" << i+1 << "_" << gfaId;
}
graphOut << ";\n";
}
}
graphOut << "}";
graphOut.close();
// Now use sfdp to compute the layout.
// Use plain format output described here
// https://www.graphviz.org/doc/info/output.html#d:plain
const string plainFileName = dotFileName + ".txt";
const string command = "sfdp -T plain " + dotFileName + " -o " + plainFileName;
bool timeoutTriggered = false;
bool signalOccurred = false;
int returnCode = 0;
runCommandWithTimeout(command, timeout,
timeoutTriggered, signalOccurred, returnCode);
if(signalOccurred) {
throw runtime_error("Unable to compute graph layout: terminated by a signal. "
"The failing command was: " + command);
}
if(timeoutTriggered) {
throw runtime_error("Timeout exceeded during graph layout computation. "
"Increase the timeout or decrease the maximum distance to simplify the graph");
}
if(returnCode!=0 ) {
throw runtime_error("Unable to compute graph layout: return code " +
to_string(returnCode) +
". The failing command was: " + command);
}
filesystem::remove(dotFileName);
// Map vertex ids to vertex descriptors.
std::map<uint64_t, vertex_descriptor> vertexMap;
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
vertexMap.insert(make_pair(graph[v].vertexId, v));
}
// Extract vertex coordinates.
ifstream plainFile(plainFileName);
string line;
vector<string> tokens;
while(true) {
// Read the next line.
std::getline(plainFile, line);
if( not plainFile) {
break;
}
// Parse it.
boost::algorithm::split(tokens, line, boost::algorithm::is_any_of(" "));
// SHASTA_ASSERT(not tokens.empty());
// If not a line describing a vertex, skip it.
if(tokens.front() != "node") {
continue;
}
SHASTA_ASSERT(tokens.size() >= 4);
// If a dummy vertex, skip it.
const string& vertexName = tokens[1];
SHASTA_ASSERT(not vertexName.empty());
if(vertexName[0] == 'D') {
continue;
}
// Get the vertex id.
const uint64_t vertexId = boost::lexical_cast<uint64_t>(vertexName);
// Get the corresponding vertex descriptor.
const auto it = vertexMap.find(vertexId);
const vertex_descriptor v = it->second;
// Store it in the layout.
array<double, 2> x;
x[0] = boost::lexical_cast<double>(tokens[2]);
x[1] = boost::lexical_cast<double>(tokens[3]);
vertexPositions.insert(make_pair(v, x));
}
plainFile.close();
filesystem::remove(plainFileName);
}
// Create a csv file with coloring.
// If the string passed in is an oriented read,
// it colors all edges that have that read.
// If it is the gfaId of an edge, it colors that edge in red
// and all related edges in green.
// This can be loaded in Bandage to color the edges.
void CompressedAssemblyGraph::color(
const string& s,
const string& fileName) const
{
ofstream csv(fileName);
color(s, csv);
}
void CompressedAssemblyGraph::color(
const string& s,
ostream& csv) const
{
const CompressedAssemblyGraph& graph = *this;
std::map<edge_descriptor, string> colorMap;
// If it is the gfaId of an edge, color that edge in red
// and all related edges in green.
edge_descriptor e0;
bool edgeWasFound = false;
tie(e0, edgeWasFound) = getEdgeFromGfaId(s);
if(edgeWasFound) {
colorMap.insert(make_pair(e0, "Red"));
for(const edge_descriptor e1: graph[e0].relatedEdges) {
colorMap.insert(make_pair(e1, "Green"));
}
}
// If it is an oriented read id, color in green all segments
// that have that oriented read.
else {
try {
const OrientedReadId orientedReadId = OrientedReadId(s);
for(const edge_descriptor e1: orientedReadTable[orientedReadId.getValue()]) {
colorMap.insert(make_pair(e1, "Green"));
}
} catch(...) {
cout << "The string to color by does not correspond to a valid "
"GFA id or a valid oriented read id.\n";
}
}
csv << "Segment,Color\n";
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
csv << graph[e].gfaId() << ",";
const auto it = colorMap.find(e);
if(it == colorMap.end()) {
csv << "Grey";
} else {
csv << it->second;
}
csv << "\n";
}
}
| 30.928571 | 107 | 0.627966 | AustinHartman |
c0392ef762db36fb4665005319d9110d07051568 | 12,729 | cpp | C++ | server/Server/Other/ShopManager.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 3 | 2018-06-19T21:37:38.000Z | 2021-07-31T21:51:40.000Z | server/Server/Other/ShopManager.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | null | null | null | server/Server/Other/ShopManager.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 13 | 2015-01-30T17:45:06.000Z | 2022-01-06T02:29:34.000Z | #include "stdafx.h"
#include "ShopManager.h"
//public
#include "Obj_Human.h"
#include "Player.h"
#include "Obj_Monster.h"
#include "PAP_DBC.h"//DBC
#include "ItemHelper.h"//TSerialHelper
#include "ItemTable.h"//_ITEM_TYPE
#include "TimeManager.h"//g_pTimeManager
#include "GCShopUpdateMerchandiseList.h"//GCShopUpdateMerchandiseList
#include "FileDef.h"
//globle
using namespace DBC;
StaticShopManager* g_pStaticShopManager = NULL;
//macro
#define SHOP_ITEM_PROPERTY_NUM 3
#define SHOP_ID 0
//#define SHOP_NAME SHOP_ID+1
#define SHOP_TYPE SHOP_ID+1
#define SHOP_REPAIR_LEVEL SHOP_TYPE+1
#define SHOP_BUY_LEVEL SHOP_REPAIR_LEVEL+1
#define SHOP_REPAIR_TYPE SHOP_BUY_LEVEL+1
#define SHOP_BUY_TYPE SHOP_REPAIR_TYPE+1
#define SHOP_REPAIR_SPEND SHOP_BUY_TYPE+1
#define SHOP_REPAIR_OKPROB SHOP_REPAIR_SPEND+1
#define SHOP_SCALE SHOP_REPAIR_OKPROB+1 +2//LM修改
#define SHOP_REFRESH_TIME SHOP_SCALE+1
#define SHOP_ITEM_NUM SHOP_REFRESH_TIME+1
#define SHOP_ITEM_PROPERTY_BEGIN SHOP_ITEM_NUM+1
#define NEW_AND_COPY_ARRAY(PDEST, PSOURCE, NUM, TYPE)\
PDEST = new TYPE[NUM];\
memcpy((CHAR*)PDEST, (CHAR*)PSOURCE, NUM*sizeof(TYPE));\
ShopMgr::ShopMgr()
{
__ENTER_FUNCTION
m_Count = 0;
m_Shops = NULL;
__LEAVE_FUNCTION
}
ShopMgr::~ShopMgr()
{
__ENTER_FUNCTION
CleanUp();
__LEAVE_FUNCTION
}
VOID ShopMgr::CleanUp( )
{
__ENTER_FUNCTION
SAFE_DELETE_ARRAY(m_Shops)
__LEAVE_FUNCTION
}
//直接从ItemBoxManager::ConvertItemType2Index抄过来
INT ShopMgr::ConvertItemType2Money(_ITEM_TYPE it)
{
__ENTER_FUNCTION
Assert(it.isNull() == FALSE);
switch(it.m_Class)
{
case ICLASS_EQUIP:
{
switch(it.m_Quality)
{
case EQUALITY_NORMAL:
{
COMMON_EQUIP_TB* pGET = g_ItemTable.GetWhiteItemTB(it.ToSerial());
Assert(pGET);
return pGET->m_BasePrice;
}
break;
case EQUALITY_BLUE:
{
BLUE_EQUIP_TB* pGET = g_ItemTable.GetBlueItemTB(it.ToSerial());
Assert(pGET);
return pGET->m_BasePrice;
}
break;
case EQUALITY_YELLOW:
{
}
break;
case EQUALITY_GREEN:
{
GREEN_EQUIP_TB* pGET = g_ItemTable.GetGreenItemTB(it.ToSerial());
Assert(pGET);
return pGET->m_BasePrice;
}
break;
default:
{
Assert(FALSE);
return FALSE;
}
}
Assert(FALSE);
}
break;
case ICLASS_MATERIAL:
case ICLASS_COMITEM:
{
COMMITEM_INFO_TB* pGET = g_ItemTable.GetCommItemInfoTB(it.ToSerial());
Assert(pGET);
return pGET->m_nBasePrice;
}
break;
case ICLASS_TASKITEM:
{
return 1;
}
break;
case ICLASS_GEM:
{
GEMINFO_TB* pGET = g_ItemTable.GetGemInfoTB(it.ToSerial());
Assert(pGET);
return pGET->m_nPrice;
}
break;
case ICLASS_STOREMAP:
{
STORE_MAP_INFO_TB* pGET = g_ItemTable.GetStoreMapTB(it.ToSerial());
Assert(pGET);
return pGET->m_nBasePrice;
break;
}
case ICLASS_TALISMAN:
Assert(FALSE);
break;
case ICLASS_GUILDITEM:
Assert(FALSE);
break;
default:
Assert(FALSE);
break;
}
Assert(FALSE);
__LEAVE_FUNCTION
return -1;
}
_SHOP* ShopMgr::GetShopByID(INT id)
{
__ENTER_FUNCTION
for(INT i = 0; i<m_Count; i++)
{
if(m_Shops[i].m_ShopId == id)
{
return &m_Shops[i];
}
}
return NULL;
__LEAVE_FUNCTION
return NULL;
}
INT ShopMgr::GetShopIndexByID(INT id)
{
__ENTER_FUNCTION
for(INT i = 0; i<m_Count; i++)
{
if(m_Shops[i].m_ShopId == id)
{
return i;
}
}
return -1;
__LEAVE_FUNCTION
return -1;
}
/*
StaticShopManager
*/
StaticShopManager::~StaticShopManager()
{
__ENTER_FUNCTION
CleanUp();
__LEAVE_FUNCTION
}
BOOL StaticShopManager::Init()
{
return LoadShopsFromFile( FILE_SHOP );
}
VOID StaticShopManager::CleanUp()
{
__ENTER_FUNCTION
SAFE_DELETE_ARRAY(m_Shops)
__LEAVE_FUNCTION
}
BOOL StaticShopManager::LoadShopsFromFile( CHAR* filename )
{
__ENTER_FUNCTION
UINT d = sizeof(_ITEM);
DBCFile ShopFile(0);
BOOL ret = ShopFile.OpenFromTXT(filename);
if( !ret )
return FALSE;
INT iTableCount = ShopFile.GetRecordsNum();
INT iTableColumn = ShopFile.GetFieldsNum();
m_Count = iTableCount;
m_Shops = new _SHOP[m_Count];
INT itemnum = 0;
INT i,j,k;
INT itemTypeSn;
_ITEM_TYPE itemType;
INT PerItemNum = 0;
INT MaxItemNum = 0;
FLOAT PerRate = 0.0;
for(i =0;i<iTableCount;i++)
{
m_Shops[i].m_ShopId = ShopFile.Search_Posistion(i,SHOP_ID)->iValue;
//strncpy( m_Shops[i].m_szShopName, ShopFile.Search_Posistion(i,SHOP_NAME)->pString, MAX_SHOP_NAME-2 );
m_Shops[i].m_ShopType = ShopFile.Search_Posistion(i,SHOP_TYPE)->iValue;
m_Shops[i].m_nRepairLevel = ShopFile.Search_Posistion(i,SHOP_REPAIR_LEVEL)->iValue;
m_Shops[i].m_nBuyLevel = ShopFile.Search_Posistion(i,SHOP_BUY_LEVEL)->iValue;
m_Shops[i].m_nRepairType = ShopFile.Search_Posistion(i,SHOP_REPAIR_TYPE)->iValue;
m_Shops[i].m_nBuyType = ShopFile.Search_Posistion(i,SHOP_BUY_TYPE)->iValue;
m_Shops[i].m_nRepairSpend = ShopFile.Search_Posistion(i,SHOP_REPAIR_SPEND)->fValue;
m_Shops[i].m_nRepairOkProb = ShopFile.Search_Posistion(i,SHOP_REPAIR_OKPROB)->fValue;
m_Shops[i].m_scale = ShopFile.Search_Posistion(i,SHOP_SCALE)->fValue;
m_Shops[i].m_refreshTime = ShopFile.Search_Posistion(i,SHOP_REFRESH_TIME)->iValue;
itemnum = ShopFile.Search_Posistion(i,SHOP_ITEM_NUM)->iValue;
//分析实际有的数据
INT nNum = 0;
for(k=0; k<itemnum*SHOP_ITEM_PROPERTY_NUM; k++)
{
itemTypeSn = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+k)->iValue;
if(itemTypeSn == 0)
{
break;
}
nNum ++;
k = k+2;
}
itemnum = nNum;
m_Shops[i].m_ItemList = new _SHOP::_MERCHANDISE_LIST(itemnum);
for(j = 0; j<itemnum*SHOP_ITEM_PROPERTY_NUM; j++)
{
//Type
itemTypeSn = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+j)->iValue;
TSerialHelper help(itemTypeSn);
itemType = help.GetItemTypeStruct();
//GroupNum 0~100
PerItemNum = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+(++j))->iValue;
if(PerItemNum<0) PerItemNum = 1;
if(PerItemNum>100) PerItemNum = 100;
//MaxNum -1代表无限,>0代表有限商品上限,不可以填0,<100
MaxItemNum = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+(++j))->iValue;
if(MaxItemNum == 0) MaxItemNum = -1;
if(PerItemNum>100) PerItemNum = 100;
//Rate 0.0~1.0
PerRate = 1.0;
//ADD TO STRUCTURE
m_Shops[i].m_ItemList->AddType(itemType, PerItemNum, MaxItemNum, PerRate);
}
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
/*
DynamicShopManager
*/
DynamicShopManager::DynamicShopManager(Obj_Monster* pboss)
{
__ENTER_FUNCTION
m_pBoss = pboss;
m_Count = MAX_SHOP_PER_PERSON;
m_Shops = new _SHOP[m_Count];
m_aRefeshTimer = new CMyTimer[m_Count];
memset(m_aRefeshTimer,0, m_Count*sizeof(CMyTimer));
__LEAVE_FUNCTION
}
DynamicShopManager::~DynamicShopManager()
{
__ENTER_FUNCTION
CleanUp();
__LEAVE_FUNCTION
}
BOOL DynamicShopManager::Init()
{
m_nCurrent = 0;
return (m_Shops!= NULL)? TRUE:FALSE;
}
VOID DynamicShopManager::CleanUp()
{
SAFE_DELETE_ARRAY(m_Shops)
SAFE_DELETE_ARRAY(m_aRefeshTimer)
return;
}
INT DynamicShopManager::AddDynamicShop(_SHOP* pSource)
{
__ENTER_FUNCTION
if(m_nCurrent > MAX_SHOP_PER_PERSON)
return -1;
for(INT i = 0;i<m_nCurrent; i++)
{
if(m_Shops[i].m_ShopId == pSource->m_ShopId)
{//表里已经有了
return -1;
}
}
INT itemnum;
_SHOP& ShopRef = m_Shops[m_nCurrent];
ShopRef.m_ShopId = pSource->m_ShopId;
ShopRef.m_scale = pSource->m_scale;
ShopRef.m_refreshTime = pSource->m_refreshTime;
itemnum = pSource->m_ItemList->m_ListCount;
ShopRef.m_ItemList = new _SHOP::_MERCHANDISE_LIST;
ShopRef.m_ItemList->m_nCurrent = pSource->m_ItemList->m_nCurrent;
ShopRef.m_ItemList->m_ListCount = itemnum;
ShopRef.m_ShopType = pSource->m_ShopType;
ShopRef.m_bIsRandShop = pSource->m_bIsRandShop;
ShopRef.m_nCountForSell = pSource->m_nCountForSell;
ShopRef.m_nRepairLevel = pSource->m_nRepairLevel;
ShopRef.m_nBuyLevel = pSource->m_nBuyLevel;
ShopRef.m_nRepairType = pSource->m_nRepairType;
ShopRef.m_nBuyType = pSource->m_nBuyType;
ShopRef.m_nRepairSpend = pSource->m_nRepairSpend;
ShopRef.m_nRepairOkProb = pSource->m_nRepairOkProb;
ShopRef.m_bCanBuyBack = pSource->m_bCanBuyBack;
ShopRef.m_bCanMultiBuy = pSource->m_bCanMultiBuy;
ShopRef.m_uSerialNum = pSource->m_uSerialNum;
ShopRef.m_Rand100 = pSource->m_Rand100;
strncpy( ShopRef.m_szShopName, pSource->m_szShopName, MAX_SHOP_NAME );
//copycopycopy!!!!!,这些数据要保存在本地,供每个商人自己改变
NEW_AND_COPY_ARRAY(ShopRef.m_ItemList->m_TypeMaxNum, pSource->m_ItemList->m_TypeMaxNum, itemnum, INT)
//其他数据全部共享静态表中的数据,这些应该全部是只读的,程序启动时由静态商店管理器初始化,
//系统运行起来后谁都不准改!!
ShopRef.m_ItemList->m_ListType = pSource->m_ItemList->m_ListType;
ShopRef.m_ItemList->m_ListTypeIndex = pSource->m_ItemList->m_ListTypeIndex;
ShopRef.m_ItemList->m_TypeCount = pSource->m_ItemList->m_TypeCount;
ShopRef.m_ItemList->m_AppearRate = pSource->m_ItemList->m_AppearRate;
//全部操作完成,标识这个商店为动态表中的商店,即,可以被商人自己修改
ShopRef.m_IsDyShop = TRUE;
//启动计时器
if(ShopRef.m_refreshTime >0)
m_aRefeshTimer[m_nCurrent].BeginTimer(ShopRef.m_refreshTime, g_pTimeManager->CurrentTime());
return m_nCurrent++;
__LEAVE_FUNCTION
return -1;
}
BOOL DynamicShopManager::Tick(UINT uTime)
{
__ENTER_FUNCTION
if(!m_pBoss)
return FALSE;
Scene* pCurScene = m_pBoss->getScene();
for(INT i = 0; i< m_nCurrent; i++)
{
if(m_Shops[i].m_refreshTime <= 0)
continue;
if(m_aRefeshTimer[i].CountingTimer(uTime))
{//refresh
INT k = 0;
//GCShopUpdateMerchandiseList::_MERCHANDISE_ITEM MerchandiseList[MAX_BOOTH_NUMBER];
for (INT j = 0; j<m_Shops[i].m_ItemList->m_ListCount;j++)
{//用静态表中的数据刷新动态表的数据
INT& LocalMaxNum = m_Shops[i].m_ItemList->m_TypeMaxNum[j] ;
INT& GlobleMaxNum = g_pStaticShopManager->GetShopByID(m_Shops[i].m_ShopId)->m_ItemList->m_TypeMaxNum[j];
if(LocalMaxNum != GlobleMaxNum)
{//改变了,填充消息
LocalMaxNum = GlobleMaxNum;
}
}
}
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
| 30.895631 | 123 | 0.565402 | viticm |
c0427b84b96afa295bc240695a26b27fd39ea4c2 | 3,501 | cpp | C++ | src/ParticleController.cpp | CS126SP20/final-project-meghasg2 | aad841877542c0fc6e51a1deeed55b8b96881844 | [
"MIT"
] | null | null | null | src/ParticleController.cpp | CS126SP20/final-project-meghasg2 | aad841877542c0fc6e51a1deeed55b8b96881844 | [
"MIT"
] | null | null | null | src/ParticleController.cpp | CS126SP20/final-project-meghasg2 | aad841877542c0fc6e51a1deeed55b8b96881844 | [
"MIT"
] | null | null | null | //
// Created by Megha Ganesh on 4/24/20.
//
#include "ParticleController.h"
#include "Conversions.h"
#include "Globals.h"
#include "cinder/Vector.h"
namespace particles {
ParticleController::ParticleController() {}
b2World* ParticleController::setup(b2World &w) {
world_ = &w;
return world_;
}
void ParticleController::draw() {
for (auto & particle : particles_) {
particle.draw();
}
}
void ParticleController::update() {
for (auto & particle : particles_) {
particle.update();
}
}
void ParticleController::AddParticle(const cinder::ivec2 &mouse_pos) {
Particle p = Particle();
// Define a body
b2BodyDef body_def;
body_def.type = b2_staticBody;
// Set the position to that of the mouse
body_def.position.Set(Conversions::ToPhysics(mouse_pos.x),
Conversions::ToPhysics(mouse_pos.y));
// b2Body will be referenced to its corresponding particle instead of just
// creating a new body
body_def.userData = &p;
// Use the world to create the body
p.body_ = world_->CreateBody(&body_def);
// Define the fixture
b2PolygonShape static_box;
// Box is 0.5f x 0.5f
static_box.SetAsBox(Conversions::ToPhysics(global::BOX_SIZE_X),
Conversions::ToPhysics(global::BOX_SIZE_Y));
b2FixtureDef fixture_def;
fixture_def.shape = &static_box;
fixture_def.density = global::DENSITY;
fixture_def.friction = global::FRICTION;
// Restitution = bounce
fixture_def.restitution = global::RESTITUTION;
// Create the fixture with density, friction, and bounce
p.body_->CreateFixture(&fixture_def);
// Particle can do the rest of the initialization on its own
p.setup(cinder::vec2(global::BOX_SIZE_X, global::BOX_SIZE_Y));
// Add Particle to list of Particles
particles_.push_back(p);
}
void ParticleController::RemoveAll() {
for (auto & particle : particles_) {
world_->DestroyBody(particle.body_);
}
particles_.clear();
// Change color of particles
if (global::COLOR_SCHEME == 0 || global::COLOR_SCHEME == 1) {
global::COLOR_SCHEME++;
} else if (global::COLOR_SCHEME == 2) {
global::COLOR_SCHEME = 0;
}
}
b2BodyType ParticleController::SwitchBodyType() {
for (auto & particle : particles_) {
// Set body type to dynamic instead of static
particle.body_->SetType(b2_dynamicBody);
b2PolygonShape dynamic_box;
// +3 is to account for the body size increasing/decreasing
dynamic_box.SetAsBox(
Conversions::ToPhysics(global::BOX_SIZE_X + kSizeDifference),
Conversions::ToPhysics(global::BOX_SIZE_Y + kSizeDifference));
b2FixtureDef fixture_def;
fixture_def.shape = &dynamic_box;
fixture_def.density = global::DENSITY;
fixture_def.friction = global::FRICTION;
// Restitution = bounce
fixture_def.restitution = global::RESTITUTION;
// Create the fixture with density, friction, and bounce
particle.body_->CreateFixture(&fixture_def);
}
return particles_.begin()->body_->GetType();
}
cinder::vec2 ParticleController::IncreaseBodySize() {
cinder::vec2 size = cinder::vec2(global::BOX_SIZE_X + kSizeDifference,
global::BOX_SIZE_X + kSizeDifference);
for (auto & particle : particles_) {
particle.resize(size);
}
return size;
}
cinder::vec2 ParticleController::DecreaseBodySize() {
cinder::vec2 size = cinder::vec2(global::BOX_SIZE_X - kSizeDifference,
global::BOX_SIZE_X - kSizeDifference);
for (auto & particle : particles_) {
particle.resize(size);
}
return size;
}
}
| 30.710526 | 76 | 0.70437 | CS126SP20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.