text
stringlengths 54
60.6k
|
---|
<commit_before>#ifndef TESTLINEDETECTION_HPP
#define TESTLINEDETECTION_HPP
#include <QtTest>
#include <intelligence/linedetection/linedetector.h>
#include <iostream>
#ifdef _WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
class TestLineDetection: public QObject
{
Q_OBJECT
private Q_SLOTS:
void testCase1()
{
//char videoFile[] = "../igvc_cam_data/stills/img_left2.jpg";
char videoFile[] = "../src/intelligence/igvc_cam_data/video/CompCourse_left0.mpeg";
LineDetector ln(videoFile);
bool success =true;
while(success){
ln.applyAlgorithm();
success = ln.loadImage(videoFile);
}
}
};
#endif // TESTLINEDETECTION_HPP
<commit_msg>Added some more comments<commit_after>#ifndef TESTLINEDETECTION_HPP
#define TESTLINEDETECTION_HPP
#include <QtTest>
#include <intelligence/linedetection/linedetector.h>
#include <iostream>
#ifdef _WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
class TestLineDetection: public QObject
{
Q_OBJECT
private Q_SLOTS:
void testCase1()
{
//char videoFile[] = "../igvc_cam_data/stills/img_left2.jpg";
///Note: This may not be the correct directory on your computer
char videoFile[] = "../src/intelligence/igvc_cam_data/video/CompCourse_left0.mpeg";
LineDetector ln(videoFile);
bool success =true;
while(success){
ln.applyAlgorithm();
success = ln.loadImage(videoFile);
}
}
};
#endif // TESTLINEDETECTION_HPP
<|endoftext|> |
<commit_before>#include <functional>
#include "arch/runtime/starter.hpp"
#include "serializer/config.hpp"
#include "unittest/mock_file.hpp"
#include "unittest/gtest.hpp"
namespace unittest {
// This test is completely vacuous, but should invite expansion in the future.
void run_CreateConstructDestroy() {
// This serves more as a mock_file_t test than a serializer test.
mock_file_opener_t file_opener;
standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t());
standard_serializer_t ser(standard_serializer_t::dynamic_config_t(),
&file_opener,
&get_global_perfmon_collection());
}
TEST(SerializerTest, CreateConstructDestroy) {
run_in_thread_pool(run_CreateConstructDestroy, 4);
}
void run_AddDeleteRepeatedly(bool perform_index_write) {
mock_file_opener_t file_opener;
standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t());
standard_serializer_t ser(standard_serializer_t::dynamic_config_t(),
&file_opener,
&get_global_perfmon_collection());
scoped_malloc_t<ser_buffer_t> buf = ser.malloc();
memset(buf->cache_data, 0, ser.get_block_size().value());
scoped_ptr_t<file_account_t> account(ser.make_io_account(1));
for (int i = 0; i < 200000; ++i) {
const block_id_t block_id = i;
std::vector<buf_write_info_t> infos;
infos.push_back(buf_write_info_t(buf.get(), ser.get_block_size(), block_id));
// Create the block
struct : public iocallback_t, public cond_t {
void on_io_complete() {
pulse();
}
} cb;
std::vector<counted_t<standard_block_token_t> > tokens
= ser.block_writes(infos, account.get(), &cb);
// Wait for it to be written (because we're nice).
cb.wait();
if (perform_index_write) {
// Do an index write creating the block.
{
std::vector<index_write_op_t> write_ops;
write_ops.push_back(index_write_op_t(block_id, tokens[0], repli_timestamp_t::distant_past));
ser.index_write(write_ops, account.get());
}
// Now delete the only block token and delete the index reference.
tokens.clear();
{
std::vector<index_write_op_t> write_ops;
write_ops.push_back(index_write_op_t(block_id, counted_t<standard_block_token_t>()));
ser.index_write(write_ops, account.get());
}
} else {
// Now delete the only block token.
tokens.clear();
}
}
}
TEST(SerializerTest, AddDeleteRepeatedly) {
run_in_thread_pool(std::bind(run_AddDeleteRepeatedly, false), 4);
}
TEST(SerializerTest, AddDeleteRepeatedlyWithIndex) {
run_in_thread_pool(std::bind(run_AddDeleteRepeatedly, true), 4);
}
} // namespace unittest
<commit_msg>Added comments about the goals of run_AddDeleteRepeatedly with regard to what issue it is testing.<commit_after>#include <functional>
#include "arch/runtime/starter.hpp"
#include "serializer/config.hpp"
#include "unittest/mock_file.hpp"
#include "unittest/gtest.hpp"
namespace unittest {
// This test is completely vacuous, but should invite expansion in the future.
void run_CreateConstructDestroy() {
// This serves more as a mock_file_t test than a serializer test.
mock_file_opener_t file_opener;
standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t());
standard_serializer_t ser(standard_serializer_t::dynamic_config_t(),
&file_opener,
&get_global_perfmon_collection());
}
TEST(SerializerTest, CreateConstructDestroy) {
run_in_thread_pool(run_CreateConstructDestroy, 4);
}
void run_AddDeleteRepeatedly(bool perform_index_write) {
mock_file_opener_t file_opener;
standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t());
standard_serializer_t ser(standard_serializer_t::dynamic_config_t(),
&file_opener,
&get_global_perfmon_collection());
scoped_malloc_t<ser_buffer_t> buf = ser.malloc();
memset(buf->cache_data, 0, ser.get_block_size().value());
scoped_ptr_t<file_account_t> account(ser.make_io_account(1));
// We run enough create/delete operations to run ourselves through the young
// extent queue and (with perform_index_write true) kick off a GC that reproduces
// #1691.
for (int i = 0; i < 200000; ++i) {
const block_id_t block_id = i;
std::vector<buf_write_info_t> infos;
infos.push_back(buf_write_info_t(buf.get(), ser.get_block_size(), block_id));
// Create the block
struct : public iocallback_t, public cond_t {
void on_io_complete() {
pulse();
}
} cb;
std::vector<counted_t<standard_block_token_t> > tokens
= ser.block_writes(infos, account.get(), &cb);
// Wait for it to be written (because we're nice).
cb.wait();
if (perform_index_write) {
// Do an index write creating the block.
{
std::vector<index_write_op_t> write_ops;
write_ops.push_back(index_write_op_t(block_id, tokens[0], repli_timestamp_t::distant_past));
ser.index_write(write_ops, account.get());
}
// Now delete the only block token and delete the index reference.
tokens.clear();
{
std::vector<index_write_op_t> write_ops;
write_ops.push_back(index_write_op_t(block_id, counted_t<standard_block_token_t>()));
ser.index_write(write_ops, account.get());
}
} else {
// Now delete the only block token.
tokens.clear();
}
}
}
TEST(SerializerTest, AddDeleteRepeatedly) {
run_in_thread_pool(std::bind(run_AddDeleteRepeatedly, false), 4);
}
// This is a regression test for #1691.
TEST(SerializerTest, AddDeleteRepeatedlyWithIndex) {
run_in_thread_pool(std::bind(run_AddDeleteRepeatedly, true), 4);
}
} // namespace unittest
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/log/log.h>
LOG_SETUP(".proton.docsummary.summarymanager");
#include "documentstoreadapter.h"
#include "summarycompacttarget.h"
#include "summaryflushtarget.h"
#include "summarymanager.h"
#include <vespa/searchcore/proton/common/eventlogger.h>
#include <vespa/searchlib/docstore/logdocumentstore.h>
#include <vespa/searchsummary/docsummary/docsumconfig.h>
#include <vespa/config/print/ostreamconfigwriter.h>
using namespace config;
using namespace document;
using namespace search::docsummary;
using namespace vespa::config::search::core;
using namespace vespa::config::search::summary;
using namespace vespa::config::search;
using search::TuneFileSummary;
using search::common::FileHeaderContext;
namespace proton {
SummaryManager::SummarySetup::
SummarySetup(const vespalib::string & baseDir,
const DocTypeName & docTypeName,
const SummaryConfig & summaryCfg,
const SummarymapConfig & summarymapCfg,
const JuniperrcConfig & juniperCfg,
const search::IAttributeManager::SP &attributeMgr,
const search::IDocumentStore::SP & docStore,
const DocumentTypeRepo::SP &repo)
: _docsumWriter(),
_wordFolder(),
_juniperProps(juniperCfg),
_juniperConfig(),
_attributeMgr(attributeMgr),
_docStore(docStore),
_fieldCacheRepo(),
_repo(repo),
_markupFields()
{
std::unique_ptr<ResultConfig> resultConfig(new ResultConfig());
if (!resultConfig->ReadConfig(summaryCfg,
vespalib::make_string("SummaryManager(%s)",
baseDir.c_str()).c_str())) {
std::ostringstream oss;
config::OstreamConfigWriter writer(oss);
writer.write(summaryCfg);
throw vespalib::IllegalArgumentException
(vespalib::make_string("Could not initialize "
"summary result config for directory '%s' "
"based on summary config '%s'",
baseDir.c_str(), oss.str().c_str()));
}
_juniperConfig.reset(new juniper::Juniper(&_juniperProps, &_wordFolder));
_docsumWriter.reset(new DynamicDocsumWriter(resultConfig.release(), NULL));
DynamicDocsumConfig dynCfg(this, _docsumWriter.get());
dynCfg.configure(summarymapCfg);
for (size_t i = 0; i < summarymapCfg.override.size(); ++i) {
const SummarymapConfig::Override & o = summarymapCfg.override[i];
if (o.command == "dynamicteaser" ||
o.command == "textextractor") {
vespalib::string markupField = o.arguments;
if (markupField.empty())
continue;
// Assume just one argument: source field that must contain markup
_markupFields.insert(markupField);
}
}
const DocumentType *docType = repo->getDocumentType(docTypeName.getName());
if (docType != NULL) {
_fieldCacheRepo.reset(new FieldCacheRepo(getResultConfig(), *docType));
} else if (getResultConfig().GetNumResultClasses() == 0) {
LOG(debug, "Create empty field cache repo for document type '%s'",
docTypeName.toString().c_str());
_fieldCacheRepo.reset(new FieldCacheRepo());
} else {
throw vespalib::IllegalArgumentException
(vespalib::make_string("Did not find document type '%s' in current document type repo. "
"Cannot setup field cache repo for the summary setup",
docTypeName.toString().c_str()));
}
}
IDocsumStore::UP SummaryManager::SummarySetup::createDocsumStore(
const vespalib::string &resultClassName) {
return search::docsummary::IDocsumStore::UP(
new DocumentStoreAdapter(
*_docStore, *_repo, getResultConfig(), resultClassName,
_fieldCacheRepo->getFieldCache(resultClassName),
_markupFields));
}
ISummaryManager::ISummarySetup::SP
SummaryManager::createSummarySetup(const SummaryConfig & summaryCfg,
const SummarymapConfig & summarymapCfg,
const JuniperrcConfig & juniperCfg,
const DocumentTypeRepo::SP &repo,
const search::IAttributeManager::SP &attributeMgr)
{
ISummarySetup::SP newSetup(new SummarySetup(_baseDir, _docTypeName, summaryCfg,
summarymapCfg, juniperCfg,
attributeMgr, _docStore, repo));
return newSetup;
}
namespace {
search::DocumentStore::Config getStoreConfig(const ProtonConfig::Summary::Cache & cache)
{
document::CompressionConfig compression;
if (cache.compression.type == ProtonConfig::Summary::Cache::Compression::LZ4) {
compression.type = document::CompressionConfig::LZ4;
}
compression.compressionLevel = cache.compression.level;
return search::DocumentStore::Config(compression, cache.maxbytes, cache.initialentries).allowVisitCaching(cache.allowvisitcaching);
}
}
SummaryManager::SummaryManager(vespalib::ThreadStackExecutorBase & executor,
const ProtonConfig::Summary & summary,
const search::GrowStrategy & growStrategy,
const vespalib::string &baseDir,
const DocTypeName &docTypeName,
const TuneFileSummary &tuneFileSummary,
const FileHeaderContext &fileHeaderContext,
search::transactionlog::SyncProxy &tlSyncer,
const search::IBucketizer::SP & bucketizer)
: _baseDir(baseDir),
_docTypeName(docTypeName),
_docStore(),
_tuneFileSummary(tuneFileSummary),
_currentSerial(0u)
{
search::DocumentStore::Config config(getStoreConfig(summary.cache));
const ProtonConfig::Summary::Log & log(summary.log);
const ProtonConfig::Summary::Log::Chunk & chunk(log.chunk);
document::CompressionConfig chunkCompression;
if (chunk.compression.type == ProtonConfig::Summary::Log::Chunk::Compression::LZ4) {
chunkCompression.type = document::CompressionConfig::LZ4;
}
chunkCompression.compressionLevel = chunk.compression.level;
document::CompressionConfig compactCompression;
if (chunk.compression.type == ProtonConfig::Summary::Log::Chunk::Compression::LZ4) {
compactCompression.type = document::CompressionConfig::LZ4;
}
compactCompression.compressionLevel = chunk.compression.level;
search::WriteableFileChunk::Config fileConfig(chunkCompression, chunk.maxbytes, chunk.maxentries);
search::LogDataStore::Config logConfig(log.maxfilesize,
log.maxdiskbloatfactor,
log.maxbucketspread,
log.minfilesizefactor,
log.numthreads,
log.compact2activefile,
compactCompression,
fileConfig);
logConfig.disableCrcOnRead(chunk.skipcrconread);
_docStore.reset(
new search::LogDocumentStore(executor, baseDir,
search::LogDocumentStore::
Config(config, logConfig),
growStrategy,
tuneFileSummary,
fileHeaderContext,
tlSyncer,
summary.compact2buckets ? bucketizer : search::IBucketizer::SP()));
}
void
SummaryManager::putDocument(uint64_t syncToken, const Document & doc, search::DocumentIdT lid)
{
_docStore->write(syncToken, doc, lid);
_currentSerial = syncToken;
}
void
SummaryManager::removeDocument(uint64_t syncToken, search::DocumentIdT lid)
{
_docStore->remove(syncToken, lid);
_currentSerial = syncToken;
}
IFlushTarget::List SummaryManager::getFlushTargets()
{
IFlushTarget::List ret;
ret.push_back(IFlushTarget::SP(new SummaryFlushTarget(getBackingStore())));
if (dynamic_cast<search::LogDocumentStore *>(_docStore.get()) != NULL) {
ret.push_back(IFlushTarget::SP(new SummaryCompactTarget(getBackingStore())));
}
return ret;
}
} // namespace proton
<commit_msg>Avoid copy paste errors by using a template for deriving compression config.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/log/log.h>
LOG_SETUP(".proton.docsummary.summarymanager");
#include "documentstoreadapter.h"
#include "summarycompacttarget.h"
#include "summaryflushtarget.h"
#include "summarymanager.h"
#include <vespa/searchcore/proton/common/eventlogger.h>
#include <vespa/searchlib/docstore/logdocumentstore.h>
#include <vespa/searchsummary/docsummary/docsumconfig.h>
#include <vespa/config/print/ostreamconfigwriter.h>
using namespace config;
using namespace document;
using namespace search::docsummary;
using namespace vespa::config::search::core;
using namespace vespa::config::search::summary;
using namespace vespa::config::search;
using search::TuneFileSummary;
using search::common::FileHeaderContext;
namespace proton {
SummaryManager::SummarySetup::
SummarySetup(const vespalib::string & baseDir,
const DocTypeName & docTypeName,
const SummaryConfig & summaryCfg,
const SummarymapConfig & summarymapCfg,
const JuniperrcConfig & juniperCfg,
const search::IAttributeManager::SP &attributeMgr,
const search::IDocumentStore::SP & docStore,
const DocumentTypeRepo::SP &repo)
: _docsumWriter(),
_wordFolder(),
_juniperProps(juniperCfg),
_juniperConfig(),
_attributeMgr(attributeMgr),
_docStore(docStore),
_fieldCacheRepo(),
_repo(repo),
_markupFields()
{
std::unique_ptr<ResultConfig> resultConfig(new ResultConfig());
if (!resultConfig->ReadConfig(summaryCfg,
vespalib::make_string("SummaryManager(%s)",
baseDir.c_str()).c_str())) {
std::ostringstream oss;
config::OstreamConfigWriter writer(oss);
writer.write(summaryCfg);
throw vespalib::IllegalArgumentException
(vespalib::make_string("Could not initialize "
"summary result config for directory '%s' "
"based on summary config '%s'",
baseDir.c_str(), oss.str().c_str()));
}
_juniperConfig.reset(new juniper::Juniper(&_juniperProps, &_wordFolder));
_docsumWriter.reset(new DynamicDocsumWriter(resultConfig.release(), NULL));
DynamicDocsumConfig dynCfg(this, _docsumWriter.get());
dynCfg.configure(summarymapCfg);
for (size_t i = 0; i < summarymapCfg.override.size(); ++i) {
const SummarymapConfig::Override & o = summarymapCfg.override[i];
if (o.command == "dynamicteaser" ||
o.command == "textextractor") {
vespalib::string markupField = o.arguments;
if (markupField.empty())
continue;
// Assume just one argument: source field that must contain markup
_markupFields.insert(markupField);
}
}
const DocumentType *docType = repo->getDocumentType(docTypeName.getName());
if (docType != NULL) {
_fieldCacheRepo.reset(new FieldCacheRepo(getResultConfig(), *docType));
} else if (getResultConfig().GetNumResultClasses() == 0) {
LOG(debug, "Create empty field cache repo for document type '%s'",
docTypeName.toString().c_str());
_fieldCacheRepo.reset(new FieldCacheRepo());
} else {
throw vespalib::IllegalArgumentException
(vespalib::make_string("Did not find document type '%s' in current document type repo. "
"Cannot setup field cache repo for the summary setup",
docTypeName.toString().c_str()));
}
}
IDocsumStore::UP SummaryManager::SummarySetup::createDocsumStore(
const vespalib::string &resultClassName) {
return search::docsummary::IDocsumStore::UP(
new DocumentStoreAdapter(
*_docStore, *_repo, getResultConfig(), resultClassName,
_fieldCacheRepo->getFieldCache(resultClassName),
_markupFields));
}
ISummaryManager::ISummarySetup::SP
SummaryManager::createSummarySetup(const SummaryConfig & summaryCfg,
const SummarymapConfig & summarymapCfg,
const JuniperrcConfig & juniperCfg,
const DocumentTypeRepo::SP &repo,
const search::IAttributeManager::SP &attributeMgr)
{
ISummarySetup::SP newSetup(new SummarySetup(_baseDir, _docTypeName, summaryCfg,
summarymapCfg, juniperCfg,
attributeMgr, _docStore, repo));
return newSetup;
}
namespace {
template<typename T>
document::CompressionConfig
deriveCompression(const T & config) {
document::CompressionConfig compression;
if (config.type == T::LZ4) {
compression.type = document::CompressionConfig::LZ4;
}
compression.compressionLevel = config.level;
return compression;
}
search::DocumentStore::Config getStoreConfig(const ProtonConfig::Summary::Cache & cache)
{
return search::DocumentStore::Config(deriveCompression(cache.compression), cache.maxbytes, cache.initialentries).allowVisitCaching(cache.allowvisitcaching);
}
}
SummaryManager::SummaryManager(vespalib::ThreadStackExecutorBase & executor,
const ProtonConfig::Summary & summary,
const search::GrowStrategy & growStrategy,
const vespalib::string &baseDir,
const DocTypeName &docTypeName,
const TuneFileSummary &tuneFileSummary,
const FileHeaderContext &fileHeaderContext,
search::transactionlog::SyncProxy &tlSyncer,
const search::IBucketizer::SP & bucketizer)
: _baseDir(baseDir),
_docTypeName(docTypeName),
_docStore(),
_tuneFileSummary(tuneFileSummary),
_currentSerial(0u)
{
search::DocumentStore::Config config(getStoreConfig(summary.cache));
const ProtonConfig::Summary::Log & log(summary.log);
const ProtonConfig::Summary::Log::Chunk & chunk(log.chunk);
search::WriteableFileChunk::Config fileConfig(deriveCompression(chunk.compression), chunk.maxbytes, chunk.maxentries);
search::LogDataStore::Config logConfig(log.maxfilesize,
log.maxdiskbloatfactor,
log.maxbucketspread,
log.minfilesizefactor,
log.numthreads,
log.compact2activefile,
deriveCompression(log.compact.compression),
fileConfig);
logConfig.disableCrcOnRead(chunk.skipcrconread);
_docStore.reset(
new search::LogDocumentStore(executor, baseDir,
search::LogDocumentStore::
Config(config, logConfig),
growStrategy,
tuneFileSummary,
fileHeaderContext,
tlSyncer,
summary.compact2buckets ? bucketizer : search::IBucketizer::SP()));
}
void
SummaryManager::putDocument(uint64_t syncToken, const Document & doc, search::DocumentIdT lid)
{
_docStore->write(syncToken, doc, lid);
_currentSerial = syncToken;
}
void
SummaryManager::removeDocument(uint64_t syncToken, search::DocumentIdT lid)
{
_docStore->remove(syncToken, lid);
_currentSerial = syncToken;
}
IFlushTarget::List SummaryManager::getFlushTargets()
{
IFlushTarget::List ret;
ret.push_back(IFlushTarget::SP(new SummaryFlushTarget(getBackingStore())));
if (dynamic_cast<search::LogDocumentStore *>(_docStore.get()) != NULL) {
ret.push_back(IFlushTarget::SP(new SummaryCompactTarget(getBackingStore())));
}
return ret;
}
} // namespace proton
<|endoftext|> |
<commit_before>#ifndef INC_STATIC_POW_HPP_
#define INC_STATIC_POW_HPP_
#include <boost/integer.hpp>
namespace utils {
template<size_t n, size_t p>
struct static_pow
{
static boost::uintmax_t const value = n * static_pow<n, p-1>::value;
};
template<size_t n>
struct static_pow<n, 1>
{
static boost::uintmax_t const value = n;
};
}
#endif
<commit_msg>assertion if p < 0<commit_after>#ifndef INC_STATIC_POW_HPP_
#define INC_STATIC_POW_HPP_
#include <boost/integer.hpp>
#include <boost/static_assert.hpp>
namespace utils {
template<size_t n, size_t p>
struct static_pow
{
BOOST_STATIC_ASSERT((p >= 0));
static boost::uintmax_t const value = n * static_pow<n, p-1>::value;
};
template<size_t n>
struct static_pow<n, 0>
{
static boost::uintmax_t const value = 1;
};
}
#endif
<|endoftext|> |
<commit_before>#include "BootSplash.h"
#include "ui_BootSplash.h"
#include <LuminaXDG.h>
BootSplash::BootSplash() : QWidget(0, Qt::SplashScreen | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint | Qt::WindowDoesNotAcceptFocus), ui(new Ui::BootSplash){
ui->setupUi(this);
this->setObjectName("LuminaBootSplash"); //for theme styling
//Center the window on the primary screen
QPoint ctr = QApplication::desktop()->screenGeometry().center();
this->move( ctr.x()-(this->width()/2), ctr.y()-(this->height()/2) );
}
void BootSplash::showScreen(QString loading){ //update icon, text, and progress
QString txt, icon;
int per = 0;
if(loading=="init"){
txt = tr("Initializing Session..."); per = 10;
icon = "preferences-system-login";
}else if(loading=="settings"){
txt = tr("Loading Settings..."); per = 20;
icon = "user-home";
}else if(loading=="user"){
txt = tr("Checking User Settings..."); per = 30;
icon = "preferences-desktop-user";
}else if(loading=="systray"){
txt = tr("Registering System Tray..."); per = 40;
icon = "preferences-plugin";
}else if(loading=="wm"){
txt = tr("Starting Window Manager..."); per = 50;
icon = "preferences-system-windows-actions";
}else if(loading=="apps"){
txt = tr("Detecting System Applications..."); per = 60;
icon = "preferences-desktop-icons";
}else if(loading=="menus"){
txt = tr("Initializing System Menu(s)..."); per = 70;
icon = "preferences-system-windows";
}else if(loading=="desktop"){
txt = tr("Initializing Desktop(s)..."); per = 80;
icon = "preferences-desktop-wallpaper";
}else if(loading=="final"){
txt = tr("Performing Final Checks..."); per = 90;
icon = "pcbsd";
}
ui->progressBar->setValue(per);
ui->label_text->setText(txt);
ui->label_icon->setPixmap( LXDG::findIcon(icon, "Lumina-DE").pixmap(64,64) );
this->show();
this->update();
QApplication::processEvents();
}
void BootSplash::showText(QString txt){ //will only update the text, not the icon/progress
ui->label_text->setText(txt);
this->show();
this->update();
QApplication::processEvents();
}<commit_msg>Tidier wording, and punctuation, in BootSplash.cpp<commit_after>#include "BootSplash.h"
#include "ui_BootSplash.h"
#include <LuminaXDG.h>
BootSplash::BootSplash() : QWidget(0, Qt::SplashScreen | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint | Qt::WindowDoesNotAcceptFocus), ui(new Ui::BootSplash){
ui->setupUi(this);
this->setObjectName("LuminaBootSplash"); //for theme styling
//Center the window on the primary screen
QPoint ctr = QApplication::desktop()->screenGeometry().center();
this->move( ctr.x()-(this->width()/2), ctr.y()-(this->height()/2) );
}
void BootSplash::showScreen(QString loading){ //update icon, text, and progress
QString txt, icon;
int per = 0;
if(loading=="init"){
txt = tr("Initializing Session …"); per = 10;
icon = "preferences-system-login";
}else if(loading=="settings"){
txt = tr("Loading System Settings …"); per = 20;
icon = "user-home";
}else if(loading=="user"){
txt = tr("Loading User Preferences …"); per = 30;
icon = "preferences-desktop-user";
}else if(loading=="systray"){
txt = tr("Preparing System Tray …"); per = 40;
icon = "preferences-plugin";
}else if(loading=="wm"){
txt = tr("Starting Window Manager …"); per = 50;
icon = "preferences-system-windows-actions";
}else if(loading=="apps"){
txt = tr("Detecting Applications …"); per = 60;
icon = "preferences-desktop-icons";
}else if(loading=="menus"){
txt = tr("Preparing Menus …"); per = 70;
icon = "preferences-system-windows";
}else if(loading=="desktop"){
txt = tr("Preparing Workspace …"); per = 80;
icon = "preferences-desktop-wallpaper";
}else if(loading=="final"){
txt = tr("Finalizing …"); per = 90;
icon = "pcbsd";
}
ui->progressBar->setValue(per);
ui->label_text->setText(txt);
ui->label_icon->setPixmap( LXDG::findIcon(icon, "Lumina-DE").pixmap(64,64) );
this->show();
this->update();
QApplication::processEvents();
}
void BootSplash::showText(QString txt){ //will only update the text, not the icon/progress
ui->label_text->setText(txt);
this->show();
this->update();
QApplication::processEvents();
}
<|endoftext|> |
<commit_before>
/*
* Copyright (c) 2012-2021 Karl N. Redgate
*
* 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 redx.cc
* \brief A diagnostic shell
*
* \todo add process status/grep/lookup/etc
* \todo add dbus
* \todo add syslog
*/
#include <sys/stat.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <dirent.h>
#include <pthread.h>
#include <string.h>
#include <syslog.h>
#include "platform.h"
#include "tcl_util.h"
#include "AppInit.h"
/**
*/
int RedX_Init( Tcl_Interp *interp ) {
int interactive = 1;
Tcl_Obj *interactive_obj;
interactive_obj = Tcl_GetVar2Ex( interp, "tcl_interactive", NULL, TCL_GLOBAL_ONLY );
if ( interactive_obj != NULL ) {
Tcl_GetIntFromObj( interp, interactive_obj, &interactive );
}
Tcl_Command command;
if ( interactive ) printf( " ** RedX debug tool v1.0\n" );
Tcl_SetVar(interp, "tcl_rcFileName", "~/.redxrc", TCL_GLOBAL_ONLY);
Tcl_EvalEx( interp, "proc clock {command} { namespace eval ::tcl::clock $command}", -1, TCL_EVAL_GLOBAL );
Tcl_EvalEx( interp, "proc commands {} {namespace eval commands {info procs}}", -1, TCL_EVAL_GLOBAL );
const char *help_script = "proc help {args} {\n"
" foreach name [namespace children] {\n"
" puts \"## $name commands\"\n"
" foreach command [info commands \"${name}::*\"] {\n"
" puts -nonewline \"[namespace tail $command] \"\n"
" }\n"
" puts {}\n"
" }\n"
"}\n";
int retcode = Tcl_EvalEx( interp, help_script, -1, TCL_EVAL_GLOBAL );
if ( retcode != TCL_OK ) return false;
#if 0
if ( getuid() != 0 ) {
if ( interactive ) printf( "BIOS not initialized, no access to /dev/mem\n" );
} else {
if ( BIOS::Initialize(interp) == false ) {
Tcl_StaticSetResult( interp, "BIOS::Initialize failed" );
return TCL_ERROR;
}
if ( interactive ) printf( "BIOS initialized\n" );
}
if ( access("/proc/xen/privcmd", R_OK) != 0 ) {
if ( interactive ) printf( "Xen not initialized, no hypervisor present\n" );
} else {
if ( Xen::Initialize(interp) == false ) {
Tcl_StaticSetResult( interp, "Xen::Initialize failed" );
return TCL_ERROR;
}
if ( interactive ) printf( "Xen initialized\n" );
}
#endif
if ( Tcl_CallAppInitChain(interp) == false ) {
// this may want to be additive result
Tcl_StaticSetResult( interp, "AppInit failed" );
return TCL_ERROR;
}
return TCL_OK;
}
/**
*/
int main( int argc, char **argv ) {
Tcl_Main( argc, argv, RedX_Init );
}
/* vim: set autoindent expandtab sw=4 : */
<commit_msg>initialize the logger<commit_after>
/*
* Copyright (c) 2012-2021 Karl N. Redgate
*
* 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 redx.cc
* \brief A diagnostic shell
*
* \todo add process status/grep/lookup/etc
* \todo add dbus
* \todo add syslog
*/
#include <sys/stat.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <dirent.h>
#include <pthread.h>
#include <string.h>
#include <syslog.h>
#include "platform.h"
#include "logger.h"
#include "tcl_util.h"
#include "AppInit.h"
/**
*/
int RedX_Init( Tcl_Interp *interp ) {
int interactive = 1;
Tcl_Obj *interactive_obj;
interactive_obj = Tcl_GetVar2Ex( interp, "tcl_interactive", NULL, TCL_GLOBAL_ONLY );
if ( interactive_obj != NULL ) {
Tcl_GetIntFromObj( interp, interactive_obj, &interactive );
}
log_interactive( interactive );
Tcl_Command command;
if ( interactive ) printf( " ** RedX debug tool v1.0\n" );
Tcl_SetVar(interp, "tcl_rcFileName", "~/.redxrc", TCL_GLOBAL_ONLY);
Tcl_EvalEx( interp, "proc clock {command} { namespace eval ::tcl::clock $command}", -1, TCL_EVAL_GLOBAL );
Tcl_EvalEx( interp, "proc commands {} {namespace eval commands {info procs}}", -1, TCL_EVAL_GLOBAL );
const char *help_script = "proc help {args} {\n"
" foreach name [namespace children] {\n"
" puts \"## $name commands\"\n"
" foreach command [info commands \"${name}::*\"] {\n"
" puts -nonewline \"[namespace tail $command] \"\n"
" }\n"
" puts {}\n"
" }\n"
"}\n";
int retcode = Tcl_EvalEx( interp, help_script, -1, TCL_EVAL_GLOBAL );
if ( retcode != TCL_OK ) return false;
#if 0
if ( getuid() != 0 ) {
if ( interactive ) printf( "BIOS not initialized, no access to /dev/mem\n" );
} else {
if ( BIOS::Initialize(interp) == false ) {
Tcl_StaticSetResult( interp, "BIOS::Initialize failed" );
return TCL_ERROR;
}
if ( interactive ) printf( "BIOS initialized\n" );
}
if ( access("/proc/xen/privcmd", R_OK) != 0 ) {
if ( interactive ) printf( "Xen not initialized, no hypervisor present\n" );
} else {
if ( Xen::Initialize(interp) == false ) {
Tcl_StaticSetResult( interp, "Xen::Initialize failed" );
return TCL_ERROR;
}
if ( interactive ) printf( "Xen initialized\n" );
}
#endif
if ( Tcl_CallAppInitChain(interp) == false ) {
// this may want to be additive result
Tcl_StaticSetResult( interp, "AppInit failed" );
return TCL_ERROR;
}
return TCL_OK;
}
/**
*/
int main( int argc, char **argv ) {
Tcl_Main( argc, argv, RedX_Init );
}
/* vim: set autoindent expandtab sw=4 : */
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2019 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#pragma once
#include <stdint.h>
namespace px4
{
class WorkQueue; // forward declaration
struct wq_config_t {
const char *name;
uint16_t stacksize;
int8_t relative_priority; // relative to max
};
namespace wq_configurations
{
static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1664, 0}; // PX4 inner loop highest priority
static constexpr wq_config_t SPI0{"wq:SPI0", 2496, -1};
static constexpr wq_config_t SPI1{"wq:SPI1", 2496, -2};
static constexpr wq_config_t SPI2{"wq:SPI2", 2496, -3};
static constexpr wq_config_t SPI3{"wq:SPI3", 2496, -4};
static constexpr wq_config_t SPI4{"wq:SPI4", 2496, -5};
static constexpr wq_config_t SPI5{"wq:SPI5", 2496, -6};
static constexpr wq_config_t SPI6{"wq:SPI6", 2496, -7};
static constexpr wq_config_t I2C0{"wq:I2C0", 1472, -8};
static constexpr wq_config_t I2C1{"wq:I2C1", 1472, -9};
static constexpr wq_config_t I2C2{"wq:I2C2", 1472, -10};
static constexpr wq_config_t I2C3{"wq:I2C3", 1472, -11};
static constexpr wq_config_t I2C4{"wq:I2C4", 1472, -12};
// PX4 att/pos controllers, highest priority after sensors.
static constexpr wq_config_t attitude_ctrl{"wq:attitude_ctrl", 1600, -13};
static constexpr wq_config_t navigation_and_controllers{"wq:navigation_and_controllers", 7200, -14};
static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -15};
static constexpr wq_config_t uavcan{"wq:uavcan", 3000, -16};
static constexpr wq_config_t UART0{"wq:UART0", 1400, -17};
static constexpr wq_config_t UART1{"wq:UART1", 1400, -18};
static constexpr wq_config_t UART2{"wq:UART2", 1400, -19};
static constexpr wq_config_t UART3{"wq:UART3", 1400, -20};
static constexpr wq_config_t UART4{"wq:UART4", 1400, -21};
static constexpr wq_config_t UART5{"wq:UART5", 1400, -22};
static constexpr wq_config_t UART6{"wq:UART6", 1400, -23};
static constexpr wq_config_t UART7{"wq:UART7", 1400, -24};
static constexpr wq_config_t UART8{"wq:UART8", 1400, -25};
static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1400, -26};
static constexpr wq_config_t lp_default{"wq:lp_default", 1700, -50};
static constexpr wq_config_t test1{"wq:test1", 2000, 0};
static constexpr wq_config_t test2{"wq:test2", 2000, 0};
} // namespace wq_configurations
/**
* Start the work queue manager task.
*/
int WorkQueueManagerStart();
/**
* Stop the work queue manager task.
*/
int WorkQueueManagerStop();
/**
* Work queue manager status.
*/
int WorkQueueManagerStatus();
/**
* Create (or find) a work queue with a particular configuration.
*
* @param new_wq The work queue configuration (see WorkQueueManager.hpp).
* @return A pointer to the WorkQueue, or nullptr on failure.
*/
WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);
/**
* Map a PX4 driver device id to a work queue (by sensor bus).
*
* @param device_id The PX4 driver's device id.
* @return A work queue configuration.
*/
const wq_config_t &device_bus_to_wq(uint32_t device_id);
/**
* Map a serial device path (eg /dev/ttyS1) to a work queue.
*
* @param device_id The device path.
* @return A work queue configuration.
*/
const wq_config_t &serial_port_to_wq(const char *serial);
} // namespace px4
<commit_msg>wq:attitude_ctrl small stack increase<commit_after>/****************************************************************************
*
* Copyright (c) 2019 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#pragma once
#include <stdint.h>
namespace px4
{
class WorkQueue; // forward declaration
struct wq_config_t {
const char *name;
uint16_t stacksize;
int8_t relative_priority; // relative to max
};
namespace wq_configurations
{
static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1664, 0}; // PX4 inner loop highest priority
static constexpr wq_config_t SPI0{"wq:SPI0", 2496, -1};
static constexpr wq_config_t SPI1{"wq:SPI1", 2496, -2};
static constexpr wq_config_t SPI2{"wq:SPI2", 2496, -3};
static constexpr wq_config_t SPI3{"wq:SPI3", 2496, -4};
static constexpr wq_config_t SPI4{"wq:SPI4", 2496, -5};
static constexpr wq_config_t SPI5{"wq:SPI5", 2496, -6};
static constexpr wq_config_t SPI6{"wq:SPI6", 2496, -7};
static constexpr wq_config_t I2C0{"wq:I2C0", 1472, -8};
static constexpr wq_config_t I2C1{"wq:I2C1", 1472, -9};
static constexpr wq_config_t I2C2{"wq:I2C2", 1472, -10};
static constexpr wq_config_t I2C3{"wq:I2C3", 1472, -11};
static constexpr wq_config_t I2C4{"wq:I2C4", 1472, -12};
// PX4 att/pos controllers, highest priority after sensors.
static constexpr wq_config_t attitude_ctrl{"wq:attitude_ctrl", 1632, -13};
static constexpr wq_config_t navigation_and_controllers{"wq:navigation_and_controllers", 7200, -14};
static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -15};
static constexpr wq_config_t uavcan{"wq:uavcan", 3000, -16};
static constexpr wq_config_t UART0{"wq:UART0", 1400, -17};
static constexpr wq_config_t UART1{"wq:UART1", 1400, -18};
static constexpr wq_config_t UART2{"wq:UART2", 1400, -19};
static constexpr wq_config_t UART3{"wq:UART3", 1400, -20};
static constexpr wq_config_t UART4{"wq:UART4", 1400, -21};
static constexpr wq_config_t UART5{"wq:UART5", 1400, -22};
static constexpr wq_config_t UART6{"wq:UART6", 1400, -23};
static constexpr wq_config_t UART7{"wq:UART7", 1400, -24};
static constexpr wq_config_t UART8{"wq:UART8", 1400, -25};
static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1400, -26};
static constexpr wq_config_t lp_default{"wq:lp_default", 1700, -50};
static constexpr wq_config_t test1{"wq:test1", 2000, 0};
static constexpr wq_config_t test2{"wq:test2", 2000, 0};
} // namespace wq_configurations
/**
* Start the work queue manager task.
*/
int WorkQueueManagerStart();
/**
* Stop the work queue manager task.
*/
int WorkQueueManagerStop();
/**
* Work queue manager status.
*/
int WorkQueueManagerStatus();
/**
* Create (or find) a work queue with a particular configuration.
*
* @param new_wq The work queue configuration (see WorkQueueManager.hpp).
* @return A pointer to the WorkQueue, or nullptr on failure.
*/
WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);
/**
* Map a PX4 driver device id to a work queue (by sensor bus).
*
* @param device_id The PX4 driver's device id.
* @return A work queue configuration.
*/
const wq_config_t &device_bus_to_wq(uint32_t device_id);
/**
* Map a serial device path (eg /dev/ttyS1) to a work queue.
*
* @param device_id The device path.
* @return A work queue configuration.
*/
const wq_config_t &serial_port_to_wq(const char *serial);
} // namespace px4
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013
* Alessio Sclocco <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <cmath>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::exception;
using std::ofstream;
using std::fixed;
using std::setprecision;
using std::numeric_limits;
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Folding.hpp>
#include <Timer.hpp>
using isa::utils::ArgumentList;
using isa::utils::toStringValue;
using isa::utils::Timer;
using AstroData::Observation;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using PulsarSearch::Folding;
typedef float dataType;
const string typeName("float");
const unsigned int maxThreadsPerBlock = 1024;
const unsigned int maxThreadsMultiplier = 512;
const unsigned int maxItemsPerThread = 256;
const unsigned int maxItemsMultiplier = 256;
const unsigned int padding = 32;
// Common parameters
const unsigned int nrBeams = 1;
const unsigned int nrStations = 64;
// LOFAR
/*const float minFreq = 138.965f;
const float channelBandwidth = 0.195f;
const unsigned int nrSamplesPerSecond = 200000;
const unsigned int nrChannels = 32;*/
// Apertif
const float minFreq = 1425.0f;
const float channelBandwidth = 0.2929f;
const unsigned int nrSamplesPerSecond = 20000;
const unsigned int nrChannels = 1024;
// Periods
const unsigned int nrBins = 256;
int main(int argc, char * argv[]) {
unsigned int lowerNrThreads = 0;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
Observation< dataType > observation("FoldingTuning", typeName);
CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true);
try {
ArgumentList args(argc, argv);
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms"));
lowerNrThreads = args.getSwitchArgument< unsigned int >("-lnt");
observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods"));
} catch ( exception & err ) {
cerr << err.what() << endl;
return 1;
}
// Setup of the observation
observation.setPadding(padding);
observation.setNrSamplesPerSecond(nrSamplesPerSecond);
observation.setNrBins(nrBins);
cl::Context * clContext = new cl::Context();
vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
vector< cl::Device > * clDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();
initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
cout << fixed << endl;
cout << "# nrDMs nrPeriods nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP/s err time err" << endl << endl;
// Allocate memory
dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
foldedData->blankHostData();
counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
counterData->blankHostData();
dedispersedData->setCLContext(clContext);
dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
foldedData->setCLContext(clContext);
foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
counterData->setCLContext(clContext);
counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
try {
dedispersedData->allocateDeviceData();
foldedData->allocateDeviceData();
foldedData->copyHostToDevice();
counterData->allocateDeviceData();
counterData->copyHostToDevice();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
}
// Find the parameters
vector< vector< unsigned int > > configurations;
for ( unsigned int DMsPerBlock = lowerNrThreads; DMsPerBlock <= maxThreadsPerBlock; DMsPerBlock++ ) {
if ( observation.getNrDMs() % DMsPerBlock != 0 ) {
continue;
}
for ( unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsMultiplier; periodsPerBlock++ ) {
if ( observation.getNrPeriods() % periodsPerBlock != 0 ) {
continue;
} else if ( DMsPerBlock * periodsPerBlock > maxThreadsPerBlock ) {
break;
}
for ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsMultiplier; binsPerBlock++ ) {
if ( observation.getNrBins() % binsPerBlock != 0 ) {
continue;
} else if ( DMsPerBlock * periodsPerBlock * binsPerBlock > maxThreadsPerBlock ) {
break;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {
if ( observation.getNrDMs() % (DMsPerBlock * DMsPerThread) != 0 ) {
continue;
}
for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsMultiplier; periodsPerThread++ ) {
if ( observation.getNrPeriods() % (periodsPerBlock * periodsPerThread) != 0 ) {
continue;
} else if ( DMsPerThread * periodsPerThread > maxItemsPerThread ) {
break;
}
for ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsMultiplier; binsPerThread++ ) {
if ( observation.getNrBins() % (binsPerBlock * binsPerThread) != 0 ) {
continue;
} else if ( DMsPerThread * periodsPerThread * binsPerThread > maxItemsPerThread ) {
break;
}
vector< unsigned int > parameters;
parameters.push_back(DMsPerBlock);
parameters.push_back(periodsPerBlock);
parameters.push_back(binsPerBlock);
parameters.push_back(DMsPerThread);
parameters.push_back(periodsPerThread);
parameters.push_back(binsPerThread);
configurations.push_back(parameters);
}
}
}
}
}
}
for ( vector< vector< unsigned int > >::const_iterator parameters = configurations.begin(); parameters != configurations.end(); parameters++ ) {
double Acur = 0.0;
double Aold = 0.0;
double Vcur = 0.0;
double Vold = 0.0;
try {
// Generate kernel
Folding< dataType > clFold("clFold", typeName);
clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
clFold.setObservation(&observation);
clFold.setNrDMsPerBlock((*parameters)[0]);
clFold.setNrPeriodsPerBlock((*parameters)[1]);
clFold.setNrBinsPerBlock((*parameters)[2]);
clFold.setNrDMsPerThread((*parameters)[3]);
clFold.setNrPeriodsPerThread((*parameters)[4]);
clFold.setNrBinsPerThread((*parameters)[5]);
clFold.generateCode();
clFold(dedispersedData, foldedData, counterData);
(clFold.getTimer()).reset();
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
clFold(dedispersedData, foldedData, counterData);
if ( iteration == 0 ) {
Acur = clFold.getGFLOP() / clFold.getTimer().getLastRunTime();
} else {
Aold = Acur;
Vold = Vcur;
Acur = Aold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) / (iteration + 1));
Vcur = Vold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) * ((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Acur));
}
}
Vcur = sqrt(Vcur / nrIterations);
cout << observation.getNrDMs() << " " << observation.getNrPeriods() << " " << (*parameters)[0] << " " << (*parameters)[1] << " " << (*parameters)[2] << " " << (*parameters)[3] << " " << (*parameters)[4] << " " << (*parameters)[5] << " " << setprecision(3) << Acur << " " << Vcur << " " << setprecision(6) << clFold.getTimer().getAverageTime() << " " << clFold.getTimer().getStdDev() << endl;
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
continue;
}
}
cout << endl;
return 0;
}
<commit_msg>Fixed the formula to compute the number of registers necessary.<commit_after>/*
* Copyright (C) 2013
* Alessio Sclocco <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <cmath>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::exception;
using std::ofstream;
using std::fixed;
using std::setprecision;
using std::numeric_limits;
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Folding.hpp>
#include <Timer.hpp>
using isa::utils::ArgumentList;
using isa::utils::toStringValue;
using isa::utils::Timer;
using AstroData::Observation;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using PulsarSearch::Folding;
typedef float dataType;
const string typeName("float");
const unsigned int maxThreadsPerBlock = 1024;
const unsigned int maxThreadsMultiplier = 512;
const unsigned int maxItemsPerThread = 256;
const unsigned int maxItemsMultiplier = 256;
const unsigned int padding = 32;
// Common parameters
const unsigned int nrBeams = 1;
const unsigned int nrStations = 64;
// LOFAR
/*const float minFreq = 138.965f;
const float channelBandwidth = 0.195f;
const unsigned int nrSamplesPerSecond = 200000;
const unsigned int nrChannels = 32;*/
// Apertif
const float minFreq = 1425.0f;
const float channelBandwidth = 0.2929f;
const unsigned int nrSamplesPerSecond = 20000;
const unsigned int nrChannels = 1024;
// Periods
const unsigned int nrBins = 256;
int main(int argc, char * argv[]) {
unsigned int lowerNrThreads = 0;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
Observation< dataType > observation("FoldingTuning", typeName);
CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true);
try {
ArgumentList args(argc, argv);
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms"));
lowerNrThreads = args.getSwitchArgument< unsigned int >("-lnt");
observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods"));
} catch ( exception & err ) {
cerr << err.what() << endl;
return 1;
}
// Setup of the observation
observation.setPadding(padding);
observation.setNrSamplesPerSecond(nrSamplesPerSecond);
observation.setNrBins(nrBins);
cl::Context * clContext = new cl::Context();
vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
vector< cl::Device > * clDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();
initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
cout << fixed << endl;
cout << "# nrDMs nrPeriods nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP/s err time err" << endl << endl;
// Allocate memory
dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
foldedData->blankHostData();
counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
counterData->blankHostData();
dedispersedData->setCLContext(clContext);
dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
foldedData->setCLContext(clContext);
foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
counterData->setCLContext(clContext);
counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
try {
dedispersedData->allocateDeviceData();
foldedData->allocateDeviceData();
foldedData->copyHostToDevice();
counterData->allocateDeviceData();
counterData->copyHostToDevice();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
}
// Find the parameters
vector< vector< unsigned int > > configurations;
for ( unsigned int DMsPerBlock = lowerNrThreads; DMsPerBlock <= maxThreadsPerBlock; DMsPerBlock++ ) {
if ( observation.getNrDMs() % DMsPerBlock != 0 ) {
continue;
}
for ( unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsMultiplier; periodsPerBlock++ ) {
if ( observation.getNrPeriods() % periodsPerBlock != 0 ) {
continue;
} else if ( DMsPerBlock * periodsPerBlock > maxThreadsPerBlock ) {
break;
}
for ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsMultiplier; binsPerBlock++ ) {
if ( observation.getNrBins() % binsPerBlock != 0 ) {
continue;
} else if ( DMsPerBlock * periodsPerBlock * binsPerBlock > maxThreadsPerBlock ) {
break;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {
if ( observation.getNrDMs() % (DMsPerBlock * DMsPerThread) != 0 ) {
continue;
}
for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsMultiplier; periodsPerThread++ ) {
if ( observation.getNrPeriods() % (periodsPerBlock * periodsPerThread) != 0 ) {
continue;
} else if ( (DMsPerThread + (2 * periodsPerThread)) + (2 * DMsPerThread * periodsPerThread) > maxItemsPerThread ) {
break;
}
for ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsMultiplier; binsPerThread++ ) {
if ( observation.getNrBins() % (binsPerBlock * binsPerThread) != 0 ) {
continue;
} else if ( (DMsPerThread + (2 * periodsPerThread) + binsPerThread) + (2 * DMsPerThread * periodsPerThread * binsPerThread) > maxItemsPerThread ) {
break;
}
vector< unsigned int > parameters;
parameters.push_back(DMsPerBlock);
parameters.push_back(periodsPerBlock);
parameters.push_back(binsPerBlock);
parameters.push_back(DMsPerThread);
parameters.push_back(periodsPerThread);
parameters.push_back(binsPerThread);
configurations.push_back(parameters);
}
}
}
}
}
}
for ( vector< vector< unsigned int > >::const_iterator parameters = configurations.begin(); parameters != configurations.end(); parameters++ ) {
double Acur = 0.0;
double Aold = 0.0;
double Vcur = 0.0;
double Vold = 0.0;
try {
// Generate kernel
Folding< dataType > clFold("clFold", typeName);
clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
clFold.setObservation(&observation);
clFold.setNrDMsPerBlock((*parameters)[0]);
clFold.setNrPeriodsPerBlock((*parameters)[1]);
clFold.setNrBinsPerBlock((*parameters)[2]);
clFold.setNrDMsPerThread((*parameters)[3]);
clFold.setNrPeriodsPerThread((*parameters)[4]);
clFold.setNrBinsPerThread((*parameters)[5]);
clFold.generateCode();
clFold(dedispersedData, foldedData, counterData);
(clFold.getTimer()).reset();
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
clFold(dedispersedData, foldedData, counterData);
if ( iteration == 0 ) {
Acur = clFold.getGFLOP() / clFold.getTimer().getLastRunTime();
} else {
Aold = Acur;
Vold = Vcur;
Acur = Aold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) / (iteration + 1));
Vcur = Vold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) * ((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Acur));
}
}
Vcur = sqrt(Vcur / nrIterations);
cout << observation.getNrDMs() << " " << observation.getNrPeriods() << " " << (*parameters)[0] << " " << (*parameters)[1] << " " << (*parameters)[2] << " " << (*parameters)[3] << " " << (*parameters)[4] << " " << (*parameters)[5] << " " << setprecision(3) << Acur << " " << Vcur << " " << setprecision(6) << clFold.getTimer().getAverageTime() << " " << clFold.getTimer().getStdDev() << endl;
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
continue;
}
}
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file rlp.cpp
* @author Gav Wood <[email protected]>
* @date 2014
* RLP test functions.
*/
#include <fstream>
#include <sstream>
#include <libdevcore/Log.h>
#include <libdevcore/RLP.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h>
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include "JsonSpiritHeaders.h"
using namespace std;
using namespace dev;
namespace js = json_spirit;
namespace dev
{
namespace test
{
static void buildRLP(js::mValue& _v, RLPStream& _rlp)
{
if (_v.type() == js::array_type)
{
RLPStream s;
for (auto& i: _v.get_array())
buildRLP(i, s);
_rlp.appendList(s.out());
}
else if (_v.type() == js::int_type)
_rlp.append(_v.get_uint64());
else if (_v.type() == js::str_type)
{
auto s = _v.get_str();
if (s.size() && s[0] == '#')
_rlp.append(bigint(s.substr(1)));
else
_rlp.append(s);
}
}
static void getRLPTestCases(js::mValue& v)
{
string s = asString(contents("../../../tests/rlptest.json"));
BOOST_REQUIRE_MESSAGE( s.length() > 0,
"Contents of 'rlptest.json' is empty. Have you cloned the 'tests' repo branch develop?");
js::read_string(s, v);
}
static void checkRLPTestCase(js::mObject& o)
{
BOOST_REQUIRE( o.count("in") > 0 );
BOOST_REQUIRE( o.count("out") > 0 );
BOOST_REQUIRE(!o["out"].is_null());
}
static void checkRLPAgainstJson(js::mValue& v, RLP& u)
{
if ( v.type() == js::str_type )
{
const std::string& expectedText = v.get_str();
if ( expectedText.front() == '#' )
{
// Deal with bigint instead of a raw string
std::string bigIntStr = expectedText.substr(1,expectedText.length()-1);
std::stringstream bintStream(bigIntStr);
bigint val;
bintStream >> val;
BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u ); // operator bool()
BOOST_CHECK(u == val);
}
else
{
BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u.isData() );
BOOST_CHECK( u );
BOOST_CHECK( u.size() == expectedText.length() );
BOOST_CHECK(u == expectedText);
}
}
else if ( v.type() == js::int_type )
{
const int expectedValue = v.get_int();
BOOST_CHECK( u.isInt() );
BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u ); // operator bool()
BOOST_CHECK(u == expectedValue);
}
else if ( v.type() == js::array_type )
{
BOOST_CHECK( u.isList() );
BOOST_CHECK( !u.isInt() );
BOOST_CHECK( !u.isData() );
js::mArray& arr = v.get_array();
BOOST_CHECK( u.itemCount() == arr.size() );
unsigned i;
for( i = 0; i < arr.size(); i++ )
{
RLP item = u[i];
checkRLPAgainstJson(arr[i], item);
}
}
else
{
BOOST_ERROR("Invalid Javascript object!");
}
}
}
}
BOOST_AUTO_TEST_CASE(rlp_encoding_test)
{
cnote << "Testing RLP Encoding...";
js::mValue v;
dev::test::getRLPTestCases(v);
for (auto& i: v.get_obj())
{
js::mObject& o = i.second.get_obj();
cnote << i.first;
dev::test::checkRLPTestCase(o);
RLPStream s;
dev::test::buildRLP(o["in"], s);
std::string expectedText(o["out"].get_str());
std::transform(expectedText.begin(), expectedText.end(), expectedText.begin(), ::tolower );
const std::string& computedText = toHex(s.out());
std::stringstream msg;
msg << "Encoding Failed: expected: " << expectedText << std::endl;
msg << " But Computed: " << computedText;
BOOST_CHECK_MESSAGE(
expectedText == computedText,
msg.str()
);
}
}
BOOST_AUTO_TEST_CASE(rlp_decoding_test)
{
cnote << "Testing RLP decoding...";
// Uses the same test cases as encoding but in reverse.
// We read into the string of hex values, convert to bytes,
// and then compare the output structure to the json of the
// input object.
js::mValue v;
dev::test::getRLPTestCases(v);
for (auto& i: v.get_obj())
{
js::mObject& o = i.second.get_obj();
cnote << i.first;
dev::test::checkRLPTestCase(o);
js::mValue& inputData = o["in"];
bytes payloadToDecode = fromHex(o["out"].get_str());
RLP payload(payloadToDecode);
dev::test::checkRLPAgainstJson(inputData, payload);
}
}
<commit_msg>test/rlp bugfix: expectedText can be empty<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file rlp.cpp
* @author Gav Wood <[email protected]>
* @date 2014
* RLP test functions.
*/
#include <fstream>
#include <sstream>
#include <libdevcore/Log.h>
#include <libdevcore/RLP.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h>
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include "JsonSpiritHeaders.h"
using namespace std;
using namespace dev;
namespace js = json_spirit;
namespace dev
{
namespace test
{
static void buildRLP(js::mValue& _v, RLPStream& _rlp)
{
if (_v.type() == js::array_type)
{
RLPStream s;
for (auto& i: _v.get_array())
buildRLP(i, s);
_rlp.appendList(s.out());
}
else if (_v.type() == js::int_type)
_rlp.append(_v.get_uint64());
else if (_v.type() == js::str_type)
{
auto s = _v.get_str();
if (s.size() && s[0] == '#')
_rlp.append(bigint(s.substr(1)));
else
_rlp.append(s);
}
}
static void getRLPTestCases(js::mValue& v)
{
string s = asString(contents("../../../tests/rlptest.json"));
BOOST_REQUIRE_MESSAGE( s.length() > 0,
"Contents of 'rlptest.json' is empty. Have you cloned the 'tests' repo branch develop?");
js::read_string(s, v);
}
static void checkRLPTestCase(js::mObject& o)
{
BOOST_REQUIRE( o.count("in") > 0 );
BOOST_REQUIRE( o.count("out") > 0 );
BOOST_REQUIRE(!o["out"].is_null());
}
static void checkRLPAgainstJson(js::mValue& v, RLP& u)
{
if ( v.type() == js::str_type )
{
const std::string& expectedText = v.get_str();
if ( !expectedText.empty() && expectedText.front() == '#' )
{
// Deal with bigint instead of a raw string
std::string bigIntStr = expectedText.substr(1,expectedText.length()-1);
std::stringstream bintStream(bigIntStr);
bigint val;
bintStream >> val;
BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u ); // operator bool()
BOOST_CHECK(u == val);
}
else
{
BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u.isData() );
BOOST_CHECK( u );
BOOST_CHECK( u.size() == expectedText.length() );
BOOST_CHECK(u == expectedText);
}
}
else if ( v.type() == js::int_type )
{
const int expectedValue = v.get_int();
BOOST_CHECK( u.isInt() );
BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u ); // operator bool()
BOOST_CHECK(u == expectedValue);
}
else if ( v.type() == js::array_type )
{
BOOST_CHECK( u.isList() );
BOOST_CHECK( !u.isInt() );
BOOST_CHECK( !u.isData() );
js::mArray& arr = v.get_array();
BOOST_CHECK( u.itemCount() == arr.size() );
unsigned i;
for( i = 0; i < arr.size(); i++ )
{
RLP item = u[i];
checkRLPAgainstJson(arr[i], item);
}
}
else
{
BOOST_ERROR("Invalid Javascript object!");
}
}
}
}
BOOST_AUTO_TEST_CASE(rlp_encoding_test)
{
cnote << "Testing RLP Encoding...";
js::mValue v;
dev::test::getRLPTestCases(v);
for (auto& i: v.get_obj())
{
js::mObject& o = i.second.get_obj();
cnote << i.first;
dev::test::checkRLPTestCase(o);
RLPStream s;
dev::test::buildRLP(o["in"], s);
std::string expectedText(o["out"].get_str());
std::transform(expectedText.begin(), expectedText.end(), expectedText.begin(), ::tolower );
const std::string& computedText = toHex(s.out());
std::stringstream msg;
msg << "Encoding Failed: expected: " << expectedText << std::endl;
msg << " But Computed: " << computedText;
BOOST_CHECK_MESSAGE(
expectedText == computedText,
msg.str()
);
}
}
BOOST_AUTO_TEST_CASE(rlp_decoding_test)
{
cnote << "Testing RLP decoding...";
// Uses the same test cases as encoding but in reverse.
// We read into the string of hex values, convert to bytes,
// and then compare the output structure to the json of the
// input object.
js::mValue v;
dev::test::getRLPTestCases(v);
for (auto& i: v.get_obj())
{
js::mObject& o = i.second.get_obj();
cnote << i.first;
dev::test::checkRLPTestCase(o);
js::mValue& inputData = o["in"];
bytes payloadToDecode = fromHex(o["out"].get_str());
RLP payload(payloadToDecode);
dev::test::checkRLPAgainstJson(inputData, payload);
}
}
<|endoftext|> |
<commit_before>/*
flink.cpp
ࠧ 㭪権 ࠡ⪥ Link` - Hard&Sym
*/
/* Revision: 1.04 05.01.2001 $ */
/*
Modify:
05.01.2001 SVS
+ 㭪 GetSubstName - ॥堫 mix.cpp
+ 㭪 DelSubstDrive - 㤠 Subst ࠩ
05.01.2000 OT
- ᬥ⨪, - ன VC :)
04.01.2001 SVS
+ 誨 CreateJunctionPoint, DeleteJunctionPoint
+ GetJunctionPointInfo - Junc
03.01.2001 SVS
! 뤥 ⢥ ᠬ⥫쭮
+ GetNumberOfLinks MkLink ॥堫 mix.cpp
*/
#include "headers.hpp"
#pragma hdrstop
#include "internalheaders.hpp"
//#if defined(__BORLANDC__)
// current thread's ANSI code page
#define CP_THREAD_ACP 3
#define MAXIMUM_REPARSE_DATA_BUFFER_SIZE ( 16 * 1024 )
// Predefined reparse tags.
// These tags need to avoid conflicting with IO_REMOUNT defined in ntos\inc\io.h
#define IO_REPARSE_TAG_RESERVED_ZERO (0)
#define IO_REPARSE_TAG_RESERVED_ONE (1)
// The value of the following constant needs to satisfy the following conditions:
// (1) Be at least as large as the largest of the reserved tags.
// (2) Be strictly smaller than all the tags in use.
#define IO_REPARSE_TAG_RESERVED_RANGE IO_REPARSE_TAG_RESERVED_ONE
// The following constant represents the bits that are valid to use in
// reparse tags.
#define IO_REPARSE_TAG_VALID_VALUES (0xE000FFFF)
// Macro to determine whether a reparse tag is a valid tag.
#define IsReparseTagValid(_tag) ( \
!((_tag) & ~IO_REPARSE_TAG_VALID_VALUES) && \
((_tag) > IO_REPARSE_TAG_RESERVED_RANGE) \
)
#define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000
#define FSCTL_GET_REPARSE_POINT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
// REPARSE_DATA_BUFFER
//#endif
struct TMN_REPARSE_DATA_BUFFER
{
DWORD ReparseTag;
WORD ReparseDataLength;
WORD Reserved;
// IO_REPARSE_TAG_MOUNT_POINT specifics follow
WORD SubstituteNameOffset;
WORD SubstituteNameLength;
WORD PrintNameOffset;
WORD PrintNameLength;
WCHAR PathBuffer[1];
// Some helper functions
//BOOL Init(LPCSTR szJunctionPoint);
//BOOL Init(LPCWSTR wszJunctionPoint);
//int BytesForIoControl() const;
};
BOOL WINAPI CreateJunctionPoint(LPCTSTR szMountDir, LPCTSTR szDestDirArg)
{
return TRUE;
}
BOOL WINAPI DeleteJunctionPoint(LPCTSTR szDir)
{
return TRUE;
}
DWORD WINAPI GetJunctionPointInfo(LPCTSTR szMountDir,
LPTSTR szDestBuff,
DWORD dwBuffSize)
{
const DWORD FileAttr = GetFileAttributes(szMountDir);
if (FileAttr == 0xffffffff || !(FileAttr & FILE_ATTRIBUTE_REPARSE_POINT))
{
SetLastError(ERROR_PATH_NOT_FOUND);
return 0;
}
HANDLE hDir=CreateFile(szMountDir,GENERIC_READ|0,0,0,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,0);
if (hDir == INVALID_HANDLE_VALUE)
{
SetLastError(ERROR_PATH_NOT_FOUND);
return 0;
}
char szBuff[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
TMN_REPARSE_DATA_BUFFER& rdb = *(TMN_REPARSE_DATA_BUFFER*)szBuff;
DWORD dwBytesReturned;
if (!DeviceIoControl(hDir,
FSCTL_GET_REPARSE_POINT,
NULL,
0,
(LPVOID)&rdb,
MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
&dwBytesReturned,
0) ||
!IsReparseTagValid(rdb.ReparseTag))
{
CloseHandle(hDir);
return 0;
}
CloseHandle(hDir);
if (dwBuffSize < rdb.SubstituteNameLength / sizeof(TCHAR) + sizeof(TCHAR))
{
return rdb.SubstituteNameLength / sizeof(TCHAR) + sizeof(TCHAR);
}
#ifdef UNICODE
lstrcpy(szDestBuff, rdb.PathBuffer);
#else
if (!WideCharToMultiByte(CP_THREAD_ACP,
0,
rdb.PathBuffer,
rdb.SubstituteNameLength / sizeof(WCHAR) + 1,
szDestBuff,
dwBuffSize,
"",
FALSE))
{
//printf("WideCharToMultiByte failed (%d)\n", GetLastError());
return 0;
}
#endif
return rdb.SubstituteNameLength / sizeof(TCHAR);
}
/* $ 07.09.2000 SVS
㭪 GetNumberOfLinks ⮦ 㯭 :-)
*/
int WINAPI GetNumberOfLinks(char *Name)
{
HANDLE hFile=CreateFile(Name,0,FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,OPEN_EXISTING,0,NULL);
if (hFile==INVALID_HANDLE_VALUE)
return(1);
BY_HANDLE_FILE_INFORMATION bhfi;
int GetCode=GetFileInformationByHandle(hFile,&bhfi);
CloseHandle(hFile);
return(GetCode ? bhfi.nNumberOfLinks:0);
}
/* SVS $*/
#if defined(__BORLANDC__)
#pragma option -a4
#endif
int WINAPI MkLink(char *Src,char *Dest)
{
struct CORRECTED_WIN32_STREAM_ID
{
DWORD dwStreamId ;
DWORD dwStreamAttributes ;
LARGE_INTEGER Size ;
DWORD dwStreamNameSize ;
WCHAR cStreamName[ ANYSIZE_ARRAY ] ;
} StreamId;
char FileSource[NM],FileDest[NM];
WCHAR FileLink[NM];
HANDLE hFileSource;
DWORD dwBytesWritten;
LPVOID lpContext;
DWORD cbPathLen;
DWORD StreamSize;
BOOL bSuccess;
// ConvertNameToFull(Src,FileSource, sizeof(FileSource));
if (ConvertNameToFull(Src,FileSource, sizeof(FileSource)) >= sizeof(FileSource)){
return FALSE;
}
// ConvertNameToFull(Dest,FileDest, sizeof(FileDest));
if (ConvertNameToFull(Dest,FileDest, sizeof(FileDest)) >= sizeof(FileDest)){
return FALSE;
}
MultiByteToWideChar(CP_OEMCP,0,FileDest,-1,FileLink,sizeof(FileLink)/sizeof(FileLink[0]));
hFileSource = CreateFile(FileSource,FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
if(hFileSource == INVALID_HANDLE_VALUE)
return(FALSE);
lpContext = NULL;
cbPathLen = (lstrlenW(FileLink) + 1) * sizeof(WCHAR);
StreamId.dwStreamId = BACKUP_LINK;
StreamId.dwStreamAttributes = 0;
StreamId.dwStreamNameSize = 0;
StreamId.Size.u.HighPart = 0;
StreamId.Size.u.LowPart = cbPathLen;
StreamSize=sizeof(StreamId)-sizeof(WCHAR **)+StreamId.dwStreamNameSize;
bSuccess = BackupWrite(hFileSource,(LPBYTE)&StreamId,StreamSize,
&dwBytesWritten,FALSE,FALSE,&lpContext);
int LastError=0;
if (bSuccess)
{
bSuccess = BackupWrite(hFileSource,(LPBYTE)FileLink,cbPathLen,
&dwBytesWritten,FALSE,FALSE,&lpContext);
if (!bSuccess)
LastError=GetLastError();
BackupWrite(hFileSource,NULL,0,&dwBytesWritten,TRUE,FALSE,&lpContext);
}
else
LastError=GetLastError();
CloseHandle(hFileSource);
if (LastError)
SetLastError(LastError);
return(bSuccess);
}
#if defined(__BORLANDC__)
#pragma option -a.
#endif
/* $ 05.01.2001 SVS
㭪 DelSubstDrive - 㤠 Subst ࠩ
Return: -1 - SUBST-ࠩ, OS .
0 - 㤠
1 - 訡 㤠.
*/
int DelSubstDrive(char *DosDeviceName)
{
if (WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT)
{
char NtDeviceName[512];
if (QueryDosDevice(DosDeviceName,NtDeviceName,sizeof(NtDeviceName))==0)
return(-1);
if (strncmp(NtDeviceName,"\\??\\",4)!=0)
return(-1);
return !DefineDosDevice(DDD_RAW_TARGET_PATH|
DDD_REMOVE_DEFINITION|
DDD_EXACT_MATCH_ON_REMOVE,
DosDeviceName, NtDeviceName)?1:0;
}
return(-1);
}
/* SVS $ */
BOOL GetSubstName(char *LocalName,char *SubstName,int SubstSize)
{
if (WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT)
{
char Name[512]="";
if (QueryDosDevice(LocalName,Name,sizeof(Name))==0)
return(FALSE);
if (strncmp(Name,"\\??\\",4)!=0)
return(FALSE);
strncpy(SubstName,Name+4,SubstSize);
return(TRUE);
}
return(FALSE);
}
<commit_msg>FAR patch 00404.SUBST_98 Дата : 25.01.2001 Сделал : Valentin Skirdin Описание : SUBST in Win98 Измененные файлы : flink.cpp Состав : 00404.SUBST_98.txt flink.cpp.404.diff Основан на патче : 403 Дополнение :<commit_after>/*
flink.cpp
ࠧ 㭪権 ࠡ⪥ Link` - Hard&Sym
*/
/* Revision: 1.05 25.01.2001 $ */
/*
Modify:
25.01.2001 SVS
! 㭪樨 GetSubstName DelSubstDrive ⥯ ଠ쭮 ࠡ
Windows98
05.01.2001 SVS
+ 㭪 GetSubstName - ॥堫 mix.cpp
+ 㭪 DelSubstDrive - 㤠 Subst ࠩ
05.01.2000 OT
- ᬥ⨪, - ன VC :)
04.01.2001 SVS
+ 誨 CreateJunctionPoint, DeleteJunctionPoint
+ GetJunctionPointInfo - Junc
03.01.2001 SVS
! 뤥 ⢥ ᠬ⥫쭮
+ GetNumberOfLinks MkLink ॥堫 mix.cpp
*/
#include "headers.hpp"
#pragma hdrstop
#include "internalheaders.hpp"
//#if defined(__BORLANDC__)
// current thread's ANSI code page
#define CP_THREAD_ACP 3
#define MAXIMUM_REPARSE_DATA_BUFFER_SIZE ( 16 * 1024 )
// Predefined reparse tags.
// These tags need to avoid conflicting with IO_REMOUNT defined in ntos\inc\io.h
#define IO_REPARSE_TAG_RESERVED_ZERO (0)
#define IO_REPARSE_TAG_RESERVED_ONE (1)
// The value of the following constant needs to satisfy the following conditions:
// (1) Be at least as large as the largest of the reserved tags.
// (2) Be strictly smaller than all the tags in use.
#define IO_REPARSE_TAG_RESERVED_RANGE IO_REPARSE_TAG_RESERVED_ONE
// The following constant represents the bits that are valid to use in
// reparse tags.
#define IO_REPARSE_TAG_VALID_VALUES (0xE000FFFF)
// Macro to determine whether a reparse tag is a valid tag.
#define IsReparseTagValid(_tag) ( \
!((_tag) & ~IO_REPARSE_TAG_VALID_VALUES) && \
((_tag) > IO_REPARSE_TAG_RESERVED_RANGE) \
)
#define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000
#define FSCTL_GET_REPARSE_POINT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
// REPARSE_DATA_BUFFER
//#endif
struct TMN_REPARSE_DATA_BUFFER
{
DWORD ReparseTag;
WORD ReparseDataLength;
WORD Reserved;
// IO_REPARSE_TAG_MOUNT_POINT specifics follow
WORD SubstituteNameOffset;
WORD SubstituteNameLength;
WORD PrintNameOffset;
WORD PrintNameLength;
WCHAR PathBuffer[1];
// Some helper functions
//BOOL Init(LPCSTR szJunctionPoint);
//BOOL Init(LPCWSTR wszJunctionPoint);
//int BytesForIoControl() const;
};
BOOL WINAPI CreateJunctionPoint(LPCTSTR szMountDir, LPCTSTR szDestDirArg)
{
return TRUE;
}
BOOL WINAPI DeleteJunctionPoint(LPCTSTR szDir)
{
return TRUE;
}
DWORD WINAPI GetJunctionPointInfo(LPCTSTR szMountDir,
LPTSTR szDestBuff,
DWORD dwBuffSize)
{
const DWORD FileAttr = GetFileAttributes(szMountDir);
if (FileAttr == 0xffffffff || !(FileAttr & FILE_ATTRIBUTE_REPARSE_POINT))
{
SetLastError(ERROR_PATH_NOT_FOUND);
return 0;
}
HANDLE hDir=CreateFile(szMountDir,GENERIC_READ|0,0,0,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,0);
if (hDir == INVALID_HANDLE_VALUE)
{
SetLastError(ERROR_PATH_NOT_FOUND);
return 0;
}
char szBuff[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
TMN_REPARSE_DATA_BUFFER& rdb = *(TMN_REPARSE_DATA_BUFFER*)szBuff;
DWORD dwBytesReturned;
if (!DeviceIoControl(hDir,
FSCTL_GET_REPARSE_POINT,
NULL,
0,
(LPVOID)&rdb,
MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
&dwBytesReturned,
0) ||
!IsReparseTagValid(rdb.ReparseTag))
{
CloseHandle(hDir);
return 0;
}
CloseHandle(hDir);
if (dwBuffSize < rdb.SubstituteNameLength / sizeof(TCHAR) + sizeof(TCHAR))
{
return rdb.SubstituteNameLength / sizeof(TCHAR) + sizeof(TCHAR);
}
#ifdef UNICODE
lstrcpy(szDestBuff, rdb.PathBuffer);
#else
if (!WideCharToMultiByte(CP_THREAD_ACP,
0,
rdb.PathBuffer,
rdb.SubstituteNameLength / sizeof(WCHAR) + 1,
szDestBuff,
dwBuffSize,
"",
FALSE))
{
//printf("WideCharToMultiByte failed (%d)\n", GetLastError());
return 0;
}
#endif
return rdb.SubstituteNameLength / sizeof(TCHAR);
}
/* $ 07.09.2000 SVS
㭪 GetNumberOfLinks ⮦ 㯭 :-)
*/
int WINAPI GetNumberOfLinks(char *Name)
{
HANDLE hFile=CreateFile(Name,0,FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,OPEN_EXISTING,0,NULL);
if (hFile==INVALID_HANDLE_VALUE)
return(1);
BY_HANDLE_FILE_INFORMATION bhfi;
int GetCode=GetFileInformationByHandle(hFile,&bhfi);
CloseHandle(hFile);
return(GetCode ? bhfi.nNumberOfLinks:0);
}
/* SVS $*/
#if defined(__BORLANDC__)
#pragma option -a4
#endif
int WINAPI MkLink(char *Src,char *Dest)
{
struct CORRECTED_WIN32_STREAM_ID
{
DWORD dwStreamId ;
DWORD dwStreamAttributes ;
LARGE_INTEGER Size ;
DWORD dwStreamNameSize ;
WCHAR cStreamName[ ANYSIZE_ARRAY ] ;
} StreamId;
char FileSource[NM],FileDest[NM];
WCHAR FileLink[NM];
HANDLE hFileSource;
DWORD dwBytesWritten;
LPVOID lpContext;
DWORD cbPathLen;
DWORD StreamSize;
BOOL bSuccess;
// ConvertNameToFull(Src,FileSource, sizeof(FileSource));
if (ConvertNameToFull(Src,FileSource, sizeof(FileSource)) >= sizeof(FileSource)){
return FALSE;
}
// ConvertNameToFull(Dest,FileDest, sizeof(FileDest));
if (ConvertNameToFull(Dest,FileDest, sizeof(FileDest)) >= sizeof(FileDest)){
return FALSE;
}
MultiByteToWideChar(CP_OEMCP,0,FileDest,-1,FileLink,sizeof(FileLink)/sizeof(FileLink[0]));
hFileSource = CreateFile(FileSource,FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
if(hFileSource == INVALID_HANDLE_VALUE)
return(FALSE);
lpContext = NULL;
cbPathLen = (lstrlenW(FileLink) + 1) * sizeof(WCHAR);
StreamId.dwStreamId = BACKUP_LINK;
StreamId.dwStreamAttributes = 0;
StreamId.dwStreamNameSize = 0;
StreamId.Size.u.HighPart = 0;
StreamId.Size.u.LowPart = cbPathLen;
StreamSize=sizeof(StreamId)-sizeof(WCHAR **)+StreamId.dwStreamNameSize;
bSuccess = BackupWrite(hFileSource,(LPBYTE)&StreamId,StreamSize,
&dwBytesWritten,FALSE,FALSE,&lpContext);
int LastError=0;
if (bSuccess)
{
bSuccess = BackupWrite(hFileSource,(LPBYTE)FileLink,cbPathLen,
&dwBytesWritten,FALSE,FALSE,&lpContext);
if (!bSuccess)
LastError=GetLastError();
BackupWrite(hFileSource,NULL,0,&dwBytesWritten,TRUE,FALSE,&lpContext);
}
else
LastError=GetLastError();
CloseHandle(hFileSource);
if (LastError)
SetLastError(LastError);
return(bSuccess);
}
#if defined(__BORLANDC__)
#pragma option -a.
#endif
/* $ 05.01.2001 SVS
㭪 DelSubstDrive - 㤠 Subst ࠩ
Return: -1 - SUBST-ࠩ, OS .
0 - 㤠
1 - 訡 㤠.
*/
int DelSubstDrive(char *DosDeviceName)
{
char NtDeviceName[512];
if(GetSubstName(DosDeviceName,NtDeviceName,sizeof(NtDeviceName)))
{
return !DefineDosDevice(DDD_RAW_TARGET_PATH|
DDD_REMOVE_DEFINITION|
DDD_EXACT_MATCH_ON_REMOVE,
DosDeviceName, NtDeviceName)?1:0;
}
return(-1);
}
/* SVS $ */
BOOL GetSubstName(char *LocalName,char *SubstName,int SubstSize)
{
char Name[NM*2]="";
LocalName=CharUpper((LPTSTR)LocalName);
if ((LocalName[0]>='A') && ((LocalName[0]<='Z')))
{
// , WIN98 !!!!
int SizeName=WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT?sizeof(Name):MAXPATH;
if (QueryDosDevice(LocalName,Name,SizeName) >= 3)
{
/* Subst drive format API differences:
* WinNT: \??\qualified_path (e.g. \??\C:\WinNT)
* Win98: qualified_path (e.g. C:\ or C:\Win98) */
if (WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT)
{
if (!strncmp(Name,"\\??\\",4))
{
strncpy(SubstName,Name+4,SubstSize);
return TRUE;
}
}
else
{
if(Name[1] == ':' && Name[2] == '\\')
{
strncpy(SubstName,Name,SubstSize);
return TRUE;
}
}
}
}
return FALSE;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/memory/scoped_ptr.h"
#include "base/rand_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/sessions/session_types.h"
#include "chrome/browser/sync/glue/synced_session_tracker.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace browser_sync {
typedef testing::Test SyncedSessionTrackerTest;
TEST_F(SyncedSessionTrackerTest, GetSession) {
SyncedSessionTracker tracker;
SyncedSession* session1 = tracker.GetSession("tag");
SyncedSession* session2 = tracker.GetSession("tag2");
ASSERT_EQ(session1, tracker.GetSession("tag"));
ASSERT_NE(session1, session2);
// Should clean up memory on it's own.
}
TEST_F(SyncedSessionTrackerTest, GetTabUnmapped) {
SyncedSessionTracker tracker;
SessionTab* tab = tracker.GetTab("tag", 0);
ASSERT_EQ(tab, tracker.GetTab("tag", 0));
// Should clean up memory on it's own.
}
TEST_F(SyncedSessionTrackerTest, PutWindowInSession) {
SyncedSessionTracker tracker;
tracker.PutWindowInSession("tag", 0);
SyncedSession* session = tracker.GetSession("tag");
ASSERT_EQ(1U, session->windows.size());
// Should clean up memory on it's own.
}
TEST_F(SyncedSessionTrackerTest, PutTabInWindow) {
SyncedSessionTracker tracker;
tracker.PutWindowInSession("tag", 10);
tracker.PutTabInWindow("tag", 10, 15, 0); // win id 10, tab id 15, tab ind 0.
SyncedSession* session = tracker.GetSession("tag");
ASSERT_EQ(1U, session->windows.size());
ASSERT_EQ(1U, session->windows[10]->tabs.size());
ASSERT_EQ(tracker.GetTab("tag", 15), session->windows[10]->tabs[0]);
// Should clean up memory on it's own.
}
TEST_F(SyncedSessionTrackerTest, LookupAllForeignSessions) {
SyncedSessionTracker tracker;
std::vector<const SyncedSession*> sessions;
ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions));
tracker.GetSession("tag1");
tracker.GetSession("tag2");
tracker.PutWindowInSession("tag1", 0);
tracker.PutTabInWindow("tag1", 0, 15, 0);
SessionTab* tab = tracker.GetTab("tag1", 15);
ASSERT_TRUE(tab);
tab->navigations.push_back(TabNavigation(
0, GURL("valid_url"), GURL("referrer"),
string16(ASCIIToUTF16("title")),
std::string("state"), content::PageTransitionFromInt(0)));
ASSERT_TRUE(tracker.LookupAllForeignSessions(&sessions));
// Only the session with a valid window and tab gets returned.
ASSERT_EQ(1U, sessions.size());
ASSERT_EQ("tag1", sessions[0]->session_tag);
}
TEST_F(SyncedSessionTrackerTest, LookupSessionWindows) {
SyncedSessionTracker tracker;
std::vector<const SessionWindow*> windows;
ASSERT_FALSE(tracker.LookupSessionWindows("tag1", &windows));
tracker.GetSession("tag1");
tracker.PutWindowInSession("tag1", 0);
tracker.PutWindowInSession("tag1", 2);
tracker.GetSession("tag2");
tracker.PutWindowInSession("tag2", 0);
tracker.PutWindowInSession("tag2", 2);
ASSERT_TRUE(tracker.LookupSessionWindows("tag1", &windows));
ASSERT_EQ(2U, windows.size()); // Only windows from tag1 session.
ASSERT_NE((SessionWindow*)NULL, windows[0]);
ASSERT_NE((SessionWindow*)NULL, windows[1]);
ASSERT_NE(windows[1], windows[0]);
}
TEST_F(SyncedSessionTrackerTest, LookupSessionTab) {
SyncedSessionTracker tracker;
const SessionTab* tab;
ASSERT_FALSE(tracker.LookupSessionTab("tag1", 5, &tab));
tracker.GetSession("tag1");
tracker.PutWindowInSession("tag1", 0);
tracker.PutTabInWindow("tag1", 0, 5, 0);
ASSERT_TRUE(tracker.LookupSessionTab("tag1", 5, &tab));
ASSERT_NE((SessionTab*)NULL, tab);
}
TEST_F(SyncedSessionTrackerTest, Complex) {
const std::string tag1 = "tag";
const std::string tag2 = "tag2";
const std::string tag3 = "tag3";
SyncedSessionTracker tracker;
std::vector<SessionTab*> tabs1, tabs2;
SessionTab* temp_tab;
ASSERT_TRUE(tracker.Empty());
ASSERT_EQ(0U, tracker.num_synced_sessions());
ASSERT_EQ(0U, tracker.num_synced_tabs(tag1));
tabs1.push_back(tracker.GetTab(tag1, 0));
tabs1.push_back(tracker.GetTab(tag1, 1));
tabs1.push_back(tracker.GetTab(tag1, 2));
ASSERT_EQ(3U, tracker.num_synced_tabs(tag1));
ASSERT_EQ(0U, tracker.num_synced_sessions());
temp_tab = tracker.GetTab(tag1, 0); // Already created.
ASSERT_EQ(3U, tracker.num_synced_tabs(tag1));
ASSERT_EQ(0U, tracker.num_synced_sessions());
ASSERT_EQ(tabs1[0], temp_tab);
tabs2.push_back(tracker.GetTab(tag2, 0));
ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));
ASSERT_EQ(0U, tracker.num_synced_sessions());
ASSERT_FALSE(tracker.DeleteSession(tag3));
SyncedSession* session = tracker.GetSession(tag1);
SyncedSession* session2 = tracker.GetSession(tag2);
SyncedSession* session3 = tracker.GetSession(tag3);
ASSERT_EQ(3U, tracker.num_synced_sessions());
ASSERT_TRUE(session);
ASSERT_TRUE(session2);
ASSERT_TRUE(session3);
ASSERT_NE(session, session2);
ASSERT_NE(session2, session3);
ASSERT_TRUE(tracker.DeleteSession(tag3));
ASSERT_EQ(2U, tracker.num_synced_sessions());
tracker.PutWindowInSession(tag1, 0); // Create a window.
tracker.PutTabInWindow(tag1, 0, 2, 0); // No longer unmapped.
ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); // Has not changed.
const SessionTab *tab_ptr;
ASSERT_TRUE(tracker.LookupSessionTab(tag1, 0, &tab_ptr));
ASSERT_EQ(tab_ptr, tabs1[0]);
ASSERT_TRUE(tracker.LookupSessionTab(tag1, 2, &tab_ptr));
ASSERT_EQ(tab_ptr, tabs1[2]);
ASSERT_FALSE(tracker.LookupSessionTab(tag1, 3, &tab_ptr));
ASSERT_EQ(static_cast<const SessionTab*>(NULL), tab_ptr);
std::vector<const SessionWindow*> windows;
ASSERT_TRUE(tracker.LookupSessionWindows(tag1, &windows));
ASSERT_EQ(1U, windows.size());
ASSERT_TRUE(tracker.LookupSessionWindows(tag2, &windows));
ASSERT_EQ(0U, windows.size());
// The sessions don't have valid tabs, lookup should not succeed.
std::vector<const SyncedSession*> sessions;
ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions));
tracker.Clear();
ASSERT_EQ(0U, tracker.num_synced_tabs(tag1));
ASSERT_EQ(0U, tracker.num_synced_tabs(tag2));
ASSERT_EQ(0U, tracker.num_synced_sessions());
}
TEST_F(SyncedSessionTrackerTest, ManyGetTabs) {
SyncedSessionTracker tracker;
ASSERT_TRUE(tracker.Empty());
const int kMaxSessions = 10;
const int kMaxTabs = 1000;
const int kMaxAttempts = 10000;
for (int j=0; j<kMaxSessions; ++j) {
std::string tag = "tag" + j;
for (int i=0; i<kMaxAttempts; ++i) {
// More attempts than tabs means we'll sometimes get the same tabs,
// sometimes have to allocate new tabs.
int rand_tab_num = base::RandInt(0, kMaxTabs);
SessionTab* tab = tracker.GetTab(tag, rand_tab_num);
ASSERT_TRUE(tab);
}
}
}
TEST_F(SyncedSessionTrackerTest, SessionTracking) {
SyncedSessionTracker tracker;
ASSERT_TRUE(tracker.Empty());
std::string tag1 = "tag1";
std::string tag2 = "tag2";
// Create some session information that is stale.
SyncedSession* session1= tracker.GetSession(tag1);
tracker.PutWindowInSession(tag1, 0);
tracker.PutTabInWindow(tag1, 0, 0, 0);
tracker.PutTabInWindow(tag1, 0, 1, 1);
tracker.GetTab(tag1, 2)->window_id.set_id(0); // Will be an unmapped tab.
tracker.GetTab(tag1, 3)->window_id.set_id(0); // Will be an unmapped tab.
tracker.PutWindowInSession(tag1, 1);
tracker.PutTabInWindow(tag1, 1, 4, 0);
tracker.PutTabInWindow(tag1, 1, 5, 1);
ASSERT_EQ(2U, session1->windows.size());
ASSERT_EQ(2U, session1->windows[0]->tabs.size());
ASSERT_EQ(2U, session1->windows[1]->tabs.size());
ASSERT_EQ(6U, tracker.num_synced_tabs(tag1));
// Create a session that should not be affected.
SyncedSession* session2 = tracker.GetSession(tag2);
tracker.PutWindowInSession(tag2, 2);
tracker.PutTabInWindow(tag2, 2, 1, 0);
ASSERT_EQ(1U, session2->windows.size());
ASSERT_EQ(1U, session2->windows[2]->tabs.size());
ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));
// Reset tracking and get the current windows/tabs.
// We simulate moving a tab from one window to another, then closing the first
// window (including it's one remaining tab), and opening a new tab on the
// remaining window.
tracker.GetTab(tag1, 6); // New tab, arrived before meta node so unmapped.
tracker.ResetSessionTracking(tag1);
tracker.PutWindowInSession(tag1, 0);
tracker.PutTabInWindow(tag1, 0, 0, 0);
// Tab 1 is closed.
tracker.PutTabInWindow(tag1, 0, 2, 1); // No longer unmapped.
// Tab 3 was unmapped and does not get used.
tracker.PutTabInWindow(tag1, 0, 4, 2); // Moved from window 1.
// Window 1 was closed, along with tab 5.
tracker.PutTabInWindow(tag1, 0, 6, 3); // No longer unmapped.
// Session 2 should not be affected.
tracker.CleanupSession(tag1);
// Verify that only those parts of the session not owned have been removed.
ASSERT_EQ(1U, session1->windows.size());
ASSERT_EQ(4U, session1->windows[0]->tabs.size());
ASSERT_EQ(1U, session2->windows.size());
ASSERT_EQ(1U, session2->windows[2]->tabs.size());
ASSERT_EQ(2U, tracker.num_synced_sessions());
ASSERT_EQ(4U, tracker.num_synced_tabs(tag1));
ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));
// All memory should be properly deallocated by destructor for the
// SyncedSessionTracker.
}
} // namespace browser_sync
<commit_msg>Use base::StringPrintf to fix SyncedSessionTrackerTest.ManyGetTabs under AddressSanitizer Review URL: http://codereview.chromium.org/8492009<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/memory/scoped_ptr.h"
#include "base/rand_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/sessions/session_types.h"
#include "chrome/browser/sync/glue/synced_session_tracker.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace browser_sync {
typedef testing::Test SyncedSessionTrackerTest;
TEST_F(SyncedSessionTrackerTest, GetSession) {
SyncedSessionTracker tracker;
SyncedSession* session1 = tracker.GetSession("tag");
SyncedSession* session2 = tracker.GetSession("tag2");
ASSERT_EQ(session1, tracker.GetSession("tag"));
ASSERT_NE(session1, session2);
// Should clean up memory on it's own.
}
TEST_F(SyncedSessionTrackerTest, GetTabUnmapped) {
SyncedSessionTracker tracker;
SessionTab* tab = tracker.GetTab("tag", 0);
ASSERT_EQ(tab, tracker.GetTab("tag", 0));
// Should clean up memory on it's own.
}
TEST_F(SyncedSessionTrackerTest, PutWindowInSession) {
SyncedSessionTracker tracker;
tracker.PutWindowInSession("tag", 0);
SyncedSession* session = tracker.GetSession("tag");
ASSERT_EQ(1U, session->windows.size());
// Should clean up memory on it's own.
}
TEST_F(SyncedSessionTrackerTest, PutTabInWindow) {
SyncedSessionTracker tracker;
tracker.PutWindowInSession("tag", 10);
tracker.PutTabInWindow("tag", 10, 15, 0); // win id 10, tab id 15, tab ind 0.
SyncedSession* session = tracker.GetSession("tag");
ASSERT_EQ(1U, session->windows.size());
ASSERT_EQ(1U, session->windows[10]->tabs.size());
ASSERT_EQ(tracker.GetTab("tag", 15), session->windows[10]->tabs[0]);
// Should clean up memory on it's own.
}
TEST_F(SyncedSessionTrackerTest, LookupAllForeignSessions) {
SyncedSessionTracker tracker;
std::vector<const SyncedSession*> sessions;
ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions));
tracker.GetSession("tag1");
tracker.GetSession("tag2");
tracker.PutWindowInSession("tag1", 0);
tracker.PutTabInWindow("tag1", 0, 15, 0);
SessionTab* tab = tracker.GetTab("tag1", 15);
ASSERT_TRUE(tab);
tab->navigations.push_back(TabNavigation(
0, GURL("valid_url"), GURL("referrer"),
string16(ASCIIToUTF16("title")),
std::string("state"), content::PageTransitionFromInt(0)));
ASSERT_TRUE(tracker.LookupAllForeignSessions(&sessions));
// Only the session with a valid window and tab gets returned.
ASSERT_EQ(1U, sessions.size());
ASSERT_EQ("tag1", sessions[0]->session_tag);
}
TEST_F(SyncedSessionTrackerTest, LookupSessionWindows) {
SyncedSessionTracker tracker;
std::vector<const SessionWindow*> windows;
ASSERT_FALSE(tracker.LookupSessionWindows("tag1", &windows));
tracker.GetSession("tag1");
tracker.PutWindowInSession("tag1", 0);
tracker.PutWindowInSession("tag1", 2);
tracker.GetSession("tag2");
tracker.PutWindowInSession("tag2", 0);
tracker.PutWindowInSession("tag2", 2);
ASSERT_TRUE(tracker.LookupSessionWindows("tag1", &windows));
ASSERT_EQ(2U, windows.size()); // Only windows from tag1 session.
ASSERT_NE((SessionWindow*)NULL, windows[0]);
ASSERT_NE((SessionWindow*)NULL, windows[1]);
ASSERT_NE(windows[1], windows[0]);
}
TEST_F(SyncedSessionTrackerTest, LookupSessionTab) {
SyncedSessionTracker tracker;
const SessionTab* tab;
ASSERT_FALSE(tracker.LookupSessionTab("tag1", 5, &tab));
tracker.GetSession("tag1");
tracker.PutWindowInSession("tag1", 0);
tracker.PutTabInWindow("tag1", 0, 5, 0);
ASSERT_TRUE(tracker.LookupSessionTab("tag1", 5, &tab));
ASSERT_NE((SessionTab*)NULL, tab);
}
TEST_F(SyncedSessionTrackerTest, Complex) {
const std::string tag1 = "tag";
const std::string tag2 = "tag2";
const std::string tag3 = "tag3";
SyncedSessionTracker tracker;
std::vector<SessionTab*> tabs1, tabs2;
SessionTab* temp_tab;
ASSERT_TRUE(tracker.Empty());
ASSERT_EQ(0U, tracker.num_synced_sessions());
ASSERT_EQ(0U, tracker.num_synced_tabs(tag1));
tabs1.push_back(tracker.GetTab(tag1, 0));
tabs1.push_back(tracker.GetTab(tag1, 1));
tabs1.push_back(tracker.GetTab(tag1, 2));
ASSERT_EQ(3U, tracker.num_synced_tabs(tag1));
ASSERT_EQ(0U, tracker.num_synced_sessions());
temp_tab = tracker.GetTab(tag1, 0); // Already created.
ASSERT_EQ(3U, tracker.num_synced_tabs(tag1));
ASSERT_EQ(0U, tracker.num_synced_sessions());
ASSERT_EQ(tabs1[0], temp_tab);
tabs2.push_back(tracker.GetTab(tag2, 0));
ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));
ASSERT_EQ(0U, tracker.num_synced_sessions());
ASSERT_FALSE(tracker.DeleteSession(tag3));
SyncedSession* session = tracker.GetSession(tag1);
SyncedSession* session2 = tracker.GetSession(tag2);
SyncedSession* session3 = tracker.GetSession(tag3);
ASSERT_EQ(3U, tracker.num_synced_sessions());
ASSERT_TRUE(session);
ASSERT_TRUE(session2);
ASSERT_TRUE(session3);
ASSERT_NE(session, session2);
ASSERT_NE(session2, session3);
ASSERT_TRUE(tracker.DeleteSession(tag3));
ASSERT_EQ(2U, tracker.num_synced_sessions());
tracker.PutWindowInSession(tag1, 0); // Create a window.
tracker.PutTabInWindow(tag1, 0, 2, 0); // No longer unmapped.
ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); // Has not changed.
const SessionTab *tab_ptr;
ASSERT_TRUE(tracker.LookupSessionTab(tag1, 0, &tab_ptr));
ASSERT_EQ(tab_ptr, tabs1[0]);
ASSERT_TRUE(tracker.LookupSessionTab(tag1, 2, &tab_ptr));
ASSERT_EQ(tab_ptr, tabs1[2]);
ASSERT_FALSE(tracker.LookupSessionTab(tag1, 3, &tab_ptr));
ASSERT_EQ(static_cast<const SessionTab*>(NULL), tab_ptr);
std::vector<const SessionWindow*> windows;
ASSERT_TRUE(tracker.LookupSessionWindows(tag1, &windows));
ASSERT_EQ(1U, windows.size());
ASSERT_TRUE(tracker.LookupSessionWindows(tag2, &windows));
ASSERT_EQ(0U, windows.size());
// The sessions don't have valid tabs, lookup should not succeed.
std::vector<const SyncedSession*> sessions;
ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions));
tracker.Clear();
ASSERT_EQ(0U, tracker.num_synced_tabs(tag1));
ASSERT_EQ(0U, tracker.num_synced_tabs(tag2));
ASSERT_EQ(0U, tracker.num_synced_sessions());
}
TEST_F(SyncedSessionTrackerTest, ManyGetTabs) {
SyncedSessionTracker tracker;
ASSERT_TRUE(tracker.Empty());
const int kMaxSessions = 10;
const int kMaxTabs = 1000;
const int kMaxAttempts = 10000;
for (int j=0; j<kMaxSessions; ++j) {
std::string tag = base::StringPrintf("tag%d", j);
for (int i=0; i<kMaxAttempts; ++i) {
// More attempts than tabs means we'll sometimes get the same tabs,
// sometimes have to allocate new tabs.
int rand_tab_num = base::RandInt(0, kMaxTabs);
SessionTab* tab = tracker.GetTab(tag, rand_tab_num);
ASSERT_TRUE(tab);
}
}
}
TEST_F(SyncedSessionTrackerTest, SessionTracking) {
SyncedSessionTracker tracker;
ASSERT_TRUE(tracker.Empty());
std::string tag1 = "tag1";
std::string tag2 = "tag2";
// Create some session information that is stale.
SyncedSession* session1= tracker.GetSession(tag1);
tracker.PutWindowInSession(tag1, 0);
tracker.PutTabInWindow(tag1, 0, 0, 0);
tracker.PutTabInWindow(tag1, 0, 1, 1);
tracker.GetTab(tag1, 2)->window_id.set_id(0); // Will be an unmapped tab.
tracker.GetTab(tag1, 3)->window_id.set_id(0); // Will be an unmapped tab.
tracker.PutWindowInSession(tag1, 1);
tracker.PutTabInWindow(tag1, 1, 4, 0);
tracker.PutTabInWindow(tag1, 1, 5, 1);
ASSERT_EQ(2U, session1->windows.size());
ASSERT_EQ(2U, session1->windows[0]->tabs.size());
ASSERT_EQ(2U, session1->windows[1]->tabs.size());
ASSERT_EQ(6U, tracker.num_synced_tabs(tag1));
// Create a session that should not be affected.
SyncedSession* session2 = tracker.GetSession(tag2);
tracker.PutWindowInSession(tag2, 2);
tracker.PutTabInWindow(tag2, 2, 1, 0);
ASSERT_EQ(1U, session2->windows.size());
ASSERT_EQ(1U, session2->windows[2]->tabs.size());
ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));
// Reset tracking and get the current windows/tabs.
// We simulate moving a tab from one window to another, then closing the first
// window (including it's one remaining tab), and opening a new tab on the
// remaining window.
tracker.GetTab(tag1, 6); // New tab, arrived before meta node so unmapped.
tracker.ResetSessionTracking(tag1);
tracker.PutWindowInSession(tag1, 0);
tracker.PutTabInWindow(tag1, 0, 0, 0);
// Tab 1 is closed.
tracker.PutTabInWindow(tag1, 0, 2, 1); // No longer unmapped.
// Tab 3 was unmapped and does not get used.
tracker.PutTabInWindow(tag1, 0, 4, 2); // Moved from window 1.
// Window 1 was closed, along with tab 5.
tracker.PutTabInWindow(tag1, 0, 6, 3); // No longer unmapped.
// Session 2 should not be affected.
tracker.CleanupSession(tag1);
// Verify that only those parts of the session not owned have been removed.
ASSERT_EQ(1U, session1->windows.size());
ASSERT_EQ(4U, session1->windows[0]->tabs.size());
ASSERT_EQ(1U, session2->windows.size());
ASSERT_EQ(1U, session2->windows[2]->tabs.size());
ASSERT_EQ(2U, tracker.num_synced_sessions());
ASSERT_EQ(4U, tracker.num_synced_tabs(tag1));
ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));
// All memory should be properly deallocated by destructor for the
// SyncedSessionTracker.
}
} // namespace browser_sync
<|endoftext|> |
<commit_before>// @(#)root/meta:$Name: $:$Id: GenericClassInfo.cxx,v 1.1 2002/05/09 20:53:21 brun Exp $
// Author: Philippe Canal 08/05/2002
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Rtypes.h"
#include "TNamed.h"
#include "TClass.h"
namespace ROOT {
const InitBehavior *DefineBehavior(void * /*parent_type*/,
void * /*actual_type*/)
{
// This function loads the default behavior for the
// loading of classes.
static DefaultInitBehavior theDefault;
return &theDefault;
}
GenericClassInfo::GenericClassInfo(const char *fullClassname,
const char *declFileName, Int_t declFileLine,
const type_info &info, const InitBehavior *action,
void *showmembers, VoidFuncPtr_t dictionary,
IsAFunc_t isa, Int_t pragmabits)
: fAction(action), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info), fIsA(isa), fShowMembers(showmembers),
fVersion(1)
{
Init(pragmabits);
}
GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const InitBehavior *action,
void* showmembers, VoidFuncPtr_t dictionary,
IsAFunc_t isa, Int_t pragmabits)
: fAction(action), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info), fIsA(isa), fShowMembers(showmembers),
fVersion(version)
{
Init(pragmabits);
}
GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const InitBehavior *action,
void* showmembers, VoidFuncPtr_t dictionary,
Int_t pragmabits)
: fAction(action), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info), fIsA(0), fShowMembers(showmembers),
fVersion(version)
{
Init(pragmabits);
}
GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const InitBehavior *action,
VoidFuncPtr_t dictionary,
Int_t pragmabits)
: fAction(action), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info), fIsA(0), fShowMembers(0),
fVersion(version)
{
Init(pragmabits);
}
void GenericClassInfo::Init(Int_t pragmabits)
{
if (!fAction) return;
GetAction().Register(fClassName,
fVersion,
fInfo, // typeid(RootClass),
fDictionary,
pragmabits);
}
GenericClassInfo::~GenericClassInfo()
{
if (fAction) GetAction().Unregister(GetClassName());
}
const InitBehavior &GenericClassInfo::GetAction() const
{
return *fAction;
}
TClass *GenericClassInfo::GetClass()
{
if (!fClass && fAction) {
fClass = GetAction().CreateClass(GetClassName(),
GetVersion(),
GetInfo(),
GetIsA(),
(ShowMembersFunc_t)GetShowMembers(),
GetDeclFileName(),
GetImplFileName(),
GetDeclFileLine(),
GetImplFileLine());
}
return fClass;
}
const char *GenericClassInfo::GetClassName() const
{
return fClassName;
}
const type_info &GenericClassInfo::GetInfo() const
{
return fInfo;
}
void *GenericClassInfo::GetShowMembers() const
{
return fShowMembers;
}
void GenericClassInfo::SetFromTemplate()
{
TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0);
if (info) SetImplFile(info->GetTitle(), info->GetUniqueID());
}
Int_t GenericClassInfo::SetImplFile(const char *file, Int_t line)
{
fImplFileName = file;
fImplFileLine = line;
if (fClass) fClass->AddImplFile(file,line);
return 0;
}
Short_t GenericClassInfo::SetVersion(Short_t version)
{
ROOT::ResetClassVersion(fClass, GetClassName(),version);
fVersion = version;
return version;
}
const char *GenericClassInfo::GetDeclFileName() const
{
return fDeclFileName;
}
Int_t GenericClassInfo::GetDeclFileLine() const
{
return fDeclFileLine;
}
const char *GenericClassInfo::GetImplFileName()
{
if (!fImplFileName) SetFromTemplate();
return fImplFileName;
}
Int_t GenericClassInfo::GetImplFileLine()
{
if (!fImplFileLine) SetFromTemplate();
return fImplFileLine;
}
Int_t GenericClassInfo::GetVersion() const
{
return fVersion;
}
TClass *GenericClassInfo::IsA(const void *obj)
{
return (GetIsA())(obj);
}
IsAFunc_t GenericClassInfo::GetIsA() const
{
return fIsA;
}
}
<commit_msg>In the GenericClassInfo destructor, return immediatly if gROOT is null. This case happens when the TROOT destructor itself is called. Without this protection, most programs crashed at the end.<commit_after>// @(#)root/meta:$Name: $:$Id: GenericClassInfo.cxx,v 1.2 2002/05/09 22:57:37 rdm Exp $
// Author: Philippe Canal 08/05/2002
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TClass.h"
namespace ROOT {
const InitBehavior *DefineBehavior(void * /*parent_type*/,
void * /*actual_type*/)
{
// This function loads the default behavior for the
// loading of classes.
static DefaultInitBehavior theDefault;
return &theDefault;
}
GenericClassInfo::GenericClassInfo(const char *fullClassname,
const char *declFileName, Int_t declFileLine,
const type_info &info, const InitBehavior *action,
void *showmembers, VoidFuncPtr_t dictionary,
IsAFunc_t isa, Int_t pragmabits)
: fAction(action), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info), fIsA(isa), fShowMembers(showmembers),
fVersion(1)
{
Init(pragmabits);
}
GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const InitBehavior *action,
void* showmembers, VoidFuncPtr_t dictionary,
IsAFunc_t isa, Int_t pragmabits)
: fAction(action), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info), fIsA(isa), fShowMembers(showmembers),
fVersion(version)
{
Init(pragmabits);
}
GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const InitBehavior *action,
void* showmembers, VoidFuncPtr_t dictionary,
Int_t pragmabits)
: fAction(action), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info), fIsA(0), fShowMembers(showmembers),
fVersion(version)
{
Init(pragmabits);
}
GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const InitBehavior *action,
VoidFuncPtr_t dictionary,
Int_t pragmabits)
: fAction(action), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info), fIsA(0), fShowMembers(0),
fVersion(version)
{
Init(pragmabits);
}
void GenericClassInfo::Init(Int_t pragmabits)
{
if (!fAction) return;
GetAction().Register(fClassName,
fVersion,
fInfo, // typeid(RootClass),
fDictionary,
pragmabits);
}
GenericClassInfo::~GenericClassInfo()
{
if (!gROOT) return;
if (fAction) GetAction().Unregister(GetClassName());
}
const InitBehavior &GenericClassInfo::GetAction() const
{
return *fAction;
}
TClass *GenericClassInfo::GetClass()
{
if (!fClass && fAction) {
fClass = GetAction().CreateClass(GetClassName(),
GetVersion(),
GetInfo(),
GetIsA(),
(ShowMembersFunc_t)GetShowMembers(),
GetDeclFileName(),
GetImplFileName(),
GetDeclFileLine(),
GetImplFileLine());
}
return fClass;
}
const char *GenericClassInfo::GetClassName() const
{
return fClassName;
}
const type_info &GenericClassInfo::GetInfo() const
{
return fInfo;
}
void *GenericClassInfo::GetShowMembers() const
{
return fShowMembers;
}
void GenericClassInfo::SetFromTemplate()
{
TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0);
if (info) SetImplFile(info->GetTitle(), info->GetUniqueID());
}
Int_t GenericClassInfo::SetImplFile(const char *file, Int_t line)
{
fImplFileName = file;
fImplFileLine = line;
if (fClass) fClass->AddImplFile(file,line);
return 0;
}
Short_t GenericClassInfo::SetVersion(Short_t version)
{
ROOT::ResetClassVersion(fClass, GetClassName(),version);
fVersion = version;
return version;
}
const char *GenericClassInfo::GetDeclFileName() const
{
return fDeclFileName;
}
Int_t GenericClassInfo::GetDeclFileLine() const
{
return fDeclFileLine;
}
const char *GenericClassInfo::GetImplFileName()
{
if (!fImplFileName) SetFromTemplate();
return fImplFileName;
}
Int_t GenericClassInfo::GetImplFileLine()
{
if (!fImplFileLine) SetFromTemplate();
return fImplFileLine;
}
Int_t GenericClassInfo::GetVersion() const
{
return fVersion;
}
TClass *GenericClassInfo::IsA(const void *obj)
{
return (GetIsA())(obj);
}
IsAFunc_t GenericClassInfo::GetIsA() const
{
return fIsA;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h"
#include "base/values.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/accessibility_util.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
// JS API callbacks names.
const char kJsApiScreenStateInitialize[] = "screenStateInitialize";
const char kJsApiToggleAccessibility[] = "toggleAccessibility";
} // namespace
namespace chromeos {
// Note that show_oobe_ui_ defaults to false because WizardController assumes
// OOBE UI is not visible by default.
CoreOobeHandler::CoreOobeHandler(OobeUI* oobe_ui)
: oobe_ui_(oobe_ui),
show_oobe_ui_(false),
version_info_updater_(this) {
}
CoreOobeHandler::~CoreOobeHandler() {
}
void CoreOobeHandler::GetLocalizedStrings(
base::DictionaryValue* localized_strings) {
localized_strings->SetString(
"productName", l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
}
void CoreOobeHandler::Initialize() {
UpdateOobeUIVisibility();
#if defined(OFFICIAL_BUILD)
version_info_updater_.StartUpdate(true);
#else
version_info_updater_.StartUpdate(false);
#endif
}
void CoreOobeHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback(kJsApiToggleAccessibility,
NewCallback(this, &CoreOobeHandler::OnToggleAccessibility));
web_ui_->RegisterMessageCallback(kJsApiScreenStateInitialize,
NewCallback(this, &CoreOobeHandler::OnInitialized));
}
void CoreOobeHandler::OnInitialized(const base::ListValue* args) {
oobe_ui_->InitializeHandlers();
}
void CoreOobeHandler::OnToggleAccessibility(const base::ListValue* args) {
accessibility::ToggleAccessibility(web_ui_);
}
void CoreOobeHandler::ShowOobeUI(bool show) {
if (show == show_oobe_ui_)
return;
show_oobe_ui_ = show;
if (page_is_ready())
UpdateOobeUIVisibility();
}
void CoreOobeHandler::UpdateOobeUIVisibility() {
base::FundamentalValue showValue(show_oobe_ui_);
web_ui_->CallJavascriptFunction("cr.ui.Oobe.showOobeUI", showValue);
}
void CoreOobeHandler::OnOSVersionLabelTextUpdated(
const std::string& os_version_label_text) {
UpdateLabel("version", os_version_label_text);
}
void CoreOobeHandler::OnBootTimesLabelTextUpdated(
const std::string& boot_times_label_text) {
UpdateLabel("boot-times", boot_times_label_text);
}
void CoreOobeHandler::UpdateLabel(const std::string& id,
const std::string& text) {
base::StringValue id_value(UTF8ToUTF16(id));
base::StringValue text_value(UTF8ToUTF16(text));
web_ui_->CallJavascriptFunction("cr.ui.Oobe.setLabelText",
id_value,
text_value);
}
} // namespace chromeos
<commit_msg>Add a title to the OOBE screen so that is doesn't say 'unknown'<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h"
#include "base/values.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/accessibility_util.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
// JS API callbacks names.
const char kJsApiScreenStateInitialize[] = "screenStateInitialize";
const char kJsApiToggleAccessibility[] = "toggleAccessibility";
} // namespace
namespace chromeos {
// Note that show_oobe_ui_ defaults to false because WizardController assumes
// OOBE UI is not visible by default.
CoreOobeHandler::CoreOobeHandler(OobeUI* oobe_ui)
: oobe_ui_(oobe_ui),
show_oobe_ui_(false),
version_info_updater_(this) {
}
CoreOobeHandler::~CoreOobeHandler() {
}
void CoreOobeHandler::GetLocalizedStrings(
base::DictionaryValue* localized_strings) {
localized_strings->SetString(
"title", l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
localized_strings->SetString(
"productName", l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
}
void CoreOobeHandler::Initialize() {
UpdateOobeUIVisibility();
#if defined(OFFICIAL_BUILD)
version_info_updater_.StartUpdate(true);
#else
version_info_updater_.StartUpdate(false);
#endif
}
void CoreOobeHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback(kJsApiToggleAccessibility,
NewCallback(this, &CoreOobeHandler::OnToggleAccessibility));
web_ui_->RegisterMessageCallback(kJsApiScreenStateInitialize,
NewCallback(this, &CoreOobeHandler::OnInitialized));
}
void CoreOobeHandler::OnInitialized(const base::ListValue* args) {
oobe_ui_->InitializeHandlers();
}
void CoreOobeHandler::OnToggleAccessibility(const base::ListValue* args) {
accessibility::ToggleAccessibility(web_ui_);
}
void CoreOobeHandler::ShowOobeUI(bool show) {
if (show == show_oobe_ui_)
return;
show_oobe_ui_ = show;
if (page_is_ready())
UpdateOobeUIVisibility();
}
void CoreOobeHandler::UpdateOobeUIVisibility() {
base::FundamentalValue showValue(show_oobe_ui_);
web_ui_->CallJavascriptFunction("cr.ui.Oobe.showOobeUI", showValue);
}
void CoreOobeHandler::OnOSVersionLabelTextUpdated(
const std::string& os_version_label_text) {
UpdateLabel("version", os_version_label_text);
}
void CoreOobeHandler::OnBootTimesLabelTextUpdated(
const std::string& boot_times_label_text) {
UpdateLabel("boot-times", boot_times_label_text);
}
void CoreOobeHandler::UpdateLabel(const std::string& id,
const std::string& text) {
base::StringValue id_value(UTF8ToUTF16(id));
base::StringValue text_value(UTF8ToUTF16(text));
web_ui_->CallJavascriptFunction("cr.ui.Oobe.setLabelText",
id_value,
text_value);
}
} // namespace chromeos
<|endoftext|> |
<commit_before>#ifndef COFFEE_MILL_COMMON_DEFERED_READER_HPP
#define COFFEE_MILL_COMMON_DEFERED_READER_HPP
#include <mill/common/Trajectory.hpp>
#include <string_view>
#include <optional>
#include <iterator>
#include <cstddef>
namespace mill
{
class DeferedReaderBase;
class ReaderIterator
{
public:
using iterator_category = std::input_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = Snapshot;
using reference = value_type&;
using pointer = value_type*;
public:
explicit ReaderIterator(DeferedReaderBase& reader)
: current_(std::nullopt), reader_(std::addressof(reader))
{}
const value_type& operator* () const
{
if(!current_) {current_ = reader_->read_frame();}
return *current_;
}
const value_type* operator->() const
{
if(!current_) {current_ = reader_->read_frame();}
return std::addressof(*current_);
}
ReaderIterator& operator++()
{
current_ = reader_->read_frame();
return *this;
}
ReaderIterator operator++(int)
{
current_ = reader_->read_frame();
return *this;
}
bool is_eof() const noexcept {return reader_->is_eof();}
std::size_t current() const noexcept {return reader_->current();}
std::string_view file_name() const noexcept {return reader_->file_name();}
private:
std::optional<value_type> current_;
DeferedReaderBase* reader_;
};
inline bool operator==(const ReaderIterator& lhs, const ReaderIterator& rhs)
{
return std::make_tuple(lhs->is_eof(), lhs->current(), lhs->file_name()) ==
std::make_tuple(lhs->is_eof(), lhs->current(), lhs->file_name());
}
inline bool operator!=(const ReaderIterator& lhs, const ReaderIterator& rhs)
{
return !(lhs == rhs);
}
class DeferedReaderBase
{
public:
using trajectory_type = Trajectory;
using snapshot_type = Snapshot;
using attribute_container_type = trajectory_type::attribute_container_type;
public:
attribute_container_type read_header() = 0;
trajectory_type read() = 0;
snapshot_type read_frame() = 0;
snapshot_type read_frame(const std::size_t idx) = 0;
bool is_eof() const noexcept = 0;
std::size_t current() const noexcept = 0;
std::string_view file_name() const noexcept = 0;
};
} // mill
#endif// COFFEE_MILL_COMMON_DEFERED_READER_HPP
<commit_msg>:sparkles: add ReaderIteratorSentinel<commit_after>#ifndef COFFEE_MILL_COMMON_DEFERED_READER_HPP
#define COFFEE_MILL_COMMON_DEFERED_READER_HPP
#include <mill/common/Trajectory.hpp>
#include <string_view>
#include <optional>
#include <iterator>
#include <cstddef>
namespace mill
{
class ReaderIterator;
class ReaderIteratorSentinel;
class DeferedReaderBase
{
public:
using trajectory_type = Trajectory;
using snapshot_type = Snapshot;
using attribute_container_type = trajectory_type::attribute_container_type;
public:
virtual ~DeferedReaderBase() = default;
virtual attribute_container_type read_header() = 0;
virtual trajectory_type read() = 0;
virtual snapshot_type read_frame() = 0;
virtual snapshot_type read_frame(const std::size_t idx) = 0;
ReaderIterator begin();
ReaderIteratorSentinel end();
virtual bool is_eof() const noexcept = 0;
virtual std::size_t current() const noexcept = 0;
virtual std::string_view file_name() const noexcept = 0;
};
class ReaderIterator
{
public:
using iterator_category = std::input_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = Snapshot;
using reference = value_type&;
using pointer = value_type*;
public:
explicit ReaderIterator(DeferedReaderBase& reader)
: current_(std::nullopt), reader_(std::addressof(reader))
{}
value_type& operator*()
{
if(!current_) {current_ = reader_->read_frame();}
return *current_;
}
value_type* operator->()
{
if(!current_) {current_ = reader_->read_frame();}
return std::addressof(*current_);
}
ReaderIterator& operator++()
{
current_ = reader_->read_frame();
return *this;
}
ReaderIterator operator++(int)
{
current_ = reader_->read_frame();
return *this;
}
bool is_eof() const noexcept {return reader_->is_eof();}
std::size_t current() const noexcept {return reader_->current();}
std::string_view file_name() const noexcept {return reader_->file_name();}
private:
std::optional<value_type> current_;
DeferedReaderBase* reader_;
};
inline bool operator==(const ReaderIterator& lhs, const ReaderIterator& rhs)
{
return std::make_tuple(lhs.is_eof(), lhs.current(), lhs.file_name()) ==
std::make_tuple(rhs.is_eof(), rhs.current(), rhs.file_name());
}
inline bool operator!=(const ReaderIterator& lhs, const ReaderIterator& rhs)
{
return !(lhs == rhs);
}
class ReaderIteratorSentinel
{
public:
using iterator_category = std::input_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = Snapshot;
using reference = value_type&;
using pointer = value_type*;
public:
explicit ReaderIteratorSentinel(DeferedReaderBase& reader)
: file_name_(reader.file_name())
{}
bool is_eof() const noexcept {return true;}
std::string_view file_name() const noexcept {return file_name_;}
private:
std::string_view file_name_;
};
inline bool operator==(
const ReaderIteratorSentinel& lhs, const ReaderIteratorSentinel& rhs)
{
return lhs.file_name() == rhs.file_name();
}
inline bool operator!=(
const ReaderIteratorSentinel& lhs, const ReaderIteratorSentinel& rhs)
{
return !(lhs == rhs);
}
inline bool operator==(const ReaderIterator& lhs, const ReaderIteratorSentinel& rhs)
{
return lhs.is_eof() && (lhs.file_name() == rhs.file_name());
}
inline bool operator==(const ReaderIteratorSentinel& lhs, const ReaderIterator& rhs)
{
return rhs.is_eof() && (lhs.file_name() == rhs.file_name());
}
inline ReaderIterator DeferedReaderBase::begin()
{
return ReaderIterator(*this);
}
inline ReaderIteratorSentinel DeferedReaderBase::end()
{
return ReaderIteratorSentinel(*this);
}
} // mill
#endif// COFFEE_MILL_COMMON_DEFERED_READER_HPP
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: parametricpolypolygonfactory.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-12-13 15:43:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
#include <canvas/debug.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>
#include "parametricpolypolygonfactory.hxx"
#include "barwipepolypolygon.hxx"
#include "boxwipe.hxx"
#include "fourboxwipe.hxx"
#include "barndoorwipe.hxx"
#include "doublediamondwipe.hxx"
#include "veewipe.hxx"
#include "iriswipe.hxx"
#include "ellipsewipe.hxx"
#include "checkerboardwipe.hxx"
#include "randomwipe.hxx"
#include "waterfallwipe.hxx"
#include "clockwipe.hxx"
#include "fanwipe.hxx"
#include "pinwheelwipe.hxx"
#include "snakewipe.hxx"
#include "spiralwipe.hxx"
#include "sweepwipe.hxx"
#include "figurewipe.hxx"
#include "zigzagwipe.hxx"
using namespace ::com::sun::star;
namespace slideshow
{
namespace internal
{
ParametricPolyPolygonSharedPtr
ParametricPolyPolygonFactory::createClipPolyPolygon(
sal_Int16 nType, sal_Int16 nSubType )
{
using namespace ::com::sun::star::animations::TransitionType;
using namespace ::com::sun::star::animations::TransitionSubType;
switch (nType)
{
case BARWIPE:
return ParametricPolyPolygonSharedPtr(
new BarWipePolyPolygon );
case BLINDSWIPE:
return ParametricPolyPolygonSharedPtr(
new BarWipePolyPolygon( 6 ) );
case BOXWIPE:
return ParametricPolyPolygonSharedPtr(
new BoxWipe( nSubType == LEFTCENTER ||
nSubType == TOPCENTER ||
nSubType == RIGHTCENTER||
nSubType == BOTTOMCENTER ) );
case FOURBOXWIPE:
return ParametricPolyPolygonSharedPtr(
new FourBoxWipe( nSubType == CORNERSOUT ) );
case BARNDOORWIPE:
return ParametricPolyPolygonSharedPtr(
new BarnDoorWipe );
case DIAGONALWIPE:
return ParametricPolyPolygonSharedPtr(
new BarWipePolyPolygon );
case VEEWIPE:
return ParametricPolyPolygonSharedPtr(
new VeeWipe );
case IRISWIPE:
return ParametricPolyPolygonSharedPtr(
new IrisWipe );
case ELLIPSEWIPE:
return ParametricPolyPolygonSharedPtr(
new EllipseWipe(nSubType) );
case CHECKERBOARDWIPE:
return ParametricPolyPolygonSharedPtr(
new CheckerBoardWipe );
case RANDOMBARWIPE:
return ParametricPolyPolygonSharedPtr(
new RandomWipe( 128, true /* bars */ ) );
case DISSOLVE:
return ParametricPolyPolygonSharedPtr(
new RandomWipe( 16 * 16, // for now until dxcanvas is faster
// 64 * 64 /* elements */,
false /* dissolve */ ) );
case WATERFALLWIPE:
return ParametricPolyPolygonSharedPtr(
new WaterfallWipe(
128,
// flipOnYAxis:
nSubType == VERTICALRIGHT ||
nSubType == HORIZONTALLEFT ) );
case CLOCKWIPE:
return ParametricPolyPolygonSharedPtr(
new ClockWipe );
case FANWIPE:
return ParametricPolyPolygonSharedPtr(
new FanWipe( // center:
nSubType == CENTERTOP ||
nSubType == CENTERRIGHT ) );
case PINWHEELWIPE: {
sal_Int32 blades;
switch (nSubType) {
case ONEBLADE:
blades = 1;
break;
case THREEBLADE:
blades = 3;
break;
case FOURBLADE:
blades = 4;
break;
case EIGHTBLADE:
blades = 8;
break;
default:
blades = 2;
break;
}
return ParametricPolyPolygonSharedPtr(
new PinWheelWipe( blades ) );
}
case SNAKEWIPE:
return ParametricPolyPolygonSharedPtr(
new SnakeWipe(
// elements:
64 * 64,
// diagonal:
nSubType == TOPLEFTDIAGONAL ||
nSubType == TOPRIGHTDIAGONAL ||
nSubType == BOTTOMRIGHTDIAGONAL ||
nSubType == BOTTOMLEFTDIAGONAL,
// flipOnYAxis:
nSubType == TOPLEFTVERTICAL ||
nSubType == TOPRIGHTDIAGONAL ||
nSubType == BOTTOMLEFTDIAGONAL
) );
case PARALLELSNAKESWIPE:
return ParametricPolyPolygonSharedPtr(
new ParallelSnakesWipe(
// elements:
64 * 64,
// diagonal:
nSubType == DIAGONALBOTTOMLEFTOPPOSITE ||
nSubType == DIAGONALTOPLEFTOPPOSITE,
// flipOnYAxis:
nSubType == VERTICALBOTTOMLEFTOPPOSITE ||
nSubType == HORIZONTALTOPLEFTOPPOSITE ||
nSubType == DIAGONALTOPLEFTOPPOSITE,
// opposite:
nSubType == VERTICALTOPLEFTOPPOSITE ||
nSubType == VERTICALBOTTOMLEFTOPPOSITE ||
nSubType == HORIZONTALTOPLEFTOPPOSITE ||
nSubType == HORIZONTALTOPRIGHTOPPOSITE ||
nSubType == DIAGONALBOTTOMLEFTOPPOSITE ||
nSubType == DIAGONALTOPLEFTOPPOSITE
) );
case SPIRALWIPE:
return ParametricPolyPolygonSharedPtr(
new SpiralWipe(
// elements:
64 * 64,
// flipOnYAxis:
nSubType == TOPLEFTCOUNTERCLOCKWISE ||
nSubType == TOPRIGHTCOUNTERCLOCKWISE ||
nSubType == BOTTOMRIGHTCOUNTERCLOCKWISE ||
nSubType == BOTTOMLEFTCOUNTERCLOCKWISE ) );
case BOXSNAKESWIPE:
return ParametricPolyPolygonSharedPtr(
new BoxSnakesWipe(
// elements:
64 * 64,
// fourBox:
nSubType == FOURBOXVERTICAL ||
nSubType == FOURBOXHORIZONTAL ) );
case SINGLESWEEPWIPE:
return ParametricPolyPolygonSharedPtr(
new SweepWipe(
// center:
nSubType == CLOCKWISETOP ||
nSubType == CLOCKWISERIGHT ||
nSubType == CLOCKWISEBOTTOM ||
nSubType == CLOCKWISELEFT,
// single:
true,
// oppositeVertical:
false,
// flipOnYAxis:
nSubType == COUNTERCLOCKWISEBOTTOMLEFT ||
nSubType == COUNTERCLOCKWISETOPRIGHT
) );
case DOUBLESWEEPWIPE:
return ParametricPolyPolygonSharedPtr(
new SweepWipe(
// center:
nSubType == PARALLELVERTICAL ||
nSubType == PARALLELDIAGONAL ||
nSubType == OPPOSITEVERTICAL ||
nSubType == OPPOSITEHORIZONTAL,
// single:
false,
// oppositeVertical:
nSubType == OPPOSITEVERTICAL ||
nSubType == OPPOSITEHORIZONTAL,
// flipOnYAxis:
false ) );
case DOUBLEFANWIPE:
return ParametricPolyPolygonSharedPtr(
new FanWipe(
//center:
true,
// single:
false,
// fanIn:
nSubType == FANINVERTICAL ||
nSubType == FANINHORIZONTAL ) );
case TRIANGLEWIPE:
return ParametricPolyPolygonSharedPtr(
FigureWipe::createTriangleWipe() );
case ARROWHEADWIPE:
return ParametricPolyPolygonSharedPtr(
FigureWipe::createArrowHeadWipe() );
case PENTAGONWIPE:
return ParametricPolyPolygonSharedPtr(
FigureWipe::createPentagonWipe() );
case HEXAGONWIPE:
return ParametricPolyPolygonSharedPtr(
FigureWipe::createHexagonWipe() );
case STARWIPE: {
sal_Int32 points;
switch (nSubType) {
case FIVEPOINT:
points = 5;
break;
case SIXPOINT:
points = 6;
break;
default:
points = 4;
break;
}
return ParametricPolyPolygonSharedPtr(
FigureWipe::createStarWipe(points) );
}
case MISCDIAGONALWIPE: {
switch (nSubType) {
case DOUBLEBARNDOOR:
return ParametricPolyPolygonSharedPtr(
new BarnDoorWipe( true /* doubled */ ) );
case DOUBLEDIAMOND:
return ParametricPolyPolygonSharedPtr(
new DoubleDiamondWipe );
}
break;
}
case ZIGZAGWIPE:
return ParametricPolyPolygonSharedPtr( new ZigZagWipe(5) );
case BARNZIGZAGWIPE:
return ParametricPolyPolygonSharedPtr( new BarnZigZagWipe(5) );
case BOWTIEWIPE:
case BARNVEEWIPE:
case EYEWIPE:
case ROUNDRECTWIPE:
case MISCSHAPEWIPE:
case SALOONDOORWIPE:
case WINDSHIELDWIPE:
// for now, map to barwipe transition
return ParametricPolyPolygonSharedPtr(
new BarWipePolyPolygon );
default:
case PUSHWIPE:
case SLIDEWIPE:
case FADE:
ENSURE_AND_THROW( false,
"createShapeClipPolyPolygonAnimation(): Transition type mismatch" );
}
return ParametricPolyPolygonSharedPtr();
}
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.74); FILE MERGED 2008/03/31 14:00:25 rt 1.7.74.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: parametricpolypolygonfactory.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
#include <canvas/debug.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>
#include "parametricpolypolygonfactory.hxx"
#include "barwipepolypolygon.hxx"
#include "boxwipe.hxx"
#include "fourboxwipe.hxx"
#include "barndoorwipe.hxx"
#include "doublediamondwipe.hxx"
#include "veewipe.hxx"
#include "iriswipe.hxx"
#include "ellipsewipe.hxx"
#include "checkerboardwipe.hxx"
#include "randomwipe.hxx"
#include "waterfallwipe.hxx"
#include "clockwipe.hxx"
#include "fanwipe.hxx"
#include "pinwheelwipe.hxx"
#include "snakewipe.hxx"
#include "spiralwipe.hxx"
#include "sweepwipe.hxx"
#include "figurewipe.hxx"
#include "zigzagwipe.hxx"
using namespace ::com::sun::star;
namespace slideshow
{
namespace internal
{
ParametricPolyPolygonSharedPtr
ParametricPolyPolygonFactory::createClipPolyPolygon(
sal_Int16 nType, sal_Int16 nSubType )
{
using namespace ::com::sun::star::animations::TransitionType;
using namespace ::com::sun::star::animations::TransitionSubType;
switch (nType)
{
case BARWIPE:
return ParametricPolyPolygonSharedPtr(
new BarWipePolyPolygon );
case BLINDSWIPE:
return ParametricPolyPolygonSharedPtr(
new BarWipePolyPolygon( 6 ) );
case BOXWIPE:
return ParametricPolyPolygonSharedPtr(
new BoxWipe( nSubType == LEFTCENTER ||
nSubType == TOPCENTER ||
nSubType == RIGHTCENTER||
nSubType == BOTTOMCENTER ) );
case FOURBOXWIPE:
return ParametricPolyPolygonSharedPtr(
new FourBoxWipe( nSubType == CORNERSOUT ) );
case BARNDOORWIPE:
return ParametricPolyPolygonSharedPtr(
new BarnDoorWipe );
case DIAGONALWIPE:
return ParametricPolyPolygonSharedPtr(
new BarWipePolyPolygon );
case VEEWIPE:
return ParametricPolyPolygonSharedPtr(
new VeeWipe );
case IRISWIPE:
return ParametricPolyPolygonSharedPtr(
new IrisWipe );
case ELLIPSEWIPE:
return ParametricPolyPolygonSharedPtr(
new EllipseWipe(nSubType) );
case CHECKERBOARDWIPE:
return ParametricPolyPolygonSharedPtr(
new CheckerBoardWipe );
case RANDOMBARWIPE:
return ParametricPolyPolygonSharedPtr(
new RandomWipe( 128, true /* bars */ ) );
case DISSOLVE:
return ParametricPolyPolygonSharedPtr(
new RandomWipe( 16 * 16, // for now until dxcanvas is faster
// 64 * 64 /* elements */,
false /* dissolve */ ) );
case WATERFALLWIPE:
return ParametricPolyPolygonSharedPtr(
new WaterfallWipe(
128,
// flipOnYAxis:
nSubType == VERTICALRIGHT ||
nSubType == HORIZONTALLEFT ) );
case CLOCKWIPE:
return ParametricPolyPolygonSharedPtr(
new ClockWipe );
case FANWIPE:
return ParametricPolyPolygonSharedPtr(
new FanWipe( // center:
nSubType == CENTERTOP ||
nSubType == CENTERRIGHT ) );
case PINWHEELWIPE: {
sal_Int32 blades;
switch (nSubType) {
case ONEBLADE:
blades = 1;
break;
case THREEBLADE:
blades = 3;
break;
case FOURBLADE:
blades = 4;
break;
case EIGHTBLADE:
blades = 8;
break;
default:
blades = 2;
break;
}
return ParametricPolyPolygonSharedPtr(
new PinWheelWipe( blades ) );
}
case SNAKEWIPE:
return ParametricPolyPolygonSharedPtr(
new SnakeWipe(
// elements:
64 * 64,
// diagonal:
nSubType == TOPLEFTDIAGONAL ||
nSubType == TOPRIGHTDIAGONAL ||
nSubType == BOTTOMRIGHTDIAGONAL ||
nSubType == BOTTOMLEFTDIAGONAL,
// flipOnYAxis:
nSubType == TOPLEFTVERTICAL ||
nSubType == TOPRIGHTDIAGONAL ||
nSubType == BOTTOMLEFTDIAGONAL
) );
case PARALLELSNAKESWIPE:
return ParametricPolyPolygonSharedPtr(
new ParallelSnakesWipe(
// elements:
64 * 64,
// diagonal:
nSubType == DIAGONALBOTTOMLEFTOPPOSITE ||
nSubType == DIAGONALTOPLEFTOPPOSITE,
// flipOnYAxis:
nSubType == VERTICALBOTTOMLEFTOPPOSITE ||
nSubType == HORIZONTALTOPLEFTOPPOSITE ||
nSubType == DIAGONALTOPLEFTOPPOSITE,
// opposite:
nSubType == VERTICALTOPLEFTOPPOSITE ||
nSubType == VERTICALBOTTOMLEFTOPPOSITE ||
nSubType == HORIZONTALTOPLEFTOPPOSITE ||
nSubType == HORIZONTALTOPRIGHTOPPOSITE ||
nSubType == DIAGONALBOTTOMLEFTOPPOSITE ||
nSubType == DIAGONALTOPLEFTOPPOSITE
) );
case SPIRALWIPE:
return ParametricPolyPolygonSharedPtr(
new SpiralWipe(
// elements:
64 * 64,
// flipOnYAxis:
nSubType == TOPLEFTCOUNTERCLOCKWISE ||
nSubType == TOPRIGHTCOUNTERCLOCKWISE ||
nSubType == BOTTOMRIGHTCOUNTERCLOCKWISE ||
nSubType == BOTTOMLEFTCOUNTERCLOCKWISE ) );
case BOXSNAKESWIPE:
return ParametricPolyPolygonSharedPtr(
new BoxSnakesWipe(
// elements:
64 * 64,
// fourBox:
nSubType == FOURBOXVERTICAL ||
nSubType == FOURBOXHORIZONTAL ) );
case SINGLESWEEPWIPE:
return ParametricPolyPolygonSharedPtr(
new SweepWipe(
// center:
nSubType == CLOCKWISETOP ||
nSubType == CLOCKWISERIGHT ||
nSubType == CLOCKWISEBOTTOM ||
nSubType == CLOCKWISELEFT,
// single:
true,
// oppositeVertical:
false,
// flipOnYAxis:
nSubType == COUNTERCLOCKWISEBOTTOMLEFT ||
nSubType == COUNTERCLOCKWISETOPRIGHT
) );
case DOUBLESWEEPWIPE:
return ParametricPolyPolygonSharedPtr(
new SweepWipe(
// center:
nSubType == PARALLELVERTICAL ||
nSubType == PARALLELDIAGONAL ||
nSubType == OPPOSITEVERTICAL ||
nSubType == OPPOSITEHORIZONTAL,
// single:
false,
// oppositeVertical:
nSubType == OPPOSITEVERTICAL ||
nSubType == OPPOSITEHORIZONTAL,
// flipOnYAxis:
false ) );
case DOUBLEFANWIPE:
return ParametricPolyPolygonSharedPtr(
new FanWipe(
//center:
true,
// single:
false,
// fanIn:
nSubType == FANINVERTICAL ||
nSubType == FANINHORIZONTAL ) );
case TRIANGLEWIPE:
return ParametricPolyPolygonSharedPtr(
FigureWipe::createTriangleWipe() );
case ARROWHEADWIPE:
return ParametricPolyPolygonSharedPtr(
FigureWipe::createArrowHeadWipe() );
case PENTAGONWIPE:
return ParametricPolyPolygonSharedPtr(
FigureWipe::createPentagonWipe() );
case HEXAGONWIPE:
return ParametricPolyPolygonSharedPtr(
FigureWipe::createHexagonWipe() );
case STARWIPE: {
sal_Int32 points;
switch (nSubType) {
case FIVEPOINT:
points = 5;
break;
case SIXPOINT:
points = 6;
break;
default:
points = 4;
break;
}
return ParametricPolyPolygonSharedPtr(
FigureWipe::createStarWipe(points) );
}
case MISCDIAGONALWIPE: {
switch (nSubType) {
case DOUBLEBARNDOOR:
return ParametricPolyPolygonSharedPtr(
new BarnDoorWipe( true /* doubled */ ) );
case DOUBLEDIAMOND:
return ParametricPolyPolygonSharedPtr(
new DoubleDiamondWipe );
}
break;
}
case ZIGZAGWIPE:
return ParametricPolyPolygonSharedPtr( new ZigZagWipe(5) );
case BARNZIGZAGWIPE:
return ParametricPolyPolygonSharedPtr( new BarnZigZagWipe(5) );
case BOWTIEWIPE:
case BARNVEEWIPE:
case EYEWIPE:
case ROUNDRECTWIPE:
case MISCSHAPEWIPE:
case SALOONDOORWIPE:
case WINDSHIELDWIPE:
// for now, map to barwipe transition
return ParametricPolyPolygonSharedPtr(
new BarWipePolyPolygon );
default:
case PUSHWIPE:
case SLIDEWIPE:
case FADE:
ENSURE_AND_THROW( false,
"createShapeClipPolyPolygonAnimation(): Transition type mismatch" );
}
return ParametricPolyPolygonSharedPtr();
}
}
}
<|endoftext|> |
<commit_before>// DnaMatchingAndVariationDetection.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "Sequence.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// Define the sample sequences.
char sequence1[33] = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTG";
// Create the necessary Sequence objects.
Sequence s1;
// Initialize the Sequence objects.
s1.Initialize(sequence1);
// Define a search key.
const int SEARCH_KEY_SIZE = 3;
char searchKey[SEARCH_KEY_SIZE + 1] = "CCC";
// Test sequence 1 and search functionality.
cout << "Sequence 1: \""; s1.PrintSequence(); cout << "\"" << endl;
cout << " - Size: " << s1.GetSize() << endl;
cout << "Search Key: " << searchKey << endl;
cout << " - Keys Found: " << s1.Search(searchKey, SEARCH_KEY_SIZE) << endl;
return 0;
}<commit_msg>Expanded sequence search testing to include both valid and non-valid search keys<commit_after>// DnaMatchingAndVariationDetection.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "Sequence.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// Define the sample sequences.
char sequence1[33] = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTG";
char sequence2[17] = "CTGCTGCTCTCCGGGG";
// Create the necessary Sequence objects.
Sequence s1, s2;
// Initialize the Sequence objects.
s1.Initialize(sequence1);
s2.Initialize(sequence2, 16);
// Define search keys.
const int SEARCH_KEY_SIZE_1 = 3;
char searchKey1[SEARCH_KEY_SIZE_1 + 1] = "CCC";
char searchKey2[SEARCH_KEY_SIZE_1 + 1] = "AAA";
const int SEARCH_KEY_SIZE_2 = 8;
char searchKey3[SEARCH_KEY_SIZE_2 + 1] = "CTCCGGGG";
char searchKey4[SEARCH_KEY_SIZE_2 + 1] = "CTGCTGCG";
// Test sequence 1 (default sequence size) and search functionality.
cout << "Sequence 1: \""; s1.PrintSequence(); cout << "\"" << endl;
cout << " - Size: " << s1.GetSize() << endl;
cout << "Search Key: " << searchKey1 << endl;
cout << " - Keys Found: " << s1.Search(searchKey1, SEARCH_KEY_SIZE_1) << endl;
cout << "Search Key: " << searchKey2 << endl;
cout << " - Keys Found: " << s1.Search(searchKey2, SEARCH_KEY_SIZE_1) << endl << endl;
// Test sequence 2 (specified sequence size) and search functionality.
cout << "Sequence 2: \""; s2.PrintSequence(); cout << "\"" << endl;
cout << " - Size: " << s2.GetSize() << endl;
cout << "Search Key: " << searchKey3 << endl;
cout << " - Keys Found: " << s2.Search(searchKey3, SEARCH_KEY_SIZE_2) << endl;
cout << "Search Key: " << searchKey4 << endl;
cout << " - Keys Found: " << s2.Search(searchKey4, SEARCH_KEY_SIZE_2) << endl << endl;
return 0;
}<|endoftext|> |
<commit_before>//$Id$
#ifndef MECHANICTRANSLATIONALMASS_HPP_INCLUDED
#define MECHANICTRANSLATIONALMASS_HPP_INCLUDED
#include <sstream>
#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup MechanicalComponents
//!
class MechanicTranslationalMass : public ComponentQ
{
private:
double m, B, k;
double mLength; //This length is not accesible by the user,
//it is set from the start values by the c-components in the ends
double *mpND_f1, *mpND_x1, *mpND_v1, *mpND_c1, *mpND_Zx1, *mpND_f2, *mpND_x2, *mpND_v2, *mpND_c2, *mpND_Zx2; //Node data pointers
double f1, x1, v1, c1, Zx1, f2, x2, v2, c2, Zx2; //Node data variables
double mNum[3];
double mDen[3];
SecondOrderFilter mFilter;
Integrator mInt;
Port *mpP1, *mpP2;
public:
static Component *Creator()
{
return new MechanicTranslationalMass("TranslationalMass");
}
MechanicTranslationalMass(const std::string name) : ComponentQ(name)
{
//Set member attributes
m = 1.0;
B = 10;
k = 0.0;
//Add ports to the component
mpP1 = addPowerPort("P1", "NodeMechanic");
mpP2 = addPowerPort("P2", "NodeMechanic");
//Register changable parameters to the HOPSAN++ core
registerParameter("m", "Mass", "[kg]", m);
registerParameter("B", "Viscous Friction", "[Ns/m]", B);
registerParameter("k", "Spring Coefficient", "[N/m]", k);
}
void initialize()
{
//Assign node data pointers
mpND_f1 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);
mpND_x1 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);
mpND_v1 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);
mpND_c1 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);
mpND_Zx1 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);
mpND_f2 = getSafeNodeDataPtr(mpP2, NodeMechanic::FORCE);
mpND_x2 = getSafeNodeDataPtr(mpP2, NodeMechanic::POSITION);
mpND_v2 = getSafeNodeDataPtr(mpP2, NodeMechanic::VELOCITY);
mpND_c2 = getSafeNodeDataPtr(mpP2, NodeMechanic::WAVEVARIABLE);
mpND_Zx2 = getSafeNodeDataPtr(mpP2, NodeMechanic::CHARIMP);
//Initialization
f1 = (*mpND_f1);
x1 = (*mpND_x1);
v1 = (*mpND_v1);
x2 = (*mpND_x2);
mLength = x1+x2;
mNum[0] = 0.0;
mNum[1] = 1.0;
mNum[2] = 0.0;
mDen[0] = m;
mDen[1] = B;
mDen[2] = k;
mFilter.initialize(mTimestep, mNum, mDen, -f1, -v1);
mInt.initialize(mTimestep, -v1, -x1+mLength);
//Print debug message if velocities do not match
if(mpP1->readNode(NodeMechanic::VELOCITY) != -mpP2->readNode(NodeMechanic::VELOCITY))
{
std::stringstream ss;
ss << "Start velocities does not match, {" << getName() << "::" << mpP1->getPortName() <<
"} and {" << getName() << "::" << mpP2->getPortName() << "}.";
this->addDebugMessage(ss.str());
}
}
void simulateOneTimestep()
{
//Get variable values from nodes
c1 = (*mpND_c1);
Zx1 = (*mpND_Zx1);
c2 = (*mpND_c2);
Zx2 = (*mpND_Zx2);
//Mass equations
mDen[1] = B+Zx1+Zx2;
mFilter.setDen(mDen);
v2 = mFilter.update(c1-c2);
v1 = -v2;
x2 = mInt.update(v2);
x1 = -x2 + mLength;
f1 = c1 + Zx1*v1;
f2 = c2 + Zx2*v2;
//Write new values to nodes
(*mpND_f1) = f1;
(*mpND_x1) = x1;
(*mpND_v1) = v1;
(*mpND_f2) = f2;
(*mpND_x2) = x2;
(*mpND_v2) = v2;
}
};
}
#endif // MECHANICTRANSLATIONALMASS_HPP_INCLUDED
<commit_msg>Added max and min positions for translational mass.<commit_after>//$Id$
#ifndef MECHANICTRANSLATIONALMASS_HPP_INCLUDED
#define MECHANICTRANSLATIONALMASS_HPP_INCLUDED
#include <sstream>
#include <math.h>
#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup MechanicalComponents
//!
class MechanicTranslationalMass : public ComponentQ
{
private:
double m, B, k, xMin, xMax;
double mLength; //This length is not accesible by the user,
//it is set from the start values by the c-components in the ends
double *mpND_f1, *mpND_x1, *mpND_v1, *mpND_c1, *mpND_Zx1, *mpND_f2, *mpND_x2, *mpND_v2, *mpND_c2, *mpND_Zx2; //Node data pointers
double f1, x1, v1, c1, Zx1, f2, x2, v2, c2, Zx2; //Node data variables
double mNum[3];
double mDen[3];
SecondOrderFilter mFilter;
Integrator mInt;
Port *mpP1, *mpP2;
public:
static Component *Creator()
{
return new MechanicTranslationalMass("TranslationalMass");
}
MechanicTranslationalMass(const std::string name) : ComponentQ(name)
{
//Set member attributes
m = 1.0;
B = 10;
k = 0.0;
xMin = -1000.0;
xMax = 1000.0;
//Add ports to the component
mpP1 = addPowerPort("P1", "NodeMechanic");
mpP2 = addPowerPort("P2", "NodeMechanic");
//Register changable parameters to the HOPSAN++ core
registerParameter("m", "Mass", "[kg]", m);
registerParameter("B", "Viscous Friction", "[Ns/m]", B);
registerParameter("k", "Spring Coefficient", "[N/m]", k);
registerParameter("x_min", "Minimum Position", "[m]", xMin);
registerParameter("x_max", "Maximum Position", "[m]", xMax);
}
void initialize()
{
//Assign node data pointers
mpND_f1 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);
mpND_x1 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);
mpND_v1 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);
mpND_c1 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);
mpND_Zx1 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);
mpND_f2 = getSafeNodeDataPtr(mpP2, NodeMechanic::FORCE);
mpND_x2 = getSafeNodeDataPtr(mpP2, NodeMechanic::POSITION);
mpND_v2 = getSafeNodeDataPtr(mpP2, NodeMechanic::VELOCITY);
mpND_c2 = getSafeNodeDataPtr(mpP2, NodeMechanic::WAVEVARIABLE);
mpND_Zx2 = getSafeNodeDataPtr(mpP2, NodeMechanic::CHARIMP);
//Initialization
f1 = (*mpND_f1);
x1 = (*mpND_x1);
v1 = (*mpND_v1);
x2 = (*mpND_x2);
mLength = x1+x2;
mNum[0] = 0.0;
mNum[1] = 1.0;
mNum[2] = 0.0;
mDen[0] = m;
mDen[1] = B;
mDen[2] = k;
mFilter.initialize(mTimestep, mNum, mDen, -f1, -v1);
mInt.initialize(mTimestep, -v1, -x1+mLength);
//Print debug message if velocities do not match
if(mpP1->readNode(NodeMechanic::VELOCITY) != -mpP2->readNode(NodeMechanic::VELOCITY))
{
std::stringstream ss;
ss << "Start velocities does not match, {" << getName() << "::" << mpP1->getPortName() <<
"} and {" << getName() << "::" << mpP2->getPortName() << "}.";
this->addDebugMessage(ss.str());
}
}
void simulateOneTimestep()
{
//Get variable values from nodes
c1 = (*mpND_c1);
Zx1 = (*mpND_Zx1);
c2 = (*mpND_c2);
Zx2 = (*mpND_Zx2);
//Mass equations
mDen[1] = B+Zx1+Zx2;
mFilter.setDen(mDen);
v2 = mFilter.update(c1-c2);
x2 = mInt.update(v2);
if(x2<xMin)
{
x2=xMin;
v2=std::min(0.0, v2);
}
if(x2>xMax)
{
x2=xMax;
v2=std::max(0.0, v2);
}
v1 = -v2;
x1 = -x2 + mLength;
f1 = c1 + Zx1*v1;
f2 = c2 + Zx2*v2;
//Write new values to nodes
(*mpND_f1) = f1;
(*mpND_x1) = x1;
(*mpND_v1) = v1;
(*mpND_f2) = f2;
(*mpND_x2) = x2;
(*mpND_v2) = v2;
}
};
}
#endif // MECHANICTRANSLATIONALMASS_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, 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 the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Wim Meeussen */
#include <boost/algorithm/string.hpp>
#include <ros/ros.h>
#include <vector>
#include "urdf/model.h"
namespace urdf{
Model::Model()
{
this->clear();
}
void Model::clear()
{
name_.clear();
this->links_.clear();
this->joints_.clear();
this->materials_.clear();
this->root_link_.reset();
}
bool Model::initFile(const std::string& filename)
{
TiXmlDocument xml_doc;
xml_doc.LoadFile(filename);
return initXml(&xml_doc);
}
bool Model::initString(const std::string& xml_string)
{
TiXmlDocument xml_doc;
xml_doc.Parse(xml_string.c_str());
return initXml(&xml_doc);
}
bool Model::initXml(TiXmlDocument *xml_doc)
{
if (!xml_doc)
{
ROS_ERROR("Could not parse the xml");
return false;
}
TiXmlElement *robot_xml = xml_doc->FirstChildElement("robot");
if (!robot_xml)
{
ROS_ERROR("Could not find the 'robot' element in the xml file");
return false;
}
return initXml(robot_xml);
}
bool Model::initXml(TiXmlElement *robot_xml)
{
this->clear();
ROS_DEBUG("Parsing robot xml");
if (!robot_xml) return false;
// Get robot name
const char *name = robot_xml->Attribute("name");
if (!name)
{
ROS_ERROR("No name given for the robot.");
return false;
}
this->name_ = std::string(name);
// Get all Material elements
for (TiXmlElement* material_xml = robot_xml->FirstChildElement("material"); material_xml; material_xml = material_xml->NextSiblingElement("material"))
{
boost::shared_ptr<Material> material;
material.reset(new Material);
if (material->initXml(material_xml))
{
if (this->getMaterial(material->name))
{
ROS_ERROR("material '%s' is not unique.", material->name.c_str());
material.reset();
return false;
}
else
{
this->materials_.insert(make_pair(material->name,material));
ROS_DEBUG("successfully added a new material '%s'", material->name.c_str());
}
}
else
{
ROS_ERROR("material xml is not initialized correctly");
material.reset();
}
}
// Get all Link elements
for (TiXmlElement* link_xml = robot_xml->FirstChildElement("link"); link_xml; link_xml = link_xml->NextSiblingElement("link"))
{
boost::shared_ptr<Link> link;
link.reset(new Link);
if (link->initXml(link_xml))
{
if (this->getLink(link->name))
{
ROS_ERROR("link '%s' is not unique.", link->name.c_str());
link.reset();
return false;
}
else
{
// set link visual material
ROS_DEBUG("setting link '%s' material", link->name.c_str());
if (link->visual)
{
if (!link->visual->material_name.empty())
{
if (this->getMaterial(link->visual->material_name))
{
ROS_DEBUG("setting link '%s' material to '%s'", link->name.c_str(),link->visual->material_name.c_str());
link->visual->material = this->getMaterial( link->visual->material_name.c_str() );
}
else
{
if (link->visual->material)
{
ROS_DEBUG("link '%s' material '%s' defined in Visual.", link->name.c_str(),link->visual->material_name.c_str());
this->materials_.insert(make_pair(link->visual->material->name,link->visual->material));
}
else
{
ROS_ERROR("link '%s' material '%s' undefined.", link->name.c_str(),link->visual->material_name.c_str());
link.reset();
return false;
}
}
}
}
this->links_.insert(make_pair(link->name,link));
ROS_DEBUG("successfully added a new link '%s'", link->name.c_str());
}
}
else
{
ROS_ERROR("link xml is not initialized correctly");
link.reset();
}
}
// Get all Joint elements
for (TiXmlElement* joint_xml = robot_xml->FirstChildElement("joint"); joint_xml; joint_xml = joint_xml->NextSiblingElement("joint"))
{
boost::shared_ptr<Joint> joint;
joint.reset(new Joint);
if (joint->initXml(joint_xml))
{
if (this->getJoint(joint->name))
{
ROS_ERROR("joint '%s' is not unique.", joint->name.c_str());
joint.reset();
return false;
}
else
{
this->joints_.insert(make_pair(joint->name,joint));
ROS_DEBUG("successfully added a new joint '%s'", joint->name.c_str());
}
}
else
{
ROS_ERROR("joint xml is not initialized correctly");
joint.reset();
}
}
// every link has children links and joints, but no parents, so we create a
// local convenience data structure for keeping child->parent relations
std::map<std::string, std::string> parent_link_tree;
parent_link_tree.clear();
// building tree: name mapping
if (!this->initTree(parent_link_tree))
{
ROS_ERROR("failed to build tree");
return false;
}
// find the root link
if (!this->initRoot(parent_link_tree))
{
ROS_ERROR("failed to find root link");
return false;
}
return true;
}
bool Model::initTree(std::map<std::string, std::string> &parent_link_tree)
{
// loop through all joints, for every link, assign children links and children joints
for (std::map<std::string,boost::shared_ptr<Joint> >::iterator joint = this->joints_.begin();joint != this->joints_.end(); joint++)
{
std::string parent_link_name = joint->second->parent_link_name;
std::string child_link_name = joint->second->child_link_name;
ROS_DEBUG("build tree: joint: '%s' has parent link '%s' and child link '%s'", joint->first.c_str(), parent_link_name.c_str(),child_link_name.c_str());
/// add an empty "world" link
if (parent_link_name == "world")
{
if (this->getLink(parent_link_name))
{
ROS_DEBUG(" parent link '%s' already exists.", parent_link_name.c_str());
}
else
{
ROS_DEBUG(" parent link '%s' is a special case, adding fake link.", parent_link_name.c_str());
boost::shared_ptr<Link> link;
link.reset(new Link);
link->name = "world";
this->links_.insert(make_pair(link->name,link));
ROS_DEBUG(" successfully added new link '%s'", link->name.c_str());
}
}
if (parent_link_name.empty())
{
ROS_DEBUG(" Joint %s: does not have parent link name specified. Joint is an abstract joint.",(joint->second)->name.c_str());
}
else if (child_link_name.empty())
{
ROS_DEBUG(" Joint %s: does not have child link name specified. Joint is an abstract joint.",(joint->second)->name.c_str());
}
else
{
// find parent link
boost::shared_ptr<Link> parent_link;
this->getLink(parent_link_name, parent_link);
if (!parent_link)
{
ROS_ERROR(" parent link '%s' is not found", parent_link_name.c_str());
return false;
}
else
{
// find child link
boost::shared_ptr<Link> child_link;
this->getLink(child_link_name, child_link);
if (!child_link)
{
ROS_ERROR(" for joint: %s child link '%s' is not found",joint->first.c_str(),child_link_name.c_str());
return false;
}
else
{
//set parent link for child link
child_link->setParent(parent_link);
//set parent joint for child link
child_link->setParentJoint(joint->second);
//set child joint for parent link
parent_link->addChildJoint(joint->second);
//set child link for parent link
parent_link->addChild(child_link);
// fill in child/parent string map
parent_link_tree[child_link->name] = parent_link_name;
ROS_DEBUG(" now Link '%s' has %i children ", parent_link->name.c_str(), (int)parent_link->child_links.size());
}
}
}
}
return true;
}
bool Model::initRoot(std::map<std::string, std::string> &parent_link_tree)
{
this->root_link_.reset();
for (std::map<std::string, std::string>::iterator p=parent_link_tree.begin(); p!=parent_link_tree.end(); p++)
{
if (parent_link_tree.find(p->second) == parent_link_tree.end())
{
if (this->root_link_)
{
ROS_DEBUG("child '%s', parent '%s', root '%s'", p->first.c_str(), p->second.c_str(), this->root_link_->name.c_str());
if (this->root_link_->name != p->second)
{
ROS_ERROR("Two root links found: '%s' and '%s'", this->root_link_->name.c_str(), p->second.c_str());
return false;
}
}
else
getLink(p->second,this->root_link_);
}
}
if (!this->root_link_)
{
ROS_ERROR("No root link found. The robot xml is empty or not a tree.");
return false;
}
ROS_DEBUG("Link '%s' is the root link", this->root_link_->name.c_str());
return true;
}
boost::shared_ptr<Material> Model::getMaterial(const std::string& name) const
{
boost::shared_ptr<Material> ptr;
if (this->materials_.find(name) == this->materials_.end())
ptr.reset();
else
ptr = this->materials_.find(name)->second;
return ptr;
}
boost::shared_ptr<const Link> Model::getLink(const std::string& name) const
{
boost::shared_ptr<const Link> ptr;
if (this->links_.find(name) == this->links_.end())
ptr.reset();
else
ptr = this->links_.find(name)->second;
return ptr;
}
void Model::getLinks(std::vector<boost::shared_ptr<Link> >& links) const
{
for (std::map<std::string,boost::shared_ptr<Link> >::const_iterator link = this->links_.begin();link != this->links_.end(); link++)
{
links.push_back(link->second);
}
}
void Model::getLink(const std::string& name,boost::shared_ptr<Link> &link) const
{
boost::shared_ptr<Link> ptr;
if (this->links_.find(name) == this->links_.end())
ptr.reset();
else
ptr = this->links_.find(name)->second;
link = ptr;
}
boost::shared_ptr<const Joint> Model::getJoint(const std::string& name) const
{
boost::shared_ptr<const Joint> ptr;
if (this->joints_.find(name) == this->joints_.end())
ptr.reset();
else
ptr = this->joints_.find(name)->second;
return ptr;
}
}
<commit_msg>update error messages.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, 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 the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Wim Meeussen */
#include <boost/algorithm/string.hpp>
#include <ros/ros.h>
#include <vector>
#include "urdf/model.h"
namespace urdf{
Model::Model()
{
this->clear();
}
void Model::clear()
{
name_.clear();
this->links_.clear();
this->joints_.clear();
this->materials_.clear();
this->root_link_.reset();
}
bool Model::initFile(const std::string& filename)
{
TiXmlDocument xml_doc;
xml_doc.LoadFile(filename);
return initXml(&xml_doc);
}
bool Model::initString(const std::string& xml_string)
{
TiXmlDocument xml_doc;
xml_doc.Parse(xml_string.c_str());
return initXml(&xml_doc);
}
bool Model::initXml(TiXmlDocument *xml_doc)
{
if (!xml_doc)
{
ROS_ERROR("Could not parse the xml");
return false;
}
TiXmlElement *robot_xml = xml_doc->FirstChildElement("robot");
if (!robot_xml)
{
ROS_ERROR("Could not find the 'robot' element in the xml file");
return false;
}
return initXml(robot_xml);
}
bool Model::initXml(TiXmlElement *robot_xml)
{
this->clear();
ROS_DEBUG("Parsing robot xml");
if (!robot_xml) return false;
// Get robot name
const char *name = robot_xml->Attribute("name");
if (!name)
{
ROS_ERROR("No name given for the robot.");
return false;
}
this->name_ = std::string(name);
// Get all Material elements
for (TiXmlElement* material_xml = robot_xml->FirstChildElement("material"); material_xml; material_xml = material_xml->NextSiblingElement("material"))
{
boost::shared_ptr<Material> material;
material.reset(new Material);
if (material->initXml(material_xml))
{
if (this->getMaterial(material->name))
{
ROS_ERROR("material '%s' is not unique.", material->name.c_str());
material.reset();
return false;
}
else
{
this->materials_.insert(make_pair(material->name,material));
ROS_DEBUG("successfully added a new material '%s'", material->name.c_str());
}
}
else
{
ROS_ERROR("material xml is not initialized correctly");
material.reset();
}
}
// Get all Link elements
for (TiXmlElement* link_xml = robot_xml->FirstChildElement("link"); link_xml; link_xml = link_xml->NextSiblingElement("link"))
{
boost::shared_ptr<Link> link;
link.reset(new Link);
if (link->initXml(link_xml))
{
if (this->getLink(link->name))
{
ROS_ERROR("link '%s' is not unique.", link->name.c_str());
link.reset();
return false;
}
else
{
// set link visual material
ROS_DEBUG("setting link '%s' material", link->name.c_str());
if (link->visual)
{
if (!link->visual->material_name.empty())
{
if (this->getMaterial(link->visual->material_name))
{
ROS_DEBUG("setting link '%s' material to '%s'", link->name.c_str(),link->visual->material_name.c_str());
link->visual->material = this->getMaterial( link->visual->material_name.c_str() );
}
else
{
if (link->visual->material)
{
ROS_DEBUG("link '%s' material '%s' defined in Visual.", link->name.c_str(),link->visual->material_name.c_str());
this->materials_.insert(make_pair(link->visual->material->name,link->visual->material));
}
else
{
ROS_ERROR("link '%s' material '%s' undefined.", link->name.c_str(),link->visual->material_name.c_str());
link.reset();
return false;
}
}
}
}
this->links_.insert(make_pair(link->name,link));
ROS_DEBUG("successfully added a new link '%s'", link->name.c_str());
}
}
else
{
ROS_ERROR("link xml is not initialized correctly");
link.reset();
}
}
// Get all Joint elements
for (TiXmlElement* joint_xml = robot_xml->FirstChildElement("joint"); joint_xml; joint_xml = joint_xml->NextSiblingElement("joint"))
{
boost::shared_ptr<Joint> joint;
joint.reset(new Joint);
if (joint->initXml(joint_xml))
{
if (this->getJoint(joint->name))
{
ROS_ERROR("joint '%s' is not unique.", joint->name.c_str());
joint.reset();
return false;
}
else
{
this->joints_.insert(make_pair(joint->name,joint));
ROS_DEBUG("successfully added a new joint '%s'", joint->name.c_str());
}
}
else
{
ROS_ERROR("joint xml is not initialized correctly");
joint.reset();
}
}
// every link has children links and joints, but no parents, so we create a
// local convenience data structure for keeping child->parent relations
std::map<std::string, std::string> parent_link_tree;
parent_link_tree.clear();
// building tree: name mapping
if (!this->initTree(parent_link_tree))
{
ROS_ERROR("failed to build tree");
return false;
}
// find the root link
if (!this->initRoot(parent_link_tree))
{
ROS_ERROR("failed to find root link");
return false;
}
return true;
}
bool Model::initTree(std::map<std::string, std::string> &parent_link_tree)
{
// loop through all joints, for every link, assign children links and children joints
for (std::map<std::string,boost::shared_ptr<Joint> >::iterator joint = this->joints_.begin();joint != this->joints_.end(); joint++)
{
std::string parent_link_name = joint->second->parent_link_name;
std::string child_link_name = joint->second->child_link_name;
ROS_DEBUG("build tree: joint: '%s' has parent link '%s' and child link '%s'", joint->first.c_str(), parent_link_name.c_str(),child_link_name.c_str());
/// add an empty "world" link
if (parent_link_name == "world")
{
if (this->getLink(parent_link_name))
{
ROS_DEBUG(" parent link '%s' already exists.", parent_link_name.c_str());
}
else
{
ROS_DEBUG(" parent link '%s' is a special case, adding fake link.", parent_link_name.c_str());
boost::shared_ptr<Link> link;
link.reset(new Link);
link->name = "world";
this->links_.insert(make_pair(link->name,link));
ROS_DEBUG(" successfully added new link '%s'", link->name.c_str());
}
}
if (parent_link_name.empty())
{
ROS_DEBUG(" Joint %s: does not have parent link name specified. Joint is an abstract joint.",(joint->second)->name.c_str());
}
else if (child_link_name.empty())
{
ROS_DEBUG(" Joint %s: does not have child link name specified. Joint is an abstract joint.",(joint->second)->name.c_str());
}
else
{
// find parent link
boost::shared_ptr<Link> parent_link;
this->getLink(parent_link_name, parent_link);
if (!parent_link)
{
ROS_ERROR(" parent link '%s' of joint '%s' not found", parent_link_name.c_str(), joint->first.c_str() );
return false;
}
else
{
// find child link
boost::shared_ptr<Link> child_link;
this->getLink(child_link_name, child_link);
if (!child_link)
{
ROS_ERROR(" child link '%s' of joint: %s not found",child_link_name.c_str(),joint->first.c_str());
return false;
}
else
{
//set parent link for child link
child_link->setParent(parent_link);
//set parent joint for child link
child_link->setParentJoint(joint->second);
//set child joint for parent link
parent_link->addChildJoint(joint->second);
//set child link for parent link
parent_link->addChild(child_link);
// fill in child/parent string map
parent_link_tree[child_link->name] = parent_link_name;
ROS_DEBUG(" now Link '%s' has %i children ", parent_link->name.c_str(), (int)parent_link->child_links.size());
}
}
}
}
return true;
}
bool Model::initRoot(std::map<std::string, std::string> &parent_link_tree)
{
this->root_link_.reset();
for (std::map<std::string, std::string>::iterator p=parent_link_tree.begin(); p!=parent_link_tree.end(); p++)
{
if (parent_link_tree.find(p->second) == parent_link_tree.end())
{
if (this->root_link_)
{
ROS_DEBUG("child '%s', parent '%s', root '%s'", p->first.c_str(), p->second.c_str(), this->root_link_->name.c_str());
if (this->root_link_->name != p->second)
{
ROS_ERROR("Two root links found: '%s' and '%s'", this->root_link_->name.c_str(), p->second.c_str());
return false;
}
}
else
getLink(p->second,this->root_link_);
}
}
if (!this->root_link_)
{
ROS_ERROR("No root link found. The robot xml is empty or not a tree.");
return false;
}
ROS_DEBUG("Link '%s' is the root link", this->root_link_->name.c_str());
return true;
}
boost::shared_ptr<Material> Model::getMaterial(const std::string& name) const
{
boost::shared_ptr<Material> ptr;
if (this->materials_.find(name) == this->materials_.end())
ptr.reset();
else
ptr = this->materials_.find(name)->second;
return ptr;
}
boost::shared_ptr<const Link> Model::getLink(const std::string& name) const
{
boost::shared_ptr<const Link> ptr;
if (this->links_.find(name) == this->links_.end())
ptr.reset();
else
ptr = this->links_.find(name)->second;
return ptr;
}
void Model::getLinks(std::vector<boost::shared_ptr<Link> >& links) const
{
for (std::map<std::string,boost::shared_ptr<Link> >::const_iterator link = this->links_.begin();link != this->links_.end(); link++)
{
links.push_back(link->second);
}
}
void Model::getLink(const std::string& name,boost::shared_ptr<Link> &link) const
{
boost::shared_ptr<Link> ptr;
if (this->links_.find(name) == this->links_.end())
ptr.reset();
else
ptr = this->links_.find(name)->second;
link = ptr;
}
boost::shared_ptr<const Joint> Model::getJoint(const std::string& name) const
{
boost::shared_ptr<const Joint> ptr;
if (this->joints_.find(name) == this->joints_.end())
ptr.reset();
else
ptr = this->joints_.find(name)->second;
return ptr;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#include "../Debug/Assertions.h"
#include "DelegatedIterator.h"
namespace Stroika::Foundation::Traversal {
#if qDebug
namespace Private_ {
template <typename T>
IteratorTracker<T>::~IteratorTracker ()
{
Assert (*fCountRunning == 0);
}
template <typename T>
Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)
{
return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);
}
}
#endif
/*
********************************************************************************
* IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *
********************************************************************************
*/
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)
: _fContextForEachIterator (contextForEachIterator)
#if qDebug
, fIteratorTracker_ ()
#endif
{
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator () const
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});
#else
return Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};
#endif
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
return false;
}
return true;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const
{
this->_Apply (doToElement);
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const
{
return this->_FindFirstThat (doToElement);
}
#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1
#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding
template <typename T>
size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T>
bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (); not i.Done ();) {
return false;
}
return true;
}
template <typename T>
void IterableFromIterator<T, void, void>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const
{
this->_Apply (doToElement);
}
template <typename T>
Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const
{
return this->_FindFirstThat (doToElement);
}
#endif
/*
********************************************************************************
**************************** MakeIterableFromIterator **************************
********************************************************************************
*/
template <typename T>
Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)
{
struct MyIterable_ : public Iterable<T> {
struct Rep : public IterableFromIterator<T>::_Rep, public Memory::UseBlockAllocationIfAppropriate<Rep> {
using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;
Iterator<T> fOriginalIterator;
#if qDebug
mutable Private_::IteratorTracker<T> fIteratorTracker_{};
#endif
Rep (const Iterator<T>& originalIterator)
: fOriginalIterator{originalIterator}
{
}
virtual Iterator<T> MakeIterator () const override
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);
#else
return fOriginalIterator;
#endif
}
virtual _IterableRepSharedPtr Clone () const override
{
return Iterable<T>::template MakeSmartPtr<Rep> (*this);
}
};
MyIterable_ (const Iterator<T>& originalIterator)
: Iterable<T>{Iterable<T>::template MakeSmartPtr<Rep> (originalIterator)}
{
}
};
return MyIterable_{iterator};
}
}
#endif /* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ */
<commit_msg>cosmetic<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#include "../Debug/Assertions.h"
#include "DelegatedIterator.h"
namespace Stroika::Foundation::Traversal {
#if qDebug
namespace Private_ {
template <typename T>
IteratorTracker<T>::~IteratorTracker ()
{
Assert (*fCountRunning == 0);
}
template <typename T>
Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)
{
return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);
}
}
#endif
/*
********************************************************************************
* IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *
********************************************************************************
*/
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)
: _fContextForEachIterator {contextForEachIterator}
{
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator () const
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});
#else
return Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};
#endif
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
return false;
}
return true;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const
{
this->_Apply (doToElement);
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const
{
return this->_FindFirstThat (doToElement);
}
#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1
#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding
template <typename T>
size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T>
bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (); not i.Done ();) {
return false;
}
return true;
}
template <typename T>
void IterableFromIterator<T, void, void>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const
{
this->_Apply (doToElement);
}
template <typename T>
Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const
{
return this->_FindFirstThat (doToElement);
}
#endif
/*
********************************************************************************
**************************** MakeIterableFromIterator **************************
********************************************************************************
*/
template <typename T>
Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)
{
struct MyIterable_ : public Iterable<T> {
struct Rep : public IterableFromIterator<T>::_Rep, public Memory::UseBlockAllocationIfAppropriate<Rep> {
using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;
Iterator<T> fOriginalIterator;
#if qDebug
mutable Private_::IteratorTracker<T> fIteratorTracker_{};
#endif
Rep (const Iterator<T>& originalIterator)
: fOriginalIterator{originalIterator}
{
}
virtual Iterator<T> MakeIterator () const override
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);
#else
return fOriginalIterator;
#endif
}
virtual _IterableRepSharedPtr Clone () const override
{
return Iterable<T>::template MakeSmartPtr<Rep> (*this);
}
};
MyIterable_ (const Iterator<T>& originalIterator)
: Iterable<T>{Iterable<T>::template MakeSmartPtr<Rep> (originalIterator)}
{
}
};
return MyIterable_{iterator};
}
}
#endif /* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ */
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#include "../Debug/Assertions.h"
#include "DelegatedIterator.h"
namespace Stroika {
namespace Foundation {
namespace Traversal {
#if qDebug
namespace Private_ {
template <typename T>
IteratorTracker<T>::~IteratorTracker ()
{
Assert (*fCountRunning == 0);
}
template <typename T>
Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)
{
return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);
}
}
#endif
/*
********************************************************************************
* IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *
********************************************************************************
*/
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)
: _fContextForEachIterator (contextForEachIterator)
#if qDebug
, fIteratorTracker_ ()
#endif
{
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator ([[maybe_unused]]IteratorOwnerID suggestedOwner) const
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSharedPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});
#else
return Iterator<T>{Iterator<T>::template MakeSharedPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};
#endif
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (this); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (this); not i.Done (); ++i) {
return false;
}
return true;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (_APPLY_ARGTYPE doToElement) const
{
this->_Apply (doToElement);
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const
{
return this->_FindFirstThat (doToElement, suggestedOwner);
}
#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1
#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding
template <typename T>
size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (this); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T>
bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (this); not i.Done ();) {
return false;
}
return true;
}
template <typename T>
void IterableFromIterator<T, void, void>::_Rep::Apply (_APPLY_ARGTYPE doToElement) const
{
this->_Apply (doToElement);
}
template <typename T>
Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const
{
return this->_FindFirstThat (doToElement, suggestedOwner);
}
#endif
/*
********************************************************************************
**************************** MakeIterableFromIterator **************************
********************************************************************************
*/
template <typename T>
Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)
{
struct MyIterable_ : public Iterable<T> {
struct Rep : public IterableFromIterator<T>::_Rep {
using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;
DECLARE_USE_BLOCK_ALLOCATION (Rep);
Iterator<T> fOriginalIterator;
#if qDebug
mutable Private_::IteratorTracker<T> fIteratorTracker_{};
#endif
Rep (const Iterator<T>& originalIterator)
: fOriginalIterator (originalIterator)
{
}
virtual Iterator<T> MakeIterator ([[maybe_unused]] IteratorOwnerID suggestedOwner) const override
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);
#else
return fOriginalIterator;
#endif
}
virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override
{
return Iterable<T>::template MakeSharedPtr<Rep> (*this);
}
};
MyIterable_ (const Iterator<T>& originalIterator)
: Iterable<T> (Iterable<T>::template MakeSharedPtr<Rep> (originalIterator))
{
}
};
return MyIterable_ (iterator);
}
}
}
}
#endif /* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ */
<commit_msg>Lots of compiler (msvc level 4) warning cleanups: [[maybe_unused]] use<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#include "../Debug/Assertions.h"
#include "DelegatedIterator.h"
namespace Stroika {
namespace Foundation {
namespace Traversal {
#if qDebug
namespace Private_ {
template <typename T>
IteratorTracker<T>::~IteratorTracker ()
{
Assert (*fCountRunning == 0);
}
template <typename T>
Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)
{
return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);
}
}
#endif
/*
********************************************************************************
* IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *
********************************************************************************
*/
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)
: _fContextForEachIterator (contextForEachIterator)
#if qDebug
, fIteratorTracker_ ()
#endif
{
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator ([[maybe_unused]] IteratorOwnerID suggestedOwner) const
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSharedPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});
#else
return Iterator<T>{Iterator<T>::template MakeSharedPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};
#endif
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (this); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (this); not i.Done (); ++i) {
return false;
}
return true;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (_APPLY_ARGTYPE doToElement) const
{
this->_Apply (doToElement);
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const
{
return this->_FindFirstThat (doToElement, suggestedOwner);
}
#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1
#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding
template <typename T>
size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (this); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T>
bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (this); not i.Done ();) {
return false;
}
return true;
}
template <typename T>
void IterableFromIterator<T, void, void>::_Rep::Apply (_APPLY_ARGTYPE doToElement) const
{
this->_Apply (doToElement);
}
template <typename T>
Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const
{
return this->_FindFirstThat (doToElement, suggestedOwner);
}
#endif
/*
********************************************************************************
**************************** MakeIterableFromIterator **************************
********************************************************************************
*/
template <typename T>
Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)
{
struct MyIterable_ : public Iterable<T> {
struct Rep : public IterableFromIterator<T>::_Rep {
using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;
DECLARE_USE_BLOCK_ALLOCATION (Rep);
Iterator<T> fOriginalIterator;
#if qDebug
mutable Private_::IteratorTracker<T> fIteratorTracker_{};
#endif
Rep (const Iterator<T>& originalIterator)
: fOriginalIterator (originalIterator)
{
}
virtual Iterator<T> MakeIterator ([[maybe_unused]] IteratorOwnerID suggestedOwner) const override
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);
#else
return fOriginalIterator;
#endif
}
virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override
{
return Iterable<T>::template MakeSharedPtr<Rep> (*this);
}
};
MyIterable_ (const Iterator<T>& originalIterator)
: Iterable<T> (Iterable<T>::template MakeSharedPtr<Rep> (originalIterator))
{
}
};
return MyIterable_ (iterator);
}
}
}
}
#endif /* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ */
<|endoftext|> |
<commit_before><commit_msg>Updated SimpleMaterial::isReadyForSubMesh function to pass material context<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2014 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project:
* Filename: test.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: [email protected]
* Date: Dec. 29, 2014
* Time: 11:10:09
* Description:
*****************************************************************************/
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
}
<commit_msg>--allow-empty_message<commit_after>/******************************************************************************
* Copyright (c) 2014 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project:
* Filename: test.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: [email protected]
* Date: Dec. 29, 2014
* Time: 11:10:09
* Description:
*****************************************************************************/
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
}
<|endoftext|> |
<commit_before>#include "php.h"
#include "php_gdal.h"
#include <ogr_core.h>
#include <cpl_conv.h>
#include <cpl_string.h>
#include "ogrexception.h"
#include "ogrspatialreference.h"
#include "ogrgeometry.h"
zend_class_entry *gdal_ogrgeometry_ce;
zend_object_handlers ogrgeometry_object_handlers;
void ogrgeometry_free_storage(void *object TSRMLS_DC)
{
php_ogrgeometry_object *obj = (php_ogrgeometry_object *)object;
//delete obj->geometry; // TODO
zend_hash_destroy(obj->std.properties);
FREE_HASHTABLE(obj->std.properties);
efree(obj);
}
zend_object_value ogrgeometry_create_handler(zend_class_entry *type TSRMLS_DC)
{
zval *tmp;
zend_object_value retval;
php_ogrgeometry_object *obj =
(php_ogrgeometry_object *)emalloc(sizeof(php_ogrgeometry_object));
memset(obj, 0, sizeof(php_ogrgeometry_object));
obj->std.ce = type;
ALLOC_HASHTABLE(obj->std.properties);
zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
#if PHP_VERSION_ID < 50399
zend_hash_copy(obj->std.properties, &type->default_properties,
(copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));
#else
object_properties_init(&obj->std, type);
#endif
retval.handle = zend_objects_store_put(obj, NULL,
ogrgeometry_free_storage, NULL TSRMLS_CC);
retval.handlers = &ogrgeometry_object_handlers;
return retval;
}
PHP_METHOD(OGRGeometry, IsValid)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
RETURN_BOOL(geometry->IsValid());
}
PHP_METHOD(OGRGeometry, ExportToWkt)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *ppszDstText;
char *ret;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
if (geometry->exportToWkt(&ppszDstText) != OGRERR_NONE) {
php_gdal_ogr_throw("Failed to convert geometry to WKT");
RETURN_EMPTY_STRING();
}
ret = estrdup(ppszDstText);
OGRFree(ppszDstText);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, ExportToWkb)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
int wkbSize;
char * buffer;
int wkbByteOrder = wkbNDR; // use as default when no byteOrder is specified
if (ZEND_NUM_ARGS() != 0) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l",
&wkbByteOrder) == FAILURE) {
php_gdal_ogr_throw("Illegal value for byteOrder");
RETURN_EMPTY_STRING();
}
}
if ((wkbByteOrder) != wkbNDR && (wkbByteOrder != wkbXDR)) {
php_gdal_ogr_throw("Illegal value for byteOrder. Has to be either wkbNDR or wkbXDR");
RETURN_EMPTY_STRING();
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
wkbSize = geometry->WkbSize();
buffer = (char*)ecalloc(sizeof(char), wkbSize+1);
if (geometry->exportToWkb(wkbNDR, (unsigned char*)buffer) != OGRERR_NONE) {
php_gdal_ogr_throw("Failed to convert geometry to WKB");
RETURN_EMPTY_STRING();
}
RETURN_STRINGL(buffer, wkbSize+1, 0);
}
PHP_METHOD(OGRGeometry, ExportToJson)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *jsonText;
char *ret;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
jsonText = geometry->exportToJson();
if (jsonText == NULL) {
php_gdal_ogr_throw("Failed to convert geometry to JSON");
RETURN_EMPTY_STRING();
}
ret = estrdup(jsonText);
CPLFree(jsonText);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, ExportToKML)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *kmlText;
char *ret;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
kmlText = geometry->exportToKML();
if (kmlText == NULL) {
php_gdal_ogr_throw("Failed to convert geometry to KML");
RETURN_EMPTY_STRING();
}
ret = estrdup(kmlText);
CPLFree(kmlText);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, ExportToGML)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *gmlText;
char *ret;
char *gmlOptions = NULL;
int gmlOptionsLen;
char **papszOptions = NULL;
if (ZEND_NUM_ARGS() != 0) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s", &gmlOptions, &gmlOptionsLen) == FAILURE) {
php_gdal_ogr_throw("Illegal value for GML format options");
RETURN_EMPTY_STRING();
}
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
#if ! ((GDAL_VERSION_MAJOR <= 1) && (GDAL_VERSION_MINOR < 8))
if (gmlOptionsLen != 0) {
papszOptions = CSLAddString(papszOptions, gmlOptions);
}
gmlText = geometry->exportToGML(papszOptions);
#else
gmlText = geometry->exportToGML();
#endif
#if ! ((GDAL_VERSION_MAJOR <= 1) && (GDAL_VERSION_MINOR < 8))
if (papszOptions) {
CSLDestroy(papszOptions);
}
#endif
if (gmlText == NULL) {
php_gdal_ogr_throw("Failed to convert geometry to GML");
RETURN_EMPTY_STRING();
}
ret = estrdup(gmlText);
CPLFree(gmlText);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, GetGeometryName)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *ret;
const char *geomName;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
geomName = geometry->getGeometryName();
ret = estrdup(geomName);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, GetGeometryType)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
RETURN_LONG(geometry->getGeometryType());
}
PHP_METHOD(OGRGeometry, IsEmpty)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
RETURN_BOOL(geometry->IsEmpty());
}
PHP_METHOD(OGRGeometry, GetSpatialReference)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *spatialreference_obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
spatialreference = geometry->getSpatialReference();
if (!spatialreference) {
RETURN_NULL();
}
if (object_init_ex(return_value, gdal_ogrspatialreference_ce) != SUCCESS) {
RETURN_NULL();
}
spatialreference_obj = (php_ogrspatialreference_object*) zend_objects_get_address(return_value TSRMLS_CC);
spatialreference_obj->spatialreference = spatialreference;
}
zend_function_entry ogrgeometry_methods[] = {
PHP_ME(OGRGeometry, IsValid, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToWkt, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToWkb, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToJson, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToKML, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToGML, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, GetGeometryName, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, GetGeometryType, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, IsEmpty, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, GetSpatialReference, NULL, ZEND_ACC_PUBLIC)
{NULL, NULL, NULL}
};
void php_gdal_ogrgeometry_startup(INIT_FUNC_ARGS)
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "OGRGeometry", ogrgeometry_methods);
gdal_ogrgeometry_ce = zend_register_internal_class(&ce TSRMLS_CC);
gdal_ogrgeometry_ce->create_object = ogrgeometry_create_handler;
memcpy(&ogrgeometry_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
ogrgeometry_object_handlers.clone_obj = NULL;
}
/* VIM settings */
/* ex: set tabstop=2 expandtab shiftwidth=2 smartindent */
<commit_msg>comment on pointer ownership for geometry pointer<commit_after>#include "php.h"
#include "php_gdal.h"
#include <ogr_core.h>
#include <cpl_conv.h>
#include <cpl_string.h>
#include "ogrexception.h"
#include "ogrspatialreference.h"
#include "ogrgeometry.h"
zend_class_entry *gdal_ogrgeometry_ce;
zend_object_handlers ogrgeometry_object_handlers;
void ogrgeometry_free_storage(void *object TSRMLS_DC)
{
php_ogrgeometry_object *obj = (php_ogrgeometry_object *)object;
delete obj->geometry; // currently all pointers here are only references which
// should not be modified
zend_hash_destroy(obj->std.properties);
FREE_HASHTABLE(obj->std.properties);
efree(obj);
}
zend_object_value ogrgeometry_create_handler(zend_class_entry *type TSRMLS_DC)
{
zval *tmp;
zend_object_value retval;
php_ogrgeometry_object *obj =
(php_ogrgeometry_object *)emalloc(sizeof(php_ogrgeometry_object));
memset(obj, 0, sizeof(php_ogrgeometry_object));
obj->std.ce = type;
ALLOC_HASHTABLE(obj->std.properties);
zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
#if PHP_VERSION_ID < 50399
zend_hash_copy(obj->std.properties, &type->default_properties,
(copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));
#else
object_properties_init(&obj->std, type);
#endif
retval.handle = zend_objects_store_put(obj, NULL,
ogrgeometry_free_storage, NULL TSRMLS_CC);
retval.handlers = &ogrgeometry_object_handlers;
return retval;
}
PHP_METHOD(OGRGeometry, IsValid)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
RETURN_BOOL(geometry->IsValid());
}
PHP_METHOD(OGRGeometry, ExportToWkt)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *ppszDstText;
char *ret;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
if (geometry->exportToWkt(&ppszDstText) != OGRERR_NONE) {
php_gdal_ogr_throw("Failed to convert geometry to WKT");
RETURN_EMPTY_STRING();
}
ret = estrdup(ppszDstText);
OGRFree(ppszDstText);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, ExportToWkb)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
int wkbSize;
char * buffer;
int wkbByteOrder = wkbNDR; // use as default when no byteOrder is specified
if (ZEND_NUM_ARGS() != 0) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l",
&wkbByteOrder) == FAILURE) {
php_gdal_ogr_throw("Illegal value for byteOrder");
RETURN_EMPTY_STRING();
}
}
if ((wkbByteOrder) != wkbNDR && (wkbByteOrder != wkbXDR)) {
php_gdal_ogr_throw("Illegal value for byteOrder. Has to be either wkbNDR or wkbXDR");
RETURN_EMPTY_STRING();
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
wkbSize = geometry->WkbSize();
buffer = (char*)ecalloc(sizeof(char), wkbSize+1);
if (geometry->exportToWkb(wkbNDR, (unsigned char*)buffer) != OGRERR_NONE) {
php_gdal_ogr_throw("Failed to convert geometry to WKB");
RETURN_EMPTY_STRING();
}
RETURN_STRINGL(buffer, wkbSize+1, 0);
}
PHP_METHOD(OGRGeometry, ExportToJson)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *jsonText;
char *ret;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
jsonText = geometry->exportToJson();
if (jsonText == NULL) {
php_gdal_ogr_throw("Failed to convert geometry to JSON");
RETURN_EMPTY_STRING();
}
ret = estrdup(jsonText);
CPLFree(jsonText);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, ExportToKML)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *kmlText;
char *ret;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
kmlText = geometry->exportToKML();
if (kmlText == NULL) {
php_gdal_ogr_throw("Failed to convert geometry to KML");
RETURN_EMPTY_STRING();
}
ret = estrdup(kmlText);
CPLFree(kmlText);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, ExportToGML)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *gmlText;
char *ret;
char *gmlOptions = NULL;
int gmlOptionsLen;
char **papszOptions = NULL;
if (ZEND_NUM_ARGS() != 0) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s", &gmlOptions, &gmlOptionsLen) == FAILURE) {
php_gdal_ogr_throw("Illegal value for GML format options");
RETURN_EMPTY_STRING();
}
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
#if ! ((GDAL_VERSION_MAJOR <= 1) && (GDAL_VERSION_MINOR < 8))
if (gmlOptionsLen != 0) {
papszOptions = CSLAddString(papszOptions, gmlOptions);
}
gmlText = geometry->exportToGML(papszOptions);
#else
gmlText = geometry->exportToGML();
#endif
#if ! ((GDAL_VERSION_MAJOR <= 1) && (GDAL_VERSION_MINOR < 8))
if (papszOptions) {
CSLDestroy(papszOptions);
}
#endif
if (gmlText == NULL) {
php_gdal_ogr_throw("Failed to convert geometry to GML");
RETURN_EMPTY_STRING();
}
ret = estrdup(gmlText);
CPLFree(gmlText);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, GetGeometryName)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
char *ret;
const char *geomName;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
geomName = geometry->getGeometryName();
ret = estrdup(geomName);
RETURN_STRING(ret, 0);
}
PHP_METHOD(OGRGeometry, GetGeometryType)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
RETURN_LONG(geometry->getGeometryType());
}
PHP_METHOD(OGRGeometry, IsEmpty)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
RETURN_BOOL(geometry->IsEmpty());
}
PHP_METHOD(OGRGeometry, GetSpatialReference)
{
OGRGeometry *geometry;
php_ogrgeometry_object *obj;
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *spatialreference_obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
geometry = obj->geometry;
spatialreference = geometry->getSpatialReference();
if (!spatialreference) {
RETURN_NULL();
}
if (object_init_ex(return_value, gdal_ogrspatialreference_ce) != SUCCESS) {
RETURN_NULL();
}
spatialreference_obj = (php_ogrspatialreference_object*) zend_objects_get_address(return_value TSRMLS_CC);
spatialreference_obj->spatialreference = spatialreference;
}
zend_function_entry ogrgeometry_methods[] = {
PHP_ME(OGRGeometry, IsValid, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToWkt, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToWkb, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToJson, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToKML, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, ExportToGML, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, GetGeometryName, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, GetGeometryType, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, IsEmpty, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRGeometry, GetSpatialReference, NULL, ZEND_ACC_PUBLIC)
{NULL, NULL, NULL}
};
void php_gdal_ogrgeometry_startup(INIT_FUNC_ARGS)
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "OGRGeometry", ogrgeometry_methods);
gdal_ogrgeometry_ce = zend_register_internal_class(&ce TSRMLS_CC);
gdal_ogrgeometry_ce->create_object = ogrgeometry_create_handler;
memcpy(&ogrgeometry_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
ogrgeometry_object_handlers.clone_obj = NULL;
}
/* VIM settings */
/* ex: set tabstop=2 expandtab shiftwidth=2 smartindent */
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include "types/type.h"
#include "modules/std/unicode/string.h"
#include "unicode/unistr.h"
#include "core/value.h"
namespace clever { namespace packages { namespace std {
#define CLEVER_USTR_TYPE icu::UnicodeString*
#define CLEVER_USTR_THIS() (CLEVER_USTR_TYPE) CLEVER_THIS()->getObj()
void* UnicodeString::allocData(CLEVER_TYPE_CTOR_ARGS) const {
if (args->size()) {
Value* from = args->at(0);
if (from) {
const CString* str = from->getStr();
if (str) {
return new icu::UnicodeString(
str->c_str(), str->size(), US_INV
);
}
}
}
return NULL;
}
void UnicodeString::deallocData(void *data) {
delete (icu::UnicodeString*) data;
}
CLEVER_METHOD(UnicodeString::dbg) {
if (CLEVER_THIS()) {
CLEVER_USTR_TYPE intern = CLEVER_USTR_THIS();
if (intern) {
printf("Fetched UnicodeString from Object\n");
}
}
}
CLEVER_TYPE_OPERATOR(UnicodeString::add) {}
CLEVER_TYPE_OPERATOR(UnicodeString::sub) {}
CLEVER_TYPE_OPERATOR(UnicodeString::mul) {}
CLEVER_TYPE_OPERATOR(UnicodeString::div) {}
CLEVER_TYPE_OPERATOR(UnicodeString::mod) {}
CLEVER_TYPE_OPERATOR(UnicodeString::greater) {}
CLEVER_TYPE_OPERATOR(UnicodeString::greater_equal) {}
CLEVER_TYPE_OPERATOR(UnicodeString::less) {}
CLEVER_TYPE_OPERATOR(UnicodeString::less_equal) {}
CLEVER_TYPE_OPERATOR(UnicodeString::equal) {}
CLEVER_TYPE_OPERATOR(UnicodeString::not_equal) {}
CLEVER_TYPE_INIT(UnicodeString::init)
{
addMethod(CSTRING("dbg"), (MethodPtr) &UnicodeString::dbg);
}
}}} // clever::packages::std
<commit_msg>macros everywhere<commit_after>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include "types/type.h"
#include "modules/std/unicode/string.h"
#include "unicode/unistr.h"
#include "core/value.h"
namespace clever { namespace packages { namespace std {
#define CLEVER_USTR_TYPE icu::UnicodeString*
#define CLEVER_USTR_CAST (CLEVER_USTR_TYPE)
#define CLEVER_USTR_THIS() CLEVER_USTR_CAST CLEVER_THIS()->getObj()
void* UnicodeString::allocData(CLEVER_TYPE_CTOR_ARGS) const {
if (args->size()) {
Value* from = args->at(0);
if (from) {
const CString* str = from->getStr();
if (str) {
return new icu::UnicodeString(
str->c_str(), str->size(), US_INV
);
}
}
}
return NULL;
}
void UnicodeString::deallocData(void *data) {
delete CLEVER_USTR_CAST data;
}
CLEVER_METHOD(UnicodeString::dbg) {
if (CLEVER_THIS()) {
CLEVER_USTR_TYPE intern = CLEVER_USTR_THIS();
if (intern) {
printf("Fetched UnicodeString from Object\n");
}
}
}
CLEVER_TYPE_OPERATOR(UnicodeString::add) {}
CLEVER_TYPE_OPERATOR(UnicodeString::sub) {}
CLEVER_TYPE_OPERATOR(UnicodeString::mul) {}
CLEVER_TYPE_OPERATOR(UnicodeString::div) {}
CLEVER_TYPE_OPERATOR(UnicodeString::mod) {}
CLEVER_TYPE_OPERATOR(UnicodeString::greater) {}
CLEVER_TYPE_OPERATOR(UnicodeString::greater_equal) {}
CLEVER_TYPE_OPERATOR(UnicodeString::less) {}
CLEVER_TYPE_OPERATOR(UnicodeString::less_equal) {}
CLEVER_TYPE_OPERATOR(UnicodeString::equal) {}
CLEVER_TYPE_OPERATOR(UnicodeString::not_equal) {}
CLEVER_TYPE_INIT(UnicodeString::init)
{
addMethod(CSTRING("dbg"), (MethodPtr) &UnicodeString::dbg);
}
}}} // clever::packages::std
<|endoftext|> |
<commit_before>#include <foot_contact_alt/FootContactAlt.h>
using namespace TwoLegs;
using namespace std;
FootContactAlt::FootContactAlt(bool _log_data_files,const float atlasWeight){
cout << "A new FootContactAlt object was created" << endl;
// was 1400*0.65 for a long time, but this didn't work with toe lift off stepping
schmitt_level_ = 0.65;
transition_timeout_ = 4000;
////////////////////////////////////////////
standing_foot = F_UNKNOWN;
lcmutime = 0;
deltautime = 0;
expectedweight = atlasWeight;
foottransitionintermediateflag = true;
l_foot_force_z = 0.f;
r_foot_force_z = 0.f;
transition_timespan = 0;
// actual noticable toe push off occurs with about 50:50 ratio: 760:760 or even later
// To reduce tic-tocing you can reduce the first number
// originally 275/375 was ok, but some upward drift (3/4 of a block height) and backward drift (1/3 of a block length)
// later 475/525 was better, upward drift (1/2 of block) and backward drift (about the same)
left_contact_state_strong_ = new SchmittTrigger(525.0, 575.0, 7000, 7000);
right_contact_state_strong_ = new SchmittTrigger(525.0, 575.0, 7000, 7000);
left_contact_state_strong_->forceHigh();
right_contact_state_strong_->forceHigh();
verbose_ =1; // 3 lots, 2 some, 1 v.important
}
contact_status_id FootContactAlt::DetectFootTransition(int64_t utime, float leftz, float rightz) {
bool lf_state_last = (bool) left_contact_state_strong_->getState();
bool rf_state_last = (bool) right_contact_state_strong_->getState();
left_contact_state_strong_->UpdateState(utime, leftz);
right_contact_state_strong_->UpdateState(utime, rightz);
bool lf_state = (bool) left_contact_state_strong_->getState();
bool rf_state = (bool) right_contact_state_strong_->getState();
std::stringstream ss;
ss << (int)standing_foot << " | " << lf_state << " " << rf_state << " ";
if (!lf_state_last && lf_state){
if (verbose_ >= 1) std::cout << ss.str() << "Left has gone high\n";
standing_foot = F_LEFT;
return F_LEFT_NEW;
}else if(!rf_state_last && rf_state){
if (verbose_ >= 1) std::cout << ss.str() << "Right has gone high\n";
standing_foot = F_RIGHT;
return F_RIGHT_NEW;
}else if(lf_state_last && !lf_state){
if (verbose_ >= 3) std::cout << ss.str() << "Left has gone low\n";
if (standing_foot==F_LEFT){
if (verbose_ >= 1) std::cout << ss.str() << "Left has gone low when used as standing, force switch to right "<< leftz << " | "<< rightz <<"\n";
standing_foot = F_RIGHT;
return F_RIGHT_NEW;
}else{
if (verbose_ >= 3) std::cout << ss.str() << "Left has gone low when used not used as standing. Continue with right\n";
return F_RIGHT_FIXED;
}
}else if(rf_state_last && !rf_state){
if (verbose_ >= 3) std::cout << ss.str() << "Right has gone low\n";
if (standing_foot==F_RIGHT){
if (verbose_ >= 1) std::cout << ss.str() << "Right has gone low when used as standing, force switch to left "<< leftz << " | "<< rightz <<"\n";
standing_foot = F_LEFT;
return F_LEFT_NEW;
}else{
if (verbose_ >= 3) std::cout << ss.str() << "Right has gone low when used not used as standing. Continue with left\n";
return F_LEFT_FIXED;
}
}else{
if (standing_foot==F_LEFT){
if (verbose_ >= 3) std::cout << ss.str() << "Left No change\n";
return F_LEFT_FIXED;
}else if (standing_foot==F_RIGHT){
if (verbose_ >= 3) std::cout << ss.str() << "Right No change\n";
return F_RIGHT_FIXED;
}
}
std::cout << ss.str() << "Situation unknown. Error\n";
exit(-1);
return F_STATUS_UNKNOWN;
}
void FootContactAlt::setStandingFoot(footid_alt foot) {
standing_foot = foot;
}
footid_alt FootContactAlt::getStandingFoot() {
return standing_foot;
}
footid_alt FootContactAlt::getSecondaryFoot() {
if (standing_foot == F_LEFT)
return F_RIGHT;
if (standing_foot == F_RIGHT)
return F_LEFT;
std::cout << "FootContactAlt::secondary_foot(): THIS SHOULD NOT HAPPEN THE FOOT NUMBERS ARE INCONSISTENT\n";
return F_UNKNOWN;
}
float FootContactAlt::getPrimaryFootZforce() {
if (standing_foot == F_LEFT)
return l_foot_force_z;
return r_foot_force_z;
}
float FootContactAlt::getSecondaryFootZforce() {
if (standing_foot == F_LEFT)
return r_foot_force_z;
return l_foot_force_z;
}
<commit_msg>fix for bdi toe off<commit_after>#include <foot_contact_alt/FootContactAlt.h>
using namespace TwoLegs;
using namespace std;
FootContactAlt::FootContactAlt(bool _log_data_files,const float atlasWeight){
cout << "A new FootContactAlt object was created" << endl;
// was 1400*0.65 for a long time, but this didn't work with toe lift off stepping
schmitt_level_ = 0.65;
transition_timeout_ = 4000;
////////////////////////////////////////////
standing_foot = F_UNKNOWN;
lcmutime = 0;
deltautime = 0;
expectedweight = atlasWeight;
foottransitionintermediateflag = true;
l_foot_force_z = 0.f;
r_foot_force_z = 0.f;
transition_timespan = 0;
// actual noticable toe push off occurs with about 50:50 ratio: 760:760 or even later
// To reduce tic-tocing you can reduce the first number
// originally 275/375 was ok, but some upward drift (3/4 of a block height) and backward drift (1/3 of a block length)
// later 475/525 was better, upward drift (1/2 of block) and backward drift (about the same)
// From April 2014 to Sept 2014 I used 525.0, 575.0, 7000, 7000
//left_contact_state_strong_ = new SchmittTrigger(525.0, 575.0, 7000, 7000);
//right_contact_state_strong_ = new SchmittTrigger(525.0, 575.0, 7000, 7000);
left_contact_state_strong_ = new SchmittTrigger(475.0, 525.0, 7000, 7000);
right_contact_state_strong_ = new SchmittTrigger(475.0, 525.0, 7000, 7000);
left_contact_state_strong_->forceHigh();
right_contact_state_strong_->forceHigh();
verbose_ =1; // 3 lots, 2 some, 1 v.important
}
contact_status_id FootContactAlt::DetectFootTransition(int64_t utime, float leftz, float rightz) {
bool lf_state_last = (bool) left_contact_state_strong_->getState();
bool rf_state_last = (bool) right_contact_state_strong_->getState();
left_contact_state_strong_->UpdateState(utime, leftz);
right_contact_state_strong_->UpdateState(utime, rightz);
bool lf_state = (bool) left_contact_state_strong_->getState();
bool rf_state = (bool) right_contact_state_strong_->getState();
std::stringstream ss;
ss << (int)standing_foot << " | " << lf_state << " " << rf_state << " ";
if (!lf_state_last && lf_state){
if (verbose_ >= 1) std::cout << ss.str() << "Left has gone high\n";
standing_foot = F_LEFT;
return F_LEFT_NEW;
}else if(!rf_state_last && rf_state){
if (verbose_ >= 1) std::cout << ss.str() << "Right has gone high\n";
standing_foot = F_RIGHT;
return F_RIGHT_NEW;
}else if(lf_state_last && !lf_state){
if (verbose_ >= 3) std::cout << ss.str() << "Left has gone low\n";
if (standing_foot==F_LEFT){
if (verbose_ >= 1) std::cout << ss.str() << "Left has gone low when used as standing, force switch to right "<< leftz << " | "<< rightz <<"\n";
standing_foot = F_RIGHT;
return F_RIGHT_NEW;
}else{
if (verbose_ >= 3) std::cout << ss.str() << "Left has gone low when used not used as standing. Continue with right\n";
return F_RIGHT_FIXED;
}
}else if(rf_state_last && !rf_state){
if (verbose_ >= 3) std::cout << ss.str() << "Right has gone low\n";
if (standing_foot==F_RIGHT){
if (verbose_ >= 1) std::cout << ss.str() << "Right has gone low when used as standing, force switch to left "<< leftz << " | "<< rightz <<"\n";
standing_foot = F_LEFT;
return F_LEFT_NEW;
}else{
if (verbose_ >= 3) std::cout << ss.str() << "Right has gone low when used not used as standing. Continue with left\n";
return F_LEFT_FIXED;
}
}else{
if (standing_foot==F_LEFT){
if (verbose_ >= 3) std::cout << ss.str() << "Left No change\n";
return F_LEFT_FIXED;
}else if (standing_foot==F_RIGHT){
if (verbose_ >= 3) std::cout << ss.str() << "Right No change\n";
return F_RIGHT_FIXED;
}
}
std::cout << ss.str() << "Situation unknown. Error\n";
exit(-1);
return F_STATUS_UNKNOWN;
}
void FootContactAlt::setStandingFoot(footid_alt foot) {
standing_foot = foot;
}
footid_alt FootContactAlt::getStandingFoot() {
return standing_foot;
}
footid_alt FootContactAlt::getSecondaryFoot() {
if (standing_foot == F_LEFT)
return F_RIGHT;
if (standing_foot == F_RIGHT)
return F_LEFT;
std::cout << "FootContactAlt::secondary_foot(): THIS SHOULD NOT HAPPEN THE FOOT NUMBERS ARE INCONSISTENT\n";
return F_UNKNOWN;
}
float FootContactAlt::getPrimaryFootZforce() {
if (standing_foot == F_LEFT)
return l_foot_force_z;
return r_foot_force_z;
}
float FootContactAlt::getSecondaryFootZforce() {
if (standing_foot == F_LEFT)
return r_foot_force_z;
return l_foot_force_z;
}
<|endoftext|> |
<commit_before>#include "../../SDP_Solver_Terminate_Reason.hxx"
#include "../../../SDP_Solver_Parameters.hxx"
void compute_feasible_and_termination(
const SDP_Solver_Parameters ¶meters, const El::BigFloat &primal_error,
const El::BigFloat &dual_error, const El::BigFloat &duality_gap,
const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,
const int &iteration,
const std::chrono::time_point<std::chrono::high_resolution_clock>
&solver_start_time,
bool &is_primal_and_dual_feasible,
SDP_Solver_Terminate_Reason &terminate_reason, bool &terminate_now)
{
const bool is_dual_feasible(dual_error < parameters.dual_error_threshold),
is_primal_feasible(primal_error < parameters.primal_error_threshold);
is_primal_and_dual_feasible = (is_primal_feasible && is_dual_feasible);
const bool is_optimal(duality_gap < parameters.duality_gap_threshold);
terminate_now = true;
if(is_primal_feasible && parameters.find_primal_feasible)
{
terminate_reason = SDP_Solver_Terminate_Reason::PrimalFeasible;
}
else if(is_dual_feasible && parameters.find_dual_feasible)
{
terminate_reason = SDP_Solver_Terminate_Reason::DualFeasible;
}
else if(primal_step_length == El::BigFloat(1)
&& parameters.detect_primal_feasible_jump)
{
terminate_reason
= SDP_Solver_Terminate_Reason::PrimalFeasibleJumpDetected;
}
else if(dual_step_length == El::BigFloat(1)
&& parameters.detect_dual_feasible_jump)
{
terminate_reason = SDP_Solver_Terminate_Reason::DualFeasibleJumpDetected;
}
else if(is_primal_and_dual_feasible && is_optimal)
{
terminate_reason = SDP_Solver_Terminate_Reason::PrimalDualOptimal;
}
else if(iteration > parameters.max_iterations)
{
terminate_reason = SDP_Solver_Terminate_Reason::MaxIterationsExceeded;
}
else if(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::high_resolution_clock::now() - solver_start_time)
.count()
>= parameters.max_runtime)
{
terminate_reason = SDP_Solver_Terminate_Reason::MaxRuntimeExceeded;
}
else
{
terminate_now = false;
}
El::byte terminate_byte(terminate_now);
// Time varies between cores, so follow the decision of the root.
El::mpi::Broadcast(terminate_byte, 0, El::mpi::COMM_WORLD);
terminate_now = static_cast<bool>(terminate_byte);
}
<commit_msg>Rearrange some termination conditions<commit_after>#include "../../SDP_Solver_Terminate_Reason.hxx"
#include "../../../SDP_Solver_Parameters.hxx"
void compute_feasible_and_termination(
const SDP_Solver_Parameters ¶meters, const El::BigFloat &primal_error,
const El::BigFloat &dual_error, const El::BigFloat &duality_gap,
const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,
const int &iteration,
const std::chrono::time_point<std::chrono::high_resolution_clock>
&solver_start_time,
bool &is_primal_and_dual_feasible,
SDP_Solver_Terminate_Reason &terminate_reason, bool &terminate_now)
{
const bool is_dual_feasible(dual_error < parameters.dual_error_threshold),
is_primal_feasible(primal_error < parameters.primal_error_threshold);
is_primal_and_dual_feasible = (is_primal_feasible && is_dual_feasible);
const bool is_optimal(duality_gap < parameters.duality_gap_threshold);
terminate_now = true;
if(is_primal_and_dual_feasible && is_optimal)
{
terminate_reason = SDP_Solver_Terminate_Reason::PrimalDualOptimal;
}
else if(is_dual_feasible && parameters.find_dual_feasible)
{
terminate_reason = SDP_Solver_Terminate_Reason::DualFeasible;
}
else if(is_primal_feasible && parameters.find_primal_feasible)
{
terminate_reason = SDP_Solver_Terminate_Reason::PrimalFeasible;
}
else if(dual_step_length == El::BigFloat(1)
&& parameters.detect_dual_feasible_jump)
{
terminate_reason = SDP_Solver_Terminate_Reason::DualFeasibleJumpDetected;
}
else if(primal_step_length == El::BigFloat(1)
&& parameters.detect_primal_feasible_jump)
{
terminate_reason
= SDP_Solver_Terminate_Reason::PrimalFeasibleJumpDetected;
}
else if(iteration > parameters.max_iterations)
{
terminate_reason = SDP_Solver_Terminate_Reason::MaxIterationsExceeded;
}
else if(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::high_resolution_clock::now() - solver_start_time)
.count()
>= parameters.max_runtime)
{
terminate_reason = SDP_Solver_Terminate_Reason::MaxRuntimeExceeded;
}
else
{
terminate_now = false;
}
El::byte terminate_byte(terminate_now);
// Time varies between cores, so follow the decision of the root.
El::mpi::Broadcast(terminate_byte, 0, El::mpi::COMM_WORLD);
terminate_now = static_cast<bool>(terminate_byte);
}
<|endoftext|> |
<commit_before>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "ShaderInstance.h"
#include "GLContext.h"
namespace n {
namespace graphics {
ShaderInstance *ShaderInstance::current = 0;
ShaderInstance::ShaderInstance(Shader<FragmentShader> *frag, Shader<VertexShader> *vert, Shader<GeometryShader> *geom) : handle(0), samplerCount(0), bases{frag, vert, geom} {
compile();
}
ShaderInstance::ShaderInstance(Shader<FragmentShader> *frag, ShaderProgram::StandardVertexShader vert, Shader<GeometryShader> *geom) : ShaderInstance(frag, ShaderProgram::getStandardVertexShader(vert), geom) {
}
ShaderInstance::~ShaderInstance() {
if(handle) {
gl::GLuint h = handle;
GLContext::getContext()->addGLTask([=]() { gl::glDeleteProgram(h); });
}
}
const ShaderInstance *ShaderInstance::getCurrent() {
return current;
}
void ShaderInstance::bind() {
GLContext::getContext()->program = 0;
if(current != this) {
rebind();
}
}
void ShaderInstance::rebind() {
GLContext::getContext()->program = 0;
gl::glUseProgram(handle);
for(uint i = 0; i != samplerCount; i++) {
bindings[i].bind(i);
}
current = this;
//bindStandards();
}
void ShaderInstance::unbind() {
current = 0;
internal::rebindProgram();
}
void ShaderInstance::compile() {
handle = gl::glCreateProgram();
bool val = true;
for(uint i = 0; i != 3; i++) {
if(bases[i]) {
gl::glAttachShader(handle, bases[i]->handle);
val &= bases[i]->isValid();
}
}
gl::glLinkProgram(handle);
int res = 0;
gl::glGetProgramiv(handle, GL_LINK_STATUS, &res);
if(!res || !val) {
int size = 0;
gl::glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &size);
char *msg = new char[size + 1];
gl::glGetProgramInfoLog(handle, size, &res, msg);
gl::glDeleteProgram(handle);
handle = 0;
msg[size] = '\0';
core::String logs = msg;
delete[] msg;
throw ShaderLinkingException(logs);
} else {
getUniforms();
}
}
void ShaderInstance::getUniforms() {
const uint max = 512;
char name[max];
int uniforms = 0;
gl::glGetProgramiv(handle, GL_ACTIVE_UNIFORMS, &uniforms);
for(uint i = 0; i != SVMax; i++) {
standards[i] = UniformAddr(GL_INVALID_INDEX);
}
for(uint i = 0; i != (uint)uniforms; i++) {
gl::GLsizei size = 0;
gl::GLenum type = GL_NONE;
gl::glGetActiveUniform(handle, i, max - 1, 0, &size, &type, name);
core::String uniform = name;
if(uniform.endsWith("[0]")) {
uniform = uniform.subString(0, uniform.size() - 3);
}
UniformInfo info({gl::glGetUniformLocation(handle, name), (uint)size});
if(isSampler(type)) {
uint slot = samplerCount++;
setValue(info.addr, int(slot));
info.addr = slot;
}
uniformsInfo[uniform] = info;
int std = computeStandardIndex(uniform);
if(std != UniformAddr(GL_INVALID_INDEX)) {
standards[std] = info.addr;
}
}
bindings = new internal::TextureBinding[samplerCount];
}
ShaderInstance::UniformAddr ShaderInstance::computeStandardIndex(const core::String &name) {
for(uint i = 0; i != SVMax; i++) {
if(name == ShaderValueName[i]) {
return i;
}
}
return UniformAddr(GL_INVALID_INDEX);
}
void ShaderInstance::bindStandards() const {
setValue("n_ProjectionMatrix", GLContext::getContext()->getProjectionMatrix());
setValue("n_ViewMatrix", GLContext::getContext()->getViewMatrix());
setValue("n_ViewportSize", math::Vec2(GLContext::getContext()->getViewport()));
setValue("n_ModelMatrix", GLContext::getContext()->getModelMatrix());
setValue("n_ViewProjectionMatrix", GLContext::getContext()->getProjectionMatrix() * GLContext::getContext()->getViewMatrix());
}
void ShaderInstance::setValue(UniformAddr addr, int a) const {
gl::glProgramUniform1i(handle, addr, a);
}
void ShaderInstance::setValue(UniformAddr addr, uint a) const {
gl::glProgramUniform1ui(handle, addr, a);
}
void ShaderInstance::setValue(UniformAddr addr, float f) const {
gl::glProgramUniform1f(handle, addr, f);
}
void ShaderInstance::setValue(UniformAddr addr, double f) const {
gl::glProgramUniform1f(handle, addr, f);
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec2i &v) const {
gl::glProgramUniform2iv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec3i &v) const {
gl::glProgramUniform3iv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec2 &v) const {
gl::glProgramUniform2fv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec3 &v) const {
gl::glProgramUniform3fv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec4 &v) const {
gl::glProgramUniform4fv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Matrix2<float> &m) const {
gl::glProgramUniformMatrix2fv(handle, addr, 1, GL_TRUE, m.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Matrix3<float> &m) const {
gl::glProgramUniformMatrix3fv(handle, addr, 1, GL_TRUE, m.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Matrix4<float> &m) const {
gl::glProgramUniformMatrix4fv(handle, addr, 1, GL_TRUE, m.begin());
}
void ShaderInstance::setValue(UniformAddr slot, const Texture &t, TextureSampler sampler) const {
if(slot != UniformAddr(GL_INVALID_INDEX)) {
bindings[slot] = t;
bindings[slot] = sampler;
if(current == this) {
bindings[slot].bind(slot);
} else {
t.prepare();
}
}
}
ShaderInstance::UniformAddr ShaderInstance::getAddr(const core::String &name) const {
return getInfo(name).addr;
}
ShaderInstance::UniformInfo ShaderInstance::getInfo(const core::String &name) const { return uniformsInfo.get(name, UniformInfo{UniformAddr(GL_INVALID_INDEX), 0});
}
}
}
<commit_msg>Fixed mem leaks.<commit_after>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "ShaderInstance.h"
#include "GLContext.h"
namespace n {
namespace graphics {
ShaderInstance *ShaderInstance::current = 0;
ShaderInstance::ShaderInstance(Shader<FragmentShader> *frag, Shader<VertexShader> *vert, Shader<GeometryShader> *geom) : handle(0), samplerCount(0), bases{frag, vert, geom} {
compile();
}
ShaderInstance::ShaderInstance(Shader<FragmentShader> *frag, ShaderProgram::StandardVertexShader vert, Shader<GeometryShader> *geom) : ShaderInstance(frag, ShaderProgram::getStandardVertexShader(vert), geom) {
}
ShaderInstance::~ShaderInstance() {
if(handle) {
gl::GLuint h = handle;
GLContext::getContext()->addGLTask([=]() { gl::glDeleteProgram(h); });
}
delete[] bindings;
}
const ShaderInstance *ShaderInstance::getCurrent() {
return current;
}
void ShaderInstance::bind() {
GLContext::getContext()->program = 0;
if(current != this) {
rebind();
}
}
void ShaderInstance::rebind() {
GLContext::getContext()->program = 0;
gl::glUseProgram(handle);
for(uint i = 0; i != samplerCount; i++) {
bindings[i].bind(i);
}
current = this;
//bindStandards();
}
void ShaderInstance::unbind() {
current = 0;
internal::rebindProgram();
}
void ShaderInstance::compile() {
handle = gl::glCreateProgram();
bool val = true;
for(uint i = 0; i != 3; i++) {
if(bases[i]) {
gl::glAttachShader(handle, bases[i]->handle);
val &= bases[i]->isValid();
}
}
gl::glLinkProgram(handle);
int res = 0;
gl::glGetProgramiv(handle, GL_LINK_STATUS, &res);
if(!res || !val) {
int size = 0;
gl::glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &size);
char *msg = new char[size + 1];
gl::glGetProgramInfoLog(handle, size, &res, msg);
gl::glDeleteProgram(handle);
handle = 0;
msg[size] = '\0';
core::String logs = msg;
delete[] msg;
throw ShaderLinkingException(logs);
} else {
getUniforms();
}
}
void ShaderInstance::getUniforms() {
const uint max = 512;
char name[max];
int uniforms = 0;
gl::glGetProgramiv(handle, GL_ACTIVE_UNIFORMS, &uniforms);
for(uint i = 0; i != SVMax; i++) {
standards[i] = UniformAddr(GL_INVALID_INDEX);
}
for(uint i = 0; i != (uint)uniforms; i++) {
gl::GLsizei size = 0;
gl::GLenum type = GL_NONE;
gl::glGetActiveUniform(handle, i, max - 1, 0, &size, &type, name);
core::String uniform = name;
if(uniform.endsWith("[0]")) {
uniform = uniform.subString(0, uniform.size() - 3);
}
UniformInfo info({gl::glGetUniformLocation(handle, name), (uint)size});
if(isSampler(type)) {
uint slot = samplerCount++;
setValue(info.addr, int(slot));
info.addr = slot;
}
uniformsInfo[uniform] = info;
int std = computeStandardIndex(uniform);
if(std != UniformAddr(GL_INVALID_INDEX)) {
standards[std] = info.addr;
}
}
bindings = new internal::TextureBinding[samplerCount];
}
ShaderInstance::UniformAddr ShaderInstance::computeStandardIndex(const core::String &name) {
for(uint i = 0; i != SVMax; i++) {
if(name == ShaderValueName[i]) {
return i;
}
}
return UniformAddr(GL_INVALID_INDEX);
}
void ShaderInstance::bindStandards() const {
setValue("n_ProjectionMatrix", GLContext::getContext()->getProjectionMatrix());
setValue("n_ViewMatrix", GLContext::getContext()->getViewMatrix());
setValue("n_ViewportSize", math::Vec2(GLContext::getContext()->getViewport()));
setValue("n_ModelMatrix", GLContext::getContext()->getModelMatrix());
setValue("n_ViewProjectionMatrix", GLContext::getContext()->getProjectionMatrix() * GLContext::getContext()->getViewMatrix());
}
void ShaderInstance::setValue(UniformAddr addr, int a) const {
gl::glProgramUniform1i(handle, addr, a);
}
void ShaderInstance::setValue(UniformAddr addr, uint a) const {
gl::glProgramUniform1ui(handle, addr, a);
}
void ShaderInstance::setValue(UniformAddr addr, float f) const {
gl::glProgramUniform1f(handle, addr, f);
}
void ShaderInstance::setValue(UniformAddr addr, double f) const {
gl::glProgramUniform1f(handle, addr, f);
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec2i &v) const {
gl::glProgramUniform2iv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec3i &v) const {
gl::glProgramUniform3iv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec2 &v) const {
gl::glProgramUniform2fv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec3 &v) const {
gl::glProgramUniform3fv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Vec4 &v) const {
gl::glProgramUniform4fv(handle, addr, 1, v.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Matrix2<float> &m) const {
gl::glProgramUniformMatrix2fv(handle, addr, 1, GL_TRUE, m.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Matrix3<float> &m) const {
gl::glProgramUniformMatrix3fv(handle, addr, 1, GL_TRUE, m.begin());
}
void ShaderInstance::setValue(UniformAddr addr, const math::Matrix4<float> &m) const {
gl::glProgramUniformMatrix4fv(handle, addr, 1, GL_TRUE, m.begin());
}
void ShaderInstance::setValue(UniformAddr slot, const Texture &t, TextureSampler sampler) const {
if(slot != UniformAddr(GL_INVALID_INDEX)) {
bindings[slot] = t;
bindings[slot] = sampler;
if(current == this) {
bindings[slot].bind(slot);
} else {
t.prepare();
}
}
}
ShaderInstance::UniformAddr ShaderInstance::getAddr(const core::String &name) const {
return getInfo(name).addr;
}
ShaderInstance::UniformInfo ShaderInstance::getInfo(const core::String &name) const { return uniformsInfo.get(name, UniformInfo{UniformAddr(GL_INVALID_INDEX), 0});
}
}
}
<|endoftext|> |
<commit_before>//===- Loads.cpp - Local load analysis ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines simple local analyses for load instructions.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Target/TargetData.h"
#include "llvm/GlobalAlias.h"
#include "llvm/GlobalVariable.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Operator.h"
using namespace llvm;
/// AreEquivalentAddressValues - Test if A and B will obviously have the same
/// value. This includes recognizing that %t0 and %t1 will have the same
/// value in code like this:
/// %t0 = getelementptr \@a, 0, 3
/// store i32 0, i32* %t0
/// %t1 = getelementptr \@a, 0, 3
/// %t2 = load i32* %t1
///
static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
// Test if the values are trivially equivalent.
if (A == B) return true;
// Test if the values come from identical arithmetic instructions.
// Use isIdenticalToWhenDefined instead of isIdenticalTo because
// this function is only used when one address use dominates the
// other, which means that they'll always either have the same
// value or one of them will have an undefined value.
if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
isa<PHINode>(A) || isa<GetElementPtrInst>(A))
if (const Instruction *BI = dyn_cast<Instruction>(B))
if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
return true;
// Otherwise they may not be equivalent.
return false;
}
/// getUnderlyingObjectWithOffset - Strip off up to MaxLookup GEPs and
/// bitcasts to get back to the underlying object being addressed, keeping
/// track of the offset in bytes from the GEPs relative to the result.
/// This is closely related to GetUnderlyingObject but is located
/// here to avoid making VMCore depend on TargetData.
static Value *getUnderlyingObjectWithOffset(Value *V, const TargetData *TD,
uint64_t &ByteOffset,
unsigned MaxLookup = 6) {
if (!V->getType()->isPointerTy())
return V;
for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
if (!GEP->hasAllConstantIndices())
return V;
SmallVector<Value*, 8> Indices(GEP->op_begin() + 1, GEP->op_end());
ByteOffset += TD->getIndexedOffset(GEP->getPointerOperandType(),
&Indices[0], Indices.size());
V = GEP->getPointerOperand();
} else if (Operator::getOpcode(V) == Instruction::BitCast) {
V = cast<Operator>(V)->getOperand(0);
} else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
if (GA->mayBeOverridden())
return V;
V = GA->getAliasee();
} else {
return V;
}
assert(V->getType()->isPointerTy() && "Unexpected operand type!");
}
return V;
}
/// isSafeToLoadUnconditionally - Return true if we know that executing a load
/// from this value cannot trap. If it is not obviously safe to load from the
/// specified pointer, we do a quick local scan of the basic block containing
/// ScanFrom, to determine if the address is already accessed.
bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
unsigned Align, const TargetData *TD) {
uint64_t ByteOffset = 0;
Value *Base = V;
if (TD)
Base = getUnderlyingObjectWithOffset(V, TD, ByteOffset);
const Type *BaseType = 0;
unsigned BaseAlign = 0;
if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
// An alloca is safe to load from as load as it is suitably aligned.
BaseType = AI->getAllocatedType();
BaseAlign = AI->getAlignment();
} else if (const GlobalValue *GV = dyn_cast<GlobalValue>(Base)) {
// Global variables are safe to load from but their size cannot be
// guaranteed if they are overridden.
if (!isa<GlobalAlias>(GV) && !GV->mayBeOverridden()) {
BaseType = GV->getType()->getElementType();
BaseAlign = GV->getAlignment();
}
}
if (BaseType && BaseType->isSized()) {
if (TD && BaseAlign == 0)
BaseAlign = TD->getPrefTypeAlignment(BaseType);
if (Align <= BaseAlign) {
if (!TD)
return true; // Loading directly from an alloca or global is OK.
// Check if the load is within the bounds of the underlying object.
const PointerType *AddrTy = cast<PointerType>(V->getType());
uint64_t LoadSize = TD->getTypeStoreSize(AddrTy->getElementType());
if (ByteOffset + LoadSize <= TD->getTypeAllocSize(BaseType) &&
(Align == 0 || (ByteOffset % Align) == 0))
return true;
}
}
// Otherwise, be a little bit aggressive by scanning the local block where we
// want to check to see if the pointer is already being loaded or stored
// from/to. If so, the previous load or store would have already trapped,
// so there is no harm doing an extra load (also, CSE will later eliminate
// the load entirely).
BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
while (BBI != E) {
--BBI;
// If we see a free or a call which may write to memory (i.e. which might do
// a free) the pointer could be marked invalid.
if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
!isa<DbgInfoIntrinsic>(BBI))
return false;
if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
if (AreEquivalentAddressValues(LI->getOperand(0), V)) return true;
} else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
if (AreEquivalentAddressValues(SI->getOperand(1), V)) return true;
}
}
return false;
}
/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
/// instruction before ScanFrom) checking to see if we have the value at the
/// memory address *Ptr locally available within a small number of instructions.
/// If the value is available, return it.
///
/// If not, return the iterator for the last validated instruction that the
/// value would be live through. If we scanned the entire block and didn't find
/// something that invalidates *Ptr or provides it, ScanFrom would be left at
/// begin() and this returns null. ScanFrom could also be left
///
/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
/// it is set to 0, it will scan the whole block. You can also optionally
/// specify an alias analysis implementation, which makes this more precise.
Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
BasicBlock::iterator &ScanFrom,
unsigned MaxInstsToScan,
AliasAnalysis *AA) {
if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
// If we're using alias analysis to disambiguate get the size of *Ptr.
uint64_t AccessSize = 0;
if (AA) {
const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
AccessSize = AA->getTypeStoreSize(AccessTy);
}
while (ScanFrom != ScanBB->begin()) {
// We must ignore debug info directives when counting (otherwise they
// would affect codegen).
Instruction *Inst = --ScanFrom;
if (isa<DbgInfoIntrinsic>(Inst))
continue;
// Restore ScanFrom to expected value in case next test succeeds
ScanFrom++;
// Don't scan huge blocks.
if (MaxInstsToScan-- == 0) return 0;
--ScanFrom;
// If this is a load of Ptr, the loaded value is available.
if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
return LI;
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
// If this is a store through Ptr, the value is available!
if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
return SI->getOperand(0);
// If Ptr is an alloca and this is a store to a different alloca, ignore
// the store. This is a trivial form of alias analysis that is important
// for reg2mem'd code.
if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
(isa<AllocaInst>(SI->getOperand(1)) ||
isa<GlobalVariable>(SI->getOperand(1))))
continue;
// If we have alias analysis and it says the store won't modify the loaded
// value, ignore the store.
if (AA &&
(AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
continue;
// Otherwise the store that may or may not alias the pointer, bail out.
++ScanFrom;
return 0;
}
// If this is some other instruction that may clobber Ptr, bail out.
if (Inst->mayWriteToMemory()) {
// If alias analysis claims that it really won't modify the load,
// ignore it.
if (AA &&
(AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
continue;
// May modify the pointer, bail out.
++ScanFrom;
return 0;
}
}
// Got to the start of the block, we didn't find it, but are done for this
// block.
return 0;
}
<commit_msg>Test commit.<commit_after>//===- Loads.cpp - Local load analysis ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines simple local analyses for load instructions.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Target/TargetData.h"
#include "llvm/GlobalAlias.h"
#include "llvm/GlobalVariable.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Operator.h"
using namespace llvm;
/// AreEquivalentAddressValues - Test if A and B will obviously have the same
/// value. This includes recognizing that %t0 and %t1 will have the same
/// value in code like this:
/// %t0 = getelementptr \@a, 0, 3
/// store i32 0, i32* %t0
/// %t1 = getelementptr \@a, 0, 3
/// %t2 = load i32* %t1
///
static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
// Test if the values are trivially equivalent.
if (A == B) return true;
// Test if the values come from identical arithmetic instructions.
// Use isIdenticalToWhenDefined instead of isIdenticalTo because
// this function is only used when one address use dominates the
// other, which means that they'll always either have the same
// value or one of them will have an undefined value.
if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
isa<PHINode>(A) || isa<GetElementPtrInst>(A))
if (const Instruction *BI = dyn_cast<Instruction>(B))
if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
return true;
// Otherwise they may not be equivalent.
return false;
}
/// getUnderlyingObjectWithOffset - Strip off up to MaxLookup GEPs and
/// bitcasts to get back to the underlying object being addressed, keeping
/// track of the offset in bytes from the GEPs relative to the result.
/// This is closely related to GetUnderlyingObject but is located
/// here to avoid making VMCore depend on TargetData.
static Value *getUnderlyingObjectWithOffset(Value *V, const TargetData *TD,
uint64_t &ByteOffset,
unsigned MaxLookup = 6) {
if (!V->getType()->isPointerTy())
return V;
for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
if (!GEP->hasAllConstantIndices())
return V;
SmallVector<Value*, 8> Indices(GEP->op_begin() + 1, GEP->op_end());
ByteOffset += TD->getIndexedOffset(GEP->getPointerOperandType(),
&Indices[0], Indices.size());
V = GEP->getPointerOperand();
} else if (Operator::getOpcode(V) == Instruction::BitCast) {
V = cast<Operator>(V)->getOperand(0);
} else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
if (GA->mayBeOverridden())
return V;
V = GA->getAliasee();
} else {
return V;
}
assert(V->getType()->isPointerTy() && "Unexpected operand type!");
}
return V;
}
/// isSafeToLoadUnconditionally - Return true if we know that executing a load
/// from this value cannot trap. If it is not obviously safe to load from the
/// specified pointer, we do a quick local scan of the basic block containing
/// ScanFrom, to determine if the address is already accessed.
bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
unsigned Align, const TargetData *TD) {
uint64_t ByteOffset = 0;
Value *Base = V;
if (TD)
Base = getUnderlyingObjectWithOffset(V, TD, ByteOffset);
const Type *BaseType = 0;
unsigned BaseAlign = 0;
if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
// An alloca is safe to load from as load as it is suitably aligned.
BaseType = AI->getAllocatedType();
BaseAlign = AI->getAlignment();
} else if (const GlobalValue *GV = dyn_cast<GlobalValue>(Base)) {
// Global variables are safe to load from but their size cannot be
// guaranteed if they are overridden.
if (!isa<GlobalAlias>(GV) && !GV->mayBeOverridden()) {
BaseType = GV->getType()->getElementType();
BaseAlign = GV->getAlignment();
}
}
if (BaseType && BaseType->isSized()) {
if (TD && BaseAlign == 0)
BaseAlign = TD->getPrefTypeAlignment(BaseType);
if (Align <= BaseAlign) {
if (!TD)
return true; // Loading directly from an alloca or global is OK.
// Check if the load is within the bounds of the underlying object.
const PointerType *AddrTy = cast<PointerType>(V->getType());
uint64_t LoadSize = TD->getTypeStoreSize(AddrTy->getElementType());
if (ByteOffset + LoadSize <= TD->getTypeAllocSize(BaseType) &&
(Align == 0 || (ByteOffset % Align) == 0))
return true;
}
}
// Otherwise, be a little bit aggressive by scanning the local block where we
// want to check to see if the pointer is already being loaded or stored
// from/to. If so, the previous load or store would have already trapped,
// so there is no harm doing an extra load (also, CSE will later eliminate
// the load entirely).
BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
while (BBI != E) {
--BBI;
// If we see a free or a call which may write to memory (i.e. which might do
// a free) the pointer could be marked invalid.
if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
!isa<DbgInfoIntrinsic>(BBI))
return false;
if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
if (AreEquivalentAddressValues(LI->getOperand(0), V)) return true;
} else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
if (AreEquivalentAddressValues(SI->getOperand(1), V)) return true;
}
}
return false;
}
/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
/// instruction before ScanFrom) checking to see if we have the value at the
/// memory address *Ptr locally available within a small number of instructions.
/// If the value is available, return it.
///
/// If not, return the iterator for the last validated instruction that the
/// value would be live through. If we scanned the entire block and didn't find
/// something that invalidates *Ptr or provides it, ScanFrom would be left at
/// begin() and this returns null. ScanFrom could also be left
///
/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
/// it is set to 0, it will scan the whole block. You can also optionally
/// specify an alias analysis implementation, which makes this more precise.
Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
BasicBlock::iterator &ScanFrom,
unsigned MaxInstsToScan,
AliasAnalysis *AA) {
if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
// If we're using alias analysis to disambiguate get the size of *Ptr.
uint64_t AccessSize = 0;
if (AA) {
const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
AccessSize = AA->getTypeStoreSize(AccessTy);
}
while (ScanFrom != ScanBB->begin()) {
// We must ignore debug info directives when counting (otherwise they
// would affect codegen).
Instruction *Inst = --ScanFrom;
if (isa<DbgInfoIntrinsic>(Inst))
continue;
// Restore ScanFrom to expected value in case next test succeeds
ScanFrom++;
// Don't scan huge blocks.
if (MaxInstsToScan-- == 0) return 0;
--ScanFrom;
// If this is a load of Ptr, the loaded value is available.
if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
return LI;
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
// If this is a store through Ptr, the value is available!
if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
return SI->getOperand(0);
// If Ptr is an alloca and this is a store to a different alloca, ignore
// the store. This is a trivial form of alias analysis that is important
// for reg2mem'd code.
if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
(isa<AllocaInst>(SI->getOperand(1)) ||
isa<GlobalVariable>(SI->getOperand(1))))
continue;
// If we have alias analysis and it says the store won't modify the loaded
// value, ignore the store.
if (AA &&
(AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
continue;
// Otherwise the store that may or may not alias the pointer, bail out.
++ScanFrom;
return 0;
}
// If this is some other instruction that may clobber Ptr, bail out.
if (Inst->mayWriteToMemory()) {
// If alias analysis claims that it really won't modify the load,
// ignore it.
if (AA &&
(AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
continue;
// May modify the pointer, bail out.
++ScanFrom;
return 0;
}
}
// Got to the start of the block, we didn't find it, but are done for this
// block.
return 0;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/hwpf/fapi2/include/fapi2_subroutine_executor.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file fapi2_sub_executor.H
///
/// @brief Defines the FAPI2 Subroutine Executor Macro.
///
/// The FAPI2 Subroutine Executor macro is called to execute a chip-op
/// or subroutine.
///
#ifndef FAPI2SUBEXECUTOR_H_
#define FAPI2SUBEXECUTOR_H_
#include <plat_sub_executor.H>
/**
* @brief Subroutine Executor macro
*
* This macro calls a PLAT macro which will do any platform specific work to
* execute the Subroutine (e.g. dlopening a shared library)
*/
#define FAPI_CALL_SUBROUTINE(RC, CHIPOP, FUNC, _args_...) \
FAPI_PLAT_CALL_SUBROUTINE(RC, CHIPOP, FUNC, ##_args_)
#endif // FAPI2SUBEXECUTOR_H_
<commit_msg>Remove CHIPOP parameter from FAPI_CALL_SUBROUTINE<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/hwpf/fapi2/include/fapi2_subroutine_executor.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file fapi2_sub_executor.H
///
/// @brief Defines the FAPI2 Subroutine Executor Macro.
///
/// The FAPI2 Subroutine Executor macro is called to execute a chip-op
/// or subroutine.
///
#ifndef FAPI2SUBEXECUTOR_H_
#define FAPI2SUBEXECUTOR_H_
#include <subroutine_executor.H>
/**
* @brief Subroutine Executor macro
*
* This macro calls a PLAT macro which will do any platform specific work to
* execute the Subroutine (e.g. dlopening a shared library)
*/
#define FAPI_CALL_SUBROUTINE(RC, FUNC, _args_...) \
FAPI_PLAT_CALL_SUBROUTINE(RC, FUNC, ##_args_)
#endif // FAPI2SUBEXECUTOR_H_
<|endoftext|> |
<commit_before>/* LICENSE NOTICE
Copyright (c) 2009, Frederick Emmott <[email protected]>
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 "ManagerPrivate.h"
#include "Settings.h"
#include "SocketManager.h"
#include "fastcgi.h"
#include <QtEndian>
#include <QCoreApplication>
#include <QDebug>
#include <QFileSystemWatcher>
#include <QHostAddress>
#include <QSocketNotifier>
#include <QTextStream>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <errno.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/ip.h>
namespace FastCgiQt
{
ManagerPrivate::ManagerPrivate(Responder::Generator responderGenerator, QObject* parent)
:
QObject(parent),
m_responderGenerator(responderGenerator),
m_applicationWatcher(new QFileSystemWatcher(this)),
m_caches(new Caches())
{
// Check we're running as a FastCGI application
sockaddr_un sa;
socklen_t len = sizeof(sa);
::memset(&sa, 0, len);
m_socket = FCGI_LISTENSOCK_FILENO;
// The recommended way of telling if we're running as fastcgi or not.
int error = ::getpeername(FCGI_LISTENSOCK_FILENO, reinterpret_cast<sockaddr*>(&sa), &len);
if(error == -1 && errno != ENOTCONN)
{
if(QCoreApplication::arguments().contains("--configure"))
{
configureHttpd();
configureDatabase();
exit(0);
}
if(QCoreApplication::arguments().contains("--configure-httpd"))
{
configureHttpd();
exit(0);
}
if(QCoreApplication::arguments().contains("--configure-database"))
{
configureDatabase();
exit(0);
}
Settings settings;
if(settings.value("FastCGI/socketType", "FCGI-UNIX").toString() == "FCGI-TCP")
{
m_socket = ::socket(AF_INET, SOCK_STREAM, 0);
in_port_t port = settings.value("FastCGI/portNumber", 0).value<in_port_t>();
if(port == 0)
{
qFatal("Configured to listen on TCP, but there isn't a valid Port Number configured. Try --configure-fastcgi");
return;
}
sockaddr_in sa;
::memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = qToBigEndian(port);
if(::bind(m_socket, reinterpret_cast<sockaddr*>(&sa), sizeof(sa)) == -1)
{
qFatal("Failed to bind() to TCP port %d, with error %d", port, errno);
return;
}
if(::listen(m_socket, 1) == -1)
{
qFatal("Failed to listen() on port %d, with error %d", port, errno);
return;
}
QTextStream cout(stdout);
cout << "Following configuration in '" << settings.fileName() << "' and listening on TCP port " << port << endl;
}
else
{
// Not a FastCGI application
QTextStream cerr(stderr);
cerr << "This application must be ran as a FastCGI application (eg from Apache via mod_fastcgi)." << endl;
cerr << "Perhaps you wanted --configure?" << endl;
exit(1);
return;
}
}
m_socketNotifier = new QSocketNotifier(m_socket, QSocketNotifier::Read, this),
connect(
m_socketNotifier,
SIGNAL(activated(int)),
this,
SLOT(listen())
);
connect(
m_applicationWatcher,
SIGNAL(fileChanged(QString)),
this,
SLOT(shutdown())
);
m_applicationWatcher->addPath(QCoreApplication::applicationFilePath());
// Spawn some threads
for(int i = 0; i < qMax(QThread::idealThreadCount(), 1); ++i)
{
QThread* thread = new QThread(this);
thread->start();
m_threads.append(thread);
m_threadLoads[thread] = 0;
}
// Wait for the event loop to start up before running
QTimer::singleShot(0, this, SLOT(listen()));
}
ManagerPrivate::~ManagerPrivate()
{
delete m_caches;
}
QList<int> ManagerPrivate::threadLoads() const
{
QList<int> data;
Q_FOREACH(const QAtomicInt& load, m_threadLoads)
{
data.append(load);
}
return data;
}
void ManagerPrivate::shutdown()
{
qDebug() << "Starting shutdown process";
// stop listening on the main socket
::close(m_socketNotifier->socket());
// stop watching it
m_socketNotifier->setEnabled(false);
// If there's no load, exit
exitIfFinished();
}
void ManagerPrivate::exitIfFinished()
{
if(m_socketNotifier->isEnabled())
{
return;
}
qDebug() << "Waiting for threads - thread loads:" << threadLoads();
Q_FOREACH(QThread* thread, m_threads)
{
if(m_threadLoads.value(thread) != 0)
{
return;
}
}
qDebug() << "Shutting down threads";
Q_FOREACH(QThread* thread, m_threads)
{
thread->quit();
bool done = thread->wait(10000);
if(!done)
{
qDebug() << "One thread took longer than 10 seconds to shut down, terminating";
thread->terminate();
}
}
qDebug() << "Shutting down caches";
delete m_caches;
m_caches = NULL;
qDebug() << "Shutdown complete. No thread load.";
QCoreApplication::exit();
}
bool ManagerPrivate::hasLessLoadThan(QThread* t1, QThread* t2)
{
Q_ASSERT(t1->parent() == t2->parent());
ManagerPrivate* p = qobject_cast<ManagerPrivate*>(t1->parent());
Q_ASSERT(p);
return p->m_threadLoads.value(t1) < p->m_threadLoads.value(t2);
}
void ManagerPrivate::listen()
{
// Initialise socket address structure
sockaddr_un sa;
socklen_t len = sizeof(sa);
::memset(&sa, 0, len);
// Listen on the socket
lockSocket(m_socket);
int newSocket = ::accept(m_socket, reinterpret_cast<sockaddr*>(&sa), &len);
releaseSocket(m_socket);
/* We're connected, setup a SocketManager.
* This will delete itself when appropriate (via deleteLater())
*/
// Pick a thread to put it in
qSort(m_threads.begin(), m_threads.end(), hasLessLoadThan);
QThread* thread = m_threads.first();
m_threadLoads[thread].ref();
SocketManager* socket = new SocketManager(m_responderGenerator, newSocket, NULL);
connect(
socket,
SIGNAL(finished(QThread*)),
this,
SLOT(reduceLoadCount(QThread*))
);
socket->moveToThread(thread);
}
void ManagerPrivate::reduceLoadCount(QThread* thread)
{
m_threadLoads[thread].deref();
exitIfFinished();
}
void ManagerPrivate::configureHttpd()
{
QTextStream cin(stdin);
QTextStream cout(stdout);
Settings settings;
settings.beginGroup("FastCGI");
QString interface;
cout << "*****************************************" << endl;
cout << "***** FastCgiQt HTTPD Configuration *****" << endl;
cout << "*****************************************" << endl;
cout << "FastCgiQt supports two interfaces for communications with the HTTPD:" << endl;
cout << "- FCGI-UNIX: Good for Apache with mod_fastcgi/mod_fcgid." << endl;
cout << " FastCgiQt tries to use the unix socket bound to file descriptor 0." << endl;
cout << " This is what the FastCGI specification says, but doesn't work too" << endl;
cout << " well with anything except Apache." << endl;
cout << "- FCGI-TCP: Good for lighttpd, cherokee, and others." << endl;
cout << " FastCgiQt listens on a user-configured TCP port." << endl;
cout << " This works with pretty much anything that isn't Apache." << endl;
cout << "Interface [FCGI-UNIX]: " << flush;
interface = cin.readLine();
if(interface.toUpper() == "FCGI-UNIX" || interface.isEmpty())
{
settings.setValue("socketType", "FCGI-UNIX");
}
else if(interface.toUpper() == "FCGI-TCP")
{
settings.setValue("socketType", "FCGI-TCP");
QString portString;
cout << "Port number: " << flush;
portString = cin.readLine();
bool ok;
quint32 portNumber = portString.toUInt(&ok);
if(!(ok && portNumber))
{
qFatal("Not a valid port number.");
return;
}
settings.setValue("portNumber", portNumber);
}
else
{
qFatal("Not a valid communication method: '%s'", qPrintable(interface));
return;
}
settings.sync();
}
void ManagerPrivate::configureDatabase()
{
QTextStream cin(stdin);
QTextStream cout(stdout);
QString driver;
QString host;
QString name;
QString user;
QString password;
cout << "********************************************" << endl;
cout << "***** FastCgiQt Database Configuration *****" << endl;
cout << "********************************************" << endl;
cout << "Driver [QMYSQL]: " << flush;
driver = cin.readLine();
if(driver.isEmpty())
{
driver = "QMYSQL";
}
cout << "Host [localhost]: " << flush;
host = cin.readLine();
if(host.isEmpty())
{
host = "localhost";
}
cout << "Database: " << flush;
name = cin.readLine();
cout << "User: " << flush;
user = cin.readLine();
cout << "Password: " << flush;
password = cin.readLine();
Settings settings;
settings.beginGroup("database");
settings.setValue("driver", driver);
settings.setValue("host", host);
settings.setValue("name", name);
settings.setValue("user", user);
settings.setValue("password", password);
settings.endGroup();
settings.sync();
cout << "Settings saved in " << settings.fileName() << endl;
}
void ManagerPrivate::lockSocket(int socket)
{
::flock(socket, LOCK_EX);
}
void ManagerPrivate::releaseSocket(int socket)
{
::flock(socket, LOCK_UN);
}
}
<commit_msg>print out string errror messages isntead of raw numbers<commit_after>/* LICENSE NOTICE
Copyright (c) 2009, Frederick Emmott <[email protected]>
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 "ManagerPrivate.h"
#include "Settings.h"
#include "SocketManager.h"
#include "fastcgi.h"
#include <QtEndian>
#include <QCoreApplication>
#include <QDebug>
#include <QFileSystemWatcher>
#include <QHostAddress>
#include <QSocketNotifier>
#include <QTextStream>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <errno.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/ip.h>
namespace FastCgiQt
{
ManagerPrivate::ManagerPrivate(Responder::Generator responderGenerator, QObject* parent)
:
QObject(parent),
m_responderGenerator(responderGenerator),
m_applicationWatcher(new QFileSystemWatcher(this)),
m_caches(new Caches())
{
// Check we're running as a FastCGI application
sockaddr_un sa;
socklen_t len = sizeof(sa);
::memset(&sa, 0, len);
m_socket = FCGI_LISTENSOCK_FILENO;
// The recommended way of telling if we're running as fastcgi or not.
int error = ::getpeername(FCGI_LISTENSOCK_FILENO, reinterpret_cast<sockaddr*>(&sa), &len);
if(error == -1 && errno != ENOTCONN)
{
if(QCoreApplication::arguments().contains("--configure"))
{
configureHttpd();
configureDatabase();
exit(0);
}
if(QCoreApplication::arguments().contains("--configure-httpd"))
{
configureHttpd();
exit(0);
}
if(QCoreApplication::arguments().contains("--configure-database"))
{
configureDatabase();
exit(0);
}
Settings settings;
if(settings.value("FastCGI/socketType", "FCGI-UNIX").toString() == "FCGI-TCP")
{
m_socket = ::socket(AF_INET, SOCK_STREAM, 0);
in_port_t port = settings.value("FastCGI/portNumber", 0).value<in_port_t>();
if(port == 0)
{
qFatal("Configured to listen on TCP, but there isn't a valid Port Number configured. Try --configure-fastcgi");
return;
}
sockaddr_in sa;
::memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = qToBigEndian(port);
if(::bind(m_socket, reinterpret_cast<sockaddr*>(&sa), sizeof(sa)) == -1)
{
qFatal("Failed to bind() to TCP port %d, with error %s", port, ::strerror(errno));
return;
}
if(::listen(m_socket, 1) == -1)
{
qFatal("Failed to listen() on port %d, with error %s", port, ::strerror(errno));
return;
}
QTextStream cout(stdout);
cout << "Following configuration in '" << settings.fileName() << "' and listening on TCP port " << port << endl;
}
else
{
// Not a FastCGI application
QTextStream cerr(stderr);
cerr << "This application must be ran as a FastCGI application (eg from Apache via mod_fastcgi)." << endl;
cerr << "Perhaps you wanted --configure?" << endl;
exit(1);
return;
}
}
m_socketNotifier = new QSocketNotifier(m_socket, QSocketNotifier::Read, this),
connect(
m_socketNotifier,
SIGNAL(activated(int)),
this,
SLOT(listen())
);
connect(
m_applicationWatcher,
SIGNAL(fileChanged(QString)),
this,
SLOT(shutdown())
);
m_applicationWatcher->addPath(QCoreApplication::applicationFilePath());
// Spawn some threads
for(int i = 0; i < qMax(QThread::idealThreadCount(), 1); ++i)
{
QThread* thread = new QThread(this);
thread->start();
m_threads.append(thread);
m_threadLoads[thread] = 0;
}
// Wait for the event loop to start up before running
QTimer::singleShot(0, this, SLOT(listen()));
}
ManagerPrivate::~ManagerPrivate()
{
delete m_caches;
}
QList<int> ManagerPrivate::threadLoads() const
{
QList<int> data;
Q_FOREACH(const QAtomicInt& load, m_threadLoads)
{
data.append(load);
}
return data;
}
void ManagerPrivate::shutdown()
{
qDebug() << "Starting shutdown process";
// stop listening on the main socket
::close(m_socketNotifier->socket());
// stop watching it
m_socketNotifier->setEnabled(false);
// If there's no load, exit
exitIfFinished();
}
void ManagerPrivate::exitIfFinished()
{
if(m_socketNotifier->isEnabled())
{
return;
}
qDebug() << "Waiting for threads - thread loads:" << threadLoads();
Q_FOREACH(QThread* thread, m_threads)
{
if(m_threadLoads.value(thread) != 0)
{
return;
}
}
qDebug() << "Shutting down threads";
Q_FOREACH(QThread* thread, m_threads)
{
thread->quit();
bool done = thread->wait(10000);
if(!done)
{
qDebug() << "One thread took longer than 10 seconds to shut down, terminating";
thread->terminate();
}
}
qDebug() << "Shutting down caches";
delete m_caches;
m_caches = NULL;
qDebug() << "Shutdown complete. No thread load.";
QCoreApplication::exit();
}
bool ManagerPrivate::hasLessLoadThan(QThread* t1, QThread* t2)
{
Q_ASSERT(t1->parent() == t2->parent());
ManagerPrivate* p = qobject_cast<ManagerPrivate*>(t1->parent());
Q_ASSERT(p);
return p->m_threadLoads.value(t1) < p->m_threadLoads.value(t2);
}
void ManagerPrivate::listen()
{
// Initialise socket address structure
sockaddr_un sa;
socklen_t len = sizeof(sa);
::memset(&sa, 0, len);
// Listen on the socket
lockSocket(m_socket);
int newSocket = ::accept(m_socket, reinterpret_cast<sockaddr*>(&sa), &len);
releaseSocket(m_socket);
/* We're connected, setup a SocketManager.
* This will delete itself when appropriate (via deleteLater())
*/
// Pick a thread to put it in
qSort(m_threads.begin(), m_threads.end(), hasLessLoadThan);
QThread* thread = m_threads.first();
m_threadLoads[thread].ref();
SocketManager* socket = new SocketManager(m_responderGenerator, newSocket, NULL);
connect(
socket,
SIGNAL(finished(QThread*)),
this,
SLOT(reduceLoadCount(QThread*))
);
socket->moveToThread(thread);
}
void ManagerPrivate::reduceLoadCount(QThread* thread)
{
m_threadLoads[thread].deref();
exitIfFinished();
}
void ManagerPrivate::configureHttpd()
{
QTextStream cin(stdin);
QTextStream cout(stdout);
Settings settings;
settings.beginGroup("FastCGI");
QString interface;
cout << "*****************************************" << endl;
cout << "***** FastCgiQt HTTPD Configuration *****" << endl;
cout << "*****************************************" << endl;
cout << "FastCgiQt supports two interfaces for communications with the HTTPD:" << endl;
cout << "- FCGI-UNIX: Good for Apache with mod_fastcgi/mod_fcgid." << endl;
cout << " FastCgiQt tries to use the unix socket bound to file descriptor 0." << endl;
cout << " This is what the FastCGI specification says, but doesn't work too" << endl;
cout << " well with anything except Apache." << endl;
cout << "- FCGI-TCP: Good for lighttpd, cherokee, and others." << endl;
cout << " FastCgiQt listens on a user-configured TCP port." << endl;
cout << " This works with pretty much anything that isn't Apache." << endl;
cout << "Interface [FCGI-UNIX]: " << flush;
interface = cin.readLine();
if(interface.toUpper() == "FCGI-UNIX" || interface.isEmpty())
{
settings.setValue("socketType", "FCGI-UNIX");
}
else if(interface.toUpper() == "FCGI-TCP")
{
settings.setValue("socketType", "FCGI-TCP");
QString portString;
cout << "Port number: " << flush;
portString = cin.readLine();
bool ok;
quint32 portNumber = portString.toUInt(&ok);
if(!(ok && portNumber))
{
qFatal("Not a valid port number.");
return;
}
settings.setValue("portNumber", portNumber);
}
else
{
qFatal("Not a valid communication method: '%s'", qPrintable(interface));
return;
}
settings.sync();
}
void ManagerPrivate::configureDatabase()
{
QTextStream cin(stdin);
QTextStream cout(stdout);
QString driver;
QString host;
QString name;
QString user;
QString password;
cout << "********************************************" << endl;
cout << "***** FastCgiQt Database Configuration *****" << endl;
cout << "********************************************" << endl;
cout << "Driver [QMYSQL]: " << flush;
driver = cin.readLine();
if(driver.isEmpty())
{
driver = "QMYSQL";
}
cout << "Host [localhost]: " << flush;
host = cin.readLine();
if(host.isEmpty())
{
host = "localhost";
}
cout << "Database: " << flush;
name = cin.readLine();
cout << "User: " << flush;
user = cin.readLine();
cout << "Password: " << flush;
password = cin.readLine();
Settings settings;
settings.beginGroup("database");
settings.setValue("driver", driver);
settings.setValue("host", host);
settings.setValue("name", name);
settings.setValue("user", user);
settings.setValue("password", password);
settings.endGroup();
settings.sync();
cout << "Settings saved in " << settings.fileName() << endl;
}
void ManagerPrivate::lockSocket(int socket)
{
::flock(socket, LOCK_EX);
}
void ManagerPrivate::releaseSocket(int socket)
{
::flock(socket, LOCK_UN);
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the Ford Motor Company 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 "application_manager/commands/mobile/delete_command_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "utils/helpers.h"
namespace application_manager {
namespace commands {
DeleteCommandRequest::DeleteCommandRequest(const MessageSharedPtr& message)
: CommandRequestImpl(message),
is_ui_send_(false),
is_vr_send_(false),
is_ui_received_(false),
is_vr_received_(false),
ui_result_(hmi_apis::Common_Result::INVALID_ENUM),
vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {
}
DeleteCommandRequest::~DeleteCommandRequest() {
}
void DeleteCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application = ApplicationManagerImpl::instance()->
application(connection_key());
if (!application) {
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
LOG4CXX_ERROR(logger_, "Application is not registered");
return;
}
const int32_t cmd_id =
(*message_)[strings::msg_params][strings::cmd_id].asInt();
smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
SendResponse(false, mobile_apis::Result::INVALID_ID);
LOG4CXX_ERROR(logger_, "Command with id " << cmd_id << " is not found.");
return;
}
smart_objects::SmartObject msg_params = smart_objects::SmartObject(
smart_objects::SmartType_Map);
msg_params[strings::cmd_id] =
(*message_)[strings::msg_params][strings::cmd_id];
msg_params[strings::app_id] = application->app_id();
// we should specify amount of required responses in the 1st request
uint32_t chaining_counter = 0;
if ((*command).keyExists(strings::menu_params)) {
++chaining_counter;
}
if ((*command).keyExists(strings::vr_commands)) {
++chaining_counter;
}
if ((*command).keyExists(strings::menu_params)) {
is_ui_send_ = true;
SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params, true);
}
// check vr params
if ((*command).keyExists(strings::vr_commands)) {
is_vr_send_ = true;
// VR params
msg_params[strings::grammar_id] = application->get_grammar_id();
msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params, true);
}
}
void DeleteCommandRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_DeleteCommand: {
LOG4CXX_INFO(logger_, "Received UI_DeleteCommand event");
is_ui_received_ = true;
ui_result_ = static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
break;
}
case hmi_apis::FunctionID::VR_DeleteCommand: {
LOG4CXX_INFO(logger_, "Received VR_DeleteCommand event");
is_vr_received_ = true;
vr_result_ = static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
break;
}
default: {
LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
return;
}
}
if (IsPendingResponseExist()) {
LOG4CXX_DEBUG(logger_, "Still awaiting for other responses.");
return;
}
ApplicationSharedPtr application =
ApplicationManagerImpl::instance()->application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
const int32_t cmd_id =
(*message_)[strings::msg_params][strings::cmd_id].asInt();
smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
LOG4CXX_ERROR(logger_, "Command id " << cmd_id << " not found for "
"application with connection key " << connection_key());
return;
}
mobile_apis::Result::eType result_code =
mobile_apis::Result::INVALID_ENUM;
const bool is_vr_success_invalid =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
vr_result_,
hmi_apis::Common_Result::SUCCESS,
hmi_apis::Common_Result::INVALID_ENUM);
const bool is_ui_success_invalid =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
ui_result_,
hmi_apis::Common_Result::SUCCESS,
hmi_apis::Common_Result::INVALID_ENUM);
const bool is_vr_ui_invalid =
Compare<hmi_apis::Common_Result::eType, EQ, ALL>(
hmi_apis::Common_Result::INVALID_ENUM,
vr_result_,
ui_result_);
bool result =
is_ui_success_invalid &&
is_vr_success_invalid &&
!is_vr_ui_invalid;
if (result) {
application->RemoveCommand(
(*message_)[strings::msg_params][strings::cmd_id].asInt());
}
const bool is_vr_or_ui_warning =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
hmi_apis::Common_Result::WARNINGS,
ui_result_,
vr_result_);
if (!result &&
hmi_apis::Common_Result::REJECTED == ui_result_) {
result_code = MessageHelper::HMIToMobileResult(vr_result_);
} else if (is_vr_or_ui_warning) {
result_code = mobile_apis::Result::WARNINGS;
} else {
result_code = MessageHelper::HMIToMobileResult(
std::max(ui_result_, vr_result_));
}
SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
if (result) {
application->UpdateHash();
}
}
bool DeleteCommandRequest::IsPendingResponseExist() {
LOG4CXX_AUTO_TRACE(logger_);
return is_ui_send_ != is_ui_received_ || is_vr_send_ != is_vr_received_;
}
} // namespace commands
} // namespace application_manager
<commit_msg>Fix WARNING result interpretation in Mobile.DeleteCommandRequest<commit_after>/*
Copyright (c) 2013, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the Ford Motor Company 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 "application_manager/commands/mobile/delete_command_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "utils/helpers.h"
namespace application_manager {
namespace commands {
DeleteCommandRequest::DeleteCommandRequest(const MessageSharedPtr& message)
: CommandRequestImpl(message),
is_ui_send_(false),
is_vr_send_(false),
is_ui_received_(false),
is_vr_received_(false),
ui_result_(hmi_apis::Common_Result::INVALID_ENUM),
vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {
}
DeleteCommandRequest::~DeleteCommandRequest() {
}
void DeleteCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application = ApplicationManagerImpl::instance()->
application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
const int32_t cmd_id =
(*message_)[strings::msg_params][strings::cmd_id].asInt();
smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
LOG4CXX_ERROR(logger_, "Command with id " << cmd_id << " is not found.");
SendResponse(false, mobile_apis::Result::INVALID_ID);
return;
}
smart_objects::SmartObject msg_params = smart_objects::SmartObject(
smart_objects::SmartType_Map);
msg_params[strings::cmd_id] =
(*message_)[strings::msg_params][strings::cmd_id];
msg_params[strings::app_id] = application->app_id();
// we should specify amount of required responses in the 1st request
uint32_t chaining_counter = 0;
if ((*command).keyExists(strings::menu_params)) {
++chaining_counter;
}
if ((*command).keyExists(strings::vr_commands)) {
++chaining_counter;
}
if ((*command).keyExists(strings::menu_params)) {
is_ui_send_ = true;
SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params, true);
}
// check vr params
if ((*command).keyExists(strings::vr_commands)) {
is_vr_send_ = true;
// VR params
msg_params[strings::grammar_id] = application->get_grammar_id();
msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params, true);
}
}
void DeleteCommandRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_DeleteCommand: {
is_ui_received_ = true;
const int result = message[strings::params][hmi_response::code].asInt();
ui_result_ = static_cast<hmi_apis::Common_Result::eType>(result);
LOG4CXX_DEBUG(logger_, "Received UI_DeleteCommand event with result "
<< MessageHelper::HMIResultToString(ui_result_));
break;
}
case hmi_apis::FunctionID::VR_DeleteCommand: {
is_vr_received_ = true;
const int result = message[strings::params][hmi_response::code].asInt();
vr_result_ = static_cast<hmi_apis::Common_Result::eType>(result);
LOG4CXX_DEBUG(logger_, "Received VR_DeleteCommand event with result "
<< MessageHelper::HMIResultToString(vr_result_));
break;
}
default: {
LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
return;
}
}
if (IsPendingResponseExist()) {
LOG4CXX_DEBUG(logger_, "Still awaiting for other responses.");
return;
}
ApplicationSharedPtr application =
ApplicationManagerImpl::instance()->application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
return;
}
smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params];
const int32_t cmd_id = msg_params[strings::cmd_id].asInt();
smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
LOG4CXX_ERROR(logger_, "Command id " << cmd_id << " not found for "
"application with connection key " << connection_key());
return;
}
const bool is_vr_success_invalid =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
vr_result_,
hmi_apis::Common_Result::SUCCESS,
hmi_apis::Common_Result::INVALID_ENUM);
const bool is_ui_success_invalid =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
ui_result_,
hmi_apis::Common_Result::SUCCESS,
hmi_apis::Common_Result::INVALID_ENUM);
const bool is_vr_ui_invalid =
Compare<hmi_apis::Common_Result::eType, EQ, ALL>(
hmi_apis::Common_Result::INVALID_ENUM,
vr_result_,
ui_result_);
const bool is_vr_or_ui_warning =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
hmi_apis::Common_Result::WARNINGS,
ui_result_,
vr_result_);
const bool result =
// In case of UI/VR is SUCCESS and other is SUCCESS/INVALID_ENUM
(is_vr_success_invalid && is_ui_success_invalid && !is_vr_ui_invalid) ||
// or one of them is WARNINGS
is_vr_or_ui_warning;
LOG4CXX_DEBUG(logger_, "Result code is " << (result ? "true" : "false"));
if (result) {
application->RemoveCommand(msg_params[strings::cmd_id].asInt());
}
mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
if (!result &&
hmi_apis::Common_Result::REJECTED == ui_result_) {
result_code = MessageHelper::HMIToMobileResult(vr_result_);
} else if (is_vr_or_ui_warning) {
LOG4CXX_DEBUG(logger_, "VR or UI result is warning");
result_code = mobile_apis::Result::WARNINGS;
} else {
result_code = MessageHelper::HMIToMobileResult(
std::max(ui_result_, vr_result_));
}
SendResponse(result, result_code, NULL, &msg_params);
if (result) {
application->UpdateHash();
}
}
bool DeleteCommandRequest::IsPendingResponseExist() {
LOG4CXX_AUTO_TRACE(logger_);
return is_ui_send_ != is_ui_received_ || is_vr_send_ != is_vr_received_;
}
} // namespace commands
} // namespace application_manager
<|endoftext|> |
<commit_before>//
// ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0
//
// See LICENSE file in project repository root for the license.
//
// Copyright (c) 2017, David Hirvonen (this file)
#include "pbo.h"
#include "ogles_gpgpu/platform/opengl/gl_includes.h"
#include <iostream>
#include <sstream>
#include <stdlib.h>
using namespace std;
using namespace ogles_gpgpu;
// ::: input/read :::
IPBO::IPBO(std::size_t width, std::size_t height)
: width(width)
, height(height)
, isReadingAsynchronously_(false) {
glGenBuffers(1, &pbo);
Tools::checkGLErr("IPBO::IPBO", "glGenBuffers()");
std::size_t pbo_size = width * height * 4;
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
Tools::checkGLErr("IPBO::IPBO", "glBindBuffer()");
glBufferData(GL_PIXEL_PACK_BUFFER, pbo_size, 0, GL_DYNAMIC_READ);
Tools::checkGLErr("IPBO::IPBO", "glBufferData()");
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
Tools::checkGLErr("IPBO::IPBO", "glBindBuffer()");
}
IPBO::~IPBO() {
if (pbo > 0) {
glDeleteBuffers(1, &pbo);
Tools::checkGLErr("IPBO::~IPBO", "glDeleteBuffers()");
pbo = 0;
}
}
bool IPBO::isReadingAsynchronously() const {
return isReadingAsynchronously_;
}
void IPBO::bind() {
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
Tools::checkGLErr("IPBO::bind", "glBindBuffer()");
}
void IPBO::unbind() {
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
Tools::checkGLErr("IPBO::unbind", "glBindBuffer()");
}
void IPBO::start() {
if (!isReadingAsynchronously_) {
glReadBuffer(GL_COLOR_ATTACHMENT0);
Tools::checkGLErr("IPBO::start", "glReadBuffer()");
// Note glReadPixels last argument == 0 for PBO reads
glReadPixels(0, 0, width, height, OGLES_GPGPU_TEXTURE_FORMAT, GL_UNSIGNED_BYTE, 0);
Tools::checkGLErr("IPBO::start", "glReadPixels()");
isReadingAsynchronously_ = true;
}
}
void IPBO::finish(GLubyte* buffer) {
if (isReadingAsynchronously_) {
std::size_t pbo_size = width * height * 4;
#if defined(OGLES_GPGPU_OSX)
// Note: glMapBufferRange does not seem to work in OS X
GLubyte* ptr = static_cast<GLubyte*>(glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY));
#else
GLubyte* ptr = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, pbo_size, GL_MAP_READ_BIT));
#endif
Tools::checkGLErr("IPBO::finish", "glMapBufferRange()");
if (ptr) {
memcpy(buffer, ptr, pbo_size);
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
Tools::checkGLErr("IPBO::finish", "glUnmapBuffer()");
}
isReadingAsynchronously_ = false;
}
}
void IPBO::read(GLubyte* buffer) {
start(); // Use start() and
finish(buffer); // finish() pair for consistent internal state
}
// ::: output/write :::
OPBO::OPBO(std::size_t width, std::size_t height)
: width(width)
, height(height) {
glGenBuffers(1, &pbo);
Tools::checkGLErr("OPBO::OPBO", "glGenBuffers()");
std::size_t pbo_size = width * height * 4;
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
Tools::checkGLErr("OPBO::OPBO", "glBindBuffer()");
glBufferData(GL_PIXEL_UNPACK_BUFFER, pbo_size, 0, GL_STREAM_DRAW);
Tools::checkGLErr("OPBO::OPBO", "glBufferData()");
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
Tools::checkGLErr("OPBO::OPBO", "glBindBuffer()");
}
OPBO::~OPBO() {
if (pbo > 0) {
glDeleteBuffers(1, &pbo);
Tools::checkGLErr("OPBO::~OPBO", "glDeleteBuffers()");
pbo = 0;
}
}
void OPBO::bind() {
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
Tools::checkGLErr("OPBO::bind", "glBindBuffer()");
}
void OPBO::unbind() {
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
Tools::checkGLErr("OPBO::unbind", "glBindBuffer()");
}
void OPBO::write(const GLubyte* buffer, GLuint texId) {
std::size_t pbo_size = width * height * 4;
glBufferData(GL_PIXEL_UNPACK_BUFFER, pbo_size, NULL, GL_STREAM_DRAW);
Tools::checkGLErr("OPBO::write", "glBufferData()");
#if defined(OGLES_GPGPU_OSX)
// TODO: glMapBufferRange does not seem to work in OS X
GLubyte* ptr = static_cast<GLubyte*>(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY));
Tools::checkGLErr("OPBO::write", "glMapBuffer()");
#else
GLubyte* ptr = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, pbo_size, GL_MAP_WRITE_BIT));
Tools::checkGLErr("OPBO::write", "glMapBufferRange()");
#endif
if (ptr) {
memcpy(ptr, buffer, pbo_size);
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
Tools::checkGLErr("OPBO::write", "glUnmapBuffer()");
glBindTexture(GL_TEXTURE_2D, texId);
Tools::checkGLErr("OPBO::write", "glBindTexture()");
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, OGLES_GPGPU_TEXTURE_FORMAT, GL_UNSIGNED_BYTE, 0);
Tools::checkGLErr("OPBO::write", "glTexSubImage2D()");
}
}
<commit_msg>Fix Linux build<commit_after>//
// ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0
//
// See LICENSE file in project repository root for the license.
//
// Copyright (c) 2017, David Hirvonen (this file)
#include "pbo.h"
#include "ogles_gpgpu/platform/opengl/gl_includes.h"
#include <iostream>
#include <sstream>
#include <cstring> // memcpy
#include <stdlib.h>
using namespace std;
using namespace ogles_gpgpu;
// ::: input/read :::
IPBO::IPBO(std::size_t width, std::size_t height)
: width(width)
, height(height)
, isReadingAsynchronously_(false) {
glGenBuffers(1, &pbo);
Tools::checkGLErr("IPBO::IPBO", "glGenBuffers()");
std::size_t pbo_size = width * height * 4;
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
Tools::checkGLErr("IPBO::IPBO", "glBindBuffer()");
glBufferData(GL_PIXEL_PACK_BUFFER, pbo_size, 0, GL_DYNAMIC_READ);
Tools::checkGLErr("IPBO::IPBO", "glBufferData()");
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
Tools::checkGLErr("IPBO::IPBO", "glBindBuffer()");
}
IPBO::~IPBO() {
if (pbo > 0) {
glDeleteBuffers(1, &pbo);
Tools::checkGLErr("IPBO::~IPBO", "glDeleteBuffers()");
pbo = 0;
}
}
bool IPBO::isReadingAsynchronously() const {
return isReadingAsynchronously_;
}
void IPBO::bind() {
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
Tools::checkGLErr("IPBO::bind", "glBindBuffer()");
}
void IPBO::unbind() {
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
Tools::checkGLErr("IPBO::unbind", "glBindBuffer()");
}
void IPBO::start() {
if (!isReadingAsynchronously_) {
glReadBuffer(GL_COLOR_ATTACHMENT0);
Tools::checkGLErr("IPBO::start", "glReadBuffer()");
// Note glReadPixels last argument == 0 for PBO reads
glReadPixels(0, 0, width, height, OGLES_GPGPU_TEXTURE_FORMAT, GL_UNSIGNED_BYTE, 0);
Tools::checkGLErr("IPBO::start", "glReadPixels()");
isReadingAsynchronously_ = true;
}
}
void IPBO::finish(GLubyte* buffer) {
if (isReadingAsynchronously_) {
std::size_t pbo_size = width * height * 4;
#if defined(OGLES_GPGPU_OSX)
// Note: glMapBufferRange does not seem to work in OS X
GLubyte* ptr = static_cast<GLubyte*>(glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY));
#else
GLubyte* ptr = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, pbo_size, GL_MAP_READ_BIT));
#endif
Tools::checkGLErr("IPBO::finish", "glMapBufferRange()");
if (ptr) {
memcpy(buffer, ptr, pbo_size);
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
Tools::checkGLErr("IPBO::finish", "glUnmapBuffer()");
}
isReadingAsynchronously_ = false;
}
}
void IPBO::read(GLubyte* buffer) {
start(); // Use start() and
finish(buffer); // finish() pair for consistent internal state
}
// ::: output/write :::
OPBO::OPBO(std::size_t width, std::size_t height)
: width(width)
, height(height) {
glGenBuffers(1, &pbo);
Tools::checkGLErr("OPBO::OPBO", "glGenBuffers()");
std::size_t pbo_size = width * height * 4;
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
Tools::checkGLErr("OPBO::OPBO", "glBindBuffer()");
glBufferData(GL_PIXEL_UNPACK_BUFFER, pbo_size, 0, GL_STREAM_DRAW);
Tools::checkGLErr("OPBO::OPBO", "glBufferData()");
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
Tools::checkGLErr("OPBO::OPBO", "glBindBuffer()");
}
OPBO::~OPBO() {
if (pbo > 0) {
glDeleteBuffers(1, &pbo);
Tools::checkGLErr("OPBO::~OPBO", "glDeleteBuffers()");
pbo = 0;
}
}
void OPBO::bind() {
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
Tools::checkGLErr("OPBO::bind", "glBindBuffer()");
}
void OPBO::unbind() {
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
Tools::checkGLErr("OPBO::unbind", "glBindBuffer()");
}
void OPBO::write(const GLubyte* buffer, GLuint texId) {
std::size_t pbo_size = width * height * 4;
glBufferData(GL_PIXEL_UNPACK_BUFFER, pbo_size, NULL, GL_STREAM_DRAW);
Tools::checkGLErr("OPBO::write", "glBufferData()");
#if defined(OGLES_GPGPU_OSX)
// TODO: glMapBufferRange does not seem to work in OS X
GLubyte* ptr = static_cast<GLubyte*>(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY));
Tools::checkGLErr("OPBO::write", "glMapBuffer()");
#else
GLubyte* ptr = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, pbo_size, GL_MAP_WRITE_BIT));
Tools::checkGLErr("OPBO::write", "glMapBufferRange()");
#endif
if (ptr) {
memcpy(ptr, buffer, pbo_size);
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
Tools::checkGLErr("OPBO::write", "glUnmapBuffer()");
glBindTexture(GL_TEXTURE_2D, texId);
Tools::checkGLErr("OPBO::write", "glBindTexture()");
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, OGLES_GPGPU_TEXTURE_FORMAT, GL_UNSIGNED_BYTE, 0);
Tools::checkGLErr("OPBO::write", "glTexSubImage2D()");
}
}
<|endoftext|> |
<commit_before>/*
* opencog/atoms/core/PutLink.cc
*
* Copyright (C) 2015 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/atom_types.h>
#include <opencog/atoms/base/ClassServer.h>
#include "DefineLink.h"
#include "FreeLink.h"
#include "LambdaLink.h"
#include "PutLink.h"
using namespace opencog;
PutLink::PutLink(const HandleSeq& oset, Type t)
: ScopeLink(oset, t)
{
init();
}
PutLink::PutLink(const Handle& a)
: ScopeLink(PUT_LINK, a)
{
init();
}
PutLink::PutLink(const Link& l)
: ScopeLink(l)
{
init();
}
/* ================================================================= */
/// PutLink expects a very strict format: an arity-2 link, with
/// the first part being a pattern, and the second a list or set
/// of values. If the pattern has N variables, then the seccond
/// part must have N values. Furthermore, any type restrictions on
/// the variables must be satisfied by the values.
///
/// The following formats are understood:
///
/// PutLink
/// <pattern with 1 variable>
/// <any single atom>
///
/// PutLink
/// <pattern with N variables>
/// ListLink ;; must have arity N
/// <atom 1>
/// ...
/// <atom N>
///
/// The below is a handy-dandy easy-to-use form. When it is reduced,
/// it will result in the creation of a set of reduced forms, not
/// just one (the two sets haveing the same arity). Unfortunately,
/// this trick cannot work for N=1 unless the variable is cosntrained
/// to not be a set.
///
/// PutLink
/// <pattern with N variables>
/// SetLink ;; Must hold a set of ListLinks
/// ListLink ;; must have arity N
/// <atom 1>
/// ...
/// <atom N>
///
void PutLink::init(void)
{
if (not classserver().isA(get_type(), PUT_LINK))
throw InvalidParamException(TRACE_INFO, "Expecting a PutLink");
size_t sz = _outgoing.size();
if (2 != sz and 3 != sz)
throw InvalidParamException(TRACE_INFO,
"Expecting an outgoing set size of two or three, got %d; %s",
sz, to_string().c_str());
ScopeLink::extract_variables(_outgoing);
if (2 == sz)
{
// If the body is just a single variable, and there are no
// type declarations for it, then ScopeLink gets confused.
_vardecl = Handle::UNDEFINED;
_body = _outgoing[0];
_values = _outgoing[1];
}
else
_values = _outgoing[2];
static_typecheck_values();
}
/// Check that the values in the PutLink obey the type constraints.
/// This only performs "static" typechecking, at construction-time;
/// since the values may be dynamically obtained at run-time, we cannot
/// check these here.
void PutLink::static_typecheck_values(void)
{
// Cannot typecheck at this pont in time, because the schema
// might not be defined yet...
Type btype = _body->get_type();
if (DEFINED_SCHEMA_NODE == btype)
return;
if (DEFINED_PREDICATE_NODE == btype)
return;
// If its part of a signature, there is nothing to do.
if (classserver().isA(btype, TYPE_NODE) or TYPE_CHOICE == btype)
return;
size_t sz = _varlist.varseq.size();
Type vtype = _values->get_type();
if (1 == sz)
{
if (not _varlist.is_type(_values)
and SET_LINK != vtype
and PUT_LINK != vtype
and not (classserver().isA(vtype, SATISFYING_LINK)))
{
throw InvalidParamException(TRACE_INFO,
"PutLink mismatched type!");
}
return;
}
// Cannot typecheck naked FunctionLinks. For example:
// (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))
if (0 == sz and classserver().isA(btype, FUNCTION_LINK))
return;
// The standard, default case is to get a ListLink as an argument.
if (LIST_LINK == vtype)
{
if (not _varlist.is_type(_values->getOutgoingSet()))
{
if (_vardecl)
throw SyntaxException(TRACE_INFO,
"PutLink has mismatched value list! vardecl=%s\nvals=%s",
_vardecl->to_string().c_str(),
_values->to_string().c_str());
else
throw SyntaxException(TRACE_INFO,
"PutLink has mismatched value list! body=%s\nvals=%s",
_body->to_string().c_str(),
_values->to_string().c_str());
}
return;
}
// GetLinks (and the like) are evaluated dynamically, later.
if (classserver().isA(vtype, SATISFYING_LINK))
return;
// If its part of a signature, there is nothing to do.
if (TYPE_NODE == vtype or TYPE_CHOICE == vtype)
return;
// The only remaining possibility is that there is set of ListLinks.
if (SET_LINK != vtype)
throw InvalidParamException(TRACE_INFO,
"PutLink was expecting a ListLink, SetLink or GetLink!");
if (1 < sz)
{
for (const Handle& h : _values->getOutgoingSet())
{
// If the arity is greater than one, then the values must be in a list.
if (h->get_type() != LIST_LINK)
throw InvalidParamException(TRACE_INFO,
"PutLink expected value list!");
if (not _varlist.is_type(h->getOutgoingSet()))
throw InvalidParamException(TRACE_INFO,
"PutLink bad value list!");
}
return;
}
// If the arity is one, the values must obey type constraint.
for (const Handle& h : _values->getOutgoingSet())
{
if (not _varlist.is_type(h))
throw InvalidParamException(TRACE_INFO,
"PutLink bad type!");
}
}
/* ================================================================= */
/**
* Perform the actual beta reduction --
*
* Substitute values for the variables in the pattern tree.
* This is a lot like applying the function fun to the argument list
* args, except that no actual evaluation is performed; only
* substitution. The resulting tree is NOT placed into any atomspace,
* either. If you want that, you must do it youself. If you want
* evaluation or execution to happen during or after sustitution, use
* either the EvaluationLink, the ExecutionOutputLink, or the Instantiator.
*
* So, for example, if this PutLink looks like this:
*
* PutLink
* EvaluationLink
* PredicateNode "is a kind of"
* ListLink
* VariableNode $a
* ConceptNode "hot patootie"
* ConceptNode "cowpie"
*
* then the reduced value will be
*
* EvaluationLink
* PredicateNode "is a kind of"
* ListLink
* ConceptNode "cowpie"
* ConceptNode "hot patootie"
*
* Type checking is performed during substitution; if the values fail to
* have the desired types, no substitution is performed. In this case,
* an undefined handle is returned. For set substitutions, this acts as
* a filter, removing (filtering out) the mismatched types.
*
* Again, only a substitution is performed, there is no execution or
* evaluation. Note also that the resulting tree is NOT placed into
* any atomspace!
*/
Handle PutLink::do_reduce(void) const
{
Handle bods(_body);
Variables vars(_varlist);
// Resolve the body, if needed. That is, if the body is
// given in a defintion, get that defintion.
Type btype = _body->get_type();
if (DEFINED_SCHEMA_NODE == btype or
DEFINED_PREDICATE_NODE == btype)
{
bods = DefineLink::get_definition(bods);
btype = bods->get_type();
// XXX TODO we should perform a type-check on the function.
if (not classserver().isA(btype, LAMBDA_LINK))
throw InvalidParamException(TRACE_INFO,
"Expecting a LambdaLink, got %s",
bods->to_string().c_str());
}
// If the body is a lambda, work with that.
if (classserver().isA(btype, LAMBDA_LINK))
{
LambdaLinkPtr lam(LambdaLinkCast(bods));
bods = lam->get_body();
vars = lam->get_variables();
btype = bods->get_type();
}
// Now get the values that we will plug into the body.
Type vtype = _values->get_type();
size_t nvars = vars.varseq.size();
// At this time, we don't know the number of arguments a FunctionLink
// might take. Atomese does have the mechanisms to declare these,
// including arbitrary-arity functions, its just that its currently
// not declared anywhere. So we just punt. Example usage:
// (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))
if (0 == nvars and classserver().isA(btype, FUNCTION_LINK))
{
return createLink(_values->getOutgoingSet(), btype);
}
// If there is only one variable in the PutLink body...
if (1 == nvars)
{
if (SET_LINK != vtype)
{
HandleSeq oset;
oset.emplace_back(_values);
try
{
return vars.substitute(bods, oset, /* silent */ true);
}
catch (const TypeCheckException& ex)
{
return Handle::UNDEFINED;
}
}
// If the values are given in a set, then iterate over the set...
HandleSeq bset;
for (const Handle& h : _values->getOutgoingSet())
{
HandleSeq oset;
oset.emplace_back(h);
try
{
bset.emplace_back(vars.substitute(bods, oset, /* silent */ true));
}
catch (const TypeCheckException& ex) {}
}
return createLink(bset, SET_LINK);
}
// If we are here, then there are multiple variables in the body.
// See how many values there are. If the values are a ListLink,
// then assume that there is only a single set of values to plug in.
if (LIST_LINK == vtype)
{
const HandleSeq& oset = _values->getOutgoingSet();
try
{
return vars.substitute(bods, oset, /* silent */ true);
}
catch (const TypeCheckException& ex)
{
return Handle::UNDEFINED;
}
}
// If we are here, then there are multiple values.
// These MUST be given to us as a SetLink.
OC_ASSERT(SET_LINK == vtype,
"Should have caught this earlier, in the ctor");
HandleSeq bset;
for (const Handle& h : _values->getOutgoingSet())
{
const HandleSeq& oset = h->getOutgoingSet();
try
{
bset.emplace_back(vars.substitute(bods, oset, /* silent */ true));
}
catch (const TypeCheckException& ex) {}
}
return createLink(bset, SET_LINK);
}
Handle PutLink::reduce(void)
{
return do_reduce();
}
DEFINE_LINK_FACTORY(PutLink, PUT_LINK)
/* ===================== END OF FILE ===================== */
<commit_msg>Handle the various different kinds f function arguments<commit_after>/*
* opencog/atoms/core/PutLink.cc
*
* Copyright (C) 2015 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/atom_types.h>
#include <opencog/atoms/base/ClassServer.h>
#include "DefineLink.h"
#include "FreeLink.h"
#include "LambdaLink.h"
#include "PutLink.h"
using namespace opencog;
PutLink::PutLink(const HandleSeq& oset, Type t)
: ScopeLink(oset, t)
{
init();
}
PutLink::PutLink(const Handle& a)
: ScopeLink(PUT_LINK, a)
{
init();
}
PutLink::PutLink(const Link& l)
: ScopeLink(l)
{
init();
}
/* ================================================================= */
/// PutLink expects a very strict format: an arity-2 link, with
/// the first part being a pattern, and the second a list or set
/// of values. If the pattern has N variables, then the seccond
/// part must have N values. Furthermore, any type restrictions on
/// the variables must be satisfied by the values.
///
/// The following formats are understood:
///
/// PutLink
/// <pattern with 1 variable>
/// <any single atom>
///
/// PutLink
/// <pattern with N variables>
/// ListLink ;; must have arity N
/// <atom 1>
/// ...
/// <atom N>
///
/// The below is a handy-dandy easy-to-use form. When it is reduced,
/// it will result in the creation of a set of reduced forms, not
/// just one (the two sets haveing the same arity). Unfortunately,
/// this trick cannot work for N=1 unless the variable is cosntrained
/// to not be a set.
///
/// PutLink
/// <pattern with N variables>
/// SetLink ;; Must hold a set of ListLinks
/// ListLink ;; must have arity N
/// <atom 1>
/// ...
/// <atom N>
///
void PutLink::init(void)
{
if (not classserver().isA(get_type(), PUT_LINK))
throw InvalidParamException(TRACE_INFO, "Expecting a PutLink");
size_t sz = _outgoing.size();
if (2 != sz and 3 != sz)
throw InvalidParamException(TRACE_INFO,
"Expecting an outgoing set size of two or three, got %d; %s",
sz, to_string().c_str());
ScopeLink::extract_variables(_outgoing);
if (2 == sz)
{
// If the body is just a single variable, and there are no
// type declarations for it, then ScopeLink gets confused.
_vardecl = Handle::UNDEFINED;
_body = _outgoing[0];
_values = _outgoing[1];
}
else
_values = _outgoing[2];
static_typecheck_values();
}
/// Check that the values in the PutLink obey the type constraints.
/// This only performs "static" typechecking, at construction-time;
/// since the values may be dynamically obtained at run-time, we cannot
/// check these here.
void PutLink::static_typecheck_values(void)
{
// Cannot typecheck at this pont in time, because the schema
// might not be defined yet...
Type btype = _body->get_type();
if (DEFINED_SCHEMA_NODE == btype)
return;
if (DEFINED_PREDICATE_NODE == btype)
return;
// If its part of a signature, there is nothing to do.
if (classserver().isA(btype, TYPE_NODE) or TYPE_CHOICE == btype)
return;
size_t sz = _varlist.varseq.size();
Type vtype = _values->get_type();
if (1 == sz)
{
if (not _varlist.is_type(_values)
and SET_LINK != vtype
and PUT_LINK != vtype
and not (classserver().isA(vtype, SATISFYING_LINK)))
{
throw InvalidParamException(TRACE_INFO,
"PutLink mismatched type!");
}
return;
}
// Cannot typecheck naked FunctionLinks. For example:
// (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))
if (0 == sz and classserver().isA(btype, FUNCTION_LINK))
return;
// The standard, default case is to get a ListLink as an argument.
if (LIST_LINK == vtype)
{
if (not _varlist.is_type(_values->getOutgoingSet()))
{
if (_vardecl)
throw SyntaxException(TRACE_INFO,
"PutLink has mismatched value list! vardecl=%s\nvals=%s",
_vardecl->to_string().c_str(),
_values->to_string().c_str());
else
throw SyntaxException(TRACE_INFO,
"PutLink has mismatched value list! body=%s\nvals=%s",
_body->to_string().c_str(),
_values->to_string().c_str());
}
return;
}
// GetLinks (and the like) are evaluated dynamically, later.
if (classserver().isA(vtype, SATISFYING_LINK))
return;
// If its part of a signature, there is nothing to do.
if (TYPE_NODE == vtype or TYPE_CHOICE == vtype)
return;
// The only remaining possibility is that there is set of ListLinks.
if (SET_LINK != vtype)
throw InvalidParamException(TRACE_INFO,
"PutLink was expecting a ListLink, SetLink or GetLink!");
if (1 < sz)
{
for (const Handle& h : _values->getOutgoingSet())
{
// If the arity is greater than one, then the values must be in a list.
if (h->get_type() != LIST_LINK)
throw InvalidParamException(TRACE_INFO,
"PutLink expected value list!");
if (not _varlist.is_type(h->getOutgoingSet()))
throw InvalidParamException(TRACE_INFO,
"PutLink bad value list!");
}
return;
}
// If the arity is one, the values must obey type constraint.
for (const Handle& h : _values->getOutgoingSet())
{
if (not _varlist.is_type(h))
throw InvalidParamException(TRACE_INFO,
"PutLink bad type!");
}
}
/* ================================================================= */
/**
* Perform the actual beta reduction --
*
* Substitute values for the variables in the pattern tree.
* This is a lot like applying the function fun to the argument list
* args, except that no actual evaluation is performed; only
* substitution. The resulting tree is NOT placed into any atomspace,
* either. If you want that, you must do it youself. If you want
* evaluation or execution to happen during or after sustitution, use
* either the EvaluationLink, the ExecutionOutputLink, or the Instantiator.
*
* So, for example, if this PutLink looks like this:
*
* PutLink
* EvaluationLink
* PredicateNode "is a kind of"
* ListLink
* VariableNode $a
* ConceptNode "hot patootie"
* ConceptNode "cowpie"
*
* then the reduced value will be
*
* EvaluationLink
* PredicateNode "is a kind of"
* ListLink
* ConceptNode "cowpie"
* ConceptNode "hot patootie"
*
* Type checking is performed during substitution; if the values fail to
* have the desired types, no substitution is performed. In this case,
* an undefined handle is returned. For set substitutions, this acts as
* a filter, removing (filtering out) the mismatched types.
*
* Again, only a substitution is performed, there is no execution or
* evaluation. Note also that the resulting tree is NOT placed into
* any atomspace!
*/
Handle PutLink::do_reduce(void) const
{
Handle bods(_body);
Variables vars(_varlist);
// Resolve the body, if needed. That is, if the body is
// given in a defintion, get that defintion.
Type btype = _body->get_type();
if (DEFINED_SCHEMA_NODE == btype or
DEFINED_PREDICATE_NODE == btype)
{
bods = DefineLink::get_definition(bods);
btype = bods->get_type();
// XXX TODO we should perform a type-check on the function.
if (not classserver().isA(btype, LAMBDA_LINK))
throw InvalidParamException(TRACE_INFO,
"Expecting a LambdaLink, got %s",
bods->to_string().c_str());
}
// If the body is a lambda, work with that.
if (classserver().isA(btype, LAMBDA_LINK))
{
LambdaLinkPtr lam(LambdaLinkCast(bods));
bods = lam->get_body();
vars = lam->get_variables();
btype = bods->get_type();
}
// Now get the values that we will plug into the body.
Type vtype = _values->get_type();
size_t nvars = vars.varseq.size();
// At this time, we don't know the number of arguments a FunctionLink
// might take. Atomese does have the mechanisms to declare these,
// including arbitrary-arity functions, its just that its currently
// not declared anywhere. So we just punt. Example usage:
// (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))
if (0 == nvars and classserver().isA(btype, FUNCTION_LINK))
{
if (LIST_LINK == vtype)
return createLink(_values->getOutgoingSet(), btype);
if (SET_LINK != vtype)
return createLink(btype, _values);
// If the values are given in a set, then iterate over the set...
HandleSeq bset;
for (const Handle& h : _values->getOutgoingSet())
{
if (LIST_LINK == h->get_type())
bset.emplace_back(createLink(h->getOutgoingSet(), btype));
else
bset.emplace_back(createLink(btype, h));
}
return createLink(bset, SET_LINK);
}
// If there is only one variable in the PutLink body...
if (1 == nvars)
{
if (SET_LINK != vtype)
{
HandleSeq oset;
oset.emplace_back(_values);
try
{
return vars.substitute(bods, oset, /* silent */ true);
}
catch (const TypeCheckException& ex)
{
return Handle::UNDEFINED;
}
}
// If the values are given in a set, then iterate over the set...
HandleSeq bset;
for (const Handle& h : _values->getOutgoingSet())
{
HandleSeq oset;
oset.emplace_back(h);
try
{
bset.emplace_back(vars.substitute(bods, oset, /* silent */ true));
}
catch (const TypeCheckException& ex) {}
}
return createLink(bset, SET_LINK);
}
// If we are here, then there are multiple variables in the body.
// See how many values there are. If the values are a ListLink,
// then assume that there is only a single set of values to plug in.
if (LIST_LINK == vtype)
{
const HandleSeq& oset = _values->getOutgoingSet();
try
{
return vars.substitute(bods, oset, /* silent */ true);
}
catch (const TypeCheckException& ex)
{
return Handle::UNDEFINED;
}
}
// If we are here, then there are multiple values.
// These MUST be given to us as a SetLink.
OC_ASSERT(SET_LINK == vtype,
"Should have caught this earlier, in the ctor");
HandleSeq bset;
for (const Handle& h : _values->getOutgoingSet())
{
const HandleSeq& oset = h->getOutgoingSet();
try
{
bset.emplace_back(vars.substitute(bods, oset, /* silent */ true));
}
catch (const TypeCheckException& ex) {}
}
return createLink(bset, SET_LINK);
}
Handle PutLink::reduce(void)
{
return do_reduce();
}
DEFINE_LINK_FACTORY(PutLink, PUT_LINK)
/* ===================== END OF FILE ===================== */
<|endoftext|> |
<commit_before>/*
* Reference: http://www.indiana.edu/~iulg/trm/
*
* Instruction set
* ===============
* Add 1 to Rn : 1^n#
* Rn.push(1)
*
* Add # to Rn : 1^n##
* Rn.push(#)
*
* Go forward n : 1^n###
* pc += n
* Go backward n : 1^n####
* pc -= n
*
* Cases on Rn : 1^n#####
* if Rn.empty(), pc += 1
* if Rn.pop() == 1, pc += 2
* if Rn.pop() == #, pc += 3
*/
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <queue>
#include <thread>
#include <chrono>
using namespace std;
enum Code {
O,
H
};
enum Op {
Add1 = 1,
Add0 = 2,
Inc = 3,
Dec = 4,
Case = 5
};
struct Instr {
Op op;
int n;
};
struct TRM {
vector< Instr > program;
map< int, queue<Code> > mem;
void push(int i, Code c) {
mem[i].push(c);
}
int cases(int i) {
queue<Code>& Rn = mem[i];
if (Rn.empty()) {
return 1;
} else if (Rn.front() == O) {
Rn.pop();
return 2;
} else if (Rn.front() == H) {
Rn.pop();
return 3;
}
}
int print_registers() {
int lines = 0;
for (map< int, queue<Code> >::iterator it=mem.begin(); it != mem.end(); it++) {
int col = 3;
cout << "R" << it->first << ":";
queue<Code> content = it->second;
while (content.empty() == false) {
Code c = content.front();
content.pop();
if (c == O) {
cout << "1";
} else {
cout << "#";
}
col++;
if (col == 80) {
cout << endl;
cout << " ";
col = 3;
lines++;
}
}
cout << endl;
lines++;
}
return lines;
}
void clear_previous(int lines, int fps) {
this_thread::sleep_for(chrono::microseconds(1000000 / fps));
for (int i = 0; i < lines; i++) {
cout << "\x1B[1A"; // Move the cursor up one line
cout << "\x1B[2K"; // Erase the entire current line
}
}
string op2string(Op o) {
switch (o) {
case Add1: return "Add1";
case Add0: return "Add#";
case Inc: return "Inc";
case Dec: return "Dec";
case Case: return "Case";
}
}
string instr2string(Instr in) {
return op2string(in.op) + " " + to_string(in.n);
}
void print_program() {
for ( auto &p : program) {
cout << instr2string(p) << endl;
}
}
void eval(int max, int fps) {
int lines = 0;
int cnt = 0;
int pc = 0;
while (pc < program.size()) {
Instr in = program[pc];
switch (in.op) {
case Add1:
push(in.n, O);
pc++;
break;
case Add0:
push(in.n, H);
pc++;
break;
case Inc:
pc += in.n;
break;
case Dec:
pc -= in.n;
break;
case Case:
pc += cases(in.n);
break;
}
cnt++;
if (cnt > 1 && fps > 0) {
clear_previous(lines + 1, fps);
}
cout << "instr: " + instr2string(in) << endl;
lines = print_registers();
}
}
void load_program() {
cin.sync_with_stdio(false);
char curr;
int n = 0;
int c = 0;
while (cin >> curr) {
if (curr == '1') {
if (c > 0) {
n = 0;
c = 0;
}
n++;
} else if (curr == '#') {
c++;
if (c == 1) {
program.push_back({Add1, n});
} else {
program.back().op = (Op)c;
}
}
}
}
};
int main(int argc, char *argv[]) {
TRM m;
m.load_program();
m.print_program();
cout << endl;
if (argc == 1) {
m.eval(1000, 0);
} else if (argc == 2) {
m.eval(atoi(argv[1]), 0);
} else if (argc == 3) {
m.eval(atoi(argv[1]), atoi(argv[2]));
}
return 0;
}
<commit_msg>enforce max cycles<commit_after>/*
* Reference: http://www.indiana.edu/~iulg/trm/
*
* Instruction set
* ===============
* Add 1 to Rn : 1^n#
* Rn.push(1)
*
* Add # to Rn : 1^n##
* Rn.push(#)
*
* Go forward n : 1^n###
* pc += n
* Go backward n : 1^n####
* pc -= n
*
* Cases on Rn : 1^n#####
* if Rn.empty(), pc += 1
* if Rn.pop() == 1, pc += 2
* if Rn.pop() == #, pc += 3
*/
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <queue>
#include <thread>
#include <chrono>
using namespace std;
enum Code {
O,
H
};
enum Op {
Add1 = 1,
Add0 = 2,
Inc = 3,
Dec = 4,
Case = 5
};
struct Instr {
Op op;
int n;
};
struct TRM {
vector< Instr > program;
map< int, queue<Code> > mem;
void push(int i, Code c) {
mem[i].push(c);
}
int cases(int i) {
queue<Code>& Rn = mem[i];
if (Rn.empty()) {
return 1;
} else if (Rn.front() == O) {
Rn.pop();
return 2;
} else if (Rn.front() == H) {
Rn.pop();
return 3;
}
}
int print_registers() {
int lines = 0;
for (map< int, queue<Code> >::iterator it=mem.begin(); it != mem.end(); it++) {
int col = 3;
cout << "R" << it->first << ":";
queue<Code> content = it->second;
while (content.empty() == false) {
Code c = content.front();
content.pop();
if (c == O) {
cout << "1";
} else {
cout << "#";
}
col++;
if (col == 80) {
cout << endl;
cout << " ";
col = 3;
lines++;
}
}
cout << endl;
lines++;
}
return lines;
}
void clear_previous(int lines, int fps) {
this_thread::sleep_for(chrono::microseconds(1000000 / fps));
for (int i = 0; i < lines; i++) {
cout << "\x1B[1A"; // Move the cursor up one line
cout << "\x1B[2K"; // Erase the entire current line
}
}
string op2string(Op o) {
switch (o) {
case Add1: return "Add1";
case Add0: return "Add#";
case Inc: return "Inc";
case Dec: return "Dec";
case Case: return "Case";
}
}
string instr2string(Instr in) {
return op2string(in.op) + " " + to_string(in.n);
}
void print_program() {
for ( auto &p : program) {
cout << instr2string(p) << endl;
}
}
void eval(int max, int fps) {
int lines = 0;
int cnt = 0;
int pc = 0;
while (pc < program.size() && cnt < max) {
Instr in = program[pc];
switch (in.op) {
case Add1:
push(in.n, O);
pc++;
break;
case Add0:
push(in.n, H);
pc++;
break;
case Inc:
pc += in.n;
break;
case Dec:
pc -= in.n;
break;
case Case:
pc += cases(in.n);
break;
}
cnt++;
if (cnt > 1 && fps > 0) {
clear_previous(lines + 1, fps);
}
cout << "instr: " + instr2string(in) << endl;
lines = print_registers();
}
}
void load_program() {
cin.sync_with_stdio(false);
char curr;
int n = 0;
int c = 0;
while (cin >> curr) {
if (curr == '1') {
if (c > 0) {
n = 0;
c = 0;
}
n++;
} else if (curr == '#') {
c++;
if (c == 1) {
program.push_back({Add1, n});
} else {
program.back().op = (Op)c;
}
}
}
}
};
int main(int argc, char *argv[]) {
TRM m;
m.load_program();
m.print_program();
cout << endl;
if (argc == 1) {
m.eval(1000, 0);
} else if (argc == 2) {
m.eval(atoi(argv[1]), 0);
} else if (argc == 3) {
m.eval(atoi(argv[1]), atoi(argv[2]));
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "message.h"
#include "segment.h"
#include "register_request_message.h"
using namespace std;
// Checks the number and formats of the environment variables passed
void checkEnvironmentVariables() {
char* serverAddress = getenv("BINDER_ADDRESS");
if (serverAddress == 0) {
exit(-1);
} // if
char* serverPort = getenv("BINDER_PORT");
if (serverPort == 0) {
exit(-1);
} // if
} // checkEnvironmentVariables
// Sets up the client socket
int setUpClientSocket() {
struct addrinfo serverAddressHints;
struct addrinfo* serverAddressResults;
// Creates the client socket
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket < 0) {
exit(-1);
} // if
// Gets the environment variables passed
char* serverAddress = getenv("BINDER_ADDRESS");
char* serverPort = getenv("BINDER_PORT");
// Sets up the server address hints and results to perform the DNS
// lookup on the server's host name to obtain the server's IP address
memset(&serverAddressHints, 0, sizeof(serverAddressHints));
serverAddressHints.ai_family = AF_INET;
serverAddressHints.ai_socktype = SOCK_STREAM;
// Performs a DNS lookup on the server's host name to obtain the
// server's IP address
int result = getaddrinfo(serverAddress, serverPort,
&serverAddressHints, &serverAddressResults);
if (result != 0) {
exit(-1);
} // if
// Initiates the TCP connection between the client and the server
result = connect(clientSocket, serverAddressResults->ai_addr,
serverAddressResults->ai_addrlen);
if (result < 0) {
exit(-1);
} // if
// Frees up memory allocated for the server address results
freeaddrinfo(serverAddressResults);
return clientSocket;
} //setUpSocket
int main() {
// Checks the number and formats of the environment variables passed
checkEnvironmentVariables();
// Sets up the client socket
int clientSocket = setUpClientSocket();
string serverIdentifier = "ubuntu1404-002.student.cs.uwaterloo.ca";
unsigned int port = 80;
string name = "func";
int argTypes[3] = {1337, 2525, 369};
RegisterRequestMessage msg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);
cout << "Server Identifier: " << msg.getServerIdentifier() << endl;
cout << "Port: " << msg.getPort() << endl;
cout << "Name: " << msg.getName() << endl;
cout << "ArgTypes: " << *(msg.getArgTypes()) << ", " << *(msg.getArgTypes() + 1) << ", " << *(msg.getArgTypes() + 2) << ", " << *(msg.getArgTypes() + 3) << ", " <<endl;
Segment seg = Segment(msg.getLength(), MSG_TYPE_REGISTER_REQUEST, &msg);
seg.send(clientSocket);
// Closes the client socket
sleep(2);
close(clientSocket);
} // main
<commit_msg>changes<commit_after>#include <iostream>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "message.h"
#include "segment.h"
#include "register_request_message.h"
using namespace std;
// Checks the number and formats of the environment variables passed
void checkEnvironmentVariables() {
char* serverAddress = getenv("BINDER_ADDRESS");
if (serverAddress == 0) {
exit(-1);
} // if
char* serverPort = getenv("BINDER_PORT");
if (serverPort == 0) {
exit(-1);
} // if
} // checkEnvironmentVariables
// Sets up the client socket
int setUpClientSocket() {
struct addrinfo serverAddressHints;
struct addrinfo* serverAddressResults;
// Creates the client socket
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket < 0) {
exit(-1);
} // if
// Gets the environment variables passed
char* serverAddress = getenv("BINDER_ADDRESS");
char* serverPort = getenv("BINDER_PORT");
// Sets up the server address hints and results to perform the DNS
// lookup on the server's host name to obtain the server's IP address
memset(&serverAddressHints, 0, sizeof(serverAddressHints));
serverAddressHints.ai_family = AF_INET;
serverAddressHints.ai_socktype = SOCK_STREAM;
// Performs a DNS lookup on the server's host name to obtain the
// server's IP address
int result = getaddrinfo(serverAddress, serverPort,
&serverAddressHints, &serverAddressResults);
if (result != 0) {
exit(-1);
} // if
// Initiates the TCP connection between the client and the server
result = connect(clientSocket, serverAddressResults->ai_addr,
serverAddressResults->ai_addrlen);
if (result < 0) {
exit(-1);
} // if
// Frees up memory allocated for the server address results
freeaddrinfo(serverAddressResults);
return clientSocket;
} //setUpSocket
int main() {
// Checks the number and formats of the environment variables passed
checkEnvironmentVariables();
// Sets up the client socket
int clientSocket = setUpClientSocket();
string serverIdentifier = "ubuntu1404-002.student.cs.uwaterloo.ca";
unsigned int port = 80;
string name = "func";
/* prepare the arguments for f0 */
int a0 = 5;
int b0 = 10;
int count0 = 3;
int return0;
int argTypes0[count0 + 1];
void **args0;
argTypes0[0] = (1 << ARG_OUTPUT) | (ARG_INT << 16);
argTypes0[1] = (1 << ARG_INPUT) | (ARG_INT << 16);
argTypes0[2] = (1 << ARG_INPUT) | (ARG_INT << 16);
argTypes0[3] = 0;
args0 = (void **)malloc(count0 * sizeof(void *));
args0[0] = (void *)&return0;
args0[1] = (void *)&a0;
args0[2] = (void *)&b0;
ExecuteRequestMessage msg = ExecuteRequestMessage(name, argTypes);
//cout << "Server Identifier: " << msg.getServerIdentifier() << endl;
//cout << "Port: " << msg.getPort() << endl;
//cout << "Name: " << msg.getName() << endl;
//cout << "ArgTypes: " << *(msg.getArgTypes()) << ", " << *(msg.getArgTypes() + 1) << ", " << *(msg.getArgTypes() + 2) << ", " << *(msg.getArgTypes() + 3) << ", " <<endl;
Segment seg = Segment(msg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &msg);
seg.send(clientSocket);
// Closes the client socket
sleep(2);
close(clientSocket);
} // main
<|endoftext|> |
<commit_before>#include "tui.h"
#include <assert.h>
#include <climits>
void Tui::add(std::shared_ptr<AComponent> const& c)
{
if(std::dynamic_pointer_cast<Menu>(c)) {
m_menus.push_back(c);
return;
}
m_built.assign("");
assert(m_current < m_ctrls.size());
m_ctrls[m_current].push_back(c);
}
void Tui::ln()
{
m_built.assign("");
m_ctrls.resize(m_ctrls.size() + 1);
m_current++;
}
void Tui::width(int const w)
{
m_width = w;
}
int Tui::build()
{
int max_width = m_width - 1 - 2;
for(size_t i = 0; i < m_ctrls.size(); ++i) {
int line_width = 3;
ComponentDriver drv;
drv.line = 0;
if(m_ctrls[i].size() == 0) continue;
drv.width = max_width / m_ctrls[i].size();
drv.height = 1;
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
int w = m_ctrls[i][j]->width(drv);
if(w < 0) line_width++;
else line_width += 1 + w;
}
if(line_width > max_width) max_width = line_width;
}
std::stringstream s;
// title bar
s << ' ' << std::string(max_width - 2, '_') << ' ' << std::endl;
s << "|X|_" << m_name << std::string(max_width - 4 - m_name.size() - 4, '_') << "_|+|" << std::endl;
//s << '|' << std::string(max_width - 2, '-') << '|' << std::endl;
s << "|";
int menuWidth = max_width - 1 - 2;
ComponentDriver scratch01;
for(std::vector<std::shared_ptr<AComponent> >::iterator i = m_menus.begin();
i != m_menus.end(); ++i)
{
if(menuWidth < (*i)->width(scratch01)) break;
s << '-';
menuWidth -= 1 + (*i)->width(scratch01);
s << (*i)->str(scratch01);
}
s << std::string(menuWidth, '-');
s << "-|" << std::endl;
for(size_t i = 0; i < m_ctrls.size(); ++i) {
int max_height = 0;
ComponentDriver drv;
if(m_ctrls[i].size() == 0) {
s << "|" << std::string(max_width - 2, ' ') << "|" << std::endl;
continue;
}
drv.width = max_width / m_ctrls[i].size();
drv.line = 0;
drv.height = 1;
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
int h = m_ctrls[i][j]->height(drv);
if(h > max_height) max_height = h;
}
drv.height = max_height;
// compute width of variable width components
std::vector<int> widths(m_ctrls[i].size(), 0);
float max_weight = 0.0f;
int remaining = max_width - 3;
bool haveVariableWidthComponents(false);
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
remaining--;
int w = m_ctrls[i][j]->width(drv);
if(w > 0) {
widths[j] = w;
remaining -= w;
} else {
max_weight += m_ctrls[i][j]->my_weight();
haveVariableWidthComponents = true;
}
}
int splitremaining = remaining;
struct {
size_t idx;
int val;
} min = { -1, INT_MAX };
if(haveVariableWidthComponents)
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
int w = m_ctrls[i][j]->width(drv);
if(w <= 0) {
widths[j] = splitremaining * m_ctrls[i][j]->my_weight() / max_weight;
if(widths[j] < min.val) {
min.idx = j;
min.val = widths[j];
}
remaining -= widths[j];
}
}
if(haveVariableWidthComponents && remaining) {
widths[min.idx] += remaining;
remaining = 0;
}
for(int h = 0; h < drv.height; ++h) {
drv.line = h;
s << "|";
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
drv.width = widths[j];
s << " " << m_ctrls[i][j]->str(drv);
}
if(remaining) {
s << std::string(remaining, ' ');
}
s << " |" << std::endl;
}
}
s << "|" << std::string(max_width - 2, '_') << "|" << std::endl;
m_built.assign(s.str());
return 0;
}
char const* const Tui::str() const
{
return m_built.c_str();
}
<commit_msg>don't print menubar line if no menu entries are present<commit_after>#include "tui.h"
#include <assert.h>
#include <climits>
void Tui::add(std::shared_ptr<AComponent> const& c)
{
if(std::dynamic_pointer_cast<Menu>(c)) {
m_menus.push_back(c);
return;
}
m_built.assign("");
assert(m_current < m_ctrls.size());
m_ctrls[m_current].push_back(c);
}
void Tui::ln()
{
m_built.assign("");
m_ctrls.resize(m_ctrls.size() + 1);
m_current++;
}
void Tui::width(int const w)
{
m_width = w;
}
int Tui::build()
{
int max_width = m_width - 1 - 2;
for(size_t i = 0; i < m_ctrls.size(); ++i) {
int line_width = 3;
ComponentDriver drv;
drv.line = 0;
if(m_ctrls[i].size() == 0) continue;
drv.width = max_width / m_ctrls[i].size();
drv.height = 1;
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
int w = m_ctrls[i][j]->width(drv);
if(w < 0) line_width++;
else line_width += 1 + w;
}
if(line_width > max_width) max_width = line_width;
}
std::stringstream s;
// title bar
s << ' ' << std::string(max_width - 2, '_') << ' ' << std::endl;
s << "|X|_" << m_name << std::string(max_width - 4 - m_name.size() - 4, '_') << "_|+|" << std::endl;
//s << '|' << std::string(max_width - 2, '-') << '|' << std::endl;
if(m_menus.size()) {
s << "|";
int menuWidth = max_width - 1 - 2;
ComponentDriver scratch01;
for(std::vector<std::shared_ptr<AComponent> >::iterator i = m_menus.begin();
i != m_menus.end(); ++i)
{
if(menuWidth < (*i)->width(scratch01)) break;
s << '-';
menuWidth -= 1 + (*i)->width(scratch01);
s << (*i)->str(scratch01);
}
s << std::string(menuWidth, '-');
s << "-|" << std::endl;
}/* else {
s << '|' << std::string(max_width - 2, ' ') << '|' << std::endl;
}*/
for(size_t i = 0; i < m_ctrls.size(); ++i) {
int max_height = 0;
ComponentDriver drv;
if(m_ctrls[i].size() == 0) {
s << "|" << std::string(max_width - 2, ' ') << "|" << std::endl;
continue;
}
drv.width = max_width / m_ctrls[i].size();
drv.line = 0;
drv.height = 1;
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
int h = m_ctrls[i][j]->height(drv);
if(h > max_height) max_height = h;
}
drv.height = max_height;
// compute width of variable width components
std::vector<int> widths(m_ctrls[i].size(), 0);
float max_weight = 0.0f;
int remaining = max_width - 3;
bool haveVariableWidthComponents(false);
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
remaining--;
int w = m_ctrls[i][j]->width(drv);
if(w > 0) {
widths[j] = w;
remaining -= w;
} else {
max_weight += m_ctrls[i][j]->my_weight();
haveVariableWidthComponents = true;
}
}
int splitremaining = remaining;
struct {
size_t idx;
int val;
} min = { -1, INT_MAX };
if(haveVariableWidthComponents)
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
int w = m_ctrls[i][j]->width(drv);
if(w <= 0) {
widths[j] = splitremaining * m_ctrls[i][j]->my_weight() / max_weight;
if(widths[j] < min.val) {
min.idx = j;
min.val = widths[j];
}
remaining -= widths[j];
}
}
if(haveVariableWidthComponents && remaining) {
widths[min.idx] += remaining;
remaining = 0;
}
for(int h = 0; h < drv.height; ++h) {
drv.line = h;
s << "|";
for(size_t j = 0; j < m_ctrls[i].size(); ++j) {
drv.width = widths[j];
s << " " << m_ctrls[i][j]->str(drv);
}
if(remaining) {
s << std::string(remaining, ' ');
}
s << " |" << std::endl;
}
}
s << "|" << std::string(max_width - 2, '_') << "|" << std::endl;
m_built.assign(s.str());
return 0;
}
char const* const Tui::str() const
{
return m_built.c_str();
}
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Model
#include <boost/test/included/unit_test.hpp>
#include "../inc/model.hpp"
using namespace Model;
const quat<float> R0{0}, R1{1},
i{0,1}, j{0,0,1}, k{0,0,0,1};
const dual<float> E0{R0}, E1{R0, 1},
Ei = E1*i, Ej = E1*j, Ek = E1*k;
BOOST_AUTO_TEST_CASE(quaternions) {
BOOST_CHECK_EQUAL(i*j, k);
BOOST_CHECK_EQUAL(j*i,-k);
}
BOOST_AUTO_TEST_CASE(dual_quaternions) {
BOOST_CHECK_EQUAL(E1*E1, E0);
}
<commit_msg>Began troubleshooting errors with test suites when *linking* (!) with Clang++.<commit_after>#include <string>
#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Model
#include <boost/test/included/unit_test.hpp>
#include "../inc/quat.hpp"
#include "../inc/dual.hpp"
#include "../inc/model.hpp"
using namespace Model;
const quat<float> R0{0}, R1{1},
i{0,1}, j{0,0,1}, k{0,0,0,1};
const dual<float> E0{R0}, E1{R0, 1},
Ei = E1*i, Ej = E1*j, Ek = E1*k;
BOOST_AUTO_TEST_CASE(quaternions) {
BOOST_CHECK_EQUAL(i*j, k);
BOOST_CHECK_EQUAL(j*i,-k);
}
BOOST_AUTO_TEST_CASE(dual_quaternions) {
BOOST_CHECK_EQUAL(E1*E1, E0);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>
#include <algorithm>
using namespace std;
Base::~Base()
{
}<commit_msg>forgot to include header<commit_after>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>
#include <algorithm>
using namespace std;
#include "Base.h"
Base::~Base()
{
}<|endoftext|> |
<commit_before>//
// Created by JULIA BALAJAN on 3/12/2016.
//
#include <random>
#include <iostream>
#include <algorithm>
#include "Game.h"
uint8_t Game::get_next_block() {
static std::mt19937 generator(std::random_device{}());
std::uniform_int_distribution<int> distribution(0,cCoord::max_coordinates);
int val;
for (val = distribution(generator); val == prev_block; val = distribution(generator))
;
return val;
}
uint8_t Game::get_color_value() {
static std::mt19937 generator(std::random_device{}());
std::uniform_int_distribution<int> distribution(0, 255);\
return distribution(generator);
}
// Stores template for all the different tetris pieces
const cCoord Game::struct_coords[][cCoord::max_coordinates + 1] = {{
/* Row: 1 */ {0, 0}, {1, 0}, {2, 0},
/* Row: 2 */ {0, 1},
},
{
/* Row: 1 */ {0, 0}, {1, 0},
/* Row: 2 */ {0, 1}, {1, 1},
},
{
/* Row: 1 */ {0, 0},
/* Row: 2 */ {0, 1},
/* Row: 3 */ {0, 2},
/* Row: 4 */ {0, 3},
},
{
/* Row: 1 */ {1, 0}, {2, 0},
/* Row: 2 */ {0, 1}, {1, 1},
},
{
/* Row: 1 */ {1, 0},
/* Row: 2 */ {0, 1}, {1, 1}, {2, 1},
}};
// Stores the origins coords for all the different tetris pieces
const cCoord Game::struct_origins[cCoord::max_coordinates + 1] = {
/* L Shaped */ {0, 0},
/* Square shaped */ {0, 0},
/* Stick shaped */ {0, 0},
/* Stair shaped */ {1, 0},
/* T shaped */ {1, 1},
};
Game::Game() {
create_block();
}
inline void Game::create_block() {
structList.push_back(Structure(get_next_block()));
}
Structure& Game::get_last_block() {
return *(structList.end() - 1);
}
bool Game::isGameOver() const {
return gameOver;
}
std::vector<Structure>& Game::getStructList() {
return structList;
}
void Game::set_draw_color(const Structure &s) {
SDL_SetRenderDrawColor(ren, s.red, s.green, s.blue, SDL_ALPHA_OPAQUE);
}
void Game::init() {
// Initialise SDL_ttf
if (TTF_Init() == -1) {
std::cout << "Unable to initialise SDL_ttf: " << SDL_GetError() << std::endl;
exit(1);
}
// Create window
win = SDL_CreateWindow("Tetris", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN);
if (win == nullptr) {
std::cout << "Window error: " << SDL_GetError() << std::endl;
exit(1);
}
// Create renderer
ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);
if (ren == nullptr) {
std::cout << "Renderer error: " << SDL_GetError() << std::endl;
SDL_DestroyWindow(win);
exit(1);
}
// Create white background
SDL_Rect screen;
screen.x = 0;
screen.y = 0;
screen.w = screen_width;
screen.h = screen_height;
SDL_SetRenderDrawColor(ren, 255, 255, 255, SDL_ALPHA_OPAQUE);
SDL_RenderFillRect(ren, &screen);
// Initialise font
constexpr int font_size = 48;
font = TTF_OpenFont("pixelated.ttf", font_size);
if (font == nullptr) {
std::cout << "Font Initialisation Error: " << SDL_GetError() << std::endl;
cleanup();
exit(1);
}
}
void Game::draw () {
SDL_SetRenderDrawColor(ren, 255, 255, 255, SDL_ALPHA_OPAQUE);
SDL_RenderClear(ren);
SDL_Rect dest;
dest.w = tile_size;
dest.h = tile_size;
int x,
y;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
// Cycle through x and y, if x and y match with block, draw block
for (auto iter1 = structList.cbegin(); iter1 != structList.cend(); ++iter1)
for (auto iter2 = iter1->coords.cbegin(); iter2 != iter1->coords.cend(); ++iter2)
if (x == iter2->get_x() && y == iter2->get_y()) {
set_draw_color(*iter1);
dest.x = x * tile_size;
dest.y = y * tile_size;
SDL_RenderFillRect(ren, &dest);
SDL_SetRenderDrawColor(ren, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderDrawRect(ren, &dest);
break;
}
}
}
const SDL_Color color = {0, 0, 0};
SDL_Surface *font_surf = TTF_RenderText_Blended(font, (std::string("Score: ") + std::to_string(score)).c_str(), color);
if (font_surf == nullptr) {
std::cout << "Font Rendering Error: " << SDL_GetError() << std::endl;
TTF_CloseFont(font);
cleanup();
exit(1);
}
SDL_Texture *font_texture = SDL_CreateTextureFromSurface(ren, font_surf);
if (font_texture == nullptr) {
std::cout << "Create Font Texture Error: " << SDL_GetError() << std::endl;
TTF_CloseFont(font);
SDL_FreeSurface(font_surf);
cleanup();
exit(1);
}
SDL_FreeSurface(font_surf);
constexpr int padding = 17;
int w,
h;
SDL_QueryTexture(font_texture, nullptr, nullptr, &w, &h);
dest.w = w;
dest.h = h;
dest.x = screen_width - w - padding;
dest.y = 0 + padding;
SDL_RenderCopy(ren, font_texture, nullptr, &dest);
SDL_RenderPresent(ren);
}
void Game::cleanup() {
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
}
void Game::controls (unsigned int &last_time) {
unsigned long current_time = SDL_GetTicks();
if ((current_time - last_time) > Game::wait_time_controls) {
SDL_PollEvent(&events);
if (events.type == SDL_KEYDOWN) {
switch(events.key.keysym.sym) {
case SDLK_UP :
get_last_block().rotate_left(structList);
break;
case SDLK_DOWN :
get_last_block().rotate_right(structList);
break;
case SDLK_LEFT :
get_last_block().move_left(structList);
break;
case SDLK_RIGHT :
get_last_block().move_right(structList);
break;
case SDLK_SPACE :
while(!get_last_block().move_down(structList))
;
break;
case SDLK_ESCAPE :
exit(0);
break;
}
}
if(events.type == SDL_QUIT)
gameOver = true;
last_time = SDL_GetTicks();
}
}
void Game::destroy() {
bool fall_flag = false; // Flag to indicate whether the blocks should fall
bool row_destroyed_flag = false; // Flag indicating whether a row has been destroyed
int row_to_destroy; // Y value indicating the row to be destroyed
int row_counter[height]; // Counter, to know which row to destroy
int rows_been_destroyed = 0; // Count of how many rows have been destroyed to be used when calculating fall distance
do {
row_destroyed_flag = false;
// Set the counter to 0
std::fill(std::begin(row_counter), std::end(row_counter), 0);
// Iterate through all the blocks, check if there are any complete rows, if so, destroy them
for (auto &s : structList)
for (auto &b : s.coords) {
// If there is a complete row
if (++row_counter[row_to_destroy = b.get_y()] >= width) {
// Destroy the blocks in the row
++rows_been_destroyed;
for (auto &s : structList)
for (auto block_iter = s.coords.begin(); block_iter != s.coords.end();) {
if (block_iter->get_y() == row_to_destroy) {
block_iter = s.coords.erase(block_iter);
fall_flag = row_destroyed_flag = true;
continue;
}
++block_iter;
}
}
}
} while (row_destroyed_flag); // Re-iterate if a row was destroyed
if (rows_been_destroyed <= 4)
score += (100 * rows_been_destroyed);
else if (rows_been_destroyed > 4)
score += (200 * rows_been_destroyed);
// If blocks have been destroyed, make the blocks above fall
if (fall_flag) {
// Iterate through the blocks, making the blocks above the destroyed row fall
for (auto &s : structList)
for (auto &b : s.coords)
if (b.get_y() <= row_to_destroy)
b.move_down(rows_been_destroyed); // Fall by how many rows have been destroyed
}
}
void Game::gameOverChecker() {
if(structList.size() < 2)
return;
Structure block = *(structList.end() - 2);
for (auto iter1 = block.coords.cbegin(); iter1 != block.coords.cend(); ++iter1) {
if (iter1->get_y() <= 1) {
gameOver = true;
cleanup();
return;
}
}
}
bool Game::collision_detector_y(int x, int y, std::vector<Structure> &structList) {
for (auto i1 = structList.cbegin(); i1 != structList.end() - 1; ++i1)
for (auto i2 = i1->coords.cbegin(); i2 != i1->coords.cend(); ++i2)
if (i2->get_y() == y && i2->get_x() == x)
return true;
return false;
}
bool Game::collision_detector_x(int x, int y, std::vector<Structure> &structList) {
for (auto i1 = structList.cbegin(); i1 != structList.end() - 1; ++i1)
for (auto i2 = i1->coords.cbegin(); i2 != i1->coords.cend(); ++i2)
if (i2->get_x() == x && i2->get_y() == y)
return true;
return false;
}
<commit_msg>Fixed destroy method once and for all<commit_after>//
// Created by JULIA BALAJAN on 3/12/2016.
//
#include <random>
#include <iostream>
#include <algorithm>
#include "Game.h"
uint8_t Game::get_next_block() {
static std::mt19937 generator(std::random_device{}());
std::uniform_int_distribution<int> distribution(0,cCoord::max_coordinates);
int val;
for (val = distribution(generator); val == prev_block; val = distribution(generator))
;
return val;
}
uint8_t Game::get_color_value() {
static std::mt19937 generator(std::random_device{}());
std::uniform_int_distribution<int> distribution(0, 255);\
return distribution(generator);
}
// Stores template for all the different tetris pieces
const cCoord Game::struct_coords[][cCoord::max_coordinates + 1] = {{
/* Row: 1 */ {0, 0}, {1, 0}, {2, 0},
/* Row: 2 */ {0, 1},
},
{
/* Row: 1 */ {0, 0}, {1, 0},
/* Row: 2 */ {0, 1}, {1, 1},
},
{
/* Row: 1 */ {0, 0},
/* Row: 2 */ {0, 1},
/* Row: 3 */ {0, 2},
/* Row: 4 */ {0, 3},
},
{
/* Row: 1 */ {1, 0}, {2, 0},
/* Row: 2 */ {0, 1}, {1, 1},
},
{
/* Row: 1 */ {1, 0},
/* Row: 2 */ {0, 1}, {1, 1}, {2, 1},
}};
// Stores the origins coords for all the different tetris pieces
const cCoord Game::struct_origins[cCoord::max_coordinates + 1] = {
/* L Shaped */ {0, 0},
/* Square shaped */ {0, 0},
/* Stick shaped */ {0, 0},
/* Stair shaped */ {1, 0},
/* T shaped */ {1, 1},
};
Game::Game() {
create_block();
}
inline void Game::create_block() {
structList.push_back(Structure(get_next_block()));
}
Structure& Game::get_last_block() {
return *(structList.end() - 1);
}
bool Game::isGameOver() const {
return gameOver;
}
std::vector<Structure>& Game::getStructList() {
return structList;
}
void Game::set_draw_color(const Structure &s) {
SDL_SetRenderDrawColor(ren, s.red, s.green, s.blue, SDL_ALPHA_OPAQUE);
}
void Game::init() {
// Initialise SDL_ttf
if (TTF_Init() == -1) {
std::cout << "Unable to initialise SDL_ttf: " << SDL_GetError() << std::endl;
exit(1);
}
// Create window
win = SDL_CreateWindow("Tetris", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN);
if (win == nullptr) {
std::cout << "Window error: " << SDL_GetError() << std::endl;
exit(1);
}
// Create renderer
ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);
if (ren == nullptr) {
std::cout << "Renderer error: " << SDL_GetError() << std::endl;
SDL_DestroyWindow(win);
exit(1);
}
// Create white background
SDL_Rect screen;
screen.x = 0;
screen.y = 0;
screen.w = screen_width;
screen.h = screen_height;
SDL_SetRenderDrawColor(ren, 255, 255, 255, SDL_ALPHA_OPAQUE);
SDL_RenderFillRect(ren, &screen);
// Initialise font
constexpr int font_size = 48;
font = TTF_OpenFont("pixelated.ttf", font_size);
if (font == nullptr) {
std::cout << "Font Initialisation Error: " << SDL_GetError() << std::endl;
cleanup();
exit(1);
}
}
void Game::draw () {
SDL_SetRenderDrawColor(ren, 255, 255, 255, SDL_ALPHA_OPAQUE);
SDL_RenderClear(ren);
SDL_Rect dest;
dest.w = tile_size;
dest.h = tile_size;
int x,
y;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
// Cycle through x and y, if x and y match with block, draw block
for (auto iter1 = structList.cbegin(); iter1 != structList.cend(); ++iter1)
for (auto iter2 = iter1->coords.cbegin(); iter2 != iter1->coords.cend(); ++iter2)
if (x == iter2->get_x() && y == iter2->get_y()) {
set_draw_color(*iter1);
dest.x = x * tile_size;
dest.y = y * tile_size;
SDL_RenderFillRect(ren, &dest);
SDL_SetRenderDrawColor(ren, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderDrawRect(ren, &dest);
break;
}
}
}
const SDL_Color color = {0, 0, 0};
SDL_Surface *font_surf = TTF_RenderText_Blended(font, (std::string("Score: ") + std::to_string(score)).c_str(), color);
if (font_surf == nullptr) {
std::cout << "Font Rendering Error: " << SDL_GetError() << std::endl;
TTF_CloseFont(font);
cleanup();
exit(1);
}
SDL_Texture *font_texture = SDL_CreateTextureFromSurface(ren, font_surf);
if (font_texture == nullptr) {
std::cout << "Create Font Texture Error: " << SDL_GetError() << std::endl;
TTF_CloseFont(font);
SDL_FreeSurface(font_surf);
cleanup();
exit(1);
}
SDL_FreeSurface(font_surf);
constexpr int padding = 17;
int w,
h;
SDL_QueryTexture(font_texture, nullptr, nullptr, &w, &h);
dest.w = w;
dest.h = h;
dest.x = screen_width - w - padding;
dest.y = 0 + padding;
SDL_RenderCopy(ren, font_texture, nullptr, &dest);
SDL_RenderPresent(ren);
}
void Game::cleanup() {
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
}
void Game::controls (unsigned int &last_time) {
unsigned long current_time = SDL_GetTicks();
if ((current_time - last_time) > Game::wait_time_controls) {
SDL_PollEvent(&events);
if (events.type == SDL_KEYDOWN) {
switch(events.key.keysym.sym) {
case SDLK_UP :
get_last_block().rotate_left(structList);
break;
case SDLK_DOWN :
get_last_block().rotate_right(structList);
break;
case SDLK_LEFT :
get_last_block().move_left(structList);
break;
case SDLK_RIGHT :
get_last_block().move_right(structList);
break;
case SDLK_SPACE :
while(!get_last_block().move_down(structList))
;
break;
case SDLK_ESCAPE :
exit(0);
break;
}
}
if(events.type == SDL_QUIT)
gameOver = true;
last_time = SDL_GetTicks();
}
}
void Game::destroy() {
bool fall_flag = false; // Flag to indicate whether the blocks should fall
bool row_destroyed_flag = false; // Flag indicating whether a row has been destroyed
int row_to_destroy; // Y value indicating the row to be destroyed
std::vector<int> row_counter(height); // Counter, to know which row to destroy
int rows_been_destroyed = 0; // Count of how many rows have been destroyed to be used when calculating fall distance
do {
row_destroyed_flag = false;
// Set the counter to 0
// Iterate through all the blocks, check if there are any complete rows, if so, destroy them
for (auto &s : structList)
for (auto &b : s.coords) {
// If there is a complete row
if (++(row_counter[b.get_y()]) >= width) {
row_to_destroy = b.get_y();
std::cerr << "Counter: " << row_counter[row_to_destroy] << '\n';
std::fill(row_counter.begin(), row_counter.end(), 0);
// Destroy the blocks in the row
++rows_been_destroyed;
for (auto &s : structList)
for (auto block_iter = s.coords.begin(); block_iter != s.coords.end();) {
if (block_iter->get_y() == row_to_destroy) {
std::cerr << row_to_destroy << '\n';
block_iter = s.coords.erase(block_iter);
fall_flag = row_destroyed_flag = true;
continue;
}
++block_iter;
}
}
}
} while (row_destroyed_flag); // Re-iterate if a row was destroyed
if (rows_been_destroyed <= 4)
score += (100 * rows_been_destroyed);
else if (rows_been_destroyed > 4)
score += (200 * rows_been_destroyed);
// If blocks have been destroyed, make the blocks above fall
if (fall_flag) {
// Iterate through the blocks, making the blocks above the destroyed row fall
for (auto &s : structList)
for (auto &b : s.coords)
if (b.get_y() < row_to_destroy) {
b.move_down(rows_been_destroyed); // Fall by how many rows have been destroyed
}
}
}
void Game::gameOverChecker() {
if(structList.size() < 2)
return;
Structure block = *(structList.end() - 2);
for (auto iter1 = block.coords.cbegin(); iter1 != block.coords.cend(); ++iter1) {
if (iter1->get_y() <= 1) {
gameOver = true;
cleanup();
return;
}
}
}
bool Game::collision_detector_y(int x, int y, std::vector<Structure> &structList) {
for (auto i1 = structList.cbegin(); i1 != structList.end() - 1; ++i1)
for (auto i2 = i1->coords.cbegin(); i2 != i1->coords.cend(); ++i2)
if (i2->get_y() == y && i2->get_x() == x)
return true;
return false;
}
bool Game::collision_detector_x(int x, int y, std::vector<Structure> &structList) {
for (auto i1 = structList.cbegin(); i1 != structList.end() - 1; ++i1)
for (auto i2 = i1->coords.cbegin(); i2 != i1->coords.cend(); ++i2)
if (i2->get_x() == x && i2->get_y() == y)
return true;
return false;
}
<|endoftext|> |
<commit_before>//Lab 6
//modified from http://learnopengl.com/
#include <ctime>
#include "stdafx.h"
#include "..\glew\glew.h" // include GL Extension Wrangler
#include "..\glfw\glfw3.h" // include GLFW helper library
#include <stdio.h>
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <fstream>
#include "glm.hpp"
#include "gtc/matrix_transform.hpp"
#include "gtc/type_ptr.hpp"
#include "Building.h"
#include <..\COMP371_Lab7\objloader.hpp>
#include "..\soil\SOIL.h"
using namespace std;
// Window dimensions
const GLuint WINDOW_WIDTH = 1000, WINDOW_HEIGHT = 1000;
const GLfloat CAMERA_MOVEMENT_STEP = 2.20f;
const float ANGLE_ROTATION_STEP = 0.15f;
glm::vec3 camera_position;
glm::mat4 projection_matrix;
//Declaring global array
vector<glm::vec3> vecBuildingCoordinate; //coordinate of the building
vector<glm::vec3> vecBuildingSize; //building size
vector<glm::vec3> vecBuildingColor; //building color
vector<glm::vec3> vecMapCoordinate; //coordinate of the new maps (for procedural generator)
//Declaring the method signature
glm::vec3 createBuilding();
glm::vec3 createCoordinate();
glm::vec3 createColor();
float randomFloat(float a, float b);
float y_rotation_angle = 0.0f, x_rotation_angle = 0.0f;
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
// Update the Projection matrix after a window resize event
projection_matrix = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 1000.0f);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
std::cout << key << std::endl;
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if (key == GLFW_KEY_W && action == GLFW_PRESS)
camera_position.z += CAMERA_MOVEMENT_STEP;
if (key == GLFW_KEY_S && action == GLFW_PRESS)
camera_position.z -= CAMERA_MOVEMENT_STEP;
if (key == GLFW_KEY_A && action == GLFW_PRESS)
camera_position.x -= CAMERA_MOVEMENT_STEP;
if (key == GLFW_KEY_D && action == GLFW_PRESS)
camera_position.x += CAMERA_MOVEMENT_STEP;
//rotate cube
if (key == GLFW_KEY_DOWN && action == GLFW_PRESS)
x_rotation_angle += ANGLE_ROTATION_STEP;
if (key == GLFW_KEY_UP && action == GLFW_PRESS)
x_rotation_angle -= ANGLE_ROTATION_STEP;
if (key == GLFW_KEY_RIGHT && action == GLFW_PRESS)
y_rotation_angle += ANGLE_ROTATION_STEP;
if (key == GLFW_KEY_LEFT && action == GLFW_PRESS)
y_rotation_angle -= ANGLE_ROTATION_STEP;
}
GLuint loadCubemap(vector<const GLchar*> faces)
{
GLuint textureID;
glGenTextures(1, &textureID);
int width, height;
unsigned char* image;
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
for (GLuint i = 0; i < faces.size(); i++)
{
image = SOIL_load_image(faces[i], &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,
GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image
);
SOIL_free_image_data(image); //free resources
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
return textureID;
}
int main()
{
srand(time(0)); //random number generator seed
std::cout << "Starting Project Team 2" << std::endl;
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 8);
glEnable(GL_MULTISAMPLE);
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Cubemaps", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
// Define the viewport dimensions
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
projection_matrix = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 1000.0f);
// Build and compile our shader program
// Vertex shader
// Read the Vertex Shader code from the file
string vertex_shader_path = "vertex.shader";
string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_shader_path, ios::in);
if (VertexShaderStream.is_open()) {
string Line = "";
while (getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}
else {
printf("Impossible to open %s. Are you in the right directory ?\n", vertex_shader_path.c_str());
getchar();
exit(-1);
}
// Read the Fragment Shader code from the file
string fragment_shader_path = "fragment.shader";
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_shader_path, std::ios::in);
if (FragmentShaderStream.is_open()) {
std::string Line = "";
while (getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
else {
printf("Impossible to open %s. Are you in the right directory?\n", fragment_shader_path.c_str());
getchar();
exit(-1);
}
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(vertexShader, 1, &VertexSourcePointer, NULL);
glCompileShader(vertexShader);
// Check for compile time errors
GLint success;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(fragmentShader, 1, &FragmentSourcePointer, NULL);
glCompileShader(fragmentShader);
// Check for compile time errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Link shaders
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// Check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader); //free up memory
glDeleteShader(fragmentShader);
glUseProgram(shaderProgram);
std::vector<glm::vec3> vertices;
std::vector<glm::vec3> normals;
std::vector<glm::vec2> UVs;
loadOBJ("cube.obj", vertices, normals, UVs);
GLuint VAO, vertices_VBO, normals_VBO, UVs_VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &vertices_VBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, vertices_VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices.front(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(0);
glGenBuffers(1, &normals_VBO);
glBindBuffer(GL_ARRAY_BUFFER, normals_VBO);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals.front(), GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(1);
glGenBuffers(1, &UVs_VBO);
glBindBuffer(GL_ARRAY_BUFFER, UVs_VBO);
glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs.front(), GL_STATIC_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
GLuint projectionLoc = glGetUniformLocation(shaderProgram, "projection_matrix");
GLuint viewMatrixLoc = glGetUniformLocation(shaderProgram, "view_matrix");
GLuint transformLoc = glGetUniformLocation(shaderProgram, "model_matrix");
GLuint drawing_skybox_id = glGetUniformLocation(shaderProgram, "drawingSkybox");
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glActiveTexture(GL_TEXTURE0); //select texture unit 0
GLuint cube_texture;
glGenTextures(1, &cube_texture);
glBindTexture(GL_TEXTURE_2D, cube_texture); //bind this texture to the currently bound texture unit
// Set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
// Set texture wrapping to GL_REPEAT (usually basic wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Load image, create texture and generate mipmaps
int cube_texture_width, cube_texture_height;
unsigned char* cube_image = SOIL_load_image("window2.jpg", &cube_texture_width, &cube_texture_height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, cube_texture_width, cube_texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, cube_image);
SOIL_free_image_data(cube_image); //free resources
unsigned char* top_image = SOIL_load_image("grass.jpg", &cube_texture_width, &cube_texture_height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 10, GL_RGB, cube_texture_width, cube_texture_height, 10, GL_RGB, GL_UNSIGNED_BYTE, top_image);
SOIL_free_image_data(top_image); //free resources
//Setup our cubemap
vector<const GLchar*> faces;
faces.push_back("cube_map/a.jpg"); //right
faces.push_back("cube_map/c.jpg"); // left
faces.push_back("cube_map/top.jpg"); // top
faces.push_back("cube_map/bottom.jpg"); // bottom
faces.push_back("cube_map/b.jpg"); // back
faces.push_back("cube_map/d.jpg"); // front
glActiveTexture(GL_TEXTURE1);
GLuint cubemapTexture = loadCubemap(faces);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glUniform1i(glGetUniformLocation(shaderProgram, "cubeTexture"), 0); //cubeTexture should read from texture unit 0
glUniform1i(glGetUniformLocation(shaderProgram, "skybox"), 1); //sky box should read from texture unit 1
glUniform1i(glGetUniformLocation(shaderProgram, "grassTexture"), 10); //cubeTexture should read from texture unit 2
//create 10 buildings
for (int i = 0; i < 1000; i++) {
createBuilding();
createCoordinate();
cout << "Create buildings " << endl;
cout << "Map of Coordinate : " << vecMapCoordinate.size() << endl;
cout << "Number of build : " << vecBuildingSize.size() << endl;
if (i == 10) {
vecBuildingCoordinate.push_back(glm::vec3(0, -1, 0));
vecBuildingSize.push_back(glm::vec3(100, 0.5, 100));
}
}
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 model_matrix;
model_matrix = glm::rotate(model_matrix, y_rotation_angle, glm::vec3(0.0f, 1.0f, 0.0f));
model_matrix = glm::rotate(model_matrix, x_rotation_angle, glm::vec3(1.0f, 0.0f, 0.0f));
glm::mat4 view_matrix;
view_matrix = translate(view_matrix, camera_position);
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model_matrix)); // Model
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection_matrix)); // The pespective
glBindVertexArray(VAO);
//Draw the skybox
glm::mat4 skybox_view = glm::mat4(glm::mat3(view_matrix)); //remove the translation data
glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(skybox_view));
glDepthMask(GL_FALSE);
glUniform1i(drawing_skybox_id, 1); //set the uniform boolean
glDrawArrays(GL_TRIANGLES, 0, vertices.size());
glDepthMask(GL_TRUE);
//Draw the textured cube
// Plane and one block
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model_matrix));
glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(view_matrix));
glUniform1i(drawing_skybox_id, 0); //set the boolean
glDrawArrays(GL_TRIANGLES, 0, vertices.size());
//glBindVertexArray(VAO);
//cout << vecMapCoordinate.size() << endl;
glm::mat4 model_building;
for (GLuint i = 0; i < vecBuildingCoordinate.size(); i++) {
//cout << "im currentoy to draw " << vecBuildingCoordinate.size() << " cubes. " << endl;
model_matrix = glm::translate(model_matrix, vecBuildingCoordinate[i]);
model_matrix = glm::scale(model_matrix, vecBuildingSize[i]);
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model_matrix));
//glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(view_matrix));
// glUniform1i(drawing_skybox_id, 0); //set the boolean
glDrawArrays(GL_TRIANGLES, 0, vertices.size());
}
glBindVertexArray(0);
// Swap the screen buffers
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
/*
Method : CreateBuilding()
Return a random size of building
*/
glm::vec3 createBuilding() {
float width = randomFloat(1, 2); // x
float height = randomFloat(1,2); // y
float depth = randomFloat(1,2); // z
cout << "WIDTH = " << width << endl;
cout << "depth = " << depth << endl;
cout << "height = " << height << endl;
glm::vec3 sizeScale = glm::vec3(width, height, depth);
vecBuildingSize.push_back(sizeScale);
return sizeScale;
}
glm::vec3 createColor() {
float R = rand() % 4;
float G = rand() % 4;
float B = rand() % 4;
cout << "R = " << R << endl;
cout << "G = " << G << endl;
cout << "B = " << B << endl;
vecBuildingColor.push_back(glm::vec3(R, G, B));
glm::vec3 color = glm::vec3(R, G, B);
return color;
}
glm::vec3 createCoordinate() {
float coox = randomFloat(-50,50);
float cooz = randomFloat(-50, 50);
cout << "coox = " << coox << endl;
cout << "cooz = " << cooz << endl;
glm::vec3 coordinate = glm::vec3(coox, 0, cooz);
vecBuildingCoordinate.push_back(coordinate);
return coordinate;
}
float randomFloat(float a, float b) {
float random = ((float)rand()) / (float)RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}<commit_msg>Delete Lab7.cpp<commit_after><|endoftext|> |
<commit_before>#include <QGLWidget>
#include "Mesh.h"
#include "Matrix44.h"
#include "Common.h"
Mesh::Mesh() : triangleColouring(MESH_COLOUR_SAME), geomType(MESH_GEOM_TRIANGLES),
surfaceTexture(NULL), useSurfaceNormals(false)
{
}
Mesh::~Mesh()
{
}
const VertexList& Mesh::vertices() const
{
return verts;
}
void Mesh::setVertices(const VertexList& newVerts)
{
verts = newVerts;
}
const TriangleList& Mesh::triangles() const
{
return tris;
}
void Mesh::setTriangles(const TriangleList& newTris)
{
tris = newTris;
}
Mesh::Colouring Mesh::colouring() const
{
return triangleColouring;
}
void Mesh::setColouring(Mesh::Colouring newColouring)
{
triangleColouring = newColouring;
}
Mesh::GeometryType Mesh::geometryType() const
{
return geomType;
}
void Mesh::setGeometryType(Mesh::GeometryType newGeomType)
{
geomType = newGeomType;
}
bool Mesh::showingNormals() const
{
return drawNormals;
}
void Mesh::showNormals(bool willShow)
{
drawNormals = willShow;
}
Texture* Mesh::texture() const
{
return surfaceTexture;
}
void Mesh::setTexture(Texture* newTexture)
{
surfaceTexture = newTexture;
}
bool Mesh::usingPerFaceNormals() const
{
return useSurfaceNormals;
}
void Mesh::setPerFaceNormals(bool usePerFace)
{
useSurfaceNormals = usePerFace;
}
void Mesh::renderVertex(const Vertex& v)
{
glTexCoord2f(v.texCoord.s, v.texCoord.t);
glNormal3f(v.normal.x, v.normal.y, v.normal.z);
glVertex3f(v.position.x, v.position.y, v.position.y);
}
void Mesh::renderTriangle(const VertexList& verticesToUse, const Triangle& tri)
{
renderVertex( verticesToUse[tri.v1] );
renderVertex( verticesToUse[tri.v2] );
renderVertex( verticesToUse[tri.v3] );
}
void Mesh::renderPoints(const VertexList& vertices)
{
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_POINTS);
for (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)
glVertex3f(it->position.x, it->position.y, it->position.x);
glEnd();
}
void Mesh::renderLines(const VertexList& vertices, const TriangleList& triangles)
{
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINES);
for (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)
{
const Vertex& v1 = vertices[it->v1];
const Vertex& v2 = vertices[it->v2];
const Vertex& v3 = vertices[it->v3];
glVertex3f(v1.position.x, v1.position.y, v1.position.x);
glVertex3f(v2.position.x, v2.position.y, v2.position.x);
glVertex3f(v2.position.x, v2.position.y, v2.position.x);
glVertex3f(v3.position.x, v3.position.y, v3.position.x);
glVertex3f(v3.position.x, v3.position.y, v3.position.x);
glVertex3f(v1.position.x, v1.position.y, v1.position.x);
}
glEnd();
}
void Mesh::renderTriangles(const VertexList& vertices, const TriangleList& triangles)
{
glBegin(GL_TRIANGLES);
if (triangleColouring == MESH_ALTERNATING_TRIANGLES)
{
// Whole for-loop put it if-statement so there isn't a branch every iteration (costly operation
for (unsigned int i = 0; (i < triangles.size()); i++)
{
const Vector3& col = ALTERNATING_TRIANGLE_COLOURS[i % NUM_ALTERNATING_COLOURS];
glColor3f(col.x, col.y, col.y);
renderTriangle(vertices, tris[i]);
}
}
else
{
for (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)
renderTriangle(vertices, *it);
}
glEnd();
}
void Mesh::renderNormals(const VertexList& vertices)
{
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINES);
for (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)
{
const Vector3& position = it->position;
const Vector3& normal = it->normal;
Vector3 end = position + (normal * NORMAL_SCALING_FACTOR);
glVertex3f(it->position.x, it->position.y, it->position.z);
glVertex3f(end.x, end.y, end.y);
}
glEnd();
}
/* Draw a torus */
#include <math.h>
static void torus(int numc, int numt)
{
int i, j, k;
double s, t, x, y, z, twopi;
twopi = 2 * (double)M_PI;
for (i = 0; i < numc; i++) {
glBegin(GL_QUAD_STRIP);
for (j = 0; j <= numt; j++) {
for (k = 1; k >= 0; k--) {
s = (i + k) % numc + 0.5;
t = j % numt;
x = (1+.1*cos(s*twopi/numc))*cos(t*twopi/numt);
y = (1+.1*cos(s*twopi/numc))*sin(t*twopi/numt);
z = .1 * sin(s * twopi / numc);
const Vector3& col = ALTERNATING_TRIANGLE_COLOURS[(i * j) % NUM_ALTERNATING_COLOURS];
glColor3f(col.x, col.y, col.y);
glVertex3f(x, y, z);
}
}
glEnd();
}
}
void Mesh::render()
{
/*MatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glRotatef(rot.x, 1.0f, 0.0f, 0.0f);
glRotatef(rot.y, 0.0f, 1.0f, 0.0f);
glRotatef(rot.z, 0.0f, 0.0f, 1.0f);
torus(8, 8);
glPopMatrix();
return;*/
// If texturing has been enabled, ensure we set the correct OpenGL state
if (triangleColouring == MESH_TEXTURE)
{
// If texture hasn't been loaded yet - load it now!
// This is lazy initialisation
if (!surfaceTexture)
surfaceTexture = new Texture("resources/world_texture.jpg");
glEnable(GL_TEXTURE_2D);
surfaceTexture->bind();
}
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Perform local model transformations on mesh
Matrix44 transformation = Matrix44::translation(pos.x, pos.y, pos.z);
transformation = transformation * Matrix44::xyzRotation(rot);
// Transform vertices using position and orientation of drawable
VertexList transformedVerts = verts;
// If using per-face normals and not per-vertex normals, compute surface normals now
if (useSurfaceNormals)
{
Vector3List surfaceNormals = computeSurfaceNormals(transformedVerts, tris);
for (int i = 0; (i < surfaceNormals.size()); i++)
{
transformedVerts[i].normal = surfaceNormals[i];
}
}
for (VertexList::iterator it = transformedVerts.begin(); (it != transformedVerts.end()); it++)
{
it->position = transformation * it->position;
it->normal = (transformation * it->normal).normalise();
}
// How mesh is drawn depends on geometry type chosen
switch (geomType)
{
case MESH_GEOM_POINTS:
renderPoints(transformedVerts);
break;
case MESH_GEOM_LINES:
renderLines(transformedVerts, tris);
break;
case MESH_GEOM_TRIANGLES:
renderTriangles(transformedVerts, tris);
break;
}
// Also draw lines reprensenting vertex normals
if (drawNormals)
{
renderNormals(transformedVerts);
}
glPopMatrix();
// Make sure the mesh's texture is unbinded after rendering
if (triangleColouring == MESH_TEXTURE)
{
if (surfaceTexture)
surfaceTexture->unbind();
glDisable(GL_TEXTURE_2D);
}
}
Vector3List Mesh::computeSurfaceNormals(const VertexList& vertices, const TriangleList& triangles)
{
Vector3List normals;
normals.resize(vertices.size());
for (TriangleList::const_iterator it = triangles.begin();
(it != triangles.end()); it++)
{
// Get two points of the triangle and create two vectors from them (sides of triangle)
Vector3 s1 = vertices[it->v2].position - vertices[it->v1].position;
Vector3 s2 = vertices[it->v3].position - vertices[it->v1].position;
// Compute cross product of sides to get surface normal
Vector3 surfaceNormal = s1.cross(s2).negate().normalise();
// Assign this surface normal to all v
normals[it->v1] = surfaceNormal;
normals[it->v2] = surfaceNormal;
normals[it->v3] = surfaceNormal;
}
return normals;
}
<commit_msg>Fixsed freverse normals for flat shading sphere<commit_after>#include <QGLWidget>
#include "Mesh.h"
#include "Matrix44.h"
#include "Common.h"
Mesh::Mesh() : triangleColouring(MESH_COLOUR_SAME), geomType(MESH_GEOM_TRIANGLES),
surfaceTexture(NULL), useSurfaceNormals(false)
{
}
Mesh::~Mesh()
{
}
const VertexList& Mesh::vertices() const
{
return verts;
}
void Mesh::setVertices(const VertexList& newVerts)
{
verts = newVerts;
}
const TriangleList& Mesh::triangles() const
{
return tris;
}
void Mesh::setTriangles(const TriangleList& newTris)
{
tris = newTris;
}
Mesh::Colouring Mesh::colouring() const
{
return triangleColouring;
}
void Mesh::setColouring(Mesh::Colouring newColouring)
{
triangleColouring = newColouring;
}
Mesh::GeometryType Mesh::geometryType() const
{
return geomType;
}
void Mesh::setGeometryType(Mesh::GeometryType newGeomType)
{
geomType = newGeomType;
}
bool Mesh::showingNormals() const
{
return drawNormals;
}
void Mesh::showNormals(bool willShow)
{
drawNormals = willShow;
}
Texture* Mesh::texture() const
{
return surfaceTexture;
}
void Mesh::setTexture(Texture* newTexture)
{
surfaceTexture = newTexture;
}
bool Mesh::usingPerFaceNormals() const
{
return useSurfaceNormals;
}
void Mesh::setPerFaceNormals(bool usePerFace)
{
useSurfaceNormals = usePerFace;
}
void Mesh::renderVertex(const Vertex& v)
{
glTexCoord2f(v.texCoord.s, v.texCoord.t);
glNormal3f(v.normal.x, v.normal.y, v.normal.z);
glVertex3f(v.position.x, v.position.y, v.position.y);
}
void Mesh::renderTriangle(const VertexList& verticesToUse, const Triangle& tri)
{
renderVertex( verticesToUse[tri.v1] );
renderVertex( verticesToUse[tri.v2] );
renderVertex( verticesToUse[tri.v3] );
}
void Mesh::renderPoints(const VertexList& vertices)
{
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_POINTS);
for (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)
glVertex3f(it->position.x, it->position.y, it->position.x);
glEnd();
}
void Mesh::renderLines(const VertexList& vertices, const TriangleList& triangles)
{
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINES);
for (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)
{
const Vertex& v1 = vertices[it->v1];
const Vertex& v2 = vertices[it->v2];
const Vertex& v3 = vertices[it->v3];
glVertex3f(v1.position.x, v1.position.y, v1.position.x);
glVertex3f(v2.position.x, v2.position.y, v2.position.x);
glVertex3f(v2.position.x, v2.position.y, v2.position.x);
glVertex3f(v3.position.x, v3.position.y, v3.position.x);
glVertex3f(v3.position.x, v3.position.y, v3.position.x);
glVertex3f(v1.position.x, v1.position.y, v1.position.x);
}
glEnd();
}
void Mesh::renderTriangles(const VertexList& vertices, const TriangleList& triangles)
{
glBegin(GL_TRIANGLES);
if (triangleColouring == MESH_ALTERNATING_TRIANGLES)
{
// Whole for-loop put it if-statement so there isn't a branch every iteration (costly operation
for (unsigned int i = 0; (i < triangles.size()); i++)
{
const Vector3& col = ALTERNATING_TRIANGLE_COLOURS[i % NUM_ALTERNATING_COLOURS];
glColor3f(col.x, col.y, col.y);
renderTriangle(vertices, tris[i]);
}
}
else
{
for (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)
renderTriangle(vertices, *it);
}
glEnd();
}
void Mesh::renderNormals(const VertexList& vertices)
{
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINES);
for (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)
{
const Vector3& position = it->position;
const Vector3& normal = it->normal;
Vector3 end = position + (normal * NORMAL_SCALING_FACTOR);
glVertex3f(it->position.x, it->position.y, it->position.z);
glVertex3f(end.x, end.y, end.y);
}
glEnd();
}
/* Draw a torus */
#include <math.h>
static void torus(int numc, int numt)
{
int i, j, k;
double s, t, x, y, z, twopi;
twopi = 2 * (double)M_PI;
for (i = 0; i < numc; i++) {
glBegin(GL_QUAD_STRIP);
for (j = 0; j <= numt; j++) {
for (k = 1; k >= 0; k--) {
s = (i + k) % numc + 0.5;
t = j % numt;
x = (1+.1*cos(s*twopi/numc))*cos(t*twopi/numt);
y = (1+.1*cos(s*twopi/numc))*sin(t*twopi/numt);
z = .1 * sin(s * twopi / numc);
const Vector3& col = ALTERNATING_TRIANGLE_COLOURS[(i * j) % NUM_ALTERNATING_COLOURS];
glColor3f(col.x, col.y, col.y);
glVertex3f(x, y, z);
}
}
glEnd();
}
}
void Mesh::render()
{
/*MatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glRotatef(rot.x, 1.0f, 0.0f, 0.0f);
glRotatef(rot.y, 0.0f, 1.0f, 0.0f);
glRotatef(rot.z, 0.0f, 0.0f, 1.0f);
torus(8, 8);
glPopMatrix();
return;*/
// If texturing has been enabled, ensure we set the correct OpenGL state
if (triangleColouring == MESH_TEXTURE)
{
// If texture hasn't been loaded yet - load it now!
// This is lazy initialisation
if (!surfaceTexture)
surfaceTexture = new Texture("resources/world_texture.jpg");
glEnable(GL_TEXTURE_2D);
surfaceTexture->bind();
}
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Perform local model transformations on mesh
Matrix44 transformation = Matrix44::translation(pos.x, pos.y, pos.z);
transformation = transformation * Matrix44::xyzRotation(rot);
// Transform vertices using position and orientation of drawable
VertexList transformedVerts = verts;
// If using per-face normals and not per-vertex normals, compute surface normals now
if (useSurfaceNormals)
{
Vector3List surfaceNormals = computeSurfaceNormals(transformedVerts, tris);
for (int i = 0; (i < surfaceNormals.size()); i++)
{
transformedVerts[i].normal = surfaceNormals[i];
}
}
for (VertexList::iterator it = transformedVerts.begin(); (it != transformedVerts.end()); it++)
{
it->position = transformation * it->position;
it->normal = (transformation * it->normal).normalise();
}
// How mesh is drawn depends on geometry type chosen
switch (geomType)
{
case MESH_GEOM_POINTS:
renderPoints(transformedVerts);
break;
case MESH_GEOM_LINES:
renderLines(transformedVerts, tris);
break;
case MESH_GEOM_TRIANGLES:
renderTriangles(transformedVerts, tris);
break;
}
// Also draw lines reprensenting vertex normals
if (drawNormals)
{
renderNormals(transformedVerts);
}
glPopMatrix();
// Make sure the mesh's texture is unbinded after rendering
if (triangleColouring == MESH_TEXTURE)
{
if (surfaceTexture)
surfaceTexture->unbind();
glDisable(GL_TEXTURE_2D);
}
}
Vector3List Mesh::computeSurfaceNormals(const VertexList& vertices, const TriangleList& triangles)
{
Vector3List normals;
normals.resize(vertices.size());
for (TriangleList::const_iterator it = triangles.begin();
(it != triangles.end()); it++)
{
// Get two points of the triangle and create two vectors from them (sides of triangle)
Vector3 s1 = vertices[it->v2].position - vertices[it->v1].position;
Vector3 s2 = vertices[it->v3].position - vertices[it->v1].position;
// Compute cross product of sides to get surface normal
Vector3 surfaceNormal = s1.cross(s2).normalise();
// Assign this surface normal to all v
normals[it->v1] = surfaceNormal;
normals[it->v2] = surfaceNormal;
normals[it->v3] = surfaceNormal;
}
return normals;
}
<|endoftext|> |
<commit_before>#include "Arduino.h"
#include "Ndef.h"
//void Adafruit_NFCShield_I2C::PrintHex(const byte * data, const uint32_t numBytes)
void PrintHex(const byte * data, const uint32_t numBytes)
{
uint32_t szPos;
for (szPos=0; szPos < numBytes; szPos++)
{
Serial.print("0x");
// Append leading 0 for small values
if (data[szPos] <= 0xF)
Serial.print("0");
Serial.print(data[szPos]&0xff, HEX);
if ((numBytes > 1) && (szPos != numBytes - 1))
{
Serial.print(" ");
}
}
Serial.println("");
}
NdefRecord::NdefRecord()
{
_tnf = 0;
_typeLength = 0;
_payloadLength = 0;
_idLength = 0;
}
NdefRecord::NdefRecord(const NdefRecord& rhs)
{
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
_type = (uint8_t*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
_payload = (uint8_t*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
_id = (uint8_t*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
// TODO NdefRecord::NdefRecord(tnf, type, payload, id)
NdefRecord::~NdefRecord()
{
if (_typeLength)
{
free(_type);
}
if (_payloadLength)
{
free(_payload);
}
if (_idLength)
{
free(_id);
}
}
NdefRecord& NdefRecord::operator=(const NdefRecord& rhs)
{
if (this != &rhs)
{
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
// TODO need to free _type, _payload, and _id if they exist
_type = (uint8_t*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
_payload = (uint8_t*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
_id = (uint8_t*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
return *this;
}
// size of records in bytes
int NdefRecord::getEncodedSize()
{
int size = 2; // tnf + typeLength
if (_payloadLength > 0xFF)
{
size += 4;
}
else
{
size += 1;
}
if (_idLength)
{
size += 1;
}
size += (_typeLength + _payloadLength + _idLength);
return size;
}
void NdefRecord::encode(uint8_t* data, bool firstRecord, bool lastRecord)
{
// assert data > getEncodedSize()
uint8_t* data_ptr = &data[0];
*data_ptr = getTnfByte(firstRecord, lastRecord);
data_ptr += 1;
*data_ptr = _typeLength;
data_ptr += 1;
*data_ptr = _payloadLength; // TODO handle sr == false
data_ptr += 1;
if (_idLength)
{
*data_ptr = _idLength;
data_ptr += 1;
}
//Serial.println(2);
memcpy(data_ptr, _type, _typeLength);
data_ptr += _typeLength;
memcpy(data_ptr, _payload, _payloadLength);
data_ptr += _payloadLength;
if (_idLength)
{
memcpy(data_ptr, _id, _idLength);
data_ptr += _idLength;
}
}
uint8_t NdefRecord::getTnfByte(bool firstRecord, bool lastRecord)
{
int value = _tnf;
if (firstRecord) { // mb
value = value | 0x80;
}
if (lastRecord) { //
value = value | 0x40;
}
// chunked flag is always false for now
// if (cf) {
// value = value | 0x20;
// }
if (_typeLength <= 0xFF) { // TODO test 0xFF on tag
value = value | 0x10;
}
if (_idLength) {
value = value | 0x8;
}
return value;
}
uint8_t NdefRecord::getTnf()
{
return _tnf;
}
void NdefRecord::setTnf(uint8_t tnf)
{
_tnf = tnf;
}
uint8_t NdefRecord::getTypeLength()
{
return _typeLength;
}
int NdefRecord::getPayloadLength()
{
return _payloadLength;
}
uint8_t NdefRecord::getIdLength()
{
return _idLength;
}
// TODO don't return an array we created
// NdefRecord::getType(uint8_t * type) and copy into their array
// OR return an object that has the type and the array
uint8_t * NdefRecord::getType()
{
return _type;
}
void NdefRecord::setType(uint8_t * type, const int numBytes)
{
_type = (uint8_t*)malloc(numBytes);
memcpy(_type, type, numBytes);
_typeLength = numBytes;
}
uint8_t * NdefRecord::getPayload()
{
return _payload;
}
void NdefRecord::setPayload(uint8_t * payload, const int numBytes)
{
_payload = (uint8_t*)malloc(numBytes);
memcpy(_payload, payload, numBytes);
_payloadLength = numBytes;
}
uint8_t * NdefRecord::getId()
{
return _id;
}
void NdefRecord::setId(uint8_t * id, const int numBytes)
{
_id = (uint8_t*)malloc(numBytes);
memcpy(_id, id, numBytes);
_idLength = numBytes;
}
void NdefRecord::print()
{
Serial.println(" NDEF Record");
Serial.print(" TNF 0x");Serial.println(_tnf, HEX);
Serial.print(" Type Length 0x");Serial.println(_typeLength, HEX);
Serial.print(" Payload Length 0x");Serial.println(_payloadLength, HEX);
if (_idLength)
{
Serial.print(" Id Length 0x");Serial.println(_idLength, HEX);
}
Serial.print(" Type ");PrintHex(_type, _typeLength);
Serial.print(" Payload ");PrintHex(_payload, _payloadLength);
if (_idLength)
{
Serial.print(" Id ");PrintHex(_id, _idLength);
}
Serial.print(" Record is ");Serial.print(getEncodedSize());Serial.println(" bytes");
}
NdefMessage::NdefMessage(void)
{
_recordCount = 0;
}
NdefMessage::NdefMessage(byte * data, const int numBytes)
{
Serial.print("Decoding ");Serial.print(numBytes);Serial.println(" bytes");
PrintHex(data, numBytes);
// _records = (NdefRecord*)malloc(sizeof(NdefRecord *) * MAX_NDEF_RECORDS);
_recordCount = 0;
int index = 0;
while (index <= numBytes) {
// decode tnf - first byte is tnf with bit flags
// see the NFDEF spec for more info
byte tnf_byte = data[index];
bool mb = (tnf_byte & 0x80) != 0;
bool me = (tnf_byte & 0x40) != 0;
bool cf = (tnf_byte & 0x20) != 0;
bool sr = (tnf_byte & 0x10) != 0;
bool il = (tnf_byte & 0x8) != 0;
byte tnf = (tnf_byte & 0x7);
NdefRecord record = NdefRecord();
record.setTnf(tnf);
index++;
int typeLength = data[index];
int payloadLength = 0;
if (sr)
{
index++;
payloadLength = data[index];
}
else
{
payloadLength = ((0xFF & data[++index]) << 24) | ((0xFF & data[++index]) << 26) |
((0xFF & data[++index]) << 8) | (0xFF & data[++index]);
}
int idLength = 0;
if (il)
{
index++;
idLength = data[index];
}
index++;
record.setType(&data[index], typeLength);
index += typeLength;
if (il)
{
record.setId(&data[index], idLength);
index += idLength;
}
record.setPayload(&data[index], payloadLength);
index += payloadLength;
add(record);
if (me) break; // last message
}
}
NdefMessage::~NdefMessage()
{
//free(_records);
}
int NdefMessage::recordCount()
{
return _recordCount;
}
int NdefMessage::getEncodedSize()
{
int size = 0;
int i;
for (i = 0; i < _recordCount; i++)
{
size += _records[i].getEncodedSize();
}
return size;
}
void NdefMessage::encode(uint8_t* data)
{
// assert sizeof(data) >= getEncodedSize()
uint8_t* data_ptr = &data[0];
int i;
for (i = 0; i < _recordCount; i++)
{
_records[i].encode(data_ptr, i == 0, (i + 1) == _recordCount);
// TODO can NdefRecord.encode return the record size?
data_ptr += _records[i].getEncodedSize();
}
// TODO don't print here
Serial.println("\nEncoded");
PrintHex(data, getEncodedSize());
}
void NdefMessage::add(NdefRecord record)
{
if (_recordCount < MAX_NDEF_RECORDS)
{
_records[_recordCount] = record;
_recordCount++;
}
else
{
// TODO consider returning status
Serial.println("WARNING: Too many records. Increase MAX_NDEF_RECORDS.");
}
}
// TODO would NdefRecord::mimeMediaRecord be better?
void NdefMessage::addMimeMediaRecord(String mimeType, String payload)
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_MIME_MEDIA);
byte type[mimeType.length() + 1];
mimeType.getBytes(type, sizeof(type));
r->setType(type, mimeType.length());
byte payloadBytes[payload.length() + 1];
payload.getBytes(payloadBytes, sizeof(payloadBytes));
r->setPayload(payloadBytes, payload.length());
add(*r);
/*
TODO call other method
byte payloadBytes[payload.length() + 1];
payload.getBytes(payloadBytes, sizeof(payloadBytes));
addMimeMediaRecord(mimeType, payloadBytes, payload.length);
*/
}
void NdefMessage::addMimeMediaRecord(String mimeType, uint8_t* payload, int payloadLength)
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_MIME_MEDIA);
byte type[mimeType.length() + 1];
mimeType.getBytes(type, sizeof(type));
r->setType(type, mimeType.length());
r->setPayload(payload, payloadLength);
add(*r);
}
void NdefMessage::addTextRecord(String text)
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_WELL_KNOWN);
uint8_t RTD_TEXT[1] = { 0x54 }; // TODO this should be a constant or preprocessor
r->setType(RTD_TEXT, sizeof(RTD_TEXT));
// TODO language encoding
byte payload[text.length() + 1];
text.getBytes(payload, sizeof(payload));
r->setPayload(payload, text.length());
add(*r);
}
void NdefMessage::addTextRecord(String text, String encoding)
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_WELL_KNOWN);
uint8_t RTD_TEXT[1] = { 0x54 }; // TODO this should be a constant or preprocessor
r->setType(RTD_TEXT, sizeof(RTD_TEXT));
// X is a placeholder for encoding length
String payloadString = "X" + encoding + text;
byte payload[payloadString.length() + 1];
payloadString.getBytes(payload, sizeof(payload));
// replace X with the real length
payload[0] = encoding.length();
r->setPayload(payload, payloadString.length());
add(*r);
}
void NdefMessage::addUriRecord(String uri)
{
}
void NdefMessage::addEmptyRecord()
{
}
NdefRecord NdefMessage::get(int index)
{
if (index > -1 && index < _recordCount)
{
return _records[_recordCount];
}
}
void NdefMessage::print()
{
Serial.print("\nNDEF Message ");Serial.print(_recordCount);Serial.print(" record");
_recordCount == 1 ? Serial.print(", ") : Serial.print("s, ");
Serial.print(getEncodedSize());Serial.println(" bytes");
int i;
for (i = 0; i < _recordCount; i++)
{
_records[i].print();
}
}
<commit_msg>combine implementation of addTextRecord<commit_after>#include "Arduino.h"
#include "Ndef.h"
//void Adafruit_NFCShield_I2C::PrintHex(const byte * data, const uint32_t numBytes)
void PrintHex(const byte * data, const uint32_t numBytes)
{
uint32_t szPos;
for (szPos=0; szPos < numBytes; szPos++)
{
Serial.print("0x");
// Append leading 0 for small values
if (data[szPos] <= 0xF)
Serial.print("0");
Serial.print(data[szPos]&0xff, HEX);
if ((numBytes > 1) && (szPos != numBytes - 1))
{
Serial.print(" ");
}
}
Serial.println("");
}
NdefRecord::NdefRecord()
{
_tnf = 0;
_typeLength = 0;
_payloadLength = 0;
_idLength = 0;
}
NdefRecord::NdefRecord(const NdefRecord& rhs)
{
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
_type = (uint8_t*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
_payload = (uint8_t*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
_id = (uint8_t*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
// TODO NdefRecord::NdefRecord(tnf, type, payload, id)
NdefRecord::~NdefRecord()
{
if (_typeLength)
{
free(_type);
}
if (_payloadLength)
{
free(_payload);
}
if (_idLength)
{
free(_id);
}
}
NdefRecord& NdefRecord::operator=(const NdefRecord& rhs)
{
if (this != &rhs)
{
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
// TODO need to free _type, _payload, and _id if they exist
_type = (uint8_t*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
_payload = (uint8_t*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
_id = (uint8_t*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
return *this;
}
// size of records in bytes
int NdefRecord::getEncodedSize()
{
int size = 2; // tnf + typeLength
if (_payloadLength > 0xFF)
{
size += 4;
}
else
{
size += 1;
}
if (_idLength)
{
size += 1;
}
size += (_typeLength + _payloadLength + _idLength);
return size;
}
void NdefRecord::encode(uint8_t* data, bool firstRecord, bool lastRecord)
{
// assert data > getEncodedSize()
uint8_t* data_ptr = &data[0];
*data_ptr = getTnfByte(firstRecord, lastRecord);
data_ptr += 1;
*data_ptr = _typeLength;
data_ptr += 1;
*data_ptr = _payloadLength; // TODO handle sr == false
data_ptr += 1;
if (_idLength)
{
*data_ptr = _idLength;
data_ptr += 1;
}
//Serial.println(2);
memcpy(data_ptr, _type, _typeLength);
data_ptr += _typeLength;
memcpy(data_ptr, _payload, _payloadLength);
data_ptr += _payloadLength;
if (_idLength)
{
memcpy(data_ptr, _id, _idLength);
data_ptr += _idLength;
}
}
uint8_t NdefRecord::getTnfByte(bool firstRecord, bool lastRecord)
{
int value = _tnf;
if (firstRecord) { // mb
value = value | 0x80;
}
if (lastRecord) { //
value = value | 0x40;
}
// chunked flag is always false for now
// if (cf) {
// value = value | 0x20;
// }
if (_typeLength <= 0xFF) { // TODO test 0xFF on tag
value = value | 0x10;
}
if (_idLength) {
value = value | 0x8;
}
return value;
}
uint8_t NdefRecord::getTnf()
{
return _tnf;
}
void NdefRecord::setTnf(uint8_t tnf)
{
_tnf = tnf;
}
uint8_t NdefRecord::getTypeLength()
{
return _typeLength;
}
int NdefRecord::getPayloadLength()
{
return _payloadLength;
}
uint8_t NdefRecord::getIdLength()
{
return _idLength;
}
// TODO don't return an array we created
// NdefRecord::getType(uint8_t * type) and copy into their array
// OR return an object that has the type and the array
uint8_t * NdefRecord::getType()
{
return _type;
}
void NdefRecord::setType(uint8_t * type, const int numBytes)
{
_type = (uint8_t*)malloc(numBytes);
memcpy(_type, type, numBytes);
_typeLength = numBytes;
}
uint8_t * NdefRecord::getPayload()
{
return _payload;
}
void NdefRecord::setPayload(uint8_t * payload, const int numBytes)
{
_payload = (uint8_t*)malloc(numBytes);
memcpy(_payload, payload, numBytes);
_payloadLength = numBytes;
}
uint8_t * NdefRecord::getId()
{
return _id;
}
void NdefRecord::setId(uint8_t * id, const int numBytes)
{
_id = (uint8_t*)malloc(numBytes);
memcpy(_id, id, numBytes);
_idLength = numBytes;
}
void NdefRecord::print()
{
Serial.println(" NDEF Record");
Serial.print(" TNF 0x");Serial.println(_tnf, HEX);
Serial.print(" Type Length 0x");Serial.println(_typeLength, HEX);
Serial.print(" Payload Length 0x");Serial.println(_payloadLength, HEX);
if (_idLength)
{
Serial.print(" Id Length 0x");Serial.println(_idLength, HEX);
}
Serial.print(" Type ");PrintHex(_type, _typeLength);
Serial.print(" Payload ");PrintHex(_payload, _payloadLength);
if (_idLength)
{
Serial.print(" Id ");PrintHex(_id, _idLength);
}
Serial.print(" Record is ");Serial.print(getEncodedSize());Serial.println(" bytes");
}
NdefMessage::NdefMessage(void)
{
_recordCount = 0;
}
NdefMessage::NdefMessage(byte * data, const int numBytes)
{
Serial.print("Decoding ");Serial.print(numBytes);Serial.println(" bytes");
PrintHex(data, numBytes);
// _records = (NdefRecord*)malloc(sizeof(NdefRecord *) * MAX_NDEF_RECORDS);
_recordCount = 0;
int index = 0;
while (index <= numBytes) {
// decode tnf - first byte is tnf with bit flags
// see the NFDEF spec for more info
byte tnf_byte = data[index];
bool mb = (tnf_byte & 0x80) != 0;
bool me = (tnf_byte & 0x40) != 0;
bool cf = (tnf_byte & 0x20) != 0;
bool sr = (tnf_byte & 0x10) != 0;
bool il = (tnf_byte & 0x8) != 0;
byte tnf = (tnf_byte & 0x7);
NdefRecord record = NdefRecord();
record.setTnf(tnf);
index++;
int typeLength = data[index];
int payloadLength = 0;
if (sr)
{
index++;
payloadLength = data[index];
}
else
{
payloadLength = ((0xFF & data[++index]) << 24) | ((0xFF & data[++index]) << 26) |
((0xFF & data[++index]) << 8) | (0xFF & data[++index]);
}
int idLength = 0;
if (il)
{
index++;
idLength = data[index];
}
index++;
record.setType(&data[index], typeLength);
index += typeLength;
if (il)
{
record.setId(&data[index], idLength);
index += idLength;
}
record.setPayload(&data[index], payloadLength);
index += payloadLength;
add(record);
if (me) break; // last message
}
}
NdefMessage::~NdefMessage()
{
//free(_records);
}
int NdefMessage::recordCount()
{
return _recordCount;
}
int NdefMessage::getEncodedSize()
{
int size = 0;
int i;
for (i = 0; i < _recordCount; i++)
{
size += _records[i].getEncodedSize();
}
return size;
}
void NdefMessage::encode(uint8_t* data)
{
// assert sizeof(data) >= getEncodedSize()
uint8_t* data_ptr = &data[0];
int i;
for (i = 0; i < _recordCount; i++)
{
_records[i].encode(data_ptr, i == 0, (i + 1) == _recordCount);
// TODO can NdefRecord.encode return the record size?
data_ptr += _records[i].getEncodedSize();
}
// TODO don't print here
Serial.println("\nEncoded");
PrintHex(data, getEncodedSize());
}
void NdefMessage::add(NdefRecord record)
{
if (_recordCount < MAX_NDEF_RECORDS)
{
_records[_recordCount] = record;
_recordCount++;
}
else
{
// TODO consider returning status
Serial.println("WARNING: Too many records. Increase MAX_NDEF_RECORDS.");
}
}
// TODO would NdefRecord::mimeMediaRecord be better?
void NdefMessage::addMimeMediaRecord(String mimeType, String payload)
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_MIME_MEDIA);
byte type[mimeType.length() + 1];
mimeType.getBytes(type, sizeof(type));
r->setType(type, mimeType.length());
byte payloadBytes[payload.length() + 1];
payload.getBytes(payloadBytes, sizeof(payloadBytes));
r->setPayload(payloadBytes, payload.length());
add(*r);
/*
TODO call other method
byte payloadBytes[payload.length() + 1];
payload.getBytes(payloadBytes, sizeof(payloadBytes));
addMimeMediaRecord(mimeType, payloadBytes, payload.length);
*/
}
void NdefMessage::addMimeMediaRecord(String mimeType, uint8_t* payload, int payloadLength)
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_MIME_MEDIA);
byte type[mimeType.length() + 1];
mimeType.getBytes(type, sizeof(type));
r->setType(type, mimeType.length());
r->setPayload(payload, payloadLength);
add(*r);
}
void NdefMessage::addTextRecord(String text)
{
addTextRecord(text, "en");
}
void NdefMessage::addTextRecord(String text, String encoding)
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_WELL_KNOWN);
uint8_t RTD_TEXT[1] = { 0x54 }; // TODO this should be a constant or preprocessor
r->setType(RTD_TEXT, sizeof(RTD_TEXT));
// X is a placeholder for encoding length
String payloadString = "X" + encoding + text;
byte payload[payloadString.length() + 1];
payloadString.getBytes(payload, sizeof(payload));
// replace X with the real length
payload[0] = encoding.length();
r->setPayload(payload, payloadString.length());
add(*r);
}
void NdefMessage::addUriRecord(String uri)
{
}
void NdefMessage::addEmptyRecord()
{
}
NdefRecord NdefMessage::get(int index)
{
if (index > -1 && index < _recordCount)
{
return _records[_recordCount];
}
}
void NdefMessage::print()
{
Serial.print("\nNDEF Message ");Serial.print(_recordCount);Serial.print(" record");
_recordCount == 1 ? Serial.print(", ") : Serial.print("s, ");
Serial.print(getEncodedSize());Serial.println(" bytes");
int i;
for (i = 0; i < _recordCount; i++)
{
_records[i].print();
}
}
<|endoftext|> |
<commit_before>#include <string.h>
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#include <ctime>
#include <assert.h>
#define pi 3.14159
#define mod 1000000007
using namespace std;
long long int a[500000];
int main()
{
long long int t,flag=0,value=0;
cin>>t;
while(t--)
{
int a,b;
cin>>a>>b;
flag = flag + b -a;
if(value < flag)
{
value = flag;
}
}
cout<<value;
return 0;
}
<commit_msg>Delete Tram.cpp<commit_after><|endoftext|> |
<commit_before>#include <nan.h>
#include "addon.h"
#include "dvbtee-parser.h"
void libVersion(const Nan::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Array> version = Nan::New<v8::Array>();
version->Set(0, Nan::New<v8::Number>(LIBDVBTEE_VERSION_A) );
version->Set(1, Nan::New<v8::Number>(LIBDVBTEE_VERSION_B) );
version->Set(2, Nan::New<v8::Number>(LIBDVBTEE_VERSION_C) );
info.GetReturnValue().Set(version);
}
void logLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) {
libdvbtee_set_debug_level((info[0]->IsNumber()) ? info[0]->Uint32Value() : 255,
(info[1]->IsNumber()) ? info[1]->Uint32Value() : 0);
info.GetReturnValue().Set(info.Holder());
}
NAN_MODULE_INIT(InitAll) {
Nan::Set(target, Nan::New<v8::String>("logLevel").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(logLevel)).ToLocalChecked());
Nan::Set(target, Nan::New<v8::String>("libVersion").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(libVersion)).ToLocalChecked());
dvbteeParser::Init(target);
}
NODE_MODULE(dvbtee, InitAll)
<commit_msg>addon: add functions getTableDecoderIds & getDescriptorDecoderIds<commit_after>#include <nan.h>
#include "addon.h"
#include "dvbtee-parser.h"
void libVersion(const Nan::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Array> version = Nan::New<v8::Array>();
version->Set(0, Nan::New<v8::Number>(LIBDVBTEE_VERSION_A) );
version->Set(1, Nan::New<v8::Number>(LIBDVBTEE_VERSION_B) );
version->Set(2, Nan::New<v8::Number>(LIBDVBTEE_VERSION_C) );
info.GetReturnValue().Set(version);
}
void logLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) {
libdvbtee_set_debug_level((info[0]->IsNumber()) ? info[0]->Uint32Value() : 255,
(info[1]->IsNumber()) ? info[1]->Uint32Value() : 0);
info.GetReturnValue().Set(info.Holder());
}
template<typename T> v8::Local<v8::Array> vectorToV8Array(std::vector<T> v) {
v8::Local<v8::Array> a = Nan::New<v8::Array>();
unsigned int pos = 0;
for (typename std::vector<T>::const_iterator it = v.begin(); it != v.end(); ++it)
a->Set(pos++, Nan::New(*it) );
return a;
}
void getTableDecoderIds(const Nan::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(vectorToV8Array(dvbtee::decode::TableRegistry::instance().list()));
}
void getDescriptorDecoderIds(const Nan::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(vectorToV8Array(dvbtee::decode::DescriptorRegistry::instance().list()));
}
NAN_MODULE_INIT(InitAll) {
Nan::Set(target, Nan::New<v8::String>("logLevel").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(logLevel)).ToLocalChecked());
Nan::Set(target, Nan::New<v8::String>("libVersion").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(libVersion)).ToLocalChecked());
Nan::Set(target, Nan::New<v8::String>("getTableDecoderIds").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(getTableDecoderIds)).ToLocalChecked());
Nan::Set(target, Nan::New<v8::String>("getDescriptorDecoderIds").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(getDescriptorDecoderIds)).ToLocalChecked());
dvbteeParser::Init(target);
}
NODE_MODULE(dvbtee, InitAll)
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <fstream>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <stack>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
// uncomment to enable debugging:
//#define CDEBUG 1
//#define EDEBUG 1
// util for debug
#ifdef CDEBUG
#define LOGnl(m,x,y,z,a) log_message(m,x,y,z,a,"\n")
#define LOG(m,x,y,z,a) log_message(m,x,y,z,a,"")
#else
#define LOGnl(m,x,y,z,a)
#define LOG(m,x,y,z,a)
#endif
#ifdef EDEBUG
#define LOGE(m,x,y,z,a) log_message(m,x,y,z,a,"\n")
#else
#define LOGE(m,x,y,z,a)
#endif
inline void log_message(std::string m, double x, double y, double z, double a, std::string e) {
std::cerr << m << "," << x << "," << y << "," << z << "," << a << e;
}
struct trEntry {
const uint64_t id;
const uint64_t size;
double pval;
size_t nextSeen;
bool inSchedule;
bool hasNext;
trEntry(uint64_t nid, uint64_t nsize)
: id(nid),
size(nsize)
{
pval = 1;
nextSeen = 0;
inSchedule = false;
hasNext = false;
};
};
int main(int argc, char* argv[]) {
// parameters
std::string path(argv[1]);
uint64_t cacheSize(atoll(argv[2]));
// each interval is represented by the index of the trace, where it started
// store trace here
std::vector<trEntry> trace;
// store lastSeen entries here
std::map<std::pair<uint64_t, uint64_t>, size_t> lastSeen;
// store which intervals are in the schedule
std::unordered_set< size_t > scheduleSet;
// open trace file
std::ifstream traceFile(path);
uint64_t time, id, size, reqc=0;
// scan trace and initialize data structures
while(traceFile >> time >> id >> size) {
// only consider objects that are requested at least once (ignore last request, because doesn't make sense to cache that one)
if(lastSeen.count(std::make_pair(id,size))>0) {
// see object second time: add to schedule and initialize datastructures
// find trace index where this interval started
const size_t indexLastSeen = lastSeen[std::make_pair(id,size)];
// add to schedule the start index of this interval
// TODO MIGHT NOT NEED THIS
scheduleSet.insert(indexLastSeen);
trEntry & lastSeenEntry = trace[indexLastSeen];
// update trace so that we know this interval has finite length
lastSeenEntry.hasNext = true;
// update trace so that we know the end time of this interval
lastSeenEntry.nextSeen = reqc;
// update trace: this interval is in schedule
lastSeenEntry.inSchedule = true;
}
// store: id, size, bool seen before, pvalue, start of this interval (if started)
trace.emplace_back(id,size);
lastSeen[std::make_pair(id,size)]=reqc++;
}
// free memory
lastSeen.clear();
std::cerr << "parsed trace\n";
// DEBUG print trace
#ifdef CDEBUG
reqc = 0;
LOGnl("TRACE",0,0,0,0);
for(auto & curEntry : trace) {
LOGnl(" ",curEntry.id,curEntry.size,0,curEntry.nextSeen);
}
#endif
// END DEBUG
// create feasible schedule by excluding worst feasibility violations
// i.e., select largest delta in every iteration
// store excluded intervals in a stack for later
std::stack<size_t> excluded;
// delta data structures
int64_t curDelta;
int64_t deltaStar;
size_t timeStar;
// map: intersecting interval set
std::map<std::pair<uint64_t, uint64_t>, size_t> curI; //intersecting intervals at current time
std::map<std::pair<uint64_t, uint64_t>, size_t> maxI; // intersectin intervals at timeStar
// iterate (every iteration removes one interval, so max iteration count = trace size)
for(size_t i=0; i<trace.size(); i++) {
// find highest delta
reqc = 0;
// iterate over all time instances (we can skip the last one)
maxI.clear();
curDelta = -cacheSize;
deltaStar = -cacheSize;
timeStar = 0;
for(size_t j=0; j<trace.size(); j++) {
trEntry & curEntry = trace[j];
// if no next request and in intersecting intervals -> remove
if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {
curI.erase(std::make_pair(curEntry.id,curEntry.size));
curDelta -= curEntry.size;
assert(!curEntry.inSchedule);
}
// if in schedule -> update curI
if(curEntry.inSchedule) {
// if not already in current intersecting set
if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {
curDelta += curEntry.size;
} // else: don't need update the size/width
// add to current intersecting set
curI[std::make_pair(curEntry.id,curEntry.size)] = j;
// check if we need to update deltaStar
if(curDelta > deltaStar) {
deltaStar = curDelta;
timeStar = j;
// copy intersecting set
maxI = curI;
}
}
#ifdef CDEBUG
for(auto it: curI) {
trEntry & curEntry = trace[it.second];
LOG("|",curEntry.id,curEntry.size,0,0);
}
LOGnl("| TW ",curDelta,j,deltaStar,timeStar);
#endif
}
// check if we found a feasible solution
if(deltaStar <= 0)
break;
curI.clear();
assert(maxI.size()>0);
assert(deltaStar > 0);
assert(timeStar > 0); // first time interval can't be the unstable one
LOGnl("\nd*,t*",deltaStar,timeStar,0,0);
std::cout << "d*" << deltaStar << " t* " << timeStar << "\n";
// find smallest rho so that p2 reaches zero
double rho = 1;
size_t toExclude = 0;
for(auto & vit : maxI) {
trEntry & curEntry = trace[vit.second];
const double thisRho = curEntry.pval/static_cast<double>(curEntry.size);
if(thisRho <= rho) {
rho = thisRho;
toExclude = vit.second;
LOGE("mrho",rho,vit.second,curEntry.pval,curEntry.size);
}
}
assert(rho < 1);
LOGnl("min rho ",rho,0,0,0);
// std::cout << " mrho " << rho << "\n";
// update p2, exclude intervals with p2=0 from schedule
for(auto & vit : maxI) {
trEntry & curEntry = trace[vit.second];
// if (min-rho-entry or p2==0): we need the first check due to double rounding errors
if(vit.second==toExclude || curEntry.pval <= rho * curEntry.size ) {
LOGnl("exclude (t,id,size,p2)",vit.second,id,curEntry.size,curEntry.pval - rho*curEntry.size);
curEntry.pval = 0;
curEntry.inSchedule = false;
// add current interval to excluded ones
excluded.push(vit.second);
// delete from current schedule
scheduleSet.erase(vit.second);
} else {
// p2 >= 0
curEntry.pval -= curEntry.size <= deltaStar ? rho * curEntry.size : rho * deltaStar; // pval = pval - p1
}
}
}
maxI.clear();
std::cerr << "found feasible schedule\n";
std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n";
// we now have a feasible schedule, which might not be maximal
while (!excluded.empty())
{
const size_t firstSeen = excluded.top();
trEntry & newEntry = trace[excluded.top()];
curI.clear();
curDelta = -cacheSize;
deltaStar = -cacheSize;
for(size_t j=0; j<trace.size(); j++) {
trEntry & curEntry = trace[j];
// if no next request and in intersecting intervals -> remove
if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {
curI.erase(std::make_pair(curEntry.id,curEntry.size));
curDelta -= curEntry.size;
assert(!curEntry.inSchedule);
}
// if in schedule -> update curI
if(j==excluded.top() || curEntry.inSchedule) {
// if not already in current intersecting set
if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {
curDelta += curEntry.size;
} // else: don't need update the size/width
// add to current intersecting set
curI[std::make_pair(curEntry.id,curEntry.size)] = j;
// check if we need to update deltaStar
if(curDelta > deltaStar) {
deltaStar = curDelta;
}
}
}
// if still feasible add excluded.top() to schedule
if(deltaStar <=0) {
newEntry.inSchedule = true;
scheduleSet.insert(excluded.top());
}
// pop stack
excluded.pop();
}
std::cerr << "found maximal schedule\n";
std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n";
return 0;
}
<commit_msg>less cout output<commit_after>#include <cassert>
#include <iostream>
#include <fstream>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <stack>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
// uncomment to enable debugging:
//#define CDEBUG 1
//#define EDEBUG 1
// util for debug
#ifdef CDEBUG
#define LOGnl(m,x,y,z,a) log_message(m,x,y,z,a,"\n")
#define LOG(m,x,y,z,a) log_message(m,x,y,z,a,"")
#else
#define LOGnl(m,x,y,z,a)
#define LOG(m,x,y,z,a)
#endif
#ifdef EDEBUG
#define LOGE(m,x,y,z,a) log_message(m,x,y,z,a,"\n")
#else
#define LOGE(m,x,y,z,a)
#endif
inline void log_message(std::string m, double x, double y, double z, double a, std::string e) {
std::cerr << m << "," << x << "," << y << "," << z << "," << a << e;
}
struct trEntry {
const uint64_t id;
const uint64_t size;
double pval;
size_t nextSeen;
bool inSchedule;
bool hasNext;
trEntry(uint64_t nid, uint64_t nsize)
: id(nid),
size(nsize)
{
pval = 1;
nextSeen = 0;
inSchedule = false;
hasNext = false;
};
};
int main(int argc, char* argv[]) {
// parameters
std::string path(argv[1]);
uint64_t cacheSize(atoll(argv[2]));
// each interval is represented by the index of the trace, where it started
// store trace here
std::vector<trEntry> trace;
// store lastSeen entries here
std::map<std::pair<uint64_t, uint64_t>, size_t> lastSeen;
// store which intervals are in the schedule
std::unordered_set< size_t > scheduleSet;
// open trace file
std::ifstream traceFile(path);
uint64_t time, id, size, reqc=0;
// scan trace and initialize data structures
while(traceFile >> time >> id >> size) {
// only consider objects that are requested at least once (ignore last request, because doesn't make sense to cache that one)
if(lastSeen.count(std::make_pair(id,size))>0) {
// see object second time: add to schedule and initialize datastructures
// find trace index where this interval started
const size_t indexLastSeen = lastSeen[std::make_pair(id,size)];
// add to schedule the start index of this interval
// TODO MIGHT NOT NEED THIS
scheduleSet.insert(indexLastSeen);
trEntry & lastSeenEntry = trace[indexLastSeen];
// update trace so that we know this interval has finite length
lastSeenEntry.hasNext = true;
// update trace so that we know the end time of this interval
lastSeenEntry.nextSeen = reqc;
// update trace: this interval is in schedule
lastSeenEntry.inSchedule = true;
}
// store: id, size, bool seen before, pvalue, start of this interval (if started)
trace.emplace_back(id,size);
lastSeen[std::make_pair(id,size)]=reqc++;
}
// free memory
lastSeen.clear();
std::cerr << "parsed trace\n";
// DEBUG print trace
#ifdef CDEBUG
reqc = 0;
LOGnl("TRACE",0,0,0,0);
for(auto & curEntry : trace) {
LOGnl(" ",curEntry.id,curEntry.size,0,curEntry.nextSeen);
}
#endif
// END DEBUG
// create feasible schedule by excluding worst feasibility violations
// i.e., select largest delta in every iteration
// store excluded intervals in a stack for later
std::stack<size_t> excluded;
// delta data structures
int64_t curDelta;
int64_t deltaStar;
size_t timeStar;
// map: intersecting interval set
std::map<std::pair<uint64_t, uint64_t>, size_t> curI; //intersecting intervals at current time
std::map<std::pair<uint64_t, uint64_t>, size_t> maxI; // intersectin intervals at timeStar
// iterate (every iteration removes one interval, so max iteration count = trace size)
for(size_t i=0; i<trace.size(); i++) {
// find highest delta
reqc = 0;
// iterate over all time instances (we can skip the last one)
maxI.clear();
curDelta = -cacheSize;
deltaStar = -cacheSize;
timeStar = 0;
for(size_t j=0; j<trace.size(); j++) {
trEntry & curEntry = trace[j];
// if no next request and in intersecting intervals -> remove
if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {
curI.erase(std::make_pair(curEntry.id,curEntry.size));
curDelta -= curEntry.size;
assert(!curEntry.inSchedule);
}
// if in schedule -> update curI
if(curEntry.inSchedule) {
// if not already in current intersecting set
if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {
curDelta += curEntry.size;
} // else: don't need update the size/width
// add to current intersecting set
curI[std::make_pair(curEntry.id,curEntry.size)] = j;
// check if we need to update deltaStar
if(curDelta > deltaStar) {
deltaStar = curDelta;
timeStar = j;
// copy intersecting set
maxI = curI;
}
}
#ifdef CDEBUG
for(auto it: curI) {
trEntry & curEntry = trace[it.second];
LOG("|",curEntry.id,curEntry.size,0,0);
}
LOGnl("| TW ",curDelta,j,deltaStar,timeStar);
#endif
}
// check if we found a feasible solution
if(deltaStar <= 0)
break;
curI.clear();
assert(maxI.size()>0);
assert(deltaStar > 0);
assert(timeStar > 0); // first time interval can't be the unstable one
LOGnl("\nd*,t*",deltaStar,timeStar,0,0);
// find smallest rho so that p2 reaches zero
double rho = 1;
size_t toExclude = 0;
for(auto & vit : maxI) {
trEntry & curEntry = trace[vit.second];
const double thisRho = curEntry.pval/static_cast<double>(curEntry.size);
if(thisRho <= rho) {
rho = thisRho;
toExclude = vit.second;
LOGE("mrho",rho,vit.second,curEntry.pval,curEntry.size);
}
}
assert(rho < 1);
LOGnl("min rho ",rho,0,0,0);
// update p2, exclude intervals with p2=0 from schedule
for(auto & vit : maxI) {
trEntry & curEntry = trace[vit.second];
// if (min-rho-entry or p2==0): we need the first check due to double rounding errors
if(vit.second==toExclude || curEntry.pval <= rho * curEntry.size ) {
LOGnl("exclude (t,id,size,p2)",vit.second,id,curEntry.size,curEntry.pval - rho*curEntry.size);
curEntry.pval = 0;
curEntry.inSchedule = false;
// add current interval to excluded ones
excluded.push(vit.second);
// delete from current schedule
scheduleSet.erase(vit.second);
} else {
// p2 >= 0
curEntry.pval -= curEntry.size <= deltaStar ? rho * curEntry.size : rho * deltaStar; // pval = pval - p1
}
}
}
maxI.clear();
std::cerr << "found feasible schedule\n";
std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n";
// we now have a feasible schedule, which might not be maximal
while (!excluded.empty())
{
const size_t firstSeen = excluded.top();
trEntry & newEntry = trace[excluded.top()];
curI.clear();
curDelta = -cacheSize;
deltaStar = -cacheSize;
for(size_t j=0; j<trace.size(); j++) {
trEntry & curEntry = trace[j];
// if no next request and in intersecting intervals -> remove
if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {
curI.erase(std::make_pair(curEntry.id,curEntry.size));
curDelta -= curEntry.size;
assert(!curEntry.inSchedule);
}
// if in schedule -> update curI
if(j==excluded.top() || curEntry.inSchedule) {
// if not already in current intersecting set
if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {
curDelta += curEntry.size;
} // else: don't need update the size/width
// add to current intersecting set
curI[std::make_pair(curEntry.id,curEntry.size)] = j;
// check if we need to update deltaStar
if(curDelta > deltaStar) {
deltaStar = curDelta;
}
}
}
// if still feasible add excluded.top() to schedule
if(deltaStar <=0) {
newEntry.inSchedule = true;
scheduleSet.insert(excluded.top());
}
// pop stack
excluded.pop();
}
std::cerr << "found maximal schedule\n";
std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n";
return 0;
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "schedule.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
marks_select();
schedule_show();
QString name_day[] = {"понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресение"};
QString h1_text = "Сегодня";
h1_text.append(", ");
h1_text.append(current_date.toString("d MMM yyyy"));
h1_text.append(", ");
h1_text.append(name_day[day_week-1]);
h1_text.append(", идет ");
h1_text.append(QString::number(cur_week));
h1_text.append("-ая неделя учебы");
ui->h1_main->setText(h1_text);
ui->form_save_lable->hide();
ui->dateEdit->setDate(current_date);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_form()));
for (int i = 1; i <= 6; i++) //назначаем одинаковые сигналы всем кнопкам
{
QPushButton *butt = findChild<QPushButton *>("sch_" + QString::number(i));
if (butt == nullptr) continue; //если объект не найден
connect(butt,SIGNAL(clicked()),this,SLOT(open_sch()));
}
QPixmap myPixmap("C:/qtprojects/curs/course_2016.git/tem2.jpg"); //фотография
ui->photo->setPixmap(myPixmap);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::db_connect()
{
QSqlDatabase dbase = QSqlDatabase::addDatabase("QSQLITE");
dbase.setDatabaseName("C:/qtprojects/curs/course_2016.git/mydatabase.sqlite");
if (!dbase.open())
{
qDebug() << "Ошибка открытия базы данных!";
}
else
{
_db_connect = 1; //если база данных успешно подключена, то меняем параметр на 1
}
}
void MainWindow::marks_select()
{
if(!_db_connect)db_connect(); //проверка подключения к базе
marks_text = ""; // обнуляем переменную
QSqlQuery a_query; // переменная для запроса
if (!a_query.exec("SELECT * FROM marks WHERE time = date('now')"))
{
qDebug() << "Ошибка выполнения запроса SELECT";
}
QSqlRecord res = a_query.record(); //результат запроса
while (a_query.next())
{
marks_text.append("\n\n"); //отступ от заметок
marks_text.append(a_query.value(res.indexOf("text")).toString());
}
//if(marks_text == "") marks_text = "Заметок на сегодня нет!";
ui->marks_conteiner->setText(marks_text);
}
void MainWindow::sch_select(int day_week, int week)
{
if(day_week == 7)
{
sch_text = "Ура! Cегодня пар нет!";
return;
}
int type_week = 1;
if(week % 2 == 0) type_week = 2;
if(!_db_connect)db_connect(); //проверка подключения к базе
sch_text = ""; // обнуляем переменную
QSqlQuery a_query; // переменная для запроса
QString str_select; //текст запроса
if(type_week == 2) str_select = "SELECT * FROM schedule WHERE day = %1 LIMIT 5";
if(type_week == 1) str_select = "SELECT * FROM schedule WHERE day = %1 LIMIT 5,5";
QString str = str_select.arg(day_week);
if (!a_query.exec(str))
{
qDebug() << "Ошибка выполнения запроса SELECT";
}
QSqlRecord res = a_query.record(); //результат запроса
int i = 1; //счетчик пар
while (a_query.next())
{
sch_text.append(QString::number(i));
sch_text.append(". ");
QString para = a_query.value(res.indexOf("name")).toString();
if(para == "") sch_text.append("-"); else sch_text.append(para);
sch_text.append("\n\n");
i++;
}
if(sch_text == "") sch_text = "Ура! Cегодня пар нет!";
}
void MainWindow::send_form()
{
mark = ui->textEdit->toPlainText();
mark = mark.simplified(); //убираем лишние пробелы из строки
form_date = ui->dateEdit->text();
if(mark == "")
{
ui->form_save_lable->setText("Введите текст заметки");
ui->form_save_lable->show();
return;
}
if(!_db_connect)db_connect(); //проверка подключения к базе
QSqlQuery a_query;
QString str_insert = "INSERT INTO marks(text,time) "
"VALUES ('%1', '%2');";
QString str = str_insert.arg(mark)
.arg(form_date);
bool b = a_query.exec(str);
if (!b)
{
qDebug() << "Ошибка выполнения запроса INSERT";
}
ui->textEdit->clear();
ui->dateEdit->setDate(current_date);
ui->form_save_lable->setText("Заметка сохранена!");
ui->form_save_lable->show();
marks_select();
}
void MainWindow::open_sch()
{
QObject* obj = QObject::sender(); //объект, который запустил слот
QString obj_name = obj->objectName(); // имя объекта
int day;
if(obj_name == "sch_1") day = 1;
else if(obj_name == "sch_2") day = 2;
else if(obj_name == "sch_3") day = 3;
else if(obj_name == "sch_4") day = 4;
else if(obj_name == "sch_5") day = 5;
else if(obj_name == "sch_6") day = 6;
schedule sch(this,day);
connect(&sch,&schedule::sch_update,this,&MainWindow::schedule_show); //коннектор обновления расписания в главном окне
sch.exec();
}
void MainWindow::schedule_show()
{
sch_select(day_week,cur_week); //выборка расписания на текущий день из таблицы
ui->sch_output->setText(sch_text); //вывод в lable в главное окно
}
void MainWindow::date()
{
QDate start_date1;
start_date1.setDate(year, 9, 1);
QDate start_date2;
start_date2.setDate(year, 9, 1); //здесь я задумался, как же определить день начала занятий или дать возможность выбора пользователю?
}
<commit_msg>изменение функции date<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "schedule.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
db_connect();
bool res_date = date();
marks_select();
if (!res_date) schedule_show(); //если каникулы или сессия не выводим расписание
QString name_day[] = {"понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресение"};
QString h1_text = "Сегодня";
h1_text.append(", ");
h1_text.append(current_date.toString("d MMM yyyy"));
h1_text.append(", ");
h1_text.append(name_day[day_week-1]);
if(!res_date)
{
h1_text.append(", идет ");
h1_text.append(QString::number(cur_week));
h1_text.append("-ая неделя учебы");
}
ui->h1_main->setText(h1_text);
ui->form_save_lable->hide();
ui->dateEdit->setDate(current_date);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_form()));
for (int i = 1; i <= 6; i++) //назначаем одинаковые сигналы всем кнопкам
{
QPushButton *butt = findChild<QPushButton *>("sch_" + QString::number(i));
if (butt == nullptr) continue; //если объект не найден
connect(butt,SIGNAL(clicked()),this,SLOT(open_sch()));
}
QPixmap myPixmap("C:/qtprojects/curs/course_2016.git/tem2.jpg"); //фотография
ui->photo->setPixmap(myPixmap);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::db_connect()
{
QSqlDatabase dbase = QSqlDatabase::addDatabase("QSQLITE");
dbase.setDatabaseName("C:/qtprojects/curs/course_2016.git/mydatabase.sqlite");
if (!dbase.open())
{
qDebug() << "Ошибка открытия базы данных!";
}
}
void MainWindow::marks_select()
{
marks_text = ""; // обнуляем переменную
QSqlQuery a_query; // переменная для запроса
if (!a_query.exec("SELECT * FROM marks WHERE time = date('now')"))
{
qDebug() << "Ошибка выполнения запроса SELECT marks";
}
QSqlRecord res = a_query.record(); //результат запроса
while (a_query.next())
{
marks_text.append("\n\n"); //отступ от заметок
marks_text.append(a_query.value(res.indexOf("text")).toString());
}
//if(marks_text == "") marks_text = "Заметок на сегодня нет!";
ui->marks_conteiner->setText(marks_text);
}
void MainWindow::sch_select(int day_week, int week)
{
if(day_week == 7)
{
sch_text = "Ура! Cегодня пар нет!";
return;
}
int type_week = 1;
if(week % 2 == 0) type_week = 2;
sch_text = ""; // обнуляем переменную
QSqlQuery a_query; // переменная для запроса
QString str_select; //текст запроса
if(type_week == 2) str_select = "SELECT * FROM schedule WHERE day = %1 LIMIT 5";
if(type_week == 1) str_select = "SELECT * FROM schedule WHERE day = %1 LIMIT 5,5";
QString str = str_select.arg(day_week);
if (!a_query.exec(str))
{
qDebug() << "Ошибка выполнения запроса SELECT schedule";
}
QSqlRecord res = a_query.record(); //результат запроса
int i = 1; //счетчик пар
while (a_query.next())
{
sch_text.append(QString::number(i));
sch_text.append(". ");
QString para = a_query.value(res.indexOf("name")).toString();
if(para == "") sch_text.append("-"); else sch_text.append(para);
sch_text.append("\n\n");
i++;
}
if(sch_text == "") sch_text = "Ура! Cегодня пар нет!";
}
void MainWindow::send_form()
{
mark = ui->textEdit->toPlainText();
mark = mark.simplified(); //убираем лишние пробелы из строки
form_date = ui->dateEdit->text();
if(mark == "")
{
ui->form_save_lable->setText("Введите текст заметки");
ui->form_save_lable->show();
return;
}
QSqlQuery a_query;
QString str_insert = "INSERT INTO marks(text,time) "
"VALUES ('%1', '%2');";
QString str = str_insert.arg(mark)
.arg(form_date);
bool b = a_query.exec(str);
if (!b)
{
qDebug() << "Ошибка выполнения запроса INSERT marks";
}
ui->textEdit->clear();
ui->dateEdit->setDate(current_date);
ui->form_save_lable->setText("Заметка сохранена!");
ui->form_save_lable->show();
marks_select();
}
void MainWindow::open_sch()
{
QObject* obj = QObject::sender(); //объект, который запустил слот
QString obj_name = obj->objectName(); // имя объекта
int day;
if(obj_name == "sch_1") day = 1;
else if(obj_name == "sch_2") day = 2;
else if(obj_name == "sch_3") day = 3;
else if(obj_name == "sch_4") day = 4;
else if(obj_name == "sch_5") day = 5;
else if(obj_name == "sch_6") day = 6;
schedule sch(this,day);
connect(&sch,&schedule::sch_update,this,&MainWindow::schedule_show); //коннектор обновления расписания в главном окне
sch.exec();
}
void MainWindow::schedule_show()
{
sch_select(day_week,cur_week); //выборка расписания на текущий день из таблицы
ui->sch_output->setText(sch_text); //вывод в lable в главное окно
}
bool MainWindow::date()
{
QSqlQuery a_query; // переменная для запроса
if (!a_query.exec("SELECT week FROM study_day LIMIT 4"))
{
qDebug() << "Ошибка выполнения запроса SELECT week";
}
QSqlRecord res = a_query.record(); //результат запроса
int i=0;
while (a_query.next())
{
study_day[i] = a_query.value(res.indexOf("week")).toInt();
i++;
}
if(week >= study_day[0] && week <= study_day[1]) cur_week = week-study_day[0] + 1; //входит ли текущая неделя в диапазон семестра
else if(week >= study_day[2] && week <= study_day[3]) cur_week = week-study_day[2] + 1;
else return 1; //значит каникулы или сессия
return 0;
}
<|endoftext|> |
<commit_before>/*++
Module Name:
ComputeROC.cpp
Abstract:
Take a SAM file with simulated reads and compute a ROC curve from it.
Authors:
Bill Bolosky, December, 2012
Environment:
`
User mode service.
Revision History:
--*/
#include "stdafx.h"
#include "SAM.h"
#include "Genome.h"
#include "Compat.h"
#include "Read.h"
#include "RangeSplitter.h"
#include "BigAlloc.h"
void usage()
{
fprintf(stderr,"usage: ComputeROC genomeDirectory inputFile {-b}\n");
fprintf(stderr," -b means to accept reads that match either end of the range regardless of RC\n");
fprintf(stderr," -c means to just count the number of reads that are aligned, not to worry about correctness\n");
fprintf(stderr,"You can specify only one of -b or -c\n");
exit(1);
}
RangeSplitter *rangeSplitter;
volatile _int64 nRunningThreads;
SingleWaiterObject allThreadsDone;
const char *inputFileName;
const Genome *genome;
bool matchBothWays = false;
bool justCount = false;
static const int MaxMAPQ = 70;
const unsigned MaxEditDistance = 100;
struct ThreadContext {
unsigned whichThread;
_int64 countOfReads[MaxMAPQ+1];
_int64 countOfMisalignments[MaxMAPQ+1];
_int64 nUnaligned;
_int64 totalReads;
_int64 countOfReadsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];
_int64 countOfMisalignmentsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];
ThreadContext() {
nUnaligned = 0;
totalReads = 0;
for (int i = 0; i <= MaxMAPQ; i++) {
countOfReads[i] = countOfMisalignments[i] = 0;
for (int j = 0; j <= MaxEditDistance; j++) {
countOfReadsByEditDistance[i][j] = 0;
countOfMisalignmentsByEditDistance[i][j] = 0;
}
}
}
};
bool inline isADigit(char x) {
return x >= '0' && x <= '9';
}
void
WorkerThreadMain(void *param)
{
ThreadContext *context = (ThreadContext *)param;
_int64 rangeStart, rangeLength;
SAMReader *samReader = NULL;
ReaderContext rcontext;
rcontext.clipping = NoClipping;
rcontext.genome = genome;
rcontext.paired = false;
rcontext.defaultReadGroup = "";
rcontext.header = NULL;
while (rangeSplitter->getNextRange(&rangeStart, &rangeLength)) {
if (NULL == samReader) {
SAMReader::readHeader(inputFileName, rcontext);
samReader = SAMReader::create(DataSupplier::Default[true], inputFileName, rcontext, rangeStart, rangeLength);
} else {
((ReadReader *)samReader)->reinit(rangeStart, rangeLength);
}
AlignmentResult alignmentResult;
unsigned genomeLocation;
Direction isRC;
unsigned mapQ;
unsigned flag;
const char *cigar;
unsigned nextFileToWrite = 0;
Read read;
LandauVishkinWithCigar lv;
while (samReader->getNextRead(&read, &alignmentResult, &genomeLocation, &isRC, &mapQ, &flag, &cigar)) {
if (mapQ < 0 || mapQ > MaxMAPQ) {
fprintf(stderr,"Invalid MAPQ: %d\n",mapQ);
exit(1);
}
context->totalReads++;
if (0xffffffff == genomeLocation) {
context->nUnaligned++;
} else if (!justCount) {
if (flag & SAM_REVERSE_COMPLEMENT) {
read.becomeRC();
}
const Genome::Piece *piece = genome->getPieceAtLocation(genomeLocation);
if (NULL == piece) {
fprintf(stderr,"couldn't find genome piece for offset %u\n",genomeLocation);
exit(1);
}
unsigned offsetA, offsetB;
bool matched;
const unsigned cigarBufLen = 1000;
char cigarForAligned[cigarBufLen];
const char *alignedGenomeData = genome->getSubstring(genomeLocation, 1);
int editDistance = lv.computeEditDistance(alignedGenomeData, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarForAligned, cigarBufLen, false);
if (editDistance == -1 || editDistance > MaxEditDistance) {
editDistance = MaxEditDistance;
}
//
// Parse the read ID. The format is ChrName_OffsetA_OffsetB_?:<more stuff>. This would be simple to parse, except that
// ChrName can include "_". So, we parse it by looking for the first : and then working backward.
//
char idBuffer[10000]; // Hopefully big enough. I'm not worried about malicious input data here.
memcpy(idBuffer,read.getId(),read.getIdLength());
idBuffer[read.getIdLength()] = 0;
const char *firstColon = strchr(idBuffer,':');
bool badParse = true;
size_t chrNameLen;
const char *beginningOfSecondNumber;
const char *beginningOfFirstNumber; int stage = 0;
unsigned offsetOfCorrectChromosome;
if (NULL != firstColon && firstColon - 3 > idBuffer && (*(firstColon-1) == '?' || isADigit(*(firstColon - 1)))) {
//
// We've parsed backwards to see that we have at least #: or ?: where '#' is a digit and ? is literal. If it's
// a digit, then scan backwards through that number.
//
const char *underscoreBeforeFirstColon = firstColon - 2;
while (underscoreBeforeFirstColon > idBuffer && isADigit(*underscoreBeforeFirstColon)) {
underscoreBeforeFirstColon--;
}
if (*underscoreBeforeFirstColon == '_' && (isADigit(*(underscoreBeforeFirstColon - 1)) || *(underscoreBeforeFirstColon - 1) == '_')) {
stage = 1;
if (isADigit(*(underscoreBeforeFirstColon - 1))) {
beginningOfSecondNumber = firstColon - 3;
while (beginningOfSecondNumber > idBuffer && isADigit(*beginningOfSecondNumber)) {
beginningOfSecondNumber--;
}
beginningOfSecondNumber++; // That loop actually moved us back one char before the beginning;
} else {
//
// There's only one number, we have two consecutive underscores.
//
beginningOfSecondNumber = underscoreBeforeFirstColon;
}
if (beginningOfSecondNumber - 2 > idBuffer && *(beginningOfSecondNumber - 1) == '_' && isADigit(*(beginningOfSecondNumber - 2))) {
stage = 2;
beginningOfFirstNumber = beginningOfSecondNumber - 2;
while (beginningOfFirstNumber > idBuffer && isADigit(*beginningOfFirstNumber)) {
beginningOfFirstNumber--;
}
beginningOfFirstNumber++; // Again, we went one too far.
offsetA = -1;
offsetB = -1;
if (*(beginningOfFirstNumber - 1) == '_' && 1 == sscanf(beginningOfFirstNumber,"%u",&offsetA) &&
('_' == *beginningOfSecondNumber || 1 == sscanf(beginningOfSecondNumber,"%u", &offsetB))) {
stage = 3;
chrNameLen = (beginningOfFirstNumber - 1) - idBuffer;
char correctChromosomeName[1000];
memcpy(correctChromosomeName, idBuffer, chrNameLen);
correctChromosomeName[chrNameLen] = '\0';
if (!genome->getOffsetOfPiece(correctChromosomeName, &offsetOfCorrectChromosome)) {
fprintf(stderr, "Couldn't parse chromosome name '%s' from read id\n", correctChromosomeName);
} else {
badParse = false;
}
}
}
}
if (badParse) {
fprintf(stderr,"Unable to parse read ID '%s', perhaps this isn't simulated data. piecelen = %d, pieceName = '%s', piece offset = %u, genome offset = %u\n", idBuffer, strlen(piece->name), piece->name, piece->beginningOffset, genomeLocation);
exit(1);
}
bool match0 = false;
bool match1 = false;
if (-1 == offsetA || -1 == offsetB) {
matched = false;
} else if(strncmp(piece->name, idBuffer, __min(read.getIdLength(), chrNameLen))) {
matched = false;
} else {
if (isWithin(offsetA, genomeLocation - piece->beginningOffset, 50)) {
matched = true;
match0 = true;
} else if (isWithin(offsetB, genomeLocation - piece->beginningOffset, 50)) {
matched = true;
match1 = true;
} else {
matched = false;
if (flag & SAM_FIRST_SEGMENT) {
match0 = true;
} else {
match1 = true;
}
}
}
context->countOfReads[mapQ]++;
context->countOfReadsByEditDistance[mapQ][editDistance]++;
if (!matched) {
context->countOfMisalignments[mapQ]++;
context->countOfMisalignmentsByEditDistance[mapQ][editDistance]++;
if (70 == mapQ || 69 == mapQ) {
//
// We don't know which offset is correct, because neither one matched. Just take the one with the lower edit distance.
//
unsigned correctLocationA = offsetOfCorrectChromosome + offsetA;
unsigned correctLocationB = offsetOfCorrectChromosome + offsetB;
unsigned correctLocation = 0;
const char *correctData = NULL;
const char *dataA = genome->getSubstring(correctLocationA, 1);
const char *dataB = genome->getSubstring(correctLocationB, 1);
int distanceA, distanceB;
char cigarA[cigarBufLen];
char cigarB[cigarBufLen];
cigarA[0] = '*'; cigarA[1] = '\0';
cigarB[0] = '*'; cigarB[1] = '\0';
if (dataA == NULL) {
distanceA = -1;
} else {
distanceA = lv.computeEditDistance(dataA, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarA, cigarBufLen, false);
}
if (dataB == NULL) {
distanceB = -1;
} else {
distanceB = lv.computeEditDistance(dataB, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarB, cigarBufLen, false);
}
const char *correctGenomeData;
char *cigarForCorrect;
if (distanceA != -1 && distanceA <= distanceB || distanceB == -1) {
correctGenomeData = dataA;
correctLocation = correctLocationA;
cigarForCorrect = cigarA;
} else {
correctGenomeData = dataB;
correctLocation = correctLocationB;
cigarForCorrect = cigarB;
}
printf("%s\t%d\t%s\t%u\t%d\t%s\t*\t*\t100\t%.*s\t%.*s\tAlignedGenomeLocation:%u\tCorrectGenomeLocation: %u\tCigarForCorrect: %s\tCorrectData: %.*s\tAlignedData: %.*s\n",
idBuffer, flag, piece->name, genomeLocation - piece->beginningOffset, mapQ, cigarForAligned, read.getDataLength(), read.getData(),
read.getDataLength(), read.getQuality(), genomeLocation, correctLocation, cigarForCorrect, read.getDataLength(),
correctGenomeData, read.getDataLength(), alignedGenomeData);
}
}
}
} // if it was mapped
} // for each read from the sam reader
}
if (0 == InterlockedAdd64AndReturnNewValue(&nRunningThreads, -1)) {
SignalSingleWaiterObject(&allThreadsDone);
}
}
int main(int argc, char * argv[])
{
BigAllocUseHugePages = false;
if (3 != argc && 4 != argc) {
usage();
}
if (4 == argc) {
if (!strcmp(argv[3],"-b")) {
matchBothWays = true;
} else if (!strcmp(argv[3], "-c")) {
justCount = true;
} else {
usage();
}
}
static const char *genomeSuffix = "Genome";
size_t filenameLen = strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1;
char *fileName = new char[strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1];
snprintf(fileName,filenameLen,"%s%c%s",argv[1],PATH_SEP,genomeSuffix);
genome = Genome::loadFromFile(fileName, 0);
if (NULL == genome) {
fprintf(stderr,"Unable to load genome from file '%s'\n",fileName);
return -1;
}
delete [] fileName;
fileName = NULL;
inputFileName = argv[2];
unsigned nThreads;
#ifdef _DEBUG
nThreads = 1;
#else // _DEBUG
nThreads = GetNumberOfProcessors();
#endif // _DEBUG
nRunningThreads = nThreads;
_int64 fileSize = QueryFileSize(argv[2]);
rangeSplitter = new RangeSplitter(fileSize, nThreads);
CreateSingleWaiterObject(&allThreadsDone);
ThreadContext *contexts = new ThreadContext[nThreads];
for (unsigned i = 0; i < nThreads; i++) {
contexts[i].whichThread = i;
StartNewThread(WorkerThreadMain, &contexts[i]);
}
WaitForSingleWaiterObject(&allThreadsDone);
_int64 nUnaligned = 0;
_int64 totalReads = 0;
for (unsigned i = 0; i < nThreads; i++) {
nUnaligned += contexts[i].nUnaligned;
totalReads += contexts[i].totalReads;
}
printf("%lld reads, %lld unaligned (%0.2f%%)\n", totalReads, nUnaligned, 100. * (double)nUnaligned / (double)totalReads);
if (justCount) return 0;
printf("%lld total unaligned\nMAPQ\tnReads\tnMisaligned\n",nUnaligned);
for (int i = 0; i <= MaxMAPQ; i++) {
_int64 nReads = 0;
_int64 nMisaligned = 0;
for (unsigned j = 0; j < nThreads; j++) {
nReads += contexts[j].countOfReads[i];
nMisaligned += contexts[j].countOfMisalignments[i];
}
printf("%d\t%lld\t%lld\n", i, nReads, nMisaligned);
}
int maxEditDistanceSeen = 0;
for (unsigned i = 0; i < nThreads; i++) {
}
return 0;
}
<commit_msg>update roc to count mapq even on reads even if alignment position is not present<commit_after>/*++
Module Name:
ComputeROC.cpp
Abstract:
Take a SAM file with simulated reads and compute a ROC curve from it.
Authors:
Bill Bolosky, December, 2012
Environment:
`
User mode service.
Revision History:
--*/
#include "stdafx.h"
#include "SAM.h"
#include "Genome.h"
#include "Compat.h"
#include "Read.h"
#include "RangeSplitter.h"
#include "BigAlloc.h"
void usage()
{
fprintf(stderr,"usage: ComputeROC genomeDirectory inputFile {-b}\n");
fprintf(stderr," -b means to accept reads that match either end of the range regardless of RC\n");
fprintf(stderr," -c means to just count the number of reads that are aligned, not to worry about correctness\n");
fprintf(stderr,"You can specify only one of -b or -c\n");
exit(1);
}
RangeSplitter *rangeSplitter;
volatile _int64 nRunningThreads;
SingleWaiterObject allThreadsDone;
const char *inputFileName;
const Genome *genome;
bool matchBothWays = false;
bool justCount = false;
static const int MaxMAPQ = 70;
const unsigned MaxEditDistance = 100;
struct ThreadContext {
unsigned whichThread;
_int64 countOfReads[MaxMAPQ+1];
_int64 countOfMisalignments[MaxMAPQ+1];
_int64 nUnaligned;
_int64 totalReads;
_int64 countOfReadsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];
_int64 countOfMisalignmentsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];
ThreadContext() {
nUnaligned = 0;
totalReads = 0;
for (int i = 0; i <= MaxMAPQ; i++) {
countOfReads[i] = countOfMisalignments[i] = 0;
for (int j = 0; j <= MaxEditDistance; j++) {
countOfReadsByEditDistance[i][j] = 0;
countOfMisalignmentsByEditDistance[i][j] = 0;
}
}
}
};
bool inline isADigit(char x) {
return x >= '0' && x <= '9';
}
void
WorkerThreadMain(void *param)
{
ThreadContext *context = (ThreadContext *)param;
_int64 rangeStart, rangeLength;
SAMReader *samReader = NULL;
ReaderContext rcontext;
rcontext.clipping = NoClipping;
rcontext.genome = genome;
rcontext.paired = false;
rcontext.defaultReadGroup = "";
rcontext.header = NULL;
while (rangeSplitter->getNextRange(&rangeStart, &rangeLength)) {
if (NULL == samReader) {
SAMReader::readHeader(inputFileName, rcontext);
samReader = SAMReader::create(DataSupplier::Default[true], inputFileName, rcontext, rangeStart, rangeLength);
} else {
((ReadReader *)samReader)->reinit(rangeStart, rangeLength);
}
AlignmentResult alignmentResult;
unsigned genomeLocation;
Direction isRC;
unsigned mapQ;
unsigned flag;
const char *cigar;
unsigned nextFileToWrite = 0;
Read read;
LandauVishkinWithCigar lv;
while (samReader->getNextRead(&read, &alignmentResult, &genomeLocation, &isRC, &mapQ, &flag, &cigar)) {
if (justCount) {
context->countOfReads[mapQ]++;
}
if (mapQ < 0 || mapQ > MaxMAPQ) {
fprintf(stderr,"Invalid MAPQ: %d\n",mapQ);
exit(1);
}
context->totalReads++;
if (0xffffffff == genomeLocation) {
context->nUnaligned++;
} else if (!justCount) {
if (flag & SAM_REVERSE_COMPLEMENT) {
read.becomeRC();
}
const Genome::Piece *piece = genome->getPieceAtLocation(genomeLocation);
if (NULL == piece) {
fprintf(stderr,"couldn't find genome piece for offset %u\n",genomeLocation);
exit(1);
}
unsigned offsetA, offsetB;
bool matched;
const unsigned cigarBufLen = 1000;
char cigarForAligned[cigarBufLen];
const char *alignedGenomeData = genome->getSubstring(genomeLocation, 1);
int editDistance = lv.computeEditDistance(alignedGenomeData, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarForAligned, cigarBufLen, false);
if (editDistance == -1 || editDistance > MaxEditDistance) {
editDistance = MaxEditDistance;
}
//
// Parse the read ID. The format is ChrName_OffsetA_OffsetB_?:<more stuff>. This would be simple to parse, except that
// ChrName can include "_". So, we parse it by looking for the first : and then working backward.
//
char idBuffer[10000]; // Hopefully big enough. I'm not worried about malicious input data here.
memcpy(idBuffer,read.getId(),read.getIdLength());
idBuffer[read.getIdLength()] = 0;
const char *firstColon = strchr(idBuffer,':');
bool badParse = true;
size_t chrNameLen;
const char *beginningOfSecondNumber;
const char *beginningOfFirstNumber; int stage = 0;
unsigned offsetOfCorrectChromosome;
if (NULL != firstColon && firstColon - 3 > idBuffer && (*(firstColon-1) == '?' || isADigit(*(firstColon - 1)))) {
//
// We've parsed backwards to see that we have at least #: or ?: where '#' is a digit and ? is literal. If it's
// a digit, then scan backwards through that number.
//
const char *underscoreBeforeFirstColon = firstColon - 2;
while (underscoreBeforeFirstColon > idBuffer && isADigit(*underscoreBeforeFirstColon)) {
underscoreBeforeFirstColon--;
}
if (*underscoreBeforeFirstColon == '_' && (isADigit(*(underscoreBeforeFirstColon - 1)) || *(underscoreBeforeFirstColon - 1) == '_')) {
stage = 1;
if (isADigit(*(underscoreBeforeFirstColon - 1))) {
beginningOfSecondNumber = firstColon - 3;
while (beginningOfSecondNumber > idBuffer && isADigit(*beginningOfSecondNumber)) {
beginningOfSecondNumber--;
}
beginningOfSecondNumber++; // That loop actually moved us back one char before the beginning;
} else {
//
// There's only one number, we have two consecutive underscores.
//
beginningOfSecondNumber = underscoreBeforeFirstColon;
}
if (beginningOfSecondNumber - 2 > idBuffer && *(beginningOfSecondNumber - 1) == '_' && isADigit(*(beginningOfSecondNumber - 2))) {
stage = 2;
beginningOfFirstNumber = beginningOfSecondNumber - 2;
while (beginningOfFirstNumber > idBuffer && isADigit(*beginningOfFirstNumber)) {
beginningOfFirstNumber--;
}
beginningOfFirstNumber++; // Again, we went one too far.
offsetA = -1;
offsetB = -1;
if (*(beginningOfFirstNumber - 1) == '_' && 1 == sscanf(beginningOfFirstNumber,"%u",&offsetA) &&
('_' == *beginningOfSecondNumber || 1 == sscanf(beginningOfSecondNumber,"%u", &offsetB))) {
stage = 3;
chrNameLen = (beginningOfFirstNumber - 1) - idBuffer;
char correctChromosomeName[1000];
memcpy(correctChromosomeName, idBuffer, chrNameLen);
correctChromosomeName[chrNameLen] = '\0';
if (!genome->getOffsetOfPiece(correctChromosomeName, &offsetOfCorrectChromosome)) {
fprintf(stderr, "Couldn't parse chromosome name '%s' from read id\n", correctChromosomeName);
} else {
badParse = false;
}
}
}
}
if (badParse) {
fprintf(stderr,"Unable to parse read ID '%s', perhaps this isn't simulated data. piecelen = %d, pieceName = '%s', piece offset = %u, genome offset = %u\n", idBuffer, strlen(piece->name), piece->name, piece->beginningOffset, genomeLocation);
exit(1);
}
bool match0 = false;
bool match1 = false;
if (-1 == offsetA || -1 == offsetB) {
matched = false;
} else if(strncmp(piece->name, idBuffer, __min(read.getIdLength(), chrNameLen))) {
matched = false;
} else {
if (isWithin(offsetA, genomeLocation - piece->beginningOffset, 50)) {
matched = true;
match0 = true;
} else if (isWithin(offsetB, genomeLocation - piece->beginningOffset, 50)) {
matched = true;
match1 = true;
} else {
matched = false;
if (flag & SAM_FIRST_SEGMENT) {
match0 = true;
} else {
match1 = true;
}
}
}
context->countOfReads[mapQ]++;
context->countOfReadsByEditDistance[mapQ][editDistance]++;
if (!matched) {
context->countOfMisalignments[mapQ]++;
context->countOfMisalignmentsByEditDistance[mapQ][editDistance]++;
if (70 == mapQ || 69 == mapQ) {
//
// We don't know which offset is correct, because neither one matched. Just take the one with the lower edit distance.
//
unsigned correctLocationA = offsetOfCorrectChromosome + offsetA;
unsigned correctLocationB = offsetOfCorrectChromosome + offsetB;
unsigned correctLocation = 0;
const char *correctData = NULL;
const char *dataA = genome->getSubstring(correctLocationA, 1);
const char *dataB = genome->getSubstring(correctLocationB, 1);
int distanceA, distanceB;
char cigarA[cigarBufLen];
char cigarB[cigarBufLen];
cigarA[0] = '*'; cigarA[1] = '\0';
cigarB[0] = '*'; cigarB[1] = '\0';
if (dataA == NULL) {
distanceA = -1;
} else {
distanceA = lv.computeEditDistance(dataA, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarA, cigarBufLen, false);
}
if (dataB == NULL) {
distanceB = -1;
} else {
distanceB = lv.computeEditDistance(dataB, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarB, cigarBufLen, false);
}
const char *correctGenomeData;
char *cigarForCorrect;
if (distanceA != -1 && distanceA <= distanceB || distanceB == -1) {
correctGenomeData = dataA;
correctLocation = correctLocationA;
cigarForCorrect = cigarA;
} else {
correctGenomeData = dataB;
correctLocation = correctLocationB;
cigarForCorrect = cigarB;
}
printf("%s\t%d\t%s\t%u\t%d\t%s\t*\t*\t100\t%.*s\t%.*s\tAlignedGenomeLocation:%u\tCorrectGenomeLocation: %u\tCigarForCorrect: %s\tCorrectData: %.*s\tAlignedData: %.*s\n",
idBuffer, flag, piece->name, genomeLocation - piece->beginningOffset, mapQ, cigarForAligned, read.getDataLength(), read.getData(),
read.getDataLength(), read.getQuality(), genomeLocation, correctLocation, cigarForCorrect, read.getDataLength(),
correctGenomeData, read.getDataLength(), alignedGenomeData);
}
}
}
} // if it was mapped
} // for each read from the sam reader
}
if (0 == InterlockedAdd64AndReturnNewValue(&nRunningThreads, -1)) {
SignalSingleWaiterObject(&allThreadsDone);
}
}
int main(int argc, char * argv[])
{
BigAllocUseHugePages = false;
if (3 != argc && 4 != argc) {
usage();
}
if (4 == argc) {
if (!strcmp(argv[3],"-b")) {
matchBothWays = true;
} else if (!strcmp(argv[3], "-c")) {
justCount = true;
} else {
usage();
}
}
static const char *genomeSuffix = "Genome";
size_t filenameLen = strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1;
char *fileName = new char[strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1];
snprintf(fileName,filenameLen,"%s%c%s",argv[1],PATH_SEP,genomeSuffix);
genome = Genome::loadFromFile(fileName, 0);
if (NULL == genome) {
fprintf(stderr,"Unable to load genome from file '%s'\n",fileName);
return -1;
}
delete [] fileName;
fileName = NULL;
inputFileName = argv[2];
unsigned nThreads;
#ifdef _DEBUG
nThreads = 1;
#else // _DEBUG
nThreads = GetNumberOfProcessors();
#endif // _DEBUG
nRunningThreads = nThreads;
_int64 fileSize = QueryFileSize(argv[2]);
rangeSplitter = new RangeSplitter(fileSize, nThreads);
CreateSingleWaiterObject(&allThreadsDone);
ThreadContext *contexts = new ThreadContext[nThreads];
for (unsigned i = 0; i < nThreads; i++) {
contexts[i].whichThread = i;
StartNewThread(WorkerThreadMain, &contexts[i]);
}
WaitForSingleWaiterObject(&allThreadsDone);
_int64 nUnaligned = 0;
_int64 totalReads = 0;
for (unsigned i = 0; i < nThreads; i++) {
nUnaligned += contexts[i].nUnaligned;
totalReads += contexts[i].totalReads;
}
printf("%lld reads, %lld unaligned (%0.2f%%)\n", totalReads, nUnaligned, 100. * (double)nUnaligned / (double)totalReads);
printf("MAPQ\tnReads\tnMisaligned\n");
for (int i = 0; i <= MaxMAPQ; i++) {
_int64 nReads = 0;
_int64 nMisaligned = 0;
for (unsigned j = 0; j < nThreads; j++) {
nReads += contexts[j].countOfReads[i];
nMisaligned += contexts[j].countOfMisalignments[i];
}
printf("%d\t%lld\t%lld\n", i, nReads, nMisaligned);
}
int maxEditDistanceSeen = 0;
for (unsigned i = 0; i < nThreads; i++) {
}
return 0;
}
<|endoftext|> |
<commit_before>
#undef NDEBUG
#include "ospray/common/OspCommon.h"
#include "apps/common/xml/xml.h"
#include "model.h"
#include "common/sys/filename.h"
namespace ospray {
namespace particle {
bool big_endian = false;
/*! a dump-file we can use for debugging; we'll simply dump each
parsed particle into this file during parsing */
FILE *particleDumpFile = NULL;
struct Particle {
double x,y,z;
};
// struct MPM {
// std::vector<vec3f> pos;
// };
// MPM mpm;
double htonlf(double f)
{
double ret;
char *in = (char*)&f;
char *out = (char*)&ret;
for (int i=0;i<8;i++)
out[i] = in[7-i];
return ret;
}
void readParticles(Model *model,
size_t numParticles, const std::string &fn, size_t begin, size_t end)
{
// std::cout << "#mpm: reading " << numParticles << " particles... " << std::flush;
// printf("#mpm: reading%7ld particles...",numParticles); fflush(0);
FILE *file = fopen(fn.c_str(),"rb");
if (!file) {
throw std::runtime_error("could not open data file "+fn);
}
assert(file);
fseek(file,begin,SEEK_SET);
size_t len = end-begin;
if (len != numParticles*sizeof(Particle)) {
PING;
PRINT(len);
PRINT(numParticles);
PRINT(len/numParticles);
}
// PRINT(len);
for (int i=0;i<numParticles;i++) {
Particle p;
int rc = fread(&p,sizeof(p),1,file);
if (rc != 1) {
fclose(file);
throw std::runtime_error("read partial data "+fn);
}
#if 1
if (big_endian) {
p.x = htonlf(p.x);
p.y = htonlf(p.y);
p.z = htonlf(p.z);
}
#endif
Model::Atom a;
a.position = vec3f(p.x,p.y,p.z);
a.type = model->getAtomType("<unnamed>");
if (particleDumpFile)
fwrite(&a,sizeof(a),1,particleDumpFile);
model->atom.push_back(a);
}
std::cout << "\r#osp:uintah: read " << numParticles << " particles (total " << float(model->atom.size()/1e6) << "M)";
// Particle *particle = new Particle[numParticles];
// fread(particle,numParticles,sizeof(Particle),file);
// for (int i=0;i
// for (int i=0;i<100;i++)
// printf("particle %5i: %lf %lf %lf\n",particle[i].x,particle[i].y,particle[i].z);
fclose(file);
}
void parse__Variable(Model *model,
const std::string &basePath, xml::Node *var)
{
size_t index = -1;
size_t start = -1;
size_t end = -1;
size_t patch = -1;
size_t numParticles = 0;
std::string variable;
std::string filename;
for (int i=0;i<var->child.size();i++) {
xml::Node *n = var->child[i];
if (n->name == "index") {
index = atoi(n->content.c_str());
} else if (n->name == "variable") {
variable = n->content;
} else if (n->name == "numParticles") {
numParticles = atol(n->content.c_str());
} else if (n->name == "patch") {
patch = atol(n->content.c_str());
} else if (n->name == "filename") {
filename = n->content;
} else if (n->name == "start") {
start = atol(n->content.c_str());
} else if (n->name == "end") {
end = atol(n->content.c_str());
}
}
if (numParticles > 0
&& variable == "p.x"
/* && index == .... */
) {
readParticles(model,numParticles,basePath+"/"+filename,start,end);
}
// PRINT(patch);
// PRINT(numParticles);
// PRINT(start);
// PRINT(filename);
}
// pase a "Uintah_Output" node
// void parse__Uintah_Output(const std::string &basePath, xml::Node *node)
// {
// assert(node->name == "Uintah_Output");
// for (int i=0;i<node->child.size();i++) {
// xml::Node *c = node->child[i];
// assert(c->name == "Variable");
// parse__Variable(basePath,c);
// }
// }
void parse__Uintah_Datafile(Model *model,
const std::string &fileName)
{
std::string basePath = embree::FileName(fileName).path();
xml::XMLDoc *doc = NULL;
try {
doc = xml::readXML(fileName);
} catch (std::runtime_error e) {
static bool warned = false;
if (!warned) {
std::cerr << "#osp:uintah: error in opening xml data file: " << e.what() << std::endl;
std::cerr << "#osp:uintah: continuing parsing, but parts of the data will be missing" << std::endl;
std::cerr << "#osp:uintah: (only printing first instance of this error; there may be more)" << std::endl;
warned = true;
}
return;
}
assert(doc);
assert(doc->child.size() == 1);
xml::Node *node = doc->child[0];
assert(node->name == "Uintah_Output");
for (int i=0;i<node->child.size();i++) {
xml::Node *c = node->child[i];
assert(c->name == "Variable");
parse__Variable(model,basePath,c);
}
delete doc;
}
void parse__Uintah_TimeStep_Data(Model *model,
const std::string &basePath, xml::Node *node)
{
assert(node->name == "Data");
for (int i=0;i<node->child.size();i++) {
xml::Node *c = node->child[i];
assert(c->name == "Datafile");
for (int j=0;j<c->prop.size();j++) {
xml::Prop *p = c->prop[j];
if (p->name == "href") {
try {
parse__Uintah_Datafile(model,basePath+"/"+p->value);
} catch (std::runtime_error e) {
static bool warned = false;
if (!warned) {
std::cerr << "#osp:uintah: error in parsing timestep data: " << e.what() << std::endl;
std::cerr << "#osp:uintah: continuing parsing, but parts of the data will be missing" << std::endl;
std::cerr << "#osp:uintah: (only printing first instance of this error; there may be more)" << std::endl;
warned = true;
}
}
}
}
}
}
void parse__Uintah_TimeStep_Meta(Model *model,
const std::string &basePath, xml::Node *node)
{
assert(node->name == "Meta");
for (int i=0;i<node->child.size();i++) {
xml::Node *c = node->child[i];
if (c->name == "endianness") {
if (c->content == "big_endian") {
std::cout << "#osp:uintah: SWITCHING TO BIG_ENDIANNESS" << std::endl;
big_endian = true;
}
}
}
}
void parse__Uintah_timestep(Model *model,
const std::string &basePath, xml::Node *node)
{
assert(node->name == "Uintah_timestep");
for (int i=0;i<node->child.size();i++) {
xml::Node *c = node->child[i];
if (c->name == "Meta") {
parse__Uintah_TimeStep_Meta(model,basePath,c);
}
if (c->name == "Data") {
parse__Uintah_TimeStep_Data(model,basePath,c);
}
}
}
Model *parse__Uintah_timestep_xml(const std::string &s)
{
Model *model = new Model;
Ref<xml::XMLDoc> doc = xml::readXML(s);
char *dumpFileName = getenv("OSPRAY_PARTICLE_DUMP_FILE");
if (dumpFileName)
particleDumpFile = fopen(dumpFileName,"wb");
assert(doc);
assert(doc->child.size() == 1);
assert(doc->child[0]->name == "Uintah_timestep");
std::string basePath = embree::FileName(s).path();
parse__Uintah_timestep(model, basePath, doc->child[0]);
std::cout << "#osp:mpm: read " << s << " : "
<< model->atom.size() << " particles" << std::endl;
box3f bounds = embree::empty;
for (int i=0;i<model->atom.size();i++) {
bounds.extend(model->atom[i].position);
}
std::cout << "#osp:mpm: bounds of particle centers: " << bounds << std::endl;
model->radius = .002f;
return model;
}
}
}
<commit_msg>can now specify particle dump file for particle viewer<commit_after>
#undef NDEBUG
#include "ospray/common/OspCommon.h"
#include "apps/common/xml/xml.h"
#include "model.h"
#include "common/sys/filename.h"
namespace ospray {
namespace particle {
bool big_endian = false;
/*! a dump-file we can use for debugging; we'll simply dump each
parsed particle into this file during parsing */
FILE *particleDumpFile = NULL;
size_t numDumpedParticles = 0;
struct Particle {
double x,y,z;
};
// struct MPM {
// std::vector<vec3f> pos;
// };
// MPM mpm;
double htonlf(double f)
{
double ret;
char *in = (char*)&f;
char *out = (char*)&ret;
for (int i=0;i<8;i++)
out[i] = in[7-i];
return ret;
}
void readParticles(Model *model,
size_t numParticles, const std::string &fn, size_t begin, size_t end)
{
// std::cout << "#mpm: reading " << numParticles << " particles... " << std::flush;
// printf("#mpm: reading%7ld particles...",numParticles); fflush(0);
FILE *file = fopen(fn.c_str(),"rb");
if (!file) {
throw std::runtime_error("could not open data file "+fn);
}
assert(file);
fseek(file,begin,SEEK_SET);
size_t len = end-begin;
if (len != numParticles*sizeof(Particle)) {
PING;
PRINT(len);
PRINT(numParticles);
PRINT(len/numParticles);
}
// PRINT(len);
for (int i=0;i<numParticles;i++) {
Particle p;
int rc = fread(&p,sizeof(p),1,file);
if (rc != 1) {
fclose(file);
throw std::runtime_error("read partial data "+fn);
}
#if 1
if (big_endian) {
p.x = htonlf(p.x);
p.y = htonlf(p.y);
p.z = htonlf(p.z);
}
#endif
Model::Atom a;
a.position = vec3f(p.x,p.y,p.z);
a.type = model->getAtomType("<unnamed>");
if (particleDumpFile) {
numDumpedParticles++;
fwrite(&a,sizeof(a),1,particleDumpFile);
} else
model->atom.push_back(a);
}
std::cout << "\r#osp:uintah: read " << numParticles << " particles (total " << float((numDumpedParticles+model->atom.size())/1e6) << "M)";
// Particle *particle = new Particle[numParticles];
// fread(particle,numParticles,sizeof(Particle),file);
// for (int i=0;i
// for (int i=0;i<100;i++)
// printf("particle %5i: %lf %lf %lf\n",particle[i].x,particle[i].y,particle[i].z);
fclose(file);
}
void parse__Variable(Model *model,
const std::string &basePath, xml::Node *var)
{
size_t index = -1;
size_t start = -1;
size_t end = -1;
size_t patch = -1;
size_t numParticles = 0;
std::string variable;
std::string filename;
for (int i=0;i<var->child.size();i++) {
xml::Node *n = var->child[i];
if (n->name == "index") {
index = atoi(n->content.c_str());
} else if (n->name == "variable") {
variable = n->content;
} else if (n->name == "numParticles") {
numParticles = atol(n->content.c_str());
} else if (n->name == "patch") {
patch = atol(n->content.c_str());
} else if (n->name == "filename") {
filename = n->content;
} else if (n->name == "start") {
start = atol(n->content.c_str());
} else if (n->name == "end") {
end = atol(n->content.c_str());
}
}
if (numParticles > 0
&& variable == "p.x"
/* && index == .... */
) {
readParticles(model,numParticles,basePath+"/"+filename,start,end);
}
// PRINT(patch);
// PRINT(numParticles);
// PRINT(start);
// PRINT(filename);
}
// pase a "Uintah_Output" node
// void parse__Uintah_Output(const std::string &basePath, xml::Node *node)
// {
// assert(node->name == "Uintah_Output");
// for (int i=0;i<node->child.size();i++) {
// xml::Node *c = node->child[i];
// assert(c->name == "Variable");
// parse__Variable(basePath,c);
// }
// }
void parse__Uintah_Datafile(Model *model,
const std::string &fileName)
{
std::string basePath = embree::FileName(fileName).path();
xml::XMLDoc *doc = NULL;
try {
doc = xml::readXML(fileName);
} catch (std::runtime_error e) {
static bool warned = false;
if (!warned) {
std::cerr << "#osp:uintah: error in opening xml data file: " << e.what() << std::endl;
std::cerr << "#osp:uintah: continuing parsing, but parts of the data will be missing" << std::endl;
std::cerr << "#osp:uintah: (only printing first instance of this error; there may be more)" << std::endl;
warned = true;
}
return;
}
assert(doc);
assert(doc->child.size() == 1);
xml::Node *node = doc->child[0];
assert(node->name == "Uintah_Output");
for (int i=0;i<node->child.size();i++) {
xml::Node *c = node->child[i];
assert(c->name == "Variable");
parse__Variable(model,basePath,c);
}
delete doc;
}
void parse__Uintah_TimeStep_Data(Model *model,
const std::string &basePath, xml::Node *node)
{
assert(node->name == "Data");
for (int i=0;i<node->child.size();i++) {
xml::Node *c = node->child[i];
assert(c->name == "Datafile");
for (int j=0;j<c->prop.size();j++) {
xml::Prop *p = c->prop[j];
if (p->name == "href") {
try {
parse__Uintah_Datafile(model,basePath+"/"+p->value);
} catch (std::runtime_error e) {
static bool warned = false;
if (!warned) {
std::cerr << "#osp:uintah: error in parsing timestep data: " << e.what() << std::endl;
std::cerr << "#osp:uintah: continuing parsing, but parts of the data will be missing" << std::endl;
std::cerr << "#osp:uintah: (only printing first instance of this error; there may be more)" << std::endl;
warned = true;
}
}
}
}
}
}
void parse__Uintah_TimeStep_Meta(Model *model,
const std::string &basePath, xml::Node *node)
{
assert(node->name == "Meta");
for (int i=0;i<node->child.size();i++) {
xml::Node *c = node->child[i];
if (c->name == "endianness") {
if (c->content == "big_endian") {
std::cout << "#osp:uintah: SWITCHING TO BIG_ENDIANNESS" << std::endl;
big_endian = true;
}
}
}
}
void parse__Uintah_timestep(Model *model,
const std::string &basePath, xml::Node *node)
{
assert(node->name == "Uintah_timestep");
for (int i=0;i<node->child.size();i++) {
xml::Node *c = node->child[i];
if (c->name == "Meta") {
parse__Uintah_TimeStep_Meta(model,basePath,c);
}
if (c->name == "Data") {
parse__Uintah_TimeStep_Data(model,basePath,c);
}
}
}
Model *parse__Uintah_timestep_xml(const std::string &s)
{
Model *model = new Model;
Ref<xml::XMLDoc> doc = xml::readXML(s);
char *dumpFileName = getenv("OSPRAY_PARTICLE_DUMP_FILE");
if (dumpFileName)
particleDumpFile = fopen(dumpFileName,"wb");
assert(doc);
assert(doc->child.size() == 1);
assert(doc->child[0]->name == "Uintah_timestep");
std::string basePath = embree::FileName(s).path();
parse__Uintah_timestep(model, basePath, doc->child[0]);
std::cout << "#osp:mpm: read " << s << " : "
<< model->atom.size() << " particles" << std::endl;
box3f bounds = embree::empty;
for (int i=0;i<model->atom.size();i++) {
bounds.extend(model->atom[i].position);
}
std::cout << "#osp:mpm: bounds of particle centers: " << bounds << std::endl;
model->radius = .002f;
return model;
}
}
}
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL
#define MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL
#include <cmath>
namespace mjolnir
{
/* Implicit membrane potential & derivative *
* potential field dependent on z coordinate. *
* tanh is used to represent membrane potential. *
* V(z) = ma * tanh(be * (|z| - th/2)) *
* dV/dr = (z/|z|) * ma * (cosh^2(be * (|z| - th/2))) *
* Cutoff ratio ensure 1/1000 accuracy. */
template<typename traitT>
class ImplicitMembranePotential
{
public:
typedef traitT traits_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef real_type parameter_type;
constexpr static real_type cutoff_ratio = 4.0;
public:
ImplicitMembranePotential() = default;
ImplicitMembranePotential(const real_type th, const real_type ma,
const real_type be, const std::vector<parameter_type>& hydrophobicities)
: half_thick_(th * 0.5), interaction_magnitude_(ma),
bend_(be), hydrophobicities_(hydrophobicities)
{}
ImplicitMembranePotential(real_type th, real_type ma,
real_type be, std::vector<parameter_type>&& hydrophobicities)
: half_thick_(th * 0.5), interaction_magnitude_(ma), bend_(be),
hydrophobicities_(std::move(hydrophobicities))
{}
~ImplicitMembranePotential() = default;
real_type half_thick() const noexcept {return half_thick_;}
real_type& half_thick() noexcept {return half_thick_;}
real_type interaction_magnitude() const noexcept
{return interaction_magnitude_;}
real_type& interaction_magnitude() noexcept
{return interaction_magnitude_;}
real_type bend() const noexcept {return bend_;}
real_type& bend() noexcept {return bend_;}
void hydrophobicities_emplace(const parameter_type);
void set_hydrophobicities(const std::vector<parameter_type>&);
void set_hydrophobicities(std::vector<parameter_type>&&);
std::size_t size() const noexcept {return hydrophobicities_.size();}
void resize (const std::size_t i){hydrophobicities_.resize();}
void reserve(const std::size_t i){hydrophobicities_.reserve();}
void clear() {hydrophobicities_.clear();}
parameter_type& operator[](const std::size_t i) noexcept
{return hydrophobicities_[i];}
parameter_type const& operator[](const std::size_t i) const noexcept
{return hydrophobicities_[i];}
parameter_type& at(const std::size_t i)
{return hydrophobicities_.at(i);}
parameter_type const& at(const std::size_t i) const
{return hydrophobicities_.at(i);}
real_type potential (const std::size_t i, const real_type z) const;
real_type derivative(const std::size_t i, const real_type z) const;
real_type max_cutoff_length() const noexcept;
private:
real_type half_thick_;//membrane half of thickness.
real_type interaction_magnitude_;
real_type bend_;//bend_ decide the slope of tanh carve.
std::vector<parameter_type> hydrophobicities_;
};
template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::hydrophobicities_emplace(
const parameter_type hydrophobicity)
{
hydrophobicities_.emplace_back(hydrophobicity);
return;
}
template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::set_hydrophobicities(
const std::vector<parameter_type>& hydrophobicities)
{
hydrophobicities_ = hydrophobicities;
return;
}
template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::set_hydrophobicities(
std::vector<parameter_type>&& hydrophobicities)
{
hydrophobicities_ = std::move(hydrophobicities);
return;
}
template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::potential(
const std::size_t i, const real_type z) const
{
return hydrophobicities_[i] * interaction_magnitude_ *
std::tanh(bend_ * (std::abs(z) - half_thick_));
}
template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::derivative(
const std::size_t i, const real_type z) const
{
return hydrophobicities_[i] * std::copysign(1.0, z) *
interaction_magnitude_ * bend_ /
std::pow((std::cosh(bend_ * (std::abs(z) - half_thick_))), 2);
}
template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::max_cutoff_length() const noexcept
{
return cutoff_ratio / bend_ + half_thick_;
}
}
#endif /* MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL */
<commit_msg>fix: pass argument to member<commit_after>#ifndef MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL
#define MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL
#include <cmath>
namespace mjolnir
{
/* Implicit membrane potential & derivative *
* potential field dependent on z coordinate. *
* tanh is used to represent membrane potential. *
* V(z) = ma * tanh(be * (|z| - th/2)) *
* dV/dr = (z/|z|) * ma * (cosh^2(be * (|z| - th/2))) *
* Cutoff ratio ensure 1/1000 accuracy. */
template<typename traitT>
class ImplicitMembranePotential
{
public:
typedef traitT traits_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef real_type parameter_type;
constexpr static real_type cutoff_ratio = 4.0;
public:
ImplicitMembranePotential() = default;
ImplicitMembranePotential(const real_type th, const real_type ma,
const real_type be, const std::vector<parameter_type>& hydrophobicities)
: half_thick_(th * 0.5), interaction_magnitude_(ma),
bend_(be), hydrophobicities_(hydrophobicities)
{}
ImplicitMembranePotential(real_type th, real_type ma,
real_type be, std::vector<parameter_type>&& hydrophobicities)
: half_thick_(th * 0.5), interaction_magnitude_(ma), bend_(be),
hydrophobicities_(std::move(hydrophobicities))
{}
~ImplicitMembranePotential() = default;
real_type half_thick() const noexcept {return half_thick_;}
real_type& half_thick() noexcept {return half_thick_;}
real_type interaction_magnitude() const noexcept
{return interaction_magnitude_;}
real_type& interaction_magnitude() noexcept
{return interaction_magnitude_;}
real_type bend() const noexcept {return bend_;}
real_type& bend() noexcept {return bend_;}
void hydrophobicities_emplace(const parameter_type);
void set_hydrophobicities(const std::vector<parameter_type>&);
void set_hydrophobicities(std::vector<parameter_type>&&);
std::size_t size() const noexcept {return hydrophobicities_.size();}
void resize (const std::size_t i){hydrophobicities_.resize(i);}
void reserve(const std::size_t i){hydrophobicities_.reserve(i);}
void clear() {hydrophobicities_.clear();}
parameter_type& operator[](const std::size_t i) noexcept
{return hydrophobicities_[i];}
parameter_type const& operator[](const std::size_t i) const noexcept
{return hydrophobicities_[i];}
parameter_type& at(const std::size_t i)
{return hydrophobicities_.at(i);}
parameter_type const& at(const std::size_t i) const
{return hydrophobicities_.at(i);}
real_type potential (const std::size_t i, const real_type z) const;
real_type derivative(const std::size_t i, const real_type z) const;
real_type max_cutoff_length() const noexcept;
private:
real_type half_thick_;//membrane half of thickness.
real_type interaction_magnitude_;
real_type bend_;//bend_ decide the slope of tanh carve.
std::vector<parameter_type> hydrophobicities_;
};
template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::hydrophobicities_emplace(
const parameter_type hydrophobicity)
{
hydrophobicities_.emplace_back(hydrophobicity);
return;
}
template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::set_hydrophobicities(
const std::vector<parameter_type>& hydrophobicities)
{
hydrophobicities_ = hydrophobicities;
return;
}
template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::set_hydrophobicities(
std::vector<parameter_type>&& hydrophobicities)
{
hydrophobicities_ = std::move(hydrophobicities);
return;
}
template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::potential(
const std::size_t i, const real_type z) const
{
return hydrophobicities_[i] * interaction_magnitude_ *
std::tanh(bend_ * (std::abs(z) - half_thick_));
}
template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::derivative(
const std::size_t i, const real_type z) const
{
return hydrophobicities_[i] * std::copysign(1.0, z) *
interaction_magnitude_ * bend_ /
std::pow((std::cosh(bend_ * (std::abs(z) - half_thick_))), 2);
}
template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::max_cutoff_length() const noexcept
{
return cutoff_ratio / bend_ + half_thick_;
}
}
#endif /* MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL */
<|endoftext|> |
<commit_before>#include "ExampleAndroidHandler.h"
#include <AndroidLog.h>
#include <GooglePlayServices.h>
#include <GoogleGames.h>
#include <AppState.h>
#include <time.h>
#include "ExampleStateListener.h"
class SignInListener : public Android::ISignInListener
{
private:
ExampleStateListener m_StateListener;
public:
virtual void OnSignInSucceeded()
{
LOGV( "Signed in!" );
char state[] = "Hello Cloud Save!";
Android::AppState::UpdateState( 1, state, sizeof( state ) );
Android::AppState::LoadState( 1, &m_StateListener );
}
virtual void OnSignInFailed()
{
LOGE( "Sign in failed." );
}
SignInListener() { }
virtual ~SignInListener() { }
};
ExampleAndroidHandler::ExampleAndroidHandler()
{
// State variables
m_bShouldQuit = false;
m_bIsVisible = false;
m_bIsPaused = true;
// Egl
m_Display = EGL_NO_DISPLAY;
m_Surface = EGL_NO_SURFACE;
m_Context = NULL;
}
ExampleAndroidHandler::~ExampleAndroidHandler()
{
DestroyOpenGL();
}
void ExampleAndroidHandler::Run()
{
SignInListener signInListener;
Android::GooglePlayServices::SetSignInListener( &signInListener );
// Example asset read
Android::Asset* pAsset = Android::GetAssetManager().GetAsset( "test.txt" );
if ( pAsset )
{
// Create a buffer to read the content into,
// [ Size() + 1 ] for null terminator character for LOG usage
char* pBuffer = new char[ pAsset->Size() + 1 ];
// Read the buffer
pAsset->Read( pBuffer, pAsset->Size() );
// Set null terminating for LOG
pBuffer[ pAsset->Size() ] = 0;
// Delete the asset file
delete pAsset;
// Show us the file's content!
LOGV( "[Example]: File content: %s", pBuffer );
// Delete the buffer
delete [] pBuffer;
}
// Create time measurement
timespec timeNow;
clock_gettime( CLOCK_MONOTONIC, &timeNow );
uint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;
// Connect to Google Play
Android::GooglePlayServices::SignIn();
// While application is alive...
while ( !m_bShouldQuit )
{
// Handle Android events
Android::PollEvents();
// Calculate delta time
clock_gettime( CLOCK_MONOTONIC, &timeNow ); // query time now
uint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; // get time in nanoseconds
float fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; // 1 second = 1,000,000,000 nanoseconds
uPreviousTime = uNowNano; // set previous time to new time
// If not paused...
if ( !m_bIsPaused )
{
// Update logic
Update( fDeltaSeconds );
}
// If visible
if ( m_bIsVisible )
{
// Draw
Draw();
}
}
LOGV( "[Example]: Mainloop terminated." );
}
void ExampleAndroidHandler::Update( float fDeltaSeconds )
{
// Do stuff here
}
void ExampleAndroidHandler::Draw()
{
// Draw things here
glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
if ( !eglSwapBuffers( m_Display, m_Surface ) )
{
LOGE( "[Example]: eglSwapBuffers() returned error %d", eglGetError() );
}
}
bool ExampleAndroidHandler::InitOpenGL()
{
const EGLint attribs[] =
{
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLDisplay display;
EGLConfig config;
EGLint numConfigs;
EGLint format;
EGLSurface surface;
EGLContext context;
EGLint width;
EGLint height;
GLfloat ratio;
LOGV( "[Example]: Initializing context" );
if ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )
{
LOGE( "[Example]: eglGetDisplay() returned error %d", eglGetError() );
return false;
}
if ( !eglInitialize( display, 0, 0 ) )
{
LOGE( "[Example]: eglInitialize() returned error %d", eglGetError() );
return false;
}
if ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )
{
LOGE( "[Example]: eglChooseConfig() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )
{
LOGE( "[Example]: eglGetConfigAttrib() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
// Set buffer geometry using our window which is saved in Android
ANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );
if ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )
{
LOGE( "[Example]: eglCreateWindowSurface() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !( context = eglCreateContext( display, config, 0, 0 ) ) )
{
LOGE( "[Example]: eglCreateContext() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglMakeCurrent(display, surface, surface, context ) )
{
LOGE( "[Example]: eglMakeCurrent() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||
!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )
{
LOGE( "[Example]: eglQuerySurface() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
m_Display = display;
m_Surface = surface;
m_Context = context;
glDisable( GL_DITHER );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
glClearColor(0, 0, 0, 0);
glEnable( GL_CULL_FACE );
glEnable( GL_DEPTH_TEST );
return true;
}
void ExampleAndroidHandler::DestroyOpenGL()
{
if ( m_Display )
{
LOGV( "[Example]: Shutting down OpenGL" );
eglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
eglDestroyContext( m_Display, m_Context );
eglDestroySurface( m_Display, m_Surface);
eglTerminate( m_Display );
m_Display = EGL_NO_DISPLAY;
m_Surface = EGL_NO_SURFACE;
m_Context = NULL;
}
}
// Application
void ExampleAndroidHandler::OnShutdown()
{
LOGV( "[Example]: Shutting down!" );
m_bShouldQuit = true;
}
// Surface
void ExampleAndroidHandler::OnSurfaceCreated()
{
LOGV( "[Example]: Creating surface!" );
if ( InitOpenGL() == false )
{
m_bShouldQuit = true;
}
}
void ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )
{
LOGV( "[Example]: Setting viewports!" );
// Set new viewport
glViewport( 0, 0, iWidth, iHeight );
}
void ExampleAndroidHandler::OnSurfaceDestroyed()
{
LOGV( "[Example]: Destroying egl!" );
DestroyOpenGL();
}
// States
void ExampleAndroidHandler::OnPause()
{
LOGV( "[Example]: Paused!" );
m_bIsPaused = true;
}
void ExampleAndroidHandler::OnResume()
{
LOGV( "[Example]: Resumed!" );
m_bIsPaused = false;
}
void ExampleAndroidHandler::OnVisible()
{
LOGV( "[Example]: Visible!" );
m_bIsVisible = true;
}
void ExampleAndroidHandler::OnHidden()
{
LOGV( "[Example]: Hidden!" );
m_bIsVisible = false;
//Android::GooglePlayServices::SignOut();
}
void ExampleAndroidHandler::OnLowMemory()
{
LOGV( "[Example]: Clearing some memory to stay alive..." );
// BigMemoryObject->Release();
}
// Input
void ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )
{
LOGV( "[Example]: Got key! %i %c", iKeyCode, iUnicodeChar );
}
void ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )
{
//LOGV( "[Example]: Touch: %i, x: %f y:, %f action:, %i.", iPointerID, fPosX, fPosY, iAction );
if ( iAction == 0 )
{
// On touch start show keyboard!
Android::ShowKeyboard();
Android::GooglePlayServices::SignIn();
//Android::GoogleGames::SubmitScore( "CgkIp8rf-fkTEAIQCQ", 1337 );
//Android::GoogleGames::UnlockAchievement( "CgkIp8rf-fkTEAIQAw" );
}
else if ( iAction == 1 )
{
// On touch up, hide keyboard...
Android::HideKeyboard();
//Android::GooglePlayServices::ShowAlert( "Test Alert!", "Test" );
//Android::GoogleGames::ShowAllLeaderboards();
//Android::GoogleGames::ShowAchievements();
}
}
<commit_msg>Notification example<commit_after>#include "ExampleAndroidHandler.h"
#include <AndroidLog.h>
#include <GooglePlayServices.h>
#include <GoogleGames.h>
#include <AppState.h>
#include <time.h>
#include "ExampleStateListener.h"
#include <Notification.h>
class SignInListener : public Android::ISignInListener
{
private:
ExampleStateListener m_StateListener;
public:
virtual void OnSignInSucceeded()
{
LOGV( "Signed in!" );
char state[] = "Hello Cloud Save!";
Android::AppState::UpdateState( 1, state, sizeof( state ) );
Android::AppState::LoadState( 1, &m_StateListener );
}
virtual void OnSignInFailed()
{
LOGE( "Sign in failed." );
}
SignInListener() { }
virtual ~SignInListener() { }
};
ExampleAndroidHandler::ExampleAndroidHandler()
{
// State variables
m_bShouldQuit = false;
m_bIsVisible = false;
m_bIsPaused = true;
// Egl
m_Display = EGL_NO_DISPLAY;
m_Surface = EGL_NO_SURFACE;
m_Context = NULL;
}
ExampleAndroidHandler::~ExampleAndroidHandler()
{
DestroyOpenGL();
}
void ExampleAndroidHandler::Run()
{
SignInListener signInListener;
Android::GooglePlayServices::SetSignInListener( &signInListener );
// Example asset read
Android::Asset* pAsset = Android::GetAssetManager().GetAsset( "test.txt" );
if ( pAsset )
{
// Create a buffer to read the content into,
// [ Size() + 1 ] for null terminator character for LOG usage
char* pBuffer = new char[ pAsset->Size() + 1 ];
// Read the buffer
pAsset->Read( pBuffer, pAsset->Size() );
// Set null terminating for LOG
pBuffer[ pAsset->Size() ] = 0;
// Delete the asset file
delete pAsset;
// Show us the file's content!
LOGV( "[Example]: File content: %s", pBuffer );
// Delete the buffer
delete [] pBuffer;
}
// Create time measurement
timespec timeNow;
clock_gettime( CLOCK_MONOTONIC, &timeNow );
uint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;
// Connect to Google Play
Android::GooglePlayServices::SignIn();
// While application is alive...
while ( !m_bShouldQuit )
{
// Handle Android events
Android::PollEvents();
// Calculate delta time
clock_gettime( CLOCK_MONOTONIC, &timeNow ); // query time now
uint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; // get time in nanoseconds
float fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; // 1 second = 1,000,000,000 nanoseconds
uPreviousTime = uNowNano; // set previous time to new time
// If not paused...
if ( !m_bIsPaused )
{
// Update logic
Update( fDeltaSeconds );
}
// If visible
if ( m_bIsVisible )
{
// Draw
Draw();
}
}
LOGV( "[Example]: Mainloop terminated." );
}
void ExampleAndroidHandler::Update( float fDeltaSeconds )
{
// Do stuff here
}
void ExampleAndroidHandler::Draw()
{
// Draw things here
glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
if ( !eglSwapBuffers( m_Display, m_Surface ) )
{
LOGE( "[Example]: eglSwapBuffers() returned error %d", eglGetError() );
}
}
bool ExampleAndroidHandler::InitOpenGL()
{
const EGLint attribs[] =
{
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLDisplay display;
EGLConfig config;
EGLint numConfigs;
EGLint format;
EGLSurface surface;
EGLContext context;
EGLint width;
EGLint height;
GLfloat ratio;
LOGV( "[Example]: Initializing context" );
if ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )
{
LOGE( "[Example]: eglGetDisplay() returned error %d", eglGetError() );
return false;
}
if ( !eglInitialize( display, 0, 0 ) )
{
LOGE( "[Example]: eglInitialize() returned error %d", eglGetError() );
return false;
}
if ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )
{
LOGE( "[Example]: eglChooseConfig() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )
{
LOGE( "[Example]: eglGetConfigAttrib() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
// Set buffer geometry using our window which is saved in Android
ANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );
if ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )
{
LOGE( "[Example]: eglCreateWindowSurface() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !( context = eglCreateContext( display, config, 0, 0 ) ) )
{
LOGE( "[Example]: eglCreateContext() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglMakeCurrent(display, surface, surface, context ) )
{
LOGE( "[Example]: eglMakeCurrent() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||
!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )
{
LOGE( "[Example]: eglQuerySurface() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
m_Display = display;
m_Surface = surface;
m_Context = context;
glDisable( GL_DITHER );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
glClearColor(0, 0, 0, 0);
glEnable( GL_CULL_FACE );
glEnable( GL_DEPTH_TEST );
return true;
}
void ExampleAndroidHandler::DestroyOpenGL()
{
if ( m_Display )
{
LOGV( "[Example]: Shutting down OpenGL" );
eglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
eglDestroyContext( m_Display, m_Context );
eglDestroySurface( m_Display, m_Surface);
eglTerminate( m_Display );
m_Display = EGL_NO_DISPLAY;
m_Surface = EGL_NO_SURFACE;
m_Context = NULL;
}
}
// Application
void ExampleAndroidHandler::OnShutdown()
{
LOGV( "[Example]: Shutting down!" );
m_bShouldQuit = true;
}
// Surface
void ExampleAndroidHandler::OnSurfaceCreated()
{
LOGV( "[Example]: Creating surface!" );
if ( InitOpenGL() == false )
{
m_bShouldQuit = true;
}
}
void ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )
{
LOGV( "[Example]: Setting viewports!" );
// Set new viewport
glViewport( 0, 0, iWidth, iHeight );
}
void ExampleAndroidHandler::OnSurfaceDestroyed()
{
LOGV( "[Example]: Destroying egl!" );
DestroyOpenGL();
}
// States
void ExampleAndroidHandler::OnPause()
{
Android::Notification notification;
notification.SetContentTitle( "New Test Title" );
notification.SetContentText( "Test Content" );
notification.SetSmallIcon( 0x7f020000 );
Android::GetNotificationManager().Notify( 500, notification );
LOGV( "[Example]: Paused!" );
m_bIsPaused = true;
}
void ExampleAndroidHandler::OnResume()
{
LOGV( "[Example]: Resumed!" );
m_bIsPaused = false;
}
void ExampleAndroidHandler::OnVisible()
{
LOGV( "[Example]: Visible!" );
m_bIsVisible = true;
}
void ExampleAndroidHandler::OnHidden()
{
LOGV( "[Example]: Hidden!" );
m_bIsVisible = false;
//Android::GooglePlayServices::SignOut();
}
void ExampleAndroidHandler::OnLowMemory()
{
LOGV( "[Example]: Clearing some memory to stay alive..." );
// BigMemoryObject->Release();
}
// Input
void ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )
{
LOGV( "[Example]: Got key! %i %c", iKeyCode, iUnicodeChar );
}
void ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )
{
//LOGV( "[Example]: Touch: %i, x: %f y:, %f action:, %i.", iPointerID, fPosX, fPosY, iAction );
if ( iAction == 0 )
{
// On touch start show keyboard!
Android::ShowKeyboard();
Android::GooglePlayServices::SignIn();
//Android::GoogleGames::SubmitScore( "CgkIp8rf-fkTEAIQCQ", 1337 );
//Android::GoogleGames::UnlockAchievement( "CgkIp8rf-fkTEAIQAw" );
}
else if ( iAction == 1 )
{
// On touch up, hide keyboard...
Android::HideKeyboard();
//Android::GooglePlayServices::ShowAlert( "Test Alert!", "Test" );
//Android::GoogleGames::ShowAllLeaderboards();
//Android::GoogleGames::ShowAchievements();
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief arango benchmark tool
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "BasicsC/common.h"
#include <stdio.h>
#include <iomanip>
#include "ArangoShell/ArangoClient.h"
#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "BasicsC/init.h"
#include "BasicsC/logging.h"
#include "BasicsC/tri-strings.h"
#include "BasicsC/string-buffer.h"
#include "BasicsC/terminal-utils.h"
#include "Logger/Logger.h"
#include "Rest/Endpoint.h"
#include "Rest/HttpRequest.h"
#include "Rest/InitialiseRest.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Benchmark/BenchmarkCounter.h"
#include "Benchmark/BenchmarkOperation.h"
#include "Benchmark/BenchmarkThread.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace triagens::arangob;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////
ArangoClient BaseClient;
////////////////////////////////////////////////////////////////////////////////
/// @brief started counter
////////////////////////////////////////////////////////////////////////////////
static volatile int Started = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for start counter
////////////////////////////////////////////////////////////////////////////////
Mutex StartMutex;
////////////////////////////////////////////////////////////////////////////////
/// @brief send asychronous requests
////////////////////////////////////////////////////////////////////////////////
static bool Async = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations in one batch
////////////////////////////////////////////////////////////////////////////////
static int BatchSize = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief collection to use
////////////////////////////////////////////////////////////////////////////////
static string Collection = "ArangoBenchmark";
////////////////////////////////////////////////////////////////////////////////
/// @brief complexity parameter for tests
////////////////////////////////////////////////////////////////////////////////
static uint64_t Complexity = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief concurrency
////////////////////////////////////////////////////////////////////////////////
static int Concurrency = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief use a startup delay
////////////////////////////////////////////////////////////////////////////////
static bool Delay = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief use HTTP keep-alive
////////////////////////////////////////////////////////////////////////////////
static bool KeepAlive = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations to perform
////////////////////////////////////////////////////////////////////////////////
static int Operations = 1000;
////////////////////////////////////////////////////////////////////////////////
/// @brief display progress
////////////////////////////////////////////////////////////////////////////////
static bool Progress = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief test case to use
////////////////////////////////////////////////////////////////////////////////
static string TestCase = "version";
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief includes all the test cases
////////////////////////////////////////////////////////////////////////////////
#include "Benchmark/test-cases.h"
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief update the number of ready threads. this is a callback function
/// that is called by each thread after it is created
////////////////////////////////////////////////////////////////////////////////
static void UpdateStartCounter () {
MUTEX_LOCKER(StartMutex);
++Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the value of the number of started threads counter
////////////////////////////////////////////////////////////////////////////////
static int GetStartCounter () {
MUTEX_LOCKER(StartMutex);
return Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief print a status line (if ! quiet)
////////////////////////////////////////////////////////////////////////////////
static void Status (const string& value) {
if (! BaseClient.quiet()) {
cout << value << endl;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////
static void ParseProgramOptions (int argc, char* argv[]) {
ProgramOptionsDescription description("STANDARD options");
description
("async", &Async, "send asychronous requests")
("concurrency", &Concurrency, "number of parallel connections")
("requests", &Operations, "total number of operations")
("batch-size", &BatchSize, "number of operations in one batch (0 disables batching")
("keep-alive", &KeepAlive, "use HTTP keep-alive")
("collection", &Collection, "collection name to use in tests")
("test-case", &TestCase, "test case to use")
("complexity", &Complexity, "complexity parameter for the test")
("delay", &Delay, "use a startup delay (necessary only when run in series)")
("progress", &Progress, "show progress")
;
BaseClient.setupGeneral(description);
BaseClient.setupServer(description);
vector<string> arguments;
description.arguments(&arguments);
ProgramOptions options;
BaseClient.parse(options, description, argc, argv, "arangob.conf");
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup arangoimp
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
TRIAGENS_C_INITIALISE(argc, argv);
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseLogging(false);
BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());
// .............................................................................
// parse the program options
// .............................................................................
ParseProgramOptions(argc, argv);
// .............................................................................
// set-up client connection
// .............................................................................
BaseClient.createEndpoint();
if (BaseClient.endpointServer() == 0) {
LOGGER_FATAL_AND_EXIT("invalid value for --server.endpoint ('" << BaseClient.endpointString() << "')");
}
BenchmarkOperation* testCase = GetTestCase(TestCase);
if (testCase == 0) {
LOGGER_FATAL_AND_EXIT("invalid test case name " << TestCase);
return EXIT_FAILURE; // will not be reached
}
Status("starting threads...");
BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);
ConditionVariable startCondition;
vector<Endpoint*> endpoints;
vector<BenchmarkThread*> threads;
const double stepSize = (double) Operations / (double) Concurrency;
int64_t realStep = (int64_t) stepSize;
if (stepSize - (double) ((int64_t) stepSize) > 0.0) {
realStep++;
}
if (realStep % 1000 != 0) {
realStep += 1000 - (realStep % 1000);
}
// add some more offset we don't get into trouble with threads of different speed
realStep += 10000;
// start client threads
for (int i = 0; i < Concurrency; ++i) {
Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());
endpoints.push_back(endpoint);
BenchmarkThread* thread = new BenchmarkThread(testCase,
&startCondition,
&UpdateStartCounter,
i,
(unsigned long) BatchSize,
&operationsCounter,
endpoint,
BaseClient.databaseName(),
BaseClient.username(),
BaseClient.password(),
BaseClient.requestTimeout(),
BaseClient.connectTimeout(),
KeepAlive,
Async);
threads.push_back(thread);
thread->setOffset(i * realStep);
thread->start();
}
// give all threads a chance to start so they will not miss the broadcast
while (GetStartCounter() < Concurrency) {
usleep(5000);
}
if (Delay) {
Status("sleeping (startup delay)...");
sleep(10);
}
Status("executing tests...");
Timing timer(Timing::TI_WALLCLOCK);
// broadcast the start signal to all threads
{
ConditionLocker guard(&startCondition);
guard.broadcast();
}
const size_t stepValue = (Operations / 20);
size_t nextReportValue = stepValue;
if (nextReportValue < 100) {
nextReportValue = 100;
}
while (1) {
const size_t numOperations = operationsCounter.getValue();
if (numOperations >= (size_t) Operations) {
break;
}
if (Progress && numOperations >= nextReportValue) {
LOGGER_INFO("number of operations: " << nextReportValue);
nextReportValue += stepValue;
}
usleep(20000);
}
double time = ((double) timer.time()) / 1000000.0;
double requestTime = 0.0;
for (int i = 0; i < Concurrency; ++i) {
requestTime += threads[i]->getTime();
}
size_t failures = operationsCounter.failures();
cout << endl;
cout << "Total number of operations: " << Operations <<
", keep alive: " << (KeepAlive ? "yes" : "no") <<
", async: " << (Async ? "yes" : "no") <<
", batch size: " << BatchSize <<
", concurrency level (threads): " << Concurrency <<
endl;
cout << "Test case: " << TestCase <<
", complexity: " << Complexity <<
", database: '" << BaseClient.databaseName() <<
"', collection: '" << Collection << "'" <<
endl;
cout << "Total request/response duration (sum of all threads): " << fixed << requestTime << " s" << endl;
cout << "Request/response duration (per thread): " << fixed << (requestTime / (double) Concurrency) << " s" << endl;
cout << "Time needed per operation: " << fixed << (time / Operations) << " s" << endl;
cout << "Time needed per operation per thread: " << fixed << (time / (double) Operations * (double) Concurrency) << " s" << endl;
cout << "Operations per second rate: " << fixed << ((double) Operations / time) << endl;
cout << "Elapsed time since start: " << fixed << time << " s" << endl << endl;
if (failures > 0) {
cerr << "WARNING: " << failures << " arangob request(s) failed!!" << endl;
}
testCase->tearDown();
for (int i = 0; i < Concurrency; ++i) {
threads[i]->join();
delete threads[i];
delete endpoints[i];
}
delete testCase;
TRIAGENS_REST_SHUTDOWN;
return (failures == 0) ? EXIT_SUCCESS : 2;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>fix typo in help text<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief arango benchmark tool
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "BasicsC/common.h"
#include <stdio.h>
#include <iomanip>
#include "ArangoShell/ArangoClient.h"
#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "BasicsC/init.h"
#include "BasicsC/logging.h"
#include "BasicsC/tri-strings.h"
#include "BasicsC/string-buffer.h"
#include "BasicsC/terminal-utils.h"
#include "Logger/Logger.h"
#include "Rest/Endpoint.h"
#include "Rest/HttpRequest.h"
#include "Rest/InitialiseRest.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Benchmark/BenchmarkCounter.h"
#include "Benchmark/BenchmarkOperation.h"
#include "Benchmark/BenchmarkThread.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace triagens::arangob;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////
ArangoClient BaseClient;
////////////////////////////////////////////////////////////////////////////////
/// @brief started counter
////////////////////////////////////////////////////////////////////////////////
static volatile int Started = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for start counter
////////////////////////////////////////////////////////////////////////////////
Mutex StartMutex;
////////////////////////////////////////////////////////////////////////////////
/// @brief send asychronous requests
////////////////////////////////////////////////////////////////////////////////
static bool Async = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations in one batch
////////////////////////////////////////////////////////////////////////////////
static int BatchSize = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief collection to use
////////////////////////////////////////////////////////////////////////////////
static string Collection = "ArangoBenchmark";
////////////////////////////////////////////////////////////////////////////////
/// @brief complexity parameter for tests
////////////////////////////////////////////////////////////////////////////////
static uint64_t Complexity = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief concurrency
////////////////////////////////////////////////////////////////////////////////
static int Concurrency = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief use a startup delay
////////////////////////////////////////////////////////////////////////////////
static bool Delay = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief use HTTP keep-alive
////////////////////////////////////////////////////////////////////////////////
static bool KeepAlive = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations to perform
////////////////////////////////////////////////////////////////////////////////
static int Operations = 1000;
////////////////////////////////////////////////////////////////////////////////
/// @brief display progress
////////////////////////////////////////////////////////////////////////////////
static bool Progress = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief test case to use
////////////////////////////////////////////////////////////////////////////////
static string TestCase = "version";
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief includes all the test cases
////////////////////////////////////////////////////////////////////////////////
#include "Benchmark/test-cases.h"
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief update the number of ready threads. this is a callback function
/// that is called by each thread after it is created
////////////////////////////////////////////////////////////////////////////////
static void UpdateStartCounter () {
MUTEX_LOCKER(StartMutex);
++Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the value of the number of started threads counter
////////////////////////////////////////////////////////////////////////////////
static int GetStartCounter () {
MUTEX_LOCKER(StartMutex);
return Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief print a status line (if ! quiet)
////////////////////////////////////////////////////////////////////////////////
static void Status (const string& value) {
if (! BaseClient.quiet()) {
cout << value << endl;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////
static void ParseProgramOptions (int argc, char* argv[]) {
ProgramOptionsDescription description("STANDARD options");
description
("async", &Async, "send asychronous requests")
("concurrency", &Concurrency, "number of parallel connections")
("requests", &Operations, "total number of operations")
("batch-size", &BatchSize, "number of operations in one batch (0 disables batching)")
("keep-alive", &KeepAlive, "use HTTP keep-alive")
("collection", &Collection, "collection name to use in tests")
("test-case", &TestCase, "test case to use")
("complexity", &Complexity, "complexity parameter for the test")
("delay", &Delay, "use a startup delay (necessary only when run in series)")
("progress", &Progress, "show progress")
;
BaseClient.setupGeneral(description);
BaseClient.setupServer(description);
vector<string> arguments;
description.arguments(&arguments);
ProgramOptions options;
BaseClient.parse(options, description, argc, argv, "arangob.conf");
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup arangoimp
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
TRIAGENS_C_INITIALISE(argc, argv);
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseLogging(false);
BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());
// .............................................................................
// parse the program options
// .............................................................................
ParseProgramOptions(argc, argv);
// .............................................................................
// set-up client connection
// .............................................................................
BaseClient.createEndpoint();
if (BaseClient.endpointServer() == 0) {
LOGGER_FATAL_AND_EXIT("invalid value for --server.endpoint ('" << BaseClient.endpointString() << "')");
}
BenchmarkOperation* testCase = GetTestCase(TestCase);
if (testCase == 0) {
LOGGER_FATAL_AND_EXIT("invalid test case name " << TestCase);
return EXIT_FAILURE; // will not be reached
}
Status("starting threads...");
BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);
ConditionVariable startCondition;
vector<Endpoint*> endpoints;
vector<BenchmarkThread*> threads;
const double stepSize = (double) Operations / (double) Concurrency;
int64_t realStep = (int64_t) stepSize;
if (stepSize - (double) ((int64_t) stepSize) > 0.0) {
realStep++;
}
if (realStep % 1000 != 0) {
realStep += 1000 - (realStep % 1000);
}
// add some more offset we don't get into trouble with threads of different speed
realStep += 10000;
// start client threads
for (int i = 0; i < Concurrency; ++i) {
Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());
endpoints.push_back(endpoint);
BenchmarkThread* thread = new BenchmarkThread(testCase,
&startCondition,
&UpdateStartCounter,
i,
(unsigned long) BatchSize,
&operationsCounter,
endpoint,
BaseClient.databaseName(),
BaseClient.username(),
BaseClient.password(),
BaseClient.requestTimeout(),
BaseClient.connectTimeout(),
KeepAlive,
Async);
threads.push_back(thread);
thread->setOffset(i * realStep);
thread->start();
}
// give all threads a chance to start so they will not miss the broadcast
while (GetStartCounter() < Concurrency) {
usleep(5000);
}
if (Delay) {
Status("sleeping (startup delay)...");
sleep(10);
}
Status("executing tests...");
Timing timer(Timing::TI_WALLCLOCK);
// broadcast the start signal to all threads
{
ConditionLocker guard(&startCondition);
guard.broadcast();
}
const size_t stepValue = (Operations / 20);
size_t nextReportValue = stepValue;
if (nextReportValue < 100) {
nextReportValue = 100;
}
while (1) {
const size_t numOperations = operationsCounter.getValue();
if (numOperations >= (size_t) Operations) {
break;
}
if (Progress && numOperations >= nextReportValue) {
LOGGER_INFO("number of operations: " << nextReportValue);
nextReportValue += stepValue;
}
usleep(20000);
}
double time = ((double) timer.time()) / 1000000.0;
double requestTime = 0.0;
for (int i = 0; i < Concurrency; ++i) {
requestTime += threads[i]->getTime();
}
size_t failures = operationsCounter.failures();
cout << endl;
cout << "Total number of operations: " << Operations <<
", keep alive: " << (KeepAlive ? "yes" : "no") <<
", async: " << (Async ? "yes" : "no") <<
", batch size: " << BatchSize <<
", concurrency level (threads): " << Concurrency <<
endl;
cout << "Test case: " << TestCase <<
", complexity: " << Complexity <<
", database: '" << BaseClient.databaseName() <<
"', collection: '" << Collection << "'" <<
endl;
cout << "Total request/response duration (sum of all threads): " << fixed << requestTime << " s" << endl;
cout << "Request/response duration (per thread): " << fixed << (requestTime / (double) Concurrency) << " s" << endl;
cout << "Time needed per operation: " << fixed << (time / Operations) << " s" << endl;
cout << "Time needed per operation per thread: " << fixed << (time / (double) Operations * (double) Concurrency) << " s" << endl;
cout << "Operations per second rate: " << fixed << ((double) Operations / time) << endl;
cout << "Elapsed time since start: " << fixed << time << " s" << endl << endl;
if (failures > 0) {
cerr << "WARNING: " << failures << " arangob request(s) failed!!" << endl;
}
testCase->tearDown();
for (int i = 0; i < Concurrency; ++i) {
threads[i]->join();
delete threads[i];
delete endpoints[i];
}
delete testCase;
TRIAGENS_REST_SHUTDOWN;
return (failures == 0) ? EXIT_SUCCESS : 2;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
"http://www.example.com");
}
};
// http://crbug.com/55642 - failing on XP.
#if defined (OS_WIN)
#define MAYBE_InstallAndUninstall FAILS_InstallAndUninstall
#else
#define MAYBE_InstallAndUninstall InstallAndUninstall
#endif
IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,
MAYBE_InstallAndUninstall) {
host_resolver()->AddRule("www.example.com", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
std::string base_url = base::StringPrintf(
"http://www.example.com:%u/files/extensions/",
test_server()->host_port_pair().port());
std::string testing_install_base_url = base_url;
testing_install_base_url += "good.crx";
InstallFunction::SetTestingInstallBaseUrl(testing_install_base_url.c_str());
std::string page_url = base_url;
page_url += "api_test/extension_gallery_install/test.html";
ASSERT_TRUE(RunPageTest(page_url.c_str()));
}
<commit_msg>Disables ExtensionGalleryInstallApiTest.InstallAndUninstall on Windows<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
"http://www.example.com");
}
};
// http://crbug.com/55642 - failing on XP.
#if defined (OS_WIN)
#define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall
#else
#define MAYBE_InstallAndUninstall InstallAndUninstall
#endif
IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,
MAYBE_InstallAndUninstall) {
host_resolver()->AddRule("www.example.com", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
std::string base_url = base::StringPrintf(
"http://www.example.com:%u/files/extensions/",
test_server()->host_port_pair().port());
std::string testing_install_base_url = base_url;
testing_install_base_url += "good.crx";
InstallFunction::SetTestingInstallBaseUrl(testing_install_base_url.c_str());
std::string page_url = base_url;
page_url += "api_test/extension_gallery_install/test.html";
ASSERT_TRUE(RunPageTest(page_url.c_str()));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/firefox_importer_unittest_utils.h"
#include "base/bind.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/importer/firefox_importer_utils.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_descriptors.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_switches.h"
#include "testing/multiprocess_func_list.h"
#define IPC_MESSAGE_IMPL
#include "chrome/browser/importer/firefox_importer_unittest_messages_internal.h"
namespace {
// Name of IPC Channel to use for Server<-> Child Communications.
const char kTestChannelID[] = "T1";
// Launch the child process:
// |nss_path| - path to the NSS directory holding the decryption libraries.
// |channel| - IPC Channel to use for communication.
// |handle| - On return, the process handle to use to communicate with the
// child.
bool LaunchNSSDecrypterChildProcess(const FilePath& nss_path,
IPC::Channel* channel, base::ProcessHandle* handle) {
CommandLine cl(*CommandLine::ForCurrentProcess());
cl.AppendSwitchASCII(switches::kTestChildProcess, "NSSDecrypterChildProcess");
// Set env variable needed for FF encryption libs to load.
// See "chrome/browser/importer/nss_decryptor_mac.mm" for an explanation of
// why we need this.
base::EnvironmentVector env;
std::pair<std::string, std::string> dyld_override;
dyld_override.first = "DYLD_FALLBACK_LIBRARY_PATH";
dyld_override.second = nss_path.value();
env.push_back(dyld_override);
int ipcfd = channel->TakeClientFileDescriptor();
if (ipcfd == -1)
return false;
file_util::ScopedFD client_file_descriptor_closer(&ipcfd);
base::FileHandleMappingVector fds_to_map;
fds_to_map.push_back(std::pair<int,int>(ipcfd, kPrimaryIPCChannel + 3));
bool debug_on_start = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDebugChildren);
base::LaunchOptions options;
options.environ = &env;
options.fds_to_remap = &fds_to_map;
options.wait = debug_on_start;
return base::LaunchProcess(cl.argv(), options, handle);
}
} // namespace
//----------------------- Server --------------------
// Class to communicate on the server side of the IPC Channel.
// Method calls are sent over IPC and replies are read back into class
// variables.
// This class needs to be called on a single thread.
class FFDecryptorServerChannelListener : public IPC::Channel::Listener {
public:
FFDecryptorServerChannelListener()
: got_result(false), sender_(NULL) {}
void SetSender(IPC::Message::Sender* sender) {
sender_ = sender;
}
void OnInitDecryptorResponse(bool result) {
DCHECK(!got_result);
result_bool = result;
got_result = true;
MessageLoop::current()->Quit();
}
void OnDecryptedTextResonse(const string16& decrypted_text) {
DCHECK(!got_result);
result_string = decrypted_text;
got_result = true;
MessageLoop::current()->Quit();
}
void QuitClient() {
if (sender_)
sender_->Send(new Msg_Decryptor_Quit());
}
virtual bool OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(FFDecryptorServerChannelListener, msg)
IPC_MESSAGE_HANDLER(Msg_Decryptor_InitReturnCode, OnInitDecryptorResponse)
IPC_MESSAGE_HANDLER(Msg_Decryptor_Response, OnDecryptedTextResonse)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
// If an error occured, just kill the message Loop.
virtual void OnChannelError() {
got_result = false;
MessageLoop::current()->Quit();
}
// Results of IPC calls.
string16 result_string;
bool result_bool;
// True if IPC call succeeded and data in above variables is valid.
bool got_result;
private:
IPC::Message::Sender* sender_; // weak
};
FFUnitTestDecryptorProxy::FFUnitTestDecryptorProxy()
: child_process_(0) {
}
bool FFUnitTestDecryptorProxy::Setup(const FilePath& nss_path) {
// Create a new message loop and spawn the child process.
message_loop_.reset(new MessageLoopForIO());
listener_.reset(new FFDecryptorServerChannelListener());
channel_.reset(new IPC::Channel(kTestChannelID,
IPC::Channel::MODE_SERVER,
listener_.get()));
CHECK(channel_->Connect());
listener_->SetSender(channel_.get());
// Spawn child and set up sync IPC connection.
bool ret = LaunchNSSDecrypterChildProcess(nss_path,
channel_.get(),
&child_process_);
return ret && (child_process_ != 0);
}
FFUnitTestDecryptorProxy::~FFUnitTestDecryptorProxy() {
listener_->QuitClient();
channel_->Close();
if (child_process_) {
base::WaitForSingleProcess(child_process_, 5000);
base::CloseProcessHandle(child_process_);
}
}
// A message_loop task that quits the message loop when invoked, setting cancel
// causes the task to do nothing when invoked.
class CancellableQuitMsgLoop : public base::RefCounted<CancellableQuitMsgLoop> {
public:
CancellableQuitMsgLoop() : cancelled_(false) {}
void QuitNow() {
if (!cancelled_)
MessageLoop::current()->Quit();
}
bool cancelled_;
};
// Spin until either a client response arrives or a timeout occurs.
bool FFUnitTestDecryptorProxy::WaitForClientResponse() {
// What we're trying to do here is to wait for an RPC message to go over the
// wire and the client to reply. If the client does not reply by a given
// timeout we kill the message loop.
// The way we do this is to post a CancellableQuitMsgLoop for 3 seconds in
// the future and cancel it if an RPC message comes back earlier.
// This relies on the IPC listener class to quit the message loop itself when
// a message comes in.
scoped_refptr<CancellableQuitMsgLoop> quit_task(
new CancellableQuitMsgLoop());
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&CancellableQuitMsgLoop::QuitNow, quit_task.get()),
TestTimeouts::action_max_timeout_ms());
message_loop_->Run();
bool ret = !quit_task->cancelled_;
quit_task->cancelled_ = false;
return ret;
}
bool FFUnitTestDecryptorProxy::DecryptorInit(const FilePath& dll_path,
const FilePath& db_path) {
channel_->Send(new Msg_Decryptor_Init(dll_path, db_path));
bool ok = WaitForClientResponse();
if (ok && listener_->got_result) {
listener_->got_result = false;
return listener_->result_bool;
}
return false;
}
string16 FFUnitTestDecryptorProxy::Decrypt(const std::string& crypt) {
channel_->Send(new Msg_Decrypt(crypt));
bool ok = WaitForClientResponse();
if (ok && listener_->got_result) {
listener_->got_result = false;
return listener_->result_string;
}
return string16();
}
//---------------------------- Child Process -----------------------
// Class to listen on the client side of the ipc channel, it calls through
// to the NSSDecryptor and sends back a reply.
class FFDecryptorClientChannelListener : public IPC::Channel::Listener {
public:
FFDecryptorClientChannelListener()
: sender_(NULL) {}
void SetSender(IPC::Message::Sender* sender) {
sender_ = sender;
}
void OnDecryptor_Init(FilePath dll_path, FilePath db_path) {
bool ret = decryptor_.Init(dll_path, db_path);
sender_->Send(new Msg_Decryptor_InitReturnCode(ret));
}
void OnDecrypt(std::string crypt) {
string16 unencrypted_str = decryptor_.Decrypt(crypt);
sender_->Send(new Msg_Decryptor_Response(unencrypted_str));
}
void OnQuitRequest() {
MessageLoop::current()->Quit();
}
virtual bool OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(FFDecryptorClientChannelListener, msg)
IPC_MESSAGE_HANDLER(Msg_Decryptor_Init, OnDecryptor_Init)
IPC_MESSAGE_HANDLER(Msg_Decrypt, OnDecrypt)
IPC_MESSAGE_HANDLER(Msg_Decryptor_Quit, OnQuitRequest)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
virtual void OnChannelError() {
MessageLoop::current()->Quit();
}
private:
NSSDecryptor decryptor_;
IPC::Message::Sender* sender_;
};
// Entry function in child process.
MULTIPROCESS_TEST_MAIN(NSSDecrypterChildProcess) {
MessageLoopForIO main_message_loop;
FFDecryptorClientChannelListener listener;
IPC::Channel channel(kTestChannelID, IPC::Channel::MODE_CLIENT, &listener);
CHECK(channel.Connect());
listener.SetSender(&channel);
// run message loop
MessageLoop::current()->Run();
return 0;
}
<commit_msg>Update uses of TimeDelta in mac firefox importer test code.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/firefox_importer_unittest_utils.h"
#include "base/bind.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/importer/firefox_importer_utils.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_descriptors.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_switches.h"
#include "testing/multiprocess_func_list.h"
#define IPC_MESSAGE_IMPL
#include "chrome/browser/importer/firefox_importer_unittest_messages_internal.h"
namespace {
// Name of IPC Channel to use for Server<-> Child Communications.
const char kTestChannelID[] = "T1";
// Launch the child process:
// |nss_path| - path to the NSS directory holding the decryption libraries.
// |channel| - IPC Channel to use for communication.
// |handle| - On return, the process handle to use to communicate with the
// child.
bool LaunchNSSDecrypterChildProcess(const FilePath& nss_path,
IPC::Channel* channel, base::ProcessHandle* handle) {
CommandLine cl(*CommandLine::ForCurrentProcess());
cl.AppendSwitchASCII(switches::kTestChildProcess, "NSSDecrypterChildProcess");
// Set env variable needed for FF encryption libs to load.
// See "chrome/browser/importer/nss_decryptor_mac.mm" for an explanation of
// why we need this.
base::EnvironmentVector env;
std::pair<std::string, std::string> dyld_override;
dyld_override.first = "DYLD_FALLBACK_LIBRARY_PATH";
dyld_override.second = nss_path.value();
env.push_back(dyld_override);
int ipcfd = channel->TakeClientFileDescriptor();
if (ipcfd == -1)
return false;
file_util::ScopedFD client_file_descriptor_closer(&ipcfd);
base::FileHandleMappingVector fds_to_map;
fds_to_map.push_back(std::pair<int,int>(ipcfd, kPrimaryIPCChannel + 3));
bool debug_on_start = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDebugChildren);
base::LaunchOptions options;
options.environ = &env;
options.fds_to_remap = &fds_to_map;
options.wait = debug_on_start;
return base::LaunchProcess(cl.argv(), options, handle);
}
} // namespace
//----------------------- Server --------------------
// Class to communicate on the server side of the IPC Channel.
// Method calls are sent over IPC and replies are read back into class
// variables.
// This class needs to be called on a single thread.
class FFDecryptorServerChannelListener : public IPC::Channel::Listener {
public:
FFDecryptorServerChannelListener()
: got_result(false), sender_(NULL) {}
void SetSender(IPC::Message::Sender* sender) {
sender_ = sender;
}
void OnInitDecryptorResponse(bool result) {
DCHECK(!got_result);
result_bool = result;
got_result = true;
MessageLoop::current()->Quit();
}
void OnDecryptedTextResonse(const string16& decrypted_text) {
DCHECK(!got_result);
result_string = decrypted_text;
got_result = true;
MessageLoop::current()->Quit();
}
void QuitClient() {
if (sender_)
sender_->Send(new Msg_Decryptor_Quit());
}
virtual bool OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(FFDecryptorServerChannelListener, msg)
IPC_MESSAGE_HANDLER(Msg_Decryptor_InitReturnCode, OnInitDecryptorResponse)
IPC_MESSAGE_HANDLER(Msg_Decryptor_Response, OnDecryptedTextResonse)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
// If an error occured, just kill the message Loop.
virtual void OnChannelError() {
got_result = false;
MessageLoop::current()->Quit();
}
// Results of IPC calls.
string16 result_string;
bool result_bool;
// True if IPC call succeeded and data in above variables is valid.
bool got_result;
private:
IPC::Message::Sender* sender_; // weak
};
FFUnitTestDecryptorProxy::FFUnitTestDecryptorProxy()
: child_process_(0) {
}
bool FFUnitTestDecryptorProxy::Setup(const FilePath& nss_path) {
// Create a new message loop and spawn the child process.
message_loop_.reset(new MessageLoopForIO());
listener_.reset(new FFDecryptorServerChannelListener());
channel_.reset(new IPC::Channel(kTestChannelID,
IPC::Channel::MODE_SERVER,
listener_.get()));
CHECK(channel_->Connect());
listener_->SetSender(channel_.get());
// Spawn child and set up sync IPC connection.
bool ret = LaunchNSSDecrypterChildProcess(nss_path,
channel_.get(),
&child_process_);
return ret && (child_process_ != 0);
}
FFUnitTestDecryptorProxy::~FFUnitTestDecryptorProxy() {
listener_->QuitClient();
channel_->Close();
if (child_process_) {
base::WaitForSingleProcess(child_process_, 5000);
base::CloseProcessHandle(child_process_);
}
}
// A message_loop task that quits the message loop when invoked, setting cancel
// causes the task to do nothing when invoked.
class CancellableQuitMsgLoop : public base::RefCounted<CancellableQuitMsgLoop> {
public:
CancellableQuitMsgLoop() : cancelled_(false) {}
void QuitNow() {
if (!cancelled_)
MessageLoop::current()->Quit();
}
bool cancelled_;
};
// Spin until either a client response arrives or a timeout occurs.
bool FFUnitTestDecryptorProxy::WaitForClientResponse() {
// What we're trying to do here is to wait for an RPC message to go over the
// wire and the client to reply. If the client does not reply by a given
// timeout we kill the message loop.
// The way we do this is to post a CancellableQuitMsgLoop for 3 seconds in
// the future and cancel it if an RPC message comes back earlier.
// This relies on the IPC listener class to quit the message loop itself when
// a message comes in.
scoped_refptr<CancellableQuitMsgLoop> quit_task(
new CancellableQuitMsgLoop());
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&CancellableQuitMsgLoop::QuitNow, quit_task.get()),
TestTimeouts::action_max_timeout());
message_loop_->Run();
bool ret = !quit_task->cancelled_;
quit_task->cancelled_ = false;
return ret;
}
bool FFUnitTestDecryptorProxy::DecryptorInit(const FilePath& dll_path,
const FilePath& db_path) {
channel_->Send(new Msg_Decryptor_Init(dll_path, db_path));
bool ok = WaitForClientResponse();
if (ok && listener_->got_result) {
listener_->got_result = false;
return listener_->result_bool;
}
return false;
}
string16 FFUnitTestDecryptorProxy::Decrypt(const std::string& crypt) {
channel_->Send(new Msg_Decrypt(crypt));
bool ok = WaitForClientResponse();
if (ok && listener_->got_result) {
listener_->got_result = false;
return listener_->result_string;
}
return string16();
}
//---------------------------- Child Process -----------------------
// Class to listen on the client side of the ipc channel, it calls through
// to the NSSDecryptor and sends back a reply.
class FFDecryptorClientChannelListener : public IPC::Channel::Listener {
public:
FFDecryptorClientChannelListener()
: sender_(NULL) {}
void SetSender(IPC::Message::Sender* sender) {
sender_ = sender;
}
void OnDecryptor_Init(FilePath dll_path, FilePath db_path) {
bool ret = decryptor_.Init(dll_path, db_path);
sender_->Send(new Msg_Decryptor_InitReturnCode(ret));
}
void OnDecrypt(std::string crypt) {
string16 unencrypted_str = decryptor_.Decrypt(crypt);
sender_->Send(new Msg_Decryptor_Response(unencrypted_str));
}
void OnQuitRequest() {
MessageLoop::current()->Quit();
}
virtual bool OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(FFDecryptorClientChannelListener, msg)
IPC_MESSAGE_HANDLER(Msg_Decryptor_Init, OnDecryptor_Init)
IPC_MESSAGE_HANDLER(Msg_Decrypt, OnDecrypt)
IPC_MESSAGE_HANDLER(Msg_Decryptor_Quit, OnQuitRequest)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
virtual void OnChannelError() {
MessageLoop::current()->Quit();
}
private:
NSSDecryptor decryptor_;
IPC::Message::Sender* sender_;
};
// Entry function in child process.
MULTIPROCESS_TEST_MAIN(NSSDecrypterChildProcess) {
MessageLoopForIO main_message_loop;
FFDecryptorClientChannelListener listener;
IPC::Channel channel(kTestChannelID, IPC::Channel::MODE_CLIENT, &listener);
CHECK(channel.Connect());
listener.SetSender(&channel);
// run message loop
MessageLoop::current()->Run();
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2007-07-06 06:48:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif
#ifndef CONNECTIVITY_STDTYPEDEFS_HXX
#include "connectivity/StdTypeDefs.hxx"
#endif
namespace connectivity
{
//**************************************************************
//************ Class: ODatabaseMetaDataResultSetMetaData
//**************************************************************
typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> ODatabaseMetaResultSetMetaData_BASE;
class ODatabaseMetaDataResultSetMetaData : public ODatabaseMetaResultSetMetaData_BASE
{
TIntVector m_vMapping; // when not every column is needed
::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;
sal_Int32 m_nColCount;
protected:
virtual ~ODatabaseMetaDataResultSetMetaData();
public:
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
ODatabaseMetaDataResultSetMetaData( )
: m_nColCount(0)
{
}
/// Avoid ambigous cast error from the compiler.
inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
{ return this; }
virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// methods to set the right column mapping
void setColumnPrivilegesMap();
void setColumnMap();
void setColumnsMap();
void setTableNameMap();
void setTablesMap();
void setProcedureColumnsMap();
void setPrimaryKeysMap();
void setIndexInfoMap();
void setTablePrivilegesMap();
void setCrossReferenceMap();
void setTypeInfoMap();
void setProcedureNameMap();
void setProceduresMap();
void setTableTypes();
void setBestRowIdentifierMap() { setVersionColumnsMap();}
void setVersionColumnsMap();
void setExportedKeysMap() { setCrossReferenceMap(); }
void setImportedKeysMap() { setCrossReferenceMap(); }
void setCatalogsMap();
void setSchemasMap();
};
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.6.122); FILE MERGED 2008/04/01 15:09:05 thb 1.6.122.3: #i85898# Stripping all external header guards 2008/04/01 10:53:16 thb 1.6.122.2: #i85898# Stripping all external header guards 2008/03/28 15:24:04 rt 1.6.122.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#include <cppuhelper/implbase1.hxx>
#ifndef _VECTOR_
#include <vector>
#endif
#include "FDatabaseMetaDataResultSet.hxx"
#include "OColumn.hxx"
#include "connectivity/StdTypeDefs.hxx"
namespace connectivity
{
//**************************************************************
//************ Class: ODatabaseMetaDataResultSetMetaData
//**************************************************************
typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> ODatabaseMetaResultSetMetaData_BASE;
class ODatabaseMetaDataResultSetMetaData : public ODatabaseMetaResultSetMetaData_BASE
{
TIntVector m_vMapping; // when not every column is needed
::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;
sal_Int32 m_nColCount;
protected:
virtual ~ODatabaseMetaDataResultSetMetaData();
public:
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
ODatabaseMetaDataResultSetMetaData( )
: m_nColCount(0)
{
}
/// Avoid ambigous cast error from the compiler.
inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
{ return this; }
virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// methods to set the right column mapping
void setColumnPrivilegesMap();
void setColumnMap();
void setColumnsMap();
void setTableNameMap();
void setTablesMap();
void setProcedureColumnsMap();
void setPrimaryKeysMap();
void setIndexInfoMap();
void setTablePrivilegesMap();
void setCrossReferenceMap();
void setTypeInfoMap();
void setProcedureNameMap();
void setProceduresMap();
void setTableTypes();
void setBestRowIdentifierMap() { setVersionColumnsMap();}
void setVersionColumnsMap();
void setExportedKeysMap() { setCrossReferenceMap(); }
void setImportedKeysMap() { setCrossReferenceMap(); }
void setCatalogsMap();
void setSchemasMap();
};
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include <boost/algorithm/string/predicate.hpp>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/tests/testProxy.h"
#include "joynr/MessagingSettings.h"
#include "joynr/MulticastSubscriptionQos.h"
#include "joynr/OnChangeSubscriptionQos.h"
#include "joynr/tests/testAbstractProvider.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/BrokerUrl.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockLocationUpdatedSelectiveFilter.h"
#include "tests/mock/MockSubscriptionListener.h"
#include "tests/utils/MyTestProvider.h"
#include "tests/utils/PtrUtils.h"
using namespace ::testing;
using namespace joynr;
static const std::string messagingPropertiesPersistenceFileName1(
"End2EndBroadcastTest-runtime1-joynr.persist");
static const std::string messagingPropertiesPersistenceFileName2(
"End2EndBroadcastTest-runtime2-joynr.persist");
namespace joynr {
class End2EndBroadcastTestBase : public TestWithParam< std::tuple<std::string, std::string> > {
public:
std::shared_ptr<JoynrClusterControllerRuntime> runtime1;
std::shared_ptr<JoynrClusterControllerRuntime> runtime2;
std::string baseUuid;
std::string uuid;
std::string domainName;
Semaphore semaphore;
Semaphore altSemaphore;
joynr::tests::TestLocationUpdateSelectiveBroadcastFilterParameters filterParameters;
std::shared_ptr<MockLocationUpdatedSelectiveFilter> filter;
std::uint16_t registerProviderWait;
std::uint16_t subscribeToAttributeWait;
std::uint16_t subscribeToBroadcastWait;
joynr::types::Localisation::GpsLocation gpsLocation;
joynr::types::Localisation::GpsLocation gpsLocation2;
joynr::types::Localisation::GpsLocation gpsLocation3;
joynr::types::Localisation::GpsLocation gpsLocation4;
End2EndBroadcastTestBase() :
runtime1(),
runtime2(),
baseUuid(util::createUuid()),
uuid( "_" + baseUuid.substr(1, baseUuid.length()-2)),
domainName("cppEnd2EndBroadcastTest_Domain" + uuid),
semaphore(0),
altSemaphore(0),
filter(std::make_shared<MockLocationUpdatedSelectiveFilter>()),
registerProviderWait(1000),
subscribeToAttributeWait(2000),
subscribeToBroadcastWait(2000),
gpsLocation(types::Localisation::GpsLocation()),
gpsLocation2(types::Localisation::GpsLocation(
9.0,
51.0,
508.0,
types::Localisation::GpsFixEnum::MODE2D,
0.0,
0.0,
0.0,
0.0,
444,
444,
2)),
gpsLocation3(types::Localisation::GpsLocation(
9.0,
51.0,
508.0,
types::Localisation::GpsFixEnum::MODE2D,
0.0,
0.0,
0.0,
0.0,
444,
444,
3)),
gpsLocation4(types::Localisation::GpsLocation(
9.0,
51.0,
508.0,
types::Localisation::GpsFixEnum::MODE2D,
0.0,
0.0,
0.0,
0.0,
444,
444,
4)),
providerParticipantId(),
integration1Settings("test-resources/libjoynrSystemIntegration1.settings"),
integration2Settings("test-resources/libjoynrSystemIntegration2.settings"),
httpTransport(false)
{
auto settings1 = std::make_unique<Settings>(std::get<0>(GetParam()));
auto settings2 = std::make_unique<Settings>(std::get<1>(GetParam()));
MessagingSettings messagingSettings1(*settings1);
MessagingSettings messagingSettings2(*settings2);
messagingSettings1.setMessagingPropertiesPersistenceFilename(
messagingPropertiesPersistenceFileName1);
messagingSettings2.setMessagingPropertiesPersistenceFilename(
messagingPropertiesPersistenceFileName2);
std::string brokerProtocol = messagingSettings1.getBrokerUrl().getBrokerChannelsBaseUrl().getProtocol();
httpTransport = boost::iequals(brokerProtocol, "http") || boost::iequals(brokerProtocol, "https");
Settings::merge(integration1Settings, *settings1, false);
runtime1 = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings1));
runtime1->init();
Settings::merge(integration2Settings, *settings2, false);
runtime2 = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings2));
runtime2->init();
filterParameters.setCountry("Germany");
filterParameters.setStartTime("4.00 pm");
runtime1->start();
runtime2->start();
}
~End2EndBroadcastTestBase(){
if (!providerParticipantId.empty()) {
unregisterProvider();
}
bool deleteChannel = true;
runtime1->stop(deleteChannel);
runtime2->stop(deleteChannel);
test::util::resetAndWaitUntilDestroyed(runtime1);
test::util::resetAndWaitUntilDestroyed(runtime2);
// Delete persisted files
test::util::removeAllCreatedSettingsAndPersistencyFiles();
}
private:
std::string providerParticipantId;
Settings integration1Settings;
Settings integration2Settings;
DISALLOW_COPY_AND_ASSIGN(End2EndBroadcastTestBase);
bool httpTransport;
protected:
bool usesHttpTransport() {
return httpTransport;
}
std::shared_ptr<MyTestProvider> registerProvider() {
return registerProvider(runtime1);
}
void unregisterProvider() {
return runtime1->unregisterProvider(providerParticipantId);
}
std::shared_ptr<MyTestProvider> registerProvider(std::shared_ptr<JoynrClusterControllerRuntime> runtime) {
auto testProvider = std::make_shared<MyTestProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerQos.setSupportsOnChangeSubscriptions(true);
providerParticipantId = runtime->registerProvider<tests::testProvider>(domainName, testProvider, providerQos);
// This wait is necessary, because registerProvider is async, and a lookup could occur
// before the register has finished.
std::this_thread::sleep_for(std::chrono::milliseconds(registerProviderWait));
return testProvider;
}
std::shared_ptr<tests::testProxy> buildProxy() {
return buildProxy(runtime2);
}
std::shared_ptr<tests::testProxy> buildProxy(std::shared_ptr<JoynrClusterControllerRuntime> runtime) {
std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder
= runtime->createProxyBuilder<tests::testProxy>(domainName);
DiscoveryQos discoveryQos;
discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
discoveryQos.setDiscoveryTimeoutMs(3000);
discoveryQos.setRetryIntervalMs(250);
std::int64_t qosRoundTripTTL = 500;
std::shared_ptr<tests::testProxy> testProxy(testProxyBuilder
->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->build());
return testProxy;
}
template <typename FireBroadcast, typename SubscribeTo, typename UnsubscribeFrom, typename T>
void testOneShotBroadcastSubscription(const T& expectedValue,
SubscribeTo subscribeTo,
UnsubscribeFrom unsubscribeFrom,
FireBroadcast fireBroadcast) {
auto mockListener = std::make_shared<MockSubscriptionListenerOneType<T>>();
// Use a semaphore to count and wait on calls to the mock listener
ON_CALL(*mockListener, onReceive(Eq(expectedValue)))
.WillByDefault(ReleaseSemaphore(&semaphore));
testOneShotBroadcastSubscription(mockListener,
subscribeTo,
unsubscribeFrom,
fireBroadcast,
expectedValue);
}
template <typename SubscriptionListener,
typename FireBroadcast,
typename SubscribeTo,
typename UnsubscribeFrom,
typename ...T>
void testOneShotBroadcastSubscription(SubscriptionListener subscriptionListener,
SubscribeTo subscribeTo,
UnsubscribeFrom unsubscribeFrom,
FireBroadcast fireBroadcast,
T... expectedValues) {
std::vector<std::string> partitions({}); // TODO test with real partitions
std::shared_ptr<MyTestProvider> testProvider = registerProvider();
std::shared_ptr<tests::testProxy> testProxy = buildProxy();
auto subscriptionQos = std::make_shared<MulticastSubscriptionQos>();
subscriptionQos->setValidityMs(500000);
std::string subscriptionId;
subscribeTo(testProxy.get(), subscriptionListener, subscriptionQos, subscriptionId);
(*testProvider.*fireBroadcast)(expectedValues..., partitions);
// Wait for a subscription message to arrive
ASSERT_TRUE(semaphore.waitFor(std::chrono::seconds(3)));
unsubscribeFrom(testProxy.get(), subscriptionId);
}
template <typename BroadcastFilter>
void addFilterToTestProvider(std::shared_ptr<MyTestProvider> testProvider, std::shared_ptr<BroadcastFilter> filter)
{
if (filter) {
testProvider->addBroadcastFilter(filter);
}
}
void addFilterToTestProvider(std::shared_ptr<MyTestProvider> testProvider, std::nullptr_t filter)
{
std::ignore = testProvider;
std::ignore = filter;
}
template <typename SubscriptionListener,
typename FireBroadcast,
typename SubscribeTo,
typename UnsubscribeFrom,
typename BroadcastFilterPtr,
typename ...T>
void testOneShotBroadcastSubscriptionWithFiltering(SubscriptionListener subscriptionListener,
SubscribeTo subscribeTo,
UnsubscribeFrom unsubscribeFrom,
FireBroadcast fireBroadcast,
BroadcastFilterPtr filter,
T... expectedValues) {
std::shared_ptr<MyTestProvider> testProvider = registerProvider();
addFilterToTestProvider(testProvider, filter);
std::shared_ptr<tests::testProxy> testProxy = buildProxy();
std::int64_t minInterval_ms = 50;
std::string subscriptionId;
auto subscriptionQos = std::make_shared<OnChangeSubscriptionQos>(
500000, // validity_ms
1000, // publication ttl
minInterval_ms); // minInterval_ms
subscribeTo(testProxy.get(), subscriptionListener, subscriptionQos, subscriptionId);
(*testProvider.*fireBroadcast)(expectedValues...);
// Wait for a subscription message to arrive
ASSERT_TRUE(semaphore.waitFor(std::chrono::seconds(3)));
unsubscribeFrom(testProxy.get(), subscriptionId);
}
};
} // namespace joynr
<commit_msg>[C++] Fixed End2EndBroadcastTestBase<commit_after>/*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include <boost/algorithm/string/predicate.hpp>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/tests/testProxy.h"
#include "joynr/MessagingSettings.h"
#include "joynr/MulticastSubscriptionQos.h"
#include "joynr/OnChangeSubscriptionQos.h"
#include "joynr/tests/testAbstractProvider.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/BrokerUrl.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockLocationUpdatedSelectiveFilter.h"
#include "tests/mock/MockSubscriptionListener.h"
#include "tests/utils/MyTestProvider.h"
#include "tests/utils/PtrUtils.h"
using namespace ::testing;
using namespace joynr;
static const std::string messagingPropertiesPersistenceFileName1(
"End2EndBroadcastTest-runtime1-joynr.persist");
static const std::string messagingPropertiesPersistenceFileName2(
"End2EndBroadcastTest-runtime2-joynr.persist");
namespace joynr {
class End2EndBroadcastTestBase : public TestWithParam< std::tuple<std::string, std::string> > {
public:
std::shared_ptr<JoynrClusterControllerRuntime> runtime1;
std::shared_ptr<JoynrClusterControllerRuntime> runtime2;
std::string baseUuid;
std::string uuid;
std::string domainName;
Semaphore semaphore;
Semaphore altSemaphore;
joynr::tests::TestLocationUpdateSelectiveBroadcastFilterParameters filterParameters;
std::shared_ptr<MockLocationUpdatedSelectiveFilter> filter;
std::uint16_t registerProviderWait;
std::uint16_t subscribeToAttributeWait;
std::uint16_t subscribeToBroadcastWait;
joynr::types::Localisation::GpsLocation gpsLocation;
joynr::types::Localisation::GpsLocation gpsLocation2;
joynr::types::Localisation::GpsLocation gpsLocation3;
joynr::types::Localisation::GpsLocation gpsLocation4;
End2EndBroadcastTestBase() :
runtime1(),
runtime2(),
baseUuid(util::createUuid()),
uuid( "_" + baseUuid.substr(1, baseUuid.length()-2)),
domainName("cppEnd2EndBroadcastTest_Domain" + uuid),
semaphore(0),
altSemaphore(0),
filter(std::make_shared<MockLocationUpdatedSelectiveFilter>()),
registerProviderWait(1000),
subscribeToAttributeWait(2000),
subscribeToBroadcastWait(2000),
gpsLocation(types::Localisation::GpsLocation()),
gpsLocation2(types::Localisation::GpsLocation(
9.0,
51.0,
508.0,
types::Localisation::GpsFixEnum::MODE2D,
0.0,
0.0,
0.0,
0.0,
444,
444,
2)),
gpsLocation3(types::Localisation::GpsLocation(
9.0,
51.0,
508.0,
types::Localisation::GpsFixEnum::MODE2D,
0.0,
0.0,
0.0,
0.0,
444,
444,
3)),
gpsLocation4(types::Localisation::GpsLocation(
9.0,
51.0,
508.0,
types::Localisation::GpsFixEnum::MODE2D,
0.0,
0.0,
0.0,
0.0,
444,
444,
4)),
providerParticipantId(),
integration1Settings("test-resources/libjoynrSystemIntegration1.settings"),
integration2Settings("test-resources/libjoynrSystemIntegration2.settings"),
httpTransport(false)
{
auto settings1 = std::make_unique<Settings>(std::get<0>(GetParam()));
auto settings2 = std::make_unique<Settings>(std::get<1>(GetParam()));
MessagingSettings messagingSettings1(*settings1);
MessagingSettings messagingSettings2(*settings2);
messagingSettings1.setMessagingPropertiesPersistenceFilename(
messagingPropertiesPersistenceFileName1);
messagingSettings2.setMessagingPropertiesPersistenceFilename(
messagingPropertiesPersistenceFileName2);
std::string brokerProtocol = messagingSettings1.getBrokerUrl().getBrokerChannelsBaseUrl().getProtocol();
httpTransport = boost::iequals(brokerProtocol, "http") || boost::iequals(brokerProtocol, "https");
Settings::merge(integration1Settings, *settings1, false);
runtime1 = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings1));
runtime1->init();
Settings::merge(integration2Settings, *settings2, false);
runtime2 = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings2));
runtime2->init();
filterParameters.setCountry("Germany");
filterParameters.setStartTime("4.00 pm");
runtime1->start();
runtime2->start();
}
~End2EndBroadcastTestBase(){
if (!providerParticipantId.empty()) {
unregisterProvider();
}
bool deleteChannel = true;
runtime1->stop(deleteChannel);
runtime2->stop(deleteChannel);
test::util::resetAndWaitUntilDestroyed(runtime1);
test::util::resetAndWaitUntilDestroyed(runtime2);
// Delete persisted files
test::util::removeAllCreatedSettingsAndPersistencyFiles();
}
private:
std::string providerParticipantId;
Settings integration1Settings;
Settings integration2Settings;
DISALLOW_COPY_AND_ASSIGN(End2EndBroadcastTestBase);
bool httpTransport;
protected:
bool usesHttpTransport() {
return httpTransport;
}
std::shared_ptr<MyTestProvider> registerProvider() {
return registerProvider(runtime1);
}
void unregisterProvider() {
return runtime1->unregisterProvider(providerParticipantId);
}
std::shared_ptr<MyTestProvider> registerProvider(std::shared_ptr<JoynrClusterControllerRuntime> runtime) {
auto testProvider = std::make_shared<MyTestProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerQos.setSupportsOnChangeSubscriptions(true);
providerParticipantId = runtime->registerProvider<tests::testProvider>(domainName, testProvider, providerQos);
// This wait is necessary, because registerProvider is async, and a lookup could occur
// before the register has finished.
std::this_thread::sleep_for(std::chrono::milliseconds(registerProviderWait));
return testProvider;
}
std::shared_ptr<tests::testProxy> buildProxy() {
return buildProxy(runtime2);
}
std::shared_ptr<tests::testProxy> buildProxy(std::shared_ptr<JoynrClusterControllerRuntime> runtime) {
std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder
= runtime->createProxyBuilder<tests::testProxy>(domainName);
DiscoveryQos discoveryQos;
discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
discoveryQos.setDiscoveryTimeoutMs(30000);
discoveryQos.setRetryIntervalMs(500);
std::int64_t qosRoundTripTTL = 40000;
std::shared_ptr<tests::testProxy> testProxy(testProxyBuilder
->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->build());
return testProxy;
}
template <typename FireBroadcast, typename SubscribeTo, typename UnsubscribeFrom, typename T>
void testOneShotBroadcastSubscription(const T& expectedValue,
SubscribeTo subscribeTo,
UnsubscribeFrom unsubscribeFrom,
FireBroadcast fireBroadcast) {
auto mockListener = std::make_shared<MockSubscriptionListenerOneType<T>>();
// Use a semaphore to count and wait on calls to the mock listener
ON_CALL(*mockListener, onReceive(Eq(expectedValue)))
.WillByDefault(ReleaseSemaphore(&semaphore));
testOneShotBroadcastSubscription(mockListener,
subscribeTo,
unsubscribeFrom,
fireBroadcast,
expectedValue);
}
template <typename SubscriptionListener,
typename FireBroadcast,
typename SubscribeTo,
typename UnsubscribeFrom,
typename ...T>
void testOneShotBroadcastSubscription(SubscriptionListener subscriptionListener,
SubscribeTo subscribeTo,
UnsubscribeFrom unsubscribeFrom,
FireBroadcast fireBroadcast,
T... expectedValues) {
std::vector<std::string> partitions({}); // TODO test with real partitions
std::shared_ptr<MyTestProvider> testProvider = registerProvider();
std::shared_ptr<tests::testProxy> testProxy = buildProxy();
auto subscriptionQos = std::make_shared<MulticastSubscriptionQos>();
subscriptionQos->setValidityMs(500000);
std::string subscriptionId;
subscribeTo(testProxy.get(), subscriptionListener, subscriptionQos, subscriptionId);
(*testProvider.*fireBroadcast)(expectedValues..., partitions);
// Wait for a subscription message to arrive
ASSERT_TRUE(semaphore.waitFor(std::chrono::seconds(3)));
unsubscribeFrom(testProxy.get(), subscriptionId);
}
template <typename BroadcastFilter>
void addFilterToTestProvider(std::shared_ptr<MyTestProvider> testProvider, std::shared_ptr<BroadcastFilter> filter)
{
if (filter) {
testProvider->addBroadcastFilter(filter);
}
}
void addFilterToTestProvider(std::shared_ptr<MyTestProvider> testProvider, std::nullptr_t filter)
{
std::ignore = testProvider;
std::ignore = filter;
}
template <typename SubscriptionListener,
typename FireBroadcast,
typename SubscribeTo,
typename UnsubscribeFrom,
typename BroadcastFilterPtr,
typename ...T>
void testOneShotBroadcastSubscriptionWithFiltering(SubscriptionListener subscriptionListener,
SubscribeTo subscribeTo,
UnsubscribeFrom unsubscribeFrom,
FireBroadcast fireBroadcast,
BroadcastFilterPtr filter,
T... expectedValues) {
std::shared_ptr<MyTestProvider> testProvider = registerProvider();
addFilterToTestProvider(testProvider, filter);
std::shared_ptr<tests::testProxy> testProxy = buildProxy();
std::int64_t minInterval_ms = 50;
std::string subscriptionId;
auto subscriptionQos = std::make_shared<OnChangeSubscriptionQos>(
500000, // validity_ms
1000, // publication ttl
minInterval_ms); // minInterval_ms
subscribeTo(testProxy.get(), subscriptionListener, subscriptionQos, subscriptionId);
(*testProvider.*fireBroadcast)(expectedValues...);
// Wait for a subscription message to arrive
ASSERT_TRUE(semaphore.waitFor(std::chrono::seconds(3)));
unsubscribeFrom(testProxy.get(), subscriptionId);
}
};
} // namespace joynr
<|endoftext|> |
<commit_before>/*=================================================================================================
Copyright (c) 2016 Joel de Guzman
Licensed under a Creative Commons Attribution-ShareAlike 4.0 International.
http://creativecommons.org/licenses/by-sa/4.0/
=================================================================================================*/
#if !defined(PHOTON_GUI_LIB_WIDGET_GALLERY_JUNE_5_2016)
#define PHOTON_GUI_LIB_WIDGET_GALLERY_JUNE_5_2016
#include <photon/support/theme.hpp>
#include <photon/support/text_utils.hpp>
#include <photon/widget.hpp>
namespace photon
{
////////////////////////////////////////////////////////////////////////////////////////////////
// Frames
////////////////////////////////////////////////////////////////////////////////////////////////
class frame : public widget
{
public:
virtual void draw(context const& ctx);
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Headings
////////////////////////////////////////////////////////////////////////////////////////////////
class heading : public widget
{
public:
heading(std::string const& text, float size_ = 1.0)
: _text(text)
, _size(size_)
{}
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
std::string text() const { return _text; }
void text(std::string const& text) { _text = text; }
using widget::text;
private:
std::string _text;
float _size;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Labels
////////////////////////////////////////////////////////////////////////////////////////////////
class label : public widget
{
public:
label(std::string const& text, float size_ = 1.0)
: _text(text)
, _size(size_)
{}
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
std::string text() const { return _text; }
void text(std::string const& text) { _text = text; }
using widget::text;
private:
std::string _text;
float _size;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Grid Lines
////////////////////////////////////////////////////////////////////////////////////////////////
class vgrid_lines : public widget
{
public:
vgrid_lines(float major_divisions, float minor_divisions)
: _major_divisions(major_divisions)
, _minor_divisions(minor_divisions)
{}
virtual void draw(context const& ctx);
private:
float _major_divisions;
float _minor_divisions;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Groups
////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Heading, typename Content>
inline auto make_group(
Heading&& heading,
Content&& content,
bool center_heading = true
)
{
auto align_ = center_heading? 0.5 : 0;
return
layer(
align_top(halign(align_, margin({ 10, 4, 10, 4 }, heading))),
std::forward<Content>(content),
frame{}
);
}
template <typename Content>
inline auto group(
std::string title,
Content&& content,
float label_size = 1.0,
bool center_heading = true
)
{
return make_group(
left_top_margin({ 10, 10 }, heading{ title, label_size }),
std::forward<Content>(content), center_heading
);
}
template <typename Heading, typename Content>
inline auto make_unframed_group(
Heading&& heading,
Content&& content,
bool center_heading = true
)
{
auto align_ = center_heading? 0.5 : 0;
return
layer(
align_top(halign(align_, margin({ 10, 4, 10, 4 }, heading))),
std::forward<Content>(content)
);
}
template <typename Content>
inline auto unframed_group(
std::string title,
Content&& content,
float label_size = 1.0,
bool center_heading = true
)
{
return make_unframed_group(
left_top_margin({ 10, 10 }, heading{ title, label_size }),
std::forward<Content>(content), center_heading
);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Captions
////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Content>
inline auto caption(Content&& content, std::string const& title, float size = 1.0)
{
return
vtile(
std::forward<Content>(content),
align_center(top_margin(5.0, label(title, size)))
);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Icons
////////////////////////////////////////////////////////////////////////////////////////////////
class icon : public widget
{
public:
icon(std::uint32_t code_, float size_ = -1);
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
private:
std::uint32_t _code;
float _size;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////////
auto const button_margin = rect{ 10, 5, 10, 5 };
auto const default_button_color = color{ 0, 0, 0, 0 };
class basic_button_body : public widget
{
public:
static float corner_radius;
basic_button_body(color body_color);
virtual void draw(context const& ctx);
private:
color body_color;
};
inline basic_button_body::basic_button_body(color body_color)
: body_color(body_color)
{}
template <typename Button, typename Label>
inline Button make_button(Label&& label, color body_color = default_button_color)
{
auto btn_body_off = basic_button_body(body_color.level(0.9));
auto btn_body_on = basic_button_body(body_color.opacity(0.5));
auto btn_img_off = layer(label, btn_body_off);
auto btn_img_on = left_top_margin({1, 1}, layer(label, btn_body_on));
return Button(std::move(btn_img_off), std::move(btn_img_on));
}
template <typename Button>
inline Button make_button(
std::string const& text
, color body_color = default_button_color
)
{
return make_button<Button>(
margin(
button_margin,
align_center(label(text))
),
body_color
);
}
template <typename Button>
inline Button make_button(
std::uint32_t icon_code
, std::string const& text
, color body_color = default_button_color
)
{
return make_button<Button>(
margin(
button_margin,
align_center(
htile(
right_margin(8, icon(icon_code)),
label(text)
)
)
),
body_color
);
}
template <typename Button>
inline Button make_button(
std::string const& text
, std::uint32_t icon_code
, color body_color = default_button_color
)
{
return make_button<Button>(
margin(
button_margin,
align_center(
htile(
label(text),
left_margin(8, icon(icon_code))
)
)
),
body_color
);
}
basic_button
button(
std::string const& text
, color body_color = default_button_color
);
basic_button
button(
std::uint32_t icon_code
, std::string const& text
, color body_color = default_button_color
);
basic_button
button(
std::string const& text
, std::uint32_t icon_code
, color body_color = default_button_color
);
basic_toggle_button
toggle_button(
std::string const& text
, color body_color = default_button_color
);
basic_toggle_button
toggle_button(
std::uint32_t icon_code
, std::string const& text
, color body_color = default_button_color
);
basic_toggle_button
toggle_button(
std::string const& text
, std::uint32_t icon_code
, color body_color = default_button_color
);
basic_latching_button
latching_button(
std::string const& text
, color body_color = default_button_color
);
basic_latching_button
latching_button(
std::uint32_t icon_code
, std::string const& text
, color body_color = default_button_color
);
basic_latching_button
latching_button(
std::string const& text
, std::uint32_t icon_code
, color body_color = default_button_color
);
////////////////////////////////////////////////////////////////////////////////////////////////
// Check Box
////////////////////////////////////////////////////////////////////////////////////////////////
void draw_check_box(
context const& ctx, std::string const& text, bool state, bool hilite
);
template <bool state>
class check_box_widget : public widget
{
public:
check_box_widget(std::string const& text)
: _text(text)
{}
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
private:
std::string _text;
};
template <bool state>
widget_limits check_box_widget<state>::limits(basic_context const& ctx) const
{
auto& thm = get_theme();
auto size = measure_text(ctx.canvas, _text.c_str(), thm.label_font, thm.label_font_size);
return { { size.x, size.y }, { size.x, size.y } };
}
template <bool state>
void check_box_widget<state>::draw(context const& ctx)
{
draw_check_box(ctx, _text, state, ctx.bounds.includes(ctx.view.cursor_pos()));
}
inline basic_toggle_button check_box(std::string const& text)
{
return basic_toggle_button(
check_box_widget<false>{ text }
, check_box_widget<true>{ text }
);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Icon Button
////////////////////////////////////////////////////////////////////////////////////////////////
void draw_icon_button(context const& ctx, uint32_t code, float size, bool state, bool hilite);
template <bool state>
class icon_button_widget : public widget
{
public:
icon_button_widget(uint32_t code, float size)
: _code(code)
, _size(size)
{}
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
uint32_t _code;
float _size;
};
template <bool state>
widget_limits icon_button_widget<state>::limits(basic_context const& ctx) const
{
auto size = _size * 1.8f;
return { { size, size }, { size, size } };
}
template <bool state>
void icon_button_widget<state>::draw(context const& ctx)
{
draw_icon_button(ctx, _code, _size, state, ctx.bounds.includes(ctx.view.cursor_pos()));
}
inline basic_toggle_button icon_button(uint32_t code, float size)
{
return {
icon_button_widget<false>{ code, size }
, icon_button_widget<true>{ code, size }
};
}
inline basic_toggle_button icon_button(uint32_t code1, uint32_t code2, float size)
{
return {
icon_button_widget<false>{ code1, size }
, icon_button_widget<true>{ code2, size }
};
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Popup Button
////////////////////////////////////////////////////////////////////////////////////////////////
basic_popup_button
popup_button(
std::string const& text
, color body_color = default_button_color
);
////////////////////////////////////////////////////////////////////////////////////////////////
// Menu Background
////////////////////////////////////////////////////////////////////////////////////////////////
class menu_background : public widget
{
public:
virtual void draw(context const& ctx);
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Menu Items
////////////////////////////////////////////////////////////////////////////////////////////////
inline auto menu_item_text(std::string const& text)
{
return xside_margin({ 20, 20 }, align_left(label(text)));
}
inline auto menu_item(std::string const& text)
{
return basic_menu_item(menu_item_text(text));
}
class menu_item_spacer_widget : public widget
{
public:
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
};
inline auto menu_item_spacer()
{
return menu_item_spacer_widget{};
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Text Entry
////////////////////////////////////////////////////////////////////////////////////////////////
class input_panel : public widget
{
public:
virtual void draw(context const& ctx);
};
template <typename InputBox, typename Panel>
inline auto input_box(
InputBox&& text_input
, Panel&& panel
, rect pad = rect{ 5, 5, 5, 4 }
)
{
return layer(
margin(
pad,
scroller(
hsize(16384, std::move(text_input)),
no_scrollbars | no_vscroll
)
),
std::move(panel)
);
}
template <typename InputBox>
inline auto input_box(
InputBox&& text_input
, rect pad = rect{ 5, 5, 5, 4 }
)
{
return input_box(std::move(text_input), input_panel{}, pad);
}
inline auto input_box(
std::string const& placeholder
, rect pad = rect{ 5, 5, 5, 4 }
)
{
return input_box(
basic_input_box{ placeholder }
, pad
);
}
inline auto input_box(
char const* placeholder
, rect pad = rect{ 5, 5, 5, 4 }
)
{
return input_box(
basic_input_box{ placeholder }
, pad
);
}
}
#endif<commit_msg>Moved knob creation to photon gallery<commit_after>/*=================================================================================================
Copyright (c) 2016 Joel de Guzman
Licensed under a Creative Commons Attribution-ShareAlike 4.0 International.
http://creativecommons.org/licenses/by-sa/4.0/
=================================================================================================*/
#if !defined(PHOTON_GUI_LIB_WIDGET_GALLERY_JUNE_5_2016)
#define PHOTON_GUI_LIB_WIDGET_GALLERY_JUNE_5_2016
#include <photon/support/theme.hpp>
#include <photon/support/text_utils.hpp>
#include <photon/widget.hpp>
namespace photon
{
////////////////////////////////////////////////////////////////////////////////////////////////
// Frames
////////////////////////////////////////////////////////////////////////////////////////////////
class frame : public widget
{
public:
virtual void draw(context const& ctx);
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Headings
////////////////////////////////////////////////////////////////////////////////////////////////
class heading : public widget
{
public:
heading(std::string const& text, float size_ = 1.0)
: _text(text)
, _size(size_)
{}
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
std::string text() const { return _text; }
void text(std::string const& text) { _text = text; }
using widget::text;
private:
std::string _text;
float _size;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Labels
////////////////////////////////////////////////////////////////////////////////////////////////
class label : public widget
{
public:
label(std::string const& text, float size_ = 1.0)
: _text(text)
, _size(size_)
{}
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
std::string text() const { return _text; }
void text(std::string const& text) { _text = text; }
using widget::text;
private:
std::string _text;
float _size;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Grid Lines
////////////////////////////////////////////////////////////////////////////////////////////////
class vgrid_lines : public widget
{
public:
vgrid_lines(float major_divisions, float minor_divisions)
: _major_divisions(major_divisions)
, _minor_divisions(minor_divisions)
{}
virtual void draw(context const& ctx);
private:
float _major_divisions;
float _minor_divisions;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Groups
////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Heading, typename Content>
inline auto make_group(
Heading&& heading,
Content&& content,
bool center_heading = true
)
{
auto align_ = center_heading? 0.5 : 0;
return
layer(
align_top(halign(align_, margin({ 10, 4, 10, 4 }, heading))),
std::forward<Content>(content),
frame{}
);
}
template <typename Content>
inline auto group(
std::string title,
Content&& content,
float label_size = 1.0,
bool center_heading = true
)
{
return make_group(
left_top_margin({ 10, 10 }, heading{ title, label_size }),
std::forward<Content>(content), center_heading
);
}
template <typename Heading, typename Content>
inline auto make_unframed_group(
Heading&& heading,
Content&& content,
bool center_heading = true
)
{
auto align_ = center_heading? 0.5 : 0;
return
layer(
align_top(halign(align_, margin({ 10, 4, 10, 4 }, heading))),
std::forward<Content>(content)
);
}
template <typename Content>
inline auto unframed_group(
std::string title,
Content&& content,
float label_size = 1.0,
bool center_heading = true
)
{
return make_unframed_group(
left_top_margin({ 10, 10 }, heading{ title, label_size }),
std::forward<Content>(content), center_heading
);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Captions
////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Content>
inline auto caption(Content&& content, std::string const& title, float size = 1.0)
{
return
vtile(
std::forward<Content>(content),
align_center(top_margin(5.0, label(title, size)))
);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Icons
////////////////////////////////////////////////////////////////////////////////////////////////
class icon : public widget
{
public:
icon(std::uint32_t code_, float size_ = -1);
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
private:
std::uint32_t _code;
float _size;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////////
auto const button_margin = rect{ 10, 5, 10, 5 };
auto const default_button_color = color{ 0, 0, 0, 0 };
class basic_button_body : public widget
{
public:
static float corner_radius;
basic_button_body(color body_color);
virtual void draw(context const& ctx);
private:
color body_color;
};
inline basic_button_body::basic_button_body(color body_color)
: body_color(body_color)
{}
template <typename Button, typename Label>
inline Button make_button(Label&& label, color body_color = default_button_color)
{
auto btn_body_off = basic_button_body(body_color.level(0.9));
auto btn_body_on = basic_button_body(body_color.opacity(0.5));
auto btn_img_off = layer(label, btn_body_off);
auto btn_img_on = left_top_margin({1, 1}, layer(label, btn_body_on));
return Button(std::move(btn_img_off), std::move(btn_img_on));
}
template <typename Button>
inline Button make_button(
std::string const& text
, color body_color = default_button_color
)
{
return make_button<Button>(
margin(
button_margin,
align_center(label(text))
),
body_color
);
}
template <typename Button>
inline Button make_button(
std::uint32_t icon_code
, std::string const& text
, color body_color = default_button_color
)
{
return make_button<Button>(
margin(
button_margin,
align_center(
htile(
right_margin(8, icon(icon_code)),
label(text)
)
)
),
body_color
);
}
template <typename Button>
inline Button make_button(
std::string const& text
, std::uint32_t icon_code
, color body_color = default_button_color
)
{
return make_button<Button>(
margin(
button_margin,
align_center(
htile(
label(text),
left_margin(8, icon(icon_code))
)
)
),
body_color
);
}
basic_button
button(
std::string const& text
, color body_color = default_button_color
);
basic_button
button(
std::uint32_t icon_code
, std::string const& text
, color body_color = default_button_color
);
basic_button
button(
std::string const& text
, std::uint32_t icon_code
, color body_color = default_button_color
);
basic_toggle_button
toggle_button(
std::string const& text
, color body_color = default_button_color
);
basic_toggle_button
toggle_button(
std::uint32_t icon_code
, std::string const& text
, color body_color = default_button_color
);
basic_toggle_button
toggle_button(
std::string const& text
, std::uint32_t icon_code
, color body_color = default_button_color
);
basic_latching_button
latching_button(
std::string const& text
, color body_color = default_button_color
);
basic_latching_button
latching_button(
std::uint32_t icon_code
, std::string const& text
, color body_color = default_button_color
);
basic_latching_button
latching_button(
std::string const& text
, std::uint32_t icon_code
, color body_color = default_button_color
);
////////////////////////////////////////////////////////////////////////////////////////////////
// Check Box
////////////////////////////////////////////////////////////////////////////////////////////////
void draw_check_box(
context const& ctx, std::string const& text, bool state, bool hilite
);
template <bool state>
class check_box_widget : public widget
{
public:
check_box_widget(std::string const& text)
: _text(text)
{}
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
private:
std::string _text;
};
template <bool state>
widget_limits check_box_widget<state>::limits(basic_context const& ctx) const
{
auto& thm = get_theme();
auto size = measure_text(ctx.canvas, _text.c_str(), thm.label_font, thm.label_font_size);
return { { size.x, size.y }, { size.x, size.y } };
}
template <bool state>
void check_box_widget<state>::draw(context const& ctx)
{
draw_check_box(ctx, _text, state, ctx.bounds.includes(ctx.view.cursor_pos()));
}
inline basic_toggle_button check_box(std::string const& text)
{
return basic_toggle_button(
check_box_widget<false>{ text }
, check_box_widget<true>{ text }
);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Icon Button
////////////////////////////////////////////////////////////////////////////////////////////////
void draw_icon_button(context const& ctx, uint32_t code, float size, bool state, bool hilite);
template <bool state>
class icon_button_widget : public widget
{
public:
icon_button_widget(uint32_t code, float size)
: _code(code)
, _size(size)
{}
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
uint32_t _code;
float _size;
};
template <bool state>
widget_limits icon_button_widget<state>::limits(basic_context const& ctx) const
{
auto size = _size * 1.8f;
return { { size, size }, { size, size } };
}
template <bool state>
void icon_button_widget<state>::draw(context const& ctx)
{
draw_icon_button(ctx, _code, _size, state, ctx.bounds.includes(ctx.view.cursor_pos()));
}
inline basic_toggle_button icon_button(uint32_t code, float size)
{
return {
icon_button_widget<false>{ code, size }
, icon_button_widget<true>{ code, size }
};
}
inline basic_toggle_button icon_button(uint32_t code1, uint32_t code2, float size)
{
return {
icon_button_widget<false>{ code1, size }
, icon_button_widget<true>{ code2, size }
};
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Popup Button
////////////////////////////////////////////////////////////////////////////////////////////////
basic_popup_button
popup_button(
std::string const& text
, color body_color = default_button_color
);
////////////////////////////////////////////////////////////////////////////////////////////////
// Menu Background
////////////////////////////////////////////////////////////////////////////////////////////////
class menu_background : public widget
{
public:
virtual void draw(context const& ctx);
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Menu Items
////////////////////////////////////////////////////////////////////////////////////////////////
inline auto menu_item_text(std::string const& text)
{
return xside_margin({ 20, 20 }, align_left(label(text)));
}
inline auto menu_item(std::string const& text)
{
return basic_menu_item(menu_item_text(text));
}
class menu_item_spacer_widget : public widget
{
public:
virtual widget_limits limits(basic_context const& ctx) const;
virtual void draw(context const& ctx);
};
inline auto menu_item_spacer()
{
return menu_item_spacer_widget{};
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Text Entry
////////////////////////////////////////////////////////////////////////////////////////////////
class input_panel : public widget
{
public:
virtual void draw(context const& ctx);
};
template <typename InputBox, typename Panel>
inline auto input_box(
InputBox&& text_input
, Panel&& panel
, rect pad = rect{ 5, 5, 5, 4 }
)
{
return layer(
margin(
pad,
scroller(
hsize(16384, std::move(text_input)),
no_scrollbars | no_vscroll
)
),
std::move(panel)
);
}
template <typename InputBox>
inline auto input_box(
InputBox&& text_input
, rect pad = rect{ 5, 5, 5, 4 }
)
{
return input_box(std::move(text_input), input_panel{}, pad);
}
inline auto input_box(
std::string const& placeholder
, rect pad = rect{ 5, 5, 5, 4 }
)
{
return input_box(
basic_input_box{ placeholder }
, pad
);
}
inline auto input_box(
char const* placeholder
, rect pad = rect{ 5, 5, 5, 4 }
)
{
return input_box(
basic_input_box{ placeholder }
, pad
);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Dials
////////////////////////////////////////////////////////////////////////////////////////////////
inline auto dial(
reference<dial_base>& control
, char const* knob_sprite
, float knob_height
, char const* background_image
, char const* caption_text
, float scale = 1.0/5
, float caption_size = 0.3
)
{
auto knob = sprite{ knob_sprite, knob_height * scale, scale };
auto lines = image{ background_image, scale };
control = reference<dial_base>(share(dial(knob)));
return
align_center_middle(
caption(
layer(
align_center_middle(control),
lines
),
caption_text, // caption
0.3 // relative caption text size
)
);
}
}
#endif<|endoftext|> |
<commit_before>// This source code is intended for use in the teaching course "Vision-Based Navigation" in summer term 2015 at Technical University Munich only.
// Copyright 2015 Vladyslav Usenko, Joerg Stueckler, Technical University Munich
#ifndef UAV_CONTROLLER_H_
#define UAV_CONTROLLER_H_
#include <ros/ros.h>
#include <std_srvs/Empty.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <sophus/se3.hpp>
#include <eigen_conversions/eigen_msg.h>
#include <mav_msgs/CommandAttitudeThrust.h>
#include <mav_msgs/CommandRateThrust.h>
#include <mav_msgs/CommandMotorSpeed.h>
#include <boost/thread/mutex.hpp>
#include <se3ukf.hpp>
#include <list>
#include <fstream>
template<typename _Scalar>
class UAVController {
private:
typedef Sophus::SE3Group<_Scalar> SE3Type;
typedef Sophus::SO3Group<_Scalar> SO3Type;
typedef Eigen::Quaternion<_Scalar> Quaternion;
typedef Eigen::Matrix<_Scalar, 3, 1> Vector3;
typedef Eigen::Matrix<_Scalar, 6, 1> Vector6;
typedef Eigen::Matrix<_Scalar, 12, 1> Vector12;
typedef Eigen::Matrix<_Scalar, 15, 1> Vector15;
typedef Eigen::Matrix<_Scalar, 3, 3> Matrix3;
typedef Eigen::Matrix<_Scalar, 6, 6> Matrix6;
typedef Eigen::Matrix<_Scalar, 12, 12> Matrix12;
typedef Eigen::Matrix<_Scalar, 15, 15> Matrix15;
ros::Publisher command_pub;
ros::Subscriber imu_sub;
ros::Subscriber pose_sub;
ros::Subscriber ground_truth_sub;
// Switch between ground truth and ukf for controller
bool use_ground_thruth_data;
// Ground thruth data
SE3Type ground_truth_pose;
Vector3 ground_truth_linear_velocity;
double ground_truth_time;
// Constants
_Scalar g;
_Scalar m;
SE3Type T_imu_cam;
SE3Type initial_pose;
Matrix15 initial_state_covariance;
Matrix3 gyro_noise;
Matrix3 accel_noise;
Matrix6 measurement6d_noise;
// Pose to hoover at
SE3Type desired_pose;
mav_msgs::CommandAttitudeThrust command;
void imuCallback(const sensor_msgs::ImuConstPtr& msg) {
Eigen::Vector3d accel_measurement, gyro_measurement;
tf::vectorMsgToEigen(msg->angular_velocity, gyro_measurement);
tf::vectorMsgToEigen(msg->linear_acceleration, accel_measurement);
sendControlSignal();
}
void groundTruthPoseCallback(
const geometry_msgs::PoseWithCovarianceStampedConstPtr& msg) {
Eigen::Quaterniond orientation;
Eigen::Vector3d position;
tf::pointMsgToEigen(msg->pose.pose.position, position);
tf::quaternionMsgToEigen(msg->pose.pose.orientation, orientation);
SE3Type pose(orientation.cast<_Scalar>(), position.cast<_Scalar>());
ground_truth_linear_velocity = (pose.translation()
- ground_truth_pose.translation())
/ (msg->header.stamp.toSec() - ground_truth_time);
ground_truth_pose = pose;
ground_truth_time = msg->header.stamp.toSec();
}
void pose1Callback(
const geometry_msgs::PoseWithCovarianceStampedConstPtr& msg) {
Eigen::Quaterniond orientation;
Eigen::Vector3d position;
tf::pointMsgToEigen(msg->pose.pose.position, position);
tf::quaternionMsgToEigen(msg->pose.pose.orientation, orientation);
SE3Type pose(orientation, position);
}
// exercise 1 d)
mav_msgs::CommandAttitudeThrust computeCommandFromForce(
const Vector3 & control_force, const SE3Type & pose,
double delta_time) {
// TODO: implement
float yaw = 0.5f; // ?
// f = m * a ==> a = f / m
Vector3 a = control_force/m;
float roll = 1.0f/g * (a.x()*sin(yaw) - a.y()*cos(yaw));
float pitch = 1.0f/g * (a.x()*cos(yaw) + a.y()*sin(yaw));
float thrust = a.z() + m*g;
// mav_msgs::CommandAttitudeThrust_(roll, pitch, yaw, thrust)
mav_msgs::CommandAttitudeThrust msg;
msg.roll = roll; // [rad]
msg.pitch = pitch; // [rad]
msg.yaw_rate = yaw; // [rad/s]
msg.thrust = thrust;
return msg;
}
// exercise 1 c)
Vector3 computeDesiredForce(const SE3Type & pose, const Vector3 & linear_velocity,
double delta_time) {
// TODO: implement
SE3Type curr_pose;
Vector3 curr_velocity;
getPoseAndVelocity(curr_pose, curr_velocity);
float kp = 1.0f; // proportional gains of the PID controller
float kd = 1.0f; // differential gains of the PID controller
float ki = 1.0f; // integral gains of the PID controller
// x'' = kp*(xd-x) + kd*(xd'-x') + ki*integral(xd-x, delta_time)
Vector3 a = kp*(pose.translation() - curr_pose.translation()) +
kd*(linear_velocity - curr_velocity) +
ki*delta_time*(pose.translation() - curr_pose.translation());
return m*a; // f = m * a
}
void getPoseAndVelocity(SE3Type & pose, Vector3 & linear_velocity) {
if (use_ground_thruth_data) {
pose = ground_truth_pose;
linear_velocity = ground_truth_linear_velocity;
} else {
}
}
public:
typedef boost::shared_ptr<UAVController> Ptr;
UAVController(ros::NodeHandle & nh) :
ground_truth_time(0) {
use_ground_thruth_data = false;
// ========= Constants ===================================//
g = 9.8; // in rate_controller g = 9.81
m = 1.55; // in rate_controller m = 1.56779
initial_state_covariance = Matrix15::Identity() * 0.001;
gyro_noise = Matrix3::Identity() * 0.0033937;
accel_noise = Matrix3::Identity() * 0.04;
measurement6d_noise = Matrix6::Identity() * 0.01;
initial_pose.translation() << 0, 0, 0.08;
// Set simulated camera to IMU transformation
Eigen::AngleAxisd rollAngle(0.2, Eigen::Vector3d::UnitX());
Eigen::AngleAxisd pitchAngle(-0.1, Eigen::Vector3d::UnitY());
Eigen::AngleAxisd yawAngle(0.3, Eigen::Vector3d::UnitZ());
Eigen::Quaterniond q = yawAngle * pitchAngle * rollAngle;
T_imu_cam.setQuaternion(q);
T_imu_cam.translation() << 0.03, -0.07, 0.1;
// set desired position
setDesiredPose(SE3Type(SO3Type::exp(Vector3(0,0,0)),Vector3(0,0,1)));
// Init subscribers and publishers
imu_sub = nh.subscribe("imu", 10, &UAVController<_Scalar>::imuCallback,
this);
pose_sub = nh.subscribe("pose1", 10,
&UAVController<_Scalar>::pose1Callback, this);
ground_truth_sub = nh.subscribe("ground_truth/pose", 10,
&UAVController<_Scalar>::groundTruthPoseCallback, this);
command_pub = nh.advertise<mav_msgs::CommandAttitudeThrust>(
"command/attitude", 10);
// Wake up simulation, from this point on, you have 30s to initialize
// everything and fly to the evaluation position (x=0m y=0m z=1m).
ROS_INFO("Waking up simulation ... ");
std_srvs::Empty srv;
bool ret = ros::service::call("/gazebo/unpause_physics", srv);
if (ret)
ROS_INFO("... ok");
else {
ROS_FATAL("could not wake up gazebo");
exit(-1);
}
}
~UAVController() {
}
// exercise 1 e)
void sendControlSignal() {
// TODO: implement
SE3Type curr_pose;
Vector3 curr_velocity;
Vector3 desired_velocity = Vector3(0,0,0);
double delta_time = 0.001d; // ?
getPoseAndVelocity(curr_pose, curr_velocity);
Vector3 dforce = computeDesiredForce(desired_pose, desired_velocity, delta_time);
command_pub.publish( computeCommandFromForce(dforce, desired_pose /*?*/, delta_time) );
}
void setDesiredPose(const SE3Type & p) {
desired_pose = p;
}
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
#endif /* UAV_CONTROLLER_H_ */
<commit_msg>Exercise 3 part 1 finsihed. May require further tuning for kp, kd, ki and testing.<commit_after>// This source code is intended for use in the teaching course "Vision-Based Navigation" in summer term 2015 at Technical University Munich only.
// Copyright 2015 Vladyslav Usenko, Joerg Stueckler, Technical University Munich
#ifndef UAV_CONTROLLER_H_
#define UAV_CONTROLLER_H_
#include <ros/ros.h>
#include <std_srvs/Empty.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <sophus/se3.hpp>
#include <eigen_conversions/eigen_msg.h>
#include <mav_msgs/CommandAttitudeThrust.h>
#include <mav_msgs/CommandRateThrust.h>
#include <mav_msgs/CommandMotorSpeed.h>
#include <boost/thread/mutex.hpp>
#include <se3ukf.hpp>
#include <list>
#include <fstream>
template<typename _Scalar>
class UAVController {
private:
typedef Sophus::SE3Group<_Scalar> SE3Type;
typedef Sophus::SO3Group<_Scalar> SO3Type;
typedef Eigen::Quaternion<_Scalar> Quaternion;
typedef Eigen::Matrix<_Scalar, 3, 1> Vector3;
typedef Eigen::Matrix<_Scalar, 6, 1> Vector6;
typedef Eigen::Matrix<_Scalar, 12, 1> Vector12;
typedef Eigen::Matrix<_Scalar, 15, 1> Vector15;
typedef Eigen::Matrix<_Scalar, 3, 3> Matrix3;
typedef Eigen::Matrix<_Scalar, 6, 6> Matrix6;
typedef Eigen::Matrix<_Scalar, 12, 12> Matrix12;
typedef Eigen::Matrix<_Scalar, 15, 15> Matrix15;
ros::Publisher command_pub;
ros::Subscriber imu_sub;
ros::Subscriber pose_sub;
ros::Subscriber ground_truth_sub;
// Switch between ground truth and ukf for controller
bool use_ground_thruth_data;
// Ground thruth data
SE3Type ground_truth_pose;
Vector3 ground_truth_linear_velocity;
double ground_truth_time;
// Constants
_Scalar g;
_Scalar m;
SE3Type T_imu_cam;
SE3Type initial_pose;
Matrix15 initial_state_covariance;
Matrix3 gyro_noise;
Matrix3 accel_noise;
Matrix6 measurement6d_noise;
// Pose to hoover at
SE3Type desired_pose;
mav_msgs::CommandAttitudeThrust command;
// debug
Vector3 position_integral;
void imuCallback(const sensor_msgs::ImuConstPtr& msg) {
Eigen::Vector3d accel_measurement, gyro_measurement;
tf::vectorMsgToEigen(msg->angular_velocity, gyro_measurement);
tf::vectorMsgToEigen(msg->linear_acceleration, accel_measurement);
sendControlSignal();
}
void groundTruthPoseCallback(
const geometry_msgs::PoseWithCovarianceStampedConstPtr& msg) {
Eigen::Quaterniond orientation;
Eigen::Vector3d position;
tf::pointMsgToEigen(msg->pose.pose.position, position);
tf::quaternionMsgToEigen(msg->pose.pose.orientation, orientation);
SE3Type pose(orientation.cast<_Scalar>(), position.cast<_Scalar>());
ground_truth_linear_velocity = (pose.translation()
- ground_truth_pose.translation())
/ (msg->header.stamp.toSec() - ground_truth_time);
ground_truth_pose = pose;
ground_truth_time = msg->header.stamp.toSec();
}
void pose1Callback(
const geometry_msgs::PoseWithCovarianceStampedConstPtr& msg) {
Eigen::Quaterniond orientation;
Eigen::Vector3d position;
tf::pointMsgToEigen(msg->pose.pose.position, position);
tf::quaternionMsgToEigen(msg->pose.pose.orientation, orientation);
SE3Type pose(orientation, position);
}
// TODO: exercise 1 d)
mav_msgs::CommandAttitudeThrust computeCommandFromForce(
const Vector3 & control_force, const SE3Type & pose,
double delta_time) {
float yaw = 0.f;
// f = m * a ==> a = f / m
Vector3 a = control_force/m;
float roll = 1.0f/g * (a.x()*sin(yaw) - a.y()*cos(yaw));
float pitch = 1.0f/g * (a.x()*cos(yaw) + a.y()*sin(yaw));
float thrust = a.z() + m*g;
mav_msgs::CommandAttitudeThrust msg;
msg.roll = roll; // [rad]
msg.pitch = pitch; // [rad]
msg.yaw_rate = yaw; // [rad/s]
msg.thrust = thrust;
return msg;
}
// TODO: exercise 1 c)
Vector3 computeDesiredForce(const SE3Type & pose, const Vector3 & linear_velocity,
double delta_time) {
SE3Type curr_pose;
Vector3 curr_velocity;
getPoseAndVelocity(curr_pose, curr_velocity);
const float kp = 4.0f; // proportional gains of the PID controller
const float kd = 4.0f; // differential gains of the PID controller
const float ki = 8.0f; // integral gains of the PID controller
// x'' = kp*(xd-x) + kd*(xd'-x') + ki*integral(xd-x, delta_time)
position_integral += delta_time*(pose.translation() - curr_pose.translation());
Vector3 a = kp*(pose.translation() - curr_pose.translation()) +
kd*(linear_velocity - curr_velocity) +
ki*position_integral;
return m*a; // f = m * a
}
// TODO: exercise 1 b)
void getPoseAndVelocity(SE3Type & pose, Vector3 & linear_velocity) {
if (use_ground_thruth_data) {
pose = ground_truth_pose;
linear_velocity = ground_truth_linear_velocity;
} else {
}
}
public:
typedef boost::shared_ptr<UAVController> Ptr;
UAVController(ros::NodeHandle & nh) :
ground_truth_time(0),
position_integral(0,0,0){
use_ground_thruth_data = true;
// ========= Constants ===================================//
g = 9.8; // in rate_controller g = 9.81
m = 1.55; // in rate_controller m = 1.56779
initial_state_covariance = Matrix15::Identity() * 0.001;
gyro_noise = Matrix3::Identity() * 0.0033937;
accel_noise = Matrix3::Identity() * 0.04;
measurement6d_noise = Matrix6::Identity() * 0.01;
initial_pose.translation() << 0, 0, 0.08;
// Set simulated camera to IMU transformation
Eigen::AngleAxisd rollAngle(0.2, Eigen::Vector3d::UnitX());
Eigen::AngleAxisd pitchAngle(-0.1, Eigen::Vector3d::UnitY());
Eigen::AngleAxisd yawAngle(0.3, Eigen::Vector3d::UnitZ());
Eigen::Quaterniond q = yawAngle * pitchAngle * rollAngle;
T_imu_cam.setQuaternion(q);
T_imu_cam.translation() << 0.03, -0.07, 0.1;
// Init subscribers and publishers
imu_sub = nh.subscribe("imu", 10, &UAVController<_Scalar>::imuCallback,
this);
pose_sub = nh.subscribe("pose1", 10,
&UAVController<_Scalar>::pose1Callback, this);
ground_truth_sub = nh.subscribe("ground_truth/pose", 10,
&UAVController<_Scalar>::groundTruthPoseCallback, this);
command_pub = nh.advertise<mav_msgs::CommandAttitudeThrust>(
"command/attitude", 10);
// Wake up simulation, from this point on, you have 30s to initialize
// everything and fly to the evaluation position (x=0m y=0m z=1m).
ROS_INFO("Waking up simulation ... ");
std_srvs::Empty srv;
bool ret = ros::service::call("/gazebo/unpause_physics", srv);
if (ret)
ROS_INFO("... ok");
else {
ROS_FATAL("could not wake up gazebo");
exit(-1);
}
}
~UAVController() {
}
// TODO: exercise 1 e)
void sendControlSignal() {
SE3Type curr_pose;
Vector3 curr_velocity;
Vector3 desired_velocity = Vector3(0,0,0);
double delta_time = 0.001d; // ?
getPoseAndVelocity(curr_pose, curr_velocity);
Vector3 dforce = computeDesiredForce(desired_pose, desired_velocity, delta_time);
command = computeCommandFromForce(dforce, desired_pose, delta_time);
command_pub.publish(command);
}
void setDesiredPose(const SE3Type & p) {
desired_pose = p;
}
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
#endif /* UAV_CONTROLLER_H_ */
<|endoftext|> |
<commit_before>// This file is a part of Simdee, see homepage at http://github.com/tufak/simdee
// This file is distributed under the MIT license.
#ifndef SIMDEE_UTIL_MALLOC_HPP
#define SIMDEE_UTIL_MALLOC_HPP
#include <type_traits>
#include <exception>
#include <cstdlib>
#include <cstdint>
#include "noexcept.hpp"
namespace sd {
namespace detail {
#if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)
// type_traits is buggered in libstdc++ up until GCC 5
template <typename T>
using is_trivially_default_constructible = std::has_trivial_default_constructor<T>;
#else
template <typename T>
using is_trivially_default_constructible = std::is_trivially_default_constructible<T>;
#endif
inline constexpr bool is_pow2(std::size_t x) {
return x && (x & (x - 1)) == 0;
}
template <typename T, std::size_t Align>
struct aligned_allocator;
template <typename T, std::size_t Align = alignof(T), bool Switch = (Align > alignof(double))>
struct alloc;
template <typename T, std::size_t Align>
struct alloc<T, Align, false> {
static T* malloc(std::size_t bytes) {
return (T*)std::malloc(bytes);
}
static void free(T* ptr) {
std::free(ptr);
}
using allocator = std::allocator<T>;
using deleter = std::default_delete<T>;
};
template <typename T, std::size_t Align>
struct alloc<T, Align, true> {
static_assert(detail::is_pow2(Align), "alignment must be a power of 2");
static_assert(Align <= 128, "alignment is too large");
static_assert(Align > alignof(double), "alignment is too small -- use malloc");
static T* malloc(std::size_t bytes) {
auto orig = (uintptr_t)std::malloc(bytes + Align);
if (orig == 0) return nullptr;
auto aligned = (orig + Align) & ~(Align - 1);
auto offset = int8_t(orig - aligned);
((int8_t*)aligned)[-1] = offset;
return (T*)aligned;
}
static void free(T* aligned) {
if (aligned == nullptr) return;
auto offset = ((int8_t*)aligned)[-1];
auto orig = uintptr_t(aligned) + offset;
std::free((void*)orig);
}
using allocator = aligned_allocator<T, Align>;
struct deleter {
template <typename S>
void operator()(S* ptr) {
free(ptr);
}
};
};
template <typename T, std::size_t Align>
struct aligned_allocator {
using value_type = T;
using alloc_t = alloc<T, Align>;
aligned_allocator() = default;
template <typename S>
aligned_allocator(const aligned_allocator<S, Align>&) {}
T* allocate(std::size_t count) const SIMDEE_NOEXCEPT {
return alloc_t::malloc(sizeof(T) * count);
}
void deallocate(T* ptr, std::size_t) const SIMDEE_NOEXCEPT {
alloc_t::free(ptr);
}
void destroy(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_destructible<T>::value) {
if (!std::is_trivially_destructible<T>::value) {
ptr->~T();
}
else {
no_op(ptr); // just to suppress MSVC warning "ptr not referenced"
}
}
static void no_op(T*) {}
void construct(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_constructible<T>::value) {
if (!is_trivially_default_constructible<T>::value) {
new (ptr)T;
}
}
template <typename A1, typename... A>
void construct(T* ptr, A1&& a1, A&&... a2) const {
new (ptr)T(std::forward<A1>(a1), std::forward<A...>(a2)...);
}
// default rebind should do just this, doesn't seem to work in MSVC though
template <typename S>
struct rebind {
using other = aligned_allocator<S, Align>;
};
};
template <typename T, typename U, std::size_t TS, std::size_t US>
bool operator==(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return true; }
template <typename T, typename U, std::size_t TS, std::size_t US>
bool operator!=(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return false; }
}
}
#endif // SIMDEE_UTIL_MALLOC_HPP
<commit_msg>Make allocator's operator== inline<commit_after>// This file is a part of Simdee, see homepage at http://github.com/tufak/simdee
// This file is distributed under the MIT license.
#ifndef SIMDEE_UTIL_MALLOC_HPP
#define SIMDEE_UTIL_MALLOC_HPP
#include <type_traits>
#include <exception>
#include <cstdlib>
#include <cstdint>
#include "noexcept.hpp"
namespace sd {
namespace detail {
#if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)
// type_traits is buggered in libstdc++ up until GCC 5
template <typename T>
using is_trivially_default_constructible = std::has_trivial_default_constructor<T>;
#else
template <typename T>
using is_trivially_default_constructible = std::is_trivially_default_constructible<T>;
#endif
inline constexpr bool is_pow2(std::size_t x) {
return x && (x & (x - 1)) == 0;
}
template <typename T, std::size_t Align>
struct aligned_allocator;
template <typename T, std::size_t Align = alignof(T), bool Switch = (Align > alignof(double))>
struct alloc;
template <typename T, std::size_t Align>
struct alloc<T, Align, false> {
static T* malloc(std::size_t bytes) {
return (T*)std::malloc(bytes);
}
static void free(T* ptr) {
std::free(ptr);
}
using allocator = std::allocator<T>;
using deleter = std::default_delete<T>;
};
template <typename T, std::size_t Align>
struct alloc<T, Align, true> {
static_assert(detail::is_pow2(Align), "alignment must be a power of 2");
static_assert(Align <= 128, "alignment is too large");
static_assert(Align > alignof(double), "alignment is too small -- use malloc");
static T* malloc(std::size_t bytes) {
auto orig = (uintptr_t)std::malloc(bytes + Align);
if (orig == 0) return nullptr;
auto aligned = (orig + Align) & ~(Align - 1);
auto offset = int8_t(orig - aligned);
((int8_t*)aligned)[-1] = offset;
return (T*)aligned;
}
static void free(T* aligned) {
if (aligned == nullptr) return;
auto offset = ((int8_t*)aligned)[-1];
auto orig = uintptr_t(aligned) + offset;
std::free((void*)orig);
}
using allocator = aligned_allocator<T, Align>;
struct deleter {
template <typename S>
void operator()(S* ptr) {
free(ptr);
}
};
};
template <typename T, std::size_t Align>
struct aligned_allocator {
using value_type = T;
using alloc_t = alloc<T, Align>;
aligned_allocator() = default;
template <typename S>
aligned_allocator(const aligned_allocator<S, Align>&) {}
T* allocate(std::size_t count) const SIMDEE_NOEXCEPT {
return alloc_t::malloc(sizeof(T) * count);
}
void deallocate(T* ptr, std::size_t) const SIMDEE_NOEXCEPT {
alloc_t::free(ptr);
}
void destroy(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_destructible<T>::value) {
if (!std::is_trivially_destructible<T>::value) {
ptr->~T();
}
else {
no_op(ptr); // just to suppress MSVC warning "ptr not referenced"
}
}
static void no_op(T*) {}
void construct(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_constructible<T>::value) {
if (!is_trivially_default_constructible<T>::value) {
new (ptr)T;
}
}
template <typename A1, typename... A>
void construct(T* ptr, A1&& a1, A&&... a2) const {
new (ptr)T(std::forward<A1>(a1), std::forward<A...>(a2)...);
}
// default rebind should do just this, doesn't seem to work in MSVC though
template <typename S>
struct rebind {
using other = aligned_allocator<S, Align>;
};
};
template <typename T, typename U, std::size_t TS, std::size_t US>
inline bool operator==(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return true; }
template <typename T, typename U, std::size_t TS, std::size_t US>
inline bool operator!=(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return false; }
}
}
#endif // SIMDEE_UTIL_MALLOC_HPP
<|endoftext|> |
<commit_before>#ifndef VSMC_UTILITY_DISPATCH_HPP
#define VSMC_UTILITY_DISPATCH_HPP
#include <vsmc/internal/common.hpp>
#include <dispatch/dispatch.h>
namespace vsmc {
/// \brief Types of DispatchQueue
/// \ingroup Dispatch
enum DispatchQueueType {
Main, ///< The queue obtained through `dispatch_get_main_queue`
Global, ///< The queue obtained through `dispatch_get_gloal_queue`
Private ///< The queue created by `dispatch_queue_create`
};
template <DispatchQueueType> class DispatchQueue;
/// \brief Base class of Dispatch objects
/// \ingroup Dispatch
///
/// \details All Dispatch objects are reference counting shared objects
template <typename DispatchType>
class DispatchObject
{
public :
/// \brief Create a DispatchObject from its C-type object
///
/// \details
/// The original object will be retained by this object
explicit DispatchObject (DispatchType object) : object_(object)
{dispatch_retain(object);}
DispatchObject (const DispatchObject &other) : object_(other.object_)
{dispatch_retain(object_);}
DispatchObject &operator= (const DispatchObject &other)
{
object_ = other.object_;
dispatch_retain(object_);
return *this;
}
~DispatchObject () {dispatch_release(object_);}
/// \brief Return the underlying Dispatch object
const DispatchType get () const {return object_;}
/// \brief If the object is non-NULL
bool empty () const
{
if (object_)
return false;
else
return true;
}
void *get_context () const {return dispatch_get_context(object_);}
void set_context (void *ctx) {dispatch_set_context(object_, ctx);}
void set_finalizer_f (dispatch_function_t finalizer)
{dispatch_set_finalizer_t(object_, finalizer);}
private :
DispatchType object_;
}; // class DispatchObject
/// \brief Base class of DispatchQueue
/// \ingroup Dispatch
class DispatchQueueBase : public DispatchObject<dispatch_queue_t>
{
public :
void resume () {dispatch_resume(this->get());}
void suspend () {dispatch_suspend(this->get());}
const char *get_label () const
{return dispatch_queue_get_label(this->get());}
#ifdef MAC_OS_X_VERSION_10_7
void *get_specific (const void *key) const
{return dispatch_queue_get_specific(this->get(), key);}
void set_specific (const void *key, void *context,
dispatch_function_t destructor)
{dispatch_queue_set_specific(this->get(), key, context, destructor);}
#endif // MAC_OS_X_VERSION_10_7
/// \brief Set this queue as the target queue for the object
///
/// \details
/// Note that set this queue as the target of an dispatch object will
/// retain the queue.
template <typename DispatchType>
void set_as_target (const DispatchObject<DispatchType> &object) const
{dispatch_set_target_queue(object.get(), this->get());}
void after_f (dispatch_time_t when, void *context,
dispatch_function_t f) const
{dispatch_after_f(when, this->get(), context, f);}
void apply_f (std::size_t iterations, void *context,
void (*work) (void *, std::size_t)) const
{dispatch_apply_f(iterations, this->get(), context, work);}
void async_f (void *context, dispatch_function_t work) const
{dispatch_async_f(this->get(), context, work);}
void sync_f (void *context, dispatch_function_t work) const
{dispatch_sync_f(this->get(), context, work);}
#ifdef MAC_OS_X_VERSION_10_7
void barrier_async_f (void *context, dispatch_function_t work) const
{dispatch_barrier_async_f(this->get(), context, work);}
void barrier_sync_f (void *context, dispatch_function_t work) const
{dispatch_barrier_sync_f(this->get(), context, work);}
#endif // MAC_OS_X_VERSION_10_7
#ifdef __BLOCKS__
void after (dispatch_time_t when, dispatch_block_t block) const
{dispatch_after(when, this->get(), block);}
void apply (std::size_t iterations, void (^block) (std::size_t)) const
{dispatch_apply(iterations, this->get(), block);}
void async (dispatch_block_t block) const
{dispatch_async(this->get(), block);}
void sync (dispatch_block_t block) const
{dispatch_sync(this->get(), block);}
#ifdef MAC_OS_X_VERSION_10_7
void barrier_async (dispatch_block_t block) const
{dispatch_barrier_async(this->get(), block);}
void barrier_sync (dispatch_block_t block) const
{dispatch_barrier_sync(this->get(), block);}
void read (dispatch_fd_t fd, std::size_t length,
void (^handler) (dispatch_data_t, int)) const
{dispatch_read(fd, length, this->get(), handler);}
void write (dispatch_fd_t fd, dispatch_data_t data,
void (^handler) (dispatch_data_t, int)) const
{dispatch_write(fd, data, this->get(), handler);}
#endif // MAC_OS_X_VERSION_10_7
#endif // __BLOCKS__
protected :
DispatchQueueBase (dispatch_queue_t queue) :
DispatchObject<dispatch_queue_t>(queue) {}
DispatchQueueBase (const DispatchQueueBase &other) :
DispatchObject<dispatch_queue_t>(other) {}
DispatchQueueBase &operator= (const DispatchQueueBase &other)
{DispatchObject<dispatch_queue_t>::operator=(other); return *this;}
}; // class DispatchQueueBase
/// \brief The main dispatch queue (`dipatch_get_main_queue`)
/// \ingroup Dispatch
template <>
class DispatchQueue<Main> : public DispatchQueueBase
{
public :
DispatchQueue () : DispatchQueueBase(dispatch_get_main_queue()) {}
}; // class DispatchQueue
/// \brief The global (concurrent) dispatch queue (`dispatch_get_gloal_queue`)
/// \ingroup Dispatch
template <>
class DispatchQueue<Global> : public DispatchQueueBase
{
public :
DispatchQueue (dispatch_queue_priority_t priority =
DISPATCH_QUEUE_PRIORITY_DEFAULT, unsigned long flags = 0) :
DispatchQueueBase(dispatch_get_global_queue(priority, flags)) {}
}; // class DispatchQueue
/// \brief A private dispatch queue (`dispatch_queue_create`)
/// \ingroup Dispatch
template <>
class DispatchQueue<Private> : public DispatchQueueBase
{
public :
DispatchQueue (const char *name, dispatch_queue_attr_t attr = NULL) :
DispatchQueueBase(dispatch_queue_create(name, attr)) {}
~DispatchQueue () {dispatch_release(this->get());}
}; // class DispatchQueue
/// \brief A Dispatch group
/// \ingroup Dispatch
class DispatchGroup : public DispatchObject<dispatch_group_t>
{
public :
DispatchGroup () :
DispatchObject<dispatch_group_t>(dispatch_group_create()) {}
~DispatchGroup () {dispatch_release(this->get());}
void enter () {dispatch_group_enter(this->get());}
void leave () {dispatch_group_leave(this->get());}
long wait (dispatch_time_t timeout)
{return dispatch_group_wait(this->get(), timeout);}
template <DispatchQueueType Type>
void async_f (const DispatchQueue<Type> &queue, void *context,
dispatch_function_t work) const
{dispatch_group_async_f(this->get(), queue.get(), context, work);}
void async_f (dispatch_queue_t queue, void *context,
dispatch_function_t work) const
{dispatch_group_async_f(this->get(), queue, context, work);}
template <DispatchQueueType Type>
void notify_f (const DispatchQueue<Type> &queue, void *context,
dispatch_function_t work) const
{dispatch_group_notify_f(this->get(), queue.get(), context, work);}
void notify_f (dispatch_queue_t queue, void *context,
dispatch_function_t work) const
{dispatch_group_notify_f(this->get(), queue, context, work);}
#ifdef __BLOCKS__
template <DispatchQueueType Type>
void async (const DispatchQueue<Type> &queue,
dispatch_block_t block) const
{dispatch_group_async(this->get(), queue.get(), block);}
void async (dispatch_queue_t queue,
dispatch_block_t block) const
{dispatch_group_async(this->get(), queue, block);}
template <DispatchQueueType Type>
void notify (const DispatchQueue<Type> &queue,
dispatch_block_t block) const
{dispatch_group_notify(this->get(), queue.get(), block);}
void notify (dispatch_queue_t queue,
dispatch_block_t block) const
{dispatch_group_notify(this->get(), queue, block);}
#endif // __BLOCKS__
}; // class DispatchGroup
/// \brief Base class of DispatchSource
/// \ingroup Dispatch
template <dispatch_source_type_t Type>
class DispatchSourceBase : public DispatchObject<dispatch_source_t>
{
public :
void resume () {dispatch_resume(this->get());}
void suspend () {dispatch_suspend(this->get());}
void cancel () {dispatch_source_cancel(this->get());}
long test_cancel () const
{return dispatch_source_test_cancel(this->get());}
unsigned long get_data () const {dispatch_source_get_data(this->get());}
uintptr_t get_handle () const {dispatch_source_get_handle(this->get());}
unsigned long get_mask () const {dispatch_source_get_mask(this->get());}
void set_cancel_handler_f (dispatch_function_t cancel_handler)
{dispatch_source_set_cancel_handler_f(this->get(), cancel_handler);}
void set_event_handler_f (dispatch_function_t event_handler)
{dispatch_source_set_event_handler_f(this->get(), event_handler);}
#ifdef MAC_OS_X_VERSION_10_7
void set_registration_handler_f (dispatch_function_t registration_handler)
{
dispatch_source_set_registration_handler_f(
this->get(), registration_handler);
}
#endif // MAC_OS_X_VERSION_10_7
#ifdef __BLOCKS__
void set_cancel_handler (dispatch_block_t cancel_handler)
{dispatch_source_set_cancel_handler(this->get(), cancel_handler);}
void set_event_handler (dispatch_block_t event_handler)
{dispatch_source_set_event_handler(this->get(), event_handler);}
#ifdef MAC_OS_X_VERSION_10_7
void set_registration_handler (dispatch_block_t registration_handler)
{
dispatch_source_set_registration_handler(
this->get(), registration_handler);
}
#endif // MAC_OS_X_VERSION_10_7
#endif // __BLOCKS__
DispatchSourceBase (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) : DispatchObject<dispatch_source_t>(
dispatch_source_create(Type, handle, mask, queue)) {}
DispatchSourceBase (const DispatchSourceBase &other) :
DispatchObject<dispatch_source_t>(other) {}
DispatchSourceBase &operator= (const DispatchSourceBase &other)
{DispatchObject<dispatch_source_t>::operator=(other); return *this;}
~DispatchSourceBase () {dispatch_release(this->get());}
}; // class DispatchSourceBase
/// \brief A dispatch source
template <dispatch_source_type_t Type>
class DispatchSource : public DispatchSourceBase<Type>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) : DispatchSourceBase<Type>(
handle, mask, queue.get()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) : DispatchSourceBase<Type>(
handle, mask, queue) {}
}; // class DispatchSource
template <>
class DispatchSource<DISPATCH_SOURCE_TYPE_DATA_ADD> :
public DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>(
handle, mask, queue.get()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>(
handle, mask, queue) {}
void merge_data (unsigned long value) const
{dispatch_source_merge_data(this->get(), value);}
}; // class DispatchSource
template <>
class DispatchSource<DISPATCH_SOURCE_TYPE_DATA_OR> :
public DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>(
handle, mask, queue.get()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>(
handle, mask, queue) {}
void merge_data (unsigned long value) const
{dispatch_source_merge_data(this->get(), value);}
}; // class DispatchSource
template <>
class DispatchSource<DISPATCH_SOURCE_TYPE_TIMER> :
public DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(
handle, mask, queue.get()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(
handle, mask, queue) {}
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue,
dispatch_time_t start, uint64_t interval, uint64_t leeway) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(
handle, mask, queue.get())
{set_timer(start, interval, leeway);}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue,
dispatch_time_t start, uint64_t interval, uint64_t leeway) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(
handle, mask, queue)
{set_timer(start, interval, leeway);}
void set_timer (dispatch_time_t start, uint64_t interval, uint64_t leeway)
{dispatch_source_set_timer(this->get(), start, interval, leeway);}
}; // class DispatchSource
} // namespace vsmc
#endif // VSMC_UTILITY_DISPATCH_HPP
<commit_msg>disable use dispatch_queue_priority_t in linux<commit_after>#ifndef VSMC_UTILITY_DISPATCH_HPP
#define VSMC_UTILITY_DISPATCH_HPP
#include <vsmc/internal/common.hpp>
#include <dispatch/dispatch.h>
namespace vsmc {
/// \brief Types of DispatchQueue
/// \ingroup Dispatch
enum DispatchQueueType {
Main, ///< The queue obtained through `dispatch_get_main_queue`
Global, ///< The queue obtained through `dispatch_get_gloal_queue`
Private ///< The queue created by `dispatch_queue_create`
};
template <DispatchQueueType> class DispatchQueue;
/// \brief Base class of Dispatch objects
/// \ingroup Dispatch
///
/// \details All Dispatch objects are reference counting shared objects
template <typename DispatchType>
class DispatchObject
{
public :
/// \brief Create a DispatchObject from its C-type object
///
/// \details
/// The original object will be retained by this object
explicit DispatchObject (DispatchType object) : object_(object)
{dispatch_retain(object);}
DispatchObject (const DispatchObject &other) : object_(other.object_)
{dispatch_retain(object_);}
DispatchObject &operator= (const DispatchObject &other)
{
object_ = other.object_;
dispatch_retain(object_);
return *this;
}
~DispatchObject () {dispatch_release(object_);}
/// \brief Return the underlying Dispatch object
const DispatchType get () const {return object_;}
/// \brief If the object is non-NULL
bool empty () const
{
if (object_)
return false;
else
return true;
}
void *get_context () const {return dispatch_get_context(object_);}
void set_context (void *ctx) {dispatch_set_context(object_, ctx);}
void set_finalizer_f (dispatch_function_t finalizer)
{dispatch_set_finalizer_t(object_, finalizer);}
private :
DispatchType object_;
}; // class DispatchObject
/// \brief Base class of DispatchQueue
/// \ingroup Dispatch
class DispatchQueueBase : public DispatchObject<dispatch_queue_t>
{
public :
void resume () {dispatch_resume(this->get());}
void suspend () {dispatch_suspend(this->get());}
const char *get_label () const
{return dispatch_queue_get_label(this->get());}
#ifdef MAC_OS_X_VERSION_10_7
void *get_specific (const void *key) const
{return dispatch_queue_get_specific(this->get(), key);}
void set_specific (const void *key, void *context,
dispatch_function_t destructor)
{dispatch_queue_set_specific(this->get(), key, context, destructor);}
#endif // MAC_OS_X_VERSION_10_7
/// \brief Set this queue as the target queue for the object
///
/// \details
/// Note that set this queue as the target of an dispatch object will
/// retain the queue.
template <typename DispatchType>
void set_as_target (const DispatchObject<DispatchType> &object) const
{dispatch_set_target_queue(object.get(), this->get());}
void after_f (dispatch_time_t when, void *context,
dispatch_function_t f) const
{dispatch_after_f(when, this->get(), context, f);}
void apply_f (std::size_t iterations, void *context,
void (*work) (void *, std::size_t)) const
{dispatch_apply_f(iterations, this->get(), context, work);}
void async_f (void *context, dispatch_function_t work) const
{dispatch_async_f(this->get(), context, work);}
void sync_f (void *context, dispatch_function_t work) const
{dispatch_sync_f(this->get(), context, work);}
#ifdef MAC_OS_X_VERSION_10_7
void barrier_async_f (void *context, dispatch_function_t work) const
{dispatch_barrier_async_f(this->get(), context, work);}
void barrier_sync_f (void *context, dispatch_function_t work) const
{dispatch_barrier_sync_f(this->get(), context, work);}
#endif // MAC_OS_X_VERSION_10_7
#ifdef __BLOCKS__
void after (dispatch_time_t when, dispatch_block_t block) const
{dispatch_after(when, this->get(), block);}
void apply (std::size_t iterations, void (^block) (std::size_t)) const
{dispatch_apply(iterations, this->get(), block);}
void async (dispatch_block_t block) const
{dispatch_async(this->get(), block);}
void sync (dispatch_block_t block) const
{dispatch_sync(this->get(), block);}
#ifdef MAC_OS_X_VERSION_10_7
void barrier_async (dispatch_block_t block) const
{dispatch_barrier_async(this->get(), block);}
void barrier_sync (dispatch_block_t block) const
{dispatch_barrier_sync(this->get(), block);}
void read (dispatch_fd_t fd, std::size_t length,
void (^handler) (dispatch_data_t, int)) const
{dispatch_read(fd, length, this->get(), handler);}
void write (dispatch_fd_t fd, dispatch_data_t data,
void (^handler) (dispatch_data_t, int)) const
{dispatch_write(fd, data, this->get(), handler);}
#endif // MAC_OS_X_VERSION_10_7
#endif // __BLOCKS__
protected :
DispatchQueueBase (dispatch_queue_t queue) :
DispatchObject<dispatch_queue_t>(queue) {}
DispatchQueueBase (const DispatchQueueBase &other) :
DispatchObject<dispatch_queue_t>(other) {}
DispatchQueueBase &operator= (const DispatchQueueBase &other)
{DispatchObject<dispatch_queue_t>::operator=(other); return *this;}
}; // class DispatchQueueBase
/// \brief The main dispatch queue (`dipatch_get_main_queue`)
/// \ingroup Dispatch
template <>
class DispatchQueue<Main> : public DispatchQueueBase
{
public :
DispatchQueue () : DispatchQueueBase(dispatch_get_main_queue()) {}
}; // class DispatchQueue
/// \brief The global (concurrent) dispatch queue (`dispatch_get_gloal_queue`)
/// \ingroup Dispatch
template <>
class DispatchQueue<Global> : public DispatchQueueBase
{
public :
#ifdef MAC_OS_X_VERSION_10_7
DispatchQueue (dispatch_queue_priority_t priority =
DISPATCH_QUEUE_PRIORITY_DEFAULT, unsigned long flags = 0) :
DispatchQueueBase(dispatch_get_global_queue(priority, flags)) {}
#else // MAC_OS_X_VERSION_10_7
DispatchQueue (long priority = 0, unsigned long flags = 0) :
DispatchQueueBase(dispatch_get_global_queue(priority, flags)) {}
#endif // MAC_OS_X_VERSION_10_7
}; // class DispatchQueue
/// \brief A private dispatch queue (`dispatch_queue_create`)
/// \ingroup Dispatch
template <>
class DispatchQueue<Private> : public DispatchQueueBase
{
public :
DispatchQueue (const char *name, dispatch_queue_attr_t attr = NULL) :
DispatchQueueBase(dispatch_queue_create(name, attr)) {}
~DispatchQueue () {dispatch_release(this->get());}
}; // class DispatchQueue
/// \brief A Dispatch group
/// \ingroup Dispatch
class DispatchGroup : public DispatchObject<dispatch_group_t>
{
public :
DispatchGroup () :
DispatchObject<dispatch_group_t>(dispatch_group_create()) {}
~DispatchGroup () {dispatch_release(this->get());}
void enter () {dispatch_group_enter(this->get());}
void leave () {dispatch_group_leave(this->get());}
long wait (dispatch_time_t timeout)
{return dispatch_group_wait(this->get(), timeout);}
template <DispatchQueueType Type>
void async_f (const DispatchQueue<Type> &queue, void *context,
dispatch_function_t work) const
{dispatch_group_async_f(this->get(), queue.get(), context, work);}
void async_f (dispatch_queue_t queue, void *context,
dispatch_function_t work) const
{dispatch_group_async_f(this->get(), queue, context, work);}
template <DispatchQueueType Type>
void notify_f (const DispatchQueue<Type> &queue, void *context,
dispatch_function_t work) const
{dispatch_group_notify_f(this->get(), queue.get(), context, work);}
void notify_f (dispatch_queue_t queue, void *context,
dispatch_function_t work) const
{dispatch_group_notify_f(this->get(), queue, context, work);}
#ifdef __BLOCKS__
template <DispatchQueueType Type>
void async (const DispatchQueue<Type> &queue,
dispatch_block_t block) const
{dispatch_group_async(this->get(), queue.get(), block);}
void async (dispatch_queue_t queue,
dispatch_block_t block) const
{dispatch_group_async(this->get(), queue, block);}
template <DispatchQueueType Type>
void notify (const DispatchQueue<Type> &queue,
dispatch_block_t block) const
{dispatch_group_notify(this->get(), queue.get(), block);}
void notify (dispatch_queue_t queue,
dispatch_block_t block) const
{dispatch_group_notify(this->get(), queue, block);}
#endif // __BLOCKS__
}; // class DispatchGroup
/// \brief Base class of DispatchSource
/// \ingroup Dispatch
template <dispatch_source_type_t Type>
class DispatchSourceBase : public DispatchObject<dispatch_source_t>
{
public :
void resume () {dispatch_resume(this->get());}
void suspend () {dispatch_suspend(this->get());}
void cancel () {dispatch_source_cancel(this->get());}
long test_cancel () const
{return dispatch_source_test_cancel(this->get());}
unsigned long get_data () const {dispatch_source_get_data(this->get());}
uintptr_t get_handle () const {dispatch_source_get_handle(this->get());}
unsigned long get_mask () const {dispatch_source_get_mask(this->get());}
void set_cancel_handler_f (dispatch_function_t cancel_handler)
{dispatch_source_set_cancel_handler_f(this->get(), cancel_handler);}
void set_event_handler_f (dispatch_function_t event_handler)
{dispatch_source_set_event_handler_f(this->get(), event_handler);}
#ifdef MAC_OS_X_VERSION_10_7
void set_registration_handler_f (dispatch_function_t registration_handler)
{
dispatch_source_set_registration_handler_f(
this->get(), registration_handler);
}
#endif // MAC_OS_X_VERSION_10_7
#ifdef __BLOCKS__
void set_cancel_handler (dispatch_block_t cancel_handler)
{dispatch_source_set_cancel_handler(this->get(), cancel_handler);}
void set_event_handler (dispatch_block_t event_handler)
{dispatch_source_set_event_handler(this->get(), event_handler);}
#ifdef MAC_OS_X_VERSION_10_7
void set_registration_handler (dispatch_block_t registration_handler)
{
dispatch_source_set_registration_handler(
this->get(), registration_handler);
}
#endif // MAC_OS_X_VERSION_10_7
#endif // __BLOCKS__
DispatchSourceBase (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) : DispatchObject<dispatch_source_t>(
dispatch_source_create(Type, handle, mask, queue)) {}
DispatchSourceBase (const DispatchSourceBase &other) :
DispatchObject<dispatch_source_t>(other) {}
DispatchSourceBase &operator= (const DispatchSourceBase &other)
{DispatchObject<dispatch_source_t>::operator=(other); return *this;}
~DispatchSourceBase () {dispatch_release(this->get());}
}; // class DispatchSourceBase
/// \brief A dispatch source
template <dispatch_source_type_t Type>
class DispatchSource : public DispatchSourceBase<Type>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) : DispatchSourceBase<Type>(
handle, mask, queue.get()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) : DispatchSourceBase<Type>(
handle, mask, queue) {}
}; // class DispatchSource
template <>
class DispatchSource<DISPATCH_SOURCE_TYPE_DATA_ADD> :
public DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>(
handle, mask, queue.get()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>(
handle, mask, queue) {}
void merge_data (unsigned long value) const
{dispatch_source_merge_data(this->get(), value);}
}; // class DispatchSource
template <>
class DispatchSource<DISPATCH_SOURCE_TYPE_DATA_OR> :
public DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>(
handle, mask, queue.get()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>(
handle, mask, queue) {}
void merge_data (unsigned long value) const
{dispatch_source_merge_data(this->get(), value);}
}; // class DispatchSource
template <>
class DispatchSource<DISPATCH_SOURCE_TYPE_TIMER> :
public DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(
handle, mask, queue.get()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(
handle, mask, queue) {}
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue,
dispatch_time_t start, uint64_t interval, uint64_t leeway) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(
handle, mask, queue.get())
{set_timer(start, interval, leeway);}
DispatchSource (uintptr_t handle, unsigned long mask,
dispatch_queue_t queue,
dispatch_time_t start, uint64_t interval, uint64_t leeway) :
DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(
handle, mask, queue)
{set_timer(start, interval, leeway);}
void set_timer (dispatch_time_t start, uint64_t interval, uint64_t leeway)
{dispatch_source_set_timer(this->get(), start, interval, leeway);}
}; // class DispatchSource
} // namespace vsmc
#endif // VSMC_UTILITY_DISPATCH_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <gcl/io/policy.hpp>
#include <gcl/functional.hpp>
#include <gcl/cx/typeinfo.hpp>
// #include <gcl/mp/function_traits.hpp>
#include <unordered_map>
#include <functional>
// todo : serializable concept
// todo : add aggregate speciali rule
namespace gcl::io::serialization
{
template <class io_policy = gcl::io::policy::binary>
struct engine {
template <typename on_deserialization_t>
class in {
using type_id_t = uint32_t;
using storage_type = std::unordered_map<type_id_t, std::function<void()>>;
std::istream& input_stream;
on_deserialization_t on_deserialize;
storage_type storage;
template <typename T>
auto generate_type_handler()
{
return std::pair{
gcl::cx::typeinfo::hashcode<T>(), std::function<void()>{[this]() {
T value;
io_policy::read(input_stream, value);
if (not input_stream.good())
throw std::runtime_error{
"serialization::engine::deserialize (value) / storage::mapped::operator() "};
on_deserialize(std::move(value));
}}};
}
public:
in(std::istream& input, on_deserialization_t&& cb)
: input_stream{input}
, on_deserialize{std::forward<decltype(cb)>(cb)}
{}
template <typename... Ts>
// requires ((std::default_initializable<Ts> and ...))
in(std::istream& input, on_deserialization_t&& cb, std::tuple<Ts...>)
: input_stream{input}
, on_deserialize{std::forward<decltype(cb)>(cb)}
, storage{generate_type_handler<Ts>()...}
{}
template <typename... Ts>
void register_types()
{
(storage.insert(generate_type_handler<Ts>()), ...);
}
template <typename... Ts>
void unregister_types()
{
(storage.erase(gcl::cx::typeinfo::hashcode<Ts>()), ...);
}
void deserialize()
{
type_id_t type_id_value;
io_policy::read(input_stream, type_id_value);
if (input_stream.eof())
return;
if (not input_stream.good())
throw std::runtime_error{"serialization::engine::deserialize (typeid)"};
try
{
auto& handler = storage.at(type_id_value);
handler();
}
catch (const std::out_of_range&)
{
throw std::runtime_error{
"serialization::engine::deserialize : unknown type extracted : cx-hash=" +
std::to_string(type_id_value)};
}
}
template <std::size_t count = 1>
void deserialize_n()
{
for (std::size_t i{0}; i < count and not input_stream.eof(); ++i)
{
deserialize();
}
}
void deserialize_all()
{
while (not input_stream.eof())
{
deserialize();
}
}
};
#if __clang__
template <class on_deserialization_t, typename... Ts>
in(std::istream&, on_deserialization_t&&, std::tuple<Ts...>) -> in<on_deserialization_t>;
#endif
class out {
std::ostream& output_stream;
public:
out(std::ostream& output)
: output_stream{output}
{}
template <typename T>
void serialize(T&& value) const
{
io_policy::write(output_stream, gcl::cx::typeinfo::hashcode<T>());
io_policy::write(output_stream, std::forward<T>(value));
}
template <typename T>
const out& operator<<(T&& value) const
{
serialize(std::forward<decltype(value)>(value));
return *this;
}
};
template <typename on_deserialization_t>
using deserializer = in<on_deserialization_t>;
using serializer = out;
};
}
#include <sstream>
namespace gcl::io::tests::serialization
{
static void test()
{
struct event_1 {};
struct event_2 {};
struct event_3 {};
try
{
std::stringstream ss;
using io_engine = typename gcl::io::serialization::engine<gcl::io::policy::binary>;
{
auto serializer = io_engine::out{ss};
serializer << event_1{} << event_2{} << event_3{};
}
{
using types = std::tuple<event_1, event_2, event_3>;
int call_counter{0};
auto deserializer = io_engine::in{
ss,
gcl::functional::overload{
[&call_counter](event_3&&) mutable {
if (++call_counter != 3)
throw std::runtime_error{"gcl::io::tests::serialization::test : event_3"};
},
[&call_counter]<typename T>(T&& arg) mutable {
static_assert(not std::is_same_v<decltype(arg), event_3>);
if constexpr (std::is_same_v<T, event_1>)
if (++call_counter not_eq 1)
throw std::runtime_error{"gcl::io::tests::serialization::test : event_1"};
if constexpr (std::is_same_v<T, event_2>)
if (++call_counter not_eq 2)
throw std::runtime_error{"gcl::io::tests::serialization::test : event_2"};
}},
types{}};
deserializer.deserialize_all();
}
}
catch (const std::exception& error)
{
std::cerr << "error : " << error.what() << '\n';
}
}
}<commit_msg>[io::serialization] engine : add template restriction : T -> serializable<commit_after>#pragma once
// original POC : https://godbolt.org/z/P4a6voYqP
#include <gcl/io/policy.hpp>
#include <gcl/io/concepts.hpp>
#include <gcl/functional.hpp>
#include <gcl/cx/typeinfo.hpp>
// #include <gcl/mp/function_traits.hpp>
#include <unordered_map>
#include <functional>
// todo : serializable concept
// todo : add aggregate speciale rule
namespace gcl::io::serialization
{
template <class io_policy = gcl::io::policy::binary>
struct engine {
template <typename on_deserialization_t>
class in {
using type_id_t = uint32_t;
using storage_type = std::unordered_map<type_id_t, std::function<void()>>;
std::istream& input_stream;
on_deserialization_t on_deserialize;
storage_type storage;
template <gcl::io::concepts::serializable T>
auto generate_type_handler()
{
return std::pair{
gcl::cx::typeinfo::hashcode<T>(), std::function<void()>{[this]() {
T value;
io_policy::read(input_stream, value);
if (not input_stream.good())
throw std::runtime_error{
"serialization::engine::deserialize (value) / storage::mapped::operator() "};
on_deserialize(std::move(value));
}}};
}
public:
in(std::istream& input, on_deserialization_t&& cb)
: input_stream{input}
, on_deserialize{std::forward<decltype(cb)>(cb)}
{}
template <gcl::io::concepts::serializable ... Ts>
in(std::istream& input, on_deserialization_t&& cb, std::tuple<Ts...>)
: input_stream{input}
, on_deserialize{std::forward<decltype(cb)>(cb)}
, storage{generate_type_handler<Ts>()...}
{}
template <gcl::io::concepts::serializable ... Ts>
void register_types()
{
(storage.insert(generate_type_handler<Ts>()), ...);
}
template <typename... Ts>
void unregister_types()
{
(storage.erase(gcl::cx::typeinfo::hashcode<Ts>()), ...);
}
void deserialize()
{
type_id_t type_id_value;
io_policy::read(input_stream, type_id_value);
if (input_stream.eof())
return;
if (not input_stream.good())
throw std::runtime_error{"serialization::engine::deserialize (typeid)"};
try
{
auto& handler = storage.at(type_id_value);
handler();
}
catch (const std::out_of_range&)
{
throw std::runtime_error{
"serialization::engine::deserialize : unknown type extracted : cx-hash=" +
std::to_string(type_id_value)};
}
}
template <std::size_t count = 1>
void deserialize_n()
{
for (std::size_t i{0}; i < count and not input_stream.eof(); ++i)
{
deserialize();
}
}
void deserialize_n(std::size_t count)
{
for (std::size_t i{0}; i < count and not input_stream.eof(); ++i)
{
deserialize();
}
}
void deserialize_all()
{
while (not input_stream.eof())
{
deserialize();
}
}
};
#if __clang__
template <class on_deserialization_t, typename... Ts>
in(std::istream&, on_deserialization_t&&, std::tuple<Ts...>) -> in<on_deserialization_t>;
#endif
class out {
std::ostream& output_stream;
public:
out(std::ostream& output)
: output_stream{output}
{}
template <typename T>
void serialize(T&& value) const
{
io_policy::write(output_stream, gcl::cx::typeinfo::hashcode<T>());
io_policy::write(output_stream, std::forward<T>(value));
}
template <typename T>
const out& operator<<(T&& value) const
{
serialize(std::forward<decltype(value)>(value));
return *this;
}
};
template <typename on_deserialization_t>
using deserializer = in<on_deserialization_t>;
using serializer = out;
};
}
#include <sstream>
namespace gcl::io::tests::serialization
{
static void test()
{
struct event_1 {};
struct event_2 {};
struct event_3 {};
try
{
std::stringstream ss;
using io_engine = typename gcl::io::serialization::engine<gcl::io::policy::binary>;
{
auto serializer = io_engine::out{ss};
serializer << event_1{} << event_2{} << event_3{};
}
{
using types = std::tuple<event_1, event_2, event_3>;
int call_counter{0};
auto deserializer = io_engine::in{
ss,
gcl::functional::overload{
[&call_counter](event_3&&) mutable {
if (++call_counter != 3)
throw std::runtime_error{"gcl::io::tests::serialization::test : event_3"};
},
[&call_counter]<typename T>(T&& arg) mutable {
static_assert(not std::is_same_v<decltype(arg), event_3>);
if constexpr (std::is_same_v<T, event_1>)
if (++call_counter not_eq 1)
throw std::runtime_error{"gcl::io::tests::serialization::test : event_1"};
if constexpr (std::is_same_v<T, event_2>)
if (++call_counter not_eq 2)
throw std::runtime_error{"gcl::io::tests::serialization::test : event_2"};
}},
types{}};
deserializer.deserialize_all();
}
}
catch (const std::exception& error)
{
std::cerr << "error : " << error.what() << '\n';
}
}
}<|endoftext|> |
<commit_before>#ifndef IMAGE_CLOUD_COMMON_PIPELINE_POINTCLOUD_H_
#define IMAGE_CLOUD_COMMON_PIPELINE_POINTCLOUD_H_
#include <image_cloud/common/filter/pcl/common.hpp>
#include <image_cloud/common/filter/pcl/filter_depth_intensity.hpp>
#include <image_cloud/common/filter/pcl/segmentation.hpp>
#include <image_cloud/common/filter/pcl/depth_filter.hpp>
#include <image_cloud/common/filter/pcl/depth_edge.hpp>
#include <image_cloud/common/filter/pcl/normal_diff_filter.hpp>
#include <image_cloud/common/filter/pcl/range_borders.hpp>
#include <image_cloud/common/filter/pcl/remove_cluster_2d.hpp>
#include <image_cloud/common/filter/pcl/depth_filter_radius.hpp>
#include <image_cloud/common/filter/pcl/depth_filter_neighbors.hpp>
#include <image_cloud/common/filter/pcl/filter_depth_projection.hpp>
#include <image_cloud/common/filter/pcl/hit_same_point.hpp>
#include <image_cloud/common/filter/pcl/edge_image_plane.hpp>
#include <image_cloud/common/project2d.hpp>
#include <image_cloud/common/calibration/pipeline/enums.h>
#include <assert.h>
#include <opencv2/opencv.hpp>
namespace image_cloud{
template <typename PointT>
inline void
filter3d_switch(const pcl::PointCloud<PointT> &in_points,
pcl::PointCloud<PointT> &out_points,
const image_geometry::PinholeCameraModel &camera_model,
pcl_filter::Filter3d filter,
int rows=0,
int cols=0){
switch (filter)
{
case pcl_filter::OFF:
out_points = in_points;
break;
case pcl_filter::DEPTH:
{
filter_3d::filter_depth_discontinuity(in_points, out_points); // epsilon
}
break;
case pcl_filter::DEPTH_INTENSITY:
{
std::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,
std::vector<boost::shared_ptr<PointT> > (rows));
Projected_pointcloud<PointT> projected_pointclouds;
project2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);
filter_3d::filter_depth_intensity<PointT>(map, out_points);
}
break;
case pcl_filter::DEPTH_EDGE:
{
std::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,
std::vector<boost::shared_ptr<PointT> > (rows));
Projected_pointcloud<PointT> projected_pointclouds;
project2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);
filter_3d::depth_edge<PointT>(map, out_points); // neighbors
}
break;
case pcl_filter::NORMAL_DIFF:
{
filter_3d::normal_diff_filter<PointT>(in_points, out_points); // threshold
}
break;
case pcl_filter::REMOVE_CLUSTER_2D:
{
filter_3d::remove_cluster_2d<PointT>(camera_model, in_points, out_points, rows, cols); // threshold
}
break;
case pcl_filter::RANGE_BORDERS:
{
filter_3d::range_borders<PointT>(in_points, out_points); // threshold
}
break;
case pcl_filter::DEPTH_RADIUS:
{
filter_3d::depth_discontinuity_radius<PointT>(in_points, out_points); // min neighbors
}
break;
case pcl_filter::DEPTH_NEIGHBORS:
{
filter_3d::depth_filter_neighbors<PointT>(in_points, out_points); // max distance
}
break;
case pcl_filter::DEPTH_EDGE_PROJECTION:
{
filter_3d::filter_depth_projection<PointT>(camera_model, in_points, out_points, rows, cols); // neighbors); // max distance
}
break;
case pcl_filter::HIT_SAME_POINT:
{
filter_3d::hit_same_point<PointT>(camera_model, in_points, out_points, rows, cols);
}
break;
case pcl_filter::OTHER:
{
filter_3d::segmentation<PointT>(in_points, out_points);
//filtred = transformed;
}
break;
case pcl_filter::DEPTH_INTENSITY_NORMAL_DIFF:
{
std::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,
std::vector<boost::shared_ptr<PointT> > (rows));
Projected_pointcloud<PointT> projected_pointclouds;
project2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);
pcl::PointCloud<PointT> temp_points;
filter_3d::filter_depth_intensity<PointT>(map, temp_points);
filter_3d::depth_discontinuity_radius<PointT>(temp_points, out_points, 0.5, 0.05, 70); // min neighbors
//filter_3d::normal_diff_filter<PointT>(temp_points, out_points);
}
break;
case pcl_filter::DEPTH_INTENSITY_AND_REMOVE_CLUSER_2D:
{
std::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,
std::vector<boost::shared_ptr<PointT> > (rows));
Projected_pointcloud<PointT> projected_pointclouds;
project2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);
pcl::PointCloud<PointT> temp_points;
filter_3d::filter_depth_intensity<PointT>(map, temp_points);
filter_3d::remove_cluster_2d<PointT>(camera_model, temp_points, out_points, rows, cols); // threshold
}
break;
case pcl_filter::REMOVE_CLUSER_2D_RADIUS_SEARCH:
{
pcl::PointCloud<PointT> temp_points;
filter_3d::remove_cluster_2d<PointT>(camera_model, in_points, temp_points, rows, cols); // threshold
filter_3d::depth_discontinuity_radius<PointT>(temp_points, out_points); // min neighbors
}
break;
case pcl_filter::EDGE_IMAGE_PLANE:
{
filter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, out_points, rows, cols);
}
break;
case pcl_filter::EDGE_IMAGE_PLANE_2D_RADIUS_SEARCH:
{
pcl::PointCloud<PointT> temp_points;
filter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, temp_points, rows, cols);
filter_3d::remove_cluster_2d<PointT>(camera_model,temp_points, out_points, rows, cols); // min neighbors
}
break;
case pcl_filter::EDGE_IMAGE_PLANE_NORMAL_DIFF:
{
pcl::PointCloud<PointT> temp_points;
filter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, temp_points, rows, cols);
filter_3d::normal_diff_filter<PointT>(temp_points, out_points, 0.001,0.1);
}
break;
default:
break;
}
}
}
#endif
<commit_msg>added depth_edge_projection filter for aggregated pointclouds<commit_after>#ifndef IMAGE_CLOUD_COMMON_PIPELINE_POINTCLOUD_H_
#define IMAGE_CLOUD_COMMON_PIPELINE_POINTCLOUD_H_
#include <image_cloud/common/filter/pcl/common.hpp>
#include <image_cloud/common/filter/pcl/filter_depth_intensity.hpp>
#include <image_cloud/common/filter/pcl/segmentation.hpp>
#include <image_cloud/common/filter/pcl/depth_filter.hpp>
#include <image_cloud/common/filter/pcl/depth_edge.hpp>
#include <image_cloud/common/filter/pcl/normal_diff_filter.hpp>
#include <image_cloud/common/filter/pcl/range_borders.hpp>
#include <image_cloud/common/filter/pcl/remove_cluster_2d.hpp>
#include <image_cloud/common/filter/pcl/depth_filter_radius.hpp>
#include <image_cloud/common/filter/pcl/depth_filter_neighbors.hpp>
#include <image_cloud/common/filter/pcl/filter_depth_projection.hpp>
#include <image_cloud/common/filter/pcl/hit_same_point.hpp>
#include <image_cloud/common/filter/pcl/edge_image_plane.hpp>
#include <image_cloud/common/project2d.hpp>
#include <image_cloud/common/calibration/pipeline/enums.h>
#include <assert.h>
#include <opencv2/opencv.hpp>
namespace image_cloud{
template <typename PointT>
inline void
filter3d_switch(const pcl::PointCloud<PointT> &in_points,
pcl::PointCloud<PointT> &out_points,
const image_geometry::PinholeCameraModel &camera_model,
pcl_filter::Filter3d filter,
int rows=0,
int cols=0){
switch (filter)
{
case pcl_filter::OFF:
out_points = in_points;
break;
case pcl_filter::DEPTH:
{
filter_3d::filter_depth_discontinuity(in_points, out_points); // epsilon
}
break;
case pcl_filter::DEPTH_INTENSITY:
{
std::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,
std::vector<boost::shared_ptr<PointT> > (rows));
Projected_pointcloud<PointT> projected_pointclouds;
project2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);
filter_3d::filter_depth_intensity<PointT>(map, out_points);
}
break;
case pcl_filter::DEPTH_EDGE:
{
std::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,
std::vector<boost::shared_ptr<PointT> > (rows));
Projected_pointcloud<PointT> projected_pointclouds;
project2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);
filter_3d::depth_edge<PointT>(map, out_points); // neighbors
}
break;
case pcl_filter::NORMAL_DIFF:
{
filter_3d::normal_diff_filter<PointT>(in_points, out_points); // threshold
}
break;
case pcl_filter::REMOVE_CLUSTER_2D:
{
filter_3d::remove_cluster_2d<PointT>(camera_model, in_points, out_points, rows, cols); // threshold
}
break;
case pcl_filter::RANGE_BORDERS:
{
filter_3d::range_borders<PointT>(in_points, out_points); // threshold
}
break;
case pcl_filter::DEPTH_RADIUS:
{
filter_3d::depth_discontinuity_radius<PointT>(in_points, out_points); // min neighbors
}
break;
case pcl_filter::DEPTH_NEIGHBORS:
{
filter_3d::depth_filter_neighbors<PointT>(in_points, out_points); // max distance
}
break;
case pcl_filter::DEPTH_EDGE_PROJECTION:
{
filter_3d::filter_depth_projection<PointT>(camera_model, in_points, out_points, rows, cols); // neighbors); // max distance
}
break;
case pcl_filter::HIT_SAME_POINT:
{
filter_3d::hit_same_point<PointT>(camera_model, in_points, out_points, rows, cols);
}
break;
case pcl_filter::OTHER:
{
filter_3d::segmentation<PointT>(in_points, out_points);
//filtred = transformed;
}
break;
case pcl_filter::DEPTH_INTENSITY_NORMAL_DIFF:
{
std::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,
std::vector<boost::shared_ptr<PointT> > (rows));
Projected_pointcloud<PointT> projected_pointclouds;
project2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);
pcl::PointCloud<PointT> temp_points;
filter_3d::filter_depth_intensity<PointT>(map, temp_points);
filter_3d::depth_discontinuity_radius<PointT>(temp_points, out_points, 0.5, 0.05, 70); // min neighbors
//filter_3d::normal_diff_filter<PointT>(temp_points, out_points);
}
break;
case pcl_filter::DEPTH_INTENSITY_AND_REMOVE_CLUSER_2D:
{
std::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,
std::vector<boost::shared_ptr<PointT> > (rows));
Projected_pointcloud<PointT> projected_pointclouds;
project2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);
pcl::PointCloud<PointT> temp_points;
filter_3d::filter_depth_intensity<PointT>(map, temp_points);
filter_3d::remove_cluster_2d<PointT>(camera_model, temp_points, out_points, rows, cols); // threshold
}
break;
case pcl_filter::REMOVE_CLUSER_2D_RADIUS_SEARCH:
{
pcl::PointCloud<PointT> temp_points;
filter_3d::remove_cluster_2d<PointT>(camera_model, in_points, temp_points, rows, cols); // threshold
filter_3d::depth_discontinuity_radius<PointT>(temp_points, out_points); // min neighbors
}
break;
case pcl_filter::EDGE_IMAGE_PLANE:
{
filter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, out_points, rows, cols);
}
break;
case pcl_filter::EDGE_IMAGE_PLANE_2D_RADIUS_SEARCH:
{
pcl::PointCloud<PointT> temp_points;
filter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, temp_points, rows, cols);
filter_3d::remove_cluster_2d<PointT>(camera_model,temp_points, out_points, rows, cols); // min neighbors
}
break;
case pcl_filter::EDGE_IMAGE_PLANE_NORMAL_DIFF:
{
pcl::PointCloud<PointT> temp_points;
filter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, temp_points, rows, cols);
filter_3d::normal_diff_filter<PointT>(temp_points, out_points, 0.001,0.1);
}
break;
case pcl_filter::DEPTH_EDGE_PROJECTION_AGGREGATED:
{
filter_3d::filter_depth_projection<PointT>(camera_model, in_points, out_points, rows, cols, 2, 1.5); // neighbors); // max distance
}
break;
default:
break;
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "bloomierFilter.h"
BloomierFilter::BloomierFilter(size_t pM, size_t pK, size_t pQ){
// mHashSeed = pHashSeed;
mM = pM;;
mK = pK;
mQ = pQ;
// mKeyDict = pKeyDict;
mBitVectorSize = ceil(pQ / static_cast<float>(CHAR_BIT));
mBloomierHash = new BloomierHash(pM, pK, mBitVectorSize);
mOrderAndMatchFinder = new OrderAndMatchFinder(pM, pK, pQ, mBloomierHash);
// vsize_t orderAndMatch = mOrderAndMatchFinder.find(); // datatype?
// mByteSize = this->getByteSize(pQ);
mTable = new bloomierTable(pM);
mValueTable = new vvsize_t_p(pM);
for (size_t i = 0; i < pM; ++i) {
(*mTable)[i] = new bitVector(mBitVectorSize, 0);
(*mValueTable)[i] = new vsize_t();
}
// mValueTable = new vvsize_t_p(pM);
mEncoder = new Encoder(mBitVectorSize);
mPiIndex = 0;
// this->create(pKeyDict, orderAndMatch);
}
BloomierFilter::~BloomierFilter(){
}
void BloomierFilter::check() {
std::cout << __LINE__ << std::endl;
size_t sumTable = 0;
for(size_t i = 0; i < mTable->size(); ++i) {
sumTable += (*mTable)[i]->size();
}
std::cout << __LINE__ << std::endl;
size_t sumValueTable = 0;
for(size_t i = 0; i < mValueTable->size(); ++i) {
sumValueTable += (*mValueTable)[i]->size();
}
std::cout << "sumTable: " << sumTable << std::endl;
std::cout << "sumValueTable: " << sumValueTable << std::endl;
std::cout << __LINE__ << std::endl;
}
bloomierTable* BloomierFilter::getTable() {
return mTable;
}
void BloomierFilter::setTable(bloomierTable* pTable) {
mTable = pTable;
}
vvsize_t_p* BloomierFilter::getValueTable() {
return mValueTable;
}
void BloomierFilter::setValueTable(vvsize_t_p* pTable) {
mValueTable = pTable;
}
void BloomierFilter::xorOperation(bitVector* pValue, bitVector* pMask, vsize_t* pNeighbors) {
// std::cout << "41" << std::endl;
// std::cout << __LINE__ << std::endl;
this->xorBitVector(pValue, pMask);
// std::cout << "44" << std::endl;
// std::cout << __LINE__ << std::endl;
for (auto it = pNeighbors->begin(); it != pNeighbors->end(); ++it) {
// std::cout << "47" << std::endl;
// std::cout << __LINE__ << std::endl;
if (*it < pNeighbors->size()) {
this->xorBitVector(pValue, (*mTable)[(*it)]);
}
// std::cout << __LINE__ << std::endl;
// std::cout << "50" << std::endl;
}
// return pValue;
}
vsize_t* BloomierFilter::get(size_t pKey) {
std::cout << __LINE__ << std::endl;
check();
std::cout << __LINE__ << std::endl;
vsize_t* neighbors = mBloomierHash->getKNeighbors(pKey, mK, mM);
std::cout << __LINE__ << ":)" << std::endl;
bitVector* mask = mBloomierHash->getMask(pKey);
std::cout << __LINE__ << ":(" << std::endl;
bitVector* valueToGet = new bitVector(mBitVectorSize, 0);
std::cout << __LINE__ << std::endl;
this->xorOperation(valueToGet, mask, neighbors);
std::cout << __LINE__ << std::endl;
size_t h = mEncoder->decode(valueToGet);
std::cout << __LINE__ << std::endl;
if (h < neighbors->size()) {
std::cout << __LINE__ << std::endl;
size_t L = (*neighbors)[h];
std::cout << __LINE__ << std::endl;
if (L < mValueTable->size()) {
std::cout << __LINE__ << std::endl;
return (*mValueTable)[L];
}
}
std::cout << __LINE__ << std::endl;
check();
std::cout << __LINE__ << std::endl;
return new vsize_t();
}
bool BloomierFilter::set(size_t pKey, size_t pValue) {
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
vsize_t* neighbors = mBloomierHash->getKNeighbors(pKey, mK, mM);
bitVector* mask = mBloomierHash->getMask(pKey);
bitVector* valueToGet = new bitVector(mBitVectorSize, 0);
this->xorOperation(valueToGet, mask, neighbors);
size_t h = mEncoder->decode(valueToGet);
// std::cout << __LINE__ << std::endl;
if (h < neighbors->size()) {
size_t L = (*neighbors)[h];
if (L < mValueTable->size()) {
vsize_t* v = ((*mValueTable)[L]);
// if (v == NULL) {
// v = new vsize_t();
// }
// std::cout << __LINE__ << std::endl;
v->push_back(pValue);
// std::cout << __LINE__ << std::endl;
// (*mValueTable)[L] = v;
// std::cout << __LINE__ << std::endl;
return true;
}
// std::cout << __LINE__ << std::endl;
} else {
// std::cout << __LINE__ << std::endl;
vsize_t* keys = new vsize_t (1, pKey);
vvsize_t_p* values = new vvsize_t_p (1);
(*values)[0] = new vsize_t(1, pValue);
this->create(keys, values, mPiIndex);
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
return true;
}
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
return false;
}
void BloomierFilter::create(vsize_t* pKeys, vvsize_t_p* pValues, size_t piIndex) {
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
// std::cout << "size if pKeys: " << pKeys->size() << std::endl;
// std::cout << std::endl;
mOrderAndMatchFinder->find(pKeys);
// std::cout << "120" << std::endl;
vsize_t* piVector = mOrderAndMatchFinder->getPiVector();
// std::cout << "123" << std::endl;
vsize_t* tauVector = mOrderAndMatchFinder->getTauVector();
// std::cout << "piVector" << std::endl;
// for (size_t i = 0; i < piVector->size(); ++i) {
// std::cout << "\t" << (*piVector)[i] << std::endl;
// }
for (size_t i = piIndex; i < piVector->size(); ++i) {
// size_t key = (*piList)[i];
// size_t value = pAssignment[key];
vsize_t* neighbors = mBloomierHash->getKNeighbors((*pKeys)[i], mK, mM);
bitVector* mask = mBloomierHash->getMask((*pKeys)[i]);
size_t l = (*tauVector)[i];
size_t L = (*neighbors)[l];
bitVector* encodeValue = mEncoder->encode(l);
bitVector* valueToStore = new bitVector(mBitVectorSize, 0);
this->xorBitVector(valueToStore, encodeValue);
this->xorBitVector(valueToStore, mask);
for (size_t j = 0; j < neighbors->size(); ++j) {
if (j != l) {
this->xorBitVector(valueToStore, (*mTable)[(*neighbors)[i]]);
}
}
(*mTable)[L] = valueToStore;
// std::cout << "size of piVector: " << piVector->size() << std::endl;
// std::cout << "i: " << i << std::endl;
// std::cout << "size of pvalues: " << pValues->size() << std::endl;
(*mValueTable)[L] = (*pValues)[i-piIndex];
}
mPiIndex = mPiIndex + pKeys->size();
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
}
void BloomierFilter::xorBitVector(bitVector* pResult, bitVector* pInput) {
size_t length = std::min(pResult->size(), pInput->size());
for (size_t i = 0; i < length; ++i) {
(*pResult)[i] = (*pResult)[i] ^ (*pInput)[i];
}
}<commit_msg>bug fix<commit_after>#include "bloomierFilter.h"
BloomierFilter::BloomierFilter(size_t pM, size_t pK, size_t pQ){
// mHashSeed = pHashSeed;
mM = pM;;
mK = pK;
mQ = pQ;
// mKeyDict = pKeyDict;
mBitVectorSize = ceil(pQ / static_cast<float>(CHAR_BIT));
mBloomierHash = new BloomierHash(pM, pK, mBitVectorSize);
mOrderAndMatchFinder = new OrderAndMatchFinder(pM, pK, pQ, mBloomierHash);
// vsize_t orderAndMatch = mOrderAndMatchFinder.find(); // datatype?
// mByteSize = this->getByteSize(pQ);
mTable = new bloomierTable(pM);
mValueTable = new vvsize_t_p(pM);
for (size_t i = 0; i < pM; ++i) {
(*mTable)[i] = new bitVector(mBitVectorSize, 0);
(*mValueTable)[i] = new vsize_t();
}
// mValueTable = new vvsize_t_p(pM);
mEncoder = new Encoder(mBitVectorSize);
mPiIndex = 0;
// this->create(pKeyDict, orderAndMatch);
}
BloomierFilter::~BloomierFilter(){
}
void BloomierFilter::check() {
std::cout << __LINE__ << std::endl;
size_t sumTable = 0;
for(size_t i = 0; i < mTable->size(); ++i) {
sumTable += (*mTable)[i]->size();
}
std::cout << __LINE__ << std::endl;
size_t sumValueTable = 0;
for(size_t i = 0; i < mValueTable->size(); ++i) {
sumValueTable += (*mValueTable)[i]->size();
}
std::cout << "sumTable: " << sumTable << std::endl;
std::cout << "sumValueTable: " << sumValueTable << std::endl;
std::cout << __LINE__ << std::endl;
}
bloomierTable* BloomierFilter::getTable() {
return mTable;
}
void BloomierFilter::setTable(bloomierTable* pTable) {
mTable = pTable;
}
vvsize_t_p* BloomierFilter::getValueTable() {
return mValueTable;
}
void BloomierFilter::setValueTable(vvsize_t_p* pTable) {
mValueTable = pTable;
}
void BloomierFilter::xorOperation(bitVector* pValue, bitVector* pMask, vsize_t* pNeighbors) {
// std::cout << "41" << std::endl;
// std::cout << __LINE__ << std::endl;
this->xorBitVector(pValue, pMask);
// std::cout << "44" << std::endl;
// std::cout << __LINE__ << std::endl;
for (auto it = pNeighbors->begin(); it != pNeighbors->end(); ++it) {
// std::cout << "47" << std::endl;
// std::cout << __LINE__ << std::endl;
if (*it < pNeighbors->size()) {
this->xorBitVector(pValue, (*mTable)[(*it)]);
}
// std::cout << __LINE__ << std::endl;
// std::cout << "50" << std::endl;
}
// return pValue;
}
vsize_t* BloomierFilter::get(size_t pKey) {
std::cout << __LINE__ << std::endl;
check();
std::cout << __LINE__ << std::endl;
vsize_t* neighbors = mBloomierHash->getKNeighbors(pKey, mK, mM);
std::cout << __LINE__ << ":)" << std::endl;
bitVector* mask = mBloomierHash->getMask(pKey);
std::cout << __LINE__ << ":(" << std::endl;
bitVector* valueToGet = new bitVector(mBitVectorSize, 0);
std::cout << __LINE__ << std::endl;
this->xorOperation(valueToGet, mask, neighbors);
std::cout << __LINE__ << std::endl;
size_t h = mEncoder->decode(valueToGet);
std::cout << __LINE__ << std::endl;
if (h < neighbors->size()) {
std::cout << __LINE__ << std::endl;
size_t L = (*neighbors)[h];
std::cout << __LINE__ << std::endl;
if (L < mValueTable->size()) {
std::cout << __LINE__ << std::endl;
return (*mValueTable)[L];
}
}
std::cout << __LINE__ << std::endl;
check();
std::cout << __LINE__ << std::endl;
return new vsize_t();
}
bool BloomierFilter::set(size_t pKey, size_t pValue) {
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
vsize_t* neighbors = mBloomierHash->getKNeighbors(pKey, mK, mM);
bitVector* mask = mBloomierHash->getMask(pKey);
bitVector* valueToGet = new bitVector(mBitVectorSize, 0);
this->xorOperation(valueToGet, mask, neighbors);
size_t h = mEncoder->decode(valueToGet);
// std::cout << __LINE__ << std::endl;
if (h < neighbors->size()) {
size_t L = (*neighbors)[h];
if (L < mValueTable->size()) {
vsize_t* v = ((*mValueTable)[L]);
// if (v == NULL) {
// v = new vsize_t();
// }
// std::cout << __LINE__ << std::endl;
v->push_back(pValue);
// std::cout << __LINE__ << std::endl;
// (*mValueTable)[L] = v;
// std::cout << __LINE__ << std::endl;
return true;
}
// std::cout << __LINE__ << std::endl;
} else {
// std::cout << __LINE__ << std::endl;
vsize_t* keys = new vsize_t (1, pKey);
vvsize_t_p* values = new vvsize_t_p (1);
(*values)[0] = new vsize_t(1, pValue);
this->create(keys, values, mPiIndex);
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
return true;
}
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
return false;
}
void BloomierFilter::create(vsize_t* pKeys, vvsize_t_p* pValues, size_t piIndex) {
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
// std::cout << "size if pKeys: " << pKeys->size() << std::endl;
// std::cout << std::endl;
mOrderAndMatchFinder->find(pKeys);
// std::cout << "120" << std::endl;
vsize_t* piVector = mOrderAndMatchFinder->getPiVector();
// std::cout << "123" << std::endl;
vsize_t* tauVector = mOrderAndMatchFinder->getTauVector();
// std::cout << "piVector" << std::endl;
// for (size_t i = 0; i < piVector->size(); ++i) {
// std::cout << "\t" << (*piVector)[i] << std::endl;
// }
for (size_t i = piIndex; i < piVector->size(); ++i) {
// size_t key = (*piList)[i];
// size_t value = pAssignment[key];
vsize_t* neighbors = mBloomierHash->getKNeighbors((*pKeys)[i], mK, mM);
bitVector* mask = mBloomierHash->getMask((*pKeys)[i]);
size_t l = (*tauVector)[i];
size_t L = (*neighbors)[l];
bitVector* encodeValue = mEncoder->encode(l);
// bitVector* valueToStore = new bitVector(mBitVectorSize, 0);
this->xorBitVector((*mTable)[L], encodeValue);
this->xorBitVector((*mTable)[L], mask);
for (size_t j = 0; j < neighbors->size(); ++j) {
if (j != l) {
this->xorBitVector((*mTable)[L], (*mTable)[(*neighbors)[j]]);
}
}
// (*mTable)[L] = valueToStore;
// std::cout << "size of piVector: " << piVector->size() << std::endl;
// std::cout << "i: " << i << std::endl;
// std::cout << "size of pvalues: " << pValues->size() << std::endl;
(*mValueTable)[L] = (*pValues)[i-piIndex];
}
mPiIndex = mPiIndex + pKeys->size();
// std::cout << __LINE__ << std::endl;
// check();
// std::cout << __LINE__ << std::endl;
}
void BloomierFilter::xorBitVector(bitVector* pResult, bitVector* pInput) {
size_t length = std::min(pResult->size(), pInput->size());
for (size_t i = 0; i < length; ++i) {
(*pResult)[i] = (*pResult)[i] ^ (*pInput)[i];
}
}<|endoftext|> |
<commit_before>#include "thruster_tortuga.h"
ThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){
ros::Rate loop_rate(rate);
subscriber = n.subscribe("/qubo/thruster_input", 1000, &ThrusterTortugaNode::thrusterCallBack, this);
ROS_DEBUG("Opening sensorboard");
sensor_file = "/dev/sensor";
fd = openSensorBoard(sensor_file.c_str());
ROS_DEBUG("Opened sensorboard with fd %d.", fd);
checkError(syncBoard(fd));
ROS_DEBUG("Synced with the Board");
//GH: This is not the correct use of checkError.
//It should be called on the return value of a function call, not on the file descriptor.
//checkError(fd);
// Unsafe all the thrusters
ROS_DEBUG("Unsafing all thrusters");
for (int i = 6; i <= 11; i++) {
checkError(setThrusterSafety(fd, i));
}
ROS_DEBUG("Unsafed all thrusters");
}
ThrusterTortugaNode::~ThrusterTortugaNode(){
//Stop all the thrusters
ROS_DEBUG("Stopping thrusters");
readSpeedResponses(fd);
setSpeeds(fd, 0, 0, 0, 0, 0, 0);
ROS_DEBUG("Safing thrusters");
// Safe all the thrusters
for (int i = 0; i <= 5; i++) {
checkError(setThrusterSafety(fd, i));
}
ROS_DEBUG("Safed thrusters");
//Close the sensorboard
close(fd);
}
void ThrusterTortugaNode::update(){
//I think we need to initialize thrusters and stuff before this will work
ros::spinOnce();
// setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);
// ROS_DEBUG("fd = %x",fd);
ROS_DEBUG("Setting thruster speeds");
int retR = readSpeedResponses(fd);
ROS_DEBUG("Read speed before: %x", retR);
int retS = setSpeeds(fd, 128, 128, 128, 128, 128, 128);
ROS_DEBUG("Set speed status: %x", retS);
usleep(20*1000);
int retA = readSpeedResponses(fd);
ROS_DEBUG("Read speed after: %x", retA);
ROS_DEBUG("thruster state = %x", readThrusterState(fd));
ROS_DEBUG("set speed returns %x", retS);
ROS_DEBUG("read speed returns %x", retR);
}
void ThrusterTortugaNode::publish(){
// setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);
}
void ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){
//SG: TODO change this shit
for(int i = 0 ;i < NUM_THRUSTERS; i++){
thruster_powers.data[i] = new_powers.data[i];
}
}
//ssh [email protected]
<commit_msg>intialized power values<commit_after>#include "thruster_tortuga.h"
ThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){
ros::Rate loop_rate(rate);
subscriber = n.subscribe("/qubo/thruster_input", 1000, &ThrusterTortugaNode::thrusterCallBack, this);
ROS_DEBUG("Opening sensorboard");
sensor_file = "/dev/sensor";
fd = openSensorBoard(sensor_file.c_str());
ROS_DEBUG("Opened sensorboard with fd %d.", fd);
checkError(syncBoard(fd));
ROS_DEBUG("Synced with the Board");
//GH: This is not the correct use of checkError.
//It should be called on the return value of a function call, not on the file descriptor.
//checkError(fd);
// Unsafe all the thrusters
ROS_DEBUG("Unsafing all thrusters");
for (int i = 6; i <= 11; i++) {
checkError(setThrusterSafety(fd, i));
}
ROS_DEBUG("Unsafed all thrusters");
for(int i = 0 ;i < NUM_THRUSTERS; i++){
thruster_powers.data[i] = 0;
}
}
}
ThrusterTortugaNode::~ThrusterTortugaNode(){
//Stop all the thrusters
ROS_DEBUG("Stopping thrusters");
readSpeedResponses(fd);
setSpeeds(fd, 0, 0, 0, 0, 0, 0);
ROS_DEBUG("Safing thrusters");
// Safe all the thrusters
for (int i = 0; i <= 5; i++) {
checkError(setThrusterSafety(fd, i));
}
ROS_DEBUG("Safed thrusters");
//Close the sensorboard
close(fd);
}
void ThrusterTortugaNode::update(){
//I think we need to initialize thrusters and stuff before this will work
ros::spinOnce();
// setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);
// ROS_DEBUG("fd = %x",fd);
ROS_DEBUG("Setting thruster speeds");
int retR = readSpeedResponses(fd);
ROS_DEBUG("Read speed before: %x", retR);
int retS = setSpeeds(fd, 128, 128, 128, 128, 128, 128);
ROS_DEBUG("Set speed status: %x", retS);
usleep(20*1000);
int retA = readSpeedResponses(fd);
ROS_DEBUG("Read speed after: %x", retA);
ROS_DEBUG("thruster state = %x", readThrusterState(fd));
ROS_DEBUG("set speed returns %x", retS);
ROS_DEBUG("read speed returns %x", retR);
}
void ThrusterTortugaNode::publish(){
// setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);
}
void ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){
//SG: TODO change this shit
for(int i = 0 ;i < NUM_THRUSTERS; i++){
thruster_powers.data[i] = new_powers.data[i];
}
}
//ssh [email protected]
<|endoftext|> |
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* 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 "pluginManagerImplementation.h"
#include <QtCore/QCoreApplication>
#include <qrkernel/logging.h>
using namespace qReal::details;
PluginManagerImplementation::PluginManagerImplementation(const QString &applicationDirPath
, const QString &additionalPart)
: mPluginsDir(QDir(applicationDirPath))
, mApplicationDirectoryPath(applicationDirPath)
, mAdditionalPart(additionalPart)
{
}
PluginManagerImplementation::~PluginManagerImplementation()
{
}
QList<QObject *> PluginManagerImplementation::loadAllPlugins()
{
while (!mPluginsDir.isRoot() && !mPluginsDir.entryList(QDir::Dirs).contains("plugins")) {
mPluginsDir.cdUp();
}
QList<QString> splittedDir = mAdditionalPart.split('/');
for (const QString &partOfDirectory : splittedDir) {
mPluginsDir.cd(partOfDirectory);
}
QList<QObject *> listOfPlugins;
for (const QString &fileName : mPluginsDir.entryList(QDir::Files)) {
QPair<QObject *, QString> const pluginAndError = pluginLoadedByName(fileName);
QObject * const pluginByName = pluginAndError.first;
if (pluginByName) {
listOfPlugins.append(pluginByName);
mFileNameAndPlugin.insert(fileName, pluginByName);
} else {
QLOG_ERROR() << "Plugin loading failed:" << pluginAndError.second;
qDebug() << "Plugin loading failed:" << pluginAndError.second;
}
}
return listOfPlugins;
}
QPair<QObject *, QString> PluginManagerImplementation::pluginLoadedByName(const QString &pluginName)
{
QPluginLoader *loader = new QPluginLoader(mPluginsDir.absoluteFilePath(pluginName), qApp);
loader->load();
QObject *plugin = loader->instance();
QPair<QString, QPluginLoader*> pairOfLoader = qMakePair(pluginName, loader);
mLoaders.append(pairOfLoader);
if (plugin) {
mFileNameAndPlugin.insert(loader->metaData()["IID"].toString(), plugin);
return qMakePair(plugin, QString());
}
const QString loaderError = loader->errorString();
// Unloading of plugins is currently (Qt 5.3) broken due to a bug in metatype system: calling Q_DECLARE_METATYPE
// from plugin registers some data from plugin address space in Qt metatype system, which is not being updated
// when plugin is unloaded and loaded again. Any subsequent calls to QVariant or other template classes/methods
// which use metainformation will result in a crash. It is likely (but not verified) that qRegisterMetaType leads
// to the same issue. Since we can not guarantee that plugin does not use Q_DECLARE_METATYPE or qRegisterMetaType
// we shall not unload plugin at all, to be safe rather than sorry.
//
// But it seems also that metainformation gets deleted BEFORE plugins are unloaded on application exit, so we can
// not call any metainformation-using code in destructors that get called on unloading. Since Qt classes themselves
// are using such calls (QGraphicsViewScene, for example), random crashes on exit may be a symptom of this problem.
//
// EditorManager is an exception, because it really needs to unload editor plugins, to be able to load new versions
// compiled by metaeditor. Editor plugins are generated, so we can guarantee to some extent that there will be no
// metatype registrations.
//
// See:
// http://stackoverflow.com/questions/19234703/using-q-declare-metatype-with-a-dll-that-may-be-loaded-multiple-times
// (and http://qt-project.org/forums/viewthread/35587)
// https://bugreports.qt-project.org/browse/QTBUG-32442
delete loader;
return qMakePair(nullptr, loaderError);
}
QString PluginManagerImplementation::unloadPlugin(const QString &pluginName)
{
int count = 0;
bool stateUnload = true;
for (const QPair<QString, QPluginLoader *> ¤tPair : mLoaders) {
if (currentPair.first == pluginName) {
stateUnload = currentPair.second->unload();
}
++count;
}
for (int j = 0; j < count; ++j) {
mLoaders.removeFirst();
}
if (stateUnload) {
return QString();
}
return QString("Plugin was not found");
}
QList<QString> PluginManagerImplementation::namesOfPlugins() const
{
QList<QString> listOfNames;
for (const QPair<QString, QPluginLoader *> ¤tPair : mLoaders) {
listOfNames.append(currentPair.first);
}
return listOfNames;
}
QString PluginManagerImplementation::fileName(QObject *plugin) const
{
return mFileNameAndPlugin.key(plugin);
}
QObject *PluginManagerImplementation::pluginByName(const QString &pluginName) const
{
return mFileNameAndPlugin[pluginName];
}
<commit_msg>small corrections<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* 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 "pluginManagerImplementation.h"
#include <QtCore/QCoreApplication>
#include <qrkernel/logging.h>
using namespace qReal::details;
PluginManagerImplementation::PluginManagerImplementation(const QString &applicationDirPath
, const QString &additionalPart)
: mPluginsDir(QDir(applicationDirPath))
, mApplicationDirectoryPath(applicationDirPath)
, mAdditionalPart(additionalPart)
{
}
PluginManagerImplementation::~PluginManagerImplementation()
{
const int count = mLoaders.length();
for (int i = 0; i < count; ++i) {
mLoaders.removeFirst();
}
}
QList<QObject *> PluginManagerImplementation::loadAllPlugins()
{
while (!mPluginsDir.isRoot() && !mPluginsDir.entryList(QDir::Dirs).contains("plugins")) {
mPluginsDir.cdUp();
}
QList<QString> splittedDir = mAdditionalPart.split('/');
for (const QString &partOfDirectory : splittedDir) {
mPluginsDir.cd(partOfDirectory);
}
QList<QObject *> listOfPlugins;
for (const QString &fileName : mPluginsDir.entryList(QDir::Files)) {
QPair<QObject *, QString> const pluginAndError = pluginLoadedByName(fileName);
QObject * const pluginByName = pluginAndError.first;
if (pluginByName) {
listOfPlugins.append(pluginByName);
mFileNameAndPlugin.insert(fileName, pluginByName);
} else {
QLOG_ERROR() << "Plugin loading failed:" << pluginAndError.second;
qDebug() << "Plugin loading failed:" << pluginAndError.second;
}
}
return listOfPlugins;
}
QPair<QObject *, QString> PluginManagerImplementation::pluginLoadedByName(const QString &pluginName)
{
QPluginLoader *loader = new QPluginLoader(mPluginsDir.absoluteFilePath(pluginName), qApp);
loader->load();
QObject *plugin = loader->instance();
QPair<QString, QPluginLoader*> pairOfLoader = qMakePair(pluginName, loader);
mLoaders.append(pairOfLoader);
if (plugin) {
mFileNameAndPlugin.insert(loader->metaData()["IID"].toString(), plugin);
return qMakePair(plugin, QString());
}
const QString loaderError = loader->errorString();
// Unloading of plugins is currently (Qt 5.3) broken due to a bug in metatype system: calling Q_DECLARE_METATYPE
// from plugin registers some data from plugin address space in Qt metatype system, which is not being updated
// when plugin is unloaded and loaded again. Any subsequent calls to QVariant or other template classes/methods
// which use metainformation will result in a crash. It is likely (but not verified) that qRegisterMetaType leads
// to the same issue. Since we can not guarantee that plugin does not use Q_DECLARE_METATYPE or qRegisterMetaType
// we shall not unload plugin at all, to be safe rather than sorry.
//
// But it seems also that metainformation gets deleted BEFORE plugins are unloaded on application exit, so we can
// not call any metainformation-using code in destructors that get called on unloading. Since Qt classes themselves
// are using such calls (QGraphicsViewScene, for example), random crashes on exit may be a symptom of this problem.
//
// EditorManager is an exception, because it really needs to unload editor plugins, to be able to load new versions
// compiled by metaeditor. Editor plugins are generated, so we can guarantee to some extent that there will be no
// metatype registrations.
//
// See:
// http://stackoverflow.com/questions/19234703/using-q-declare-metatype-with-a-dll-that-may-be-loaded-multiple-times
// (and http://qt-project.org/forums/viewthread/35587)
// https://bugreports.qt-project.org/browse/QTBUG-32442
delete loader;
return qMakePair(nullptr, loaderError);
}
QString PluginManagerImplementation::unloadPlugin(const QString &pluginName)
{
int count = 0;
bool stateUnload = true;
for (const QPair<QString, QPluginLoader *> ¤tPair : mLoaders) {
if (currentPair.first == pluginName) {
stateUnload = currentPair.second->unload();
}
++count;
}
if (stateUnload) {
return QString();
}
return QString("Plugin was not found");
}
QList<QString> PluginManagerImplementation::namesOfPlugins() const
{
QList<QString> listOfNames;
for (const QPair<QString, QPluginLoader *> ¤tPair : mLoaders) {
listOfNames.append(currentPair.first);
}
return listOfNames;
}
QString PluginManagerImplementation::fileName(QObject *plugin) const
{
return mFileNameAndPlugin.key(plugin);
}
QObject *PluginManagerImplementation::pluginByName(const QString &pluginName) const
{
return mFileNameAndPlugin[pluginName];
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* c7a/data/data_manager.hpp
*
******************************************************************************/
#ifndef C7A_DATA_DATA_MANAGER_HEADER
#define C7A_DATA_DATA_MANAGER_HEADER
#include <map>
#include "block_iterator.hpp"
namespace c7a {
namespace data {
//! Identification for DIAs
typedef int DIAId;
//! Stores in-memory data
//!
//! Future versions: Provide access to remote DIAs
class DataManager
{
public:
//! returns iterator on requested partition
//!
//! \param id ID of the DIA
template<class T>
BlockIterator<T> getLocalBlocks(DIAId id) {
const auto& block = data_[id];
return BlockIterator<T>(block.cbegin(), block.cend());
}
//! returns true if the manager holds data of given DIA
//!
//! \param id ID of the DIA
bool Contains(DIAId id) {
return data_.find(id) != data_.end();
}
/*BlockEmitter<T> getLocalEmitter(DIAId) {
}*/
private:
std::map<DIAId, std::vector<Blob>> data_;
};
}
}
#endif // !C7A_DATA_DATA_MANAGER_HEADER
/******************************************************************************/
<commit_msg>implement getLocalEmitter<commit_after>/*******************************************************************************
* c7a/data/data_manager.hpp
*
******************************************************************************/
#ifndef C7A_DATA_DATA_MANAGER_HEADER
#define C7A_DATA_DATA_MANAGER_HEADER
#include <map>
#include <functional>
#include <stdexcept>
#include "block_iterator.hpp"
namespace c7a {
namespace data {
//! Identification for DIAs
typedef int DIAId;
//! function Signature for an emitt function
template<typename T>
using BlockEmitter = std::function<void(T)>;
//! Stores in-memory data
//!
//! Future versions: Provide access to remote DIAs
class DataManager
{
public:
//! returns iterator on requested partition
//!
//! \param id ID of the DIA
template<class T>
BlockIterator<T> getLocalBlocks(DIAId id) {
const auto& block = data_[id];
return BlockIterator<T>(block.cbegin(), block.cend());
}
//! returns true if the manager holds data of given DIA
//!
//! \param id ID of the DIA
bool Contains(DIAId id) {
return data_.find(id) != data_.end();
}
template<class T>
BlockEmitter<T> getLocalEmitter(DIAId id) {
if (!Contains(id)) {
throw std::runtime_error("target dia id unknown.");
}
auto& target = data_[id];
return [&target](T elem){ target.push_back(Serialize(elem)); };
}
private:
std::map<DIAId, std::vector<Blob>> data_;
};
}
}
#endif // !C7A_DATA_DATA_MANAGER_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>#include <array>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "OsMock.hpp"
#include "mission/sail.hpp"
#include "mock/HasStateMock.hpp"
#include "mock/comm.hpp"
#include "obc/telecommands/sail.hpp"
#include "os/os.hpp"
using telecommunication::downlink::DownlinkAPID;
using testing::ElementsAre;
using testing::Eq;
using testing::Return;
using testing::ReturnRef;
using testing::_;
namespace
{
class StopSailDeploymentTelecommandTest : public testing::Test
{
protected:
StopSailDeploymentTelecommandTest();
testing::NiceMock<HasStateMock<SystemState>> stateContainer;
testing::NiceMock<TransmitterMock> transmitter;
testing::NiceMock<OSMock> os;
OSReset guard;
obc::telecommands::StopSailDeployment telecommand{stateContainer};
};
StopSailDeploymentTelecommandTest::StopSailDeploymentTelecommandTest()
{
this->guard = InstallProxy(&os);
ON_CALL(os, TakeSemaphore(_, _)).WillByDefault(Return(OSResult::Success));
}
TEST_F(StopSailDeploymentTelecommandTest, ShouldDisableDeploymentBeforeItBegins)
{
SystemState state;
auto& persistentState = state.PersistentState;
persistentState.Set(state::SailState(state::SailOpeningState::Waiting));
EXPECT_CALL(stateContainer, MockGetState()).WillOnce(ReturnRef(state));
EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0x22, 0))));
std::array<std::uint8_t, 1> frame{0x22};
telecommand.Handle(this->transmitter, frame);
state::SailState sailState;
persistentState.Get(sailState);
ASSERT_THAT(sailState.CurrentState(), Eq(state::SailOpeningState::OpeningStopped));
}
TEST_F(StopSailDeploymentTelecommandTest, ShouldStopOpening)
{
SystemState state;
auto& persistentState = state.PersistentState;
persistentState.Set(state::SailState(state::SailOpeningState::Opening));
EXPECT_CALL(stateContainer, MockGetState()).WillOnce(ReturnRef(state));
EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0x22, 0))));
std::array<std::uint8_t, 1> frame{0x22};
telecommand.Handle(this->transmitter, frame);
state::SailState sailState;
persistentState.Get(sailState);
ASSERT_THAT(sailState.CurrentState(), Eq(state::SailOpeningState::OpeningStopped));
}
TEST_F(StopSailDeploymentTelecommandTest, ShouldRespondWithErrorOnInvalidFrame)
{
EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0, 255))));
telecommand.Handle(this->transmitter, gsl::span<const uint8_t>());
}
}
<commit_msg>[telecommunication] Fix test failure.<commit_after>#include <array>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "OsMock.hpp"
#include "mission/sail.hpp"
#include "mock/HasStateMock.hpp"
#include "mock/comm.hpp"
#include "obc/telecommands/sail.hpp"
#include "os/os.hpp"
using telecommunication::downlink::DownlinkAPID;
using testing::ElementsAre;
using testing::Eq;
using testing::Return;
using testing::ReturnRef;
using testing::_;
namespace
{
class StopSailDeploymentTelecommandTest : public testing::Test
{
protected:
StopSailDeploymentTelecommandTest();
testing::NiceMock<HasStateMock<SystemState>> stateContainer;
testing::NiceMock<TransmitterMock> transmitter;
testing::NiceMock<OSMock> os;
OSReset guard;
obc::telecommands::StopSailDeployment telecommand{stateContainer};
};
StopSailDeploymentTelecommandTest::StopSailDeploymentTelecommandTest()
{
this->guard = InstallProxy(&os);
ON_CALL(os, TakeSemaphore(_, _)).WillByDefault(Return(OSResult::Success));
}
TEST_F(StopSailDeploymentTelecommandTest, ShouldDisableDeploymentBeforeItBegins)
{
SystemState state;
auto& persistentState = state.PersistentState;
persistentState.Set(state::SailState(state::SailOpeningState::Waiting));
EXPECT_CALL(stateContainer, MockGetState()).WillOnce(ReturnRef(state));
EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0x22, 0))));
std::array<std::uint8_t, 1> frame{0x22};
telecommand.Handle(this->transmitter, frame);
state::SailState sailState;
persistentState.Get(sailState);
ASSERT_THAT(sailState.CurrentState(), Eq(state::SailOpeningState::OpeningStopped));
}
TEST_F(StopSailDeploymentTelecommandTest, ShouldStopOpening)
{
SystemState state;
auto& persistentState = state.PersistentState;
persistentState.Set(state::SailState(state::SailOpeningState::Opening));
EXPECT_CALL(stateContainer, MockGetState()).WillOnce(ReturnRef(state));
EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0x22, 0))));
std::array<std::uint8_t, 1> frame{0x22};
telecommand.Handle(this->transmitter, frame);
state::SailState sailState;
persistentState.Get(sailState);
ASSERT_THAT(sailState.CurrentState(), Eq(state::SailOpeningState::OpeningStopped));
}
TEST_F(StopSailDeploymentTelecommandTest, ShouldRespondWithErrorOnInvalidFrame)
{
SystemState state;
ON_CALL(stateContainer, MockGetState()).WillByDefault(ReturnRef(state));
EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0, 255))));
telecommand.Handle(this->transmitter, gsl::span<const uint8_t>());
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; indent-tabs-mode:nil; c-basic-offset:4; -*- */
/*
* gtkmm-utils - tile.cc
*
* Copyright (C) 2007 Marko Anastasov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "tile.hh"
namespace Gtk {
namespace Util {
Tile::Tile(const Glib::ustring& title,
const Glib::ustring& summary,
bool paint_white)
:
root_hbox_(),
image_(),
content_vbox_(),
title_label_(),
summary_label_(),
title_(title),
summary_(summary),
paint_white_(paint_white)
{
set_flags(Gtk::CAN_FOCUS);
// set up root hbox
root_hbox_.set_border_width(5);
root_hbox_.set_spacing(2);
add(root_hbox_);
// pack illustration image
image_.show();
root_hbox_.pack_start(image_, false, false, 0);
// prepare vbox to appear on the right hand side of the image
content_vbox_.set_border_width(5);
content_vbox_.set_spacing(2);
// set up the title label
title_label_.set_markup("<span weight=\"bold\">" +
Glib::strescape(title_) +
"</span>");
title_label_.set_ellipsize(Pango::ELLIPSIZE_END);
title_label_.set_max_width_chars(30);
title_label_.modify_fg(Gtk::STATE_NORMAL,
this->get_style()->get_fg(Gtk::STATE_INSENSITIVE));
content_vbox_.pack_start(title_label_, false, false, 0);
// set up the summary label
summary_label_.set_markup("<small>" +
Glib::strescape(summary_) +
"</small>");
summary_label_.set_ellipsize(Pango::ELLIPSIZE_END);
summary_label_.set_max_width_chars(30);
summary_label_.modify_fg(Gtk::STATE_NORMAL,
this->get_style()->get_fg(Gtk::STATE_INSENSITIVE));
content_vbox_.pack_start(summary_label_, false, false, 0);
// wrap up
content_vbox_.show_all();
root_hbox_.pack_start(content_vbox_);
}
Tile::~Tile()
{
}
Gtk::HBox&
Tile::get_root_hbox()
{
return root_hbox_;
}
Gtk::Image&
Tile::get_image()
{
return image_;
}
Gtk::VBox&
Tile::get_content_vbox()
{
return content_vbox_;
}
Tile::SignalTileSelected&
Tile::get_signal_tile_selected()
{
return signal_tile_selected_;
}
bool
Tile::on_expose_event(GdkEventExpose* event)
{
if (! is_visible())
return false;
GdkWindow* event_window = event->window;
if (paint_white_ &&
(gdk_window_get_window_type(event_window) == GDK_WINDOW_CHILD))
{
Glib::RefPtr<Gdk::Window> window = this->get_window();
Glib::RefPtr<Gdk::GC> gc =
this->get_style()->get_base_gc(this->get_state());
window->draw_rectangle(gc,
true, // fill
event->area.x, event->area.y,
event->area.width, event->area.height);
}
if (this->get_flags() & Gtk::HAS_FOCUS)
{
int focus_pad, width, height;
Glib::RefPtr<Gdk::Window> window = this->get_window();
Gdk::Rectangle alloc = this->get_allocation();
Glib::RefPtr<Gtk::Style> style = get_style();
this->get_style_property<int>("focus_padding", focus_pad);
// We do not need to calculate x and y origins of the box
// for pain_* functions - just starting from (0,0) will
// do the right thing.
width =
alloc.get_width() - 2 * (focus_pad + style->get_xthickness());
height =
alloc.get_height() - 2 * (focus_pad + style->get_ythickness());
style->paint_box(content_vbox_.get_window(),
Gtk::STATE_SELECTED,
Gtk::SHADOW_NONE,
Gdk::Rectangle(&(event->area)),
content_vbox_,
"TileSelectionBox",
0, 0,
width, height);
title_label_.set_state(Gtk::STATE_SELECTED);
summary_label_.set_state(Gtk::STATE_SELECTED);
style->paint_focus(window,
this->get_state(),
Gdk::Rectangle(&(event->area)),
*this,
"TileFocus",
0, 0,
width, height);
}
else
{
title_label_.set_state(Gtk::STATE_NORMAL);
summary_label_.set_state(Gtk::STATE_NORMAL);
}
Gtk::Widget* child_widget = this->get_child(); // Gtk::Bin
if (child_widget)
propagate_expose(*child_widget, event);
return false;
}
bool
Tile::on_button_press_event(GdkEventButton* /* event */)
{
grab_focus();
return false;
}
bool
Tile::on_focus_in_event(GdkEventFocus* event)
{
signal_tile_selected_.emit();
return Gtk::EventBox::on_focus_in_event(event);
}
} // namespace Util
} // namespace Gtk
<commit_msg>Wrote some comments on the code in Tile::on_expose_event().<commit_after>/* -*- Mode: C++; indent-tabs-mode:nil; c-basic-offset:4; -*- */
/*
* gtkmm-utils - tile.cc
*
* Copyright (C) 2007 Marko Anastasov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "tile.hh"
namespace Gtk {
namespace Util {
Tile::Tile(const Glib::ustring& title,
const Glib::ustring& summary,
bool paint_white)
:
root_hbox_(),
image_(),
content_vbox_(),
title_label_(),
summary_label_(),
title_(title),
summary_(summary),
paint_white_(paint_white)
{
set_flags(Gtk::CAN_FOCUS);
// set up root hbox
root_hbox_.set_border_width(5);
root_hbox_.set_spacing(2);
add(root_hbox_);
// pack illustration image
image_.show();
root_hbox_.pack_start(image_, false, false, 0);
// prepare vbox to appear on the right hand side of the image
content_vbox_.set_border_width(5);
content_vbox_.set_spacing(2);
// set up the title label
title_label_.set_markup("<span weight=\"bold\">" +
Glib::strescape(title_) +
"</span>");
title_label_.set_ellipsize(Pango::ELLIPSIZE_END);
title_label_.set_max_width_chars(30);
title_label_.modify_fg(Gtk::STATE_NORMAL,
this->get_style()->get_fg(Gtk::STATE_INSENSITIVE));
content_vbox_.pack_start(title_label_, false, false, 0);
// set up the summary label
summary_label_.set_markup("<small>" +
Glib::strescape(summary_) +
"</small>");
summary_label_.set_ellipsize(Pango::ELLIPSIZE_END);
summary_label_.set_max_width_chars(30);
summary_label_.modify_fg(Gtk::STATE_NORMAL,
this->get_style()->get_fg(Gtk::STATE_INSENSITIVE));
content_vbox_.pack_start(summary_label_, false, false, 0);
// wrap up
content_vbox_.show_all();
root_hbox_.pack_start(content_vbox_);
}
Tile::~Tile()
{
}
Gtk::HBox&
Tile::get_root_hbox()
{
return root_hbox_;
}
Gtk::Image&
Tile::get_image()
{
return image_;
}
Gtk::VBox&
Tile::get_content_vbox()
{
return content_vbox_;
}
Tile::SignalTileSelected&
Tile::get_signal_tile_selected()
{
return signal_tile_selected_;
}
bool
Tile::on_expose_event(GdkEventExpose* event)
{
if (! is_visible())
return false;
GdkWindow* event_window = event->window;
if (paint_white_ &&
(gdk_window_get_window_type(event_window) == GDK_WINDOW_CHILD))
{
// Paint white background on the widget.
Glib::RefPtr<Gdk::Window> window = this->get_window();
Glib::RefPtr<Gdk::GC> gc =
this->get_style()->get_base_gc(this->get_state());
window->draw_rectangle(gc,
true, // fill
event->area.x, event->area.y,
event->area.width, event->area.height);
}
if (this->get_flags() & Gtk::HAS_FOCUS)
{
int focus_pad, width, height;
Glib::RefPtr<Gdk::Window> window = this->get_window();
Gdk::Rectangle alloc = this->get_allocation();
Glib::RefPtr<Gtk::Style> style = get_style();
this->get_style_property<int>("focus_padding", focus_pad);
// We do not need to calculate x and y origins of the box
// for pain_* functions - just starting from (0,0) will
// do the right thing.
width =
alloc.get_width() - 2 * (focus_pad + style->get_xthickness());
height =
alloc.get_height() - 2 * (focus_pad + style->get_ythickness());
// Paint a backround box, the usual selection indicator
// which is usually blue. It is important to paint on the
// container box's window, otherwise if we'd, for instance,
// paint on the widget itself, the box would completely cover it.
style->paint_box(root_hbox_.get_window(),
Gtk::STATE_SELECTED,
Gtk::SHADOW_NONE,
Gdk::Rectangle(&(event->area)),
root_hbox_,
"TileSelectionBox",
0, 0,
width, height);
// Change the label state to selected, so that the theme
// engine changes the font color appropriately to contrast
// the colour of the box.
title_label_.set_state(Gtk::STATE_SELECTED);
summary_label_.set_state(Gtk::STATE_SELECTED);
// Also paint the the little line border around the widget,
// another usual focus indicator.
style->paint_focus(window,
this->get_state(),
Gdk::Rectangle(&(event->area)),
*this,
"TileFocus",
0, 0,
width, height);
}
else
{
title_label_.set_state(Gtk::STATE_NORMAL);
summary_label_.set_state(Gtk::STATE_NORMAL);
}
Gtk::Widget* child_widget = this->get_child(); // Gtk::Bin method
if (child_widget)
propagate_expose(*child_widget, event);
return false;
}
bool
Tile::on_button_press_event(GdkEventButton* /* event */)
{
grab_focus();
return false;
}
bool
Tile::on_focus_in_event(GdkEventFocus* event)
{
signal_tile_selected_.emit();
return Gtk::EventBox::on_focus_in_event(event);
}
} // namespace Util
} // namespace Gtk
<|endoftext|> |
<commit_before>#include "traceloader.h"
#include "apitrace.h"
#include <QDebug>
#include <QFile>
#include <QStack>
#define FRAMES_TO_CACHE 100
static ApiTraceCall *
apiCallFromTraceCall(const trace::Call *call,
const QHash<QString, QUrl> &helpHash,
ApiTraceFrame *frame,
ApiTraceCall *parentCall,
TraceLoader *loader)
{
ApiTraceCall *apiCall;
if (parentCall)
apiCall = new ApiTraceCall(parentCall, loader, call);
else
apiCall = new ApiTraceCall(frame, loader, call);
apiCall->setHelpUrl(helpHash.value(apiCall->name()));
return apiCall;
}
TraceLoader::TraceLoader(QObject *parent)
: QObject(parent)
{
}
TraceLoader::~TraceLoader()
{
m_parser.close();
qDeleteAll(m_signatures);
qDeleteAll(m_enumSignatures);
}
void TraceLoader::loadTrace(const QString &filename)
{
if (m_helpHash.isEmpty()) {
loadHelpFile();
}
if (!m_frameBookmarks.isEmpty()) {
qDeleteAll(m_signatures);
qDeleteAll(m_enumSignatures);
m_signatures.clear();
m_enumSignatures.clear();
m_frameBookmarks.clear();
m_createdFrames.clear();
m_parser.close();
}
if (!m_parser.open(filename.toLatin1())) {
qDebug() << "error: failed to open " << filename;
return;
}
emit startedParsing();
if (m_parser.supportsOffsets()) {
scanTrace();
} else {
//Load the entire file into memory
parseTrace();
}
emit guessedApi(static_cast<int>(m_parser.api));
emit finishedParsing();
}
void TraceLoader::loadFrame(ApiTraceFrame *currentFrame)
{
fetchFrameContents(currentFrame);
}
int TraceLoader::numberOfFrames() const
{
return m_frameBookmarks.size();
}
int TraceLoader::numberOfCallsInFrame(int frameIdx) const
{
if (frameIdx >= m_frameBookmarks.size()) {
return 0;
}
FrameBookmarks::const_iterator itr =
m_frameBookmarks.find(frameIdx);
return itr->numberOfCalls;
}
void TraceLoader::loadHelpFile()
{
QFile file(":/resources/glreference.tsv");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QString line;
while (!file.atEnd()) {
line = file.readLine();
QString function = line.section('\t', 0, 0).trimmed();
QUrl url = QUrl(line.section('\t', 1, 1).trimmed());
//qDebug()<<"function = "<<function<<", url = "<<url.toString();
m_helpHash.insert(function, url);
}
} else {
qWarning() << "Couldn't open reference file "
<< file.fileName();
}
file.close();
}
void TraceLoader::scanTrace()
{
QList<ApiTraceFrame*> frames;
ApiTraceFrame *currentFrame = 0;
trace::Call *call;
trace::ParseBookmark startBookmark;
int numOfFrames = 0;
int numOfCalls = 0;
int lastPercentReport = 0;
m_parser.getBookmark(startBookmark);
while ((call = m_parser.scan_call())) {
++numOfCalls;
if (call->flags & trace::CALL_FLAG_END_FRAME) {
FrameBookmark frameBookmark(startBookmark);
frameBookmark.numberOfCalls = numOfCalls;
currentFrame = new ApiTraceFrame();
currentFrame->number = numOfFrames;
currentFrame->setNumChildren(numOfCalls);
currentFrame->setLastCallIndex(call->no);
frames.append(currentFrame);
m_createdFrames.append(currentFrame);
m_frameBookmarks[numOfFrames] = frameBookmark;
++numOfFrames;
if (m_parser.percentRead() - lastPercentReport >= 5) {
emit parsed(m_parser.percentRead());
lastPercentReport = m_parser.percentRead();
}
m_parser.getBookmark(startBookmark);
numOfCalls = 0;
}
delete call;
}
if (numOfCalls) {
//trace::File::Bookmark endBookmark = m_parser.currentBookmark();
FrameBookmark frameBookmark(startBookmark);
frameBookmark.numberOfCalls = numOfCalls;
currentFrame = new ApiTraceFrame();
currentFrame->number = numOfFrames;
currentFrame->setNumChildren(numOfCalls);
frames.append(currentFrame);
m_createdFrames.append(currentFrame);
m_frameBookmarks[numOfFrames] = frameBookmark;
++numOfFrames;
}
emit parsed(100);
emit framesLoaded(frames);
}
void TraceLoader::parseTrace()
{
QList<ApiTraceFrame*> frames;
ApiTraceFrame *currentFrame = 0;
int frameCount = 0;
QStack<ApiTraceCall*> groups;
QVector<ApiTraceCall*> topLevelItems;
QVector<ApiTraceCall*> allCalls;
quint64 binaryDataSize = 0;
int lastPercentReport = 0;
trace::Call *call = m_parser.parse_call();
while (call) {
//std::cout << *call;
if (!currentFrame) {
currentFrame = new ApiTraceFrame();
currentFrame->number = frameCount;
++frameCount;
}
ApiTraceCall *apiCall =
apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this);
allCalls.append(apiCall);
if (groups.count() == 0) {
topLevelItems.append(apiCall);
}
if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {
groups.push(apiCall);
} else if (call->flags & trace::CALL_FLAG_MARKER_POP) {
groups.top()->finishedAddingChildren();
groups.pop();
}
if (!groups.isEmpty()) {
groups.top()->addChild(apiCall);
}
if (apiCall->hasBinaryData()) {
QByteArray data =
apiCall->arguments()[apiCall->binaryDataIndex()].toByteArray();
binaryDataSize += data.size();
}
if (call->flags & trace::CALL_FLAG_END_FRAME) {
allCalls.squeeze();
topLevelItems.squeeze();
if (topLevelItems.count() == allCalls.count()) {
currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
} else {
currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
}
allCalls.clear();
groups.clear();
topLevelItems.clear();
frames.append(currentFrame);
currentFrame = 0;
binaryDataSize = 0;
if (frames.count() >= FRAMES_TO_CACHE) {
emit framesLoaded(frames);
frames.clear();
}
if (m_parser.percentRead() - lastPercentReport >= 5) {
emit parsed(m_parser.percentRead());
lastPercentReport = m_parser.percentRead();
}
}
delete call;
call = m_parser.parse_call();
}
//last frames won't have markers
// it's just a bunch of Delete calls for every object
// after the last SwapBuffers
if (currentFrame) {
allCalls.squeeze();
if (topLevelItems.count() == allCalls.count()) {
currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
} else {
currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
}
frames.append(currentFrame);
currentFrame = 0;
}
if (frames.count()) {
emit framesLoaded(frames);
}
}
ApiTraceCallSignature * TraceLoader::signature(unsigned id)
{
if (id >= m_signatures.count()) {
m_signatures.resize(id + 1);
return NULL;
} else {
return m_signatures[id];
}
}
void TraceLoader::addSignature(unsigned id, ApiTraceCallSignature *signature)
{
m_signatures[id] = signature;
}
ApiTraceEnumSignature * TraceLoader::enumSignature(unsigned id)
{
if (id >= m_enumSignatures.count()) {
m_enumSignatures.resize(id + 1);
return NULL;
} else {
return m_enumSignatures[id];
}
}
void TraceLoader::addEnumSignature(unsigned id, ApiTraceEnumSignature *signature)
{
m_enumSignatures[id] = signature;
}
void TraceLoader::searchNext(const ApiTrace::SearchRequest &request)
{
Q_ASSERT(m_parser.supportsOffsets());
if (m_parser.supportsOffsets()) {
int startFrame = m_createdFrames.indexOf(request.frame);
const FrameBookmark &frameBookmark = m_frameBookmarks[startFrame];
m_parser.setBookmark(frameBookmark.start);
trace::Call *call = 0;
while ((call = m_parser.parse_call())) {
if (callContains(call, request.text, request.cs)) {
unsigned frameIdx = callInFrame(call->no);
ApiTraceFrame *frame = m_createdFrames[frameIdx];
const QVector<ApiTraceCall*> calls =
fetchFrameContents(frame);
for (int i = 0; i < calls.count(); ++i) {
if (calls[i]->index() == call->no) {
emit searchResult(request, ApiTrace::SearchResult_Found,
calls[i]);
break;
}
}
delete call;
return;
}
delete call;
}
}
emit searchResult(request, ApiTrace::SearchResult_NotFound, 0);
}
void TraceLoader::searchPrev(const ApiTrace::SearchRequest &request)
{
Q_ASSERT(m_parser.supportsOffsets());
if (m_parser.supportsOffsets()) {
int startFrame = m_createdFrames.indexOf(request.frame);
trace::Call *call = 0;
QList<trace::Call*> frameCalls;
int frameIdx = startFrame;
const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];
int numCallsToParse = frameBookmark.numberOfCalls;
m_parser.setBookmark(frameBookmark.start);
while ((call = m_parser.parse_call())) {
frameCalls.append(call);
--numCallsToParse;
if (numCallsToParse == 0) {
bool foundCall = searchCallsBackwards(frameCalls,
frameIdx,
request);
qDeleteAll(frameCalls);
frameCalls.clear();
if (foundCall) {
return;
}
--frameIdx;
if (frameIdx >= 0) {
const FrameBookmark &frameBookmark =
m_frameBookmarks[frameIdx];
m_parser.setBookmark(frameBookmark.start);
numCallsToParse = frameBookmark.numberOfCalls;
}
}
}
}
emit searchResult(request, ApiTrace::SearchResult_NotFound, 0);
}
bool TraceLoader::searchCallsBackwards(const QList<trace::Call*> &calls,
int frameIdx,
const ApiTrace::SearchRequest &request)
{
for (int i = calls.count() - 1; i >= 0; --i) {
trace::Call *call = calls[i];
if (callContains(call, request.text, request.cs)) {
ApiTraceFrame *frame = m_createdFrames[frameIdx];
const QVector<ApiTraceCall*> apiCalls =
fetchFrameContents(frame);
for (int i = 0; i < apiCalls.count(); ++i) {
if (apiCalls[i]->index() == call->no) {
emit searchResult(request,
ApiTrace::SearchResult_Found,
apiCalls[i]);
break;
}
}
return true;
}
}
return false;
}
int TraceLoader::callInFrame(int callIdx) const
{
unsigned numCalls = 0;
for (int frameIdx = 0; frameIdx < m_frameBookmarks.size(); ++frameIdx) {
const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];
unsigned firstCall = numCalls;
unsigned endCall = numCalls + frameBookmark.numberOfCalls;
if (firstCall <= callIdx && endCall > callIdx) {
return frameIdx;
}
numCalls = endCall;
}
Q_ASSERT(!"call not in the trace");
return 0;
}
bool TraceLoader::callContains(trace::Call *call,
const QString &str,
Qt::CaseSensitivity sensitivity)
{
/*
* FIXME: do string comparison directly on trace::Call
*/
ApiTraceCall *apiCall = apiCallFromTraceCall(call, m_helpHash,
0, 0, this);
bool result = apiCall->contains(str, sensitivity);
delete apiCall;
return result;
}
QVector<ApiTraceCall*>
TraceLoader::fetchFrameContents(ApiTraceFrame *currentFrame)
{
Q_ASSERT(currentFrame);
if (currentFrame->isLoaded()) {
return currentFrame->calls();
}
if (m_parser.supportsOffsets()) {
unsigned frameIdx = currentFrame->number;
int numOfCalls = numberOfCallsInFrame(frameIdx);
if (numOfCalls) {
quint64 binaryDataSize = 0;
QStack<ApiTraceCall*> groups;
QVector<ApiTraceCall*> topLevelItems;
QVector<ApiTraceCall*> allCalls(numOfCalls);
const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];
m_parser.setBookmark(frameBookmark.start);
trace::Call *call;
int parsedCalls = 0;
while ((call = m_parser.parse_call())) {
ApiTraceCall *apiCall =
apiCallFromTraceCall(call, m_helpHash,
currentFrame, groups.isEmpty() ? 0 : groups.top(), this);
Q_ASSERT(apiCall);
Q_ASSERT(parsedCalls < allCalls.size());
allCalls[parsedCalls++] = apiCall;
if (groups.count() == 0) {
topLevelItems.append(apiCall);
}
if (!groups.isEmpty()) {
groups.top()->addChild(apiCall);
}
if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {
groups.push(apiCall);
} else if (call->flags & trace::CALL_FLAG_MARKER_POP) {
groups.top()->finishedAddingChildren();
groups.pop();
}
if (apiCall->hasBinaryData()) {
QByteArray data =
apiCall->arguments()[
apiCall->binaryDataIndex()].toByteArray();
binaryDataSize += data.size();
}
delete call;
if (apiCall->flags() & trace::CALL_FLAG_END_FRAME) {
break;
}
}
// There can be fewer parsed calls when call in different
// threads cross the frame boundary
Q_ASSERT(parsedCalls <= numOfCalls);
Q_ASSERT(parsedCalls <= allCalls.size());
allCalls.resize(parsedCalls);
allCalls.squeeze();
Q_ASSERT(parsedCalls <= currentFrame->numChildrenToLoad());
if (topLevelItems.count() == allCalls.count()) {
emit frameContentsLoaded(currentFrame, allCalls,
allCalls, binaryDataSize);
} else {
emit frameContentsLoaded(currentFrame, topLevelItems,
allCalls, binaryDataSize);
}
return allCalls;
}
}
return QVector<ApiTraceCall*>();
}
void TraceLoader::findFrameStart(ApiTraceFrame *frame)
{
if (!frame->isLoaded()) {
loadFrame(frame);
}
emit foundFrameStart(frame);
}
void TraceLoader::findFrameEnd(ApiTraceFrame *frame)
{
if (!frame->isLoaded()) {
loadFrame(frame);
}
emit foundFrameEnd(frame);
}
void TraceLoader::findCallIndex(int index)
{
int frameIdx = callInFrame(index);
ApiTraceFrame *frame = m_createdFrames[frameIdx];
QVector<ApiTraceCall*> calls = fetchFrameContents(frame);
QVector<ApiTraceCall*>::const_iterator itr;
ApiTraceCall *call = 0;
for (itr = calls.constBegin(); itr != calls.constEnd(); ++itr) {
if ((*itr)->index() == index) {
call = *itr;
break;
}
}
if (call) {
emit foundCallIndex(call);
}
}
void TraceLoader::search(const ApiTrace::SearchRequest &request)
{
if (request.direction == ApiTrace::SearchRequest::Next) {
searchNext(request);
} else {
searchPrev(request);
}
}
#include "traceloader.moc"
<commit_msg>qapitrace: fix an inline string FIXME request<commit_after>#include "traceloader.h"
#include "apitrace.h"
#include <QDebug>
#include <QFile>
#include <QStack>
#define FRAMES_TO_CACHE 100
static ApiTraceCall *
apiCallFromTraceCall(const trace::Call *call,
const QHash<QString, QUrl> &helpHash,
ApiTraceFrame *frame,
ApiTraceCall *parentCall,
TraceLoader *loader)
{
ApiTraceCall *apiCall;
if (parentCall)
apiCall = new ApiTraceCall(parentCall, loader, call);
else
apiCall = new ApiTraceCall(frame, loader, call);
apiCall->setHelpUrl(helpHash.value(apiCall->name()));
return apiCall;
}
TraceLoader::TraceLoader(QObject *parent)
: QObject(parent)
{
}
TraceLoader::~TraceLoader()
{
m_parser.close();
qDeleteAll(m_signatures);
qDeleteAll(m_enumSignatures);
}
void TraceLoader::loadTrace(const QString &filename)
{
if (m_helpHash.isEmpty()) {
loadHelpFile();
}
if (!m_frameBookmarks.isEmpty()) {
qDeleteAll(m_signatures);
qDeleteAll(m_enumSignatures);
m_signatures.clear();
m_enumSignatures.clear();
m_frameBookmarks.clear();
m_createdFrames.clear();
m_parser.close();
}
if (!m_parser.open(filename.toLatin1())) {
qDebug() << "error: failed to open " << filename;
return;
}
emit startedParsing();
if (m_parser.supportsOffsets()) {
scanTrace();
} else {
//Load the entire file into memory
parseTrace();
}
emit guessedApi(static_cast<int>(m_parser.api));
emit finishedParsing();
}
void TraceLoader::loadFrame(ApiTraceFrame *currentFrame)
{
fetchFrameContents(currentFrame);
}
int TraceLoader::numberOfFrames() const
{
return m_frameBookmarks.size();
}
int TraceLoader::numberOfCallsInFrame(int frameIdx) const
{
if (frameIdx >= m_frameBookmarks.size()) {
return 0;
}
FrameBookmarks::const_iterator itr =
m_frameBookmarks.find(frameIdx);
return itr->numberOfCalls;
}
void TraceLoader::loadHelpFile()
{
QFile file(":/resources/glreference.tsv");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QString line;
while (!file.atEnd()) {
line = file.readLine();
QString function = line.section('\t', 0, 0).trimmed();
QUrl url = QUrl(line.section('\t', 1, 1).trimmed());
//qDebug()<<"function = "<<function<<", url = "<<url.toString();
m_helpHash.insert(function, url);
}
} else {
qWarning() << "Couldn't open reference file "
<< file.fileName();
}
file.close();
}
void TraceLoader::scanTrace()
{
QList<ApiTraceFrame*> frames;
ApiTraceFrame *currentFrame = 0;
trace::Call *call;
trace::ParseBookmark startBookmark;
int numOfFrames = 0;
int numOfCalls = 0;
int lastPercentReport = 0;
m_parser.getBookmark(startBookmark);
while ((call = m_parser.scan_call())) {
++numOfCalls;
if (call->flags & trace::CALL_FLAG_END_FRAME) {
FrameBookmark frameBookmark(startBookmark);
frameBookmark.numberOfCalls = numOfCalls;
currentFrame = new ApiTraceFrame();
currentFrame->number = numOfFrames;
currentFrame->setNumChildren(numOfCalls);
currentFrame->setLastCallIndex(call->no);
frames.append(currentFrame);
m_createdFrames.append(currentFrame);
m_frameBookmarks[numOfFrames] = frameBookmark;
++numOfFrames;
if (m_parser.percentRead() - lastPercentReport >= 5) {
emit parsed(m_parser.percentRead());
lastPercentReport = m_parser.percentRead();
}
m_parser.getBookmark(startBookmark);
numOfCalls = 0;
}
delete call;
}
if (numOfCalls) {
//trace::File::Bookmark endBookmark = m_parser.currentBookmark();
FrameBookmark frameBookmark(startBookmark);
frameBookmark.numberOfCalls = numOfCalls;
currentFrame = new ApiTraceFrame();
currentFrame->number = numOfFrames;
currentFrame->setNumChildren(numOfCalls);
frames.append(currentFrame);
m_createdFrames.append(currentFrame);
m_frameBookmarks[numOfFrames] = frameBookmark;
++numOfFrames;
}
emit parsed(100);
emit framesLoaded(frames);
}
void TraceLoader::parseTrace()
{
QList<ApiTraceFrame*> frames;
ApiTraceFrame *currentFrame = 0;
int frameCount = 0;
QStack<ApiTraceCall*> groups;
QVector<ApiTraceCall*> topLevelItems;
QVector<ApiTraceCall*> allCalls;
quint64 binaryDataSize = 0;
int lastPercentReport = 0;
trace::Call *call = m_parser.parse_call();
while (call) {
//std::cout << *call;
if (!currentFrame) {
currentFrame = new ApiTraceFrame();
currentFrame->number = frameCount;
++frameCount;
}
ApiTraceCall *apiCall =
apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this);
allCalls.append(apiCall);
if (groups.count() == 0) {
topLevelItems.append(apiCall);
}
if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {
groups.push(apiCall);
} else if (call->flags & trace::CALL_FLAG_MARKER_POP) {
groups.top()->finishedAddingChildren();
groups.pop();
}
if (!groups.isEmpty()) {
groups.top()->addChild(apiCall);
}
if (apiCall->hasBinaryData()) {
QByteArray data =
apiCall->arguments()[apiCall->binaryDataIndex()].toByteArray();
binaryDataSize += data.size();
}
if (call->flags & trace::CALL_FLAG_END_FRAME) {
allCalls.squeeze();
topLevelItems.squeeze();
if (topLevelItems.count() == allCalls.count()) {
currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
} else {
currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
}
allCalls.clear();
groups.clear();
topLevelItems.clear();
frames.append(currentFrame);
currentFrame = 0;
binaryDataSize = 0;
if (frames.count() >= FRAMES_TO_CACHE) {
emit framesLoaded(frames);
frames.clear();
}
if (m_parser.percentRead() - lastPercentReport >= 5) {
emit parsed(m_parser.percentRead());
lastPercentReport = m_parser.percentRead();
}
}
delete call;
call = m_parser.parse_call();
}
//last frames won't have markers
// it's just a bunch of Delete calls for every object
// after the last SwapBuffers
if (currentFrame) {
allCalls.squeeze();
if (topLevelItems.count() == allCalls.count()) {
currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
} else {
currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
}
frames.append(currentFrame);
currentFrame = 0;
}
if (frames.count()) {
emit framesLoaded(frames);
}
}
ApiTraceCallSignature * TraceLoader::signature(unsigned id)
{
if (id >= m_signatures.count()) {
m_signatures.resize(id + 1);
return NULL;
} else {
return m_signatures[id];
}
}
void TraceLoader::addSignature(unsigned id, ApiTraceCallSignature *signature)
{
m_signatures[id] = signature;
}
ApiTraceEnumSignature * TraceLoader::enumSignature(unsigned id)
{
if (id >= m_enumSignatures.count()) {
m_enumSignatures.resize(id + 1);
return NULL;
} else {
return m_enumSignatures[id];
}
}
void TraceLoader::addEnumSignature(unsigned id, ApiTraceEnumSignature *signature)
{
m_enumSignatures[id] = signature;
}
void TraceLoader::searchNext(const ApiTrace::SearchRequest &request)
{
Q_ASSERT(m_parser.supportsOffsets());
if (m_parser.supportsOffsets()) {
int startFrame = m_createdFrames.indexOf(request.frame);
const FrameBookmark &frameBookmark = m_frameBookmarks[startFrame];
m_parser.setBookmark(frameBookmark.start);
trace::Call *call = 0;
while ((call = m_parser.parse_call())) {
if (callContains(call, request.text, request.cs)) {
unsigned frameIdx = callInFrame(call->no);
ApiTraceFrame *frame = m_createdFrames[frameIdx];
const QVector<ApiTraceCall*> calls =
fetchFrameContents(frame);
for (int i = 0; i < calls.count(); ++i) {
if (calls[i]->index() == call->no) {
emit searchResult(request, ApiTrace::SearchResult_Found,
calls[i]);
break;
}
}
delete call;
return;
}
delete call;
}
}
emit searchResult(request, ApiTrace::SearchResult_NotFound, 0);
}
void TraceLoader::searchPrev(const ApiTrace::SearchRequest &request)
{
Q_ASSERT(m_parser.supportsOffsets());
if (m_parser.supportsOffsets()) {
int startFrame = m_createdFrames.indexOf(request.frame);
trace::Call *call = 0;
QList<trace::Call*> frameCalls;
int frameIdx = startFrame;
const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];
int numCallsToParse = frameBookmark.numberOfCalls;
m_parser.setBookmark(frameBookmark.start);
while ((call = m_parser.parse_call())) {
frameCalls.append(call);
--numCallsToParse;
if (numCallsToParse == 0) {
bool foundCall = searchCallsBackwards(frameCalls,
frameIdx,
request);
qDeleteAll(frameCalls);
frameCalls.clear();
if (foundCall) {
return;
}
--frameIdx;
if (frameIdx >= 0) {
const FrameBookmark &frameBookmark =
m_frameBookmarks[frameIdx];
m_parser.setBookmark(frameBookmark.start);
numCallsToParse = frameBookmark.numberOfCalls;
}
}
}
}
emit searchResult(request, ApiTrace::SearchResult_NotFound, 0);
}
bool TraceLoader::searchCallsBackwards(const QList<trace::Call*> &calls,
int frameIdx,
const ApiTrace::SearchRequest &request)
{
for (int i = calls.count() - 1; i >= 0; --i) {
trace::Call *call = calls[i];
if (callContains(call, request.text, request.cs)) {
ApiTraceFrame *frame = m_createdFrames[frameIdx];
const QVector<ApiTraceCall*> apiCalls =
fetchFrameContents(frame);
for (int i = 0; i < apiCalls.count(); ++i) {
if (apiCalls[i]->index() == call->no) {
emit searchResult(request,
ApiTrace::SearchResult_Found,
apiCalls[i]);
break;
}
}
return true;
}
}
return false;
}
int TraceLoader::callInFrame(int callIdx) const
{
unsigned numCalls = 0;
for (int frameIdx = 0; frameIdx < m_frameBookmarks.size(); ++frameIdx) {
const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];
unsigned firstCall = numCalls;
unsigned endCall = numCalls + frameBookmark.numberOfCalls;
if (firstCall <= callIdx && endCall > callIdx) {
return frameIdx;
}
numCalls = endCall;
}
Q_ASSERT(!"call not in the trace");
return 0;
}
bool TraceLoader::callContains(trace::Call *call,
const QString &str,
Qt::CaseSensitivity sensitivity)
{
if (sensitivity == Qt::CaseSensitive) {
return (bool) strstr (call->name(), str.toAscii().data());
} else {
return (bool) strcasestr (call->name(), str.toAscii().data());
}
}
QVector<ApiTraceCall*>
TraceLoader::fetchFrameContents(ApiTraceFrame *currentFrame)
{
Q_ASSERT(currentFrame);
if (currentFrame->isLoaded()) {
return currentFrame->calls();
}
if (m_parser.supportsOffsets()) {
unsigned frameIdx = currentFrame->number;
int numOfCalls = numberOfCallsInFrame(frameIdx);
if (numOfCalls) {
quint64 binaryDataSize = 0;
QStack<ApiTraceCall*> groups;
QVector<ApiTraceCall*> topLevelItems;
QVector<ApiTraceCall*> allCalls(numOfCalls);
const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];
m_parser.setBookmark(frameBookmark.start);
trace::Call *call;
int parsedCalls = 0;
while ((call = m_parser.parse_call())) {
ApiTraceCall *apiCall =
apiCallFromTraceCall(call, m_helpHash,
currentFrame, groups.isEmpty() ? 0 : groups.top(), this);
Q_ASSERT(apiCall);
Q_ASSERT(parsedCalls < allCalls.size());
allCalls[parsedCalls++] = apiCall;
if (groups.count() == 0) {
topLevelItems.append(apiCall);
}
if (!groups.isEmpty()) {
groups.top()->addChild(apiCall);
}
if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {
groups.push(apiCall);
} else if (call->flags & trace::CALL_FLAG_MARKER_POP) {
groups.top()->finishedAddingChildren();
groups.pop();
}
if (apiCall->hasBinaryData()) {
QByteArray data =
apiCall->arguments()[
apiCall->binaryDataIndex()].toByteArray();
binaryDataSize += data.size();
}
delete call;
if (apiCall->flags() & trace::CALL_FLAG_END_FRAME) {
break;
}
}
// There can be fewer parsed calls when call in different
// threads cross the frame boundary
Q_ASSERT(parsedCalls <= numOfCalls);
Q_ASSERT(parsedCalls <= allCalls.size());
allCalls.resize(parsedCalls);
allCalls.squeeze();
Q_ASSERT(parsedCalls <= currentFrame->numChildrenToLoad());
if (topLevelItems.count() == allCalls.count()) {
emit frameContentsLoaded(currentFrame, allCalls,
allCalls, binaryDataSize);
} else {
emit frameContentsLoaded(currentFrame, topLevelItems,
allCalls, binaryDataSize);
}
return allCalls;
}
}
return QVector<ApiTraceCall*>();
}
void TraceLoader::findFrameStart(ApiTraceFrame *frame)
{
if (!frame->isLoaded()) {
loadFrame(frame);
}
emit foundFrameStart(frame);
}
void TraceLoader::findFrameEnd(ApiTraceFrame *frame)
{
if (!frame->isLoaded()) {
loadFrame(frame);
}
emit foundFrameEnd(frame);
}
void TraceLoader::findCallIndex(int index)
{
int frameIdx = callInFrame(index);
ApiTraceFrame *frame = m_createdFrames[frameIdx];
QVector<ApiTraceCall*> calls = fetchFrameContents(frame);
QVector<ApiTraceCall*>::const_iterator itr;
ApiTraceCall *call = 0;
for (itr = calls.constBegin(); itr != calls.constEnd(); ++itr) {
if ((*itr)->index() == index) {
call = *itr;
break;
}
}
if (call) {
emit foundCallIndex(call);
}
}
void TraceLoader::search(const ApiTrace::SearchRequest &request)
{
if (request.direction == ApiTrace::SearchRequest::Next) {
searchNext(request);
} else {
searchPrev(request);
}
}
#include "traceloader.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: continuousactivitybase.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:35:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// must be first
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <continuousactivitybase.hxx>
namespace presentation
{
namespace internal
{
ContinuousActivityBase::ContinuousActivityBase( const ActivityParameters& rParms ) :
SimpleContinuousActivityBase( rParms )
{
}
void ContinuousActivityBase::simplePerform( double nSimpleTime,
sal_uInt32 nRepeatCount ) const
{
perform( calcAcceleratedTime( nSimpleTime ),
nRepeatCount );
}
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.50); FILE MERGED 2006/09/01 17:39:36 kaib 1.3.50.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: continuousactivitybase.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:32:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
// must be first
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <continuousactivitybase.hxx>
namespace presentation
{
namespace internal
{
ContinuousActivityBase::ContinuousActivityBase( const ActivityParameters& rParms ) :
SimpleContinuousActivityBase( rParms )
{
}
void ContinuousActivityBase::simplePerform( double nSimpleTime,
sal_uInt32 nRepeatCount ) const
{
perform( calcAcceleratedTime( nSimpleTime ),
nRepeatCount );
}
}
}
<|endoftext|> |
<commit_before>#include "usbutil.h"
#include "buffers.h"
// TODO move this up to cantranslator.pde
USB_HANDLE USB_INPUT_HANDLE = 0;
void sendMessage(CanUsbDevice* usbDevice, uint8_t* message, int messageSize) {
#ifdef DEBUG
Serial.print("sending message: ");
Serial.println((char*)message);
#endif
// Make sure the USB write is 100% complete before messing with this buffer
// after we copy the message into it - the Microchip library doesn't copy
// the data to its own internal buffer. See #171 for background on this
// issue.
int i = 0;
bool usbConnected = usbDevice->configured;
while(usbDevice->device.HandleBusy(USB_INPUT_HANDLE)) {
i++;
if(i > 200000) {
// stop waiting, USB probably isn't connected
usbConnected = false;
// break;
}
}
strncpy(usbDevice->sendBuffer, (char*)message, messageSize);
usbDevice->sendBuffer[messageSize] = '\n';
messageSize += 1;
if(!usbConnected) {
// Serial transfers are really, really slow, so we don't want to send unless
// explicitly set to do so at compile-time. Alternatively, we could send
// on serial whenever we detect below that we're probably not connected to a
// USB device, but explicit is better than implicit.
usbDevice->serial->device->write((const uint8_t*)usbDevice->sendBuffer, messageSize);
} else {
int nextByteIndex = 0;
while(nextByteIndex < messageSize) {
while(usbDevice->device.HandleBusy(USB_INPUT_HANDLE));
int bytesToTransfer = min(USB_PACKET_SIZE,
messageSize - nextByteIndex);
uint8_t* currentByte = (uint8_t*)(usbDevice->sendBuffer
+ nextByteIndex);
USB_INPUT_HANDLE = usbDevice->device.GenWrite(usbDevice->endpoint,
currentByte, bytesToTransfer);
nextByteIndex += bytesToTransfer;
}
}
}
void initializeUsb(CanUsbDevice* usbDevice) {
Serial.print("Initializing USB.....");
usbDevice->device.InitializeSystem(false);
Serial.println("Done.");
}
USB_HANDLE armForRead(CanUsbDevice* usbDevice, char* buffer) {
buffer[0] = 0;
return usbDevice->device.GenRead(usbDevice->endpoint, (uint8_t*)buffer,
usbDevice->endpointSize);
}
USB_HANDLE readFromHost(CanUsbDevice* usbDevice, USB_HANDLE handle,
bool (*callback)(char*)) {
if(!usbDevice->device.HandleBusy(handle)) {
// TODO see #569
delay(200);
if(usbDevice->receiveBuffer[0] != NULL) {
strncpy((char*)(usbDevice->packetBuffer +
usbDevice->packetBufferIndex), usbDevice->receiveBuffer,
ENDPOINT_SIZE);
usbDevice->packetBufferIndex += ENDPOINT_SIZE;
processBuffer(usbDevice->packetBuffer,
&usbDevice->packetBufferIndex, PACKET_BUFFER_SIZE, callback);
}
return armForRead(usbDevice, usbDevice->receiveBuffer);
}
return handle;
}
<commit_msg>Don't play the waiting game with USB - just assume it's unplugged after a while.<commit_after>#include "usbutil.h"
#include "buffers.h"
// TODO move this up to cantranslator.pde
USB_HANDLE USB_INPUT_HANDLE = 0;
void sendMessage(CanUsbDevice* usbDevice, uint8_t* message, int messageSize) {
#ifdef DEBUG
Serial.print("sending message: ");
Serial.println((char*)message);
#endif
// Make sure the USB write is 100% complete before messing with this buffer
// after we copy the message into it - the Microchip library doesn't copy
// the data to its own internal buffer. See #171 for background on this
// issue.
int i = 0;
while(usbDevice->configured && usbDevice->device.HandleBusy(USB_INPUT_HANDLE)) {
i++;
if(i > 1000000) {
// USB was probably unplugged, mark it as unplugged and continue on
// sending over serial.
usbDevice->configured = false;
}
}
Serial.println(i);
strncpy(usbDevice->sendBuffer, (char*)message, messageSize);
usbDevice->sendBuffer[messageSize] = '\n';
messageSize += 1;
if(!usbDevice->configured) {
// Serial transfers are really, really slow, so we don't want to send unless
// explicitly set to do so at compile-time. Alternatively, we could send
// on serial whenever we detect below that we're probably not connected to a
// USB device, but explicit is better than implicit.
usbDevice->serial->device->write((const uint8_t*)usbDevice->sendBuffer, messageSize);
} else {
int nextByteIndex = 0;
while(nextByteIndex < messageSize) {
while(usbDevice->device.HandleBusy(USB_INPUT_HANDLE));
int bytesToTransfer = min(USB_PACKET_SIZE,
messageSize - nextByteIndex);
uint8_t* currentByte = (uint8_t*)(usbDevice->sendBuffer
+ nextByteIndex);
USB_INPUT_HANDLE = usbDevice->device.GenWrite(usbDevice->endpoint,
currentByte, bytesToTransfer);
nextByteIndex += bytesToTransfer;
}
}
}
void initializeUsb(CanUsbDevice* usbDevice) {
Serial.print("Initializing USB.....");
usbDevice->device.InitializeSystem(false);
Serial.println("Done.");
}
USB_HANDLE armForRead(CanUsbDevice* usbDevice, char* buffer) {
buffer[0] = 0;
return usbDevice->device.GenRead(usbDevice->endpoint, (uint8_t*)buffer,
usbDevice->endpointSize);
}
USB_HANDLE readFromHost(CanUsbDevice* usbDevice, USB_HANDLE handle,
bool (*callback)(char*)) {
if(!usbDevice->device.HandleBusy(handle)) {
// TODO see #569
delay(200);
if(usbDevice->receiveBuffer[0] != NULL) {
strncpy((char*)(usbDevice->packetBuffer +
usbDevice->packetBufferIndex), usbDevice->receiveBuffer,
ENDPOINT_SIZE);
usbDevice->packetBufferIndex += ENDPOINT_SIZE;
processBuffer(usbDevice->packetBuffer,
&usbDevice->packetBufferIndex, PACKET_BUFFER_SIZE, callback);
}
return armForRead(usbDevice, usbDevice->receiveBuffer);
}
return handle;
}
<|endoftext|> |
<commit_before>#include "sixtracklib/cuda/wrappers/track_job_wrappers.h"
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <gtest/gtest.h>
#include <cuda_runtime_api.h>
#include "sixtracklib/testlib.h"
#include "sixtracklib/common/definitions.h"
#include "sixtracklib/common/control/definitions.h"
#include "sixtracklib/common/buffer.h"
#include "sixtracklib/common/particles/particles_addr.h"
#include "sixtracklib/common/particles.h"
#include "sixtracklib/common/be_drift.h"
#include "sixtracklib/cuda/controller.h"
#include "sixtracklib/cuda/argument.h"
#include "sixtracklib/cuda/control/kernel_config.h"
#include "sixtracklib/cuda/control/node_info.h"
namespace SIXTRL_CXX_NAMESPACE
{
namespace tests
{
bool run_test(
std::string const& node_id_str,
::NS(buffer_size_t) const num_elements,
::NS(buffer_size_t) const num_blocks,
::NS(buffer_size_t) const num_threads_per_block,
::NS(buffer_size_t) const min_num_particles =
::NS(buffer_size_t{ 1 },
::NS(buffer_size_t) const max_num_particles =
::NS(buffer_size_t{ 2 },
double const probabilty_to_not_particles = double{ 0 },
::NS(buffer_size_t) const seed = ::NS(buffer_size_t){ 20190517 } );
}
}
TEST( C99_CudaWrappersExtractParticleAddrTest, SingleParticleSetTest )
{
namespace st = SIXTRL_CXX_NAMESPACE;
ASSERT_TRUE( st::tests::run_test( "", 1, 1, 1 ) );
ASSERT_TRUE( st::tests::run_test( "", 1, 2048, 1 ) );
ASSERT_TRUE( st::tests::run_test( "", 1, 1, 256 ) );
}
TEST( C99_CudaWrappersExtractParticleAddrTest, MultiParticleSetTest )
{
ASSERT_TRUE( st::tests::run_test( "", 2048, 1, 1 ) );
ASSERT_TRUE( st::tests::run_test( "", 2048, 2048, 1 ) );
ASSERT_TRUE( st::tests::run_test( "", 2048, 1, 256 ) );
ASSERT_TRUE( st::tests::run_test( "", 2048, 8, 256 ) );
ASSERT_TRUE( st::tests::run_test( "", 2048, 16, 256 ) );
}
TEST( C99_CudaWrappersExtractParticleAddrTest, MultiParticleSetWithNonParticles )
{
ASSERT_TRUE( st::tests::run_test( "", 2048, 1, 1 , 1, 2, 0.1 ) );
ASSERT_TRUE( st::tests::run_test( "", 2048, 2048, 1 , 1, 2, 0.1 ) );
ASSERT_TRUE( st::tests::run_test( "", 2048, 1, 256, 1, 2, 0.1 ) );
ASSERT_TRUE( st::tests::run_test( "", 2048, 8, 256, 1, 2, 0.1 ) );
ASSERT_TRUE( st::tests::run_test( "", 2048, 16, 256, 1, 2, 0.1 ) );
}
namespace SIXTRL_CXX_NAMESPACE
{
namespace tests
{
bool run_test(
::NS(CudaController)* SIXTRL_RESTRICT ctrl,
::NS(CudaKernelConfig)* SIXTRL_RESTRICT ptr_kernel_config,
::NS(buffer_size_t) const num_elements,
::NS(buffer_size_t) const min_num_particles,
::NS(buffer_size_t) const max_num_particles,
double const probabilty_to_not_particles,
::NS(buffer_size_t) const seed = ::NS(buffer_size_t){ 20190517 } )
{
using particles_t = ::NS(Particles);
using particles_addr_t = ::NS(ParticlesAddr);
using c_buffer_t = ::NS(Buffer);
using cuda_ctrl_t = ::NS(CudaController);
using cuda_arg_t = ::NS(CudaArgument);
using cuda_kernel_conf_t = ::NS(CudaKernelConfig);
using kernel_id_t = ::NS(ctrl_kernel_id_t);
using size_t = ::NS(buffer_size_t);
using status_t = ::NS(arch_status_t);
using result_register_t = ::NS(arch_debugging_t);
using address_t = ::NS(buffer_addr_t);
using addr_diff_t = ::NS(buffer_addr_diff_t);
bool success = false;
status_t status = ::NS(ARCH_STATUS_SUCCESS);
if( ( ctrl == nullptr ) ||
( ptr_kernel_config == nullptr ) ||
( ptr_kernel_config->needsUpdate() ) )
{
return success;
}
/* -------------------------------------------------------------------- */
/* Prepare the cmp particles and particles addr buffer; the former is
* used to verify the results of the test */
c_buffer_t* particles_buffer = ::NS(Buffer_new)( size_t{ 0 } );
c_buffer_t* cmp_paddr_buffer = ::NS(Buffer_new)( size_t{ 0 } );
SIXTRL_ASSERT( cmp_paddr_buffer != nullptr );
SIXTRL_ASSERT( particles_buffer != nullptr );
size_t const slot_size =
::NS(Buffer_get_slot_size)( particles_buffer );
SIXTRL_ASSERT( slot_size > size_t{ 0 } );
size_t constexpr prng_seed = size_t{ 20190517 };
size_t constexpr num_psets = size_t{ 1 };
size_t constexpr min_num_particles = size_t{ 100 };
size_t constexpr max_num_particles = size_t{ 200 };
/* Enforce that we always have a NS(Particles) instance in this test */
double const probabilty_to_not_particles = double{ 0.0 };
status = ::NS(TestParticlesAddr_prepare_buffers)( particles_buffer,
cmp_paddr_buffer, num_psets, min_num_particles, max_num_particles,
probabilty_to_not_particles, prng_seed );
SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );
status = ::NS(ParticlesAddr_buffer_store_all_addresses)(
cmp_paddr_buffer, particles_buffer );
SIXRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );
status = ::NS(TestParticlesAddr_verify_structure)(
cmp_paddr_buffer, particles_buffer );
SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );
status = ::NS(TestParticlesAddr_verify_addresses)(
cmp_paddr_buffer, particles_buffer );
SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );
/* --------------------------------------------------------------------- */
/* Prepare the actual paddr_buffer that is used for the test */
c_buffer_t* paddr_buffer = ::NS(Buffer_new)( size_t{ 0 } );
SIXTRL_ASSERT( paddr_buffer != nullptr );
status = ::NS(ParticlesAddr_prepare_buffer_based_on_particles_buffer)(
paddr_buffer, particles_buffer );
SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );
/* -------------------------------------------------------------------- */
/* Init the Cuda controller and arguments for the addresses
* and the particles */
success = true;
cuda_arg_t* particles_arg = ::NS(CudaArgument_new)( ctrl );
SIXTRL_ASSERT( particles_arg != nullptr );
cuda_arg_t* addresses_arg = ::NS(CudaArgument_new)( ctrl );
SIXTRL_ASSERT( addresses_arg != nullptr );
result_register_t result_register = ::NS(ARCH_DEBUGGING_GENERAL_FAILURE);
cuda_arg_t* result_register_arg =
::NS(CudaArgument_new_raw_argument)(
&result_register, sizeof( result_register ), ctrl );
SIXTRL_ASSERT( result_register_arg != nullptr );
/* Send the particles and the addresses buffer to the node */
status = ::NS(Argument_send_buffer)( particles_arg, particles_buffer );
SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );
status = ::NS(Argument_send_buffer)( addresses_arg, paddr_buffer );
SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );
/* reset the particles address buffer at the host side,
* so that we can be certain about the success of the operation */
::NS(Buffer_clear)( paddr_buffer, true );
::NS(Buffer_reset)( paddr_buffer );
SIXTRL_ASSERT( ::NS(Buffer_get_num_of_objects)( paddr_buffer ) ==
size_t{ 0 } );
/* ===================================================================== */
/* !!! START OF THE ACTUAL TEST !!! */
::NS(Particles_buffer_store_all_addresses_cuda_wrapper)(
ptr_kernel_config, addresses_arg, particles_arg,
result_register_arg );
status = ::NS(Argument_receive_buffer)( paddr_buffer );
SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS );
SIXTRL_ASSERT( !::NS(Buffer_needs_remapping)( paddr_buffer ) );
status = ::NS(Argument_receive_raw_arg)(
&result_register, sizeof( result_register ) );
SIXTRL_ASSERT( status == :NS(ARCH_STATUS_SUCCESS) );
if( result_register != ::NS(ARCH_DEBUGGING_REGISTER_EMPTY) )
{
success = false;
}
success &= ( ::NS(TestParticlesAddr_verify_structure)( paddr_buffer,
particles_buffer ) == ::NS(ARCH_STATUS_SUCCESS) );
if( success )
{
status = ::NS(Argument_receive_buffer_without_remap)(
particles_arg, particles_buffer );
SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );
address_t const device_begin_addr =
::NS(ManagedBuffer_get_stored_begin_addr)(
particles_buffer, slot_size );
address_t const host_begin_addr =
::NS(ManagedBuffer_get_buffer_begin_addr)(
particles_buffer, slot_size );
/* addr_offset = host_begin_addr - device_begin_addr -->
* host_begin_addr = device_begin_addr + addr_offset */
addr_diff_t const addr_offset =
host_begin_addr - device_begin_addr;
}
/* Cleanup: */
::NS(Argument_delete)( particles_arg );
::NS(Argument_delete)( addresses_arg );
::NS(Argument_delete)( result_register_arg );
::NS(Buffer_delete)( paddr_buffer );
::NS(Buffer_delete)( particles_buffer );
::NS(Buffer_delete)( cmp_paddr_buffer );
::NS(Controller_delete)( ctrl );
return success;
}
}
}
/* end: tests/sixtracklib/cuda/wrappers/test_track_job_wrappers_c99.cpp */
<commit_msg>tests/cuda: remove no longer needed tests file<commit_after><|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <memory>
#include <gtest/gtest.h>
#include <vw/Core/Cache.h>
#include <vw/Core/FundamentalTypes.h>
using namespace vw;
// A dummy BlockGenerator that generates blocks of 1-byte data.
class BlockGenerator {
protected:
int m_dimension;
vw::uint8 m_fill_value;
public:
BlockGenerator(int dimension, vw::uint8 fill_value = 0) :
m_dimension(dimension), m_fill_value(fill_value) {}
typedef vw::uint8 value_type;
size_t size() const {
return m_dimension * m_dimension * sizeof(vw::uint8);
}
boost::shared_ptr< value_type > generate() const {
boost::shared_ptr< value_type > ptr(new vw::uint8[m_dimension*m_dimension]);
(&(*ptr))[0] = m_fill_value;
return ptr;
}
};
class CacheTest : public ::testing::Test {
public:
typedef Cache::Handle<BlockGenerator> HandleT;
typedef std::vector<HandleT> ContainerT;
vw::Cache cache;
ContainerT cache_handles;
const static int dimension = 1024;
const static int num_actual_blocks = 10;
const static int num_cache_blocks = 3;
CacheTest() :
cache( num_cache_blocks*dimension*dimension ), cache_handles( num_actual_blocks ) {
for (uint8 i = 0; i < num_actual_blocks; ++i) {
cache_handles[i] = cache.insert( BlockGenerator( dimension, i ) );
}
}
};
TEST_F(CacheTest, CacheLineLRU) {
// Test assumes cache size less than total data
ASSERT_LT(+num_cache_blocks, +num_actual_blocks);
for (int i = 0; i < num_actual_blocks; ++i) {
Cache::Handle<BlockGenerator> &h = cache_handles[i];
ASSERT_EQ(h.size(), dimension*dimension*sizeof(BlockGenerator::value_type));
ASSERT_FALSE(h.valid());
EXPECT_EQ(i, *h);
EXPECT_TRUE(h.valid());
boost::shared_ptr<BlockGenerator::value_type> ptr = h;
EXPECT_EQ(i, *ptr);
// LRU cache, so the last num_cache_blocks should still be valid
for (int j = 0; i-j >= 0; ++j)
{
SCOPED_TRACE(::testing::Message() << "Cache block " << i);
if (j < num_cache_blocks) {
EXPECT_TRUE(cache_handles[i-j].valid());
} else {
EXPECT_FALSE(cache_handles[i-j].valid());
}
}
}
}
TEST_F(CacheTest, Priority) {
// Test assumes cache size less than total data
ASSERT_LT(+num_cache_blocks, +num_actual_blocks);
// prime the cache
for (int i = 0; i < num_actual_blocks; ++i) {
EXPECT_EQ(i, *cache_handles[i]);
}
//make sure last element is valid
ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());
// deprioritize the last element, and ensure it's still valid
cache_handles[num_actual_blocks-1].deprioritize();
ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());
// bring the first element back into cache
ASSERT_FALSE(cache_handles[0].valid());
EXPECT_EQ( 0, *cache_handles[0] );
EXPECT_TRUE(cache_handles[0].valid());
// make sure that the deprioritized element dropped out of cache
EXPECT_FALSE(cache_handles[num_actual_blocks-1].valid());
}
// Every copy increases the fill_value by one
class GenGen : public BlockGenerator {
public:
GenGen() : BlockGenerator(1, 0) {}
GenGen(const GenGen& obj) :
BlockGenerator(obj.m_dimension, boost::numeric_cast<uint8>(obj.m_fill_value+1)) {}
};
TEST(Cache, Types) {
// This test makes sure cache handles can hold polymorphic types
// and gives the user control over copying vs. not.
typedef Cache::Handle<GenGen> obj_t;
typedef Cache::Handle<boost::shared_ptr<GenGen> > sptr_t;
vw::Cache cache(sizeof(vw::uint8));
GenGen value;
boost::shared_ptr<GenGen> shared(new GenGen());
obj_t h1 = cache.insert(value);
sptr_t h2 = cache.insert(shared);
// Make sure the value hasn't generated yet
ASSERT_FALSE(h1.valid());
ASSERT_FALSE(h2.valid());
// value should have copied once
EXPECT_EQ(1, *h1);
// shared_ptr should not have copied
EXPECT_EQ(0, *h2);
}
TEST(Cache, Stats) {
typedef Cache::Handle<BlockGenerator> handle_t;
// Cache can hold 2 items
vw::Cache cache(2*sizeof(handle_t::value_type));
handle_t h[3] = {
cache.insert(BlockGenerator(1, 0)),
cache.insert(BlockGenerator(1, 1)),
cache.insert(BlockGenerator(1, 2))};
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(0u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss
EXPECT_EQ(0, *h[0]);
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(1u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// hit
EXPECT_EQ(0, *h[0]);
EXPECT_EQ(1u, cache.hits());
EXPECT_EQ(1u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss
EXPECT_EQ(1, *h[1]);
EXPECT_EQ(1u, cache.hits());
EXPECT_EQ(2u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// hit
EXPECT_EQ(1, *h[1]);
EXPECT_EQ(2u, cache.hits());
EXPECT_EQ(2u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss, eviction
EXPECT_EQ(2, *h[2]);
EXPECT_EQ(2u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// hit
EXPECT_EQ(2, *h[2]);
EXPECT_EQ(3u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// hit
EXPECT_EQ(1, *h[1]);
EXPECT_EQ(4u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// miss, eviction
EXPECT_EQ(0, *h[0]);
EXPECT_EQ(4u, cache.hits());
EXPECT_EQ(4u, cache.misses());
EXPECT_EQ(2u, cache.evictions());
cache.clear_stats();
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(0u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
}
<commit_msg>fix leaky test.<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <memory>
#include <gtest/gtest.h>
#include <vw/Core/Cache.h>
#include <vw/Core/FundamentalTypes.h>
#include <boost/shared_array.hpp>
using namespace vw;
// A dummy BlockGenerator that generates blocks of 1-byte data.
class BlockGenerator {
protected:
int m_dimension;
vw::uint8 m_fill_value;
public:
BlockGenerator(int dimension, vw::uint8 fill_value = 0) :
m_dimension(dimension), m_fill_value(fill_value) {}
typedef vw::uint8 value_type;
size_t size() const {
return m_dimension * m_dimension * sizeof(vw::uint8);
}
boost::shared_ptr< value_type > generate() const {
boost::shared_ptr< value_type > ptr(new vw::uint8[m_dimension*m_dimension], boost::checked_array_deleter<value_type>());
(&(*ptr))[0] = m_fill_value;
return ptr;
}
};
class CacheTest : public ::testing::Test {
public:
typedef Cache::Handle<BlockGenerator> HandleT;
typedef std::vector<HandleT> ContainerT;
vw::Cache cache;
ContainerT cache_handles;
const static int dimension = 1024;
const static int num_actual_blocks = 10;
const static int num_cache_blocks = 3;
CacheTest() :
cache( num_cache_blocks*dimension*dimension ), cache_handles( num_actual_blocks ) {
for (uint8 i = 0; i < num_actual_blocks; ++i) {
cache_handles[i] = cache.insert( BlockGenerator( dimension, i ) );
}
}
};
TEST_F(CacheTest, CacheLineLRU) {
// Test assumes cache size less than total data
ASSERT_LT(+num_cache_blocks, +num_actual_blocks);
for (int i = 0; i < num_actual_blocks; ++i) {
Cache::Handle<BlockGenerator> &h = cache_handles[i];
ASSERT_EQ(h.size(), dimension*dimension*sizeof(BlockGenerator::value_type));
ASSERT_FALSE(h.valid());
EXPECT_EQ(i, *h);
EXPECT_TRUE(h.valid());
boost::shared_ptr<BlockGenerator::value_type> ptr = h;
EXPECT_EQ(i, *ptr);
// LRU cache, so the last num_cache_blocks should still be valid
for (int j = 0; i-j >= 0; ++j)
{
SCOPED_TRACE(::testing::Message() << "Cache block " << i);
if (j < num_cache_blocks) {
EXPECT_TRUE(cache_handles[i-j].valid());
} else {
EXPECT_FALSE(cache_handles[i-j].valid());
}
}
}
}
TEST_F(CacheTest, Priority) {
// Test assumes cache size less than total data
ASSERT_LT(+num_cache_blocks, +num_actual_blocks);
// prime the cache
for (int i = 0; i < num_actual_blocks; ++i) {
EXPECT_EQ(i, *cache_handles[i]);
}
//make sure last element is valid
ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());
// deprioritize the last element, and ensure it's still valid
cache_handles[num_actual_blocks-1].deprioritize();
ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());
// bring the first element back into cache
ASSERT_FALSE(cache_handles[0].valid());
EXPECT_EQ( 0, *cache_handles[0] );
EXPECT_TRUE(cache_handles[0].valid());
// make sure that the deprioritized element dropped out of cache
EXPECT_FALSE(cache_handles[num_actual_blocks-1].valid());
}
// Every copy increases the fill_value by one
class GenGen : public BlockGenerator {
public:
GenGen() : BlockGenerator(1, 0) {}
GenGen(const GenGen& obj) :
BlockGenerator(obj.m_dimension, boost::numeric_cast<uint8>(obj.m_fill_value+1)) {}
};
TEST(Cache, Types) {
// This test makes sure cache handles can hold polymorphic types
// and gives the user control over copying vs. not.
typedef Cache::Handle<GenGen> obj_t;
typedef Cache::Handle<boost::shared_ptr<GenGen> > sptr_t;
vw::Cache cache(sizeof(vw::uint8));
GenGen value;
boost::shared_ptr<GenGen> shared(new GenGen());
obj_t h1 = cache.insert(value);
sptr_t h2 = cache.insert(shared);
// Make sure the value hasn't generated yet
ASSERT_FALSE(h1.valid());
ASSERT_FALSE(h2.valid());
// value should have copied once
EXPECT_EQ(1, *h1);
// shared_ptr should not have copied
EXPECT_EQ(0, *h2);
}
TEST(Cache, Stats) {
typedef Cache::Handle<BlockGenerator> handle_t;
// Cache can hold 2 items
vw::Cache cache(2*sizeof(handle_t::value_type));
handle_t h[3] = {
cache.insert(BlockGenerator(1, 0)),
cache.insert(BlockGenerator(1, 1)),
cache.insert(BlockGenerator(1, 2))};
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(0u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss
EXPECT_EQ(0, *h[0]);
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(1u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// hit
EXPECT_EQ(0, *h[0]);
EXPECT_EQ(1u, cache.hits());
EXPECT_EQ(1u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss
EXPECT_EQ(1, *h[1]);
EXPECT_EQ(1u, cache.hits());
EXPECT_EQ(2u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// hit
EXPECT_EQ(1, *h[1]);
EXPECT_EQ(2u, cache.hits());
EXPECT_EQ(2u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss, eviction
EXPECT_EQ(2, *h[2]);
EXPECT_EQ(2u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// hit
EXPECT_EQ(2, *h[2]);
EXPECT_EQ(3u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// hit
EXPECT_EQ(1, *h[1]);
EXPECT_EQ(4u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// miss, eviction
EXPECT_EQ(0, *h[0]);
EXPECT_EQ(4u, cache.hits());
EXPECT_EQ(4u, cache.misses());
EXPECT_EQ(2u, cache.evictions());
cache.clear_stats();
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(0u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
}
<|endoftext|> |
<commit_before>#include "event_base.h"
#include "logging.h"
#include "util.h"
#include <map>
#include <string.h>
#include <fcntl.h>
#include "poller.h"
#include "conn.h"
using namespace std;
namespace handy {
namespace {
struct TimerRepeatable {
int64_t at; //current timer timeout timestamp
int64_t interval;
TimerId timerid;
Task cb;
};
struct IdleNode {
TcpConnPtr con_;
int64_t updated_;
TcpCallBack cb_;
};
}
struct IdleIdImp {
IdleIdImp() {}
typedef list<IdleNode>::iterator Iter;
IdleIdImp(list<IdleNode>* lst, Iter iter): lst_(lst), iter_(iter){}
list<IdleNode>* lst_;
Iter iter_;
};
struct EventsImp {
EventBase* base_;
PollerBase* poller_;
std::atomic<bool> exit_;
int wakeupFds_[2];
int nextTimeout_;
SafeQueue<Task> tasks_;
std::map<TimerId, TimerRepeatable> timerReps_;
std::map<TimerId, Task> timers_;
std::atomic<int64_t> timerSeq_;
std::map<int, std::list<IdleNode>> idleConns_;
std::set<TcpConnPtr> reconnectConns_;
bool idleEnabled;
EventsImp(EventBase* base, int taskCap);
~EventsImp();
void init();
void callIdles();
IdleId registerIdle(int idle, const TcpConnPtr& con, const TcpCallBack& cb);
void unregisterIdle(const IdleId& id);
void updateIdle(const IdleId& id);
void handleTimeouts();
void refreshNearest(const TimerId* tid=NULL);
void repeatableTimeout(TimerRepeatable* tr);
//eventbase functions
EventBase& exit();
bool exited() { return exit_; }
void safeCall(Task&& task) { tasks_.push(move(task)); wakeup(); }
void loop() { while (!exit_) loop_once(10000); loop_once(0); }
void loop_once(int waitMs) { poller_->loop_once(std::min(waitMs, nextTimeout_)); handleTimeouts(); }
void wakeup() {
int r = write(wakeupFds_[1], "", 1);
fatalif(r<=0, "write error wd %d %d %s", r, errno, strerror(errno));
}
bool cancel(TimerId timerid);
TimerId runAt(int64_t milli, Task&& task, int64_t interval);
};
EventBase::EventBase(int taskCapacity) {
imp_.reset(new EventsImp(this, taskCapacity));
imp_->init();
}
EventBase::~EventBase() {}
EventBase& EventBase::exit() { return imp_->exit(); }
bool EventBase::exited() { return imp_->exited(); }
void EventBase::safeCall(Task&& task) { imp_->safeCall(move(task)); }
void EventBase::wakeup(){ imp_->wakeup(); }
void EventBase::loop() { imp_->loop(); }
void EventBase::loop_once(int waitMs) { imp_->loop_once(waitMs); }
bool EventBase::cancel(TimerId timerid) { return imp_->cancel(timerid); }
TimerId EventBase::runAt(int64_t milli, Task&& task, int64_t interval) {
return imp_->runAt(milli, std::move(task), interval);
}
EventsImp::EventsImp(EventBase* base, int taskCap):
base_(base), poller_(new PlatformPoller()), exit_(false), nextTimeout_(1<<30), tasks_(taskCap),
timerSeq_(0), idleEnabled(false)
{
}
void EventsImp::init() {
int r = pipe(wakeupFds_);
fatalif(r, "pipe failed %d %s", errno, strerror(errno));
r = util::addFdFlag(wakeupFds_[0], FD_CLOEXEC);
fatalif(r, "addFdFlag failed %d %s", errno, strerror(errno));
r = util::addFdFlag(wakeupFds_[1], FD_CLOEXEC);
fatalif(r, "addFdFlag failed %d %s", errno, strerror(errno));
trace("wakeup pipe created %d %d", wakeupFds_[0], wakeupFds_[1]);
Channel* ch = new Channel(base_, wakeupFds_[0], kReadEvent);
ch->onRead([=] {
char buf[1024];
int r = ch->fd() >= 0 ? ::read(ch->fd(), buf, sizeof buf) : 0;
if (r > 0) {
Task task;
while (tasks_.pop_wait(&task, 0)) {
task();
}
} else if (r == 0) {
delete ch;
} else if (errno == EINTR) {
} else {
fatal("wakeup channel read error %d %d %s", r, errno, strerror(errno));
}
});
}
EventBase& EventsImp::exit() {
exit_ = true;
wakeup();
timerReps_.clear();
timers_.clear();
idleConns_.clear();
for (auto recon: reconnectConns_) { //重连的连接无法通过channel清理,因此单独清理
recon->cleanup(recon);
}
return *base_; }
void EventsImp::handleTimeouts() {
int64_t now = util::timeMilli();
TimerId tid { now, 1L<<62 };
while (timers_.size() && timers_.begin()->first < tid) {
Task task = move(timers_.begin()->second);
timers_.erase(timers_.begin());
task();
}
refreshNearest();
}
EventsImp::~EventsImp() {
delete poller_;
::close(wakeupFds_[1]);
}
void EventsImp::callIdles() {
int64_t now = util::timeMilli() / 1000;
for (auto& l: idleConns_) {
int idle = l.first;
auto lst = l.second;
while(lst.size()) {
IdleNode& node = lst.front();
if (node.updated_ + idle > now) {
break;
}
node.updated_ = now;
lst.splice(lst.end(), lst, lst.begin());
node.cb_(node.con_);
}
}
}
IdleId EventsImp::registerIdle(int idle, const TcpConnPtr& con, const TcpCallBack& cb) {
if (!idleEnabled) {
base_->runAfter(1000, [this] { callIdles(); }, 1000);
idleEnabled = true;
}
auto& lst = idleConns_[idle];
lst.push_back(IdleNode {con, util::timeMilli()/1000, move(cb) });
trace("register idle");
return IdleId(new IdleIdImp(&lst, --lst.end()));
}
void EventsImp::unregisterIdle(const IdleId& id) {
trace("unregister idle");
id->lst_->erase(id->iter_);
}
void EventsImp::updateIdle(const IdleId& id) {
trace("update idle");
id->iter_->updated_ = util::timeMilli() / 1000;
id->lst_->splice(id->lst_->end(), *id->lst_, id->iter_);
}
void EventsImp::refreshNearest(const TimerId* tid){
if (timers_.empty()) {
nextTimeout_ = 1 << 30;
} else {
const TimerId &t = timers_.begin()->first;
nextTimeout_ = t.first - util::timeMilli();
nextTimeout_ = nextTimeout_ < 0 ? 0 : nextTimeout_;
}
}
void EventsImp::repeatableTimeout(TimerRepeatable* tr) {
tr->at += tr->interval;
tr->timerid = { tr->at, ++timerSeq_ };
timers_[tr->timerid] = [this, tr] { repeatableTimeout(tr); };
refreshNearest(&tr->timerid);
tr->cb();
}
TimerId EventsImp::runAt(int64_t milli, Task&& task, int64_t interval) {
if (exit_) {
return TimerId();
}
if (interval) {
TimerId tid { -milli, ++timerSeq_};
TimerRepeatable& rtr = timerReps_[tid];
rtr = { milli, interval, { milli, ++timerSeq_ }, move(task) };
TimerRepeatable* tr = &rtr;
timers_[tr->timerid] = [this, tr] { repeatableTimeout(tr); };
refreshNearest(&tr->timerid);
return tid;
} else {
TimerId tid { milli, ++timerSeq_};
timers_.insert({tid, move(task)});
refreshNearest(&tid);
return tid;
}
}
bool EventsImp::cancel(TimerId timerid) {
if (timerid.first < 0) {
auto p = timerReps_.find(timerid);
auto ptimer = timers_.find(p->second.timerid);
if (ptimer != timers_.end()) {
timers_.erase(ptimer);
}
timerReps_.erase(p);
return true;
} else {
auto p = timers_.find(timerid);
if (p != timers_.end()) {
timers_.erase(p);
return true;
}
return false;
}
}
void MultiBase::loop() {
int sz = bases_.size();
vector<thread> ths(sz -1);
for(int i = 0; i < sz -1; i++) {
thread t([this, i]{ bases_[i].loop();});
ths[i].swap(t);
}
bases_.back().loop();
for (int i = 0; i < sz -1; i++) {
ths[i].join();
}
}
Channel::Channel(EventBase* base, int fd, int events): base_(base), fd_(fd), events_(events) {
fatalif(net::setNonBlock(fd_) < 0, "channel set non block failed");
static atomic<int64_t> id(0);
id_ = ++id;
poller_ = base_->imp_->poller_;
poller_->addChannel(this);
}
Channel::~Channel() {
close();
}
void Channel::enableRead(bool enable) {
if (enable) {
events_ |= kReadEvent;
} else {
events_ &= ~kReadEvent;
}
poller_->updateChannel(this);
}
void Channel::enableWrite(bool enable) {
if (enable) {
events_ |= kWriteEvent;
} else {
events_ &= ~kWriteEvent;
}
poller_->updateChannel(this);
}
void Channel::enableReadWrite(bool readable, bool writable) {
if (readable) {
events_ |= kReadEvent;
} else {
events_ &= ~kReadEvent;
}
if (writable) {
events_ |= kWriteEvent;
} else {
events_ &= ~kWriteEvent;
}
poller_->updateChannel(this);
}
void Channel::close() {
if (fd_>=0) {
trace("close channel %ld fd %d", (long)id_, fd_);
poller_->removeChannel(this);
::close(fd_);
fd_ = -1;
handleRead();
}
}
bool Channel::readEnabled() { return events_ & kReadEvent; }
bool Channel::writeEnabled() { return events_ & kWriteEvent; }
void handyUnregisterIdle(EventBase* base, const IdleId& idle) {
base->imp_->unregisterIdle(idle);
}
void handyUpdateIdle(EventBase* base, const IdleId& idle) {
base->imp_->updateIdle(idle);
}
TcpConn::TcpConn()
:base_(NULL), channel_(NULL), state_(State::Invalid), destPort_(-1), connectTimeout_(0), reconnectInterval_(-1)
{
}
TcpConn::~TcpConn() {
trace("tcp destroyed %s - %s", local_.toString().c_str(), peer_.toString().c_str());
delete channel_;
}
void TcpConn::addIdleCB(int idle, const TcpCallBack& cb) {
if (channel_) {
idleIds_.push_back(getBase()->imp_->registerIdle(idle, shared_from_this(), cb));
}
}
void TcpConn::reconnect() {
auto con = shared_from_this();
getBase()->imp_->reconnectConns_.insert(con);
getBase()->runAfter(reconnectInterval_, [this, con]() {
getBase()->imp_->reconnectConns_.erase(con);
connect(getBase(), destHost_, (short)destPort_, connectTimeout_, localIp_);
});
delete channel_;
channel_ = NULL;
}
}<commit_msg>move clean operation from exit to loop, keep exit async call ok<commit_after>#include "event_base.h"
#include "logging.h"
#include "util.h"
#include <map>
#include <string.h>
#include <fcntl.h>
#include "poller.h"
#include "conn.h"
using namespace std;
namespace handy {
namespace {
struct TimerRepeatable {
int64_t at; //current timer timeout timestamp
int64_t interval;
TimerId timerid;
Task cb;
};
struct IdleNode {
TcpConnPtr con_;
int64_t updated_;
TcpCallBack cb_;
};
}
struct IdleIdImp {
IdleIdImp() {}
typedef list<IdleNode>::iterator Iter;
IdleIdImp(list<IdleNode>* lst, Iter iter): lst_(lst), iter_(iter){}
list<IdleNode>* lst_;
Iter iter_;
};
struct EventsImp {
EventBase* base_;
PollerBase* poller_;
std::atomic<bool> exit_;
int wakeupFds_[2];
int nextTimeout_;
SafeQueue<Task> tasks_;
std::map<TimerId, TimerRepeatable> timerReps_;
std::map<TimerId, Task> timers_;
std::atomic<int64_t> timerSeq_;
std::map<int, std::list<IdleNode>> idleConns_;
std::set<TcpConnPtr> reconnectConns_;
bool idleEnabled;
EventsImp(EventBase* base, int taskCap);
~EventsImp();
void init();
void callIdles();
IdleId registerIdle(int idle, const TcpConnPtr& con, const TcpCallBack& cb);
void unregisterIdle(const IdleId& id);
void updateIdle(const IdleId& id);
void handleTimeouts();
void refreshNearest(const TimerId* tid=NULL);
void repeatableTimeout(TimerRepeatable* tr);
//eventbase functions
EventBase& exit() {exit_ = true; wakeup(); return *base_;}
bool exited() { return exit_; }
void safeCall(Task&& task) { tasks_.push(move(task)); wakeup(); }
void loop();
void loop_once(int waitMs) { poller_->loop_once(std::min(waitMs, nextTimeout_)); handleTimeouts(); }
void wakeup() {
int r = write(wakeupFds_[1], "", 1);
fatalif(r<=0, "write error wd %d %d %s", r, errno, strerror(errno));
}
bool cancel(TimerId timerid);
TimerId runAt(int64_t milli, Task&& task, int64_t interval);
};
EventBase::EventBase(int taskCapacity) {
imp_.reset(new EventsImp(this, taskCapacity));
imp_->init();
}
EventBase::~EventBase() {}
EventBase& EventBase::exit() { return imp_->exit(); }
bool EventBase::exited() { return imp_->exited(); }
void EventBase::safeCall(Task&& task) { imp_->safeCall(move(task)); }
void EventBase::wakeup(){ imp_->wakeup(); }
void EventBase::loop() { imp_->loop(); }
void EventBase::loop_once(int waitMs) { imp_->loop_once(waitMs); }
bool EventBase::cancel(TimerId timerid) { return imp_->cancel(timerid); }
TimerId EventBase::runAt(int64_t milli, Task&& task, int64_t interval) {
return imp_->runAt(milli, std::move(task), interval);
}
EventsImp::EventsImp(EventBase* base, int taskCap):
base_(base), poller_(new PlatformPoller()), exit_(false), nextTimeout_(1<<30), tasks_(taskCap),
timerSeq_(0), idleEnabled(false)
{
}
void EventsImp::loop() {
while (!exit_)
loop_once(10000);
timerReps_.clear();
timers_.clear();
idleConns_.clear();
for (auto recon: reconnectConns_) { //重连的连接无法通过channel清理,因此单独清理
recon->cleanup(recon);
}
loop_once(0);
}
void EventsImp::init() {
int r = pipe(wakeupFds_);
fatalif(r, "pipe failed %d %s", errno, strerror(errno));
r = util::addFdFlag(wakeupFds_[0], FD_CLOEXEC);
fatalif(r, "addFdFlag failed %d %s", errno, strerror(errno));
r = util::addFdFlag(wakeupFds_[1], FD_CLOEXEC);
fatalif(r, "addFdFlag failed %d %s", errno, strerror(errno));
trace("wakeup pipe created %d %d", wakeupFds_[0], wakeupFds_[1]);
Channel* ch = new Channel(base_, wakeupFds_[0], kReadEvent);
ch->onRead([=] {
char buf[1024];
int r = ch->fd() >= 0 ? ::read(ch->fd(), buf, sizeof buf) : 0;
if (r > 0) {
Task task;
while (tasks_.pop_wait(&task, 0)) {
task();
}
} else if (r == 0) {
delete ch;
} else if (errno == EINTR) {
} else {
fatal("wakeup channel read error %d %d %s", r, errno, strerror(errno));
}
});
}
void EventsImp::handleTimeouts() {
int64_t now = util::timeMilli();
TimerId tid { now, 1L<<62 };
while (timers_.size() && timers_.begin()->first < tid) {
Task task = move(timers_.begin()->second);
timers_.erase(timers_.begin());
task();
}
refreshNearest();
}
EventsImp::~EventsImp() {
delete poller_;
::close(wakeupFds_[1]);
}
void EventsImp::callIdles() {
int64_t now = util::timeMilli() / 1000;
for (auto& l: idleConns_) {
int idle = l.first;
auto lst = l.second;
while(lst.size()) {
IdleNode& node = lst.front();
if (node.updated_ + idle > now) {
break;
}
node.updated_ = now;
lst.splice(lst.end(), lst, lst.begin());
node.cb_(node.con_);
}
}
}
IdleId EventsImp::registerIdle(int idle, const TcpConnPtr& con, const TcpCallBack& cb) {
if (!idleEnabled) {
base_->runAfter(1000, [this] { callIdles(); }, 1000);
idleEnabled = true;
}
auto& lst = idleConns_[idle];
lst.push_back(IdleNode {con, util::timeMilli()/1000, move(cb) });
trace("register idle");
return IdleId(new IdleIdImp(&lst, --lst.end()));
}
void EventsImp::unregisterIdle(const IdleId& id) {
trace("unregister idle");
id->lst_->erase(id->iter_);
}
void EventsImp::updateIdle(const IdleId& id) {
trace("update idle");
id->iter_->updated_ = util::timeMilli() / 1000;
id->lst_->splice(id->lst_->end(), *id->lst_, id->iter_);
}
void EventsImp::refreshNearest(const TimerId* tid){
if (timers_.empty()) {
nextTimeout_ = 1 << 30;
} else {
const TimerId &t = timers_.begin()->first;
nextTimeout_ = t.first - util::timeMilli();
nextTimeout_ = nextTimeout_ < 0 ? 0 : nextTimeout_;
}
}
void EventsImp::repeatableTimeout(TimerRepeatable* tr) {
tr->at += tr->interval;
tr->timerid = { tr->at, ++timerSeq_ };
timers_[tr->timerid] = [this, tr] { repeatableTimeout(tr); };
refreshNearest(&tr->timerid);
tr->cb();
}
TimerId EventsImp::runAt(int64_t milli, Task&& task, int64_t interval) {
if (exit_) {
return TimerId();
}
if (interval) {
TimerId tid { -milli, ++timerSeq_};
TimerRepeatable& rtr = timerReps_[tid];
rtr = { milli, interval, { milli, ++timerSeq_ }, move(task) };
TimerRepeatable* tr = &rtr;
timers_[tr->timerid] = [this, tr] { repeatableTimeout(tr); };
refreshNearest(&tr->timerid);
return tid;
} else {
TimerId tid { milli, ++timerSeq_};
timers_.insert({tid, move(task)});
refreshNearest(&tid);
return tid;
}
}
bool EventsImp::cancel(TimerId timerid) {
if (timerid.first < 0) {
auto p = timerReps_.find(timerid);
auto ptimer = timers_.find(p->second.timerid);
if (ptimer != timers_.end()) {
timers_.erase(ptimer);
}
timerReps_.erase(p);
return true;
} else {
auto p = timers_.find(timerid);
if (p != timers_.end()) {
timers_.erase(p);
return true;
}
return false;
}
}
void MultiBase::loop() {
int sz = bases_.size();
vector<thread> ths(sz -1);
for(int i = 0; i < sz -1; i++) {
thread t([this, i]{ bases_[i].loop();});
ths[i].swap(t);
}
bases_.back().loop();
for (int i = 0; i < sz -1; i++) {
ths[i].join();
}
}
Channel::Channel(EventBase* base, int fd, int events): base_(base), fd_(fd), events_(events) {
fatalif(net::setNonBlock(fd_) < 0, "channel set non block failed");
static atomic<int64_t> id(0);
id_ = ++id;
poller_ = base_->imp_->poller_;
poller_->addChannel(this);
}
Channel::~Channel() {
close();
}
void Channel::enableRead(bool enable) {
if (enable) {
events_ |= kReadEvent;
} else {
events_ &= ~kReadEvent;
}
poller_->updateChannel(this);
}
void Channel::enableWrite(bool enable) {
if (enable) {
events_ |= kWriteEvent;
} else {
events_ &= ~kWriteEvent;
}
poller_->updateChannel(this);
}
void Channel::enableReadWrite(bool readable, bool writable) {
if (readable) {
events_ |= kReadEvent;
} else {
events_ &= ~kReadEvent;
}
if (writable) {
events_ |= kWriteEvent;
} else {
events_ &= ~kWriteEvent;
}
poller_->updateChannel(this);
}
void Channel::close() {
if (fd_>=0) {
trace("close channel %ld fd %d", (long)id_, fd_);
poller_->removeChannel(this);
::close(fd_);
fd_ = -1;
handleRead();
}
}
bool Channel::readEnabled() { return events_ & kReadEvent; }
bool Channel::writeEnabled() { return events_ & kWriteEvent; }
void handyUnregisterIdle(EventBase* base, const IdleId& idle) {
base->imp_->unregisterIdle(idle);
}
void handyUpdateIdle(EventBase* base, const IdleId& idle) {
base->imp_->updateIdle(idle);
}
TcpConn::TcpConn()
:base_(NULL), channel_(NULL), state_(State::Invalid), destPort_(-1), connectTimeout_(0), reconnectInterval_(-1)
{
}
TcpConn::~TcpConn() {
trace("tcp destroyed %s - %s", local_.toString().c_str(), peer_.toString().c_str());
delete channel_;
}
void TcpConn::addIdleCB(int idle, const TcpCallBack& cb) {
if (channel_) {
idleIds_.push_back(getBase()->imp_->registerIdle(idle, shared_from_this(), cb));
}
}
void TcpConn::reconnect() {
auto con = shared_from_this();
getBase()->imp_->reconnectConns_.insert(con);
getBase()->runAfter(reconnectInterval_, [this, con]() {
getBase()->imp_->reconnectConns_.erase(con);
connect(getBase(), destHost_, (short)destPort_, connectTimeout_, localIp_);
});
delete channel_;
channel_ = NULL;
}
}<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Copyright (C) 2012 Richard Moore <[email protected]>
** Copyright (C) 2012 David Faure <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// An implementation of QX11Info for Qt5. This code only provides the
// static methods of the QX11Info, not the methods for getting information
// about particular widgets or pixmaps.
//
#include "qx11info_x11.h"
#include <qpa/qplatformnativeinterface.h>
#include <qpa/qplatformwindow.h>
#include <qscreen.h>
#include <qdesktopwidget.h>
#include <qwindow.h>
#include <qapplication.h>
#include <xcb/xcb.h>
QT_BEGIN_NAMESPACE
/*!
\class QX11Info
\brief The QX11Info class provides information about the X display
configuration.
The class provides two APIs: a set of non-static functions that
provide information about a specific widget or pixmap, and a set
of static functions that provide the default information for the
application.
\warning This class is only available on X11. For querying
per-screen information in a portable way, use QDesktopWidget.
*/
/*!
Constructs an empty QX11Info object.
*/
QX11Info::QX11Info()
{
}
/*!
Returns the horizontal resolution of the given \a screen in terms of the
number of dots per inch.
The \a screen argument is an X screen number. Be aware that if
the user's system uses Xinerama (as opposed to traditional X11
multiscreen), there is only one X screen. Use QDesktopWidget to
query for information about Xinerama screens.
\sa setAppDpiX(), appDpiY()
*/
int QX11Info::appDpiX(int screen)
{
if (screen == -1) {
const QScreen *scr = QGuiApplication::primaryScreen();
if (!scr)
return 75;
return qRound(scr->logicalDotsPerInchX());
}
QList<QScreen *> screens = QGuiApplication::screens();
if (screen >= screens.size())
return 0;
return screens[screen]->logicalDotsPerInchX();
}
/*!
Returns the vertical resolution of the given \a screen in terms of the
number of dots per inch.
The \a screen argument is an X screen number. Be aware that if
the user's system uses Xinerama (as opposed to traditional X11
multiscreen), there is only one X screen. Use QDesktopWidget to
query for information about Xinerama screens.
\sa setAppDpiY(), appDpiX()
*/
int QX11Info::appDpiY(int screen)
{
if (screen == -1) {
const QScreen *scr = QGuiApplication::primaryScreen();
if (!scr)
return 75;
return qRound(scr->logicalDotsPerInchY());
}
QList<QScreen *> screens = QGuiApplication::screens();
if (screen > screens.size())
return 0;
return screens[screen]->logicalDotsPerInchY();
}
/*!
Returns a handle for the applications root window on the given \a screen.
The \a screen argument is an X screen number. Be aware that if
the user's system uses Xinerama (as opposed to traditional X11
multiscreen), there is only one X screen. Use QDesktopWidget to
query for information about Xinerama screens.
\sa QApplication::desktop()
*/
Qt::HANDLE QX11Info::appRootWindow(int screen)
{
if (!qApp)
return 0;
#if 0
// This looks like it should work, but gives the wrong value.
QDesktopWidget *desktop = QApplication::desktop();
QWidget *screenWidget = desktop->screen(screen);
QWindow *window = screenWidget->windowHandle();
#else
Q_UNUSED(screen);
QDesktopWidget *desktop = QApplication::desktop();
QWindow *window = desktop->windowHandle();
#endif
return Qt::HANDLE(window->winId());
}
/*!
Returns the number of the screen where the application is being
displayed.
\sa display(), screen()
*/
int QX11Info::appScreen()
{
if (!qApp)
return 0;
QDesktopWidget *desktop = QApplication::desktop();
return desktop->primaryScreen();
}
/*!
Returns the X11 time.
\sa setAppTime(), appUserTime()
*/
unsigned long QX11Info::appTime()
{
if (!qApp)
return 0;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
return static_cast<xcb_timestamp_t>(reinterpret_cast<quintptr>(native->nativeResourceForIntegration("apptime")));
}
/*!
Returns the X11 user time.
\sa setAppUserTime(), appTime()
*/
unsigned long QX11Info::appUserTime()
{
if (!qApp)
return 0;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
return static_cast<xcb_timestamp_t>(reinterpret_cast<quintptr>(native->nativeResourceForIntegration("appusertime")));
}
/*!
Sets the X11 time to the value specified by \a time.
\sa appTime(), setAppUserTime()
*/
void QX11Info::setAppTime(unsigned long time)
{
if (!qApp)
return;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
typedef void (*SetAppTimeFunc)(xcb_timestamp_t);
SetAppTimeFunc func = reinterpret_cast<SetAppTimeFunc>(native->nativeResourceFunctionForIntegration("setapptime"));
if (func)
func(time);
else
qWarning("Internal error: QPA plugin doesn't implement setAppTime");
}
/*!
Sets the X11 user time as specified by \a time.
\sa appUserTime(), setAppTime()
*/
void QX11Info::setAppUserTime(unsigned long time)
{
if (!qApp)
return;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
typedef void (*SetAppUserTimeFunc)(xcb_timestamp_t);
SetAppUserTimeFunc func = reinterpret_cast<SetAppUserTimeFunc>(native->nativeResourceFunctionForIntegration("setappusertime"));
if (func)
func(time);
else
qWarning("Internal error: QPA plugin doesn't implement setAppUserTime");
}
/*!
Returns the default display for the application.
\sa appScreen()
*/
Display *QX11Info::display()
{
if (!qApp)
return NULL;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
void *display = native->nativeResourceForScreen(QByteArray("display"), QGuiApplication::primaryScreen());
return reinterpret_cast<Display *>(display);
}
/*!
Returns the default XCB connection for the application.
\sa display()
*/
xcb_connection_t *QX11Info::connection()
{
if (!qApp)
return NULL;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
void *connection = native->nativeResourceForWindow(QByteArray("connection"), 0);
return reinterpret_cast<xcb_connection_t *>(connection);
}
QT_END_NAMESPACE
<commit_msg>Port to the version of the appTime/appUserTime that got merged in.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Copyright (C) 2012 Richard Moore <[email protected]>
** Copyright (C) 2012 David Faure <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// An implementation of QX11Info for Qt5. This code only provides the
// static methods of the QX11Info, not the methods for getting information
// about particular widgets or pixmaps.
//
#include "qx11info_x11.h"
#include <qpa/qplatformnativeinterface.h>
#include <qpa/qplatformwindow.h>
#include <qscreen.h>
#include <qdesktopwidget.h>
#include <qwindow.h>
#include <qapplication.h>
#include <xcb/xcb.h>
QT_BEGIN_NAMESPACE
/*!
\class QX11Info
\brief The QX11Info class provides information about the X display
configuration.
The class provides two APIs: a set of non-static functions that
provide information about a specific widget or pixmap, and a set
of static functions that provide the default information for the
application.
\warning This class is only available on X11. For querying
per-screen information in a portable way, use QDesktopWidget.
*/
/*!
Constructs an empty QX11Info object.
*/
QX11Info::QX11Info()
{
}
/*!
Returns the horizontal resolution of the given \a screen in terms of the
number of dots per inch.
The \a screen argument is an X screen number. Be aware that if
the user's system uses Xinerama (as opposed to traditional X11
multiscreen), there is only one X screen. Use QDesktopWidget to
query for information about Xinerama screens.
\sa setAppDpiX(), appDpiY()
*/
int QX11Info::appDpiX(int screen)
{
if (screen == -1) {
const QScreen *scr = QGuiApplication::primaryScreen();
if (!scr)
return 75;
return qRound(scr->logicalDotsPerInchX());
}
QList<QScreen *> screens = QGuiApplication::screens();
if (screen >= screens.size())
return 0;
return screens[screen]->logicalDotsPerInchX();
}
/*!
Returns the vertical resolution of the given \a screen in terms of the
number of dots per inch.
The \a screen argument is an X screen number. Be aware that if
the user's system uses Xinerama (as opposed to traditional X11
multiscreen), there is only one X screen. Use QDesktopWidget to
query for information about Xinerama screens.
\sa setAppDpiY(), appDpiX()
*/
int QX11Info::appDpiY(int screen)
{
if (screen == -1) {
const QScreen *scr = QGuiApplication::primaryScreen();
if (!scr)
return 75;
return qRound(scr->logicalDotsPerInchY());
}
QList<QScreen *> screens = QGuiApplication::screens();
if (screen > screens.size())
return 0;
return screens[screen]->logicalDotsPerInchY();
}
/*!
Returns a handle for the applications root window on the given \a screen.
The \a screen argument is an X screen number. Be aware that if
the user's system uses Xinerama (as opposed to traditional X11
multiscreen), there is only one X screen. Use QDesktopWidget to
query for information about Xinerama screens.
\sa QApplication::desktop()
*/
Qt::HANDLE QX11Info::appRootWindow(int screen)
{
if (!qApp)
return 0;
#if 0
// This looks like it should work, but gives the wrong value.
QDesktopWidget *desktop = QApplication::desktop();
QWidget *screenWidget = desktop->screen(screen);
QWindow *window = screenWidget->windowHandle();
#else
Q_UNUSED(screen);
QDesktopWidget *desktop = QApplication::desktop();
QWindow *window = desktop->windowHandle();
#endif
return Qt::HANDLE(window->winId());
}
/*!
Returns the number of the screen where the application is being
displayed.
\sa display(), screen()
*/
int QX11Info::appScreen()
{
if (!qApp)
return 0;
QDesktopWidget *desktop = QApplication::desktop();
return desktop->primaryScreen();
}
/*!
Returns the X11 time.
\sa setAppTime(), appUserTime()
*/
unsigned long QX11Info::appTime()
{
if (!qApp)
return 0;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
QScreen* screen = QGuiApplication::primaryScreen();
return static_cast<xcb_timestamp_t>(reinterpret_cast<quintptr>(native->nativeResourceForScreen("apptime", screen)));
}
/*!
Returns the X11 user time.
\sa setAppUserTime(), appTime()
*/
unsigned long QX11Info::appUserTime()
{
if (!qApp)
return 0;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
QScreen* screen = QGuiApplication::primaryScreen();
return static_cast<xcb_timestamp_t>(reinterpret_cast<quintptr>(native->nativeResourceForScreen("appusertime", screen)));
}
/*!
Sets the X11 time to the value specified by \a time.
\sa appTime(), setAppUserTime()
*/
void QX11Info::setAppTime(unsigned long time)
{
if (!qApp)
return;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
typedef void (*SetAppTimeFunc)(QScreen *, xcb_timestamp_t);
QScreen* screen = QGuiApplication::primaryScreen();
SetAppTimeFunc func = reinterpret_cast<SetAppTimeFunc>(native->nativeResourceFunctionForScreen("setapptime"));
if (func)
func(screen, time);
else
qWarning("Internal error: QPA plugin doesn't implement setAppTime");
}
/*!
Sets the X11 user time as specified by \a time.
\sa appUserTime(), setAppTime()
*/
void QX11Info::setAppUserTime(unsigned long time)
{
if (!qApp)
return;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
typedef void (*SetAppUserTimeFunc)(QScreen *, xcb_timestamp_t);
QScreen* screen = QGuiApplication::primaryScreen();
SetAppUserTimeFunc func = reinterpret_cast<SetAppUserTimeFunc>(native->nativeResourceFunctionForScreen("setappusertime"));
if (func)
func(screen, time);
else
qWarning("Internal error: QPA plugin doesn't implement setAppUserTime");
}
/*!
Returns the default display for the application.
\sa appScreen()
*/
Display *QX11Info::display()
{
if (!qApp)
return NULL;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
void *display = native->nativeResourceForScreen(QByteArray("display"), QGuiApplication::primaryScreen());
return reinterpret_cast<Display *>(display);
}
/*!
Returns the default XCB connection for the application.
\sa display()
*/
xcb_connection_t *QX11Info::connection()
{
if (!qApp)
return NULL;
QPlatformNativeInterface *native = qApp->platformNativeInterface();
void *connection = native->nativeResourceForWindow(QByteArray("connection"), 0);
return reinterpret_cast<xcb_connection_t *>(connection);
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/*
kleo/enum.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004 Klarlvdalens Datakonsult AB
Libkleopatra is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
Libkleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "enum.h"
#include <klocale.h>
#include <qstring.h>
#include <qstringlist.h>
static const struct {
Kleo::CryptoMessageFormat format;
const char * displayName;
const char * configName;
} cryptoMessageFormats[] = {
{ Kleo::InlineOpenPGPFormat,
I18N_NOOP("Inline OpenPGP (deprecated)"),
"inline openpgp" },
{ Kleo::OpenPGPMIMEFormat,
I18N_NOOP("OpenPGP/MIME"),
"openpgp/mime" },
{ Kleo::SMIMEFormat,
I18N_NOOP("S/MIME"),
"s/mime" },
{ Kleo::SMIMEOpaqueFormat,
I18N_NOOP("S/MIME Opaque"),
"s/mime opaque" },
};
static const unsigned int numCryptoMessageFormats
= sizeof cryptoMessageFormats / sizeof *cryptoMessageFormats ;
const char * Kleo::cryptoMessageFormatToString( Kleo::CryptoMessageFormat f ) {
if ( f == AutoFormat )
return "auto";
for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )
if ( f == cryptoMessageFormats[i].format )
return cryptoMessageFormats[i].configName;
return 0;
}
QStringList Kleo::cryptoMessageFormatsToStringList( unsigned int f ) {
QStringList result;
for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )
if ( f & cryptoMessageFormats[i].format )
result.push_back( cryptoMessageFormats[i].configName );
return result;
}
QString Kleo::cryptoMessageFormatToLabel( Kleo::CryptoMessageFormat f ) {
if ( f == AutoFormat )
return i18n("Any");
for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )
if ( f == cryptoMessageFormats[i].format )
return i18n( cryptoMessageFormats[i].displayName );
return QString::null;
}
Kleo::CryptoMessageFormat Kleo::stringToCryptoMessageFormat( const QString & s ) {
const QString t = s.lower();
for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )
if ( t == cryptoMessageFormats[i].configName )
return cryptoMessageFormats[i].format;
return AutoFormat;
}
unsigned int Kleo::stringListToCryptoMessageFormats( const QStringList & sl ) {
unsigned int result = 0;
for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it )
result |= stringToCryptoMessageFormat( *it );
return result;
}
// For the config values used below, see also kaddressbook/editors/cryptowidget.cpp
const char* Kleo::encryptionPreferenceToString( EncryptionPreference pref )
{
switch( pref ) {
case UnknownPreference:
return 0;
case NeverEncrypt:
return "never";
case AlwaysEncrypt:
return "always";
case AlwaysEncryptIfPossible:
return "alwaysIfPossible";
case AlwaysAskForEncryption:
return "askAlways";
case AskWheneverPossible:
return "askWhenPossible";
}
return 0; // keep the compiler happy
}
Kleo::EncryptionPreference Kleo::stringToEncryptionPreference( const QString& str )
{
if ( str == "never" )
return NeverEncrypt;
if ( str == "always" )
return AlwaysEncrypt;
if ( str == "alwaysIfPossible" )
return AlwaysEncryptIfPossible;
if ( str == "askAlways" )
return AlwaysAskForEncryption;
if ( str == "askWhenPossible" )
return AskWheneverPossible;
return UnknownPreference;
}
QString Kleo::encryptionPreferenceToLabel( EncryptionPreference pref )
{
switch( pref ) {
case NeverEncrypt:
return i18n( "Never Encrypt" );
case AlwaysEncrypt:
return i18n( "Always Encrypt" );
case AlwaysEncryptIfPossible:
return i18n( "Always Encrypt If Possible" );
case AlwaysAskForEncryption:
return i18n( "Ask" );
case AskWheneverPossible:
return i18n( "Ask Whenever Possible" );
default:
return i18n( "no specific preference", "<none>" );
}
}
const char* Kleo::signingPreferenceToString( SigningPreference pref )
{
switch( pref ) {
case UnknownSigningPreference:
return 0;
case NeverSign:
return "never";
case AlwaysSign:
return "always";
case AlwaysSignIfPossible:
return "alwaysIfPossible";
case AlwaysAskForSigning:
return "askAlways";
case AskSigningWheneverPossible:
return "askWhenPossible";
}
return 0; // keep the compiler happy
}
Kleo::SigningPreference Kleo::stringToSigningPreference( const QString& str )
{
if ( str == "never" )
return NeverSign;
if ( str == "always" )
return AlwaysSign;
if ( str == "alwaysIfPossible" )
return AlwaysSignIfPossible;
if ( str == "askAlways" )
return AlwaysAskForSigning;
if ( str == "askWhenPossible" )
return AskSigningWheneverPossible;
return UnknownSigningPreference;
}
QString Kleo::signingPreferenceToLabel( SigningPreference pref )
{
switch( pref ) {
case NeverSign:
return i18n( "Never Sign" );
case AlwaysSign:
return i18n( "Always Sign" );
case AlwaysSignIfPossible:
return i18n( "Always Sign If Possible" );
case AlwaysAskForSigning:
return i18n( "Ask" );
case AskSigningWheneverPossible:
return i18n( "Ask Whenever Possible" );
default:
return i18n( "no specific preference", "<none>" );
}
}
<commit_msg>CVS_SILENT wrong branch<commit_after>/*
kleo/enum.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004 Klarlvdalens Datakonsult AB
Libkleopatra is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
Libkleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "enum.h"
#include <klocale.h>
#include <qstring.h>
#include <qstringlist.h>
static const struct {
Kleo::CryptoMessageFormat format;
const char * displayName;
const char * configName;
} cryptoMessageFormats[] = {
{ Kleo::InlineOpenPGPFormat,
I18N_NOOP("Inline OpenPGP (deprecated)"),
"inline openpgp" },
{ Kleo::OpenPGPMIMEFormat,
I18N_NOOP("OpenPGP/MIME"),
"openpgp/mime" },
{ Kleo::SMIMEFormat,
I18N_NOOP("S/MIME"),
"s/mime" },
{ Kleo::SMIMEOpaqueFormat,
I18N_NOOP("S/MIME opaque"),
"s/mime opaque" },
};
static const unsigned int numCryptoMessageFormats
= sizeof cryptoMessageFormats / sizeof *cryptoMessageFormats ;
const char * Kleo::cryptoMessageFormatToString( Kleo::CryptoMessageFormat f ) {
if ( f == AutoFormat )
return "auto";
for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )
if ( f == cryptoMessageFormats[i].format )
return cryptoMessageFormats[i].configName;
return 0;
}
QStringList Kleo::cryptoMessageFormatsToStringList( unsigned int f ) {
QStringList result;
for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )
if ( f & cryptoMessageFormats[i].format )
result.push_back( cryptoMessageFormats[i].configName );
return result;
}
QString Kleo::cryptoMessageFormatToLabel( Kleo::CryptoMessageFormat f ) {
if ( f == AutoFormat )
return i18n("Any");
for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )
if ( f == cryptoMessageFormats[i].format )
return i18n( cryptoMessageFormats[i].displayName );
return QString::null;
}
Kleo::CryptoMessageFormat Kleo::stringToCryptoMessageFormat( const QString & s ) {
const QString t = s.lower();
for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )
if ( t == cryptoMessageFormats[i].configName )
return cryptoMessageFormats[i].format;
return AutoFormat;
}
unsigned int Kleo::stringListToCryptoMessageFormats( const QStringList & sl ) {
unsigned int result = 0;
for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it )
result |= stringToCryptoMessageFormat( *it );
return result;
}
// For the config values used below, see also kaddressbook/editors/cryptowidget.cpp
const char* Kleo::encryptionPreferenceToString( EncryptionPreference pref )
{
switch( pref ) {
case UnknownPreference:
return 0;
case NeverEncrypt:
return "never";
case AlwaysEncrypt:
return "always";
case AlwaysEncryptIfPossible:
return "alwaysIfPossible";
case AlwaysAskForEncryption:
return "askAlways";
case AskWheneverPossible:
return "askWhenPossible";
}
return 0; // keep the compiler happy
}
Kleo::EncryptionPreference Kleo::stringToEncryptionPreference( const QString& str )
{
if ( str == "never" )
return NeverEncrypt;
if ( str == "always" )
return AlwaysEncrypt;
if ( str == "alwaysIfPossible" )
return AlwaysEncryptIfPossible;
if ( str == "askAlways" )
return AlwaysAskForEncryption;
if ( str == "askWhenPossible" )
return AskWheneverPossible;
return UnknownPreference;
}
QString Kleo::encryptionPreferenceToLabel( EncryptionPreference pref )
{
switch( pref ) {
case NeverEncrypt:
return i18n( "Never Encrypt" );
case AlwaysEncrypt:
return i18n( "Always Encrypt" );
case AlwaysEncryptIfPossible:
return i18n( "Always Encrypt If Possible" );
case AlwaysAskForEncryption:
return i18n( "Ask" );
case AskWheneverPossible:
return i18n( "Ask Whenever Possible" );
default:
return i18n( "no specific preference", "<none>" );
}
}
const char* Kleo::signingPreferenceToString( SigningPreference pref )
{
switch( pref ) {
case UnknownSigningPreference:
return 0;
case NeverSign:
return "never";
case AlwaysSign:
return "always";
case AlwaysSignIfPossible:
return "alwaysIfPossible";
case AlwaysAskForSigning:
return "askAlways";
case AskSigningWheneverPossible:
return "askWhenPossible";
}
return 0; // keep the compiler happy
}
Kleo::SigningPreference Kleo::stringToSigningPreference( const QString& str )
{
if ( str == "never" )
return NeverSign;
if ( str == "always" )
return AlwaysSign;
if ( str == "alwaysIfPossible" )
return AlwaysSignIfPossible;
if ( str == "askAlways" )
return AlwaysAskForSigning;
if ( str == "askWhenPossible" )
return AskSigningWheneverPossible;
return UnknownSigningPreference;
}
QString Kleo::signingPreferenceToLabel( SigningPreference pref )
{
switch( pref ) {
case NeverSign:
return i18n( "Never Sign" );
case AlwaysSign:
return i18n( "Always Sign" );
case AlwaysSignIfPossible:
return i18n( "Always Sign If Possible" );
case AlwaysAskForSigning:
return i18n( "Ask" );
case AskSigningWheneverPossible:
return i18n( "Ask Whenever Possible" );
default:
return i18n( "no specific preference", "<none>" );
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_rsc.hxx"
/****************** I N C L U D E S **************************************/
// C and C++ Includes.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <rscflag.hxx>
/****************** C O D E **********************************************/
/****************** R s c F l a g ****************************************/
/*************************************************************************
|*
|* RscFlag::RscFlag()
|*
*************************************************************************/
RscFlag::RscFlag( Atom nId, sal_uInt32 nTypeId )
: RscConst( nId, nTypeId )
{}
/*************************************************************************
|*
|* RscFlag::Size()
|*
|* Beschreibung Die Groe�e der Instanzdaten richtet sich nach
|* der Anzahl der Flags
|*
*************************************************************************/
sal_uInt32 RscFlag::Size()
{
return( ALIGNED_SIZE( sizeof( RscFlagInst ) *
( 1 + (nEntries -1) / (sizeof( sal_uInt32 ) * 8) ) ) );
}
/*************************************************************************
|*
|* RscFlag::SetNotConst()
|*
*************************************************************************/
ERRTYPE RscFlag::SetNotConst( const RSCINST & rInst, Atom nConst )
{
sal_uInt32 i = 0, nFlag = 0;
if( nEntries != (i = GetConstPos( nConst )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
((RscFlagInst *)rInst.pData)[ i ].nFlags &= ~nFlag;
((RscFlagInst *)rInst.pData)[ i ].nDfltFlags &= ~nFlag;
return( ERR_OK );
};
return( ERR_RSCFLAG );
}
/*************************************************************************
|*
|* RscFlag::SetConst()
|*
*************************************************************************/
ERRTYPE RscFlag::SetConst( const RSCINST & rInst, Atom nConst, sal_Int32 /*nVal*/ )
{
sal_uInt32 i = 0, nFlag = 0;
if( nEntries != (i = GetConstPos( nConst )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
((RscFlagInst *)rInst.pData)[ i ].nFlags |= nFlag;
((RscFlagInst *)rInst.pData)[ i ].nDfltFlags &= ~nFlag;
return( ERR_OK );
};
return( ERR_RSCFLAG );
}
/*************************************************************************
|*
|* RscFlag::CreateBasic()
|*
*************************************************************************/
RSCINST RscFlag::CreateBasic( RSCINST * pInst )
{
RSCINST aInst;
if( !pInst ){
aInst.pClass = this;
aInst.pData = (CLASS_DATA) rtl_allocateMemory( Size() );
}
else
aInst = *pInst;
return( aInst );
}
/*************************************************************************
|*
|* RscFlag::Create()
|*
*************************************************************************/
RSCINST RscFlag::Create( RSCINST * pInst, const RSCINST & rDflt, sal_Bool bOwnClass )
{
RSCINST aInst = CreateBasic( pInst );
sal_uInt32 i = 0;
if( !bOwnClass && rDflt.IsInst() )
bOwnClass = rDflt.pClass->InHierarchy( this );
if( bOwnClass )
memmove( aInst.pData, rDflt.pData, Size() );
else
{
for( i = 0; i < Size() / sizeof( RscFlagInst ); i++ )
{
((RscFlagInst *)aInst.pData)[ i ].nFlags = 0;
((RscFlagInst *)aInst.pData)[ i ].nDfltFlags = 0xFFFFFFFF;
}
};
return( aInst );
}
/*************************************************************************
|*
|* RscFlag::CreateClient()
|*
*************************************************************************/
RSCINST RscFlag::CreateClient( RSCINST * pInst, const RSCINST & rDfltI,
sal_Bool bOwnClass, Atom nConstId )
{
RSCINST aInst = CreateBasic( pInst );
sal_uInt32 i = 0, nFlag = 0;
if( !bOwnClass && rDfltI.IsInst() )
bOwnClass = rDfltI.pClass->InHierarchy( this );
if( nEntries != (i = GetConstPos( nConstId )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
if( bOwnClass ){
((RscFlagInst *)aInst.pData)[ i ].nFlags &=
~nFlag | ((RscFlagInst *)rDfltI.pData)[ i ].nFlags;
((RscFlagInst *)aInst.pData)[ i ].nDfltFlags &=
~nFlag | ((RscFlagInst *)rDfltI.pData)[ i ].nDfltFlags;
}
else{
((RscFlagInst *)aInst.pData)[ i ].nFlags &= ~nFlag;
((RscFlagInst *)aInst.pData)[ i ].nDfltFlags |= nFlag;
}
}
return( aInst );
}
/*************************************************************************
|*
|* RscFlag::SetToDefault()
|*
*************************************************************************/
void RscFlag::SetToDefault( const RSCINST & rInst )
{
sal_uInt32 i = 0;
for( i = 0; i < Size() / sizeof( RscFlagInst ); i++ )
((RscFlagInst *)rInst.pData)[ i ].nDfltFlags = 0xFFFFFFFF;
}
/*************************************************************************
|*
|* RscFlag::IsDlft()
|*
*************************************************************************/
sal_Bool RscFlag::IsDefault( const RSCINST & rInst )
{
sal_uInt32 i = 0;
for( i = 0; i < Size() / sizeof( RscFlagInst ); i++ )
if( ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags != 0xFFFFFFFF )
return( sal_False );
return( sal_True );
}
sal_Bool RscFlag::IsDefault( const RSCINST & rInst, Atom nConstId )
{
sal_uInt32 i = 0, nFlag = 0;
if( nEntries != (i = GetConstPos( nConstId )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
if( ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags & nFlag )
return( sal_True );
else
return( sal_False );
};
return( sal_True );
}
/*************************************************************************
|*
|* RscFlag::IsValueDefault()
|*
*************************************************************************/
sal_Bool RscFlag::IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef,
Atom nConstId )
{
sal_uInt32 i = 0, nFlag = 0;
if( nEntries != (i = GetConstPos( nConstId )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
if( pDef ){
if( (((RscFlagInst *)rInst.pData)[ i ].nFlags & nFlag)
== (((RscFlagInst *)pDef)[ i ].nFlags & nFlag) )
{
return sal_True;
}
}
};
return sal_False;
}
sal_Bool RscFlag::IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef )
{
sal_uInt32 i = 0;
if( pDef ){
sal_uInt32 Flag = 0, nIndex = 0;
Flag = 1;
for( i = 0; i < nEntries; i++ ){
nIndex = i / (sizeof( sal_uInt32 ) * 8);
if( (((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag)
!= (((RscFlagInst *)pDef)[ nIndex ].nFlags & Flag) )
{
return sal_False;
}
Flag <<= 1;
if( !Flag )
Flag = 1;
};
}
else
return sal_False;
return sal_True;
}
/*************************************************************************
|*
|* RscFlag::IsSet()
|*
*************************************************************************/
sal_Bool RscFlag::IsSet( const RSCINST & rInst, Atom nConstId )
{
sal_uInt32 i = 0, nFlag = 0;
if( nEntries != (i = GetConstPos( nConstId )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
if( ((RscFlagInst *)rInst.pData)[ i ].nFlags & nFlag )
return( sal_True );
else
return( sal_False );
};
return( sal_True );
}
/*************************************************************************
|*
|* RscFlag::WriteSrc()
|*
*************************************************************************/
void RscFlag::WriteSrc( const RSCINST & rInst, FILE * fOutput,
RscTypCont *, sal_uInt32, const char * )
{
sal_uInt32 i = 0, Flag = 0, nIndex = 0;
sal_Bool bComma = sal_False;
Flag = 1;
for( i = 0; i < nEntries; i++ ){
nIndex = i / (sizeof( sal_uInt32 ) * 8);
if( !( ((RscFlagInst *)rInst.pData)[ nIndex ].nDfltFlags & Flag) ){
if( bComma )
fprintf( fOutput, ", " );
if( ((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag )
fprintf( fOutput, "%s", pHS->getString( pVarArray[ i ].nId ).getStr() );
else{
fprintf( fOutput, "not " );
fprintf( fOutput, "%s", pHS->getString( pVarArray[ i ].nId ).getStr() );
}
bComma = sal_True;
}
Flag <<= 1;
if( !Flag )
Flag = 1;
};
}
/*************************************************************************
|*
|* RscFlag::WriteRc()
|*
*************************************************************************/
ERRTYPE RscFlag::WriteRc( const RSCINST & rInst, RscWriteRc & aMem,
RscTypCont *, sal_uInt32, sal_Bool )
{
sal_Int32 lVal = 0;
sal_uInt32 i = 0, Flag = 0, nIndex = 0;
Flag = 1;
for( i = 0; i < nEntries; i++ ){
nIndex = i / (sizeof( sal_uInt32 ) * 8);
if( ((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag )
lVal |= pVarArray[ i ].lValue;
Flag <<= 1;
if( !Flag )
Flag = 1;
};
aMem.Put( (sal_Int32)lVal );
return( ERR_OK );
}
/*************************************************************************
|*
|* RscClient::RscClient()
|*
*************************************************************************/
RscClient::RscClient( Atom nId, sal_uInt32 nTypeId, RscFlag * pClass,
Atom nConstantId )
: RscTop ( nId, nTypeId )
{
pRefClass = pClass;
nConstId = nConstantId;
}
/*************************************************************************
|*
|* RscClient::GetClassType()
|*
*************************************************************************/
RSCCLASS_TYPE RscClient::GetClassType() const
{
return RSCCLASS_BOOL;
}
/*************************************************************************
|*
|* RscClient::WriteSrc()
|*
*************************************************************************/
void RscClient::WriteSrc( const RSCINST & rInst, FILE * fOutput,
RscTypCont *, sal_uInt32, const char * )
{
if( pRefClass->IsSet( rInst, nConstId ) )
fprintf( fOutput, "TRUE" );
else
fprintf( fOutput, "FALSE" );
}
/*************************************************************************
|*
|* RscClient::Create()
|*
*************************************************************************/
RSCINST RscClient::Create( RSCINST * pInst, const RSCINST & rDflt,
sal_Bool bOwnClass )
{
RSCINST aTmpI, aDfltI;
if( pInst ){
aTmpI.pClass = pRefClass;
aTmpI.pData = pInst->pData;
}
if( !bOwnClass && rDflt.IsInst() ){
bOwnClass = rDflt.pClass->InHierarchy( this );
if( bOwnClass ){
aDfltI.pClass = pRefClass;
aDfltI.pData = rDflt.pData;
}
}
if( pInst )
aTmpI = pRefClass->CreateClient( &aTmpI, aDfltI,
bOwnClass, nConstId );
else
aTmpI = pRefClass->CreateClient( NULL, aDfltI,
bOwnClass, nConstId );
aTmpI.pClass = this;
return( aTmpI );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppcheck: reduce scope of var in rsc rscflag.cxx<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_rsc.hxx"
/****************** I N C L U D E S **************************************/
// C and C++ Includes.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <rscflag.hxx>
/****************** C O D E **********************************************/
/****************** R s c F l a g ****************************************/
/*************************************************************************
|*
|* RscFlag::RscFlag()
|*
*************************************************************************/
RscFlag::RscFlag( Atom nId, sal_uInt32 nTypeId )
: RscConst( nId, nTypeId )
{}
/*************************************************************************
|*
|* RscFlag::Size()
|*
|* Beschreibung Die Groe�e der Instanzdaten richtet sich nach
|* der Anzahl der Flags
|*
*************************************************************************/
sal_uInt32 RscFlag::Size()
{
return( ALIGNED_SIZE( sizeof( RscFlagInst ) *
( 1 + (nEntries -1) / (sizeof( sal_uInt32 ) * 8) ) ) );
}
/*************************************************************************
|*
|* RscFlag::SetNotConst()
|*
*************************************************************************/
ERRTYPE RscFlag::SetNotConst( const RSCINST & rInst, Atom nConst )
{
sal_uInt32 i = 0;
if( nEntries != (i = GetConstPos( nConst )) ){
sal_uInt32 nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
((RscFlagInst *)rInst.pData)[ i ].nFlags &= ~nFlag;
((RscFlagInst *)rInst.pData)[ i ].nDfltFlags &= ~nFlag;
return( ERR_OK );
};
return( ERR_RSCFLAG );
}
/*************************************************************************
|*
|* RscFlag::SetConst()
|*
*************************************************************************/
ERRTYPE RscFlag::SetConst( const RSCINST & rInst, Atom nConst, sal_Int32 /*nVal*/ )
{
sal_uInt32 i = 0;
if( nEntries != (i = GetConstPos( nConst )) ){
sal_uInt32 nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
((RscFlagInst *)rInst.pData)[ i ].nFlags |= nFlag;
((RscFlagInst *)rInst.pData)[ i ].nDfltFlags &= ~nFlag;
return( ERR_OK );
};
return( ERR_RSCFLAG );
}
/*************************************************************************
|*
|* RscFlag::CreateBasic()
|*
*************************************************************************/
RSCINST RscFlag::CreateBasic( RSCINST * pInst )
{
RSCINST aInst;
if( !pInst ){
aInst.pClass = this;
aInst.pData = (CLASS_DATA) rtl_allocateMemory( Size() );
}
else
aInst = *pInst;
return( aInst );
}
/*************************************************************************
|*
|* RscFlag::Create()
|*
*************************************************************************/
RSCINST RscFlag::Create( RSCINST * pInst, const RSCINST & rDflt, sal_Bool bOwnClass )
{
RSCINST aInst = CreateBasic( pInst );
if( !bOwnClass && rDflt.IsInst() )
bOwnClass = rDflt.pClass->InHierarchy( this );
if( bOwnClass )
memmove( aInst.pData, rDflt.pData, Size() );
else
{
for( sal_uInt32 i = 0; i < Size() / sizeof( RscFlagInst ); i++ )
{
((RscFlagInst *)aInst.pData)[ i ].nFlags = 0;
((RscFlagInst *)aInst.pData)[ i ].nDfltFlags = 0xFFFFFFFF;
}
};
return( aInst );
}
/*************************************************************************
|*
|* RscFlag::CreateClient()
|*
*************************************************************************/
RSCINST RscFlag::CreateClient( RSCINST * pInst, const RSCINST & rDfltI,
sal_Bool bOwnClass, Atom nConstId )
{
RSCINST aInst = CreateBasic( pInst );
sal_uInt32 i = 0;
if( !bOwnClass && rDfltI.IsInst() )
bOwnClass = rDfltI.pClass->InHierarchy( this );
if( nEntries != (i = GetConstPos( nConstId )) )
{
sal_uInt32 nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
if( bOwnClass ){
((RscFlagInst *)aInst.pData)[ i ].nFlags &=
~nFlag | ((RscFlagInst *)rDfltI.pData)[ i ].nFlags;
((RscFlagInst *)aInst.pData)[ i ].nDfltFlags &=
~nFlag | ((RscFlagInst *)rDfltI.pData)[ i ].nDfltFlags;
}
else{
((RscFlagInst *)aInst.pData)[ i ].nFlags &= ~nFlag;
((RscFlagInst *)aInst.pData)[ i ].nDfltFlags |= nFlag;
}
}
return( aInst );
}
/*************************************************************************
|*
|* RscFlag::SetToDefault()
|*
*************************************************************************/
void RscFlag::SetToDefault( const RSCINST & rInst )
{
sal_uInt32 i = 0;
for( i = 0; i < Size() / sizeof( RscFlagInst ); i++ )
((RscFlagInst *)rInst.pData)[ i ].nDfltFlags = 0xFFFFFFFF;
}
/*************************************************************************
|*
|* RscFlag::IsDlft()
|*
*************************************************************************/
sal_Bool RscFlag::IsDefault( const RSCINST & rInst )
{
sal_uInt32 i = 0;
for( i = 0; i < Size() / sizeof( RscFlagInst ); i++ )
if( ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags != 0xFFFFFFFF )
return( sal_False );
return( sal_True );
}
sal_Bool RscFlag::IsDefault( const RSCINST & rInst, Atom nConstId )
{
sal_uInt32 i = 0, nFlag = 0;
if( nEntries != (i = GetConstPos( nConstId )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
if( ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags & nFlag )
return( sal_True );
else
return( sal_False );
};
return( sal_True );
}
/*************************************************************************
|*
|* RscFlag::IsValueDefault()
|*
*************************************************************************/
sal_Bool RscFlag::IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef,
Atom nConstId )
{
sal_uInt32 i = 0, nFlag = 0;
if( nEntries != (i = GetConstPos( nConstId )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
if( pDef ){
if( (((RscFlagInst *)rInst.pData)[ i ].nFlags & nFlag)
== (((RscFlagInst *)pDef)[ i ].nFlags & nFlag) )
{
return sal_True;
}
}
};
return sal_False;
}
sal_Bool RscFlag::IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef )
{
if( pDef ){
sal_uInt32 Flag = 0, nIndex = 0;
Flag = 1;
for( sal_uInt32 i = 0; i < nEntries; i++ ){
nIndex = i / (sizeof( sal_uInt32 ) * 8);
if( (((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag)
!= (((RscFlagInst *)pDef)[ nIndex ].nFlags & Flag) )
{
return sal_False;
}
Flag <<= 1;
if( !Flag )
Flag = 1;
};
}
else
return sal_False;
return sal_True;
}
/*************************************************************************
|*
|* RscFlag::IsSet()
|*
*************************************************************************/
sal_Bool RscFlag::IsSet( const RSCINST & rInst, Atom nConstId )
{
sal_uInt32 i = 0, nFlag = 0;
if( nEntries != (i = GetConstPos( nConstId )) ){
nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );
i = i / (sizeof( sal_uInt32 ) * 8);
if( ((RscFlagInst *)rInst.pData)[ i ].nFlags & nFlag )
return( sal_True );
else
return( sal_False );
};
return( sal_True );
}
/*************************************************************************
|*
|* RscFlag::WriteSrc()
|*
*************************************************************************/
void RscFlag::WriteSrc( const RSCINST & rInst, FILE * fOutput,
RscTypCont *, sal_uInt32, const char * )
{
sal_uInt32 i = 0, Flag = 0, nIndex = 0;
sal_Bool bComma = sal_False;
Flag = 1;
for( i = 0; i < nEntries; i++ ){
nIndex = i / (sizeof( sal_uInt32 ) * 8);
if( !( ((RscFlagInst *)rInst.pData)[ nIndex ].nDfltFlags & Flag) ){
if( bComma )
fprintf( fOutput, ", " );
if( ((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag )
fprintf( fOutput, "%s", pHS->getString( pVarArray[ i ].nId ).getStr() );
else{
fprintf( fOutput, "not " );
fprintf( fOutput, "%s", pHS->getString( pVarArray[ i ].nId ).getStr() );
}
bComma = sal_True;
}
Flag <<= 1;
if( !Flag )
Flag = 1;
};
}
/*************************************************************************
|*
|* RscFlag::WriteRc()
|*
*************************************************************************/
ERRTYPE RscFlag::WriteRc( const RSCINST & rInst, RscWriteRc & aMem,
RscTypCont *, sal_uInt32, sal_Bool )
{
sal_Int32 lVal = 0;
sal_uInt32 i = 0, Flag = 0, nIndex = 0;
Flag = 1;
for( i = 0; i < nEntries; i++ ){
nIndex = i / (sizeof( sal_uInt32 ) * 8);
if( ((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag )
lVal |= pVarArray[ i ].lValue;
Flag <<= 1;
if( !Flag )
Flag = 1;
};
aMem.Put( (sal_Int32)lVal );
return( ERR_OK );
}
/*************************************************************************
|*
|* RscClient::RscClient()
|*
*************************************************************************/
RscClient::RscClient( Atom nId, sal_uInt32 nTypeId, RscFlag * pClass,
Atom nConstantId )
: RscTop ( nId, nTypeId )
{
pRefClass = pClass;
nConstId = nConstantId;
}
/*************************************************************************
|*
|* RscClient::GetClassType()
|*
*************************************************************************/
RSCCLASS_TYPE RscClient::GetClassType() const
{
return RSCCLASS_BOOL;
}
/*************************************************************************
|*
|* RscClient::WriteSrc()
|*
*************************************************************************/
void RscClient::WriteSrc( const RSCINST & rInst, FILE * fOutput,
RscTypCont *, sal_uInt32, const char * )
{
if( pRefClass->IsSet( rInst, nConstId ) )
fprintf( fOutput, "TRUE" );
else
fprintf( fOutput, "FALSE" );
}
/*************************************************************************
|*
|* RscClient::Create()
|*
*************************************************************************/
RSCINST RscClient::Create( RSCINST * pInst, const RSCINST & rDflt,
sal_Bool bOwnClass )
{
RSCINST aTmpI, aDfltI;
if( pInst ){
aTmpI.pClass = pRefClass;
aTmpI.pData = pInst->pData;
}
if( !bOwnClass && rDflt.IsInst() ){
bOwnClass = rDflt.pClass->InHierarchy( this );
if( bOwnClass ){
aDfltI.pClass = pRefClass;
aDfltI.pData = rDflt.pData;
}
}
if( pInst )
aTmpI = pRefClass->CreateClient( &aTmpI, aDfltI,
bOwnClass, nConstId );
else
aTmpI = pRefClass->CreateClient( NULL, aDfltI,
bOwnClass, nConstId );
aTmpI.pClass = this;
return( aTmpI );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2003 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.9 2004/01/29 11:48:46 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.8 2003/12/17 00:18:35 cargilld
* Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
*
* Revision 1.7 2003/10/29 16:18:41 peiyongz
* Implement serialization/deserialization
*
* Revision 1.6 2003/10/09 13:49:30 neilg
* make StringPool functions virtual so that we can implement a synchronized version of StringPool for thread-safe updates.
*
* Revision 1.5 2003/05/18 14:02:05 knoaman
* Memory manager implementation: pass per instance manager.
*
* Revision 1.4 2003/05/16 06:01:52 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.3 2003/05/15 19:07:45 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.2 2002/11/04 15:22:04 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:22:12 peiyongz
* sane_include
*
* Revision 1.6 2001/10/22 15:43:35 tng
* [Bug 3361] "String pool id was not legal" error in Attributes::getURI().
*
* Revision 1.5 2000/07/07 22:16:51 jpolast
* remove old put(value) function. use put(key,value) instead.
*
* Revision 1.4 2000/05/15 22:31:20 andyh
* Replace #include<memory.h> with <string.h> everywhere.
*
* Revision 1.3 2000/03/02 19:54:46 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.2 2000/02/06 07:48:04 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:05:10 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:14 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/StringPool.hpp>
#include <assert.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// StringPool::PoolElem: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLStringPool::PoolElem::PoolElem( const XMLCh* const string
, const unsigned int id
, MemoryManager* const manager) :
fId(id)
, fString(0)
, fMemoryManager(manager)
{
fString = XMLString::replicate(string, fMemoryManager);
}
XMLStringPool::PoolElem::~PoolElem()
{
fMemoryManager->deallocate(fString); //delete [] fString;
}
// ---------------------------------------------------------------------------
// StringPool::PoolElem: Public methods
// ---------------------------------------------------------------------------
void
XMLStringPool::PoolElem::reset(const XMLCh* const string, const unsigned int id)
{
fId = id;
fMemoryManager->deallocate(fString);//delete [] fString;
fString = XMLString::replicate(string, fMemoryManager);
}
// ---------------------------------------------------------------------------
// XMLStringPool: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLStringPool::XMLStringPool(const unsigned int modulus,
MemoryManager* const manager) :
fMemoryManager(manager)
, fIdMap(0)
, fHashTable(0)
, fMapCapacity(64)
, fCurId(1)
{
// Create the hash table, passing it the modulus
fHashTable = new (fMemoryManager) RefHashTableOf<PoolElem>(modulus, fMemoryManager);
// Do an initial allocation of the id map and zero it all out
fIdMap = (PoolElem**) fMemoryManager->allocate
(
fMapCapacity * sizeof(PoolElem*)
); //new PoolElem*[fMapCapacity];
memset(fIdMap, 0, sizeof(PoolElem*) * fMapCapacity);
}
XMLStringPool::~XMLStringPool()
{
delete fHashTable;
fMemoryManager->deallocate(fIdMap); //delete [] fIdMap;
}
// ---------------------------------------------------------------------------
// XMLStringPool: Pool management methods
// ---------------------------------------------------------------------------
unsigned int XMLStringPool::addOrFind(const XMLCh* const newString)
{
PoolElem* elemToFind = fHashTable->get(newString);
if (elemToFind)
return elemToFind->fId;
return addNewEntry(newString);
}
bool XMLStringPool::exists(const XMLCh* const newString) const
{
return fHashTable->containsKey(newString);
}
bool XMLStringPool::exists(const unsigned int id) const
{
if (!id || (id >= fCurId))
return false;
return true;
}
void XMLStringPool::flushAll()
{
fCurId = 1;
fHashTable->removeAll();
}
unsigned int XMLStringPool::getId(const XMLCh* const toFind) const
{
PoolElem* elemToFind = fHashTable->get(toFind);
if (elemToFind)
return elemToFind->fId;
// Not found, so return zero, which is never a legal id
return 0;
}
const XMLCh* XMLStringPool::getValueForId(const unsigned int id) const
{
if (!id || (id >= fCurId))
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::StrPool_IllegalId, fMemoryManager);
// Just index the id map and return that element's string
return fIdMap[id]->fString;
}
unsigned int XMLStringPool::getStringCount() const
{
return fCurId-1;
}
// ---------------------------------------------------------------------------
// XMLStringPool: Private helper methods
// ---------------------------------------------------------------------------
unsigned int XMLStringPool::addNewEntry(const XMLCh* const newString)
{
// See if we need to expand the id map
if (fCurId == fMapCapacity)
{
// Calculate the new capacity, create a temp new map, and zero it
const unsigned int newCap = (unsigned int)(fMapCapacity * 1.5);
PoolElem** newMap = (PoolElem**) fMemoryManager->allocate
(
newCap * sizeof(PoolElem*)
); //new PoolElem*[newCap];
memset(newMap, 0, sizeof(PoolElem*) * newCap);
//
// Copy over the old elements from the old map. They are just pointers
// so we can do it all at once.
//
memcpy(newMap, fIdMap, sizeof(PoolElem*) * fMapCapacity);
// Clean up the old map and store the new info
fMemoryManager->deallocate(fIdMap); //delete [] fIdMap;
fIdMap = newMap;
fMapCapacity = newCap;
}
//
// Ok, now create a new element and add it to the hash table. Then store
// this new element in the id map at the current id index, then bump the
// id index.
//
PoolElem* newElem = new (fMemoryManager) PoolElem(newString, fCurId, fMemoryManager);
fHashTable->put((void*)(newElem->getKey()), newElem);
fIdMap[fCurId] = newElem;
// Bump the current id and return the id of the new elem we just added
fCurId++;
return newElem->fId;
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(XMLStringPool)
void XMLStringPool::serialize(XSerializeEngine& serEng)
{
/***
* Since we are pretty sure that fIdMap and fHashTable is
* not shared by any other object, therefore there is no owned/referenced
* issue. Thus we can serialize the raw data only, rather than serializing
* both fIdMap and fHashTable.
*
* And we can rebuild the fIdMap and fHashTable out of the raw data during
* deserialization.
*
***/
if (serEng.isStoring())
{
serEng<<fCurId;
for (unsigned int index = 1; index < fCurId; index++)
{
const XMLCh* stringData = getValueForId(index);
serEng.writeString(stringData);
}
}
else
{
unsigned int mapSize;
serEng>>mapSize;
assert(1 == fCurId); //make sure empty
for (unsigned int index = 1; index < mapSize; index++)
{
XMLCh* stringData;
serEng.readString(stringData);
addNewEntry(stringData);
}
}
}
XMLStringPool::XMLStringPool(MemoryManager* const manager) :
fMemoryManager(manager)
, fIdMap(0)
, fHashTable(0)
, fMapCapacity(64)
, fCurId(1)
{
// Create the hash table, passing it the modulus
fHashTable = new (fMemoryManager) RefHashTableOf<PoolElem>(109, fMemoryManager);
// Do an initial allocation of the id map and zero it all out
fIdMap = (PoolElem**) fMemoryManager->allocate
(
fMapCapacity * sizeof(PoolElem*)
); //new PoolElem*[fMapCapacity];
memset(fIdMap, 0, sizeof(PoolElem*) * fMapCapacity);
}
XERCES_CPP_NAMESPACE_END
<commit_msg>eliminate leakage<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2003 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.10 2004/03/02 23:21:37 peiyongz
* eliminate leakage
*
* Revision 1.9 2004/01/29 11:48:46 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.8 2003/12/17 00:18:35 cargilld
* Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
*
* Revision 1.7 2003/10/29 16:18:41 peiyongz
* Implement serialization/deserialization
*
* Revision 1.6 2003/10/09 13:49:30 neilg
* make StringPool functions virtual so that we can implement a synchronized version of StringPool for thread-safe updates.
*
* Revision 1.5 2003/05/18 14:02:05 knoaman
* Memory manager implementation: pass per instance manager.
*
* Revision 1.4 2003/05/16 06:01:52 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.3 2003/05/15 19:07:45 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.2 2002/11/04 15:22:04 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:22:12 peiyongz
* sane_include
*
* Revision 1.6 2001/10/22 15:43:35 tng
* [Bug 3361] "String pool id was not legal" error in Attributes::getURI().
*
* Revision 1.5 2000/07/07 22:16:51 jpolast
* remove old put(value) function. use put(key,value) instead.
*
* Revision 1.4 2000/05/15 22:31:20 andyh
* Replace #include<memory.h> with <string.h> everywhere.
*
* Revision 1.3 2000/03/02 19:54:46 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.2 2000/02/06 07:48:04 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:05:10 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:14 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/StringPool.hpp>
#include <assert.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// StringPool::PoolElem: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLStringPool::PoolElem::PoolElem( const XMLCh* const string
, const unsigned int id
, MemoryManager* const manager) :
fId(id)
, fString(0)
, fMemoryManager(manager)
{
fString = XMLString::replicate(string, fMemoryManager);
}
XMLStringPool::PoolElem::~PoolElem()
{
fMemoryManager->deallocate(fString); //delete [] fString;
}
// ---------------------------------------------------------------------------
// StringPool::PoolElem: Public methods
// ---------------------------------------------------------------------------
void
XMLStringPool::PoolElem::reset(const XMLCh* const string, const unsigned int id)
{
fId = id;
fMemoryManager->deallocate(fString);//delete [] fString;
fString = XMLString::replicate(string, fMemoryManager);
}
// ---------------------------------------------------------------------------
// XMLStringPool: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLStringPool::XMLStringPool(const unsigned int modulus,
MemoryManager* const manager) :
fMemoryManager(manager)
, fIdMap(0)
, fHashTable(0)
, fMapCapacity(64)
, fCurId(1)
{
// Create the hash table, passing it the modulus
fHashTable = new (fMemoryManager) RefHashTableOf<PoolElem>(modulus, fMemoryManager);
// Do an initial allocation of the id map and zero it all out
fIdMap = (PoolElem**) fMemoryManager->allocate
(
fMapCapacity * sizeof(PoolElem*)
); //new PoolElem*[fMapCapacity];
memset(fIdMap, 0, sizeof(PoolElem*) * fMapCapacity);
}
XMLStringPool::~XMLStringPool()
{
delete fHashTable;
fMemoryManager->deallocate(fIdMap); //delete [] fIdMap;
}
// ---------------------------------------------------------------------------
// XMLStringPool: Pool management methods
// ---------------------------------------------------------------------------
unsigned int XMLStringPool::addOrFind(const XMLCh* const newString)
{
PoolElem* elemToFind = fHashTable->get(newString);
if (elemToFind)
return elemToFind->fId;
return addNewEntry(newString);
}
bool XMLStringPool::exists(const XMLCh* const newString) const
{
return fHashTable->containsKey(newString);
}
bool XMLStringPool::exists(const unsigned int id) const
{
if (!id || (id >= fCurId))
return false;
return true;
}
void XMLStringPool::flushAll()
{
fCurId = 1;
fHashTable->removeAll();
}
unsigned int XMLStringPool::getId(const XMLCh* const toFind) const
{
PoolElem* elemToFind = fHashTable->get(toFind);
if (elemToFind)
return elemToFind->fId;
// Not found, so return zero, which is never a legal id
return 0;
}
const XMLCh* XMLStringPool::getValueForId(const unsigned int id) const
{
if (!id || (id >= fCurId))
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::StrPool_IllegalId, fMemoryManager);
// Just index the id map and return that element's string
return fIdMap[id]->fString;
}
unsigned int XMLStringPool::getStringCount() const
{
return fCurId-1;
}
// ---------------------------------------------------------------------------
// XMLStringPool: Private helper methods
// ---------------------------------------------------------------------------
unsigned int XMLStringPool::addNewEntry(const XMLCh* const newString)
{
// See if we need to expand the id map
if (fCurId == fMapCapacity)
{
// Calculate the new capacity, create a temp new map, and zero it
const unsigned int newCap = (unsigned int)(fMapCapacity * 1.5);
PoolElem** newMap = (PoolElem**) fMemoryManager->allocate
(
newCap * sizeof(PoolElem*)
); //new PoolElem*[newCap];
memset(newMap, 0, sizeof(PoolElem*) * newCap);
//
// Copy over the old elements from the old map. They are just pointers
// so we can do it all at once.
//
memcpy(newMap, fIdMap, sizeof(PoolElem*) * fMapCapacity);
// Clean up the old map and store the new info
fMemoryManager->deallocate(fIdMap); //delete [] fIdMap;
fIdMap = newMap;
fMapCapacity = newCap;
}
//
// Ok, now create a new element and add it to the hash table. Then store
// this new element in the id map at the current id index, then bump the
// id index.
//
PoolElem* newElem = new (fMemoryManager) PoolElem(newString, fCurId, fMemoryManager);
fHashTable->put((void*)(newElem->getKey()), newElem);
fIdMap[fCurId] = newElem;
// Bump the current id and return the id of the new elem we just added
fCurId++;
return newElem->fId;
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(XMLStringPool)
void XMLStringPool::serialize(XSerializeEngine& serEng)
{
/***
* Since we are pretty sure that fIdMap and fHashTable is
* not shared by any other object, therefore there is no owned/referenced
* issue. Thus we can serialize the raw data only, rather than serializing
* both fIdMap and fHashTable.
*
* And we can rebuild the fIdMap and fHashTable out of the raw data during
* deserialization.
*
***/
if (serEng.isStoring())
{
serEng<<fCurId;
for (unsigned int index = 1; index < fCurId; index++)
{
const XMLCh* stringData = getValueForId(index);
serEng.writeString(stringData);
}
}
else
{
unsigned int mapSize;
serEng>>mapSize;
assert(1 == fCurId); //make sure empty
for (unsigned int index = 1; index < mapSize; index++)
{
XMLCh* stringData;
serEng.readString(stringData);
addNewEntry(stringData);
//we got to deallocate this string
//since stringpool will duplicate this string in the PoolElem and own that copy
fMemoryManager->deallocate(stringData);
}
}
}
XMLStringPool::XMLStringPool(MemoryManager* const manager) :
fMemoryManager(manager)
, fIdMap(0)
, fHashTable(0)
, fMapCapacity(64)
, fCurId(1)
{
// Create the hash table, passing it the modulus
fHashTable = new (fMemoryManager) RefHashTableOf<PoolElem>(109, fMemoryManager);
// Do an initial allocation of the id map and zero it all out
fIdMap = (PoolElem**) fMemoryManager->allocate
(
fMapCapacity * sizeof(PoolElem*)
); //new PoolElem*[fMapCapacity];
memset(fIdMap, 0, sizeof(PoolElem*) * fMapCapacity);
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: KResultSetMetaData.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2005-12-19 16:51:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_
#define _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_
#ifndef _CONNECTIVITY_KAB_CONNECTION_HXX_
#include "KConnection.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VOS_REF_HXX_
#include <vos/ref.hxx>
#endif
namespace connectivity
{
namespace kab
{
/*
** KabResultSetMetaData
*/
typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> KabResultSetMetaData_BASE;
class KabResultSetMetaData : public KabResultSetMetaData_BASE
{
KabConnection* m_pConnection;
::std::vector<sal_Int32> m_aKabFields; // for each selected column, contains the number
// of the corresponding KAddressBook field
protected:
virtual ~KabResultSetMetaData();
public:
KabResultSetMetaData(KabConnection* _pConnection);
// avoid ambigous cast error from the compiler
inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
{ return this; }
void setKabFields(
const ::vos::ORef<connectivity::OSQLColumns> &xColumns) throw(::com::sun::star::sdbc::SQLException);
inline sal_uInt32 fieldAtColumn(sal_Int32 columnIndex) const
{ return m_aKabFields[columnIndex - 1]; }
virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
}
#endif // _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.2.348); FILE MERGED 2008/04/01 15:08:53 thb 1.2.348.3: #i85898# Stripping all external header guards 2008/04/01 10:53:07 thb 1.2.348.2: #i85898# Stripping all external header guards 2008/03/28 15:23:44 rt 1.2.348.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: KResultSetMetaData.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_
#define _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_
#include "KConnection.hxx"
#include <connectivity/CommonTools.hxx>
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#include <cppuhelper/implbase1.hxx>
#include <vos/ref.hxx>
namespace connectivity
{
namespace kab
{
/*
** KabResultSetMetaData
*/
typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> KabResultSetMetaData_BASE;
class KabResultSetMetaData : public KabResultSetMetaData_BASE
{
KabConnection* m_pConnection;
::std::vector<sal_Int32> m_aKabFields; // for each selected column, contains the number
// of the corresponding KAddressBook field
protected:
virtual ~KabResultSetMetaData();
public:
KabResultSetMetaData(KabConnection* _pConnection);
// avoid ambigous cast error from the compiler
inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
{ return this; }
void setKabFields(
const ::vos::ORef<connectivity::OSQLColumns> &xColumns) throw(::com::sun::star::sdbc::SQLException);
inline sal_uInt32 fieldAtColumn(sal_Int32 columnIndex) const
{ return m_aKabFields[columnIndex - 1]; }
virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
}
#endif // _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_
<|endoftext|> |
<commit_before>AliAnalysisTaskSEDvsMultiplicity *AddTaskDvsMultiplicity(Int_t system=0,
Bool_t readMC=kFALSE,
Int_t MCOption=0,
Int_t pdgMeson=411,
TString finDirname="Loose",
TString filename="",
TString finAnObjname="AnalysisCuts",
TString estimatorFilename="",
Double_t refMult=9.26,
Bool_t subtractDau=kFALSE,
Bool_t NchWeight=kFALSE,
Int_t recoEstimator = AliAnalysisTaskSEDvsMultiplicity::kNtrk10,
Int_t MCEstimator = AliAnalysisTaskSEDvsMultiplicity::kEta10,
Bool_t isPPbData=kFALSE)
{
//
// Test macro for the AliAnalysisTaskSE for D+ candidates
//Invariant mass histogram and
// association with MC truth (using MC info in AOD)
// R. Bala, [email protected]
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskDvsMultiplicity", "No analysis manager to connect to.");
}
Bool_t stdcuts=kFALSE;
TFile* filecuts;
if( filename.EqualTo("") ) {
stdcuts=kTRUE;
} else {
filecuts=TFile::Open(filename.Data());
if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
AliFatal("Input file not found : check your cut object");
}
}
//Analysis Task
AliRDHFCuts *analysiscuts=0x0;
TString Name="";
if(pdgMeson==411){
if(stdcuts) {
analysiscuts = new AliRDHFCutsDplustoKpipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(finAnObjname);
Name="Dplus";
}else if(pdgMeson==421){
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(finAnObjname);
Name="D0";
}else if(pdgMeson==413){
if(stdcuts) {
analysiscuts = new AliRDHFCutsDStartoKpipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get(finAnObjname);
Name="DStar";
}
AliAnalysisTaskSEDvsMultiplicity *dMultTask = new AliAnalysisTaskSEDvsMultiplicity("dMultAnalysis",pdgMeson,analysiscuts,isPPbData);
dMultTask->SetReadMC(readMC);
dMultTask->SetDebugLevel(0);
dMultTask->SetUseBit(kTRUE);
dMultTask->SetDoImpactParameterHistos(kFALSE);
dMultTask->SetSubtractTrackletsFromDaughters(subtractDau);
dMultTask->SetMultiplicityEstimator(recoEstimator);
dMultTask->SetMCPrimariesEstimator(MCEstimator);
dMultTask->SetMCOption(MCOption);
if(isPPbData) dMultTask->SetIsPPbData();
if(NchWeight){
TH1F *hNchPrimaries = (TH1F*)filecuts->Get("hGenPrimaryParticlesInelGt0");
if(hNchPrimaries) {
dMultTask->UseMCNchWeight(true);
dMultTask->SetHistoNchWeight(hNchPrimaries);
} else {
AliFatal("Histogram for multiplicity weights not found");
return 0x0;
}
}
if(pdgMeson==421) {
dMultTask->SetMassLimits(1.5648,2.1648);
dMultTask->SetNMassBins(200);
}else if(pdgMeson==411)dMultTask->SetMassLimits(pdgMeson,0.2);
if(estimatorFilename.EqualTo("") ) {
printf("Estimator file not provided, multiplcity corrected histograms will not be filled\n");
} else{
TFile* fileEstimator=TFile::Open(estimatorFilename.Data());
if(!fileEstimator) {
AliFatal("File with multiplicity estimator not found\n");
return;
}
dMultTask->SetReferenceMultiplcity(refMult);
if (isPPbData) { //Only use two profiles if pPb
const Char_t* periodNames[2] = {"LHC13b", "LHC13c"};
TProfile* multEstimatorAvg[2];
for(Int_t ip=0; ip<2; ip++) {
multEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form("SPDmult10_%s",periodNames[ip]))->Clone(Form("SPDmult10_%s_clone",periodNames[ip])));
if (!multEstimatorAvg[ip]) {
AliFatal(Form("Multiplicity estimator for %s not found! Please check your estimator file",periodNames[ip]));
return;
}
}
dMultTask->SetMultiplVsZProfileLHC13b(multEstimatorAvg[0]);
dMultTask->SetMultiplVsZProfileLHC13c(multEstimatorAvg[1]);
}
else {
const Char_t* periodNames[4] = {"LHC10b", "LHC10c", "LHC10d", "LHC10e"};
TProfile* multEstimatorAvg[4];
for(Int_t ip=0; ip<4; ip++) {
multEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form("SPDmult10_%s",periodNames[ip]))->Clone(Form("SPDmult10_%s_clone",periodNames[ip])));
if (!multEstimatorAvg[ip]) {
AliFatal(Form("Multiplicity estimator for %s not found! Please check your estimator file",periodNames[ip]));
return;
}
}
dMultTask->SetMultiplVsZProfileLHC10b(multEstimatorAvg[0]);
dMultTask->SetMultiplVsZProfileLHC10c(multEstimatorAvg[1]);
dMultTask->SetMultiplVsZProfileLHC10d(multEstimatorAvg[2]);
dMultTask->SetMultiplVsZProfileLHC10e(multEstimatorAvg[3]);
}
}
mgr->AddTask(dMultTask);
// Create containers for input/output
TString inname = "cinput";
TString outname = "coutput";
TString cutsname = "coutputCuts";
TString normname = "coutputNorm";
TString profname = "coutputProf";
inname += Name.Data();
outname += Name.Data();
cutsname += Name.Data();
normname += Name.Data();
profname += Name.Data();
inname += finDirname.Data();
outname += finDirname.Data();
cutsname += finDirname.Data();
normname += finDirname.Data();
profname += finDirname.Data();
AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(),AliAnalysisManager::kInputContainer);
TString outputfile = AliAnalysisManager::GetCommonFileName();
outputfile += ":PWG3_D2H_DMult_";
outputfile += Name.Data();
outputfile += finDirname.Data();
AliAnalysisDataContainer *coutputCuts = mgr->CreateContainer(cutsname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
AliAnalysisDataContainer *coutput = mgr->CreateContainer(outname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
AliAnalysisDataContainer *coutputNorm = mgr->CreateContainer(normname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
AliAnalysisDataContainer *coutputProf = mgr->CreateContainer(profname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectInput(dMultTask,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(dMultTask,1,coutput);
mgr->ConnectOutput(dMultTask,2,coutputCuts);
mgr->ConnectOutput(dMultTask,3,coutputNorm);
mgr->ConnectOutput(dMultTask,4,coutputProf);
return dMultTask;
}
<commit_msg>Change weight tracklet histo for pPb<commit_after>AliAnalysisTaskSEDvsMultiplicity *AddTaskDvsMultiplicity(Int_t system=0,
Bool_t readMC=kFALSE,
Int_t MCOption=0,
Int_t pdgMeson=411,
TString finDirname="Loose",
TString filename="",
TString finAnObjname="AnalysisCuts",
TString estimatorFilename="",
Double_t refMult=9.26,
Bool_t subtractDau=kFALSE,
Bool_t NchWeight=kFALSE,
Int_t recoEstimator = AliAnalysisTaskSEDvsMultiplicity::kNtrk10,
Int_t MCEstimator = AliAnalysisTaskSEDvsMultiplicity::kEta10,
Bool_t isPPbData=kFALSE)
{
//
// Test macro for the AliAnalysisTaskSE for D+ candidates
//Invariant mass histogram and
// association with MC truth (using MC info in AOD)
// R. Bala, [email protected]
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskDvsMultiplicity", "No analysis manager to connect to.");
}
Bool_t stdcuts=kFALSE;
TFile* filecuts;
if( filename.EqualTo("") ) {
stdcuts=kTRUE;
} else {
filecuts=TFile::Open(filename.Data());
if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
AliFatal("Input file not found : check your cut object");
}
}
//Analysis Task
AliRDHFCuts *analysiscuts=0x0;
TString Name="";
if(pdgMeson==411){
if(stdcuts) {
analysiscuts = new AliRDHFCutsDplustoKpipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(finAnObjname);
Name="Dplus";
}else if(pdgMeson==421){
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(finAnObjname);
Name="D0";
}else if(pdgMeson==413){
if(stdcuts) {
analysiscuts = new AliRDHFCutsDStartoKpipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get(finAnObjname);
Name="DStar";
}
AliAnalysisTaskSEDvsMultiplicity *dMultTask = new AliAnalysisTaskSEDvsMultiplicity("dMultAnalysis",pdgMeson,analysiscuts,isPPbData);
dMultTask->SetReadMC(readMC);
dMultTask->SetDebugLevel(0);
dMultTask->SetUseBit(kTRUE);
dMultTask->SetDoImpactParameterHistos(kFALSE);
dMultTask->SetSubtractTrackletsFromDaughters(subtractDau);
dMultTask->SetMultiplicityEstimator(recoEstimator);
dMultTask->SetMCPrimariesEstimator(MCEstimator);
dMultTask->SetMCOption(MCOption);
if(isPPbData) dMultTask->SetIsPPbData();
if(NchWeight){
TH1F *hNchPrimaries = NULL;
if(isPPbData) hNchPrimaries = (TH1F*)filecuts->Get("hNtrUnCorrEvWithDWeight");
else hNchPrimaries = (TH1F*)filecuts->Get("hGenPrimaryParticlesInelGt0");
if(hNchPrimaries) {
dMultTask->UseMCNchWeight(true);
dMultTask->SetHistoNchWeight(hNchPrimaries);
} else {
AliFatal("Histogram for multiplicity weights not found");
return 0x0;
}
}
if(pdgMeson==421) {
dMultTask->SetMassLimits(1.5648,2.1648);
dMultTask->SetNMassBins(200);
}else if(pdgMeson==411)dMultTask->SetMassLimits(pdgMeson,0.2);
if(estimatorFilename.EqualTo("") ) {
printf("Estimator file not provided, multiplcity corrected histograms will not be filled\n");
} else{
TFile* fileEstimator=TFile::Open(estimatorFilename.Data());
if(!fileEstimator) {
AliFatal("File with multiplicity estimator not found\n");
return;
}
dMultTask->SetReferenceMultiplcity(refMult);
if (isPPbData) { //Only use two profiles if pPb
const Char_t* periodNames[2] = {"LHC13b", "LHC13c"};
TProfile* multEstimatorAvg[2];
for(Int_t ip=0; ip<2; ip++) {
multEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form("SPDmult10_%s",periodNames[ip]))->Clone(Form("SPDmult10_%s_clone",periodNames[ip])));
if (!multEstimatorAvg[ip]) {
AliFatal(Form("Multiplicity estimator for %s not found! Please check your estimator file",periodNames[ip]));
return;
}
}
dMultTask->SetMultiplVsZProfileLHC13b(multEstimatorAvg[0]);
dMultTask->SetMultiplVsZProfileLHC13c(multEstimatorAvg[1]);
}
else {
const Char_t* periodNames[4] = {"LHC10b", "LHC10c", "LHC10d", "LHC10e"};
TProfile* multEstimatorAvg[4];
for(Int_t ip=0; ip<4; ip++) {
multEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form("SPDmult10_%s",periodNames[ip]))->Clone(Form("SPDmult10_%s_clone",periodNames[ip])));
if (!multEstimatorAvg[ip]) {
AliFatal(Form("Multiplicity estimator for %s not found! Please check your estimator file",periodNames[ip]));
return;
}
}
dMultTask->SetMultiplVsZProfileLHC10b(multEstimatorAvg[0]);
dMultTask->SetMultiplVsZProfileLHC10c(multEstimatorAvg[1]);
dMultTask->SetMultiplVsZProfileLHC10d(multEstimatorAvg[2]);
dMultTask->SetMultiplVsZProfileLHC10e(multEstimatorAvg[3]);
}
}
mgr->AddTask(dMultTask);
// Create containers for input/output
TString inname = "cinput";
TString outname = "coutput";
TString cutsname = "coutputCuts";
TString normname = "coutputNorm";
TString profname = "coutputProf";
inname += Name.Data();
outname += Name.Data();
cutsname += Name.Data();
normname += Name.Data();
profname += Name.Data();
inname += finDirname.Data();
outname += finDirname.Data();
cutsname += finDirname.Data();
normname += finDirname.Data();
profname += finDirname.Data();
AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(),AliAnalysisManager::kInputContainer);
TString outputfile = AliAnalysisManager::GetCommonFileName();
outputfile += ":PWG3_D2H_DMult_";
outputfile += Name.Data();
outputfile += finDirname.Data();
AliAnalysisDataContainer *coutputCuts = mgr->CreateContainer(cutsname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
AliAnalysisDataContainer *coutput = mgr->CreateContainer(outname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
AliAnalysisDataContainer *coutputNorm = mgr->CreateContainer(normname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
AliAnalysisDataContainer *coutputProf = mgr->CreateContainer(profname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectInput(dMultTask,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(dMultTask,1,coutput);
mgr->ConnectOutput(dMultTask,2,coutputCuts);
mgr->ConnectOutput(dMultTask,3,coutputNorm);
mgr->ConnectOutput(dMultTask,4,coutputProf);
return dMultTask;
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : D2.cpp
* Author : Kazune Takahashi
* Created : 11/13/2019, 7:24:07 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <boost/rational.hpp>
using boost::rational;
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "0 1" << endl;
exit(0);
}
using Info = tuple<ll, ll>;
int main()
{
int N;
cin >> N;
vector<Info> V(N);
ll A_sum{0LL};
for (auto i = 0; i < N; i++)
{
ll A, B;
cin >> A >> B;
V[i] = Info(max(A, B), B);
A_sum += A;
}
sort(V.rbegin(), V.rend());
vector<ll> C_sum(N + 1);
C_sum[0] = 0;
for (auto i = 0; i < N; i++)
{
#if DEBUG == 1
cerr << "C_sum[" << i + 1 << " = " << C_sum[i + 1] << endl;
#endif
C_sum[i + 1] = C_sum[i] + get<0>(V[i]);
}
if (C_sum[N] == A_sum)
{
No();
}
rational<ll> ans{0, 1};
#if DEBUG == 1
cerr << "A_sum = " << A_sum << endl;
#endif
for (auto k = 0; k < N; k++)
{
ll B_k{get<1>(V[k])};
ll ok{N}, ng{-1};
ll tmp_sum{0};
bool included{false};
while (abs(ok - ng) > 1)
{
ll t{(ok + ng) / 2};
ll tmp{C_sum[t]};
if (k < t)
{
tmp -= B_k;
}
if (tmp + B_k >= A_sum)
{
ok = t;
included = k < t;
tmp_sum = tmp;
}
else
{
ng = t;
}
}
rational<ll> r{A_sum - tmp_sum, B_k};
#if DEBUG == 1
cerr << "k = " << k << ", B_k = " << B_k << ", tmp_sum = " << tmp_sum << ", r = " << r << endl;
#endif
ll M{included ? ok - 1 : ok};
#if DEBUG == 1
cerr << "ok = " << ok << ", included = " << included << ", M = " << M << ", r = " << r << endl;
#endif
rational<ll> tmp_ans = (N - M - r) / N;
#if DEBUG == 1
cerr << "tmp_ans = " << tmp_ans << endl;
#endif
if (r < 0)
{
continue;
}
ch_max(ans, tmp_ans);
}
cout << ans.numerator() << " " << ans.denominator() << endl;
}
<commit_msg>tried D2.cpp to 'D'<commit_after>#define DEBUG 1
/**
* File : D2.cpp
* Author : Kazune Takahashi
* Created : 11/13/2019, 7:24:07 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <boost/rational.hpp>
using boost::rational;
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "0 1" << endl;
exit(0);
}
using Info = tuple<ll, ll>;
int main()
{
int N;
cin >> N;
vector<Info> V(N);
ll A_sum{0LL};
for (auto i = 0; i < N; i++)
{
ll A, B;
cin >> A >> B;
V[i] = Info(max(A, B), B);
A_sum += A;
}
sort(V.rbegin(), V.rend());
vector<ll> C_sum(N + 1);
C_sum[0] = 0;
for (auto i = 0; i < N; i++)
{
C_sum[i + 1] = C_sum[i] + get<0>(V[i]);
#if DEBUG == 1
cerr << "C_sum[" << i + 1 << "] = " << C_sum[i + 1] << endl;
#endif
}
if (C_sum[N] == A_sum)
{
No();
}
rational<ll> ans{0, 1};
#if DEBUG == 1
cerr << "A_sum = " << A_sum << endl;
#endif
for (auto k = 0; k < N; k++)
{
ll B_k{get<1>(V[k])};
ll ok{N}, ng{-1};
ll tmp_sum{0};
bool included{false};
while (abs(ok - ng) > 1)
{
ll t{(ok + ng) / 2};
ll tmp{C_sum[t]};
if (k < t)
{
tmp -= B_k;
}
if (tmp + B_k >= A_sum)
{
ok = t;
included = k < t;
tmp_sum = tmp;
}
else
{
ng = t;
}
}
rational<ll> r{A_sum - tmp_sum, B_k};
#if DEBUG == 1
cerr << "k = " << k << ", B_k = " << B_k << ", tmp_sum = " << tmp_sum << ", r = " << r << endl;
#endif
ll M{included ? ok - 1 : ok};
#if DEBUG == 1
cerr << "ok = " << ok << ", included = " << included << ", M = " << M << ", r = " << r << endl;
#endif
rational<ll> tmp_ans = (N - M - r) / N;
#if DEBUG == 1
cerr << "tmp_ans = " << tmp_ans << endl;
#endif
if (r < 0)
{
continue;
}
ch_max(ans, tmp_ans);
}
cout << ans.numerator() << " " << ans.denominator() << endl;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include <exdisp.h>
#include <comdef.h>
#include "ControlEx.h"
class C360SafeFrameWnd : public CWindowWnd, public INotifyUI
{
public:
C360SafeFrameWnd() { };
LPCTSTR GetWindowClassName() const { return _T("UIMainFrame"); };
UINT GetClassStyle() const { return CS_DBLCLKS; };
void OnFinalMessage(HWND /*hWnd*/) { delete this; };
void Init() {
m_pCloseBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T("closebtn")));
m_pMaxBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T("maxbtn")));
m_pRestoreBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T("restorebtn")));
m_pMinBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T("minbtn")));
}
void OnPrepare() {
}
void Notify(TNotifyUI& msg)
{
if( msg.sType == _T("windowinit") ) OnPrepare();
else if( msg.sType == _T("click") ) {
if( msg.pSender == m_pCloseBtn ) {
PostQuitMessage(0);
return;
}
else if( msg.pSender == m_pMinBtn ) {
SendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0); return; }
else if( msg.pSender == m_pMaxBtn ) {
SendMessage(WM_SYSCOMMAND, SC_MAXIMIZE, 0); return; }
else if( msg.pSender == m_pRestoreBtn ) {
SendMessage(WM_SYSCOMMAND, SC_RESTORE, 0); return; }
}
else if(msg.sType==_T("selectchanged"))
{
CStdString name = msg.pSender->GetName();
CTabLayoutUI* pControl = static_cast<CTabLayoutUI*>(m_pm.FindControl(_T("switch")));
if(name==_T("examine"))
pControl->SelectItem(0);
else if(name==_T("trojan"))
pControl->SelectItem(1);
else if(name==_T("plugins"))
pControl->SelectItem(2);
else if(name==_T("vulnerability"))
pControl->SelectItem(3);
else if(name==_T("rubbish"))
pControl->SelectItem(4);
else if(name==_T("cleanup"))
pControl->SelectItem(5);
else if(name==_T("fix"))
pControl->SelectItem(6);
else if(name==_T("tool"))
pControl->SelectItem(7);
}
}
LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
styleValue &= ~WS_CAPTION;
::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
m_pm.Init(m_hWnd);
CDialogBuilder builder;
CDialogBuilderCallbackEx cb;
CControlUI* pRoot = builder.Create(_T("skin.xml"), (UINT)0, &cb, &m_pm);
ASSERT(pRoot && "Failed to parse XML");
m_pm.AttachDialog(pRoot);
m_pm.AddNotifier(this);
Init();
return 0;
}
LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
::PostQuitMessage(0L);
bHandled = FALSE;
return 0;
}
LRESULT OnNcActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if( ::IsIconic(*this) ) bHandled = FALSE;
return (wParam == 0) ? TRUE : FALSE;
}
LRESULT OnNcCalcSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
LRESULT OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
LRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
POINT pt; pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam);
::ScreenToClient(*this, &pt);
RECT rcClient;
::GetClientRect(*this, &rcClient);
// if( !::IsZoomed(*this) ) {
// RECT rcSizeBox = m_pm.GetSizeBox();
// if( pt.y < rcClient.top + rcSizeBox.top ) {
// if( pt.x < rcClient.left + rcSizeBox.left ) return HTTOPLEFT;
// if( pt.x > rcClient.right - rcSizeBox.right ) return HTTOPRIGHT;
// return HTTOP;
// }
// else if( pt.y > rcClient.bottom - rcSizeBox.bottom ) {
// if( pt.x < rcClient.left + rcSizeBox.left ) return HTBOTTOMLEFT;
// if( pt.x > rcClient.right - rcSizeBox.right ) return HTBOTTOMRIGHT;
// return HTBOTTOM;
// }
// if( pt.x < rcClient.left + rcSizeBox.left ) return HTLEFT;
// if( pt.x > rcClient.right - rcSizeBox.right ) return HTRIGHT;
// }
RECT rcCaption = m_pm.GetCaptionRect();
if( pt.x >= rcClient.left + rcCaption.left && pt.x < rcClient.right - rcCaption.right \
&& pt.y >= rcCaption.top && pt.y < rcCaption.bottom ) {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(pt));
if( pControl && _tcscmp(pControl->GetClass(), _T("ButtonUI")) != 0 &&
_tcscmp(pControl->GetClass(), _T("OptionUI")) != 0 &&
_tcscmp(pControl->GetClass(), _T("TextUI")) != 0 )
return HTCAPTION;
}
return HTCLIENT;
}
LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
SIZE szRoundCorner = m_pm.GetRoundCorner();
if( !::IsIconic(*this) && (szRoundCorner.cx != 0 || szRoundCorner.cy != 0) ) {
CRect rcWnd;
::GetWindowRect(*this, &rcWnd);
rcWnd.Offset(-rcWnd.left, -rcWnd.top);
rcWnd.right++; rcWnd.bottom++;
HRGN hRgn = ::CreateRoundRectRgn(rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom, szRoundCorner.cx, szRoundCorner.cy);
::SetWindowRgn(*this, hRgn, TRUE);
::DeleteObject(hRgn);
}
bHandled = FALSE;
return 0;
}
LRESULT OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
MONITORINFO oMonitor = {};
oMonitor.cbSize = sizeof(oMonitor);
::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTOPRIMARY), &oMonitor);
CRect rcWork = oMonitor.rcWork;
rcWork.Offset(-rcWork.left, -rcWork.top);
LPMINMAXINFO lpMMI = (LPMINMAXINFO) lParam;
lpMMI->ptMaxPosition.x = rcWork.left;
lpMMI->ptMaxPosition.y = rcWork.top;
lpMMI->ptMaxSize.x = rcWork.right;
lpMMI->ptMaxSize.y = rcWork.bottom;
bHandled = FALSE;
return 0;
}
LRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
// ʱյWM_NCDESTROYյwParamΪSC_CLOSEWM_SYSCOMMAND
if( wParam == SC_CLOSE ) {
::PostQuitMessage(0L);
bHandled = TRUE;
return 0;
}
BOOL bZoomed = ::IsZoomed(*this);
LRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);
if( ::IsZoomed(*this) != bZoomed ) {
if( !bZoomed ) {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("maxbtn")));
if( pControl ) pControl->SetVisible(false);
pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("restorebtn")));
if( pControl ) pControl->SetVisible(true);
}
else {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("maxbtn")));
if( pControl ) pControl->SetVisible(true);
pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("restorebtn")));
if( pControl ) pControl->SetVisible(false);
}
}
return lRes;
}
LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lRes = 0;
BOOL bHandled = TRUE;
switch( uMsg ) {
case WM_CREATE: lRes = OnCreate(uMsg, wParam, lParam, bHandled); break;
case WM_CLOSE: lRes = OnClose(uMsg, wParam, lParam, bHandled); break;
case WM_DESTROY: lRes = OnDestroy(uMsg, wParam, lParam, bHandled); break;
case WM_NCACTIVATE: lRes = OnNcActivate(uMsg, wParam, lParam, bHandled); break;
case WM_NCCALCSIZE: lRes = OnNcCalcSize(uMsg, wParam, lParam, bHandled); break;
case WM_NCPAINT: lRes = OnNcPaint(uMsg, wParam, lParam, bHandled); break;
case WM_NCHITTEST: lRes = OnNcHitTest(uMsg, wParam, lParam, bHandled); break;
case WM_SIZE: lRes = OnSize(uMsg, wParam, lParam, bHandled); break;
case WM_GETMINMAXINFO: lRes = OnGetMinMaxInfo(uMsg, wParam, lParam, bHandled); break;
case WM_SYSCOMMAND: lRes = OnSysCommand(uMsg, wParam, lParam, bHandled); break;
default:
bHandled = FALSE;
}
if( bHandled ) return lRes;
if( m_pm.MessageHandler(uMsg, wParam, lParam, lRes) ) return lRes;
return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}
public:
CPaintManagerUI m_pm;
private:
CButtonUI* m_pCloseBtn;
CButtonUI* m_pMaxBtn;
CButtonUI* m_pRestoreBtn;
CButtonUI* m_pMinBtn;
//...
};
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int nCmdShow)
{
CPaintManagerUI::SetInstance(hInstance);
CPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath() + _T("skin"));
CPaintManagerUI::SetResourceZip(_T("360SafeRes.zip"));
HRESULT Hr = ::CoInitialize(NULL);
if( FAILED(Hr) ) return 0;
C360SafeFrameWnd* pFrame = new C360SafeFrameWnd();
if( pFrame == NULL ) return 0;
pFrame->Create(NULL, _T("360ȫʿ"), UI_WNDSTYLE_FRAME, 0L, 0, 0, 800, 572);
pFrame->CenterWindow();
::ShowWindow(*pFrame, SW_SHOW);
CPaintManagerUI::MessageLoop();
::CoUninitialize();
return 0;
}<commit_msg>fix.<commit_after>#include "stdafx.h"
#include <exdisp.h>
#include <comdef.h>
#include "ControlEx.h"
class C360SafeFrameWnd : public CWindowWnd, public INotifyUI
{
public:
C360SafeFrameWnd() { };
LPCTSTR GetWindowClassName() const { return _T("UIMainFrame"); };
UINT GetClassStyle() const { return CS_DBLCLKS; };
void OnFinalMessage(HWND /*hWnd*/) { delete this; };
void Init() {
m_pCloseBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T("closebtn")));
m_pMaxBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T("maxbtn")));
m_pRestoreBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T("restorebtn")));
m_pMinBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T("minbtn")));
}
void OnPrepare() {
}
void Notify(TNotifyUI& msg)
{
if( msg.sType == _T("windowinit") ) OnPrepare();
else if( msg.sType == _T("click") ) {
if( msg.pSender == m_pCloseBtn ) {
PostMessage(WM_SYSCOMMAND, SC_CLOSE, 0); return; }
else if( msg.pSender == m_pMinBtn ) {
SendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0); return; }
else if( msg.pSender == m_pMaxBtn ) {
SendMessage(WM_SYSCOMMAND, SC_MAXIMIZE, 0); return; }
else if( msg.pSender == m_pRestoreBtn ) {
SendMessage(WM_SYSCOMMAND, SC_RESTORE, 0); return; }
}
else if(msg.sType==_T("selectchanged"))
{
CStdString name = msg.pSender->GetName();
CTabLayoutUI* pControl = static_cast<CTabLayoutUI*>(m_pm.FindControl(_T("switch")));
if(name==_T("examine"))
pControl->SelectItem(0);
else if(name==_T("trojan"))
pControl->SelectItem(1);
else if(name==_T("plugins"))
pControl->SelectItem(2);
else if(name==_T("vulnerability"))
pControl->SelectItem(3);
else if(name==_T("rubbish"))
pControl->SelectItem(4);
else if(name==_T("cleanup"))
pControl->SelectItem(5);
else if(name==_T("fix"))
pControl->SelectItem(6);
else if(name==_T("tool"))
pControl->SelectItem(7);
}
}
LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
styleValue &= ~WS_CAPTION;
::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
m_pm.Init(m_hWnd);
CDialogBuilder builder;
CDialogBuilderCallbackEx cb;
CControlUI* pRoot = builder.Create(_T("skin.xml"), (UINT)0, &cb, &m_pm);
ASSERT(pRoot && "Failed to parse XML");
m_pm.AttachDialog(pRoot);
m_pm.AddNotifier(this);
Init();
return 0;
}
LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
::PostQuitMessage(0L);
bHandled = FALSE;
return 0;
}
LRESULT OnNcActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if( ::IsIconic(*this) ) bHandled = FALSE;
return (wParam == 0) ? TRUE : FALSE;
}
LRESULT OnNcCalcSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
LRESULT OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
LRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
POINT pt; pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam);
::ScreenToClient(*this, &pt);
RECT rcClient;
::GetClientRect(*this, &rcClient);
// if( !::IsZoomed(*this) ) {
// RECT rcSizeBox = m_pm.GetSizeBox();
// if( pt.y < rcClient.top + rcSizeBox.top ) {
// if( pt.x < rcClient.left + rcSizeBox.left ) return HTTOPLEFT;
// if( pt.x > rcClient.right - rcSizeBox.right ) return HTTOPRIGHT;
// return HTTOP;
// }
// else if( pt.y > rcClient.bottom - rcSizeBox.bottom ) {
// if( pt.x < rcClient.left + rcSizeBox.left ) return HTBOTTOMLEFT;
// if( pt.x > rcClient.right - rcSizeBox.right ) return HTBOTTOMRIGHT;
// return HTBOTTOM;
// }
// if( pt.x < rcClient.left + rcSizeBox.left ) return HTLEFT;
// if( pt.x > rcClient.right - rcSizeBox.right ) return HTRIGHT;
// }
RECT rcCaption = m_pm.GetCaptionRect();
if( pt.x >= rcClient.left + rcCaption.left && pt.x < rcClient.right - rcCaption.right \
&& pt.y >= rcCaption.top && pt.y < rcCaption.bottom ) {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(pt));
if( pControl && _tcscmp(pControl->GetClass(), _T("ButtonUI")) != 0 &&
_tcscmp(pControl->GetClass(), _T("OptionUI")) != 0 &&
_tcscmp(pControl->GetClass(), _T("TextUI")) != 0 )
return HTCAPTION;
}
return HTCLIENT;
}
LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
SIZE szRoundCorner = m_pm.GetRoundCorner();
if( !::IsIconic(*this) && (szRoundCorner.cx != 0 || szRoundCorner.cy != 0) ) {
CRect rcWnd;
::GetWindowRect(*this, &rcWnd);
rcWnd.Offset(-rcWnd.left, -rcWnd.top);
rcWnd.right++; rcWnd.bottom++;
HRGN hRgn = ::CreateRoundRectRgn(rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom, szRoundCorner.cx, szRoundCorner.cy);
::SetWindowRgn(*this, hRgn, TRUE);
::DeleteObject(hRgn);
}
bHandled = FALSE;
return 0;
}
LRESULT OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
MONITORINFO oMonitor = {};
oMonitor.cbSize = sizeof(oMonitor);
::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTOPRIMARY), &oMonitor);
CRect rcWork = oMonitor.rcWork;
rcWork.Offset(-rcWork.left, -rcWork.top);
LPMINMAXINFO lpMMI = (LPMINMAXINFO) lParam;
lpMMI->ptMaxPosition.x = rcWork.left;
lpMMI->ptMaxPosition.y = rcWork.top;
lpMMI->ptMaxSize.x = rcWork.right;
lpMMI->ptMaxSize.y = rcWork.bottom;
bHandled = FALSE;
return 0;
}
LRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
BOOL bZoomed = ::IsZoomed(*this);
LRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);
if( ::IsZoomed(*this) != bZoomed ) {
if( !bZoomed ) {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("maxbtn")));
if( pControl ) pControl->SetVisible(false);
pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("restorebtn")));
if( pControl ) pControl->SetVisible(true);
}
else {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("maxbtn")));
if( pControl ) pControl->SetVisible(true);
pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("restorebtn")));
if( pControl ) pControl->SetVisible(false);
}
}
return lRes;
}
LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lRes = 0;
BOOL bHandled = TRUE;
switch( uMsg ) {
case WM_CREATE: lRes = OnCreate(uMsg, wParam, lParam, bHandled); break;
case WM_CLOSE: lRes = OnClose(uMsg, wParam, lParam, bHandled); break;
case WM_DESTROY: lRes = OnDestroy(uMsg, wParam, lParam, bHandled); break;
case WM_NCACTIVATE: lRes = OnNcActivate(uMsg, wParam, lParam, bHandled); break;
case WM_NCCALCSIZE: lRes = OnNcCalcSize(uMsg, wParam, lParam, bHandled); break;
case WM_NCPAINT: lRes = OnNcPaint(uMsg, wParam, lParam, bHandled); break;
case WM_NCHITTEST: lRes = OnNcHitTest(uMsg, wParam, lParam, bHandled); break;
case WM_SIZE: lRes = OnSize(uMsg, wParam, lParam, bHandled); break;
case WM_GETMINMAXINFO: lRes = OnGetMinMaxInfo(uMsg, wParam, lParam, bHandled); break;
case WM_SYSCOMMAND: lRes = OnSysCommand(uMsg, wParam, lParam, bHandled); break;
default:
bHandled = FALSE;
}
if( bHandled ) return lRes;
if( m_pm.MessageHandler(uMsg, wParam, lParam, lRes) ) return lRes;
return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}
public:
CPaintManagerUI m_pm;
private:
CButtonUI* m_pCloseBtn;
CButtonUI* m_pMaxBtn;
CButtonUI* m_pRestoreBtn;
CButtonUI* m_pMinBtn;
//...
};
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int nCmdShow)
{
CPaintManagerUI::SetInstance(hInstance);
CPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath() + _T("skin"));
CPaintManagerUI::SetResourceZip(_T("360SafeRes.zip"));
HRESULT Hr = ::CoInitialize(NULL);
if( FAILED(Hr) ) return 0;
C360SafeFrameWnd* pFrame = new C360SafeFrameWnd();
if( pFrame == NULL ) return 0;
pFrame->Create(NULL, _T("360ȫʿ"), UI_WNDSTYLE_FRAME, 0L, 0, 0, 800, 572);
pFrame->CenterWindow();
::ShowWindow(*pFrame, SW_SHOW);
CPaintManagerUI::MessageLoop();
::CoUninitialize();
return 0;
}<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_GRAD_PFQ_HPP
#define STAN_MATH_PRIM_FUN_GRAD_PFQ_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log_rising_factorial.hpp>
#include <stan/math/prim/fun/hypergeometric_pFq.hpp>
#include <stan/math/prim/fun/max.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <cmath>
namespace stan {
namespace math {
namespace internal {
/**
* Returns the gradient of generalised hypergeometric function wrt to the
* input arguments:
* \f$ _pF_q(a_1,...,a_p;b_1,...,b_q;z) \f$
*
* The derivatives wrt a and b are defined using a Kampé de Fériet function,
* (https://en.wikipedia.org/wiki/Kamp%C3%A9_de_F%C3%A9riet_function).
* This is implemented below as an infinite sum (on the log scale) until
* convergence.
*
* \f$ \frac{\partial}{\partial a_1} =
* \frac{z\prod_{j=2}^pa_j}{\prod_{j=1}^qb_j}
* F_{q+1\:0\;1}^{p\:1\:2}\left(\begin{array}&a_1+1,...,a_p+1;1;1,a_1\\
* 2, b_1+1,...,b_1+1;;a_1+1\end{array};z,z\right) \f$
*
* \f$ \frac{\partial}{\partial b_1}=
* -\frac{z\prod_{j=1}^pa_j}{b_1\prod_{j=1}^qb_j}
* F_{q+1\:0\;1}^{p\:1\:2}\left(\begin{array}&a_1+1,...,a_p+1;1;1,b_1\\
* 2, b_1+1,...,b_1+1;;b_1+1\end{array};z,z\right) \f$
*
* \f$ \frac{\partial}{\partial z}= \frac{\prod_{j=1}^pa_j}{\prod_{j=1}^qb_j}
* {}_pF_q(a_1 + 1,...,a_p + 1; b_1 +1,...,b_q+1;z) \f$
*
* @tparam calc_a Boolean for whether to calculate derivatives wrt to 'a'
* @tparam calc_b Boolean for whether to calculate derivatives wrt to 'b'
* @tparam calc_z Boolean for whether to calculate derivatives wrt to 'z'
* @tparam TupleT Type of tuple containing objects to evaluate gradients into
* @tparam Ta Eigen type with either one row or column at compile time
* @tparam Tb Eigen type with either one row or column at compile time
* @tparam Tz Scalar type
* @param[in] grad_tuple Tuple of references to evaluate gradients into
* @param[in] a Vector of 'a' arguments to function
* @param[in] b Vector of 'b' arguments to function
* @param[in] z Scalar z argument
* @param[in] precision Convergence criteria for infinite sum
* @param[in] max_steps Maximum number of iterations for infinite sum
* @return Generalised hypergeometric function
*/
template <bool calc_a, bool calc_b, bool calc_z, typename TupleT, typename Ta,
typename Tb, typename Tz,
require_all_eigen_vector_t<Ta, Tb>* = nullptr,
require_stan_scalar_t<Tz>* = nullptr>
void grad_pFq_impl(TupleT&& grad_tuple, const Ta& a, const Tb& b, const Tz& z,
double precision, int max_steps) {
using std::max;
using scalar_t = return_type_t<Ta, Tb, Tz>;
using Ta_plain = plain_type_t<Ta>;
using Tb_plain = plain_type_t<Tb>;
using T_vec = Eigen::Matrix<scalar_t, -1, 1>;
Ta_plain ap1 = (a.array() + 1).matrix();
Tb_plain bp1 = (b.array() + 1).matrix();
Ta_plain log_a = log(a);
Tb_plain log_b = log(b);
scalar_type_t<Tz> log_z = log(z);
scalar_type_t<Ta> sum_log_a = sum(log_a);
scalar_type_t<Tb> sum_log_b = sum(log_b);
// Declare vectors to accumulate sums into
// where NEGATIVE_INFTY is zero on the log scale
T_vec da_infsum = T_vec::Constant(a.size(), NEGATIVE_INFTY);
T_vec db_infsum = T_vec::Constant(b.size(), NEGATIVE_INFTY);
// Vectors to accumulate outer sum into
T_vec da_iter_m = T_vec::Constant(a.size(), NEGATIVE_INFTY);
T_vec da_mn = T_vec::Constant(a.size(), NEGATIVE_INFTY);
T_vec db_iter_m = T_vec::Constant(b.size(), NEGATIVE_INFTY);
T_vec db_mn = T_vec::Constant(b.size(), NEGATIVE_INFTY);
// Only need the infinite sum for partials wrt p & b
if (calc_a || calc_b) {
double log_precision = log(precision);
int m = 0;
scalar_t outer_diff = 0;
da_infsum.setConstant(NEGATIVE_INFTY);
db_infsum.setConstant(NEGATIVE_INFTY);
while ((outer_diff > log_precision) && (m < max_steps)) {
// Vectors to accumulate outer sum into
da_iter_m.setConstant(NEGATIVE_INFTY);
da_mn.setConstant(NEGATIVE_INFTY);
db_iter_m.setConstant(NEGATIVE_INFTY);
db_mn.setConstant(NEGATIVE_INFTY);
double log_phammer_1m = log_rising_factorial(1, m);
double lgamma_mp1 = lgamma(m + 1);
int n = 0;
scalar_t inner_diff = 0;
while ((inner_diff > log_precision) & (n < max_steps)) {
// Numerator term
scalar_t term1_mn = (m + n) * log_z
+ sum(log_rising_factorial(ap1, m + n))
+ log_phammer_1m + log_rising_factorial(1, n);
// Denominator term
scalar_t term2_mn = lgamma_mp1 + lgamma(n + 1)
+ sum(log_rising_factorial(bp1, m + n))
+ log_rising_factorial(2, m + n);
if (calc_a) {
// Division (on log scale) for the a & b partials
da_mn = (term1_mn + log_rising_factorial(a, n).array())
- (term2_mn + log_rising_factorial(ap1, n).array());
// Perform a row-wise log_sum_exp to accumulate current iteration
da_iter_m = da_iter_m.binaryExpr(
da_mn, [&](auto& a, auto& b) { return log_sum_exp(a, b); });
}
if (calc_b) {
db_mn = (term1_mn + log_rising_factorial(b, n).array())
- (term2_mn + log_rising_factorial(bp1, n).array());
db_iter_m = db_iter_m.binaryExpr(
db_mn, [&](auto& a, auto& b) { return log_sum_exp(a, b); });
}
// Series convergence assessed by whether the sum of all terms is
// smaller than the specified criteria (precision)
inner_diff = max(log_sum_exp(da_mn), log_sum_exp(db_mn));
n += 1;
}
if (calc_a) {
// Accumulate sums once the inner loop for the current iteration has
// converged
da_infsum = da_infsum.binaryExpr(
da_iter_m, [&](auto& a, auto& b) { return log_sum_exp(a, b); });
}
if (calc_b) {
db_infsum = db_infsum.binaryExpr(
db_iter_m, [&](auto& a, auto& b) { return log_sum_exp(a, b); });
}
// Assess convergence of outer loop
outer_diff = max(log_sum_exp(da_iter_m), log_sum_exp(db_iter_m));
m += 1;
}
if (m == max_steps) {
throw_domain_error("grad_pFq", "k (internal counter)", max_steps,
"exceeded ",
" iterations, hypergeometric function gradient "
"did not converge.");
}
if (calc_a) {
// Workaround to construct vector where each element is the product of
// all other elements
Eigen::VectorXi ind_vector
= Eigen::VectorXi::LinSpaced(a.size(), 0, a.size() - 1);
Ta_plain prod_excl_curr = ind_vector.unaryExpr(
[&log_a, &sum_log_a](int i) { return sum_log_a - log_a[i]; });
T_vec pre_mult_a = (log_z + prod_excl_curr.array() - sum_log_b).matrix();
// Evaluate gradients into provided containers
std::get<0>(grad_tuple) = exp(pre_mult_a + da_infsum);
}
if (calc_b) {
T_vec pre_mult_b = (log_z + sum_log_a) - (log_b.array() + sum_log_b);
std::get<1>(grad_tuple) = -exp(pre_mult_b + db_infsum);
}
}
if (calc_z) {
std::get<2>(grad_tuple)
= exp(sum_log_a - sum_log_b) * hypergeometric_pFq(ap1, bp1, z);
}
}
} // namespace internal
/**
* Wrapper function for calculating gradients for the generalized
* hypergeometric function. The function always returns a tuple with
* three elements (gradients wrt a, b, and z, respectively), but the
* elements will only be defined/calculated when the respective parameter
* is not a primitive type.
*
* @tparam Ta Eigen type with either one row or column at compile time
* @tparam Tb Eigen type with either one row or column at compile time
* @tparam Tz Scalar type
* @param[in] a Vector of 'a' arguments to function
* @param[in] b Vector of 'b' arguments to function
* @param[in] z Scalar z argument
* @param[in] precision Convergence criteria for infinite sum
* @param[in] max_steps Maximum number of iterations for infinite sum
* @return Tuple of gradients
*/
template <typename Ta, typename Tb, typename Tz>
auto grad_pFq(const Ta& a, const Tb& b, const Tz& z, double precision = 1e-14,
int max_steps = 1e6) {
using partials_t = partials_return_t<Ta, Tb, Tz>;
std::tuple<promote_scalar_t<partials_t, plain_type_t<Ta>>,
promote_scalar_t<partials_t, plain_type_t<Tb>>,
promote_scalar_t<partials_t, plain_type_t<Tz>>>
ret_tuple;
internal::grad_pFq_impl<!is_constant<Ta>::value, !is_constant<Tb>::value,
!is_constant<Tz>::value>(
ret_tuple, value_of(a), value_of(b), value_of(z), precision, max_steps);
return ret_tuple;
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Construct lgamma and log_factorial iteratively & loosen inner convergence criteria<commit_after>#ifndef STAN_MATH_PRIM_FUN_GRAD_PFQ_HPP
#define STAN_MATH_PRIM_FUN_GRAD_PFQ_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log_rising_factorial.hpp>
#include <stan/math/prim/fun/hypergeometric_pFq.hpp>
#include <stan/math/prim/fun/max.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <cmath>
namespace stan {
namespace math {
namespace internal {
/**
* Returns the gradient of generalised hypergeometric function wrt to the
* input arguments:
* \f$ _pF_q(a_1,...,a_p;b_1,...,b_q;z) \f$
*
* The derivatives wrt a and b are defined using a Kampé de Fériet function,
* (https://en.wikipedia.org/wiki/Kamp%C3%A9_de_F%C3%A9riet_function).
* This is implemented below as an infinite sum (on the log scale) until
* convergence.
*
* \f$ \frac{\partial}{\partial a_1} =
* \frac{z\prod_{j=2}^pa_j}{\prod_{j=1}^qb_j}
* F_{q+1\:0\;1}^{p\:1\:2}\left(\begin{array}&a_1+1,...,a_p+1;1;1,a_1\\
* 2, b_1+1,...,b_1+1;;a_1+1\end{array};z,z\right) \f$
*
* \f$ \frac{\partial}{\partial b_1}=
* -\frac{z\prod_{j=1}^pa_j}{b_1\prod_{j=1}^qb_j}
* F_{q+1\:0\;1}^{p\:1\:2}\left(\begin{array}&a_1+1,...,a_p+1;1;1,b_1\\
* 2, b_1+1,...,b_1+1;;b_1+1\end{array};z,z\right) \f$
*
* \f$ \frac{\partial}{\partial z}= \frac{\prod_{j=1}^pa_j}{\prod_{j=1}^qb_j}
* {}_pF_q(a_1 + 1,...,a_p + 1; b_1 +1,...,b_q+1;z) \f$
*
* @tparam calc_a Boolean for whether to calculate derivatives wrt to 'a'
* @tparam calc_b Boolean for whether to calculate derivatives wrt to 'b'
* @tparam calc_z Boolean for whether to calculate derivatives wrt to 'z'
* @tparam TupleT Type of tuple containing objects to evaluate gradients into
* @tparam Ta Eigen type with either one row or column at compile time
* @tparam Tb Eigen type with either one row or column at compile time
* @tparam Tz Scalar type
* @param[in] grad_tuple Tuple of references to evaluate gradients into
* @param[in] a Vector of 'a' arguments to function
* @param[in] b Vector of 'b' arguments to function
* @param[in] z Scalar z argument
* @param[in] precision Convergence criteria for infinite sum
* @param[in] max_steps Maximum number of iterations for infinite sum
* @return Generalised hypergeometric function
*/
template <bool calc_a, bool calc_b, bool calc_z, typename TupleT, typename Ta,
typename Tb, typename Tz,
require_all_eigen_vector_t<Ta, Tb>* = nullptr,
require_stan_scalar_t<Tz>* = nullptr>
void grad_pFq_impl(TupleT&& grad_tuple, const Ta& a, const Tb& b, const Tz& z,
double precision, int max_steps) {
using std::max;
using scalar_t = return_type_t<Ta, Tb, Tz>;
using Ta_plain = plain_type_t<Ta>;
using Tb_plain = plain_type_t<Tb>;
using T_vec = Eigen::Matrix<scalar_t, -1, 1>;
Ta_plain ap1 = (a.array() + 1).matrix();
Tb_plain bp1 = (b.array() + 1).matrix();
Ta_plain log_a = log(a);
Tb_plain log_b = log(b);
scalar_type_t<Tz> log_z = log(z);
scalar_type_t<Ta> sum_log_a = sum(log_a);
scalar_type_t<Tb> sum_log_b = sum(log_b);
// Declare vectors to accumulate sums into
// where NEGATIVE_INFTY is zero on the log scale
T_vec da_infsum = T_vec::Constant(a.size(), NEGATIVE_INFTY);
T_vec db_infsum = T_vec::Constant(b.size(), NEGATIVE_INFTY);
// Vectors to accumulate outer sum into
T_vec da_iter_m = T_vec::Constant(a.size(), NEGATIVE_INFTY);
T_vec da_mn = T_vec::Constant(a.size(), NEGATIVE_INFTY);
T_vec db_iter_m = T_vec::Constant(b.size(), NEGATIVE_INFTY);
T_vec db_mn = T_vec::Constant(b.size(), NEGATIVE_INFTY);
// Only need the infinite sum for partials wrt p & b
if (calc_a || calc_b) {
double outer_precision = log(precision);
double inner_precision = log(precision) - LOG_TWO;
int m = 0;
scalar_t outer_diff = 0;
da_infsum.setConstant(NEGATIVE_INFTY);
db_infsum.setConstant(NEGATIVE_INFTY);
double lgamma_mp1 = 0;
double log_phammer_1m = 0;
double log_phammer_2m = 0;
Ta_plain log_phammer_ap1_m = Ta_plain::Zero(ap1.size());
Tb_plain log_phammer_bp1_m = Tb_plain::Zero(bp1.size());
double log_phammer_1n;
double log_phammer_2_mpn;
double lgamma_np1;
Ta_plain log_phammer_an(a.size());
Ta_plain log_phammer_ap1_n(a.size());
Ta_plain log_phammer_bp1_n(b.size());
Tb_plain log_phammer_bn(b.size());
Ta_plain log_phammer_ap1_mpn(a.size());
Tb_plain log_phammer_bp1_mpn(b.size());
while ((outer_diff > outer_precision) && (m < max_steps)) {
// Vectors to accumulate outer sum into
da_iter_m.setConstant(NEGATIVE_INFTY);
da_mn.setConstant(NEGATIVE_INFTY);
db_iter_m.setConstant(NEGATIVE_INFTY);
db_mn.setConstant(NEGATIVE_INFTY);
int n = 0;
scalar_t inner_diff = 0;
lgamma_np1 = 0;
log_phammer_1n = 0;
log_phammer_an.setZero();
log_phammer_ap1_n.setZero();
log_phammer_bp1_n.setZero();
log_phammer_bn.setZero();
log_phammer_ap1_mpn = log_phammer_ap1_m;
log_phammer_bp1_mpn = log_phammer_bp1_m;
log_phammer_2_mpn = log_phammer_2m;
while ((inner_diff > inner_precision) & (n < (max_steps / 2))) {
// Numerator term
scalar_t term1_mn = (m + n) * log_z + sum(log_phammer_ap1_mpn)
+ log_phammer_1m + log_phammer_1n;
// Denominator term
scalar_t term2_mn = lgamma_mp1 + lgamma_np1 + sum(log_phammer_bp1_mpn)
+ log_phammer_2_mpn;
if (calc_a) {
// Division (on log scale) for the a & b partials
da_mn = (term1_mn + log_phammer_an.array())
- (term2_mn + log_phammer_ap1_n.array());
// Perform a row-wise log_sum_exp to accumulate current iteration
da_iter_m = da_iter_m.binaryExpr(
da_mn, [&](auto& a, auto& b) { return log_sum_exp(a, b); });
}
if (calc_b) {
db_mn = (term1_mn + log_phammer_bn.array())
- (term2_mn + log_phammer_bp1_n.array());
db_iter_m = db_iter_m.binaryExpr(
db_mn, [&](auto& a, auto& b) { return log_sum_exp(a, b); });
}
// Series convergence assessed by whether the sum of all terms is
// smaller than the specified criteria (precision)
inner_diff = max(log_sum_exp(da_mn), log_sum_exp(db_mn));
log_phammer_1n += log1p(n);
log_phammer_2_mpn += log1p(1 + m + n);
log_phammer_ap1_n.array() += log(ap1.array() + n);
log_phammer_bp1_n.array() += log(bp1.array() + n);
log_phammer_an.array() += log(a.array() + n);
log_phammer_bn.array() += log(b.array() + n);
log_phammer_ap1_mpn.array() += log(ap1.array() + m + n);
log_phammer_bp1_mpn.array() += log(bp1.array() + m + n);
n += 1;
lgamma_np1 += log(n);
}
if (calc_a) {
// Accumulate sums once the inner loop for the current iteration has
// converged
da_infsum = da_infsum.binaryExpr(
da_iter_m, [&](auto& a, auto& b) { return log_sum_exp(a, b); });
}
if (calc_b) {
db_infsum = db_infsum.binaryExpr(
db_iter_m, [&](auto& a, auto& b) { return log_sum_exp(a, b); });
}
// Assess convergence of outer loop
outer_diff = max(log_sum_exp(da_iter_m), log_sum_exp(db_iter_m));
log_phammer_1m += log1p(m);
log_phammer_2m += log1p(1 + m);
log_phammer_ap1_m.array() += log(ap1.array() + m);
log_phammer_bp1_m.array() += log(bp1.array() + m);
m += 1;
lgamma_mp1 += log(m);
}
if (m == max_steps) {
throw_domain_error("grad_pFq", "k (internal counter)", max_steps,
"exceeded ",
" iterations, hypergeometric function gradient "
"did not converge.");
}
if (calc_a) {
// Workaround to construct vector where each element is the product of
// all other elements
Eigen::VectorXi ind_vector
= Eigen::VectorXi::LinSpaced(a.size(), 0, a.size() - 1);
Ta_plain prod_excl_curr = ind_vector.unaryExpr(
[&log_a, &sum_log_a](int i) { return sum_log_a - log_a[i]; });
T_vec pre_mult_a = (log_z + prod_excl_curr.array() - sum_log_b).matrix();
// Evaluate gradients into provided containers
std::get<0>(grad_tuple) = exp(pre_mult_a + da_infsum);
}
if (calc_b) {
T_vec pre_mult_b = (log_z + sum_log_a) - (log_b.array() + sum_log_b);
std::get<1>(grad_tuple) = -exp(pre_mult_b + db_infsum);
}
}
if (calc_z) {
std::get<2>(grad_tuple)
= exp(sum_log_a - sum_log_b) * hypergeometric_pFq(ap1, bp1, z);
}
}
} // namespace internal
/**
* Wrapper function for calculating gradients for the generalized
* hypergeometric function. The function always returns a tuple with
* three elements (gradients wrt a, b, and z, respectively), but the
* elements will only be defined/calculated when the respective parameter
* is not a primitive type.
*
* @tparam Ta Eigen type with either one row or column at compile time
* @tparam Tb Eigen type with either one row or column at compile time
* @tparam Tz Scalar type
* @param[in] a Vector of 'a' arguments to function
* @param[in] b Vector of 'b' arguments to function
* @param[in] z Scalar z argument
* @param[in] precision Convergence criteria for infinite sum
* @param[in] max_steps Maximum number of iterations for infinite sum
* @return Tuple of gradients
*/
template <typename Ta, typename Tb, typename Tz>
auto grad_pFq(const Ta& a, const Tb& b, const Tz& z, double precision = 1e-10,
int max_steps = 1e6) {
using partials_t = partials_return_t<Ta, Tb, Tz>;
std::tuple<promote_scalar_t<partials_t, plain_type_t<Ta>>,
promote_scalar_t<partials_t, plain_type_t<Tb>>,
promote_scalar_t<partials_t, plain_type_t<Tz>>>
ret_tuple;
internal::grad_pFq_impl<!is_constant<Ta>::value, !is_constant<Tb>::value,
!is_constant<Tz>::value>(
ret_tuple, value_of(a), value_of(b), value_of(z), precision, max_steps);
return ret_tuple;
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>// @(#)root/hist:$Name: $:$Id: TLimit.cxx,v 1.2 2002/09/06 20:24:18 brun Exp $
// Author: [email protected] 21/08/2002
///////////////////////////////////////////////////////////////////////////
//
// TLimit
//
// Class to compute 95% CL limits
//
///////////////////////////////////////////////////////////////////////////
/*************************************************************************
* C.Delaere *
* adapted from the mclimit code from Tom Junk *
* see http://cern.ch/thomasj/searchlimits/ecl.html *
*************************************************************************/
#include "TLimit.h"
#include "TArrayF.h"
#include "TOrdCollection.h"
#include "TConfidenceLevel.h"
#include "TLimitDataSource.h"
#include "TRandom3.h"
#include "TH1.h"
#include "TObjArray.h"
#include "TMath.h"
#include "TIterator.h"
#include "TObjString.h"
#include "TClassTable.h"
#include "Riostream.h"
ClassImp(TLimit)
TArrayF *TLimit::fgTable = new TArrayF(0);
TOrdCollection *TLimit::fgSystNames = new TOrdCollection();
TConfidenceLevel *TLimit::ComputeLimit(TLimitDataSource * data,
Int_t nmc, TRandom * generator,
Double_t(*statistic) (Double_t,
Double_t,
Double_t))
{
// class TLimit
// ------------
//
// Algorithm to compute 95% C.L. limits using the Likelihood ratio
// semi-bayesian method.
// It takes signal, background and data histograms wrapped in a
// TLimitDataSource as input and runs a set of Monte Carlo experiments in
// order to compute the limits. If needed, inputs are fluctuated according
// to systematics. The output is a TConfidenceLevel.
//
// class TLimitDataSource
// ----------------------
//
// Takes the signal, background and data histograms as well as different
// systematics sources to form the TLimit input.
//
// class TConfidenceLevel
// ----------------------
//
// Final result of the TLimit algorithm. It is created just after the
// time-consuming part and can be stored in a TFile for further processing.
// It contains light methods to return CLs, CLb and other interesting
// quantities.
//
// The actual algorithm...
// From an input (TLimitDataSource) it produces an output TConfidenceLevel.
// For this, nmc Monte Carlo experiments are performed.
// As usual, the larger this number, the longer the compute time,
// but the better the result.
//Begin_Html
/*
<FONT SIZE=+0>
<p>Supposing that there is a plotfile.root file containing 3 histograms
(signal, background and data), you can imagine doing things like:</p>
<p>
<BLOCKQUOTE><PRE>
TFile* infile=new TFile("plotfile.root","READ");
infile->cd();
TH1F* sh=(TH1F*)infile->Get("signal");
TH1F* bh=(TH1F*)infile->Get("background");
TH1F* dh=(TH1F*)infile->Get("data");
TLimitDataSource* mydatasource = new TLimitDataSource(sh,bh,dh);
TConfidenceLevel *myconfidence = TLimit::ComputeLimit(mydatasource,50000);
cout << " CLs : " << myconfidence->CLs() << endl;
cout << " CLsb : " << myconfidence->CLsb() << endl;
cout << " CLb : " << myconfidence->CLb() << endl;
cout << "< CLs > : " << myconfidence->GetExpectedCLs_b() << endl;
cout << "< CLsb > : " << myconfidence->GetExpectedCLsb_b() << endl;
cout << "< CLb > : " << myconfidence->GetExpectedCLb_b() << endl;
delete myconfidence;
delete mydatasource;
infile->Close();
</PRE></BLOCKQUOTE></p>
<p></p>
<p>More informations can still be found on
<a HREF="http://cern.ch/aleph-proj-alphapp/doc/tlimit.html">this</a> page.</p>
</FONT>
*/
//End_Html
// The final object returned...
TConfidenceLevel *result = new TConfidenceLevel(nmc);
// The random generator used...
TRandom *myrandom = generator ? generator : new TRandom3;
// Compute some total quantities on all the channels
Int_t nbins = 0;
Int_t maxbins = 0;
Double_t nsig = 0;
Double_t nbg = 0;
Int_t ncand = 0;
Int_t i;
for (i = 0; i <= data->GetSignal()->GetLast(); i++) {
nbins += ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX();
maxbins = ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX() > maxbins ?
((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX() + 1 : maxbins;
nsig += ((TH1F *) (data->GetSignal()->At(i)))->Integral();
nbg += ((TH1F *) (data->GetBackground()->At(i)))->Integral();
ncand += (Int_t) ((TH1F *) (data->GetCandidates()->At(i)))->Integral();
}
result->SetBtot(nbg);
result->SetStot(nsig);
result->SetDtot(ncand);
Double_t buffer = 0;
fgTable->Set(maxbins * (data->GetSignal()->GetLast() + 1));
for (Int_t channel = 0; channel <= data->GetSignal()->GetLast(); channel++)
for (Int_t bin = 0;
bin <= ((TH1F *) (data->GetSignal()->At(channel)))->GetNbinsX();
bin++) {
Double_t s = (Double_t) ((TH1F *) (data->GetSignal()->At(channel)))->GetBinContent(bin);
Double_t b = (Double_t) ((TH1F *) (data->GetBackground()->At(channel)))->GetBinContent(bin);
Double_t d = (Double_t) ((TH1F *) (data->GetCandidates()->At(channel)))->GetBinContent(bin);
// Compute the value of the "-2lnQ" for the actual data
if ((b == 0) && (s > 0)) {
cout << "WARNING: Ignoring bin " << bin << " of channel "
<< channel << " which has s=" << s << " but b=" << b << endl;
cout << " Maybe the MC statistic has to be improved..." << endl;
}
if ((s > 0) && (b > 0))
buffer += statistic(s, b, d);
// precompute the log(1+s/b)'s in an array to speed up computation
// background-free bins are set to have a maximum t.s. value
// for protection (corresponding to s/b of about 5E8)
if ((s > 0) && (b > 0))
fgTable->AddAt(statistic(s, b, 1), (channel * maxbins) + bin);
else if ((s > 0) && (b == 0))
fgTable->AddAt(20, (channel * maxbins) + bin);
}
result->SetTSD(buffer);
// accumulate MC experiments. Hold the test statistic function fixed, but
// fluctuate s and b within syst. errors for computing probabilities of
// having that outcome. (Alex Read's prescription -- errors are on the ensemble,
// not on the observed test statistic. This technique does not split outcomes.)
// keep the tstats as sum log(1+s/b). convert to -2lnQ when preparing the results
// (reason -- like to keep the < signs right)
Double_t *tss = new Double_t[nmc];
Double_t *tsb = new Double_t[nmc];
Double_t *lrs = new Double_t[nmc];
Double_t *lrb = new Double_t[nmc];
for (i = 0; i < nmc; i++) {
tss[i] = 0;
tsb[i] = 0;
lrs[i] = 0;
lrb[i] = 0;
// fluctuate signal and background
TLimitDataSource *fluctuated = Fluctuate(data, !i, myrandom);
for (Int_t channel = 0;
channel <= fluctuated->GetSignal()->GetLast(); channel++) {
for (Int_t bin = 0;
bin <=((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetNbinsX();
bin++) {
if ((Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin) != 0) {
// s+b hypothesis
Double_t rate = (Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin) +
(Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);
Double_t rand = myrandom->Poisson(rate);
tss[i] += rand * fgTable->At((channel * maxbins) + bin);
Double_t s = (Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin);
Double_t b = (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);
if ((s > 0) && (b > 0))
lrs[i] += statistic(s, b, rand) - s;
else if ((s > 0) && (b = 0))
lrs[i] += 20 * rand - s;
// b hypothesis
rate = (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);
rand = myrandom->Poisson(rate);
tsb[i] += rand * fgTable->At((channel * maxbins) + bin);
if ((s > 0) && (b > 0))
lrb[i] += statistic(s, b, rand) - s;
else if ((s > 0) && (b = 0))
lrb[i] += 20 * rand - s;
}
}
}
lrs[i] = TMath::Exp(lrs[i]);
lrb[i] = TMath::Exp(lrb[i]);
if (data != fluctuated)
delete fluctuated;
}
// lrs and lrb are the LR's (no logs) = prob(s+b)/prob(b) for
// that choice of s and b within syst. errors in the ensemble. These are
// the MC experiment weights for relating the s+b and b PDF's of the unsmeared
// test statistic (in which cas one can use another test statistic if one likes).
// Now produce the output object.
// The final quantities are computed on-demand form the arrays tss, tsb, lrs and lrb.
result->SetTSS(tss);
result->SetTSB(tsb);
result->SetLRS(lrs);
result->SetLRB(lrb);
if (!generator)
delete myrandom;
return result;
}
TLimitDataSource *TLimit::Fluctuate(TLimitDataSource * input, bool init,
TRandom * generator)
{
// initialisation: create a sorted list of all the names of systematics
if (init) {
// create a "map" with the systematics names
TIterator *errornames = input->GetErrorNames()->MakeIterator();
TObjArray *listofnames = 0;
while ((listofnames = ((TObjArray *) errornames->Next()))) {
TObjString *name = NULL;
TIterator *loniter = listofnames->MakeIterator();
while ((name = (TObjString *) (loniter->Next())))
if ((fgSystNames->IndexOf(name)) < 0)
fgSystNames->AddLast(name);
}
fgSystNames->Sort();
}
// if there are no systematics, just returns the input as "fluctuated" output
if (fgSystNames->GetSize() <= 0)
return input;
// Find a choice for the random variation and
// re-toss all random numbers if any background or signal
// goes negative. (background = 0 is bad too, so put a little protection
// around it -- must have at least 10% of the bg estimate).
bool retoss = kTRUE;
Double_t *serrf = NULL;
Double_t *berrf = NULL;
do {
Double_t *toss = new Double_t[fgSystNames->GetSize()];
for (Int_t i = 0; i < fgSystNames->GetSize(); i++)
toss[i] = generator->Gaus(0, 1);
retoss = kFALSE;
serrf = new Double_t[(input->GetSignal()->GetLast()) + 1];
berrf = new Double_t[(input->GetSignal()->GetLast()) + 1];
for (Int_t channel = 0;
channel <= input->GetSignal()->GetLast();
channel++) {
serrf[channel] = 0;
berrf[channel] = 0;
for (Int_t bin = 0;
bin <=((TH1F *) (input->GetErrorOnSignal()->At(channel)))->GetNbinsX();
bin++) {
serrf[channel] += ((TH1F *) (input->GetErrorOnSignal()->At(channel)))->GetBinContent(bin) *
toss[fgSystNames->BinarySearch((TObjString*) (((TObjArray *) (input->GetErrorNames()->At(channel)))->At(bin)))];
berrf[channel] += ((TH1F *) (input->GetErrorOnBackground()->At(channel)))->GetBinContent(bin) *
toss[fgSystNames->BinarySearch((TObjString*) (((TObjArray *) (input->GetErrorNames()->At(channel)))->At(bin)))];
}
if ((serrf[channel] < -1.0) || (berrf[channel] < -0.9)) {
retoss = kTRUE;
continue;
}
}
delete[]toss;
} while (retoss);
// adjust the fluctuated signal and background counts with a legal set
// of random fluctuations above.
TLimitDataSource *result = new TLimitDataSource();
result->SetOwner();
for (Int_t channel = 0; channel <= input->GetSignal()->GetLast();
channel++) {
TH1F *newsignal = new TH1F(*(TH1F *) (input->GetSignal()->At(channel)));
newsignal->Scale(1 + serrf[channel]);
newsignal->SetDirectory(0);
TH1F *newbackground = new TH1F(*(TH1F *) (input->GetBackground()->At(channel)));
newbackground->Scale(1 + berrf[channel]);
newbackground->SetDirectory(0);
TH1F *newcandidates = new TH1F(*(TH1F *) (input->GetCandidates()));
newcandidates->SetDirectory(0);
result->AddChannel(newsignal, newbackground, newcandidates);
}
delete[] serrf;
delete[] berrf;
return result;
}
<commit_msg>change (b = 0) to (b == 0) in if statement.<commit_after>// @(#)root/hist:$Name: $:$Id: TLimit.cxx,v 1.3 2002/09/06 21:41:23 brun Exp $
// Author: [email protected] 21/08/2002
///////////////////////////////////////////////////////////////////////////
//
// TLimit
//
// Class to compute 95% CL limits
//
///////////////////////////////////////////////////////////////////////////
/*************************************************************************
* C.Delaere *
* adapted from the mclimit code from Tom Junk *
* see http://cern.ch/thomasj/searchlimits/ecl.html *
*************************************************************************/
#include "TLimit.h"
#include "TArrayF.h"
#include "TOrdCollection.h"
#include "TConfidenceLevel.h"
#include "TLimitDataSource.h"
#include "TRandom3.h"
#include "TH1.h"
#include "TObjArray.h"
#include "TMath.h"
#include "TIterator.h"
#include "TObjString.h"
#include "TClassTable.h"
#include "Riostream.h"
ClassImp(TLimit)
TArrayF *TLimit::fgTable = new TArrayF(0);
TOrdCollection *TLimit::fgSystNames = new TOrdCollection();
TConfidenceLevel *TLimit::ComputeLimit(TLimitDataSource * data,
Int_t nmc, TRandom * generator,
Double_t(*statistic) (Double_t,
Double_t,
Double_t))
{
// class TLimit
// ------------
//
// Algorithm to compute 95% C.L. limits using the Likelihood ratio
// semi-bayesian method.
// It takes signal, background and data histograms wrapped in a
// TLimitDataSource as input and runs a set of Monte Carlo experiments in
// order to compute the limits. If needed, inputs are fluctuated according
// to systematics. The output is a TConfidenceLevel.
//
// class TLimitDataSource
// ----------------------
//
// Takes the signal, background and data histograms as well as different
// systematics sources to form the TLimit input.
//
// class TConfidenceLevel
// ----------------------
//
// Final result of the TLimit algorithm. It is created just after the
// time-consuming part and can be stored in a TFile for further processing.
// It contains light methods to return CLs, CLb and other interesting
// quantities.
//
// The actual algorithm...
// From an input (TLimitDataSource) it produces an output TConfidenceLevel.
// For this, nmc Monte Carlo experiments are performed.
// As usual, the larger this number, the longer the compute time,
// but the better the result.
//Begin_Html
/*
<FONT SIZE=+0>
<p>Supposing that there is a plotfile.root file containing 3 histograms
(signal, background and data), you can imagine doing things like:</p>
<p>
<BLOCKQUOTE><PRE>
TFile* infile=new TFile("plotfile.root","READ");
infile->cd();
TH1F* sh=(TH1F*)infile->Get("signal");
TH1F* bh=(TH1F*)infile->Get("background");
TH1F* dh=(TH1F*)infile->Get("data");
TLimitDataSource* mydatasource = new TLimitDataSource(sh,bh,dh);
TConfidenceLevel *myconfidence = TLimit::ComputeLimit(mydatasource,50000);
cout << " CLs : " << myconfidence->CLs() << endl;
cout << " CLsb : " << myconfidence->CLsb() << endl;
cout << " CLb : " << myconfidence->CLb() << endl;
cout << "< CLs > : " << myconfidence->GetExpectedCLs_b() << endl;
cout << "< CLsb > : " << myconfidence->GetExpectedCLsb_b() << endl;
cout << "< CLb > : " << myconfidence->GetExpectedCLb_b() << endl;
delete myconfidence;
delete mydatasource;
infile->Close();
</PRE></BLOCKQUOTE></p>
<p></p>
<p>More informations can still be found on
<a HREF="http://cern.ch/aleph-proj-alphapp/doc/tlimit.html">this</a> page.</p>
</FONT>
*/
//End_Html
// The final object returned...
TConfidenceLevel *result = new TConfidenceLevel(nmc);
// The random generator used...
TRandom *myrandom = generator ? generator : new TRandom3;
// Compute some total quantities on all the channels
Int_t nbins = 0;
Int_t maxbins = 0;
Double_t nsig = 0;
Double_t nbg = 0;
Int_t ncand = 0;
Int_t i;
for (i = 0; i <= data->GetSignal()->GetLast(); i++) {
nbins += ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX();
maxbins = ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX() > maxbins ?
((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX() + 1 : maxbins;
nsig += ((TH1F *) (data->GetSignal()->At(i)))->Integral();
nbg += ((TH1F *) (data->GetBackground()->At(i)))->Integral();
ncand += (Int_t) ((TH1F *) (data->GetCandidates()->At(i)))->Integral();
}
result->SetBtot(nbg);
result->SetStot(nsig);
result->SetDtot(ncand);
Double_t buffer = 0;
fgTable->Set(maxbins * (data->GetSignal()->GetLast() + 1));
for (Int_t channel = 0; channel <= data->GetSignal()->GetLast(); channel++)
for (Int_t bin = 0;
bin <= ((TH1F *) (data->GetSignal()->At(channel)))->GetNbinsX();
bin++) {
Double_t s = (Double_t) ((TH1F *) (data->GetSignal()->At(channel)))->GetBinContent(bin);
Double_t b = (Double_t) ((TH1F *) (data->GetBackground()->At(channel)))->GetBinContent(bin);
Double_t d = (Double_t) ((TH1F *) (data->GetCandidates()->At(channel)))->GetBinContent(bin);
// Compute the value of the "-2lnQ" for the actual data
if ((b == 0) && (s > 0)) {
cout << "WARNING: Ignoring bin " << bin << " of channel "
<< channel << " which has s=" << s << " but b=" << b << endl;
cout << " Maybe the MC statistic has to be improved..." << endl;
}
if ((s > 0) && (b > 0))
buffer += statistic(s, b, d);
// precompute the log(1+s/b)'s in an array to speed up computation
// background-free bins are set to have a maximum t.s. value
// for protection (corresponding to s/b of about 5E8)
if ((s > 0) && (b > 0))
fgTable->AddAt(statistic(s, b, 1), (channel * maxbins) + bin);
else if ((s > 0) && (b == 0))
fgTable->AddAt(20, (channel * maxbins) + bin);
}
result->SetTSD(buffer);
// accumulate MC experiments. Hold the test statistic function fixed, but
// fluctuate s and b within syst. errors for computing probabilities of
// having that outcome. (Alex Read's prescription -- errors are on the ensemble,
// not on the observed test statistic. This technique does not split outcomes.)
// keep the tstats as sum log(1+s/b). convert to -2lnQ when preparing the results
// (reason -- like to keep the < signs right)
Double_t *tss = new Double_t[nmc];
Double_t *tsb = new Double_t[nmc];
Double_t *lrs = new Double_t[nmc];
Double_t *lrb = new Double_t[nmc];
for (i = 0; i < nmc; i++) {
tss[i] = 0;
tsb[i] = 0;
lrs[i] = 0;
lrb[i] = 0;
// fluctuate signal and background
TLimitDataSource *fluctuated = Fluctuate(data, !i, myrandom);
for (Int_t channel = 0;
channel <= fluctuated->GetSignal()->GetLast(); channel++) {
for (Int_t bin = 0;
bin <=((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetNbinsX();
bin++) {
if ((Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin) != 0) {
// s+b hypothesis
Double_t rate = (Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin) +
(Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);
Double_t rand = myrandom->Poisson(rate);
tss[i] += rand * fgTable->At((channel * maxbins) + bin);
Double_t s = (Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin);
Double_t b = (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);
if ((s > 0) && (b > 0))
lrs[i] += statistic(s, b, rand) - s;
else if ((s > 0) && (b == 0))
lrs[i] += 20 * rand - s;
// b hypothesis
rate = (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);
rand = myrandom->Poisson(rate);
tsb[i] += rand * fgTable->At((channel * maxbins) + bin);
if ((s > 0) && (b > 0))
lrb[i] += statistic(s, b, rand) - s;
else if ((s > 0) && (b == 0))
lrb[i] += 20 * rand - s;
}
}
}
lrs[i] = TMath::Exp(lrs[i]);
lrb[i] = TMath::Exp(lrb[i]);
if (data != fluctuated)
delete fluctuated;
}
// lrs and lrb are the LR's (no logs) = prob(s+b)/prob(b) for
// that choice of s and b within syst. errors in the ensemble. These are
// the MC experiment weights for relating the s+b and b PDF's of the unsmeared
// test statistic (in which cas one can use another test statistic if one likes).
// Now produce the output object.
// The final quantities are computed on-demand form the arrays tss, tsb, lrs and lrb.
result->SetTSS(tss);
result->SetTSB(tsb);
result->SetLRS(lrs);
result->SetLRB(lrb);
if (!generator)
delete myrandom;
return result;
}
TLimitDataSource *TLimit::Fluctuate(TLimitDataSource * input, bool init,
TRandom * generator)
{
// initialisation: create a sorted list of all the names of systematics
if (init) {
// create a "map" with the systematics names
TIterator *errornames = input->GetErrorNames()->MakeIterator();
TObjArray *listofnames = 0;
while ((listofnames = ((TObjArray *) errornames->Next()))) {
TObjString *name = NULL;
TIterator *loniter = listofnames->MakeIterator();
while ((name = (TObjString *) (loniter->Next())))
if ((fgSystNames->IndexOf(name)) < 0)
fgSystNames->AddLast(name);
}
fgSystNames->Sort();
}
// if there are no systematics, just returns the input as "fluctuated" output
if (fgSystNames->GetSize() <= 0)
return input;
// Find a choice for the random variation and
// re-toss all random numbers if any background or signal
// goes negative. (background = 0 is bad too, so put a little protection
// around it -- must have at least 10% of the bg estimate).
bool retoss = kTRUE;
Double_t *serrf = NULL;
Double_t *berrf = NULL;
do {
Double_t *toss = new Double_t[fgSystNames->GetSize()];
for (Int_t i = 0; i < fgSystNames->GetSize(); i++)
toss[i] = generator->Gaus(0, 1);
retoss = kFALSE;
serrf = new Double_t[(input->GetSignal()->GetLast()) + 1];
berrf = new Double_t[(input->GetSignal()->GetLast()) + 1];
for (Int_t channel = 0;
channel <= input->GetSignal()->GetLast();
channel++) {
serrf[channel] = 0;
berrf[channel] = 0;
for (Int_t bin = 0;
bin <=((TH1F *) (input->GetErrorOnSignal()->At(channel)))->GetNbinsX();
bin++) {
serrf[channel] += ((TH1F *) (input->GetErrorOnSignal()->At(channel)))->GetBinContent(bin) *
toss[fgSystNames->BinarySearch((TObjString*) (((TObjArray *) (input->GetErrorNames()->At(channel)))->At(bin)))];
berrf[channel] += ((TH1F *) (input->GetErrorOnBackground()->At(channel)))->GetBinContent(bin) *
toss[fgSystNames->BinarySearch((TObjString*) (((TObjArray *) (input->GetErrorNames()->At(channel)))->At(bin)))];
}
if ((serrf[channel] < -1.0) || (berrf[channel] < -0.9)) {
retoss = kTRUE;
continue;
}
}
delete[]toss;
} while (retoss);
// adjust the fluctuated signal and background counts with a legal set
// of random fluctuations above.
TLimitDataSource *result = new TLimitDataSource();
result->SetOwner();
for (Int_t channel = 0; channel <= input->GetSignal()->GetLast();
channel++) {
TH1F *newsignal = new TH1F(*(TH1F *) (input->GetSignal()->At(channel)));
newsignal->Scale(1 + serrf[channel]);
newsignal->SetDirectory(0);
TH1F *newbackground = new TH1F(*(TH1F *) (input->GetBackground()->At(channel)));
newbackground->Scale(1 + berrf[channel]);
newbackground->SetDirectory(0);
TH1F *newcandidates = new TH1F(*(TH1F *) (input->GetCandidates()));
newcandidates->SetDirectory(0);
result->AddChannel(newsignal, newbackground, newcandidates);
}
delete[] serrf;
delete[] berrf;
return result;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "V8CustomEvent.h"
#include "V8Event.h"
#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ScriptState.h"
#include "bindings/v8/ScriptValue.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8DOMWrapper.h"
#include "bindings/v8/V8HiddenPropertyName.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/ExceptionCode.h"
#include "core/page/Frame.h"
#include "RuntimeEnabledFeatures.h"
namespace WebCore {
static v8::Handle<v8::Value> cacheState(v8::Handle<v8::Object> customEvent, v8::Handle<v8::Value> detail)
{
customEvent->SetHiddenValue(V8HiddenPropertyName::detail(), detail);
return detail;
}
void V8CustomEvent::detailAttrGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
CustomEvent* event = V8CustomEvent::toNative(info.Holder());
ASSERT(!event->serializedScriptValue().get());
v8::Handle<v8::Value> result = info.Holder()->GetHiddenValue(V8HiddenPropertyName::detail());
if (!result.IsEmpty()) {
v8SetReturnValue(info, result);
return;
}
RefPtr<SerializedScriptValue> serialized = event->serializedScriptValue();
if (serialized) {
result = serialized->deserialize();
v8SetReturnValue(info, cacheState(info.Holder(), result));
return;
}
v8SetReturnValue(info, cacheState(info.Holder(), v8::Null(info.GetIsolate())));
}
void V8CustomEvent::initCustomEventMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args)
{
CustomEvent* event = V8CustomEvent::toNative(args.Holder());
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, typeArg, args[0]);
V8TRYCATCH_VOID(bool, canBubbleArg, args[1]->BooleanValue());
V8TRYCATCH_VOID(bool, cancelableArg, args[2]->BooleanValue());
v8::Handle<v8::Value> detailsArg = args[3];
args.Holder()->SetHiddenValue(V8HiddenPropertyName::detail(), detailsArg);
event->initEvent(typeArg, canBubbleArg, cancelableArg);
}
} // namespace WebCore
<commit_msg>Moved broken assert in CustomEvent from detail getter to init. Assert was hit in browser_test WebViewTest.IndexedDBIsolation.<commit_after>/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "V8CustomEvent.h"
#include "V8Event.h"
#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ScriptState.h"
#include "bindings/v8/ScriptValue.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8DOMWrapper.h"
#include "bindings/v8/V8HiddenPropertyName.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/ExceptionCode.h"
#include "core/page/Frame.h"
#include "RuntimeEnabledFeatures.h"
namespace WebCore {
static v8::Handle<v8::Value> cacheState(v8::Handle<v8::Object> customEvent, v8::Handle<v8::Value> detail)
{
customEvent->SetHiddenValue(V8HiddenPropertyName::detail(), detail);
return detail;
}
void V8CustomEvent::detailAttrGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
CustomEvent* event = V8CustomEvent::toNative(info.Holder());
v8::Handle<v8::Value> result = info.Holder()->GetHiddenValue(V8HiddenPropertyName::detail());
if (!result.IsEmpty()) {
v8SetReturnValue(info, result);
return;
}
RefPtr<SerializedScriptValue> serialized = event->serializedScriptValue();
if (serialized) {
result = serialized->deserialize();
v8SetReturnValue(info, cacheState(info.Holder(), result));
return;
}
v8SetReturnValue(info, cacheState(info.Holder(), v8::Null(info.GetIsolate())));
}
void V8CustomEvent::initCustomEventMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args)
{
CustomEvent* event = V8CustomEvent::toNative(args.Holder());
ASSERT(!event->serializedScriptValue());
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, typeArg, args[0]);
V8TRYCATCH_VOID(bool, canBubbleArg, args[1]->BooleanValue());
V8TRYCATCH_VOID(bool, cancelableArg, args[2]->BooleanValue());
v8::Handle<v8::Value> detailsArg = args[3];
args.Holder()->SetHiddenValue(V8HiddenPropertyName::detail(), detailsArg);
event->initEvent(typeArg, canBubbleArg, cancelableArg);
}
} // namespace WebCore
<|endoftext|> |
<commit_before>/**
* @file
* @author 2012 Stefan Radomski ([email protected])
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#include "umundo/connection/zeromq/ZeroMQNode.h"
#include "umundo/connection/Publisher.h"
#include "umundo/common/Message.h"
#include "umundo/common/UUID.h"
// include order matters with MSVC ...
#include "umundo/connection/zeromq/ZeroMQSubscriber.h"
#include "umundo/config.h"
#if defined UNIX || defined IOS || defined IOSSIM
#include <stdio.h> // snprintf
#endif
namespace umundo {
shared_ptr<Implementation> ZeroMQSubscriber::create(void*) {
shared_ptr<Implementation> instance(new ZeroMQSubscriber());
return instance;
}
void ZeroMQSubscriber::destroy() {
delete(this);
}
ZeroMQSubscriber::ZeroMQSubscriber() {
}
ZeroMQSubscriber::~ZeroMQSubscriber() {
LOG_INFO("deleting subscriber for %s", _channelName.c_str());
join();
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQSubscriber::init(shared_ptr<Configuration> config) {
_config = boost::static_pointer_cast<SubscriberConfig>(config);
_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());
assert(_uuid.length() == 36);
void* ctx = ZeroMQNode::getZeroMQContext();
(_socket = zmq_socket(ctx, ZMQ_SUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
(_closer = zmq_socket(ctx, ZMQ_PUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
assert(_channelName.size() > 0);
int hwm = NET_ZEROMQ_RCV_HWM;
zmq_setsockopt(_socket, ZMQ_RCVHWM, &hwm, sizeof(hwm)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
zmq_setsockopt(_socket, ZMQ_IDENTITY, _uuid.c_str(), _uuid.length()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
zmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _channelName.c_str(), _channelName.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
LOG_DEBUG("Subscribing to %s", _channelName.c_str());
zmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
LOG_DEBUG("Subscribing to %s", SHORT_UUID(_uuid).c_str());
// reconnection intervals
int reconnect_ivl_min = 100;
int reconnect_ivl_max = 200;
zmq_setsockopt (_socket, ZMQ_RECONNECT_IVL, &reconnect_ivl_min, sizeof(int)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
zmq_setsockopt (_socket, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl_max, sizeof(int)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
// make sure we can close the socket later
std::stringstream ss;
ss << "inproc://" << _uuid;
zmq_bind(_closer, ss.str().c_str()) && LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_connect: %s",zmq_strerror(errno));
LOG_INFO("creating subscriber for %s", _channelName.c_str());
start();
}
/**
* Break blocking zmq_recvmsg in ZeroMQSubscriber::run.
*/
void ZeroMQSubscriber::join() {
UMUNDO_LOCK(_mutex);
stop();
// this is a hack .. the thread is blocking at zmq_recvmsg - unblock by sending a message
zmq_msg_t channelEnvlp;
ZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());
zmq_sendmsg(_closer, &channelEnvlp, 0) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&channelEnvlp) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
Thread::join();
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQSubscriber::suspend() {
UMUNDO_LOCK(_mutex);
if (_isSuspended) {
UMUNDO_UNLOCK(_mutex);
return;
}
_isSuspended = true;
stop();
join();
_connections.clear();
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQSubscriber::resume() {
UMUNDO_LOCK(_mutex);
if (!_isSuspended) {
UMUNDO_UNLOCK(_mutex);
return;
}
_isSuspended = false;
init(_config);
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQSubscriber::run() {
int32_t more;
size_t more_size = sizeof(more);
zmq_pollitem_t pollItem;
pollItem.socket = _socket;
pollItem.events = ZMQ_POLLIN | ZMQ_POLLOUT;
while(isStarted()) {
int rc = 0;
{
ScopeLock lock(&_mutex);
zmq_poll(&pollItem, 1, 30);
}
if (rc < 0) {
// an error occurred
switch(rc) {
case ETERM:
LOG_WARN("zmq_poll called with terminated socket");
break;
case EFAULT:
LOG_WARN("zmq_poll called with invalid items");
break;
case EINTR:
default:
break;
}
} else if (rc == 0) {
// Nothing to read - released lock
Thread::yield();
// Thread::sleepMs(5);
} if (rc > 0) {
// there is a message to be read
ScopeLock lock(&_mutex);
Message* msg = new Message();
while (1) {
// read and dispatch the whole message
zmq_msg_t message;
zmq_msg_init(&message) && LOG_WARN("zmq_msg_init: %s",zmq_strerror(errno));
while (zmq_recvmsg(_socket, &message, 0) < 0)
if (errno != EINTR)
LOG_WARN("zmq_recvmsg: %s",zmq_strerror(errno));
size_t msgSize = zmq_msg_size(&message);
if (!isStarted()) {
zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
return;
}
// last message contains actual data
zmq_getsockopt(_socket, ZMQ_RCVMORE, &more, &more_size) && LOG_WARN("zmq_getsockopt: %s",zmq_strerror(errno));
if (more) {
char* key = (char*)zmq_msg_data(&message);
char* value = ((char*)zmq_msg_data(&message) + strlen(key) + 1);
// is this the first message with the channelname?
if (strlen(key) + 1 == msgSize &&
msg->getMeta().find(key) == msg->getMeta().end()) {
msg->putMeta("channel", key);
} else {
assert(strlen(key) + strlen(value) + 2 == msgSize);
if (strlen(key) + strlen(value) + 2 != msgSize) {
LOG_WARN("Received malformed message %d + %d + 2 != %d", strlen(key), strlen(value), msgSize);
zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
break;
} else {
msg->putMeta(key, value);
}
}
zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
} else {
msg->setData((char*)zmq_msg_data(&message), msgSize);
zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
if (_receiver != NULL) {
_receiver->receive(msg);
delete(msg);
} else {
ScopeLock lock(&_msgMutex);
_msgQueue.push_back(msg);
}
break; // last message part
}
}
}
}
}
Message* ZeroMQSubscriber::getNextMsg() {
if (_receiver != NULL) {
LOG_WARN("getNextMsg not functional when a receiver is given");
return NULL;
}
ScopeLock lock(&_msgMutex);
Message* msg = NULL;
if (_msgQueue.size() > 0) {
msg = _msgQueue.front();
_msgQueue.pop_front();
}
return msg;
}
Message* ZeroMQSubscriber::peekNextMsg() {
if (_receiver != NULL) {
LOG_WARN("peekNextMsg not functional when a receiver is given");
return NULL;
}
ScopeLock lock(&_msgMutex);
Message* msg = NULL;
if (_msgQueue.size() > 0) {
msg = _msgQueue.front();
}
return msg;
}
void ZeroMQSubscriber::added(shared_ptr<PublisherStub> pub) {
std::stringstream ss;
if (pub->isInProcess() && false) {
ss << "inproc://" << pub->getUUID();
} else {
ss << pub->getTransport() << "://" << pub->getIP() << ":" << pub->getPort();
}
if (_connections.find(ss.str()) != _connections.end()) {
LOG_INFO("Already connected to %s", ss.str().c_str());
return;
}
ScopeLock lock(&_mutex);
LOG_INFO("%s subscribing at %s", _channelName.c_str(), ss.str().c_str());
zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_connect: %s", zmq_strerror(errno));
_connections.insert(ss.str());
}
void ZeroMQSubscriber::removed(shared_ptr<PublisherStub> pub) {
ScopeLock lock(&_mutex);
std::stringstream ss;
if (pub->isInProcess() && false) {
ss << "inproc://" << pub->getUUID();
} else {
ss << pub->getTransport() << "://" << pub->getIP() << ":" << pub->getPort();
}
if (_connections.find(ss.str()) == _connections.end()) {
LOG_INFO("Never connected to %s won't disconnect", ss.str().c_str());
return;
}
LOG_DEBUG("unsubscribing from %s", ss.str().c_str());
zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_disconnect: %s", zmq_strerror(errno));
_connections.erase(ss.str());
}
void ZeroMQSubscriber::changed(shared_ptr<PublisherStub>) {
// never called
}
}<commit_msg>Forgot to assign return value<commit_after>/**
* @file
* @author 2012 Stefan Radomski ([email protected])
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#include "umundo/connection/zeromq/ZeroMQNode.h"
#include "umundo/connection/Publisher.h"
#include "umundo/common/Message.h"
#include "umundo/common/UUID.h"
// include order matters with MSVC ...
#include "umundo/connection/zeromq/ZeroMQSubscriber.h"
#include "umundo/config.h"
#if defined UNIX || defined IOS || defined IOSSIM
#include <stdio.h> // snprintf
#endif
namespace umundo {
shared_ptr<Implementation> ZeroMQSubscriber::create(void*) {
shared_ptr<Implementation> instance(new ZeroMQSubscriber());
return instance;
}
void ZeroMQSubscriber::destroy() {
delete(this);
}
ZeroMQSubscriber::ZeroMQSubscriber() {
}
ZeroMQSubscriber::~ZeroMQSubscriber() {
LOG_INFO("deleting subscriber for %s", _channelName.c_str());
join();
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQSubscriber::init(shared_ptr<Configuration> config) {
_config = boost::static_pointer_cast<SubscriberConfig>(config);
_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());
assert(_uuid.length() == 36);
void* ctx = ZeroMQNode::getZeroMQContext();
(_socket = zmq_socket(ctx, ZMQ_SUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
(_closer = zmq_socket(ctx, ZMQ_PUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
assert(_channelName.size() > 0);
int hwm = NET_ZEROMQ_RCV_HWM;
zmq_setsockopt(_socket, ZMQ_RCVHWM, &hwm, sizeof(hwm)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
zmq_setsockopt(_socket, ZMQ_IDENTITY, _uuid.c_str(), _uuid.length()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
zmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _channelName.c_str(), _channelName.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
LOG_DEBUG("Subscribing to %s", _channelName.c_str());
zmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
LOG_DEBUG("Subscribing to %s", SHORT_UUID(_uuid).c_str());
// reconnection intervals
int reconnect_ivl_min = 100;
int reconnect_ivl_max = 200;
zmq_setsockopt (_socket, ZMQ_RECONNECT_IVL, &reconnect_ivl_min, sizeof(int)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
zmq_setsockopt (_socket, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl_max, sizeof(int)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
// make sure we can close the socket later
std::stringstream ss;
ss << "inproc://" << _uuid;
zmq_bind(_closer, ss.str().c_str()) && LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_connect: %s",zmq_strerror(errno));
LOG_INFO("creating subscriber for %s", _channelName.c_str());
start();
}
/**
* Break blocking zmq_recvmsg in ZeroMQSubscriber::run.
*/
void ZeroMQSubscriber::join() {
UMUNDO_LOCK(_mutex);
stop();
// this is a hack .. the thread is blocking at zmq_recvmsg - unblock by sending a message
zmq_msg_t channelEnvlp;
ZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());
zmq_sendmsg(_closer, &channelEnvlp, 0) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&channelEnvlp) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
Thread::join();
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQSubscriber::suspend() {
UMUNDO_LOCK(_mutex);
if (_isSuspended) {
UMUNDO_UNLOCK(_mutex);
return;
}
_isSuspended = true;
stop();
join();
_connections.clear();
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQSubscriber::resume() {
UMUNDO_LOCK(_mutex);
if (!_isSuspended) {
UMUNDO_UNLOCK(_mutex);
return;
}
_isSuspended = false;
init(_config);
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQSubscriber::run() {
int32_t more;
size_t more_size = sizeof(more);
zmq_pollitem_t pollItem;
pollItem.socket = _socket;
pollItem.events = ZMQ_POLLIN | ZMQ_POLLOUT;
while(isStarted()) {
int rc = 0;
{
ScopeLock lock(&_mutex);
rc = zmq_poll(&pollItem, 1, 30);
}
if (rc < 0) {
// an error occurred
switch(rc) {
case ETERM:
LOG_WARN("zmq_poll called with terminated socket");
break;
case EFAULT:
LOG_WARN("zmq_poll called with invalid items");
break;
case EINTR:
default:
break;
}
} else if (rc == 0) {
// Nothing to read - released lock
Thread::yield();
// Thread::sleepMs(5);
} if (rc > 0) {
// there is a message to be read
ScopeLock lock(&_mutex);
Message* msg = new Message();
while (1) {
// read and dispatch the whole message
zmq_msg_t message;
zmq_msg_init(&message) && LOG_WARN("zmq_msg_init: %s",zmq_strerror(errno));
while (zmq_recvmsg(_socket, &message, 0) < 0)
if (errno != EINTR)
LOG_WARN("zmq_recvmsg: %s",zmq_strerror(errno));
size_t msgSize = zmq_msg_size(&message);
if (!isStarted()) {
zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
return;
}
// last message contains actual data
zmq_getsockopt(_socket, ZMQ_RCVMORE, &more, &more_size) && LOG_WARN("zmq_getsockopt: %s",zmq_strerror(errno));
if (more) {
char* key = (char*)zmq_msg_data(&message);
char* value = ((char*)zmq_msg_data(&message) + strlen(key) + 1);
// is this the first message with the channelname?
if (strlen(key) + 1 == msgSize &&
msg->getMeta().find(key) == msg->getMeta().end()) {
msg->putMeta("channel", key);
} else {
assert(strlen(key) + strlen(value) + 2 == msgSize);
if (strlen(key) + strlen(value) + 2 != msgSize) {
LOG_WARN("Received malformed message %d + %d + 2 != %d", strlen(key), strlen(value), msgSize);
zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
break;
} else {
msg->putMeta(key, value);
}
}
zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
} else {
msg->setData((char*)zmq_msg_data(&message), msgSize);
zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
if (_receiver != NULL) {
_receiver->receive(msg);
delete(msg);
} else {
ScopeLock lock(&_msgMutex);
_msgQueue.push_back(msg);
}
break; // last message part
}
}
}
}
}
Message* ZeroMQSubscriber::getNextMsg() {
if (_receiver != NULL) {
LOG_WARN("getNextMsg not functional when a receiver is given");
return NULL;
}
ScopeLock lock(&_msgMutex);
Message* msg = NULL;
if (_msgQueue.size() > 0) {
msg = _msgQueue.front();
_msgQueue.pop_front();
}
return msg;
}
Message* ZeroMQSubscriber::peekNextMsg() {
if (_receiver != NULL) {
LOG_WARN("peekNextMsg not functional when a receiver is given");
return NULL;
}
ScopeLock lock(&_msgMutex);
Message* msg = NULL;
if (_msgQueue.size() > 0) {
msg = _msgQueue.front();
}
return msg;
}
void ZeroMQSubscriber::added(shared_ptr<PublisherStub> pub) {
std::stringstream ss;
if (pub->isInProcess() && false) {
ss << "inproc://" << pub->getUUID();
} else {
ss << pub->getTransport() << "://" << pub->getIP() << ":" << pub->getPort();
}
if (_connections.find(ss.str()) != _connections.end()) {
LOG_INFO("Already connected to %s", ss.str().c_str());
return;
}
ScopeLock lock(&_mutex);
LOG_INFO("%s subscribing at %s", _channelName.c_str(), ss.str().c_str());
zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_connect: %s", zmq_strerror(errno));
_connections.insert(ss.str());
}
void ZeroMQSubscriber::removed(shared_ptr<PublisherStub> pub) {
ScopeLock lock(&_mutex);
std::stringstream ss;
if (pub->isInProcess() && false) {
ss << "inproc://" << pub->getUUID();
} else {
ss << pub->getTransport() << "://" << pub->getIP() << ":" << pub->getPort();
}
if (_connections.find(ss.str()) == _connections.end()) {
LOG_INFO("Never connected to %s won't disconnect", ss.str().c_str());
return;
}
LOG_DEBUG("unsubscribing from %s", ss.str().c_str());
zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_disconnect: %s", zmq_strerror(errno));
_connections.erase(ss.str());
}
void ZeroMQSubscriber::changed(shared_ptr<PublisherStub>) {
// never called
}
}<|endoftext|> |
<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>
namespace RosettaStone::PlayerTasks
{
TaskID EndTurnTask::GetTaskID() const
{
return TaskID::END_TURN;
}
TaskStatus EndTurnTask::Impl(Player& player)
{
player.GetGame()->step = Step::MAIN_END;
player.GetGame()->MainEnd();
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::PlayerTasks
<commit_msg>refactor: Use 'nextStep' instead of 'step' and call ProcessNextStep()<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameManager.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>
namespace RosettaStone::PlayerTasks
{
TaskID EndTurnTask::GetTaskID() const
{
return TaskID::END_TURN;
}
TaskStatus EndTurnTask::Impl(Player& player)
{
auto game = player.GetGame();
game->nextStep = Step::MAIN_END;
GameManager::ProcessNextStep(*game, game->nextStep);
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::PlayerTasks
<|endoftext|> |
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "GraphTrack.h"
#include "GlCanvas.h"
GraphTrack::GraphTrack(TimeGraph* time_graph, std::string name)
: Track(time_graph), name_(std::move(name)) {}
void GraphTrack::Draw(GlCanvas* canvas, PickingMode picking_mode) {
Batcher* batcher = canvas->GetBatcher();
float trackWidth = canvas->GetWorldWidth();
const TimeGraphLayout& layout = time_graph_->GetLayout();
pos_[0] = canvas->GetWorldTopLeftX();
SetSize(trackWidth, GetHeight());
Track::Draw(canvas, picking_mode);
float x0 = pos_[0];
float x1 = x0 + size_[0];
float y0 = pos_[1];
float y1 = y0 - size_[1];
const Color kPickedColor(0, 128, 255, 128);
Color color = color_;
if (picked_) {
// TODO: Is this really used? Is picked_ even a thing?
color = kPickedColor;
}
float track_z = GlCanvas::kZValueTrack;
Box box(pos_, Vec2(size_[0], -size_[1]), track_z);
// Draw label with graph value at current mouse position.
const Color kWhiteColor(255, 255, 255, 255);
const Color kBlackColor(0, 0, 0, 255);
double graph_value = GetValueAtTime(time_graph_->GetCurrentMouseTimeNs());
int white_text_box_width =
canvas->GetTextRenderer().GetStringWidth(std::to_string(graph_value).c_str());
Vec2 white_text_box_size(white_text_box_width, layout.GetTextBoxHeight());
auto rightmost_x_position = canvas->GetWorldTopLeftX() + canvas->GetWorldWidth() -
layout.GetRightMargin() - layout.GetSliderWidth() -
white_text_box_size[0];
Vec2 white_text_box_position(
std::min(canvas->GetMouseX(), rightmost_x_position),
y0 - static_cast<float>((max_ - graph_value) * size_[1] / value_range_) -
white_text_box_size[1] / 2.f);
canvas->GetTextRenderer().AddText(std::to_string(graph_value).c_str(), white_text_box_position[0],
white_text_box_position[1] + layout.GetTextOffset(),
GlCanvas::kZValueTextUi, kBlackColor,
time_graph_->CalculateZoomedFontSize(), white_text_box_size[0]);
Box white_text_box(white_text_box_position, white_text_box_size, GlCanvas::kZValueUi);
batcher->AddBox(white_text_box, kWhiteColor);
batcher->AddBox(box, color, shared_from_this());
if (canvas->GetPickingManager().IsThisElementPicked(this)) {
color = Color(255, 255, 255, 255);
}
batcher->AddLine(pos_, Vec2(x1, y0), track_z, color, shared_from_this());
batcher->AddLine(Vec2(x1, y1), Vec2(x0, y1), track_z, color, shared_from_this());
const Color kLineColor(0, 128, 255, 128);
// Current time window
uint64_t min_ns = time_graph_->GetTickFromUs(time_graph_->GetMinTimeUs());
uint64_t max_ns = time_graph_->GetTickFromUs(time_graph_->GetMaxTimeUs());
double time_range = static_cast<float>(max_ns - min_ns);
if (values_.size() < 2 || time_range == 0) return;
auto it = values_.upper_bound(min_ns);
if (it == values_.end()) return;
if (it != values_.begin()) --it;
uint64_t previous_time = it->first;
double last_normalized_value = (it->second - min_) * inv_value_range_;
for (++it; it != values_.end(); ++it) {
if (previous_time > max_ns) break;
uint64_t time = it->first;
double normalized_value = (it->second - min_) * inv_value_range_;
float base_y = pos_[1] - size_[1];
float x0 = time_graph_->GetWorldFromTick(previous_time);
float x1 = time_graph_->GetWorldFromTick(time);
float y0 = base_y + static_cast<float>(last_normalized_value) * size_[1];
float y1 = base_y + static_cast<float>(normalized_value) * size_[1];
time_graph_->GetBatcher().AddLine(Vec2(x0, y0), Vec2(x1, y0), GlCanvas::kZValueText,
kLineColor);
time_graph_->GetBatcher().AddLine(Vec2(x1, y0), Vec2(x1, y1), GlCanvas::kZValueText,
kLineColor);
previous_time = time;
last_normalized_value = normalized_value;
}
}
void GraphTrack::AddValue(double value, uint64_t time) {
values_[time] = value;
max_ = std::max(max_, value);
min_ = std::min(min_, value);
value_range_ = max_ - min_;
if (value_range_ > 0) inv_value_range_ = 1.0 / value_range_;
}
double GraphTrack::GetValueAtTime(uint64_t time, double default_value) const {
auto iterator_lower = values_.upper_bound(time);
if (iterator_lower == values_.end() || iterator_lower == values_.begin()) {
return default_value;
}
--iterator_lower;
return iterator_lower->second;
}
float GraphTrack::GetHeight() const {
const TimeGraphLayout& layout = time_graph_->GetLayout();
float height = layout.GetTextBoxHeight() + layout.GetSpaceBetweenTracksAndThread() +
layout.GetEventTrackHeight() + layout.GetTrackBottomMargin();
return height;
}
<commit_msg>Fix bug when picking in GraphTrack<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "GraphTrack.h"
#include "GlCanvas.h"
GraphTrack::GraphTrack(TimeGraph* time_graph, std::string name)
: Track(time_graph), name_(std::move(name)) {}
void GraphTrack::Draw(GlCanvas* canvas, PickingMode picking_mode) {
Batcher* batcher = canvas->GetBatcher();
float trackWidth = canvas->GetWorldWidth();
const TimeGraphLayout& layout = time_graph_->GetLayout();
const bool picking = picking_mode != PickingMode::kNone;
pos_[0] = canvas->GetWorldTopLeftX();
SetSize(trackWidth, GetHeight());
Track::Draw(canvas, picking_mode);
float x0 = pos_[0];
float x1 = x0 + size_[0];
float y0 = pos_[1];
float y1 = y0 - size_[1];
const Color kPickedColor(0, 128, 255, 128);
Color color = color_;
if (picked_) {
// TODO: Is this really used? Is picked_ even a thing?
color = kPickedColor;
}
float track_z = GlCanvas::kZValueTrack;
Box box(pos_, Vec2(size_[0], -size_[1]), track_z);
// Draw label with graph value at current mouse position.
const Color kWhiteColor(255, 255, 255, 255);
const Color kBlackColor(0, 0, 0, 255);
double graph_value = GetValueAtTime(time_graph_->GetCurrentMouseTimeNs());
int white_text_box_width =
canvas->GetTextRenderer().GetStringWidth(std::to_string(graph_value).c_str());
Vec2 white_text_box_size(white_text_box_width, layout.GetTextBoxHeight());
auto rightmost_x_position = canvas->GetWorldTopLeftX() + canvas->GetWorldWidth() -
layout.GetRightMargin() - layout.GetSliderWidth() -
white_text_box_size[0];
Vec2 white_text_box_position(
std::min(canvas->GetMouseX(), rightmost_x_position),
y0 - static_cast<float>((max_ - graph_value) * size_[1] / value_range_) -
white_text_box_size[1] / 2.f);
if (!picking) {
canvas->GetTextRenderer().AddText(
std::to_string(graph_value).c_str(), white_text_box_position[0],
white_text_box_position[1] + layout.GetTextOffset(), GlCanvas::kZValueTextUi, kBlackColor,
time_graph_->CalculateZoomedFontSize(), white_text_box_size[0]);
Box white_text_box(white_text_box_position, white_text_box_size, GlCanvas::kZValueUi);
batcher->AddBox(white_text_box, kWhiteColor);
}
batcher->AddBox(box, color, shared_from_this());
if (canvas->GetPickingManager().IsThisElementPicked(this)) {
color = Color(255, 255, 255, 255);
}
batcher->AddLine(pos_, Vec2(x1, y0), track_z, color, shared_from_this());
batcher->AddLine(Vec2(x1, y1), Vec2(x0, y1), track_z, color, shared_from_this());
const Color kLineColor(0, 128, 255, 128);
if (!picking) {
// Current time window
uint64_t min_ns = time_graph_->GetTickFromUs(time_graph_->GetMinTimeUs());
uint64_t max_ns = time_graph_->GetTickFromUs(time_graph_->GetMaxTimeUs());
double time_range = static_cast<float>(max_ns - min_ns);
if (values_.size() < 2 || time_range == 0) return;
auto it = values_.upper_bound(min_ns);
if (it == values_.end()) return;
if (it != values_.begin()) --it;
uint64_t previous_time = it->first;
double last_normalized_value = (it->second - min_) * inv_value_range_;
for (++it; it != values_.end(); ++it) {
if (previous_time > max_ns) break;
uint64_t time = it->first;
double normalized_value = (it->second - min_) * inv_value_range_;
float base_y = pos_[1] - size_[1];
float x0 = time_graph_->GetWorldFromTick(previous_time);
float x1 = time_graph_->GetWorldFromTick(time);
float y0 = base_y + static_cast<float>(last_normalized_value) * size_[1];
float y1 = base_y + static_cast<float>(normalized_value) * size_[1];
time_graph_->GetBatcher().AddLine(Vec2(x0, y0), Vec2(x1, y0), GlCanvas::kZValueText,
kLineColor);
time_graph_->GetBatcher().AddLine(Vec2(x1, y0), Vec2(x1, y1), GlCanvas::kZValueText,
kLineColor);
previous_time = time;
last_normalized_value = normalized_value;
}
}
}
void GraphTrack::AddValue(double value, uint64_t time) {
values_[time] = value;
max_ = std::max(max_, value);
min_ = std::min(min_, value);
value_range_ = max_ - min_;
if (value_range_ > 0) inv_value_range_ = 1.0 / value_range_;
}
double GraphTrack::GetValueAtTime(uint64_t time, double default_value) const {
auto iterator_lower = values_.upper_bound(time);
if (iterator_lower == values_.end() || iterator_lower == values_.begin()) {
return default_value;
}
--iterator_lower;
return iterator_lower->second;
}
float GraphTrack::GetHeight() const {
const TimeGraphLayout& layout = time_graph_->GetLayout();
float height = layout.GetTextBoxHeight() + layout.GetSpaceBetweenTracksAndThread() +
layout.GetEventTrackHeight() + layout.GetTrackBottomMargin();
return height;
}
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <vector>
#if HAVE_DUNE_GEOMETRY
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/grid/common/genericreferenceelements.hh>
#endif
#include <dune/common/shared_ptr.hh>
#include <dune/common/fvector.hh>
#include <dune/grid/common/backuprestore.hh>
#include <dune/grid/common/grid.hh>
#include <dune/grid/common/gridview.hh>
#include <dune/grid/common/entity.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/fem/namespace.hh>
#ifdef HAVE_DUNE_FEM
#include <dune/fem/function/common/discretefunction.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#endif
#include <dune/grid/io/file/vtk/function.hh>
#include <boost/range/iterator_range.hpp>
namespace Dune {
namespace Stuff {
template <class ViewTraits>
class StrategyBase {
public:
typedef typename ViewTraits::template Codim<0>::Entity EntityType;
typedef typename EntityType::Geometry::LocalCoordinate LocalCoordinateType;
typedef typename EntityType::Geometry::GlobalCoordinate GlobalCoordinateType;
typedef std::vector<typename EntityType::EntityPointer> EntityPointerVector;
};
template <class ViewTraits>
class InlevelSearchStrategy : public StrategyBase<ViewTraits> {
typedef StrategyBase<ViewTraits> BaseType;
typedef GenericReferenceElements< typename BaseType::LocalCoordinateType::value_type,
BaseType::LocalCoordinateType::dimension >
RefElementType;
typedef typename Dune::GridView<ViewTraits>::template Codim< 0 >::Iterator IteratorType;
inline bool check_add(const typename BaseType::EntityType& entity,
const typename BaseType::GlobalCoordinateType& point,
typename BaseType::EntityPointerVector& ret) const {
const auto& geometry = entity.geometry();
const auto& refElement = RefElementType::general(geometry.type());
if(refElement.checkInside(geometry.local(point)))
{
ret.emplace_back(entity);
return true;
}
return false;
}
public:
InlevelSearchStrategy(const Dune::GridView<ViewTraits>& gridview)
: gridview_(gridview)
, it_last_(gridview_.template begin< 0 >())
{}
template <class QuadpointContainerType>
typename BaseType::EntityPointerVector operator() (const QuadpointContainerType& quad_points)
{
const auto max_size = quad_points.size();
const IteratorType begin = gridview_.template begin< 0 >();
const IteratorType end = gridview_.template end< 0 >();
std::vector<typename BaseType::EntityType::EntityPointer> ret;
for(const auto& point : quad_points)
{
IteratorType it_current = it_last_;
bool it_reset = true;
for(; it_current != end && ret.size() < max_size; ++it_current)
{
if(check_add(*it_current, point, ret)) {
it_reset = false;
it_last_ = it_current;
break;
}
}
if(!it_reset)
continue;
for(it_current = begin;
it_current != it_last_ && ret.size() < max_size;
++it_current)
{
if(check_add(*it_current, point, ret)) {
it_reset = false;
it_last_ = it_current;
break;
}
}
assert(!it_reset);
}
return ret;
}
private:
const Dune::GridView<ViewTraits>& gridview_;
IteratorType it_last_;
};
template <class ViewTraits>
class HierarchicSearchStrategy : public StrategyBase<ViewTraits> {
typedef StrategyBase<ViewTraits> BaseType;
const Dune::GridView<ViewTraits>& gridview_;
const int start_level_;
public:
HierarchicSearchStrategy(const Dune::GridView<ViewTraits>& gridview)
: gridview_(gridview)
, start_level_(0)
{}
template <class QuadpointContainerType>
typename BaseType::EntityPointerVector
operator() (const QuadpointContainerType& quad_points) const
{
auto level = std::min(gridview_.grid().maxLevel(), start_level_);
auto range = DSC::viewRange(gridview_.grid().levelView(level));
return process(quad_points, range);
}
private:
template <class QuadpointContainerType, class RangeType>
std::vector<typename BaseType::EntityType::EntityPointer>
process(const QuadpointContainerType& quad_points,
const RangeType& range) const
{
typedef GenericReferenceElements< typename BaseType::LocalCoordinateType::value_type,
BaseType::LocalCoordinateType::dimension > RefElementType;
std::vector<typename BaseType::EntityType::EntityPointer> ret;
for(const auto& my_ent : range) {
const int my_level = my_ent.level();
const auto& geometry = my_ent.geometry();
const auto& refElement = RefElementType::general(geometry.type());
for(const auto& point : quad_points)
{
if(refElement.checkInside(geometry.local(point)))
{
//if I cannot descend further add this entity even if it's not my view
if(gridview_.grid().maxLevel() <= my_level || gridview_.contains(my_ent)) {
ret.emplace_back(my_ent);
}
else {
const auto h_end = my_ent.hend(my_level+1);
const auto h_begin = my_ent.hbegin(my_level+1);
const auto h_range = boost::make_iterator_range(h_begin, h_end);
const auto kids = process(QuadpointContainerType(1, point), h_range);
ret.insert(ret.end(), kids.begin(), kids.end());
}
}
}
}
return ret;
}
};
template <template <class> class SearchStrategy = InlevelSearchStrategy>
class HeterogenousProjection
{
public:
#ifdef HAVE_DUNE_FEM
template < class SourceDFImp, class TargetDFImp >
static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,
Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)
{
typedef SearchStrategy<typename SourceDFImp::GridType::LeafGridView::Traits> SearchStrategyType;
typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;
typedef typename TargetDFImp::DofType TargetDofType;
static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;
const auto& space = target.space();
const auto infinity = std::numeric_limits< TargetDofType >::infinity();
// set all DoFs to infinity
const auto dend = target.dend();
for( auto dit = target.dbegin(); dit != dend; ++dit )
*dit = infinity;
SearchStrategyType search(source.gridPart().grid().leafView());
const auto endit = space.end();
for(auto it = space.begin(); it != endit ; ++it)
{
const auto& target_entity = *it;
const auto& target_geometry = target_entity.geometry();
auto target_local_function = target.localFunction(target_entity);
const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);
const auto quadNop = target_lagrangepoint_set.nop();
typename TargetDiscreteFunctionSpaceType::RangeType source_value;
std::vector<typename TargetDiscreteFunctionSpaceType::DomainType> global_quads(quadNop);
for(size_t qP = 0; qP < quadNop ; ++qP) {
global_quads[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));
}
const auto evaluation_entities = search(global_quads);
assert(evaluation_entities.size() == global_quads.size());
int k = 0;
for(size_t qP = 0; qP < quadNop ; ++qP)
{
if(std::isinf(target_local_function[ k ]))
{
const auto& global_point = global_quads[qP];
// evaluate source function
const auto source_entity = evaluation_entities[qP];
const auto& source_geometry = source_entity->geometry();
const auto& source_local_point = source_geometry.local(global_point);
const auto& source_local_function = source.localFunction(*source_entity);
source_local_function.evaluate(source_local_point, source_value);
for(int i = 0; i < target_dimRange; ++i, ++k)
target_local_function[k] = source_value[i];
}
else
k += target_dimRange;
}
}
} // ... project(...)
#endif // HAVE_DUNE_FEM
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
<commit_msg>[discretefunction.projection] make use of grid.search<commit_after>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
#include <dune/common/fvector.hh>
#include <dune/grid/common/backuprestore.hh>
#include <dune/grid/common/grid.hh>
#include <dune/grid/common/entity.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/fem/namespace.hh>
#ifdef HAVE_DUNE_FEM
#include <dune/fem/function/common/discretefunction.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#endif
#include <dune/grid/io/file/vtk/function.hh>
#include <dune/stuff/grid/search.hh>
namespace Dune {
namespace Stuff {
#ifdef HAVE_DUNE_FEM
template< template< class > class SearchStrategy = Grid::EntityInlevelSearch >
class HeterogenousProjection
{
public:
template < class SourceDFImp, class TargetDFImp >
static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,
Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)
{
typedef SearchStrategy<typename SourceDFImp::GridType::LeafGridView> SearchStrategyType;
typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;
typedef typename TargetDFImp::DofType TargetDofType;
static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;
const auto& space = target.space();
const auto infinity = std::numeric_limits< TargetDofType >::infinity();
// set all DoFs to infinity
const auto dend = target.dend();
for( auto dit = target.dbegin(); dit != dend; ++dit )
*dit = infinity;
SearchStrategyType search(source.gridPart().grid().leafView());
const auto endit = space.end();
for(auto it = space.begin(); it != endit ; ++it)
{
const auto& target_entity = *it;
const auto& target_geometry = target_entity.geometry();
auto target_local_function = target.localFunction(target_entity);
const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);
const auto quadNop = target_lagrangepoint_set.nop();
typename TargetDiscreteFunctionSpaceType::RangeType source_value;
std::vector<typename TargetDiscreteFunctionSpaceType::DomainType> global_quads(quadNop);
for(size_t qP = 0; qP < quadNop ; ++qP) {
global_quads[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));
}
const auto evaluation_entities = search(global_quads);
assert(evaluation_entities.size() == global_quads.size());
int k = 0;
for(size_t qP = 0; qP < quadNop ; ++qP)
{
if(std::isinf(target_local_function[ k ]))
{
const auto& global_point = global_quads[qP];
// evaluate source function
const auto source_entity = evaluation_entities[qP];
const auto& source_geometry = source_entity->geometry();
const auto& source_local_point = source_geometry.local(global_point);
const auto& source_local_function = source.localFunction(*source_entity);
source_local_function.evaluate(source_local_point, source_value);
for(int i = 0; i < target_dimRange; ++i, ++k)
target_local_function[k] = source_value[i];
}
else
k += target_dimRange;
}
}
} // ... project(...)
}; // class HeterogenousProjection
#endif // HAVE_DUNE_FEM
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: datalistener.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-03-23 11:50:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_DATALISTENER_HXX
#define _SVX_DATALISTENER_HXX
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_
#include <com/sun/star/frame/XFrameActionListener.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_DOM_EVENTS_XEVENTLISTENER_HPP_
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#endif
//............................................................................
namespace svxform
{
//............................................................................
class DataNavigatorWindow;
typedef cppu::WeakImplHelper3<
com::sun::star::container::XContainerListener,
com::sun::star::frame::XFrameActionListener,
com::sun::star::xml::dom::events::XEventListener > DataListener_t;
class DataListener : public DataListener_t
{
private:
DataNavigatorWindow* m_pNaviWin;
public:
DataListener( DataNavigatorWindow* pNaviWin );
protected:
~DataListener();
public:
// XContainerListener
virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
// XFrameActionListener
virtual void SAL_CALL frameAction( const ::com::sun::star::frame::FrameActionEvent& Action ) throw (::com::sun::star::uno::RuntimeException);
// xml::dom::events::XEventListener
virtual void SAL_CALL handleEvent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::events::XEvent >& evt ) throw (::com::sun::star::uno::RuntimeException);
// lang::XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);
};
//............................................................................
} // namespace svxform
//............................................................................
#endif // #ifndef _SVX_DATALISTENER_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.252); FILE MERGED 2005/09/05 14:25:01 rt 1.3.252.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: datalistener.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:11:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVX_DATALISTENER_HXX
#define _SVX_DATALISTENER_HXX
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_
#include <com/sun/star/frame/XFrameActionListener.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_DOM_EVENTS_XEVENTLISTENER_HPP_
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#endif
//............................................................................
namespace svxform
{
//............................................................................
class DataNavigatorWindow;
typedef cppu::WeakImplHelper3<
com::sun::star::container::XContainerListener,
com::sun::star::frame::XFrameActionListener,
com::sun::star::xml::dom::events::XEventListener > DataListener_t;
class DataListener : public DataListener_t
{
private:
DataNavigatorWindow* m_pNaviWin;
public:
DataListener( DataNavigatorWindow* pNaviWin );
protected:
~DataListener();
public:
// XContainerListener
virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
// XFrameActionListener
virtual void SAL_CALL frameAction( const ::com::sun::star::frame::FrameActionEvent& Action ) throw (::com::sun::star::uno::RuntimeException);
// xml::dom::events::XEventListener
virtual void SAL_CALL handleEvent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::events::XEvent >& evt ) throw (::com::sun::star::uno::RuntimeException);
// lang::XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);
};
//............................................................................
} // namespace svxform
//............................................................................
#endif // #ifndef _SVX_DATALISTENER_HXX
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2020 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "PairingCommand.h"
#include "platform/PlatformManager.h"
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <crypto/CHIPCryptoPAL.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/support/logging/CHIPLogging.h>
#include <protocols/secure_channel/PASESession.h>
#include <setup_payload/ManualSetupPayloadParser.h>
#include <setup_payload/QRCodeSetupPayloadParser.h>
using namespace ::chip;
using namespace ::chip::Controller;
CHIP_ERROR PairingCommand::RunCommand()
{
CurrentCommissioner().RegisterPairingDelegate(this);
return RunInternal(mNodeId);
}
CHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)
{
CHIP_ERROR err = CHIP_NO_ERROR;
switch (mPairingMode)
{
case PairingMode::None:
err = Unpair(remoteId);
break;
case PairingMode::QRCode:
err = PairWithCode(remoteId);
break;
case PairingMode::ManualCode:
err = PairWithCode(remoteId);
break;
case PairingMode::QRCodePaseOnly:
case PairingMode::ManualCodePaseOnly:
err = PaseWithCode(remoteId);
break;
case PairingMode::Ble:
err = Pair(remoteId, PeerAddress::BLE());
break;
case PairingMode::OnNetwork:
err = PairWithMdns(remoteId);
break;
case PairingMode::SoftAP:
err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));
break;
case PairingMode::Ethernet:
err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));
break;
}
return err;
}
CommissioningParameters PairingCommand::GetCommissioningParameters()
{
switch (mNetworkType)
{
case PairingNetworkType::WiFi:
return CommissioningParameters().SetWiFiCredentials(Controller::WiFiCredentials(mSSID, mPassword));
case PairingNetworkType::Thread:
return CommissioningParameters().SetThreadOperationalDataset(mOperationalDataset);
case PairingNetworkType::Ethernet:
case PairingNetworkType::None:
return CommissioningParameters();
}
return CommissioningParameters();
}
CHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)
{
return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload);
}
CHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)
{
CommissioningParameters commissioningParams = GetCommissioningParameters();
return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams);
}
CHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)
{
RendezvousParameters params =
RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address);
CommissioningParameters commissioningParams = GetCommissioningParameters();
return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);
}
CHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)
{
Dnssd::DiscoveryFilter filter(mFilterType);
switch (mFilterType)
{
case chip::Dnssd::DiscoveryFilterType::kNone:
break;
case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:
case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:
case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:
case chip::Dnssd::DiscoveryFilterType::kVendorId:
case chip::Dnssd::DiscoveryFilterType::kDeviceType:
filter.code = mDiscoveryFilterCode;
break;
case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:
break;
case chip::Dnssd::DiscoveryFilterType::kCommissioner:
filter.code = 1;
break;
case chip::Dnssd::DiscoveryFilterType::kInstanceName:
filter.code = 0;
filter.instanceName = mDiscoveryFilterInstanceName;
break;
}
CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);
return CurrentCommissioner().DiscoverCommissionableNodes(filter);
}
CHIP_ERROR PairingCommand::Unpair(NodeId remoteId)
{
CHIP_ERROR err = CurrentCommissioner().UnpairDevice(remoteId);
SetCommandExitStatus(err);
return err;
}
void PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)
{
switch (status)
{
case DevicePairingDelegate::Status::SecurePairingSuccess:
ChipLogProgress(chipTool, "Secure Pairing Success");
break;
case DevicePairingDelegate::Status::SecurePairingFailed:
ChipLogError(chipTool, "Secure Pairing Failed");
break;
}
}
void PairingCommand::OnPairingComplete(CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Pairing Success");
if (mPairingMode == PairingMode::QRCodePaseOnly || mPairingMode == PairingMode::ManualCodePaseOnly)
{
SetCommandExitStatus(err);
}
}
else
{
ChipLogProgress(chipTool, "Pairing Failure: %s", ErrorStr(err));
}
if (err != CHIP_NO_ERROR)
{
SetCommandExitStatus(err);
}
}
void PairingCommand::OnPairingDeleted(CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Pairing Deleted Success");
}
else
{
ChipLogProgress(chipTool, "Pairing Deleted Failure: %s", ErrorStr(err));
}
SetCommandExitStatus(err);
}
void PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Device commissioning completed with success");
}
else
{
ChipLogProgress(chipTool, "Device commissioning Failure: %s", ErrorStr(err));
}
SetCommandExitStatus(err);
}
void PairingCommand::OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData)
{
const uint16_t port = nodeData.port;
char buf[chip::Inet::IPAddress::kMaxStringLength];
nodeData.ipAddress[0].ToString(buf);
ChipLogProgress(chipTool, "Discovered Device: %s:%u", buf, port);
// Stop Mdns discovery. Is it the right method ?
CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);
Inet::InterfaceId interfaceId = nodeData.ipAddress[0].IsIPv6LinkLocal() ? nodeData.interfaceId : Inet::InterfaceId::Null();
PeerAddress peerAddress = PeerAddress::UDP(nodeData.ipAddress[0], port, interfaceId);
CHIP_ERROR err = Pair(mNodeId, peerAddress);
if (CHIP_NO_ERROR != err)
{
SetCommandExitStatus(err);
}
}
<commit_msg>[chip-tool] Filter out non-commissionable devices (#16221)<commit_after>/*
* Copyright (c) 2020 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "PairingCommand.h"
#include "platform/PlatformManager.h"
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <crypto/CHIPCryptoPAL.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/support/logging/CHIPLogging.h>
#include <protocols/secure_channel/PASESession.h>
#include <setup_payload/ManualSetupPayloadParser.h>
#include <setup_payload/QRCodeSetupPayloadParser.h>
using namespace ::chip;
using namespace ::chip::Controller;
CHIP_ERROR PairingCommand::RunCommand()
{
CurrentCommissioner().RegisterPairingDelegate(this);
return RunInternal(mNodeId);
}
CHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)
{
CHIP_ERROR err = CHIP_NO_ERROR;
switch (mPairingMode)
{
case PairingMode::None:
err = Unpair(remoteId);
break;
case PairingMode::QRCode:
err = PairWithCode(remoteId);
break;
case PairingMode::ManualCode:
err = PairWithCode(remoteId);
break;
case PairingMode::QRCodePaseOnly:
case PairingMode::ManualCodePaseOnly:
err = PaseWithCode(remoteId);
break;
case PairingMode::Ble:
err = Pair(remoteId, PeerAddress::BLE());
break;
case PairingMode::OnNetwork:
err = PairWithMdns(remoteId);
break;
case PairingMode::SoftAP:
err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));
break;
case PairingMode::Ethernet:
err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));
break;
}
return err;
}
CommissioningParameters PairingCommand::GetCommissioningParameters()
{
switch (mNetworkType)
{
case PairingNetworkType::WiFi:
return CommissioningParameters().SetWiFiCredentials(Controller::WiFiCredentials(mSSID, mPassword));
case PairingNetworkType::Thread:
return CommissioningParameters().SetThreadOperationalDataset(mOperationalDataset);
case PairingNetworkType::Ethernet:
case PairingNetworkType::None:
return CommissioningParameters();
}
return CommissioningParameters();
}
CHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)
{
return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload);
}
CHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)
{
CommissioningParameters commissioningParams = GetCommissioningParameters();
return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams);
}
CHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)
{
RendezvousParameters params =
RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address);
CommissioningParameters commissioningParams = GetCommissioningParameters();
return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);
}
CHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)
{
Dnssd::DiscoveryFilter filter(mFilterType);
switch (mFilterType)
{
case chip::Dnssd::DiscoveryFilterType::kNone:
break;
case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:
case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:
case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:
case chip::Dnssd::DiscoveryFilterType::kVendorId:
case chip::Dnssd::DiscoveryFilterType::kDeviceType:
filter.code = mDiscoveryFilterCode;
break;
case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:
break;
case chip::Dnssd::DiscoveryFilterType::kCommissioner:
filter.code = 1;
break;
case chip::Dnssd::DiscoveryFilterType::kInstanceName:
filter.code = 0;
filter.instanceName = mDiscoveryFilterInstanceName;
break;
}
CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);
return CurrentCommissioner().DiscoverCommissionableNodes(filter);
}
CHIP_ERROR PairingCommand::Unpair(NodeId remoteId)
{
CHIP_ERROR err = CurrentCommissioner().UnpairDevice(remoteId);
SetCommandExitStatus(err);
return err;
}
void PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)
{
switch (status)
{
case DevicePairingDelegate::Status::SecurePairingSuccess:
ChipLogProgress(chipTool, "Secure Pairing Success");
break;
case DevicePairingDelegate::Status::SecurePairingFailed:
ChipLogError(chipTool, "Secure Pairing Failed");
break;
}
}
void PairingCommand::OnPairingComplete(CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Pairing Success");
if (mPairingMode == PairingMode::QRCodePaseOnly || mPairingMode == PairingMode::ManualCodePaseOnly)
{
SetCommandExitStatus(err);
}
}
else
{
ChipLogProgress(chipTool, "Pairing Failure: %s", ErrorStr(err));
}
if (err != CHIP_NO_ERROR)
{
SetCommandExitStatus(err);
}
}
void PairingCommand::OnPairingDeleted(CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Pairing Deleted Success");
}
else
{
ChipLogProgress(chipTool, "Pairing Deleted Failure: %s", ErrorStr(err));
}
SetCommandExitStatus(err);
}
void PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Device commissioning completed with success");
}
else
{
ChipLogProgress(chipTool, "Device commissioning Failure: %s", ErrorStr(err));
}
SetCommandExitStatus(err);
}
void PairingCommand::OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData)
{
// Ignore nodes with closed comissioning window
VerifyOrReturn(nodeData.commissioningMode != 0);
const uint16_t port = nodeData.port;
char buf[chip::Inet::IPAddress::kMaxStringLength];
nodeData.ipAddress[0].ToString(buf);
ChipLogProgress(chipTool, "Discovered Device: %s:%u", buf, port);
// Stop Mdns discovery. Is it the right method ?
CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);
Inet::InterfaceId interfaceId = nodeData.ipAddress[0].IsIPv6LinkLocal() ? nodeData.interfaceId : Inet::InterfaceId::Null();
PeerAddress peerAddress = PeerAddress::UDP(nodeData.ipAddress[0], port, interfaceId);
CHIP_ERROR err = Pair(mNodeId, peerAddress);
if (CHIP_NO_ERROR != err)
{
SetCommandExitStatus(err);
}
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/init.h>
#include <shogun/base/ParameterMap.h>
using namespace shogun;
void print_message(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void print_value(CSGParamInfo* key, CParameterMap* map)
{
CSGParamInfo* current=map->get(key);
SG_SPRINT("key: ");
key->print();
SG_SPRINT("value: ");
if (current)
current->print();
else
SG_SPRINT("no element\n");
SG_SPRINT("\n");
SG_UNREF(current);
}
int main(int argc, char **argv)
{
init_shogun(&print_message, &print_message, &print_message);
CParameterMap* map=new CParameterMap();
EContainerType cfrom=CT_SCALAR;
EContainerType cto=CT_MATRIX;
EStructType sfrom=ST_NONE;
EStructType sto=ST_STRING;
EPrimitiveType pfrom=PT_BOOL;
EPrimitiveType pto=PT_SGOBJECT;
map->put(new CSGParamInfo("1", cfrom, sfrom, pfrom),
new CSGParamInfo("eins", cto, sto, pto));
map->put(new CSGParamInfo("2", cfrom, sfrom, pfrom),
new CSGParamInfo("zwei", cto, sto, pto));
map->put(new CSGParamInfo("3", cfrom, sfrom, pfrom),
new CSGParamInfo("drei", cto, sto, pto));
map->put(new CSGParamInfo("4", cfrom, sfrom, pfrom),
new CSGParamInfo("vier", cto, sto, pto));
CSGParamInfo* key;
key=new CSGParamInfo("1", cfrom, sfrom, pfrom);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("2", cfrom, sfrom, pfrom);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("2", cto, sfrom, pfrom);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("2", cfrom, sto, pfrom);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("2", cfrom, sfrom, pto);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("5", cfrom, sfrom, pfrom);
print_value(key, map);
SG_UNREF(key);
SG_UNREF(map);
exit_shogun();
return 0;
}
<commit_msg>applied changes in parameter map to example<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/init.h>
#include <shogun/base/ParameterMap.h>
using namespace shogun;
void print_message(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void print_value(CSGParamInfo* key, CParameterMap* map)
{
CSGParamInfo* current=map->get(key);
key->print_param_info();
SG_SPRINT("value: ");
if (current)
current->print_param_info();
else
SG_SPRINT("no element\n");
SG_SPRINT("\n");
SG_UNREF(current);
}
int main(int argc, char **argv)
{
init_shogun(&print_message, &print_message, &print_message);
CParameterMap* map=new CParameterMap();
EContainerType cfrom=CT_SCALAR;
EContainerType cto=CT_MATRIX;
EStructType sfrom=ST_NONE;
EStructType sto=ST_STRING;
EPrimitiveType pfrom=PT_BOOL;
EPrimitiveType pto=PT_SGOBJECT;
map->put(new CSGParamInfo("2", cfrom, sfrom, pfrom),
new CSGParamInfo("zwei", cto, sto, pto));
map->put(new CSGParamInfo("1", cfrom, sfrom, pfrom),
new CSGParamInfo("eins", cto, sto, pto));
map->put(new CSGParamInfo("4", cfrom, sfrom, pfrom),
new CSGParamInfo("vier", cto, sto, pto));
map->put(new CSGParamInfo("3", cfrom, sfrom, pfrom),
new CSGParamInfo("drei", cto, sto, pto));
SG_SPRINT("before finalization:\n");
map->print_map();
map->finalize_map();
SG_SPRINT("\n\nafter finalization:\n");
map->print_map();
CSGParamInfo* key;
SG_SPRINT("\n\ntesting map\n");
key=new CSGParamInfo("1", cfrom, sfrom, pfrom);
SG_REF(key);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("2", cfrom, sfrom, pfrom);
SG_REF(key);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("2", cto, sfrom, pfrom);
SG_REF(key);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("2", cfrom, sto, pfrom);
SG_REF(key);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("2", cfrom, sfrom, pto);
SG_REF(key);
print_value(key, map);
SG_UNREF(key);
key=new CSGParamInfo("5", cfrom, sfrom, pfrom);
SG_REF(key);
print_value(key, map);
SG_UNREF(key);
SG_UNREF(map);
exit_shogun();
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2018-2020, University of Edinburgh, University of Oxford
// 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 nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include <exotica_ik_solver/ik_solver.h>
REGISTER_MOTIONSOLVER_TYPE("IKSolver", exotica::IKSolver)
namespace exotica
{
void IKSolver::SpecifyProblem(PlanningProblemPtr pointer)
{
if (pointer->type() != "exotica::UnconstrainedEndPoseProblem")
{
ThrowNamed("This IKSolver can't solve problem of type '" << pointer->type() << "'!");
}
MotionSolver::SpecifyProblem(pointer);
prob_ = std::static_pointer_cast<UnconstrainedEndPoseProblem>(pointer);
W_inv_ = prob_->W.inverse();
// Check dimension of W_ as this is a public member of the problem, and thus, can be edited by error.
if (W_inv_.rows() != prob_->N || W_inv_.cols() != prob_->N)
ThrowNamed("Size of W incorrect: (" << W_inv_.rows() << ", " << W_inv_.cols() << "), when expected: (" << prob_->N << ", " << prob_->N << ")");
// Warn if deprecated MaxStep configuration detected:
if (parameters_.MaxStep != 0.0 && GetNumberOfMaxIterations() != 1)
WARNING_NAMED("IKSolver", "Deprecated configuration detected: MaxStep (given: " << parameters_.MaxStep << ") only works if MaxIterations == 1 (given: " << GetNumberOfMaxIterations() << ")");
// Set up backtracking line-search coefficients
alpha_space_ = Eigen::VectorXd::LinSpaced(10, 1.0, 0.1);
lambda_ = parameters_.RegularizationRate;
th_stepinc_ = parameters_.ThresholdRegularizationIncrease;
th_stepdec_ = parameters_.ThresholdRegularizationDecrease;
th_stop_ = parameters_.GradientToleranceConvergenceThreshold;
// Allocate variables
q_.resize(prob_->N);
qd_.resize(prob_->N);
yd_.resize(prob_->cost.length_jacobian);
cost_jacobian_.resize(prob_->cost.length_jacobian, prob_->N);
J_pseudo_inverse_.resize(prob_->N, prob_->cost.length_jacobian);
J_tmp_.resize(prob_->cost.length_jacobian, prob_->cost.length_jacobian);
}
void IKSolver::Solve(Eigen::MatrixXd& solution)
{
if (!prob_) ThrowNamed("Solver has not been initialized!");
Timer timer;
prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);
lambda_ = parameters_.RegularizationRate;
q_ = prob_->ApplyStartState();
if (prob_->q_nominal.rows() == prob_->N)
{
WARNING("Nominal state regularization is no longer supported - please use a JointPose task-map.");
}
int i;
for (i = 0; i < GetNumberOfMaxIterations(); ++i)
{
prob_->Update(q_);
error_ = prob_->GetScalarCost();
prob_->SetCostEvolution(i, error_);
// Absolute function tolerance check
if (error_ < parameters_.Tolerance)
{
prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
break;
}
yd_.noalias() = prob_->cost.S * prob_->cost.ydiff;
cost_jacobian_.noalias() = prob_->cost.S * prob_->cost.jacobian;
// Weighted Regularized Pseudo-Inverse
// J_pseudo_inverse_ = W_inv_ * cost_jacobian_.transpose() * ( cost_jacobian_ * W_inv_ * cost_jacobian_.transpose() + C_ ).inverse();
bool decomposition_ok = false;
while (!decomposition_ok)
{
J_tmp_.noalias() = cost_jacobian_ * W_inv_ * cost_jacobian_.transpose();
J_tmp_.diagonal().array() += lambda_; // Add regularisation
J_decomposition_.compute(J_tmp_);
if (J_decomposition_.info() != Eigen::Success)
{
IncreaseRegularization();
if (lambda_ > parameters_.MaximumRegularization)
{
WARNING("Divergence in Cholesky decomposition :-(");
prob_->termination_criterion = TerminationCriterion::Divergence;
break;
}
// ThrowPretty("Error during matrix decomposition of J_tmp_ (lambda=" << lambda_ << "):\n"
// << J_tmp_);
}
else
{
decomposition_ok = true;
}
}
J_tmp_.noalias() = J_decomposition_.solve(Eigen::MatrixXd::Identity(prob_->cost.length_jacobian, prob_->cost.length_jacobian)); // Inverse
J_pseudo_inverse_.noalias() = W_inv_ * cost_jacobian_.transpose() * J_tmp_;
qd_.noalias() = J_pseudo_inverse_ * yd_;
// Support for a maximum step, e.g., when used as real-time, interactive IK
if (GetNumberOfMaxIterations() == 1 && parameters_.MaxStep != 0.0)
{
ScaleToStepSize(qd_);
}
// Line search
for (int ai = 0; ai < alpha_space_.size(); ++ai)
{
steplength_ = alpha_space_(ai);
Eigen::VectorXd q_tmp = q_ - steplength_ * qd_;
prob_->Update(q_tmp);
if (prob_->GetScalarCost() < error_)
{
q_ = q_tmp;
qd_ *= steplength_;
break;
}
}
// Step tolerance parameter
step_ = qd_.squaredNorm();
// Gradient tolerance
stop_ = cost_jacobian_.norm();
// Debug output
if (debug_) PrintDebug(i);
// Check step tolerance
if (step_ < parameters_.StepToleranceConvergenceThreshold)
{
prob_->termination_criterion = TerminationCriterion::StepTolerance;
break;
}
// Check gradient tolerance (convergence)
if (stop_ < parameters_.GradientToleranceConvergenceThreshold)
{
prob_->termination_criterion = TerminationCriterion::GradientTolerance;
break;
}
// Adapt regularization based on step-length
if (steplength_ > th_stepdec_)
{
DecreaseRegularization();
}
if (steplength_ <= th_stepinc_)
{
IncreaseRegularization();
if (lambda_ == regmax_)
{
prob_->termination_criterion = TerminationCriterion::Divergence;
break;
}
}
}
// Check if we ran out of iterations
if (i == GetNumberOfMaxIterations())
{
prob_->termination_criterion = TerminationCriterion::IterationLimit;
}
else
{
if (debug_) PrintDebug(i);
}
if (debug_)
{
switch (prob_->termination_criterion)
{
case TerminationCriterion::GradientTolerance:
HIGHLIGHT_NAMED("IKSolver", "Reached convergence (" << std::scientific << stop_ << " < " << parameters_.GradientToleranceConvergenceThreshold << ")");
break;
case TerminationCriterion::FunctionTolerance:
HIGHLIGHT_NAMED("IKSolver", "Reached absolute function tolerance (" << std::scientific << error_ << " < " << parameters_.Tolerance << ")");
break;
case TerminationCriterion::StepTolerance:
HIGHLIGHT_NAMED("IKSolver", "Reached step tolerance (" << std::scientific << step_ << " < " << parameters_.StepToleranceConvergenceThreshold << ")");
break;
case TerminationCriterion::Divergence:
WARNING_NAMED("IKSolver", "Regularization exceeds maximum regularization: " << lambda_ << " > " << regmax_);
break;
case TerminationCriterion::IterationLimit:
HIGHLIGHT_NAMED("IKSolver", "Reached iteration limit.");
break;
default:
break;
}
}
solution.resize(1, prob_->N);
solution.row(0) = q_.transpose();
planning_time_ = timer.GetDuration();
}
void IKSolver::ScaleToStepSize(Eigen::VectorXdRef xd)
{
const double max_vel = xd.cwiseAbs().maxCoeff();
if (max_vel > parameters_.MaxStep)
{
xd = xd * parameters_.MaxStep / max_vel;
}
}
} // namespace exotica
<commit_msg>[exotica_ik_solver] Do not exit for high regularisation<commit_after>//
// Copyright (c) 2018-2020, University of Edinburgh, University of Oxford
// 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 nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include <exotica_ik_solver/ik_solver.h>
REGISTER_MOTIONSOLVER_TYPE("IKSolver", exotica::IKSolver)
namespace exotica
{
void IKSolver::SpecifyProblem(PlanningProblemPtr pointer)
{
if (pointer->type() != "exotica::UnconstrainedEndPoseProblem")
{
ThrowNamed("This IKSolver can't solve problem of type '" << pointer->type() << "'!");
}
MotionSolver::SpecifyProblem(pointer);
prob_ = std::static_pointer_cast<UnconstrainedEndPoseProblem>(pointer);
W_inv_ = prob_->W.inverse();
// Check dimension of W_ as this is a public member of the problem, and thus, can be edited by error.
if (W_inv_.rows() != prob_->N || W_inv_.cols() != prob_->N)
ThrowNamed("Size of W incorrect: (" << W_inv_.rows() << ", " << W_inv_.cols() << "), when expected: (" << prob_->N << ", " << prob_->N << ")");
// Warn if deprecated MaxStep configuration detected:
if (parameters_.MaxStep != 0.0 && GetNumberOfMaxIterations() != 1)
WARNING_NAMED("IKSolver", "Deprecated configuration detected: MaxStep (given: " << parameters_.MaxStep << ") only works if MaxIterations == 1 (given: " << GetNumberOfMaxIterations() << ")");
// Set up backtracking line-search coefficients
alpha_space_ = Eigen::VectorXd::LinSpaced(10, 1.0, 0.1);
lambda_ = parameters_.RegularizationRate;
th_stepinc_ = parameters_.ThresholdRegularizationIncrease;
th_stepdec_ = parameters_.ThresholdRegularizationDecrease;
th_stop_ = parameters_.GradientToleranceConvergenceThreshold;
// Allocate variables
q_.resize(prob_->N);
qd_.resize(prob_->N);
yd_.resize(prob_->cost.length_jacobian);
cost_jacobian_.resize(prob_->cost.length_jacobian, prob_->N);
J_pseudo_inverse_.resize(prob_->N, prob_->cost.length_jacobian);
J_tmp_.resize(prob_->cost.length_jacobian, prob_->cost.length_jacobian);
}
void IKSolver::Solve(Eigen::MatrixXd& solution)
{
if (!prob_) ThrowNamed("Solver has not been initialized!");
Timer timer;
prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);
lambda_ = parameters_.RegularizationRate;
q_ = prob_->ApplyStartState();
if (prob_->q_nominal.rows() == prob_->N)
{
WARNING("Nominal state regularization is no longer supported - please use a JointPose task-map.");
}
int i;
for (i = 0; i < GetNumberOfMaxIterations(); ++i)
{
prob_->Update(q_);
error_ = prob_->GetScalarCost();
prob_->SetCostEvolution(i, error_);
// Absolute function tolerance check
if (error_ < parameters_.Tolerance)
{
prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
break;
}
yd_.noalias() = prob_->cost.S * prob_->cost.ydiff;
cost_jacobian_.noalias() = prob_->cost.S * prob_->cost.jacobian;
// Weighted Regularized Pseudo-Inverse
// J_pseudo_inverse_ = W_inv_ * cost_jacobian_.transpose() * ( cost_jacobian_ * W_inv_ * cost_jacobian_.transpose() + C_ ).inverse();
bool decomposition_ok = false;
while (!decomposition_ok)
{
J_tmp_.noalias() = cost_jacobian_ * W_inv_ * cost_jacobian_.transpose();
J_tmp_.diagonal().array() += lambda_; // Add regularisation
J_decomposition_.compute(J_tmp_);
if (J_decomposition_.info() != Eigen::Success)
{
IncreaseRegularization();
if (lambda_ > parameters_.MaximumRegularization)
{
WARNING("Divergence in Cholesky decomposition :-(");
prob_->termination_criterion = TerminationCriterion::Divergence;
break;
}
// ThrowPretty("Error during matrix decomposition of J_tmp_ (lambda=" << lambda_ << "):\n"
// << J_tmp_);
}
else
{
decomposition_ok = true;
}
}
J_tmp_.noalias() = J_decomposition_.solve(Eigen::MatrixXd::Identity(prob_->cost.length_jacobian, prob_->cost.length_jacobian)); // Inverse
J_pseudo_inverse_.noalias() = W_inv_ * cost_jacobian_.transpose() * J_tmp_;
qd_.noalias() = J_pseudo_inverse_ * yd_;
// Support for a maximum step, e.g., when used as real-time, interactive IK
if (GetNumberOfMaxIterations() == 1 && parameters_.MaxStep != 0.0)
{
ScaleToStepSize(qd_);
}
// Line search
for (int ai = 0; ai < alpha_space_.size(); ++ai)
{
steplength_ = alpha_space_(ai);
Eigen::VectorXd q_tmp = q_ - steplength_ * qd_;
prob_->Update(q_tmp);
if (prob_->GetScalarCost() < error_)
{
q_ = q_tmp;
qd_ *= steplength_;
break;
}
}
// Step tolerance parameter
step_ = qd_.squaredNorm();
// Gradient tolerance
stop_ = cost_jacobian_.norm();
// Debug output
if (debug_) PrintDebug(i);
// Check step tolerance
if (step_ < parameters_.StepToleranceConvergenceThreshold)
{
prob_->termination_criterion = TerminationCriterion::StepTolerance;
break;
}
// Check gradient tolerance (convergence)
if (stop_ < parameters_.GradientToleranceConvergenceThreshold)
{
prob_->termination_criterion = TerminationCriterion::GradientTolerance;
break;
}
// Adapt regularization based on step-length
if (steplength_ > th_stepdec_)
{
DecreaseRegularization();
}
if (steplength_ <= th_stepinc_)
{
IncreaseRegularization();
// if (lambda_ == regmax_)
// {
// prob_->termination_criterion = TerminationCriterion::Divergence;
// break;
// }
}
}
// Check if we ran out of iterations
if (i == GetNumberOfMaxIterations())
{
prob_->termination_criterion = TerminationCriterion::IterationLimit;
}
else
{
if (debug_) PrintDebug(i);
}
if (debug_)
{
switch (prob_->termination_criterion)
{
case TerminationCriterion::GradientTolerance:
HIGHLIGHT_NAMED("IKSolver", "Reached convergence (" << std::scientific << stop_ << " < " << parameters_.GradientToleranceConvergenceThreshold << ")");
break;
case TerminationCriterion::FunctionTolerance:
HIGHLIGHT_NAMED("IKSolver", "Reached absolute function tolerance (" << std::scientific << error_ << " < " << parameters_.Tolerance << ")");
break;
case TerminationCriterion::StepTolerance:
HIGHLIGHT_NAMED("IKSolver", "Reached step tolerance (" << std::scientific << step_ << " < " << parameters_.StepToleranceConvergenceThreshold << ")");
break;
case TerminationCriterion::Divergence:
WARNING_NAMED("IKSolver", "Regularization exceeds maximum regularization: " << lambda_ << " > " << regmax_);
break;
case TerminationCriterion::IterationLimit:
HIGHLIGHT_NAMED("IKSolver", "Reached iteration limit.");
break;
default:
break;
}
}
solution.resize(1, prob_->N);
solution.row(0) = q_.transpose();
planning_time_ = timer.GetDuration();
}
void IKSolver::ScaleToStepSize(Eigen::VectorXdRef xd)
{
const double max_vel = xd.cwiseAbs().maxCoeff();
if (max_vel > parameters_.MaxStep)
{
xd = xd * parameters_.MaxStep / max_vel;
}
}
} // namespace exotica
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: swuipardlg.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:06:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SWUI_PARDLG_HXX
#define _SWUI_PARDLG_HXX
#include "pardlg.hxx"
class SwParaDlg: public SfxTabDialog
{
SwView& rView;
USHORT nHtmlMode;
BYTE nDlgMode;
BOOL bDrawParaDlg;
void PageCreated(USHORT nID, SfxTabPage& rPage);
public:
SwParaDlg( Window *pParent,
SwView& rVw,
const SfxItemSet&,
BYTE nDialogMode,
const String *pCollName = 0,
BOOL bDraw = FALSE,
UINT16 nDefPage = 0);
~SwParaDlg();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.1202); FILE MERGED 2008/03/31 16:58:40 rt 1.4.1202.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: swuipardlg.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SWUI_PARDLG_HXX
#define _SWUI_PARDLG_HXX
#include "pardlg.hxx"
class SwParaDlg: public SfxTabDialog
{
SwView& rView;
USHORT nHtmlMode;
BYTE nDlgMode;
BOOL bDrawParaDlg;
void PageCreated(USHORT nID, SfxTabPage& rPage);
public:
SwParaDlg( Window *pParent,
SwView& rVw,
const SfxItemSet&,
BYTE nDialogMode,
const String *pCollName = 0,
BOOL bDraw = FALSE,
UINT16 nDefPage = 0);
~SwParaDlg();
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: shdwcrsr.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:56:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#include "swtypes.hxx"
#include "shdwcrsr.hxx"
SwShadowCursor::~SwShadowCursor()
{
if( USHRT_MAX != nOldMode )
DrawCrsr( aOldPt, nOldHeight, nOldMode );
}
void SwShadowCursor::SetPos( const Point& rPt, long nHeight, USHORT nMode )
{
Point aPt( pWin->LogicToPixel( rPt ));
nHeight = pWin->LogicToPixel( Size( 0, nHeight )).Height();
if( aOldPt != aPt || nOldHeight != nHeight || nOldMode != nMode )
{
if( USHRT_MAX != nOldMode )
DrawCrsr( aOldPt, nOldHeight, nOldMode );
DrawCrsr( aPt, nHeight, nMode );
nOldMode = nMode;
nOldHeight = nHeight;
aOldPt = aPt;
}
}
void SwShadowCursor::DrawTri( const Point& rPt, long nHeight, BOOL bLeft )
{
USHORT nLineDiff = ( nHeight / 2 );
USHORT nLineDiffHalf = nLineDiff / 2;
// Punkt oben
Point aPt1( (bLeft ? rPt.X() - 3 : rPt.X() + 3),
rPt.Y() + nLineDiffHalf );
// Punkt unten
Point aPt2( aPt1.X(), aPt1.Y() + nHeight - nLineDiff - 1 );
short nDiff = bLeft ? -1 : 1;
while( aPt1.Y() <= aPt2.Y() )
{
pWin->DrawLine( aPt1, aPt2 );
aPt1.Y()++, aPt2.Y()--;
aPt2.X() = aPt1.X() += nDiff;
}
}
void SwShadowCursor::DrawCrsr( const Point& rPt, long nHeight, USHORT nMode )
{
nHeight = (((nHeight / 4)+1) * 4) + 1;
pWin->Push();
pWin->SetMapMode( MAP_PIXEL );
pWin->SetRasterOp( ROP_XOR );
pWin->SetLineColor( Color( aCol.GetColor() ^ COL_WHITE ) );
// 1. der Strich:
pWin->DrawLine( Point( rPt.X(), rPt.Y() + 1),
Point( rPt.X(), rPt.Y() - 2 + nHeight ));
// 2. das Dreieck
if( HORI_LEFT == nMode || HORI_CENTER == nMode ) // Pfeil nach rechts
DrawTri( rPt, nHeight, FALSE );
if( HORI_RIGHT == nMode || HORI_CENTER == nMode ) // Pfeil nach links
DrawTri( rPt, nHeight, TRUE );
pWin->Pop();
}
void SwShadowCursor::Paint()
{
if( USHRT_MAX != nOldMode )
DrawCrsr( aOldPt, nOldHeight, nOldMode );
}
Rectangle SwShadowCursor::GetRect() const
{
long nH = nOldHeight;
Point aPt( aOldPt );
nH = (((nH / 4)+1) * 4) + 1;
USHORT nWidth = nH / 4 + 3 + 1;
Size aSz( nWidth, nH );
if( HORI_RIGHT == nOldMode )
aPt.X() -= aSz.Width();
else if( HORI_CENTER == nOldMode )
{
aPt.X() -= aSz.Width();
aSz.Width() *= 2;
}
return pWin->PixelToLogic( Rectangle( aPt, aSz ) );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.1254); FILE MERGED 2005/09/05 13:48:16 rt 1.3.1254.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shdwcrsr.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 11:30:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#include "swtypes.hxx"
#include "shdwcrsr.hxx"
SwShadowCursor::~SwShadowCursor()
{
if( USHRT_MAX != nOldMode )
DrawCrsr( aOldPt, nOldHeight, nOldMode );
}
void SwShadowCursor::SetPos( const Point& rPt, long nHeight, USHORT nMode )
{
Point aPt( pWin->LogicToPixel( rPt ));
nHeight = pWin->LogicToPixel( Size( 0, nHeight )).Height();
if( aOldPt != aPt || nOldHeight != nHeight || nOldMode != nMode )
{
if( USHRT_MAX != nOldMode )
DrawCrsr( aOldPt, nOldHeight, nOldMode );
DrawCrsr( aPt, nHeight, nMode );
nOldMode = nMode;
nOldHeight = nHeight;
aOldPt = aPt;
}
}
void SwShadowCursor::DrawTri( const Point& rPt, long nHeight, BOOL bLeft )
{
USHORT nLineDiff = ( nHeight / 2 );
USHORT nLineDiffHalf = nLineDiff / 2;
// Punkt oben
Point aPt1( (bLeft ? rPt.X() - 3 : rPt.X() + 3),
rPt.Y() + nLineDiffHalf );
// Punkt unten
Point aPt2( aPt1.X(), aPt1.Y() + nHeight - nLineDiff - 1 );
short nDiff = bLeft ? -1 : 1;
while( aPt1.Y() <= aPt2.Y() )
{
pWin->DrawLine( aPt1, aPt2 );
aPt1.Y()++, aPt2.Y()--;
aPt2.X() = aPt1.X() += nDiff;
}
}
void SwShadowCursor::DrawCrsr( const Point& rPt, long nHeight, USHORT nMode )
{
nHeight = (((nHeight / 4)+1) * 4) + 1;
pWin->Push();
pWin->SetMapMode( MAP_PIXEL );
pWin->SetRasterOp( ROP_XOR );
pWin->SetLineColor( Color( aCol.GetColor() ^ COL_WHITE ) );
// 1. der Strich:
pWin->DrawLine( Point( rPt.X(), rPt.Y() + 1),
Point( rPt.X(), rPt.Y() - 2 + nHeight ));
// 2. das Dreieck
if( HORI_LEFT == nMode || HORI_CENTER == nMode ) // Pfeil nach rechts
DrawTri( rPt, nHeight, FALSE );
if( HORI_RIGHT == nMode || HORI_CENTER == nMode ) // Pfeil nach links
DrawTri( rPt, nHeight, TRUE );
pWin->Pop();
}
void SwShadowCursor::Paint()
{
if( USHRT_MAX != nOldMode )
DrawCrsr( aOldPt, nOldHeight, nOldMode );
}
Rectangle SwShadowCursor::GetRect() const
{
long nH = nOldHeight;
Point aPt( aOldPt );
nH = (((nH / 4)+1) * 4) + 1;
USHORT nWidth = nH / 4 + 3 + 1;
Size aSz( nWidth, nH );
if( HORI_RIGHT == nOldMode )
aPt.X() -= aSz.Width();
else if( HORI_CENTER == nOldMode )
{
aPt.X() -= aSz.Width();
aSz.Width() *= 2;
}
return pWin->PixelToLogic( Rectangle( aPt, aSz ) );
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "rocksdb/cache.h"
#include <vector>
#include <string>
#include <iostream>
#include "util/coding.h"
#include "util/testharness.h"
namespace rocksdb {
// Conversions between numeric keys/values and the types expected by Cache.
static std::string EncodeKey(int k) {
std::string result;
PutFixed32(&result, k);
return result;
}
static int DecodeKey(const Slice& k) {
assert(k.size() == 4);
return DecodeFixed32(k.data());
}
static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }
static int DecodeValue(void* v) {
return static_cast<int>(reinterpret_cast<uintptr_t>(v));
}
class CacheTest {
public:
static CacheTest* current_;
static void Deleter(const Slice& key, void* v) {
current_->deleted_keys_.push_back(DecodeKey(key));
current_->deleted_values_.push_back(DecodeValue(v));
}
static const int kCacheSize = 1000;
static const int kNumShardBits = 4;
static const int kRemoveScanCountLimit = 16;
static const int kCacheSize2 = 100;
static const int kNumShardBits2 = 2;
static const int kRemoveScanCountLimit2 = 200;
std::vector<int> deleted_keys_;
std::vector<int> deleted_values_;
shared_ptr<Cache> cache_;
shared_ptr<Cache> cache2_;
CacheTest() :
cache_(NewLRUCache(kCacheSize, kNumShardBits, kRemoveScanCountLimit)),
cache2_(NewLRUCache(kCacheSize2, kNumShardBits2,
kRemoveScanCountLimit2)) {
current_ = this;
}
~CacheTest() {
}
int Lookup(shared_ptr<Cache> cache, int key) {
Cache::Handle* handle = cache->Lookup(EncodeKey(key));
const int r = (handle == nullptr) ? -1 : DecodeValue(cache->Value(handle));
if (handle != nullptr) {
cache->Release(handle);
}
return r;
}
void Insert(shared_ptr<Cache> cache, int key, int value, int charge = 1) {
cache->Release(cache->Insert(EncodeKey(key), EncodeValue(value), charge,
&CacheTest::Deleter));
}
void Erase(shared_ptr<Cache> cache, int key) {
cache->Erase(EncodeKey(key));
}
int Lookup(int key) {
return Lookup(cache_, key);
}
void Insert(int key, int value, int charge = 1) {
Insert(cache_, key, value, charge);
}
void Erase(int key) {
Erase(cache_, key);
}
int Lookup2(int key) {
return Lookup(cache2_, key);
}
void Insert2(int key, int value, int charge = 1) {
Insert(cache2_, key, value, charge);
}
void Erase2(int key) {
Erase(cache2_, key);
}
};
CacheTest* CacheTest::current_;
namespace {
void dumbDeleter(const Slice& key, void* value) { }
} // namespace
TEST(CacheTest, UsageTest) {
// cache is shared_ptr and will be automatically cleaned up.
const uint64_t kCapacity = 100000;
auto cache = NewLRUCache(kCapacity, 8, 200);
size_t usage = 0;
const char* value = "abcdef";
// make sure everything will be cached
for (int i = 1; i < 100; ++i) {
std::string key(i, 'a');
auto kv_size = key.size() + 5;
cache->Release(
cache->Insert(key, (void*)value, kv_size, dumbDeleter)
);
usage += kv_size;
ASSERT_EQ(usage, cache->GetUsage());
}
// make sure the cache will be overloaded
for (uint64_t i = 1; i < kCapacity; ++i) {
auto key = ToString(i);
cache->Release(
cache->Insert(key, (void*)value, key.size() + 5, dumbDeleter)
);
}
// the usage should be close to the capacity
ASSERT_GT(kCapacity, cache->GetUsage());
ASSERT_LT(kCapacity * 0.95, cache->GetUsage());
}
TEST(CacheTest, HitAndMiss) {
ASSERT_EQ(-1, Lookup(100));
Insert(100, 101);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(200, 201);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(100, 102);
ASSERT_EQ(102, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
ASSERT_EQ(1U, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
}
TEST(CacheTest, Erase) {
Erase(200);
ASSERT_EQ(0U, deleted_keys_.size());
Insert(100, 101);
Insert(200, 201);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1U, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1U, deleted_keys_.size());
}
TEST(CacheTest, EntriesArePinned) {
Insert(100, 101);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));
ASSERT_EQ(1, cache_->GetUsage());
Insert(100, 102);
Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));
ASSERT_EQ(0U, deleted_keys_.size());
ASSERT_EQ(2, cache_->GetUsage());
cache_->Release(h1);
ASSERT_EQ(1U, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
ASSERT_EQ(1, cache_->GetUsage());
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(1U, deleted_keys_.size());
ASSERT_EQ(1, cache_->GetUsage());
cache_->Release(h2);
ASSERT_EQ(2U, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[1]);
ASSERT_EQ(102, deleted_values_[1]);
ASSERT_EQ(0, cache_->GetUsage());
}
TEST(CacheTest, EvictionPolicy) {
Insert(100, 101);
Insert(200, 201);
// Frequently used entry must be kept around
for (int i = 0; i < kCacheSize + 100; i++) {
Insert(1000+i, 2000+i);
ASSERT_EQ(2000+i, Lookup(1000+i));
ASSERT_EQ(101, Lookup(100));
}
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
}
TEST(CacheTest, EvictionPolicyRef) {
Insert(100, 101);
Insert(101, 102);
Insert(102, 103);
Insert(103, 104);
Insert(200, 101);
Insert(201, 102);
Insert(202, 103);
Insert(203, 104);
Cache::Handle* h201 = cache_->Lookup(EncodeKey(200));
Cache::Handle* h202 = cache_->Lookup(EncodeKey(201));
Cache::Handle* h203 = cache_->Lookup(EncodeKey(202));
Cache::Handle* h204 = cache_->Lookup(EncodeKey(203));
Insert(300, 101);
Insert(301, 102);
Insert(302, 103);
Insert(303, 104);
// Insert entries much more than Cache capacity
for (int i = 0; i < kCacheSize + 100; i++) {
Insert(1000 + i, 2000 + i);
}
// Check whether the entries inserted in the beginning
// are evicted. Ones without extra ref are evicted and
// those with are not.
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(-1, Lookup(101));
ASSERT_EQ(-1, Lookup(102));
ASSERT_EQ(-1, Lookup(103));
ASSERT_EQ(-1, Lookup(300));
ASSERT_EQ(-1, Lookup(301));
ASSERT_EQ(-1, Lookup(302));
ASSERT_EQ(-1, Lookup(303));
ASSERT_EQ(101, Lookup(200));
ASSERT_EQ(102, Lookup(201));
ASSERT_EQ(103, Lookup(202));
ASSERT_EQ(104, Lookup(203));
// Cleaning up all the handles
cache_->Release(h201);
cache_->Release(h202);
cache_->Release(h203);
cache_->Release(h204);
}
TEST(CacheTest, ErasedHandleState) {
// insert a key and get two handles
Insert(100, 1000);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(h1, h2);
ASSERT_EQ(DecodeValue(cache_->Value(h1)), 1000);
ASSERT_EQ(DecodeValue(cache_->Value(h2)), 1000);
// delete the key from the cache
Erase(100);
// can no longer find in the cache
ASSERT_EQ(-1, Lookup(100));
// release one handle
cache_->Release(h1);
// still can't find in cache
ASSERT_EQ(-1, Lookup(100));
cache_->Release(h2);
}
TEST(CacheTest, HeavyEntries) {
// Add a bunch of light and heavy entries and then count the combined
// size of items still in the cache, which must be approximately the
// same as the total capacity.
const int kLight = 1;
const int kHeavy = 10;
int added = 0;
int index = 0;
while (added < 2*kCacheSize) {
const int weight = (index & 1) ? kLight : kHeavy;
Insert(index, 1000+index, weight);
added += weight;
index++;
}
int cached_weight = 0;
for (int i = 0; i < index; i++) {
const int weight = (i & 1 ? kLight : kHeavy);
int r = Lookup(i);
if (r >= 0) {
cached_weight += weight;
ASSERT_EQ(1000+i, r);
}
}
ASSERT_LE(cached_weight, kCacheSize + kCacheSize/10);
}
TEST(CacheTest, NewId) {
uint64_t a = cache_->NewId();
uint64_t b = cache_->NewId();
ASSERT_NE(a, b);
}
class Value {
private:
int v_;
public:
explicit Value(int v) : v_(v) { }
~Value() { std::cout << v_ << " is destructed\n"; }
};
namespace {
void deleter(const Slice& key, void* value) {
delete static_cast<Value *>(value);
}
} // namespace
TEST(CacheTest, OverCapacity) {
int n = 10;
// a LRUCache with n entries and one shard only
std::shared_ptr<Cache> cache = NewLRUCache(n, 0);
std::vector<Cache::Handle*> handles(n+1);
// Insert n+1 entries, but not releasing.
for (int i = 0; i < n+1; i++) {
std::string key = ToString(i+1);
handles[i] = cache->Insert(key, new Value(i+1), 1, &deleter);
}
// Guess what's in the cache now?
for (int i = 0; i < n+1; i++) {
std::string key = ToString(i+1);
auto h = cache->Lookup(key);
std::cout << key << (h?" found\n":" not found\n");
ASSERT_TRUE(h != nullptr);
if (h) cache->Release(h);
}
// the cache is over capacity since nothing could be evicted
ASSERT_EQ(n + 1, cache->GetUsage());
for (int i = 0; i < n+1; i++) {
cache->Release(handles[i]);
}
// cache is under capacity now since elements were released
ASSERT_EQ(n, cache->GetUsage());
// element 0 is evicted and the rest is there
// This is consistent with the LRU policy since the element 0
// was released first
for (int i = 0; i < n+1; i++) {
std::string key = ToString(i+1);
auto h = cache->Lookup(key);
if (h) {
ASSERT_NE(i, 0);
cache->Release(h);
} else {
ASSERT_EQ(i, 0);
}
}
}
namespace {
std::vector<std::pair<int, int>> callback_state;
void callback(void* entry, size_t charge) {
callback_state.push_back({DecodeValue(entry), static_cast<int>(charge)});
}
};
TEST(CacheTest, ApplyToAllCacheEntiresTest) {
std::vector<std::pair<int, int>> inserted;
callback_state.clear();
for (int i = 0; i < 10; ++i) {
Insert(i, i * 2, i + 1);
inserted.push_back({i * 2, i + 1});
}
cache_->ApplyToAllCacheEntries(callback, true);
sort(inserted.begin(), inserted.end());
sort(callback_state.begin(), callback_state.end());
ASSERT_TRUE(inserted == callback_state);
}
} // namespace rocksdb
int main(int argc, char** argv) {
return rocksdb::test::RunAllTests();
}
<commit_msg>Fix Mac compile errors on util/cache_test.cc<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "rocksdb/cache.h"
#include <vector>
#include <string>
#include <iostream>
#include "util/coding.h"
#include "util/testharness.h"
namespace rocksdb {
// Conversions between numeric keys/values and the types expected by Cache.
static std::string EncodeKey(int k) {
std::string result;
PutFixed32(&result, k);
return result;
}
static int DecodeKey(const Slice& k) {
assert(k.size() == 4);
return DecodeFixed32(k.data());
}
static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }
static int DecodeValue(void* v) {
return static_cast<int>(reinterpret_cast<uintptr_t>(v));
}
class CacheTest {
public:
static CacheTest* current_;
static void Deleter(const Slice& key, void* v) {
current_->deleted_keys_.push_back(DecodeKey(key));
current_->deleted_values_.push_back(DecodeValue(v));
}
static const int kCacheSize = 1000;
static const int kNumShardBits = 4;
static const int kRemoveScanCountLimit = 16;
static const int kCacheSize2 = 100;
static const int kNumShardBits2 = 2;
static const int kRemoveScanCountLimit2 = 200;
std::vector<int> deleted_keys_;
std::vector<int> deleted_values_;
shared_ptr<Cache> cache_;
shared_ptr<Cache> cache2_;
CacheTest() :
cache_(NewLRUCache(kCacheSize, kNumShardBits, kRemoveScanCountLimit)),
cache2_(NewLRUCache(kCacheSize2, kNumShardBits2,
kRemoveScanCountLimit2)) {
current_ = this;
}
~CacheTest() {
}
int Lookup(shared_ptr<Cache> cache, int key) {
Cache::Handle* handle = cache->Lookup(EncodeKey(key));
const int r = (handle == nullptr) ? -1 : DecodeValue(cache->Value(handle));
if (handle != nullptr) {
cache->Release(handle);
}
return r;
}
void Insert(shared_ptr<Cache> cache, int key, int value, int charge = 1) {
cache->Release(cache->Insert(EncodeKey(key), EncodeValue(value), charge,
&CacheTest::Deleter));
}
void Erase(shared_ptr<Cache> cache, int key) {
cache->Erase(EncodeKey(key));
}
int Lookup(int key) {
return Lookup(cache_, key);
}
void Insert(int key, int value, int charge = 1) {
Insert(cache_, key, value, charge);
}
void Erase(int key) {
Erase(cache_, key);
}
int Lookup2(int key) {
return Lookup(cache2_, key);
}
void Insert2(int key, int value, int charge = 1) {
Insert(cache2_, key, value, charge);
}
void Erase2(int key) {
Erase(cache2_, key);
}
};
CacheTest* CacheTest::current_;
namespace {
void dumbDeleter(const Slice& key, void* value) { }
} // namespace
TEST(CacheTest, UsageTest) {
// cache is shared_ptr and will be automatically cleaned up.
const uint64_t kCapacity = 100000;
auto cache = NewLRUCache(kCapacity, 8, 200);
size_t usage = 0;
const char* value = "abcdef";
// make sure everything will be cached
for (int i = 1; i < 100; ++i) {
std::string key(i, 'a');
auto kv_size = key.size() + 5;
cache->Release(
cache->Insert(key, (void*)value, kv_size, dumbDeleter)
);
usage += kv_size;
ASSERT_EQ(usage, cache->GetUsage());
}
// make sure the cache will be overloaded
for (uint64_t i = 1; i < kCapacity; ++i) {
auto key = ToString(i);
cache->Release(
cache->Insert(key, (void*)value, key.size() + 5, dumbDeleter)
);
}
// the usage should be close to the capacity
ASSERT_GT(kCapacity, cache->GetUsage());
ASSERT_LT(kCapacity * 0.95, cache->GetUsage());
}
TEST(CacheTest, HitAndMiss) {
ASSERT_EQ(-1, Lookup(100));
Insert(100, 101);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(200, 201);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(100, 102);
ASSERT_EQ(102, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
ASSERT_EQ(1U, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
}
TEST(CacheTest, Erase) {
Erase(200);
ASSERT_EQ(0U, deleted_keys_.size());
Insert(100, 101);
Insert(200, 201);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1U, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1U, deleted_keys_.size());
}
TEST(CacheTest, EntriesArePinned) {
Insert(100, 101);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));
ASSERT_EQ(1U, cache_->GetUsage());
Insert(100, 102);
Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));
ASSERT_EQ(0U, deleted_keys_.size());
ASSERT_EQ(2U, cache_->GetUsage());
cache_->Release(h1);
ASSERT_EQ(1U, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
ASSERT_EQ(1U, cache_->GetUsage());
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(1U, deleted_keys_.size());
ASSERT_EQ(1U, cache_->GetUsage());
cache_->Release(h2);
ASSERT_EQ(2U, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[1]);
ASSERT_EQ(102, deleted_values_[1]);
ASSERT_EQ(0U, cache_->GetUsage());
}
TEST(CacheTest, EvictionPolicy) {
Insert(100, 101);
Insert(200, 201);
// Frequently used entry must be kept around
for (int i = 0; i < kCacheSize + 100; i++) {
Insert(1000+i, 2000+i);
ASSERT_EQ(2000+i, Lookup(1000+i));
ASSERT_EQ(101, Lookup(100));
}
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
}
TEST(CacheTest, EvictionPolicyRef) {
Insert(100, 101);
Insert(101, 102);
Insert(102, 103);
Insert(103, 104);
Insert(200, 101);
Insert(201, 102);
Insert(202, 103);
Insert(203, 104);
Cache::Handle* h201 = cache_->Lookup(EncodeKey(200));
Cache::Handle* h202 = cache_->Lookup(EncodeKey(201));
Cache::Handle* h203 = cache_->Lookup(EncodeKey(202));
Cache::Handle* h204 = cache_->Lookup(EncodeKey(203));
Insert(300, 101);
Insert(301, 102);
Insert(302, 103);
Insert(303, 104);
// Insert entries much more than Cache capacity
for (int i = 0; i < kCacheSize + 100; i++) {
Insert(1000 + i, 2000 + i);
}
// Check whether the entries inserted in the beginning
// are evicted. Ones without extra ref are evicted and
// those with are not.
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(-1, Lookup(101));
ASSERT_EQ(-1, Lookup(102));
ASSERT_EQ(-1, Lookup(103));
ASSERT_EQ(-1, Lookup(300));
ASSERT_EQ(-1, Lookup(301));
ASSERT_EQ(-1, Lookup(302));
ASSERT_EQ(-1, Lookup(303));
ASSERT_EQ(101, Lookup(200));
ASSERT_EQ(102, Lookup(201));
ASSERT_EQ(103, Lookup(202));
ASSERT_EQ(104, Lookup(203));
// Cleaning up all the handles
cache_->Release(h201);
cache_->Release(h202);
cache_->Release(h203);
cache_->Release(h204);
}
TEST(CacheTest, ErasedHandleState) {
// insert a key and get two handles
Insert(100, 1000);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(h1, h2);
ASSERT_EQ(DecodeValue(cache_->Value(h1)), 1000);
ASSERT_EQ(DecodeValue(cache_->Value(h2)), 1000);
// delete the key from the cache
Erase(100);
// can no longer find in the cache
ASSERT_EQ(-1, Lookup(100));
// release one handle
cache_->Release(h1);
// still can't find in cache
ASSERT_EQ(-1, Lookup(100));
cache_->Release(h2);
}
TEST(CacheTest, HeavyEntries) {
// Add a bunch of light and heavy entries and then count the combined
// size of items still in the cache, which must be approximately the
// same as the total capacity.
const int kLight = 1;
const int kHeavy = 10;
int added = 0;
int index = 0;
while (added < 2*kCacheSize) {
const int weight = (index & 1) ? kLight : kHeavy;
Insert(index, 1000+index, weight);
added += weight;
index++;
}
int cached_weight = 0;
for (int i = 0; i < index; i++) {
const int weight = (i & 1 ? kLight : kHeavy);
int r = Lookup(i);
if (r >= 0) {
cached_weight += weight;
ASSERT_EQ(1000+i, r);
}
}
ASSERT_LE(cached_weight, kCacheSize + kCacheSize/10);
}
TEST(CacheTest, NewId) {
uint64_t a = cache_->NewId();
uint64_t b = cache_->NewId();
ASSERT_NE(a, b);
}
class Value {
private:
size_t v_;
public:
explicit Value(size_t v) : v_(v) { }
~Value() { std::cout << v_ << " is destructed\n"; }
};
namespace {
void deleter(const Slice& key, void* value) {
delete static_cast<Value *>(value);
}
} // namespace
TEST(CacheTest, OverCapacity) {
size_t n = 10;
// a LRUCache with n entries and one shard only
std::shared_ptr<Cache> cache = NewLRUCache(n, 0);
std::vector<Cache::Handle*> handles(n+1);
// Insert n+1 entries, but not releasing.
for (size_t i = 0; i < n + 1; i++) {
std::string key = ToString(i+1);
handles[i] = cache->Insert(key, new Value(i+1), 1, &deleter);
}
// Guess what's in the cache now?
for (size_t i = 0; i < n + 1; i++) {
std::string key = ToString(i+1);
auto h = cache->Lookup(key);
std::cout << key << (h?" found\n":" not found\n");
ASSERT_TRUE(h != nullptr);
if (h) cache->Release(h);
}
// the cache is over capacity since nothing could be evicted
ASSERT_EQ(n + 1U, cache->GetUsage());
for (size_t i = 0; i < n + 1; i++) {
cache->Release(handles[i]);
}
// cache is under capacity now since elements were released
ASSERT_EQ(n, cache->GetUsage());
// element 0 is evicted and the rest is there
// This is consistent with the LRU policy since the element 0
// was released first
for (size_t i = 0; i < n + 1; i++) {
std::string key = ToString(i+1);
auto h = cache->Lookup(key);
if (h) {
ASSERT_NE(i, 0U);
cache->Release(h);
} else {
ASSERT_EQ(i, 0U);
}
}
}
namespace {
std::vector<std::pair<int, int>> callback_state;
void callback(void* entry, size_t charge) {
callback_state.push_back({DecodeValue(entry), static_cast<int>(charge)});
}
};
TEST(CacheTest, ApplyToAllCacheEntiresTest) {
std::vector<std::pair<int, int>> inserted;
callback_state.clear();
for (int i = 0; i < 10; ++i) {
Insert(i, i * 2, i + 1);
inserted.push_back({i * 2, i + 1});
}
cache_->ApplyToAllCacheEntries(callback, true);
sort(inserted.begin(), inserted.end());
sort(callback_state.begin(), callback_state.end());
ASSERT_TRUE(inserted == callback_state);
}
} // namespace rocksdb
int main(int argc, char** argv) {
return rocksdb::test::RunAllTests();
}
<|endoftext|> |
<commit_before>/*Copyright 2010 George Karagoulis
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 "encryption.h"
#include "default.h"
#include "hex.h"
#include "base64.h"
#include "files.h"
#include "gzip.h"
#include "osrng.h"
#include "exception.h"
using namespace std;
using namespace GUtil;
int CryptoHelpers::DEFAULT_COMPRESSION_LEVEL = CryptoPP::Gzip::DEFAULT_DEFLATE_LEVEL;
int CryptoHelpers::MIN_COMPRESSION_LEVEL = CryptoPP::Gzip::MIN_DEFLATE_LEVEL;
int CryptoHelpers::MAX_COMPRESSION_LEVEL = CryptoPP::Gzip::MAX_DEFLATE_LEVEL;
string CryptoHelpers::encryptString(const string &instr, const string &passPhrase)
{
string outstr;
CryptoPP::DefaultEncryptorWithMAC encryptor(passPhrase.c_str(),
new CryptoPP::StringSink(outstr));
try
{
encryptor.Put((byte *)instr.c_str(), instr.length());
encryptor.MessageEnd();
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return outstr;
}
string CryptoHelpers::decryptString(const string &instr, const string &passPhrase)
{
string outstr;
CryptoPP::DefaultDecryptorWithMAC decryptor(passPhrase.c_str(),
new CryptoPP::StringSink(outstr));
try
{
decryptor.Put((byte *)instr.c_str(), instr.length());
decryptor.MessageEnd();
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return outstr;
}
void CryptoHelpers::encryptFile(const char *in, const char *out, const char *passPhrase)
{
try
{
CryptoPP::FileSource f(in, true, new CryptoPP::DefaultEncryptorWithMAC(passPhrase, new CryptoPP::FileSink(out)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
}
void CryptoHelpers::decryptFile(const char *in, const char *out, const char *passPhrase)
{
try
{
CryptoPP::FileSource f(in, true, new CryptoPP::DefaultDecryptorWithMAC(passPhrase, new CryptoPP::FileSink(out)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
}
string CryptoHelpers::compress(const string &instr, int level)
{
string ret;
if(level < MIN_COMPRESSION_LEVEL ||
level > MAX_COMPRESSION_LEVEL)
level = DEFAULT_COMPRESSION_LEVEL;
try
{
CryptoPP::Gzip zipper(new CryptoPP::StringSink(ret), level);
zipper.Put((byte*)instr.c_str(), instr.length());
zipper.MessageEnd();
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return ret;
}
string CryptoHelpers::decompress(const string &instr)
{
string tmp;
try
{
CryptoPP::StringSource(instr, true, new CryptoPP::Gunzip(new CryptoPP::StringSink(tmp)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return tmp;
}
string CryptoHelpers::toBase64(const string &instr)
{
string tmp;
CryptoPP::Base64Encoder encoder(new CryptoPP::StringSink(tmp), false);
encoder.Put((byte *)instr.c_str(), instr.length());
encoder.MessageEnd();
return tmp;
}
string CryptoHelpers::fromBase64(const string &instr)
{
string tmp;
try
{
CryptoPP::StringSource(instr, true,
new CryptoPP::Base64Decoder(new CryptoPP::StringSink(tmp)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return tmp;
}
string CryptoHelpers::toBase16(const string &instr)
{
string tmp;
CryptoPP::HexEncoder encoder(new CryptoPP::StringSink(tmp), true);
encoder.Put((byte *)instr.c_str(), instr.length());
encoder.MessageEnd();
return tmp;
}
string CryptoHelpers::fromBase16(const string &instr)
{
string tmp;
try
{
CryptoPP::StringSource(instr, true,
new CryptoPP::HexDecoder(new CryptoPP::StringSink(tmp)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return tmp;
}
int CryptoHelpers::rand()
{
CryptoPP::AutoSeededRandomPool rng;
return rng.GenerateWord32();
}
string CryptoHelpers::randData(int size, int seed)
{
CryptoPP::RandomPool *rng;
if(seed == -1)
{
rng = new CryptoPP::AutoSeededRandomPool();
}
else
{
rng = new CryptoPP::RandomPool();
// Seed the random pool
rng->Put((byte*)(&seed), sizeof(int));
}
byte *output = new byte[size];
rng->GenerateBlock(output, size);
string ret = string((char*)output, size);
delete output;
delete rng;
return ret;
}
<commit_msg>Now it doesn't compress if the file would get bigger<commit_after>/*Copyright 2010 George Karagoulis
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 "encryption.h"
#include "default.h"
#include "hex.h"
#include "base64.h"
#include "files.h"
#include "gzip.h"
#include "osrng.h"
#include "exception.h"
using namespace std;
using namespace GUtil;
int CryptoHelpers::DEFAULT_COMPRESSION_LEVEL = CryptoPP::Gzip::DEFAULT_DEFLATE_LEVEL;
int CryptoHelpers::MIN_COMPRESSION_LEVEL = CryptoPP::Gzip::MIN_DEFLATE_LEVEL;
int CryptoHelpers::MAX_COMPRESSION_LEVEL = CryptoPP::Gzip::MAX_DEFLATE_LEVEL;
string CryptoHelpers::encryptString(const string &instr, const string &passPhrase)
{
string outstr;
CryptoPP::DefaultEncryptorWithMAC encryptor(passPhrase.c_str(),
new CryptoPP::StringSink(outstr));
try
{
encryptor.Put((byte *)instr.c_str(), instr.length());
encryptor.MessageEnd();
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return outstr;
}
string CryptoHelpers::decryptString(const string &instr, const string &passPhrase)
{
string outstr;
CryptoPP::DefaultDecryptorWithMAC decryptor(passPhrase.c_str(),
new CryptoPP::StringSink(outstr));
try
{
decryptor.Put((byte *)instr.c_str(), instr.length());
decryptor.MessageEnd();
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return outstr;
}
void CryptoHelpers::encryptFile(const char *in, const char *out, const char *passPhrase)
{
try
{
CryptoPP::FileSource f(in, true, new CryptoPP::DefaultEncryptorWithMAC(passPhrase, new CryptoPP::FileSink(out)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
}
void CryptoHelpers::decryptFile(const char *in, const char *out, const char *passPhrase)
{
try
{
CryptoPP::FileSource f(in, true, new CryptoPP::DefaultDecryptorWithMAC(passPhrase, new CryptoPP::FileSink(out)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
}
string CryptoHelpers::compress(const string &instr, int level)
{
string ret;
bool skip_compression = instr.length() > 10000000;
if(!skip_compression)
{
if(level < MIN_COMPRESSION_LEVEL ||
level > MAX_COMPRESSION_LEVEL)
level = DEFAULT_COMPRESSION_LEVEL;
try
{
CryptoPP::Gzip zipper(new CryptoPP::StringSink(ret), level);
zipper.Put((byte*)instr.c_str(), instr.length());
zipper.MessageEnd();
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
}
if(skip_compression || ret.length() > instr.length())
{
// Leave it uncompressed, because we didn't gain anything by compression
return "0" + instr;
}
return "1" + ret;
}
string CryptoHelpers::decompress(const string &instr)
{
string tmp;
if(instr.length() > 0)
{
bool is_compressed = false;
char tmpc = instr.at(0);
if(tmpc == '1')
is_compressed = true;
string newstr;
if(tmpc == '0' || tmpc == '1')
newstr = instr.substr(1);
else
{
is_compressed = true;
newstr = instr;
}
if(is_compressed)
{
try
{
CryptoPP::StringSource(newstr, true, new CryptoPP::Gunzip(new CryptoPP::StringSink(tmp)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
}
else
return newstr;
}
return tmp;
}
string CryptoHelpers::toBase64(const string &instr)
{
string tmp;
CryptoPP::Base64Encoder encoder(new CryptoPP::StringSink(tmp), false);
encoder.Put((byte *)instr.c_str(), instr.length());
encoder.MessageEnd();
return tmp;
}
string CryptoHelpers::fromBase64(const string &instr)
{
string tmp;
try
{
CryptoPP::StringSource(instr, true,
new CryptoPP::Base64Decoder(new CryptoPP::StringSink(tmp)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return tmp;
}
string CryptoHelpers::toBase16(const string &instr)
{
string tmp;
CryptoPP::HexEncoder encoder(new CryptoPP::StringSink(tmp), true);
encoder.Put((byte *)instr.c_str(), instr.length());
encoder.MessageEnd();
return tmp;
}
string CryptoHelpers::fromBase16(const string &instr)
{
string tmp;
try
{
CryptoPP::StringSource(instr, true,
new CryptoPP::HexDecoder(new CryptoPP::StringSink(tmp)));
}
catch(CryptoPP::Exception ex)
{
throw GUtil::Exception(ex.GetWhat());
}
return tmp;
}
int CryptoHelpers::rand()
{
CryptoPP::AutoSeededRandomPool rng;
return rng.GenerateWord32();
}
string CryptoHelpers::randData(int size, int seed)
{
CryptoPP::RandomPool *rng;
if(seed == -1)
{
rng = new CryptoPP::AutoSeededRandomPool();
}
else
{
rng = new CryptoPP::RandomPool();
// Seed the random pool
rng->Put((byte*)(&seed), sizeof(int));
}
byte *output = new byte[size];
rng->GenerateBlock(output, size);
string ret = string((char*)output, size);
delete output;
delete rng;
return ret;
}
<|endoftext|> |
<commit_before>/*
* A Remote Debugger for SpiderMonkey Java Script engine.
* Copyright (C) 2014-2015 Sławomir Wojtasiak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "encoding.hpp"
#include <langinfo.h>
#include <string>
#include <iostream>
#include <sstream>
#include <iconv.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#define MBS_ENC_LOCAL_ENCODING_BUFF_LEN 512
using namespace Utils;
EncodingFailedException::EncodingFailedException( const std::string& msg )
: _msg(msg) {
}
EncodingFailedException::~EncodingFailedException() {
}
const std::string& EncodingFailedException::getMsg() const {
return _msg;
}
<commit_msg>encoding.cpp: remove unused macro and includes<commit_after>/*
* A Remote Debugger for SpiderMonkey Java Script engine.
* Copyright (C) 2014-2015 Sławomir Wojtasiak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "encoding.hpp"
#include <string>
using namespace Utils;
EncodingFailedException::EncodingFailedException( const std::string& msg )
: _msg(msg) {
}
EncodingFailedException::~EncodingFailedException() {
}
const std::string& EncodingFailedException::getMsg() const {
return _msg;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3439
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3439 to 3440<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3440
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>#include <boost/preprocessor.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/to_seq.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <silicium/to_unique.hpp>
#if SILICIUM_COMPILER_GENERATES_MOVES
# define SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \
struct_name() = default; \
SILICIUM_DEFAULT_MOVE(struct_name)
#else
# define SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \
struct_name() : member_name() BOOST_NOEXCEPT {} \
struct_name(struct_name &&other) BOOST_NOEXCEPT : member_name(std::move(other.member_name)) {} \
struct_name &operator = (struct_name &&other) BOOST_NOEXCEPT { member_name = std::move(other.member_name); return *this; }
#endif
#define SILICIUM_DETAIL_MAKE_PARAMETER(z, n, array) BOOST_PP_COMMA_IF(n) BOOST_PP_ARRAY_ELEM(n, array) BOOST_PP_CAT(arg, n)
#define SILICIUM_DETAIL_MAKE_PARAMETERS(array) ( BOOST_PP_REPEAT(BOOST_PP_ARRAY_SIZE(array), SILICIUM_DETAIL_MAKE_PARAMETER, array) )
#define SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD(r, data, elem) \
virtual \
BOOST_PP_TUPLE_ELEM(4, 2, elem) \
BOOST_PP_TUPLE_ELEM(4, 0, elem) \
SILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \
BOOST_PP_TUPLE_ELEM(4, 3, elem) \
= 0;
#define SILICIUM_DETAIL_MAKE_INTERFACE(name, methods) struct name { \
virtual ~name() {} \
BOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD, _, methods) \
};
#define SILICIUM_DETAIL_ERASER_METHOD_ARGUMENT(z, n, text) , BOOST_PP_CAT(_, n)
#define SILICIUM_DETAIL_MAKE_ERASER_METHOD(r, data, elem) \
virtual \
BOOST_PP_TUPLE_ELEM(4, 2, elem) \
BOOST_PP_TUPLE_ELEM(4, 0, elem) \
SILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \
BOOST_PP_TUPLE_ELEM(4, 3, elem) \
SILICIUM_OVERRIDE { \
return original. BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \
BOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \
); \
}
#define SILICIUM_DETAIL_MAKE_BOX_METHOD(r, data, elem) \
BOOST_PP_TUPLE_ELEM(4, 2, elem) \
BOOST_PP_TUPLE_ELEM(4, 0, elem) \
SILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \
BOOST_PP_TUPLE_ELEM(4, 3, elem) { \
assert(original); \
return original -> BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \
BOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \
); \
}
#define SILICIUM_DETAIL_MAKE_ERASER(name, methods) template <class Original> struct name : interface { \
Original original; \
SILICIUM_MOVABLE_MEMBER(name, original) \
explicit name(Original original) : original(std::move(original)) {} \
BOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_ERASER_METHOD, _, methods) \
};
#define SILICIUM_DETAIL_MAKE_BOX(name, methods) struct box { \
std::unique_ptr<interface> original; \
SILICIUM_MOVABLE_MEMBER(name, original) \
explicit name(std::unique_ptr<interface> original) BOOST_NOEXCEPT : original(std::move(original)) {} \
BOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_BOX_METHOD, _, methods) \
};
#define SILICIUM_SPECIALIZED_TRAIT(name, specialization, methods) struct name specialization { \
SILICIUM_DETAIL_MAKE_INTERFACE(interface, methods) \
SILICIUM_DETAIL_MAKE_ERASER(eraser, methods) \
SILICIUM_DETAIL_MAKE_BOX(box, methods) \
template <class Original> \
static eraser<typename std::decay<Original>::type> erase(Original &&original) { \
return eraser<typename std::decay<Original>::type>{std::forward<Original>(original)}; \
} \
template <class Original> \
static box make_box(Original &&original) { \
return box{Si::to_unique(erase(std::forward<Original>(original)))}; \
} \
};
#define SILICIUM_TRAIT(name, methods) SILICIUM_SPECIALIZED_TRAIT(name, , methods)
typedef long element;
SILICIUM_TRAIT(
Producer,
((get, (0, ()), element))
)
struct test_producer
{
element get()
{
return 42;
}
};
BOOST_AUTO_TEST_CASE(trivial_trait)
{
std::unique_ptr<Producer::interface> p = Si::to_unique(Producer::erase(test_producer{}));
BOOST_REQUIRE(p);
BOOST_CHECK_EQUAL(42, p->get());
}
template <class T>
SILICIUM_TRAIT(
Container,
((emplace_back, (1, (T)), void))
((resize, (1, (size_t)), void))
((resize, (2, (size_t, T const &)), void))
((empty, (0, ()), bool, const))
((size, (0, ()), size_t, const BOOST_NOEXCEPT))
)
BOOST_AUTO_TEST_CASE(templatized_trait)
{
auto container = Container<int>::erase(std::vector<int>{});
container.emplace_back(123);
{
std::vector<int> const expected{123};
BOOST_CHECK(expected == container.original);
}
container.resize(2);
{
std::vector<int> const expected{123, 0};
BOOST_CHECK(expected == container.original);
}
container.resize(3, 7);
{
std::vector<int> const expected{123, 0, 7};
BOOST_CHECK(expected == container.original);
}
}
BOOST_AUTO_TEST_CASE(trait_const_method)
{
auto container = Container<int>::erase(std::vector<int>{});
auto const &const_ref = container;
BOOST_CHECK(const_ref.empty());
container.original.resize(1);
BOOST_CHECK(!const_ref.empty());
}
#if SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT
BOOST_AUTO_TEST_CASE(trait_noexcept_method)
{
auto container = Container<int>::erase(std::vector<int>{});
auto const &const_ref = container;
BOOST_CHECK_EQUAL(0, const_ref.size());
container.original.resize(3);
BOOST_CHECK_EQUAL(3, const_ref.size());
BOOST_STATIC_ASSERT(BOOST_NOEXCEPT_EXPR(const_ref.size()));
}
#endif
BOOST_AUTO_TEST_CASE(trait_box)
{
//default constructor is available:
Container<int>::box container;
{
//move construction is available:
Container<int>::box container2 = Container<int>::make_box(std::vector<int>{});
//move assignment is available:
container = std::move(container2);
BOOST_REQUIRE(container.original);
BOOST_CHECK(!container2.original);
}
container.emplace_back(3);
BOOST_CHECK(!container.empty());
BOOST_CHECK_EQUAL(1u, container.size());
}
BOOST_AUTO_TEST_CASE(trait_eraser)
{
//default constructor is available:
Container<int>::eraser<std::vector<int>> container;
{
//move construction is available:
Container<int>::eraser<std::vector<int>> container2 = Container<int>::erase(std::vector<int>{1, 2, 3});
BOOST_CHECK_EQUAL(0, container.original.size());
BOOST_CHECK_EQUAL(3, container2.original.size());
//move assignment is available:
container = std::move(container2);
BOOST_CHECK_EQUAL(3, container.original.size());
BOOST_CHECK_EQUAL(0, container2.original.size());
}
container.emplace_back(4);
BOOST_CHECK(!container.empty());
BOOST_CHECK_EQUAL(4, container.size());
}
template <class Signature>
struct Callable;
template <class Result, class A0>
SILICIUM_SPECIALIZED_TRAIT(
Callable,
<Result(A0)>,
((operator(), (1, (A0)), Result))
)
BOOST_AUTO_TEST_CASE(trait_specialization)
{
auto add_two = Callable<int(int)>::make_box([](int a) { return a + 2; });
BOOST_CHECK_EQUAL(3, add_two(1));
}
<commit_msg>fix sign comparison warnings<commit_after>#include <boost/preprocessor.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/to_seq.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <silicium/to_unique.hpp>
#if SILICIUM_COMPILER_GENERATES_MOVES
# define SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \
struct_name() = default; \
SILICIUM_DEFAULT_MOVE(struct_name)
#else
# define SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \
struct_name() : member_name() BOOST_NOEXCEPT {} \
struct_name(struct_name &&other) BOOST_NOEXCEPT : member_name(std::move(other.member_name)) {} \
struct_name &operator = (struct_name &&other) BOOST_NOEXCEPT { member_name = std::move(other.member_name); return *this; }
#endif
#define SILICIUM_DETAIL_MAKE_PARAMETER(z, n, array) BOOST_PP_COMMA_IF(n) BOOST_PP_ARRAY_ELEM(n, array) BOOST_PP_CAT(arg, n)
#define SILICIUM_DETAIL_MAKE_PARAMETERS(array) ( BOOST_PP_REPEAT(BOOST_PP_ARRAY_SIZE(array), SILICIUM_DETAIL_MAKE_PARAMETER, array) )
#define SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD(r, data, elem) \
virtual \
BOOST_PP_TUPLE_ELEM(4, 2, elem) \
BOOST_PP_TUPLE_ELEM(4, 0, elem) \
SILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \
BOOST_PP_TUPLE_ELEM(4, 3, elem) \
= 0;
#define SILICIUM_DETAIL_MAKE_INTERFACE(name, methods) struct name { \
virtual ~name() {} \
BOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD, _, methods) \
};
#define SILICIUM_DETAIL_ERASER_METHOD_ARGUMENT(z, n, text) , BOOST_PP_CAT(_, n)
#define SILICIUM_DETAIL_MAKE_ERASER_METHOD(r, data, elem) \
virtual \
BOOST_PP_TUPLE_ELEM(4, 2, elem) \
BOOST_PP_TUPLE_ELEM(4, 0, elem) \
SILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \
BOOST_PP_TUPLE_ELEM(4, 3, elem) \
SILICIUM_OVERRIDE { \
return original. BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \
BOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \
); \
}
#define SILICIUM_DETAIL_MAKE_BOX_METHOD(r, data, elem) \
BOOST_PP_TUPLE_ELEM(4, 2, elem) \
BOOST_PP_TUPLE_ELEM(4, 0, elem) \
SILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \
BOOST_PP_TUPLE_ELEM(4, 3, elem) { \
assert(original); \
return original -> BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \
BOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \
); \
}
#define SILICIUM_DETAIL_MAKE_ERASER(name, methods) template <class Original> struct name : interface { \
Original original; \
SILICIUM_MOVABLE_MEMBER(name, original) \
explicit name(Original original) : original(std::move(original)) {} \
BOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_ERASER_METHOD, _, methods) \
};
#define SILICIUM_DETAIL_MAKE_BOX(name, methods) struct box { \
std::unique_ptr<interface> original; \
SILICIUM_MOVABLE_MEMBER(name, original) \
explicit name(std::unique_ptr<interface> original) BOOST_NOEXCEPT : original(std::move(original)) {} \
BOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_BOX_METHOD, _, methods) \
};
#define SILICIUM_SPECIALIZED_TRAIT(name, specialization, methods) struct name specialization { \
SILICIUM_DETAIL_MAKE_INTERFACE(interface, methods) \
SILICIUM_DETAIL_MAKE_ERASER(eraser, methods) \
SILICIUM_DETAIL_MAKE_BOX(box, methods) \
template <class Original> \
static eraser<typename std::decay<Original>::type> erase(Original &&original) { \
return eraser<typename std::decay<Original>::type>{std::forward<Original>(original)}; \
} \
template <class Original> \
static box make_box(Original &&original) { \
return box{Si::to_unique(erase(std::forward<Original>(original)))}; \
} \
};
#define SILICIUM_TRAIT(name, methods) SILICIUM_SPECIALIZED_TRAIT(name, , methods)
typedef long element;
SILICIUM_TRAIT(
Producer,
((get, (0, ()), element))
)
struct test_producer
{
element get()
{
return 42;
}
};
BOOST_AUTO_TEST_CASE(trivial_trait)
{
std::unique_ptr<Producer::interface> p = Si::to_unique(Producer::erase(test_producer{}));
BOOST_REQUIRE(p);
BOOST_CHECK_EQUAL(42, p->get());
}
template <class T>
SILICIUM_TRAIT(
Container,
((emplace_back, (1, (T)), void))
((resize, (1, (size_t)), void))
((resize, (2, (size_t, T const &)), void))
((empty, (0, ()), bool, const))
((size, (0, ()), size_t, const BOOST_NOEXCEPT))
)
BOOST_AUTO_TEST_CASE(templatized_trait)
{
auto container = Container<int>::erase(std::vector<int>{});
container.emplace_back(123);
{
std::vector<int> const expected{123};
BOOST_CHECK(expected == container.original);
}
container.resize(2);
{
std::vector<int> const expected{123, 0};
BOOST_CHECK(expected == container.original);
}
container.resize(3, 7);
{
std::vector<int> const expected{123, 0, 7};
BOOST_CHECK(expected == container.original);
}
}
BOOST_AUTO_TEST_CASE(trait_const_method)
{
auto container = Container<int>::erase(std::vector<int>{});
auto const &const_ref = container;
BOOST_CHECK(const_ref.empty());
container.original.resize(1);
BOOST_CHECK(!const_ref.empty());
}
#if SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT
BOOST_AUTO_TEST_CASE(trait_noexcept_method)
{
auto container = Container<int>::erase(std::vector<int>{});
auto const &const_ref = container;
BOOST_CHECK_EQUAL(0, const_ref.size());
container.original.resize(3);
BOOST_CHECK_EQUAL(3, const_ref.size());
BOOST_STATIC_ASSERT(BOOST_NOEXCEPT_EXPR(const_ref.size()));
}
#endif
BOOST_AUTO_TEST_CASE(trait_box)
{
//default constructor is available:
Container<int>::box container;
{
//move construction is available:
Container<int>::box container2 = Container<int>::make_box(std::vector<int>{});
//move assignment is available:
container = std::move(container2);
BOOST_REQUIRE(container.original);
BOOST_CHECK(!container2.original);
}
container.emplace_back(3);
BOOST_CHECK(!container.empty());
BOOST_CHECK_EQUAL(1u, container.size());
}
BOOST_AUTO_TEST_CASE(trait_eraser)
{
//default constructor is available:
Container<int>::eraser<std::vector<int>> container;
{
//move construction is available:
Container<int>::eraser<std::vector<int>> container2 = Container<int>::erase(std::vector<int>{1, 2, 3});
BOOST_CHECK_EQUAL(0u, container.original.size());
BOOST_CHECK_EQUAL(3u, container2.original.size());
//move assignment is available:
container = std::move(container2);
BOOST_CHECK_EQUAL(3u, container.original.size());
BOOST_CHECK_EQUAL(0u, container2.original.size());
}
container.emplace_back(4);
BOOST_CHECK(!container.empty());
BOOST_CHECK_EQUAL(4u, container.size());
}
template <class Signature>
struct Callable;
template <class Result, class A0>
SILICIUM_SPECIALIZED_TRAIT(
Callable,
<Result(A0)>,
((operator(), (1, (A0)), Result))
)
BOOST_AUTO_TEST_CASE(trait_specialization)
{
auto add_two = Callable<int(int)>::make_box([](int a) { return a + 2; });
BOOST_CHECK_EQUAL(3, add_two(1));
}
<|endoftext|> |
<commit_before>#include <map>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include "boxer.h"
#include "stage.h"
#ifdef __ANDROID__
#include "jni.h"
#include <android/log.h>
#else
#include <pulse/simple.h>
#endif
extern int32_t _BOXER_FILES_SIZE;
extern char* _BOXER_FILES[];
int32_t cachedArgc = 0;
char argvStorage[1024];
char* cachedArgv[64];
namespace boxer
{
enum error: int32_t
{
SUCCESS,
FAILURE
};
stage* gStage = NULL;
int32_t gFrameDelay = 0;
std::map<int32_t, uint8_t*> gResourceMap;
struct audioParam
{
int32_t id;
int32_t delay;
bool keepGoing;
};
pthread_mutex_t jAudioMutex;
audioParam* jAudioParam = NULL;
#define MAX_AUDIO_THREADS 16
pthread_t gAudioThread[MAX_AUDIO_THREADS];
audioParam gAudioThreadParam[MAX_AUDIO_THREADS];
int32_t gAudioThreadIndex = 0;
int32_t getArgc()
{
return cachedArgc;
}
char** getArgv()
{
return cachedArgv;
}
int32_t getFrameDelay()
{
return gFrameDelay;
}
void setFrameDelay(int32_t ms)
{
gFrameDelay = ms;
}
const uint8_t* getResource(int32_t id)
{
auto found = gResourceMap.find(id);
return found == gResourceMap.end() ? NULL: gResourceMap.find(id)->second;
}
void setStage(int32_t id)
{
if(gStage != NULL)
{
gStage->~stage();
free(gStage);
}
gStage = (stage*)malloc(sizeof(stage));
gStage->init(id);
}
int32_t blockResource(int32_t id, int32_t x, int32_t y)
{
int32_t code = FAILURE;
if(gStage == NULL || (x > gStage->getWidth()) || (y > gStage->getHeight()))
return code;
const boxer::bmpStat* stat = (const boxer::bmpStat*)boxer::getResource(id);
assert(stat != NULL);
assert(stat->colorPlanes == 1);
assert(stat->compression == 3); //BI_BITFIELDS
if((x+stat->width) <= gStage->getWidth() && (y+stat->height) <= gStage->getHeight())
{
gStage->draw(boxer::getResource(id), x, y);
code = SUCCESS;
}
return code;
}
void showStage()
{
if(gStage != NULL)
{
gStage->show();
}
usleep(gFrameDelay*1000);
}
#define WAV_HEADER_SIZE 44
#ifdef __ANDROID__
#define AUDIO_BUFFER_SIZE 2048
#else
#define AUDIO_BUFFER_SIZE 1024
#endif
void* audioResourceThread(void* param)
{
audioParam* desc = (audioParam*)param;
while(true)
{
#ifdef __ANDROID__
pthread_mutex_lock(&jAudioMutex);
while(jAudioParam != NULL && desc->keepGoing)
{
pthread_mutex_unlock(&jAudioMutex);
sched_yield();
pthread_mutex_lock(&jAudioMutex);
}
audioParam* jParam = new audioParam();
jParam->id = desc->id;
jParam->keepGoing = desc->keepGoing;
jAudioParam = jParam;
pthread_mutex_unlock(&jAudioMutex);
while(jAudioParam != NULL && desc->keepGoing)
{
sched_yield();
}
#else
const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(desc->id);
const uint8_t* data = (const uint8_t*)(boxer::getResource(desc->id) + WAV_HEADER_SIZE);
static const pa_sample_spec spec = { .format = PA_SAMPLE_S16LE, .rate = 44100, .channels = 2 };
pa_simple* stream = pa_simple_new(NULL, NULL, PA_STREAM_PLAYBACK, NULL, "boxer_track", &spec, NULL, NULL, NULL);
if(stream != NULL)
{
int32_t i = 0;
while((i+AUDIO_BUFFER_SIZE < stat->size) && desc->keepGoing)
{
if(pa_simple_write(stream, &data[i], AUDIO_BUFFER_SIZE, NULL) < 0)
{
break;
}
i+=AUDIO_BUFFER_SIZE;
}
pa_simple_drain(stream, NULL);
pa_simple_free(stream);
}
#endif
if(desc->keepGoing == false || desc->delay == -1)
break;
usleep(desc->delay*1000);
}
return NULL;
}
void startAudioResource(int32_t id, int32_t delay)
{
waitAudioResource(id);
gAudioThreadParam[gAudioThreadIndex].id = id;
gAudioThreadParam[gAudioThreadIndex].delay = delay;
gAudioThreadParam[gAudioThreadIndex].keepGoing = true;
pthread_create(&gAudioThread[gAudioThreadIndex], NULL, audioResourceThread, &gAudioThreadParam[gAudioThreadIndex]);
if(++gAudioThreadIndex == MAX_AUDIO_THREADS)
{
gAudioThreadIndex = 0;
}
}
void stopAudioResource(int32_t id)
{
int32_t i = MAX_AUDIO_THREADS;
while(i--)
{
if(gAudioThreadParam[i].id == id)
{
gAudioThreadParam[i].keepGoing = false;
pthread_mutex_lock(&jAudioMutex);
if(jAudioParam != NULL && jAudioParam->id == id)
{
jAudioParam->keepGoing = false;
}
pthread_mutex_unlock(&jAudioMutex);
waitAudioResource(id);
break;
}
}
}
void waitAudioResource(int32_t id)
{
int32_t i = MAX_AUDIO_THREADS;
while(i--)
{
if(gAudioThreadParam[i].id == id)
{
pthread_join(gAudioThread[i], NULL);
break;
}
}
}
struct _BUILDER
{
_BUILDER()
{
pthread_mutex_init(&jAudioMutex, NULL);
}
~_BUILDER()
{
int32_t count = 0;
char buffer[PATH_MAX];
while(count < _BOXER_FILES_SIZE)
{
free(gResourceMap.find(count++)->second);
}
if(gStage != NULL)
{
gStage->~stage();
free(gStage);
}
}
};
static _BUILDER resourceBuilder;
}
void preload(const char* path)
{
int32_t delay = 0;
#ifdef __ANDROID__
delay = 48; //Empirical, but could be derived by checking CPU usage is less than max output of 2 threads
#else
delay = 1000;
#endif
boxer::setFrameDelay(delay);
int32_t count = 0;
char buffer[PATH_MAX];
while(count < _BOXER_FILES_SIZE)
{
memset(buffer, '\0', PATH_MAX);
memcpy(buffer, path, strlen(path));
strcat(buffer, _BOXER_FILES[count]);
FILE* temp = fopen(buffer, "r");
if(temp)
{
fseek(temp, 0, SEEK_END);
int32_t size = ftell(temp);
rewind(temp);
uint8_t* binary = (uint8_t*)malloc(size);
size_t read = fread(binary, 1, size, temp);
assert(read == size);
boxer::gResourceMap.insert(std::pair<int32_t, uint8_t*>(count, binary));
fclose(temp);
}
count++;
}
}
int32_t main(int32_t argc, char** argv)
{
cachedArgc = argc;
char* storagePointer = argvStorage;
while(argc--)
{
cachedArgv[argc] = storagePointer;
int32_t length = strlen(argv[argc]);
strcat(storagePointer, argv[argc]);
storagePointer+=(length+1);
}
char buffer[PATH_MAX];
memset(buffer, '\0', PATH_MAX);
char* finalSlash = strrchr(cachedArgv[0], '/');
memcpy(buffer, cachedArgv[0], (finalSlash - cachedArgv[0]) + 1);
preload(buffer);
boxerMain();
return 0;
}
#ifdef __ANDROID__
JavaVM* jVM = NULL;
jclass jBoxerEngine = NULL;
jmethodID jShowStage = NULL;
char androidData[PATH_MAX];
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
jVM = vm;
JNIEnv* env;
if(vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)
{
return -1;
}
return JNI_VERSION_1_6;
}
extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_preload(JNIEnv* env, jobject obj, jstring pathString)
{
const char* path = env->GetStringUTFChars(pathString, NULL);
preload(path);
memset(androidData, '\0', PATH_MAX);
char* finalSlash = strrchr(path, '/');
memcpy(androidData, path, (finalSlash - path) + 1);
env->ReleaseStringUTFChars(pathString, path);
}
extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_boxerMain(JNIEnv* env, jobject obj)
{
jBoxerEngine = env->FindClass("org/starlo/boxer/BoxerEngine");
jShowStage = env->GetStaticMethodID(jBoxerEngine, "showStage", "(Ljava/lang/String;)V");
boxerMain();
}
extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_audioResourceThread(JNIEnv* env, jobject obj)
{
jclass engine = env->FindClass("org/starlo/boxer/BoxerEngine");
jmethodID audioWrite = env->GetStaticMethodID(engine, "audioWrite", "([S)V");
while(true)
{
if(boxer::jAudioParam != NULL)
{
int32_t i = 0;
const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(boxer::jAudioParam->id);
const uint8_t* data = (const uint8_t*)(boxer::getResource(boxer::jAudioParam->id) + WAV_HEADER_SIZE);
jshortArray jData = env->NewShortArray(AUDIO_BUFFER_SIZE);
while(i+AUDIO_BUFFER_SIZE < stat->size && boxer::jAudioParam->keepGoing)
{
env->SetShortArrayRegion(jData, 0, AUDIO_BUFFER_SIZE, (const short*)&data[i]);
env->CallStaticVoidMethod(engine, audioWrite, jData);
i+=AUDIO_BUFFER_SIZE;
}
env->DeleteLocalRef(jData);
pthread_mutex_lock(&boxer::jAudioMutex);
delete boxer::jAudioParam;
boxer::jAudioParam = NULL;
pthread_mutex_unlock(&boxer::jAudioMutex);
}
sched_yield();
}
}
#endif
<commit_msg>Fix playback issue on Android<commit_after>#include <map>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include "boxer.h"
#include "stage.h"
#ifdef __ANDROID__
#include "jni.h"
#include <android/log.h>
#else
#include <pulse/simple.h>
#endif
extern int32_t _BOXER_FILES_SIZE;
extern char* _BOXER_FILES[];
int32_t cachedArgc = 0;
char argvStorage[1024];
char* cachedArgv[64];
namespace boxer
{
enum error: int32_t
{
SUCCESS,
FAILURE
};
stage* gStage = NULL;
int32_t gFrameDelay = 0;
std::map<int32_t, uint8_t*> gResourceMap;
struct audioParam
{
int32_t id;
int32_t delay;
bool keepGoing;
};
pthread_mutex_t jAudioMutex;
audioParam* jAudioParam = NULL;
#define MAX_AUDIO_THREADS 16
pthread_t gAudioThread[MAX_AUDIO_THREADS];
audioParam gAudioThreadParam[MAX_AUDIO_THREADS];
int32_t gAudioThreadIndex = 0;
int32_t getArgc()
{
return cachedArgc;
}
char** getArgv()
{
return cachedArgv;
}
int32_t getFrameDelay()
{
return gFrameDelay;
}
void setFrameDelay(int32_t ms)
{
gFrameDelay = ms;
}
const uint8_t* getResource(int32_t id)
{
auto found = gResourceMap.find(id);
return found == gResourceMap.end() ? NULL: gResourceMap.find(id)->second;
}
void setStage(int32_t id)
{
if(gStage != NULL)
{
gStage->~stage();
free(gStage);
}
gStage = (stage*)malloc(sizeof(stage));
gStage->init(id);
}
int32_t blockResource(int32_t id, int32_t x, int32_t y)
{
int32_t code = FAILURE;
if(gStage == NULL || (x > gStage->getWidth()) || (y > gStage->getHeight()))
return code;
const boxer::bmpStat* stat = (const boxer::bmpStat*)boxer::getResource(id);
assert(stat != NULL);
assert(stat->colorPlanes == 1);
assert(stat->compression == 3); //BI_BITFIELDS
if((x+stat->width) <= gStage->getWidth() && (y+stat->height) <= gStage->getHeight())
{
gStage->draw(boxer::getResource(id), x, y);
code = SUCCESS;
}
return code;
}
void showStage()
{
if(gStage != NULL)
{
gStage->show();
}
usleep(gFrameDelay*1000);
}
#define WAV_HEADER_SIZE 44
#define AUDIO_BUFFER_SIZE 1024
void* audioResourceThread(void* param)
{
audioParam* desc = (audioParam*)param;
while(true)
{
#ifdef __ANDROID__
pthread_mutex_lock(&jAudioMutex);
while(jAudioParam != NULL && desc->keepGoing)
{
pthread_mutex_unlock(&jAudioMutex);
sched_yield();
pthread_mutex_lock(&jAudioMutex);
}
audioParam* jParam = new audioParam();
jParam->id = desc->id;
jParam->keepGoing = desc->keepGoing;
jAudioParam = jParam;
pthread_mutex_unlock(&jAudioMutex);
while(jAudioParam != NULL && desc->keepGoing)
{
sched_yield();
}
#else
const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(desc->id);
const uint8_t* data = (const uint8_t*)(boxer::getResource(desc->id) + WAV_HEADER_SIZE);
static const pa_sample_spec spec = { .format = PA_SAMPLE_S16LE, .rate = 44100, .channels = 2 };
pa_simple* stream = pa_simple_new(NULL, NULL, PA_STREAM_PLAYBACK, NULL, "boxer_track", &spec, NULL, NULL, NULL);
if(stream != NULL)
{
int32_t i = 0;
while((i+AUDIO_BUFFER_SIZE < stat->size) && desc->keepGoing)
{
if(pa_simple_write(stream, &data[i], AUDIO_BUFFER_SIZE, NULL) < 0)
{
break;
}
i+=AUDIO_BUFFER_SIZE;
}
pa_simple_drain(stream, NULL);
pa_simple_free(stream);
}
#endif
if(desc->keepGoing == false || desc->delay == -1)
break;
usleep(desc->delay*1000);
}
return NULL;
}
void startAudioResource(int32_t id, int32_t delay)
{
waitAudioResource(id);
gAudioThreadParam[gAudioThreadIndex].id = id;
gAudioThreadParam[gAudioThreadIndex].delay = delay;
gAudioThreadParam[gAudioThreadIndex].keepGoing = true;
pthread_create(&gAudioThread[gAudioThreadIndex], NULL, audioResourceThread, &gAudioThreadParam[gAudioThreadIndex]);
if(++gAudioThreadIndex == MAX_AUDIO_THREADS)
{
gAudioThreadIndex = 0;
}
}
void stopAudioResource(int32_t id)
{
int32_t i = MAX_AUDIO_THREADS;
while(i--)
{
if(gAudioThreadParam[i].id == id)
{
gAudioThreadParam[i].keepGoing = false;
pthread_mutex_lock(&jAudioMutex);
if(jAudioParam != NULL && jAudioParam->id == id)
{
jAudioParam->keepGoing = false;
}
pthread_mutex_unlock(&jAudioMutex);
waitAudioResource(id);
break;
}
}
}
void waitAudioResource(int32_t id)
{
int32_t i = MAX_AUDIO_THREADS;
while(i--)
{
if(gAudioThreadParam[i].id == id)
{
pthread_join(gAudioThread[i], NULL);
break;
}
}
}
struct _BUILDER
{
_BUILDER()
{
pthread_mutex_init(&jAudioMutex, NULL);
}
~_BUILDER()
{
int32_t count = 0;
char buffer[PATH_MAX];
while(count < _BOXER_FILES_SIZE)
{
free(gResourceMap.find(count++)->second);
}
if(gStage != NULL)
{
gStage->~stage();
free(gStage);
}
}
};
static _BUILDER resourceBuilder;
}
void preload(const char* path)
{
int32_t delay = 0;
#ifdef __ANDROID__
delay = 48; //Empirical, but could be derived by checking CPU usage is less than max output of 2 threads
#else
delay = 1000;
#endif
boxer::setFrameDelay(delay);
int32_t count = 0;
char buffer[PATH_MAX];
while(count < _BOXER_FILES_SIZE)
{
memset(buffer, '\0', PATH_MAX);
memcpy(buffer, path, strlen(path));
strcat(buffer, _BOXER_FILES[count]);
FILE* temp = fopen(buffer, "r");
if(temp)
{
fseek(temp, 0, SEEK_END);
int32_t size = ftell(temp);
rewind(temp);
uint8_t* binary = (uint8_t*)malloc(size);
size_t read = fread(binary, 1, size, temp);
assert(read == size);
boxer::gResourceMap.insert(std::pair<int32_t, uint8_t*>(count, binary));
fclose(temp);
}
count++;
}
}
int32_t main(int32_t argc, char** argv)
{
cachedArgc = argc;
char* storagePointer = argvStorage;
while(argc--)
{
cachedArgv[argc] = storagePointer;
int32_t length = strlen(argv[argc]);
strcat(storagePointer, argv[argc]);
storagePointer+=(length+1);
}
char buffer[PATH_MAX];
memset(buffer, '\0', PATH_MAX);
char* finalSlash = strrchr(cachedArgv[0], '/');
memcpy(buffer, cachedArgv[0], (finalSlash - cachedArgv[0]) + 1);
preload(buffer);
boxerMain();
return 0;
}
#ifdef __ANDROID__
JavaVM* jVM = NULL;
jclass jBoxerEngine = NULL;
jmethodID jShowStage = NULL;
char androidData[PATH_MAX];
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
jVM = vm;
JNIEnv* env;
if(vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)
{
return -1;
}
return JNI_VERSION_1_6;
}
extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_preload(JNIEnv* env, jobject obj, jstring pathString)
{
const char* path = env->GetStringUTFChars(pathString, NULL);
preload(path);
memset(androidData, '\0', PATH_MAX);
char* finalSlash = strrchr(path, '/');
memcpy(androidData, path, (finalSlash - path) + 1);
env->ReleaseStringUTFChars(pathString, path);
}
extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_boxerMain(JNIEnv* env, jobject obj)
{
jBoxerEngine = env->FindClass("org/starlo/boxer/BoxerEngine");
jShowStage = env->GetStaticMethodID(jBoxerEngine, "showStage", "(Ljava/lang/String;)V");
boxerMain();
}
extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_audioResourceThread(JNIEnv* env, jobject obj)
{
jclass engine = env->FindClass("org/starlo/boxer/BoxerEngine");
jmethodID audioWrite = env->GetStaticMethodID(engine, "audioWrite", "([S)V");
while(true)
{
if(boxer::jAudioParam != NULL)
{
int32_t i = 0;
const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(boxer::jAudioParam->id);
const uint8_t* data = (const uint8_t*)(boxer::getResource(boxer::jAudioParam->id) + WAV_HEADER_SIZE);
jshortArray jData = env->NewShortArray(AUDIO_BUFFER_SIZE/sizeof(short));
while(i+AUDIO_BUFFER_SIZE < stat->size && boxer::jAudioParam->keepGoing)
{
env->SetShortArrayRegion(jData, 0, AUDIO_BUFFER_SIZE/sizeof(short), (const short*)&data[i]);
env->CallStaticVoidMethod(engine, audioWrite, jData);
i+=AUDIO_BUFFER_SIZE;
}
env->DeleteLocalRef(jData);
pthread_mutex_lock(&boxer::jAudioMutex);
delete boxer::jAudioParam;
boxer::jAudioParam = NULL;
pthread_mutex_unlock(&boxer::jAudioMutex);
}
sched_yield();
}
}
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.